/**
 * page variables
 */
var carouselInstance;
var currentPage = 0;
var currentPageView;
var firstVisible;
var lastVisible;
var imgLoaded = true;
 
/**
 * We use the initCallback callback to assign functionality to the controls
 */
function mycarousel_initCallback(carousel, state, idx) {
    carouselInstance = carousel;
    carousel.size(GLOBAL_IMAGES_COUNT);
    
    jQuery('.photoButton .next').bind('click', function(event) {		    
    	if (imgLoaded == false) {
    		return false;
    	};
    	
		// if we reach the end of the collection       		
        if (getSelected() >= GLOBAL_IMAGES_COUNT) {         	
        	return false;         	
    	}
		
    	// select the next item        
    	if ((getSelected()+1) > lastVisible) {
    		carousel.next();
    	}
        		
		setSelectedItem(getSelected()+1);        	
    	    
		// refresh ads on click
        window.setTimeout("RefreshAds()",1500);        
        
        return false;
    });

    jQuery('.photoButton .prev').bind('click', function(event) {
    	if (imgLoaded == false) {
    		return false;
    	};
    	
        if (getSelected() == 1) {
        	return false;
      	}
		
      	if (getSelected() <= firstVisible) {
    		carousel.prev();    				
    	}		      	    
    		
		setSelectedItem(getSelected() - 1);	    
            	
        window.setTimeout("RefreshAds()",1500);      
        
	    return false;
    });
};

/**
  * When an item is no longer the first one in the visible range.
 */
function mycarousel_itemFirstOutCallback(carousel, item, idx, state) {
    //window.console.log('Item #' + idx + ' is no longer the first item - ' + state);      
};

/**
  * When an item is no longer the last one in the visible range.
 */
function mycarousel_itemLastOutCallback(carousel, item, idx, state) {
    //window.console.log('Item #' + idx + ' is no longer the last item - ' + state);
};

/**
 * When an item becomes the first one in the visible range of the carousel
 */
function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
	firstVisible = idx; //window.console.log("first visible item is: "+firstVisible);
}
/**
 * When an item becomes the last one in the visible range.
 */
function mycarousel_itemLastInCallback(carousel, item, idx, state) {
	lastVisible = idx; //window.console.log("last visible item is: "+lastVisible);    	
};

/**
 * This function gets called after new items loaded into carousel.
 */
function mycarousel_itemLoadCallback (carousel, state) {
	var rStart;
	var rEnd;	
	
	if (state == 'next') {				
		rEnd = lastVisible + GLOBAL_PAGE_SIZE;
		if (rEnd > GLOBAL_IMAGES_COUNT)	{
			rEnd = GLOBAL_IMAGES_COUNT;
		}		
		rStart = rEnd - GLOBAL_PAGE_SIZE;		
		
		var placeHolder = 0;
		//now, let's figure out how many items require loading
		for (var i = rEnd; i >= rStart; i--) {
			if ($("#photoCarousel li[jcarouselindex='"+i+"']").hasClass("jcarousel-item-placeholder")) {
				placeHolder++;
			}
		}
        loadImages(rEnd-placeHolder,placeHolder,state);                
        externalControlsCheck($("#photoCarousel li"));        
    }
    
    if (state == 'prev') {    	
    	rStart = firstVisible - GLOBAL_PAGE_SIZE - 1;    	
    	if (rStart < 0 ) {
			rStart = 0;
		}		
		var placeHolder = 0;
		//now, let's figure out how many items require loading
		for (var i = rStart; i <= lastVisible; i++) {
			if ($("#photoCarousel li[jcarouselindex='"+i+"']").hasClass("jcarousel-item-placeholder")) {
				placeHolder++;
			}
		}		
		loadImages(rStart,placeHolder,state);		    	
    	externalControlsCheck($("#photoCarousel li"));          	      	
    }
    
    if (state == 'init') {
    	 // select the first item if nothing is selected
    	 if (getSelected() == 0) {
    	 	setSelectedItem(1);
    	 }
    }
}

// To Victor: I'm not sure what this does, but the other part I added wanted it.
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;
} 

/**
This fuction will grab new images from server if required.
*/
function loadImages(rangeStart,rangeDelta,state) {
	// do not allow negative starting ranges
	if (rangeStart < 0) { rangeStart = 0; }

	// check to see if any items in the range exist	
	if (state =='prev') {
		for (k=rangeStart; k <=(rangeStart+rangeDelta); k++) {
        if (carouselInstance.has(k))
            return false;
    	}	
	}

    // the rangeEnd is the start + # of items to be loaded
    rangeEnd = rangeStart + rangeDelta;
    
    // if the rangeEnd exceeds the total number of images then limit it
    if (rangeEnd > GLOBAL_IMAGES_COUNT) {
    	rangeDelta = GLOBAL_IMAGES_COUNT-rangeStart;
    }
	
	// adjust for next
    if (state == 'next') {    	
		for (k=rangeStart+1; k <=(rangeStart+rangeDelta); k++) {    	
        if (carouselInstance.has(k))
            return false;
    	}	
    }    
	
    // if no items need to be loaded then don't execute
    if (rangeDelta == 0) { return false; }
    
    // calculate path of images to return
    var ajaxPath = GLOBAL_AJAX_PATH + (rangeStart) + '-' + rangeDelta ;    	
    
    // adjust for next
    if (state == 'next') { rangeDelta = rangeDelta + 1; }    
    
	carouselInstance.lock();
    $.ajax({
        url: ajaxPath,
        timeout: 6000,
        success: function(rawResponse) {
            carouselInstance.unlock();
                        
            var allImages = rawResponse.split(GLOBAL_AJAX_ROW_DELIM);
            
            function renderMarkup() {
            	if (allImages[index]) {
                    var imgCurrent = allImages[index].split(GLOBAL_AJAX_DELIM);

                    if (imgCurrent[1]) {
                        var markup = "<a class=\"image\" title=\"" + imgCurrent[0].replace(/"/g, '&quot;') + "\" href=\"" + printf(GLOBAL_BASE_LINK, imgCurrent[6]) + "\">" + 
                                        "<img src=\"" + imgCurrent[1] + "\" " + 
                                        "bigImg=\"" + imgCurrent[7] +  "\" " +
                                        "photoText=\"" + imgCurrent[0].replace(/"/g, '&quot;') + "\" " +
                                        "photoCredit=\"" + imgCurrent[2].replace(/"/g, '&quot;') + "\" " +
                                        "alt=\"" + imgCurrent[5].replace(/"/g, '&quot;') + "\" />" +
                                        "</a>";                                        
                                        
                        carouselInstance.add(i, markup);	                                            
                        carouselInstance.get(i).children('a').bind('click', imageClickHandler);
                        carouselInstance.get(i).css("background-color", "transparent").css("background-image", "none");
                    }
                }
            }
            
            if (state == 'prev') {  
	            for (var i = rangeStart+1; i <= (rangeStart + rangeDelta); i++) {
	            	var index = i-rangeStart-1;            		            	
	                renderMarkup();
	            }
            }
            
            if (state == 'next') { 
            	rangeStart = rangeStart + 1; 
	            for (var i = rangeStart; i < (rangeStart + rangeDelta); i++) {
	            	var index = i-rangeStart;            	
					renderMarkup();
	            }	
        	}                       
        }
    });
    
    return true;
};

/**
 * Change the state of the external controls 
 * based on image index.
 */
function externalControlsCheck(galleryItems) {		
    
    // check next controls	
	if (getSelectedImageIndex(galleryItems) < GLOBAL_IMAGES_COUNT)
        enableNextButton();
    else
        disableNextButton();
        
    //check prev controls
    if (getSelectedImageIndex(galleryItems) > 1)
        enablePrevButton();
    else
        disablePrevButton();
}

function getSelected() {
    var selectedIndex = parseInt(getSelectedImageIndex($("#photoCarousel li")));
    return selectedIndex ? selectedIndex : 0;
}

function enableNextButton() {
    $(".photoButton .next").removeClass("disabled");
}

function disableNextButton() {
    $(".photoButton .next").addClass("disabled");
}

function enablePrevButton() {
    $(".photoButton .prev").removeClass("disabled");
}

function disablePrevButton() {
    $(".photoButton .prev").addClass("disabled");
}

 
/**
 * Function to determine how many pages 
 */
function getPageCount() {
    if (GLOBAL_IMAGES_COUNT > 0) {
        return Math.floor(GLOBAL_IMAGES_COUNT / GLOBAL_PAGE_SIZE) + 1;
    } else {
    	return 1
    };
}

/**
 * Function to return the currently selected item
 * input: the collection of thumbnails in the carousel
 * output: the jcarousel index number of the selected item
 */
function getSelectedImageIndex(thisCol) {	
	var returnedIndex;
	
	$(thisCol).each(function(i) {			
    	if ($(this).hasClass("selected")) {       			
    		returnedIndex = parseInt($(this).attr("jcarouselindex"));
    	}
    });     		
    return returnedIndex; 
}

function setSelectedItem(pId) {	
	$("#photoCarousel li[jcarouselindex='"+ pId + "']").addClass("selected").children("a").click();		    
}

/**
 * Image Load Transition
 */
function imageLoadFX(thisTarget) {
	var imgPath = $(thisTarget).attr("bigImg");	  
    $("#photoFrame table tbody tr td img").load(function() {
    	$(this).hide();
    	$("#photoFrame table td").removeClass("loading");
    	$(this).fadeIn("fast");	 
    	imgLoaded = true;       	
	})
	// if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded		      
    })
	.attr('src', imgPath);
    $("#photoText p").text($(thisTarget).attr("photoText"));
    $("#photoCredit").text($(thisTarget).attr("photoCredit"));
    try 
    {
        //Try to set share this image.
        shared_object.properties.icon = imgPath;
    } catch (ex) { }
}

/**
 * Place holder function to load the images
 */
function showSelectedImage(pId) {	
	var imgTarget = $("#photoCarousel li[jcarouselindex='"+ pId + "']").addClass("selected").children("a").children("img");
	imgLoaded = false;	
		
	$("#BigPhoto").fadeOut(100, function() {		
		$("#photoFrame table td").addClass("loading");
		if ($(imgTarget).attr("bigImg")) {
			imageLoadFX(imgTarget);			
		} else {
		    // Set main image to loading....		    
		    return false;
		    window.setTimeout("showSelectedImage('" + pId + "')",500);
		}			
	});
}

/**
 * Function to set the specified thumbnail as selected
 * input: imageId from querystring
 */
function setSelectedItemByImageId(imageId) {
	// simulate click on element
    $("#photoCarousel li[imageid='"+ imageId + "']").addClass("selected").children("a").click();
}

/**
 * Function to load the specified image by imageId
 * input: imageId from querystring
 */
function showSelectedImagebyImageId(imageId) {
    var imgTarget = $("#photoCarousel li[imageid='"+ imageId + "']").addClass("selected").children("a").children("img"); 
    imgLoaded = false;
    
    $("#BigPhoto").fadeOut("fast", function() {		
		$("#photoFrame table td").addClass("loading");
	    if ($(imgTarget).attr("bigImg")) {
	    	imageLoadFX(imgTarget);
		}
		else
		{
			return false;
		    window.setTimeout("showSelectedImagebyImageId('" + imageId + "')",500);
		}
	});
}

function imageClickHandler() {
    var gallery_items = $("#photoCarousel li");		    
    // clear selections on all li
    gallery_items.removeClass("selected");
	
    // add selected class to clicked element
    $(this).parent().addClass("selected");
    
    // update image index    	    	
    var pId = getSelectedImageIndex(gallery_items);
    $(".imageIndex").text(pId);
	
    // set the currentPage	    
	// currentPage = (pId - (pId % GLOBAL_PAGE_SIZE)) / GLOBAL_PAGE_SIZE;
    
    //preload next batch if necessary
    if (pId == lastVisible) {
    	loadImages(lastVisible,GLOBAL_PAGE_SIZE,"next");	
    }
    
    if (pId == firstVisible) {    	
    	var numcheck = firstVisible-(GLOBAL_PAGE_SIZE)-1;
    	var leftover = GLOBAL_PAGE_SIZE;
    	if (numcheck < 0) { numcheck = 0; }    	    	
    	if (firstVisible < GLOBAL_PAGE_SIZE) { leftover = firstVisible-1; }
    	loadImages(numcheck,leftover,"prev");    	
    }
    
    // update the photo
    showSelectedImage(pId);
    
    // initialize external controls
    externalControlsCheck(gallery_items);
    
    // negate default behavior    	
    return false;
}

// 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];
	}
}

$(document).ready(function() {	
    // initialize the carousel	
    if ($('#photoCarousel').size() > 0) {
    	// offset the list so we can pre-load the images	
		var initOffset = (GLOBAL_CURRENT_PAGE_INDEX * GLOBAL_PAGE_SIZE) + 1;
		
		// start this page of images
		var initStart = (GLOBAL_CURRENT_PAGE_INDEX * GLOBAL_PAGE_SIZE) + 1;	
    	
        if ($.jcarousel) {
            $('#photoCarousel').jcarousel({
                // Configuration goes here
                scroll: 8,
                easing: "easeInOutCubic",
                offset: initOffset,    
                start: initStart,            
                initCallback: mycarousel_initCallback,
                itemLoadCallback: mycarousel_itemLoadCallback,
                itemLastInCallback: mycarousel_itemLastInCallback,
                itemFirstOutCallback: mycarousel_itemFirstOutCallback,
                itemLastOutCallback: mycarousel_itemLastOutCallback,
                itemFirstInCallback: mycarousel_itemFirstInCallback,
                itemLastInCallback: mycarousel_itemLastInCallback                
            });
        } else {
            $.getScript(scriptPath + jQCarousel, function() {
                $('#photoCarousel').jcarousel({
                    // Configuration goes here
                    scroll: 8,
                    easing: "easeInOutCubic",                    
                    offset: initOffset,
                    start: initStart,
                    initCallback: mycarousel_initCallback,
                    itemLoadCallback: mycarousel_itemLoadCallback,
                    itemLastInCallback: mycarousel_itemLastInCallback,
                	itemFirstOutCallback: mycarousel_itemFirstOutCallback,
                	itemLastOutCallback: mycarousel_itemLastOutCallback,
	                itemFirstInCallback: mycarousel_itemFirstInCallback,
    	            itemLastInCallback: mycarousel_itemLastInCallback  
                });
            });
        }

        // handle clicks on the carousel    
        $("#photoCarousel li a").bind('click', imageClickHandler);

        // start on this item         
        var imageId = getUrlParameter("ImageId");
        
        if (imageId) {
            setSelectedItemByImageId(imageId);
        } else {
        	setSelectedItem(1);
        }       
    }
});
