/**
 * page variables
 */
var selectedImageIndex = 0;
var currentPage = 0;
var initialIndex = 0;

function printf() { 
  var num = arguments.length; 
  var oStr = arguments[0];   
  for (var i = 1; i < num; i++) { 
    var pattern = "\\{" + (i-1) + "\\}"; 
    var re = new RegExp(pattern, "g"); 
    oStr = oStr.replace(re, arguments[i]); 
  } 
  return oStr; 
} 
var moveCarousel = false;
/**
 * We use the initCallback callback
 * to assign functionality to the controls
 */
function mycarousel_initCallback(carousel, state) {
    jQuery('#head_next, #foot_next').bind('click', function(event) {
		var selImgIdx = getSelectedImageIndex($("#photo_carousel li"));
		if (selImgIdx >= GLOBAL_IMAGES_COUNT - 1) {
          return false;
        }
		
		if (carousel.slideshowON) {
			stopSlideshow(carousel);
		}
		
		if (event.target.id == 'head_next') {
		  InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_NextButton');
		}
		else if (event.target.id == 'a_foot_next' || event.target.id == 'foot_next') {
		  InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_Next');
		}
		
		if ((selImgIdx + 2) >= (carousel.first + GLOBAL_PAGE_SIZE)) { moveCarousel = true; carousel.next(); }
    	setSelectedItem(selImgIdx+1, carousel);

        return false;
    });

    jQuery('#head_prev, #foot_prev').bind('click', function(event) {
		var selImgIdx = getSelectedImageIndex($("#photo_carousel li"));
        if (selImgIdx == 0 && currentPage == 0) {
          return false;
        }

		if (carousel.slideshowON) {
			stopSlideshow(carousel);
		}

		if (event.target.id == 'head_prev') {
			InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_PrevButton');
		}
		else if (event.target.id == 'a_foot_prev' || event.target.id == 'foot_prev') {
			InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_Prev');
		}

		if (selImgIdx<carousel.first) { moveCarousel = true; carousel.prev(); }
    	setSelectedItem(selImgIdx-1, carousel);

	    return false;
    });
	
	jQuery("#photo_categories a").bind('click', function(event) {
		var clickedLink = $(this);
		var count = 0;
		$("#photo_categories .movie_category_item_total").each(function(i) {
			if ($(this).parent("a").attr("id") == clickedLink.attr("id")) {
				var stIndex = count-(count % GLOBAL_PAGE_SIZE);
				moveCarousel = true;
				carousel.scroll(stIndex+1);
				setSelectedItem(count, carousel);
			}
			count = count + parseInt($(this).text());
		});
		return false;
	});

    /* slideshow controls */
    var SLIDE_SPEED = 0;
    
    var SLIDE_FAST   = 2000;
    var SLIDE_MEDIUM = 4000;
    var SLIDE_SLOW   = 6000;
    var speedToggle = $("li.speed_toggle a");

	function stopSlideshow(c) {
		document.getElementById('carousel_slideshow_start').style.display = 'block';
		document.getElementById('carousel_slideshow_stop').style.display = 'none';
		document.getElementById('carousel_slideshow_rewind').style.display = 'none';
		carousel.slideshowON = false;
		speedToggle.removeClass();
		clearInterval(slideInterval);
	}

    function startSlideshow(c) {
		document.getElementById('carousel_slideshow_start').style.display = 'none';
		document.getElementById('carousel_slideshow_stop').style.display = 'block';	
		document.getElementById('carousel_slideshow_rewind').style.display = 'none';	
		carousel.slideshowON = true;

		function slideNext() {
			var oldScrollVal = c.options.scroll;
			var oldWrapVal = c.options.wrap;		
			
			/* switch to single scroll and disable wrap temporarily */
			c.options.scroll = 1;
			c.options.wrap = null;
			moveCarousel = true;
			c.next();
			c.options.scroll = oldScrollVal;
			c.options.wrap = oldWrapVal;	
			
			var g_items = $("#photo_carousel li");
			var currentlySelected = getSelectedImageIndex(g_items);
			/* get next thumb */
			var nextLI = $(g_items).eq(currentlySelected).next();
			/* if already on the last image */
			if (currentlySelected == (GLOBAL_IMAGES_COUNT-1)) {
				stopSlideshow(c);
				return false;
			}
			if (nextLI.length > 0) {
				var childA = nextLI.children("a");
				childA.click();
				/* stop slideshow if reached right most position */
				if (nextLI.next().length == 0 || currentlySelected == (GLOBAL_IMAGES_COUNT-1)) {
					stopSlideshow(c);
					displayRewindSlideshow();	
				}
				return false;
			}
		}
		
		/* start slideshow */
		if (SLIDE_SPEED == 0) {
			SLIDE_SPEED = SLIDE_MEDIUM;
			$("a#slide_medium").addClass("selected");
		}
		else if (SLIDE_SPEED == SLIDE_FAST) {
			if (!$("a#slide_fast").hasClass("selected")) { $("a#slide_fast").addClass("selected"); }
		}
		else if (SLIDE_SPEED == SLIDE_MEDIUM) {
			if (!$("a#slide_medium").hasClass("selected")) { $("a#slide_medium").addClass("selected"); }
		}
		else if (SLIDE_SPEED == SLIDE_SLOW) {
			if (!$("a#slide_slow").hasClass("selected")) { $("a#slide_slow").addClass("selected"); }
		}
		slideInterval = setInterval(slideNext, SLIDE_SPEED);
	}
	
	function rewindCarousel(c) {
		var oldScrollVal = c.options.scroll;
		var oldWrapVal = c.options.wrap;	
			
		/* switch to single scroll and enable wrap to go back to beginning */
		c.options.scroll = 1;
		c.options.wrap = "last";
		c.next();
		c.options.scroll = oldScrollVal;
		c.options.wrap = oldWrapVal;
		
		/* reset the play buttons */
		document.getElementById('carousel_slideshow_start').style.display = 'none';	
		document.getElementById('carousel_slideshow_stop').style.display = 'block';	
		document.getElementById('carousel_slideshow_rewind').style.display = 'none';
	}
	
	function displayRewindSlideshow() {		
		// disable speed buttons
		speedToggle.each(function() {
			$(this).addClass("disable");
		});
		document.getElementById('carousel_slideshow_start').style.display = 'none';	
		document.getElementById('carousel_slideshow_stop').style.display = 'none';	
		document.getElementById('carousel_slideshow_rewind').style.display = 'block';
	}
	
	function pauseSlideshow(c) {
		clearInterval(slideInterval);	
	}
	
	jQuery('#carousel_slideshow_start').bind('click', function() { /* bind click on object of choice to start slideshow */			
		startSlideshow(carousel);
		return false;
	});
	jQuery('#carousel_slideshow_stop').bind('click', function() { /* bind click on object of choice to start slideshow */
		stopSlideshow(carousel);
		return false;
	});
	
	jQuery('#carousel_slideshow_rewind').bind('click', function() { /* bind click on object of choice to rewind slideshow */
		speedToggle.each(function() {
			$(this).removeClass("disable");
		});
		setSelectedItem(0, carousel);
		rewindCarousel(carousel);
		clearInterval(slideInterval);
		startSlideshow(carousel);
		return false;
	});
	
	/* pause slideshow when mouse is over carousel */
	carousel.clip.hover(function() { if (carousel.slideshowON) pauseSlideshow(carousel);  }, 
						function() { if (carousel.slideshowON) startSlideshow(carousel);  });	

	/* stop slideshow when any carousel thumb is clicked on */	
	carousel.clip.click(function() { if (carousel.slideshowON) stopSlideshow(carousel);	});
		
	/* Change speeds*/	
	jQuery("a#slide_medium").bind('click', function() {		
		if ($(this).hasClass("disable")) {
			return false;	
		} else {
			SLIDE_SPEED = SLIDE_MEDIUM;
			InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_Med');
			resetSlideShow(this);
		}
	});
	jQuery("a#slide_fast").bind('click', function() {
		if ($(this).hasClass("disable")) {
			return false;	
		} else {
			SLIDE_SPEED = SLIDE_FAST;
			InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_Fast');
			resetSlideShow(this);
		}
	});
	jQuery("a#slide_slow").bind('click', function() {
		if ($(this).hasClass("disable")) {
			return false;	
		} else {	
			SLIDE_SPEED = SLIDE_SLOW;
			InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_Slow');
			resetSlideShow(this);
		}		
	});	
	
	function resetSlideShow(thisEl) {
		if (carousel.slideshowON) pauseSlideshow(carousel);		
		speedToggle.removeClass();
		$(thisEl).addClass("selected");
		startSlideshow(carousel);
		return false;
	}
	// if an image is preselected, move around initial set to the correct page index
	if (initialIndex > 0) {
		var idx = initialIndex - (initialIndex % GLOBAL_PAGE_SIZE) + 1;
		carousel.size(GLOBAL_IMAGES_COUNT);
		
		for (var k=1;k<=6;k++) {
			carousel.add(idx+k-1,carousel.get(k).html());
			carousel.add(k,'');
		}
	}
};
/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 */
function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
	var nonArrow = moveCarousel;
	moveCarousel = false;

	if (state == 'prev' && !nonArrow) {
		InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_PrevArrow');
	}
	else if (state == 'next' && !nonArrow) {
		InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_NextArrow');
	}
	
	// if image should be selected, scroll to that page
	if (initialIndex > 0) {
		var subPageIndex = initialIndex % GLOBAL_PAGE_SIZE;
		var startIndex = initialIndex - subPageIndex + 1;
		carousel.scroll(startIndex);
		setSelectedItem(initialIndex, carousel);
		initialIndex = 0;
	}

	currentPage = Math.ceil((idx - 1)/GLOBAL_PAGE_SIZE);
	if (currentPage > GLOBAL_PAGE_COUNT) { currentPage = GLOBAL_PAGE_COUNT; }
	if (currentPage < 0) { currentPage = 0; }

	var f = idx;
	var l;
	var fSet = false;
	// check if the items have been loaded already
	for (var j=0;j<GLOBAL_PAGE_SIZE;j++) {
		if (!carousel.has(j+idx) && !fSet) {
			f = j+idx;
			fSet = true;
		}
		l = j+idx;
	}

	var ajaxPath = GLOBAL_AJAX_PATH + (f-1) + '-' + (l-1);
	carousel.lock();
	$.ajax({
		url: ajaxPath,
		success: function (rawResponse) {
		    carousel.unlock();
			carousel.size(GLOBAL_IMAGES_COUNT);
			var allImages = rawResponse.split(GLOBAL_AJAX_ROW_DELIM);
			for (var i = f; i <= l; i++) {
				var index = i - f;
				if (allImages[index]) {
					var imgCurrent = allImages[index].split(GLOBAL_AJAX_DELIM);
					if (imgCurrent[1]) { 
						var markup = "<a href=\""+ printf(GLOBAL_BASE_LINK, imgCurrent[6]) +"\"><img src=\"" + imgCurrent[1] + "\" alt=\"" + imgCurrent[5].replace(/"/g, '&quot;') + "\" /></a>";
						carousel.add(i, markup);
						carousel.get(i).children('a').bind('click', function() {
							selectImage($(this).parent(), -1);
							InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_Thumb');
							return false;
						});
						carousel.get(i).css("background-color", "transparent").css("background-image", "none");
					}
				}
			}
	        if (typeof RefreshAds == 'function' && state != 'init' && !nonArrow) {
	            RefreshAds();
				RefreshGsl();
	        }
		}
	});
	if (jQuery.browser.safari) {
		$("#photo_carousel").css("width", ($("#photo_carousel").width() + 72) + "px");
	}
};
$(document).ready(function() {
 
    // make sure the basic elements are defined on this page, otherwise, dont bother executing.
    if ((typeof(GLOBAL_IMAGES_COUNT) == 'undefined' || typeof(GLOBAL_PAGE_SIZE) == 'undefined'))
    {
        return;
    }

	// initial variables
	var imageId = selectedImageIndex;
	initialIndex = selectedImageIndex;

	var preSelect = true;
	if (initialIndex > 0) { preSelect = false; }
	
	// easing equation
	jQuery.easing['InOutCubic'] = function(x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	};
	
	// initialize the carousel	
    jQuery('#photo_carousel').jcarousel({
        // Configuration goes here
        scroll: 6,
        easing: "InOutCubic",
        initCallback: mycarousel_initCallback,
        itemFirstInCallback:  mycarousel_itemFirstInCallback
    });
    
    // enumerate number of items in gallery
    $("#gallery_total").text(GLOBAL_IMAGES_COUNT);

    // handle clicks on the carousel    
    $("#photo_carousel li a").bind('click', function() {
		selectImage($(this).parent(), -1);
		InformWSS(GLOBAL_WSS_HEAD+getHbLinkCategory(), GLOBAL_WSS_HEAD+getHbLinkCategory()+'_Thumb');
    	return false;
    });
    // start on this item if an initial index hasn't been assigned
	if (preSelect) {
		setSelectedItem(imageId, '');
	}
});

function selectCategory(index) {
	var count = 0;
	var clickedLink;
	var doUpdate = true;
	var done = false;
	var subIndex = 1;

	$("#photo_categories .movie_category_item_total").each(function(i) {
		if (!done) { 
			subIndex = index - count + 1;
			count = count + parseInt($(this).text());
			if (index >= 0 && count > index) {
				if ($(this).parent(".movie_category_selected").length > 0) {
					done = true;
					doUpdate = false;
				} else {
					clickedLink = $(this).parent("a");
					done = true;
				}
			}
		}
	});

	var selected = $("#photo_categories .movie_category_selected");
	selected.children(".movie_category_selected_index").text(subIndex);

	if (doUpdate && clickedLink) {
		var clone = clickedLink.clone(true);

		var selectedTotal = selected.children(".movie_category_item_total").text();
		var cloneTotal = clone.children(".movie_category_item_total").text();
		selected.children(".movie_category_item_total").text(cloneTotal);
		clone.children(".movie_category_item_total").text(selectedTotal);
		
		var selectedText = selected.children("strong").text();
		var cloneText = clone.children("strong").text();
		
		selected.children("strong").text(cloneText);
		clone.children("strong").text(selectedText);
		
		clone.insertBefore($("#photo_categories .movie_category_selected"));
		$("#photo_categories .movie_category_selected").insertAfter(clickedLink);
		clickedLink.remove();
		
		//update wss value for see all thumbnails link
		var lid = GLOBAL_WSS_HEAD+getHbLinkCategory();
		$("#photo_container a.see_thumbs").attr("name", "&lid="+lid+"&lpos="+lid+"_More");
		
		// update thumbnails link
		var selCategory = getSelectedCategory();
		if (selCategory == "Special Events") {
			$("#photo_container a.see_thumbs").attr("href", GLOBAL_EVENTS_LINK);
		} else if (selCategory == "Posters") {
			$("#photo_container a.see_thumbs").attr("href", GLOBAL_POSTERS_LINK);
		} else {
			$("#photo_container a.see_thumbs").attr("href", GLOBAL_STILLS_LINK);
		}
	}
	if (getUrlParameter("mode") != "thumbs") {
		document.title = GLOBAL_PAGE_TITLE_FIRST + getTitleText();
		if (!movTitleUpdated) {
			var movTitle = $("h1.movie_title .right_separator").text();
			$("h1.movie_title .right_separator").text(GLOBAL_H1_PREPEND + movTitle);
			movTitleUpdated = true;
		}
		var $title = $("h1 .right_separator");
		$("h1.movie_title").empty();
		$("h1.movie_title").append($title);
		$title.after(getTitleText());
	}
}
var movTitleUpdated = false;
function externalControlsCheck(selImgIdx) {
	// check next controls
	if ((selImgIdx + 1) == GLOBAL_IMAGES_COUNT) {
		$("#head_next, #foot_next").addClass("disabled");
    } else {
    	$("#head_next, #foot_next").removeClass("disabled");
    }
    
    //check prev controls
    if (selImgIdx <= 0 && currentPage == 0) {
    	$("#head_prev, #foot_prev").addClass("disabled");
    } else {
    	$("#head_prev, #foot_prev").removeClass("disabled");
    }
}
function getSelectedImageIndex(thisCol) {
	return selectedImageIndex;
}
function setSelectedItem(pId, carousel) {
	var m = pId % GLOBAL_PAGE_SIZE;
	var q = (pId - m)/GLOBAL_PAGE_SIZE
	var previousPage = currentPage;
	selectedImageIndex = pId;
	if (currentPage != q) {
		currentPage = q;
	}
	if (carousel.length != 0) {
		var carItem = carousel.get(pId+1);
		if (carItem.length > 0) {
			selectImage(carItem, pId);
		}
	} else {
		var subIndex = m;
		selectImage($("#photo_carousel li:eq(" + subIndex + ")"), pId);
	}
}
function selectImage(listItem, imgIndex) {
	var gallery_items = $("#photo_carousel li");
	gallery_items.removeClass("selected");
	
	// add selection on currently selected
	listItem.addClass("selected");
	var imgIdx;
	if (imgIndex >= 0) {
		imgIdx = imgIndex;
	} else {
		imgIdx = getIndexFromClass(listItem)-1;
		selectedImageIndex = imgIdx;
	}
	// update image index
	var displayIndex = imgIdx+1;
	$("#image_index").text(displayIndex);

	// initialize external controls
	externalControlsCheck(imgIdx);

	if (typeof showSelectedImage == 'function') {
		showSelectedImage(imgIdx);
		RefreshAds(); 
		RefreshGsl();
	}
	selectCategory(imgIdx);
}
// get url parameter
function getUrlParameter(name) {
  if (window.location.href.match("/moviephotos/") != null)
	{
	    var urlParts = window.location.href.split("_");
	    if (urlParts.length == 4)
	    {
	        return urlParts[3];
	    }
	    return 1;
	}
	else
	{
  		name 	= name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  		var regexS = "[\\?&]"+name+"=([^&#]*)";
  		var regex = new RegExp( regexS );
  		var results = regex.exec( window.location.href );
  		if( results == null )
    			return "";
  		else{
    			return results[1];
    			}
	}
}
function getIndexFromClass(listItem) {
	var classes = listItem.attr("class");
	var indiv = classes.split(/ /);
	for (var j=0; j<indiv.length; j++) {
		if (indiv[j].indexOf(GLOBAL_INDEX_CLASS_PREFIX) == 0) {
			var numString = indiv[j].substring(GLOBAL_INDEX_CLASS_PREFIX.length);
			var k = parseInt(numString);
			if (k > 0) { return k; }
		}
	}
	return 0;
}
function getHbLinkCategory() {
	var selCategory = getSelectedCategory();
	if (selCategory == "Special Events") {
		return "Events";
	}
	if (selCategory == "Posters") {
		return "Posters";
	}
	return "Stills";
}
function getTitleText() {
	var selCategory = getSelectedCategory();
	if (selCategory == "Special Events") {
		return "Special Events Photos";
	}
	if (selCategory == "Posters") {
		return "Movie Posters";
	}
	return "Movie Photos";
}
function getSelectedCategory() {
	return $("#photo_categories .movie_category_selected").children("strong").text();
}
var gsl_root = "";
function RefreshGsl() {
	try {
		if (gsl_root.length == 0) {
			gsl_root = $(".gsl iframe").attr("src");
		}
		$(".gsl iframe").attr("src", gsl_root + "&" + new Date().getTime());
	} catch (e) {
	}
}
