

//slideshow variables
var mediaCategory;
var mediaKeyword;
var mediaImageList;
var mediaRoomCat;
var mediaRestMenu;
var photoPath;
var thumbPath;
var mediaTimer;
var barY;
var currentLabel;
var mediaCurrentImage;
var mediaWebSection;
var mediaPhotoList			= [];
var mediaPhotoListThumb		= [];
var mediaPhotoSet			= [];
var mediaImageDescription	= [];
var mediaImageMenus			= [];
var mediaLoopTotal			= 0;
var thumbHeight				= 39;
var divPadding				= 37;
var aniSpeed				= 500;
var mediaImagePause			= 2000;
var mediaImageFade			= 500;
var visibleThumbs			= 10;
var mediaCounter			= 1;
var mediaPhotoSetIndex		= 0;
var tmpPhotoIndex			= 0;
var createdMediaMenu		= false;
var setFx					= true;
var mediaIsClickable		= true;
var showsDesc				= true;
var mediaPlayShow			= true;
var mediaDynamic			= false;



// loading the images
function mediaLoadImage(){
	var currents = Number(mediaPhotoSetIndex*visibleThumbs) + Number(mediaCurrentImage);
	
	if(mediaDynamic){
		imgSrc = mediaPhotoSet[mediaPhotoSetIndex][mediaCurrentImage];
	} else {
		imgSrc = mediaPhotoSet[mediaPhotoSetIndex][mediaCurrentImage]+"?random=" + Math.round(Math.random()*99999);
	}
	
	if(mediaCounter > 3){
		mediaCounter = 2;
		$('#jscontainer img:first').css('z-index', '1')	;
	}
	imgStyle = 'z-index:'+ mediaCounter +'; display:none;';
	
	$('<img />').attr('src', imgSrc).attr('style', imgStyle).load(function(){
		$('#jscontainer').prepend($(this));
		
		//start initial menu
		if(mediaRestMenu != ''){
			showRestMenu(mediaRestMenu);
			menuSrc  = menuPath + mediaRestMenu;
			mediaPlayShow = false;
			mediaIsClickable   = false;
			clearTimeout(mediaTimer);
			$('#menuRestaurant').fadeOut(500);
			$('#description').fadeOut(500);
			$('#mediaPlayPause').fadeOut(500);
			$('#showMenuRestaurant').fadeIn(500, function(){
				$("#closeMenu").fadeIn(500);	
				$('#containerMenuRes').html('<img src="'+menuSrc+'" />');
				startScrolling();
			});	
			
			mediaRestMenu = '';
		} else {
			// showing the current menu of the corner
			showRestMenu(mediaImageMenus[currents]);
		}
		// image description
		getDesc(mediaImageDescription[currents]);
		
		$('#jscontainer img:first').stop(true,false).fadeIn(mediaImageFade,function(){
			$('#jscontainer img:not(:first-child)').remove();
			mediaCounter++;
			
			tmpImgURL = imgSrc.split('?');
			
			$("#btnDownload").attr('href','/media/player/slideshow/includes/saveImage.cfm?image='+tmpImgURL[0]);
			
			// condition to set the time on the mediaNextImage function
			if(mediaPlayShow){
				mediaTimer = setTimeout(mediaNextImage,mediaImagePause);
			}
		});
	});
}
    
// function next image
function mediaNextImage(){
	clearTimeout(mediaTimer);
	
	// increment the mediaCurrentImage
	mediaCurrentImage++;		
	
	// condition if the current image is more that the phot set index
	if(mediaCurrentImage == mediaPhotoSet[mediaPhotoSetIndex].length){
		mediaPhotoSetChange('next');
	}
	
	mediaSetThumbNail('clear');
	mediaLoadImage();
	mediaSetThumbNail('set');
}

// function mediaPrevImage
function mediaPrevImage(){
	clearTimeout(mediaTimer);
	
	mediaCurrentImage--;
	
	// the condition to see if the current image is equl to 0
	if(mediaCurrentImage == -1){
		mediaPhotoSetChange('prev');
	}
	
	mediaSetThumbNail('clear');
	mediaLoadImage();
	mediaSetThumbNail('update');	
}

// setting border on current thumbnail
function mediaSetThumbNail(type){
	if(type == 'clear'){
		$('.currentThumb').removeClass('currentThumb');
	} else {
		var cImage = Number(mediaPhotoSetIndex*visibleThumbs) + Number(mediaCurrentImage);
		$('#photo_' + cImage).addClass('currentThumb');
	}	
}

//update the photoSet vars
function mediaPhotoSetChange(dir){
	if(dir == 'next'){
		mediaPhotoSetIndex++;
		if(mediaPhotoSetIndex == mediaPhotoSet.length){
			mediaPhotoSetIndex = 0;
		}
		
		mediaSetThumbNail('clear');
		mediaSetThumbNail('set');
		if(setFx){
			newThumbs('next');
		}
		mediaCurrentImage = 0;
	} else {
		mediaPhotoSetIndex--;
		
		if(mediaPhotoSetIndex < 0){
		   mediaPhotoSetIndex = mediaPhotoSet.length-1;
		}
		
		mediaSetThumbNail('clear');
		mediaSetThumbNail('set');
		
		if(setFx){
			newThumbs('prev');
		}
		mediaCurrentImage = mediaPhotoSet[mediaPhotoSetIndex].length-1;
	}
}

// function to close the floatbox
function closet(){
	clearTimeout(mediaTimer);
	resetMediaGallery();
	fb.end();	
}

// function to show the menu of the showRestMenu
function showRestMenu(showIt){
	menuPath = '/media/player/slideshow/menus/' + mediaCategory + '/';
	
	if(showIt){
		menuSrc  = menuPath + showIt;
		$('#menuRestaurant').fadeIn(500, function(){
			$(this).click(function(event){
				event.stopImmediatePropagation();
				mediaPlayShow = false;
				mediaIsClickable   = false;
				clearTimeout(mediaTimer);
				$('#menuRestaurant').fadeOut(500);
				$('#description').fadeOut(500);
				$('#mediaPlayPause').fadeOut(500);
				$('#showMenuRestaurant').fadeIn(500, function(){
					$("#closeMenu").fadeIn(500);	
					$('#containerMenuRes').html('<img src="'+menuSrc+'" />');
					startScrolling();
				});	
			});	
		});
		
		
		$('#closeMenu').click(function(event){
			event.stopImmediatePropagation();
			$(this).fadeOut(500);
			$('#showMenuRestaurant').fadeOut(500, function(){
				$('#containerMenuRes').html('');
				menuSrc = '';
				mediaIsClickable = true;
			});
			$('#menuRestaurant').fadeIn(500);
			$('#description').fadeIn(500);
			$('#mediaPlayPause').fadeIn(500);
			mediaPlayShow = true;
			mediaLoadImage();
		});		
	} else {
		$('#menuRestaurant').css('display', 'none');
	}
}

function startScrolling(){
	barY = $('#scrollBar').offset().top;
	$("#scroller").draggable({
		axis:'y',
		containment:'parent',
		drag:function(){ moveMenu(200); }
	});
	
	$('#scrollBar_clickable').click(function(e){
		var mouseY = e.pageY;
		
		var newY = mouseY - barY - ($('#scroller').height()/2);
		if(newY < 0){ newY = 0; }
		if(newY > ($('#scroll').height() - $('#scroller').height())){ newY = $('#scroll').height() - $('#scroller').height(); }
		$('#scroller').css({ 'top':newY });
		moveMenu(800);
	});		
}

// function moveMenu to move the men
function moveMenu(scrollTime) {
	var handleY = barY - $('#scroller').offset().top;
	// (MenuImgHeight - MaskHeight - HandleHeight) * HandleY / ScrollBarHeight
	var menuY = ($('#containerMenuRes img').height() - ($('#containerMenuRes').height() - $('#scroller').height())) * handleY / $('#scrollBar').height();
	$('#containerMenuRes img').stop(true,true).animate({'top':menuY},scrollTime);	
}
	
// function for the description
function getDesc(descrip){
	if(descrip){
		if(showsDesc == true){
			$('#description').fadeIn(function(){
				$(this).prepend('<p>' + descrip + '</p>' );
				$('#description p:first-child').fadeIn(function(){
					$('#description p:not(:first-child)').remove();	
				});	
			});
		}
		
		// method for the hide and show description
		$('.hideCapDesc').click(function(){
			$('#description').fadeOut(500);	
			$('.showCapDesc').fadeIn(500, function(){
				$(this).html("<img src='/media/player/images/btn-showCaption.gif' />");	
			});
			showsDesc = false;
		});
		
		$('.showCapDesc').click(function(){
			$('.showCapDesc').fadeOut(500, function(){
				$(this).html('');	
			});	
			$('#description').fadeIn(500);
			showsDesc = true;
		});
	} else {
		$('#description').fadeOut(500);	
		$('.showCapDesc').fadeOut(500);
	}
}
	
// function new thumbs
function newThumbs(dir){
	
	var mediaDistance    = mediaPhotoSetIndex * (thumbHeight + divPadding);
	var finishDistance = - (mediaPhotoSet.length * (thumbHeight + divPadding)) + divPadding; //get finishing mediaDistance with the white space
	
	
	//get next image set
	if(dir == 'next'){
		
		if(mediaDistance == 0){
			$('#nextSet').unbind('click');
			//animate to white space, when done, pop the div up to the top, but just before the first image set.... back into whitespace
			//then animate to 0... this creates the never ending loop animation
			$('#thumbnails').dequeue().stop().animate({ top:finishDistance },aniSpeed/2, function(){
				$('#nextSet').click(function(event){
					event.stopImmediatePropagation();
					mediaPhotoSetChange('next');
				});
				
				$('#thumbnails').css('top', divPadding);
				mediaDistance = '-' + mediaDistance;
				$('#thumbnails').animate({ top: mediaDistance },aniSpeed/2);
			});
			
			//finishDistance = -(mediaPhotoSet.length * (thumbHeight + divPadding)) + divPadding;
			//scroll to proper y index
		} else {
			mediaDistance = '-' + mediaDistance;
			
			$('#nextSet').unbind('click');
			
			$('#thumbnails').stop().animate({ top:mediaDistance },aniSpeed, function(){
				$('#nextSet').click(function(event){
					event.stopImmediatePropagation();
					mediaPhotoSetChange('next');
				});
			});
		}
	
	// get previous image set
	} else {
		
		
		if(mediaDistance == -(finishDistance+thumbHeight)){
			$('#prevSet').unbind('click');
			finishDistance = (mediaPhotoSet.length * (thumbHeight + divPadding)) + divPadding;
			
			//alert('esto se esta cumpliedo');
			//then animate to 0... this creates the never ending loop animation and, the hidden point of this is 0, them change to 760px
			// alert(-($('#thumbnails').height()));
			//$('#thumbnails').css('top',$('#thumbnails').height());
			
			$('#thumbnails').dequeue().stop().animate({ top:divPadding },aniSpeed/2, function(){
				$('#prevSet').click(function(event){
					event.stopImmediatePropagation();
					mediaPhotoSetChange('prev');
				});	
				
				//pop the div to hidden spot
				$('#thumbnails').css('top', -($('#thumbnails').height()-thumbHeight));
				
				mediaDistance = '-' + mediaDistance;
				//alert(mediaDistance);
				$('#thumbnails').animate({ top:mediaDistance },aniSpeed/2);
			});
			
		} else {
			var mediaDistance = '-' + mediaDistance;   
			
			// let unbind the click event and after that send it to the update method
			$('#prevSet').unbind('click');
					 
			$('#thumbnails').stop().animate({ top:mediaDistance },aniSpeed, function(){
				$('#prevSet').click(function(event){
					event.stopImmediatePropagation();
					mediaPhotoSetChange('prev');	
				});	
			});    
		}		
	}
	setMediaDots();
}
	
// function to get the Room Category from the oee, this is just passing the rst_code and the room category code, send back the description
function getRoomCat(catCode){
	if(catCode != ''){
		$.ajax({
			type:'POST',
			url:'/media/player/slideshow/includes/rmDescriptionReturn.cfm?rst_code=' + urlCat + '&rmCat=' + catCode,
			dataType:'html',
			success:function(datos){
				//showRoomCat(datos);
				$('#roomCat').fadeIn(function(){
					$(this).prepend(datos).addClass('dotBlue');
					$(this).append("<img class='hideCap' id='hideCap' style='boder:none;'/>");
				});
			}
			
		});
		
		$('#hideCap').live('click', function(){
			$('#roomCat').fadeOut(500);	
			$('#showCap').fadeIn(500, function(){
				$(this).html("<img src='/media/player/images/btn-showCaption.gif' />");	
			});
		});
		
		$('#showCap').click(function(){
			$('#showCap').fadeOut(500, function(){
				$(this).html('');	
			});
			
			$('#roomCat').fadeIn(500);
		});
	}
}


// pause the slide show
function mediaPauseShow(){
	if(mediaPlayShow){
		clearTimeout(mediaTimer);
		$('#playPause').fadeOut(500, function(){
			$('#btnPause').hide();
			$('#btnPlay').show();
			$('#playPause').fadeIn(500);
		});
	}
	
	mediaPlayShow = false;
}

// play the slideShow
function mediaStartShow(){
	if(!mediaPlayShow){
		$('#playPause').fadeOut(500, function(){
			$('#btnPlay').hide();
			$('#btnPause').show();
			$('#playPause').fadeIn(500);
		});
	}
	mediaNextImage();
	mediaPlayShow = true;
}


// function load Thumbs
function loadThumbs(){    
    var thumbHTML = '';
	var tmpPhotoIndex = 0;
	var tmbSrc = '';
	
	for(i=0; i< mediaPhotoListThumb.length; i++){
		tmbSrc = mediaPhotoListThumb[i];
		if(tmpPhotoIndex == visibleThumbs){ tmpPhotoIndex = 0; }
		if(tmpPhotoIndex == 0){ thumbHTML += '<div class="mediaPhotoSet">'; }
		thumbHTML += '<img id="photo_'+i+'" src ="' + tmbSrc + '" width="72" height="37" />';
		if(tmpPhotoIndex == visibleThumbs-1){ thumbHTML += '</div>'; }
		tmpPhotoIndex++;		
	}
	
	if(mediaPhotoListThumb.length % visibleThumbs != 0){ thumbHTML += '</div>'; }
	
	$('#thumbnails').css('top',0);
	$('#thumbnails').html(thumbHTML);
	
	tmpPhotoIndex = 0;
	
	$('#thumbnails img').each(function(i){
		if(tmpPhotoIndex == visibleThumbs){
			 tmpPhotoIndex = 0;
		}
		
		$(this).attr('rel',tmpPhotoIndex);
		
		$(this).click(function(){
			if(mediaIsClickable){
				mediaPauseShow();
				mediaSetThumbNail('clear');
				mediaCurrentImage = $(this).attr('rel');
				mediaSetThumbNail('set');
				mediaLoadImage();
			}
		});
			
		tmpPhotoIndex++;
	});
	
	//creating dots
	var dotString = '';
	if(mediaLoopTotal > 1){
		for(i=0; i<mediaLoopTotal; i++){
			dotString += '<a id="'+i+'" href="" onclick="gotoMediaPhotoSet('+i+'); return false;"></a>';
		}
	}
	$('#dots').html(dotString);
}

function gotoMediaPhotoSet(dotIndex){
	clearTimeout(mediaTimer);
	var mediaDistance = dotIndex * (thumbHeight + divPadding);
	var finishDistance = - (mediaPhotoSet.length * (thumbHeight + divPadding)) + divPadding; //get finishing mediaDistance with the white space
	
	if(mediaDistance == -(finishDistance+thumbHeight)){
		$('#prevSet').unbind('click');
		finishDistance = (mediaPhotoSet.length * (thumbHeight + divPadding)) + divPadding;
		
		//alert('esto se esta cumpliedo');
		//then animate to 0... this creates the never ending loop animation and, the hidden point of this is 0, them change to 760px
		// alert(-($('#thumbnails').height()));
		//$('#thumbnails').css('top',$('#thumbnails').height());
		
		$('#thumbnails').dequeue().stop().animate({ top:divPadding },aniSpeed/2, function(){
			$('#prevSet').click(function(event){
				event.stopImmediatePropagation();
				mediaPhotoSetChange('prev');
			});	
			
			//pop the div to hidden spot
			$('#thumbnails').css('top', -($('#thumbnails').height()-thumbHeight));
			
			mediaDistance = '-' + mediaDistance;
			//alert(mediaDistance);
			$('#thumbnails').animate({ top:mediaDistance },aniSpeed/2);
		});
		
	} else {
		mediaDistance = '-' + mediaDistance;   
		
		// let unbind the click event and after that send it to the update method
		$('#prevSet').unbind('click');
				 
		$('#thumbnails').stop().animate({ top:mediaDistance },aniSpeed, function(){
			$('#prevSet').click(function(event){
				event.stopImmediatePropagation();
				mediaPhotoSetChange('prev');	
			});	
		});    
	}
	
	mediaPhotoSetIndex = dotIndex;
	mediaCurrentImage = 0;
	setMediaDots();
}

function setMediaDots(){
	$('#dots a').each(function(){
		if($(this).attr('id') == mediaPhotoSetIndex){
			if(!$(this).hasClass('current')){
				$(this).addClass('current');
			}
		} else {
			$(this).removeClass('current');	
		}
	});
}


// parsing the result
function parseMediaXML(data){
	resetMediaGallery();
	
	switch(mediaWebSection){
	
		case 'news':
			mediaDynamic = true; // tells the JS that this is images from a DB for caching issues
			
			$(data).find("settings").each(function(){
		
				// gettin the path of the images
				photoPath = $(this).attr("imgRoot");
				
				
				//###### POPULATING ARRAYS WITH IMAGES #########
				$(this).find("page").each(function(){
					
					$(this).find("image").each(function(){
						mediaImageDescription.push('');
						mediaImageMenus.push('');
						mediaPhotoList.push(photoPath + $(this).attr("img"));
						mediaPhotoListThumb.push(photoPath + $(this).attr("img") + '&thumb=true');
						
					});
					
				});
				
				
				//###### CREATING SUB MENU ###########
				if(!createdMediaMenu){
					
					//pull up the playPause and menu buttons
					$('#playPause').css('top','16px');
					$('#menuRestaurant').css('top','16px');	
					createdMediaMenu = true;
				}
			});
			break;
		default:
			$(data).find("settings").each(function(){
		
				// gettin the path of the images
				thumbPath = $(this).attr("imgRoot") + 'thumbnails/';
				photoPath = $(this).attr("imgRoot") + 'large/';
				
				//###### POPULATING ARRAYS WITH IMAGES #########
				
				//check if there is an image list
				if(mediaImageList) {
					mediaImageList = mediaImageList.split(',');
					for(n=0; n<mediaImageList.length; n++) {
						mediaPhotoList.push(photoPath + mediaCategory + '-' + mediaImageList[n] + '.jpg');
						mediaPhotoListThumb.push(thumbPath + mediaCategory + '-' + mediaImageList[n] + '-thumb.jpg');
					}
					mediaImageList = null;
				} else {
					$(this).find("page").each(function(){
						if($(this).attr("id") == mediaKeyword){
							$(this).find("image").each(function(){
								
								if($(this).attr("dir")){
									tmpPhotoPath = $(this).attr("dir") + 'large/';
									tmpThumbPath = $(this).attr("dir") + 'thumbnails/';
								} else {
									tmpPhotoPath = photoPath;
									tmpThumbPath = thumbPath;
								}
								mediaImageDescription.push($(this).text()); 
								mediaPhotoList.push(tmpPhotoPath + $(this).attr("img") + '.jpg');
								mediaPhotoListThumb.push(tmpThumbPath + $(this).attr("img") + '-thumb.jpg');
								
								//checking restaurant menu
								if($(this).attr('menu') && $(this).attr('menu') != ''){
									mediaImageMenus.push($(this).attr('menu'));	
								} else {
									mediaImageMenus.push('');
								}
							});
						}
					});
				}
				
				//###### CREATING SUB MENU ###########
				if(!createdMediaMenu){
					if($("page",this).length > 1){
						var menuHTML = '';
					
						$(this).find("page").each(function(){
							if($(this).attr('id') != '' && $(this).attr('label')){
								tmpLabel = $(this).attr('label');
								tmpLabelID = $(this).attr('id');
								menuHTML += '<a id="'+tmpLabelID+'">' + tmpLabel.toUpperCase() +  '</a>';
							}
						});
						
						$('#label').html(menuHTML);
						
						if(menuHTML != ''){
							$('#label a').each(function(){
								// add the class to the current Keyword
								if($(this).attr('id') == mediaKeyword){
									$(this).addClass('currentLab');
									currentLabel = $(this).attr('id');
								}
								// assign click functionality
								$(this).click(function(){
									if(mediaIsClickable){
										clearTimeout(mediaTimer);
										mediaKeyword = $(this).attr('id');
										$('#'+currentLabel).removeClass('currentLab');
										$(this).addClass('currentLab');
										currentLabel = $(this).attr('id');
										parseMediaXML(data);
									}
								});
								
							});
							
							$('#labels').show();
						} else {
							//pull up the playPause and menu buttons
							$('#playPause').css('top','16px');
							$('#menuRestaurant').css('top','16px');		
						}
						
					} else {
						//pull up the playPause and menu buttons
						$('#playPause').css('top','16px');
						$('#menuRestaurant').css('top','16px');	
					}
					createdMediaMenu = true;
				}
			});
	}
	
	
	
	//######## SETTING UP VARS FOR THUMBNAILS ########
	mediaLoopTotal = Math.ceil(mediaPhotoList.length/visibleThumbs);
	
	if(mediaLoopTotal <= 1){
		$('#nextSet').hide();
		$('#prevSet').hide();
		$('#thumb').css('margin-left','23px');
		setFx = false;
	} else {
		$('#nextSet').show();
		$('#prevSet').show();
		$('#thumb').css('margin-left','0px');
		setFx = true;
	}
	
	var mediaPhotoList_all = [];
	mediaPhotoList_all = mediaPhotoListThumb.slice();
	
	//create image sets of mediaPhotoList array
	for(i=0; i<mediaLoopTotal; i++){
		var tmpArray = [];
		for(q=0; q<visibleThumbs; q++){
			if(mediaPhotoList[q] != undefined){ 
				tmpArray.push(mediaPhotoList[q]); 
			}
		}
		mediaPhotoList.splice(0,visibleThumbs);
		mediaPhotoSet.push(tmpArray);
	}
	
	// next a prev button
	$('#nextSet').click(function(event){
		event.stopImmediatePropagation();
		if(setFx){
			if(mediaIsClickable){
				mediaPhotoSetChange('next');	
			}
		}
	});
	
	$('#prevSet').click(function(event){
		event.stopImmediatePropagation();
		if(setFx){
			if(mediaIsClickable){
				mediaPhotoSetChange('prev');	
			}
		}
	});
	
	loadThumbs();	
	mediaLoadImage();
	mediaSetThumbNail('set');
	setMediaDots();
}


// handler the error of the 
function xmlError(){ alert("Error parsing XML."); }


function resetMediaGallery(){
	mediaCurrentImage		= 0;
	mediaPhotoSetIndex		= 0;
	mediaLoopTotal			= 0;
	tmpPhotoIndex			= 0;
	mediaPhotoList			= [];
	mediaPhotoListThumb 	= [];
	mediaPhotoSet			= [];
	mediaImageDescription	= [];
	mediaImageMenus			= [];
}


function startMediaGallery(xml,category,keyword,imageList,rmCat,restMenu,websection){
	createdMediaMenu = false;
	
	mediaCategory = category;
	mediaKeyword = keyword;
	mediaImageList = imageList;
	mediaRoomCat = rmCat;
	mediaRestMenu = restMenu;
	mediaWebSection = websection;
	
	//fetch xml
	$.ajax({
		url:xml,
		dataType:'xml',
		encoding:"UTF-8",
		success:parseMediaXML,
		error:xmlError
	});
}
