// Variable to keep track of current thumbnail set.
var thumbnailSet;

// Variable to keep track if previous is pressed when the user is on first image thumbnail of the thumbnail set.
var lastSelected = false;

// Counter for current image which is to be displayed on slide show
slideShowCounter = parseInt("0",10);
var slideShowTimer;
var _slideshowInProgress = false;

// First image number from which slide show is started
firstImageSlideShowNumber = parseInt("0",10);

// Ajax call is made for getting image for slide show only if this variable is true
var getMoreImages = true;

// Search tab(view all tab has search photos) is shown if searchTab = true
var searchTab = false;

// Search term
var searchTerm = "";

// View All tab generated
var isTabGenerated = false;

var ajaxCallForFilteringByDate = false;

var _photoResponseObject = new Array();
var _slideshowTimeInMilliseconds = 5000;
var _slideshowIsPaused = false;

// This method is executed on page load
$(document).ready(function()
{
    setTimeout( function() {

	    var carouselWidth = 0;
	    $('ul#mycarousel li').each(function(){ carouselWidth += $(this).width() });
    	
	    var imageWidth = $('.previewImage').width();
    	
	    if (carouselWidth > imageWidth) $('.jcarousel-prev, .jcarousel-next').show();
	    else $('.jcarousel-prev, .jcarousel-next').hide();
    	
    }, 100);

    // If the this div exists on the page then onload the variable firsttime is incremented
    if (document.getElementById("divPhotoGallery")) 
    { 
        thumbnailSet = 1;
    }

    // Click event for "Next" in the thumbnail area
    $("#divPaginationThumbnailArea a.linkNext").click(function(event) 
    {
        event.preventDefault();
        var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);    
        var lastPhotoNumber = parseInt($(".thumbnailContainer ul li:last div.photoInfoThumbnail span.photoNumber").html(),10);    
        
        // If total number of phots is greater than last photo number then only photo galery thumbnails shoiuld be reloaded
        if(totalPhotos > lastPhotoNumber)
        {
            thumbnailSet = thumbnailSet+1;
            
            categoryName = $(".searchBoxContent .categoryInfo .categoryTitle").html();
            categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();            
		    displayPhotoGallery(categoryName, categoryCount);
        }
        
        //Gray out the navigation links 
        setNavigationLinksForPhotos();
    });

    // Click event for "Previous" in the thumbnail area
    $("#divPaginationThumbnailArea a.linkPrevioius").click(function(event) 
    {
        event.preventDefault();
        var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);    
        var firstPhoto = parseInt($(".thumbnailContainer ul li:first div.photoInfoThumbnail span.photoNumber").html(),10);
        
        // This link should not work if user is on first thumbnail set
        if(firstPhoto != 1)
        {
            thumbnailSet = thumbnailSet-1;
            categoryName = $(".searchBoxContent .categoryInfo .categoryTitle").html();
            categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();		    
		    displayPhotoGallery(categoryName, categoryCount);
        }
        
        //Gray out the navigation links 
        setNavigationLinksForPhotos();
    });

    // Click event for "Next" in the main content area
    $("#divPaginationContentArea a.linkNext").click(function(event) 
    {
        event.preventDefault(); 
        var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);    
        var lastPhotoNumber = parseInt($(".thumbnailContainer ul li:last div.photoInfoThumbnail span.photoNumber").html(),10);
        var currentPhotoNumber = parseInt($(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html(),10);
        
        // If current photo number is equal to total number of photos then nothing should happen on click of the link
        if(currentPhotoNumber != totalPhotos)
        {
            // Last photo number is equal to current photo number then the thumbnails should be reloaded
            if((lastPhotoNumber == currentPhotoNumber))
            {
                thumbnailSet = thumbnailSet+1;
                categoryName = $(".searchBoxContent .categoryInfo .categoryTitle").html();
                categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();		    
		        displayPhotoGallery(categoryName, categoryCount);
            }
            // Else only the selection should change 
            else
            { 
	            $(".thumbnailContainer ul li.selected").next("li").addClass("selected");
                $(".thumbnailContainer ul li.selected").prev("li").removeClass("selected");     
                setSelectedThumbnail();
            }
        }
        
        //Gray out the navigation links 
        setNavigationLinksForPhotos();
    });

    // Click event for "Previous" in the main content area
    $("#divPaginationContentArea a.linkPrevioius").click(function(event) 
    {
        event.preventDefault();
        var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);    
        var firstPhoto = parseInt($(".thumbnailContainer ul li:first div.photoInfoThumbnail span.photoNumber").html(),10);
        var currentPhotoNumber = parseInt($(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html(),10);
        
        // If user is on photo number one of the gallery then nothing should happen on click of the link
        if(currentPhotoNumber != 1)
        {
            // If first photo number is equal to current photo number then the thumbnails should be reloaded
            if(firstPhoto == currentPhotoNumber)
            {
                thumbnailSet = thumbnailSet-1;
                lastSelected = true;
                categoryName = $(".searchBoxContent .categoryInfo .categoryTitle").html();
                categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();	    
		        displayPhotoGallery(categoryName, categoryCount);                
            }
            // Else only the selection should change 
            else
            {
                $(".thumbnailContainer ul li.selected").prev("li").addClass("selected");
                $(".thumbnailContainer ul li.selected").next("li").removeClass("selected");     
	            setSelectedThumbnail();
            }
        }
        
        //Gray out the navigation links 
        setNavigationLinksForPhotos();
    });
   
    // Binds the search events
    bindSearchEvent();
    
    // Binds the events for date filter
    bindDateEvent();
    
    // Sets the sected thumbnail on DOM load (first time)
	setSelectedThumbnail();

    // Binds click event for tabs
    bindTabs();
    
    // Binds the events
    rebindEvents();  
    
    // Binds slide show events
    bindSlideShowEvents();
    
    setDefaultSearchText();
    
    //showWallpaperDownload();
    
    //Hide or Display navigation buttons for Thumbnails 
    displayThumbnailNavigation();

    //Gray out the navigation links 
    setNavigationLinksForPhotos();
    
    bindWallpaperCatgoryEvent();
    
    bindGuestCatgoryEvent();    
    
    fixDateCaptionSpacing();
});

function bindWallpaperCatgoryEvent()
{   
    $(".innerDivWallPaper a").click(function(event) 
    {
        event.preventDefault();
        showWallpaperDownload($(".wallpaperCategory").html());
    });
}

function bindGuestCatgoryEvent()
{   
    $(".divGuestCategory a").click(function(event) 
    {
        event.preventDefault();
        showWallpaperDownload($(".guestCategory").html());
    });
}



function SetCategoryTitle(categoryName, categoryCount)
{   
    $(".searchBoxContent .categoryInfo").html("<span class='categoryTitle'>" + categoryName + "</span>&nbsp;" + "(<span class='categoryCount'>" + categoryCount + "</span>)");
}


function showWallpaperDownload(currentCategory)
{    
    if(currentCategory == $(".guestCategory").html())
    {
        $(".photoTabs a").parent().parent().removeClass("tabs-selected");
        $("#txtSearchPhoto").val("Search Photos");
		    thumbnailSet = 1;
		    searchTab = false;
		    removeTab();
		    isTabGenerated = false;
		    resetDateFilter();
		    categoryCount = $(".lblGuestCategoryCount").html();		    
		    displayPhotoGallery(currentCategory,categoryCount);
		    initialize();		    
		    setSelectedThumbnail();
		    //displayThumbnailNavigation();
		    displayDates(currentCategory);
		    setDefaultSearchText();
		    if(!($("#divWallpaper").hasClass("hideDiv")))
            {
                $("#divWallpaper").addClass("hideDiv");
            }
    }
    
    if(($(".viewWallpaperDownload").html() == "true") && ($(".wallpaperCategory").html() == currentCategory))
    {
        $("#divWallpaper").removeClass("hideDiv");
        bindWallpaperEvent();
        $(".photoTabs a").parent().parent().removeClass("tabs-selected");
        $("#txtSearchPhoto").val("Search Photos");
		    thumbnailSet = 1;
		    searchTab = false;
		    removeTab();
		    isTabGenerated = false;
		    resetDateFilter();
		    categoryCount = $(".lblWallpaperCategoryCount").html();		    
		    displayPhotoGallery(currentCategory,categoryCount);
		    initialize();
		    setSelectedThumbnail();
		    //displayThumbnailNavigation();
		    displayDates(currentCategory);
		    setDefaultSearchText();
    }
    else if(!($("#divWallpaper").hasClass("hideDiv")))
    {
        $("#divWallpaper").addClass("hideDiv");
    }
}

function bindWallpaperEvent()
{
	var width = 0;
	var height = 0;
	var overlayDivWidth = 0;
	var overlayDivHeight = 0;
	// Looping through all the photo tabs
	$(".photoWallpaperHolder a").unbind("click").bind("click", function(event)
	{
		event.preventDefault();		
		
		width = $(this).html().split(" x ")[0];
		height = $(this).html().split(" x ")[1];
		
		/*
		if ( $("body > .ui-dialog .viewWallpaperModal").length == 0 ){
		    $('.viewWallpaperModal').dialog({
			    bgiframe: true,
			    autoOpen: false,
			    width: 960,
			    height: 750,
			    modal: true,
			    resizable: false,
			    position: 'top',
			    closeOnEscape: true
		    });
		}		
		
		getWallpaper(width, height);
		*/
		
		var photoUrl = $(".thumbnailContainer ul li.selected a").attr("largeurl");
		var rootPhotoUrl = photoUrl.substring(0, photoUrl.indexOf("?"));
				
		window.open(rootPhotoUrl + "?w=" + width + "&h=" + height);
		
		return false;
	});
}

function getWallpaper(width, height)
{
    // Extracting the category name
    //$(".viewWallpaperModal").removeClass("hideDiv");
    var photoNumber = $(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html();;
    
	// URL for service call
	var photoWallaperURL= "/vailresorts/sites/breckenridge/WebServices/PhotoGalleryService.svc/GetWallpaper";

	// AJAX call for getting the data to be loaded in the thumbnails
	$.ajax(
	{
	    type: "POST",
	    url: photoWallaperURL,
	    data: "{\"photoNumber\" : \"" + photoNumber + "\",\"width\" : \"" + width + "\",\"height\" : \"" + height + "\"}",
	    contentType: "application/json; charset=utf-8",
	    dataType: "json",
	    success: function(msg) {
	        $("body > .ui-dialog .viewWallpaperModal").closest(".ui-dialog").css("overflow", "visible");

	        $('body > .ui-dialog .viewWallpaperModal').html(msg.d);
	        $('body > .ui-dialog .viewWallpaperModal img').css("width", "960px");
	        $("body > .ui-dialog .viewWallpaperModal").removeClass("hideDiv").dialog("open");
	    },
	    error: function(xhr, status, error) {
	        handlePhotoGalleryError(xhr, status, error);
	    }
	});
}

function handlePhotoGalleryError(xhr, status, error) {
    var errMsg = getErrorMessage(xhr, status, error);
    if ($("#slideShowControl").is(":visible")) {
        $("#slideShowControl").html('<span class="errorMessage">' + errMsg + '</span>');
    }

    $("#divPhotoGallery").html('<span class="errorMessage">' + errMsg + '</span>');
}

function bindDateEvent()
{
    $("#filterByDate").click(function(event){
		$("#txtSearchPhoto").val("Search Photos");
        searchTab = false;
        ajaxCallForFilteringByDate = true;
        categoryName = $(".searchBoxContent .categoryInfo .categoryTitle").html();        
        categoryCount = $(".searchBoxContent .categoryInfo .categoryCount").html();	
           
		displayPhotoGallery(categoryName, categoryCount);        
    });
}

// Gets the date selecetd in the filter
function getDateFilter()
{
    var value = $("#divDates select").val();
    
    if ( $("#divDates select")[0].selectedIndex > 0 ){
        return value;
    } else {
        return "";
    }
}

// Resetting the date filter
function resetDateFilter()
{
	$("#divDates select")[0].selectedIndex = 0;
    var firstOption = $("#divDates select")[0].options[0];
    $("#divDates select")[0].options.length = 0;
    $("#divDates select")[0].options[0] = firstOption;
}

// Binds search event
function bindSearchEvent()
{
    $("#searchPhoto").click(function(event) 
    {
        event.preventDefault();
        
        if($('#txtSearchPhoto').length > 0 && $('#txtSearchPhoto').val() != "Search Photos")
        {
            searchTerm = document.getElementById('txtSearchPhoto').value;
            // If search box is not empty
            if(searchTerm != "")
            {
                 var regExp = /[\~\?\"\!\^\_\*\+\=\(\)\<\>\,\#\{\}\\;\:\\\/\\[\]]/
				 if(searchTerm.match(regExp)){
				    alert("Special characters are not allowed");
					return false;
				} 
                searchTab = true;
                
                if( $("#mycarousel li:first").hasClass("hideDiv") )
                {
    	            $("#mycarousel li:first").removeClass("hideDiv");
	                //var width = eval( $("#mycarousel").outerWidth() );
	                //width += eval( $("#mycarousel li:first").outerWidth() );
    	            //$("#mycarousel").css("width", width + 2 + "px");
    	            isTabGenerated = true;
	            }
	            
                $("#mycarousel li").removeClass("tabs-selected");
                $("#mycarousel li:first").addClass("tabs-selected");
	            
	            thumbnailSet = 1;
	            categoryName = $(".photoTabs li.tabs-selected span:first span").html();
                categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();	  
                resetDateFilter();                  
		        displayPhotoGallery(categoryName, categoryCount, true);
		        
		        if(!($("#divWallpaper").hasClass("hideDiv")))
                {
                    $("#divWallpaper").addClass("hideDiv");
                }
		        
		        initialize();
		        setSelectedThumbnail();
		        //displayDates(categoryName);
            }
        }
    });
}

// Removing search tab if not required
function removeTab()
{
    // If tab is generated
    if(isTabGenerated)
    {
        var width = eval( $("#mycarousel").outerWidth() );
        width -= eval( $("#mycarousel li:first").outerWidth() );
        $("#mycarousel li:first").addClass("hideDiv");
    	$("#mycarousel").css("width", width - 2 + "px");
        
        isTabGenerated = false;
    }
}

// Method for binding click event for tabs
function bindTabs()
{    
	// Looping through all the photo tabs
	$(".photoTabs a").each(function()
	{
		if ($(this).html().indexOf("Search Results") == -1) {
			// Click event for the tabs
			$(this).click(function(event)
			{
				event.preventDefault();
				$(".photoTabs a").parent().parent().removeClass("tabs-selected");
				var activeClass = $(this).parent().attr("class")
				$(this).parent().parent().addClass("tabs-selected");
				//Set the Search Photo to default text 
				$("#txtSearchPhoto").val("Search Photos");
				thumbnailSet = 1;
				searchTab = false;
				removeTab();
				isTabGenerated = false;
				resetDateFilter();
			    
				categoryName = $(".photoTabs li.tabs-selected span:first span").html();
				categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();
	            
				displayPhotoGallery(categoryName, categoryCount, true);
				initialize();
				setSelectedThumbnail();
				//displayThumbnailNavigation();
				//displayDates(categoryName);
				setDefaultSearchText();
				//showWallpaperDownload();
				if(!($("#divWallpaper").hasClass("hideDiv")))
				{
					$("#divWallpaper").addClass("hideDiv");
				}
			});
		}
	});
	
	categoryName = $(".photoTabs li.tabs-selected span:first span").html();
	categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();
	    
	SetCategoryTitle(categoryName, categoryCount);    
}

// This method is called when we need to set the last photo as sected on thumbnails reload
function selectLastThumbnail()
{
    // If last image from the thumbnails is selected
    if(lastSelected = true)
    {
        $(".thumbnailContainer ul li.selected").removeClass("selected");     
	    $(".thumbnailContainer ul li:last").addClass("selected");  
	    setSelectedThumbnail();
    }
}

// Binding events
function rebindEvents()
{
    //Image switching photogallery
    // Click event of image thumbnails
    $("#thumbnailContainer a").click(function(event) 
    {
        event.preventDefault();
	    $(this).parents("li").parents("ul").find("li").removeClass("selected");
	    $(this).parent("li").addClass("selected");
	    setSelectedThumbnail();	
	    setNavigationLinksForPhotos();
    }); 
}
	
// Setting the page elements on the basis of thumbnail selected
function setSelectedThumbnail()
{
	// Setting the main content image
	var image = $(".thumbnailContainer ul li.selected a").attr("href");
	var largeImage = $(".thumbnailContainer ul li.selected a").attr("largeUrl");
	$("#previewImageContainer .previewImage").attr("src", image);
	$(".viewLargeContainer #viewLarge img").attr("src", largeImage);
	
	// Setting the caption below the main content image
	var changedCaption = $(".thumbnailContainer ul li.selected div.photoInfoThumbnail").html();
	$(".photoCaption").html(changedCaption);
	
	// Current photo number selected
	var photoNumber = $(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html();
	
	// Total photos in the category
	var totalCategoryPhotos = $(".totalNumberOfPhotos").html(); 
	if(totalCategoryPhotos == 1)
	{
	    $("#divPaginationContentArea .linkPrevioius").addClass("hideDiv");
	    $("#divPaginationContentArea .linkNext").addClass("hideDiv");
	    $("#divSlideshowPaginationContentArea .linkPrevioius").addClass("hideDiv");
	    $("#divSlideshowPaginationContentArea .linkNext").addClass("hideDiv");
	    $("#divSlideshowPaginationContentArea .linkPlayPause").addClass("hideDiv");
	} 
    else 
    {
	    $("#divPaginationContentArea .linkPrevioius").removeClass("hideDiv");
	    $("#divPaginationContentArea .linkNext").removeClass("hideDiv");
	    $("#divSlideshowPaginationContentArea .linkPrevioius").removeClass("hideDiv");
	    $("#divSlideshowPaginationContentArea .linkNext").removeClass("hideDiv");
	    $("#divSlideshowPaginationContentArea .linkPlayPause").removeClass("hideDiv");
    }
	// Pagination for main content image
	var photoPagingNumber = photoNumber +" of " + totalCategoryPhotos;
	$(".photoPagingNumber").html(photoPagingNumber);
	
	// First photo number in the thumbnail set
	var firstPhotoNumber = $(".thumbnailContainer ul li:first div.photoInfoThumbnail span.photoNumber").html();
	
	// Last photo number in the thumbnail set
	var lastPhotoNumber = $(".thumbnailContainer ul li:last div.photoInfoThumbnail span.photoNumber").html();
	
	// Pagination for thumbnails 
	var categoryPagingNumber = firstPhotoNumber +"-"+ lastPhotoNumber +" of " + totalCategoryPhotos;
	$(".categoryPagingNumber").html(categoryPagingNumber);	
	
	//Enable/Disable Navigation links
	if ( photoNumber == totalCategoryPhotos ){
		$("#divPaginationContentArea span.btnPrimary").addClass("spanNextDisabled");
	    $("#divPaginationContentArea .linkNext").addClass("linkPhotoNextDisable");
	    $("#divSlideshowPaginationContentArea .linkNext").addClass("linkPhotoNextDisable");
	    $("#divSlideshowPaginationContentArea .linkPlayPause").html("Start Over");
	} else {
		$("#divPaginationContentArea span.btnPrimary").removeClass("spanNextDisabled");
	    $("#divPaginationContentArea .linkNext").removeClass("linkPhotoNextDisable");
	    $("#divSlideshowPaginationContentArea .linkNext").removeClass("linkPhotoNextDisable");
	    $("#divSlideshowPaginationContentArea .linkPlayPause").removeClass("linkPhotoPlayPauseDisable");
	    
	    var playPause = $("#divSlideshowPaginationContentArea .linkPlayPause").html();
	    if (playPause.toUpperCase() == "START OVER" && _slideshowIsPaused) {
			$("#divSlideshowPaginationContentArea .linkPlayPause").html("Play");
	    }
	    else if (playPause.toUpperCase() == "START OVER") {
			$("#divSlideshowPaginationContentArea .linkPlayPause").html("Pause");
	    }
	}
	
	if ( photoNumber == 1 ){
		$("#divPaginationContentArea span.previousButton").addClass("spanPrevDisabled");
	    $("#divPaginationContentArea .linkPrevioius").addClass("linkPhotoPrevDisable");
	    $("#divSlideshowPaginationContentArea .linkPrevioius").addClass("linkPhotoPrevDisable");
	} else {
		$("#divPaginationContentArea span.previousButton").removeClass("spanPrevDisabled");
	    $("#divPaginationContentArea .linkPrevioius").removeClass("linkPhotoPrevDisable");
	    $("#divSlideshowPaginationContentArea .linkPrevioius").removeClass("linkPhotoPrevDisable");
	}
	
	if ( lastPhotoNumber == totalCategoryPhotos ){
	    $("#divPaginationThumbnailArea .linkNext").addClass("linkPhotoNextDisable");
		$("#divPaginationThumbnailArea a.linkNext").css("cursor", "default");
		$("#divPaginationThumbnailArea span.btnPrimary").addClass("spanPrevDisabled");
	} else {
	    $("#divPaginationThumbnailArea .linkNext").removeClass("linkPhotoNextDisable");
		$("#divPaginationThumbnailArea a.linkNext").css("cursor", "pointer");
		$("#divPaginationThumbnailArea span.btnPrimary").removeClass("spanPrevDisabled");
	}
	
	if ( firstPhotoNumber == 1 ){
		$("#divPaginationThumbnailArea span.btnPrimaryBack").addClass("spanPrevDisabled");
	    $("#divPaginationThumbnailArea .linkPrevioius").addClass("linkPhotoPrevDisable");
	} else {
		$("#divPaginationThumbnailArea span.btnPrimaryBack").removeClass("spanPrevDisabled");
	    $("#divPaginationThumbnailArea .linkPrevioius").removeClass("linkPhotoPrevDisable");
	}
	
	bindViewLarge();
	
	if( parseInt(totalCategoryPhotos) <= parseInt(totalPhotoImagesPerPage))
	{
		$("#divPaginationThumbnailArea .linkPrevioius").hide();
		$("#divPaginationThumbnailArea .linkNext").hide();
	}
	else
	{
		$("#divPaginationThumbnailArea .linkPrevioius").show();
		$("#divPaginationThumbnailArea .linkNext").show();
	}
	
}

// Method for calling the service to get the data for loading the thumbnails
function displayPhotoGallery(categoryName,categoryCount,newCategory)
{ 
	SetCategoryTitle(categoryName,categoryCount);  

    if(searchTab == false)
	{
	    searchTerm = "";
	}
	
	var makeAjaxCall = true;
	var date = getDateFilter();
	if(ajaxCallForFilteringByDate == true)	
	{
	    if(date == "")
	    {
	        makeAjaxCall = false;
	    }
	    else
	    {
	        thumbnailSet = 1;
	    }
	    ajaxCallForFilteringByDate = false;
	}	
	
	if(makeAjaxCall == true)
	{
		$(".thumbnailPagination, #thumbnailContainer .divThumbnailImages").hide();
        $(".noResultPlaceholder").hide();
		$(".loading").show();
		
	    // URL for service call
	    //var photoThumbnailURL= "/vailresorts/sites/breckenridge/WebServices/PhotoGalleryService.svc/LoadThumbnailsForPhotoGallery"
	    var photoThumbnailURL= "/vailresorts/sites/Global/WebServices/PhotoGalleryService.svc/LoadThumbnailsForPhotoGalleryIntoTemplate";
	    var photoGalleryId  = $.trim($(".photoGalleryId").html());
	    var totalNumberOfPhotos = $(".totalNumberOfPhotos").html();
	    var totalNumberOfPhotosInCategory = 1;
	    var numberOfThumbnailsPerPage = totalPhotoImagesPerPage;

	    // AJAX call for getting the data to be loaded in the thumbnails
	    $.ajax(
	    {
	        type: "POST",
	        url: photoThumbnailURL,
	        data: "{\"id\" : \"" + photoGalleryId + "\",\"category\" : \"" + categoryName + "\",\"thumbnailSet\" : \"" + thumbnailSet + "\",\"searchTerm\" : \"" + searchTerm + "\",\"date\" : \"" + date + "\",\"numberOfThumbnailsPerPage\" : \"" + numberOfThumbnailsPerPage + "\",\"totalNumberOfPhotosInCategory\" : \"" + totalNumberOfPhotosInCategory + "\"}",
	        //data: "{\"category\" : \""+categoryName+"\",\"thumbnailSet\" : \""+thumbnailSet+"\",\"searchTerm\" : \""+searchTerm+"\",\"date\" : \""+date+"\"}",
	        contentType: "application/json; charset=utf-8",
	        dataType: "json",
	        success: function(msg) {
	            //$('#thumbnailContainer .divThumbnailImages').html(msg.d);    

	            var res = eval(msg);
	            _photoResponseObject = eval(res.d);

	            resetIdx();
	            if (_photoResponseObject.length > 0) {
	                totalNumberOfPhotos = _photoResponseObject[0].TotalImages;
	            }
	            else {
	                totalNumberOfPhotos = 0;
	            }
	            //initialize();

	            $(".totalNumberOfPhotos").html(totalNumberOfPhotos);
	            if (parseInt(totalNumberOfPhotos) > parseInt(numberOfThumbnailsPerPage)) {
	                $(".divShowPagination").html("True");
	            }
	            else {
	                $(".divShowPagination").html("False");
	            }

	            $('#thumbnailContainer .divThumbnailImages').setTemplateURL('/vailresorts/sites/breckenridge/assets/template/PhotoGalleryThumbnails.htm', null, null);
	            $('#thumbnailContainer .divThumbnailImages').processTemplate(_photoResponseObject);


	            // turn the hover effect back on
	            $("ul.thumbnails li").hover(
					function() {
					    $(this).addClass('imgOver');
					},
						function() {
						    $(this).removeClass('imgOver');
						}
				);
	            fixDateCaptionSpacing();

				// If last image thumbnail is needed to be selected
	            if (lastSelected == true) {
	                selectLastThumbnail();
	                lastSelected = false;
	            }
	            setSelectedThumbnail();

	            if (_slideshowInProgress) {
	                slideSwitch(true);
	            }

	            displayThumbnailNavigation();
	            rebindEvents();
	            setPreviewImage();

	            if (newCategory) {
	                displayDates(categoryName);
	            }

	            // update counts if search results
	            if (categoryName == "Search Results") {
	                if (_photoResponseObject.length > 0) {
	                    categoryCount = _photoResponseObject[0].TotalImages;
	                }
	                else {
	                    categoryCount = 0;
	                }
	                $(".photoTabs li.tabs-selected span.categoryCount").html(categoryCount);
	                SetCategoryTitle(categoryName, categoryCount);
	            }
	        },
	        error: function(xhr, status, error) {
	            handlePhotoGalleryError(xhr, status, error);
	        }
	    });
	}
	
	
}

function fixDateCaptionSpacing() {
	var photosWithDates = 0;
	$("ul.thumbnails li").each(function()
	{
		if($(this).html().indexOf("/20") > -1) {
			photosWithDates++;
		}
	});
	if (photosWithDates > 0) {
		$("ul.thumbnails li").each(function()
		{
			if($(this).html().indexOf("/20") == -1) {
				$(this).append("&nbsp;");
			}
		});
	}
}

// Method for calling the service to get the data for loading the thumbnails
function displayDates(category)
{
	// Extracting the category name
	//var category = $(".photoTabs li.tabs-selected span:first span").html();
	
	/*
	// URL for service call
	var photoDatesURL= "/vailresorts/sites/breckenridge/WebServices/PhotoGalleryService.svc/GetDatesForFilter"

	// AJAX call for getting the data to be loaded in the thumbnails
	$.ajax(
	{
		type: "POST",
		url: photoDatesURL,
		data: "{\"category\" : \""+category+"\"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg) 
		{
			$('#divDates').html(msg.d);
		}
	});
	*/
	
	if (_photoResponseObject.length > 0) {
		if (_photoResponseObject[0].DateFilters != "") {
			var dateFilters = _photoResponseObject[0].DateFilters.split(",");
			for (d = 0; d < dateFilters.length; d++) {
				$("#divDates select")[0].options[$("#divDates select")[0].options.length] = new Option(dateFilters[d], dateFilters[d]);
			}
		}
	}
	
}

	
//View Large
//to show the div
function bindViewLarge()
{
    //View Large    

	if ( $('.viewLargeModal').length > 0 && $("body > .ui-dialog .viewLargeModal").length == 0 ){
		$('.viewLargeModal').eq(0).dialog({
			bgiframe: true,
			autoOpen: false,
			width: 700,
			modal: true,
			resizable: false,
			position: 'center',
			closeOnEscape: true
		});
	}
	
	$('.viewLargerLink').unbind("click").bind('click', function() {
		var objModal = $("body > .ui-dialog .viewLargeModal");
		//var imageBigger = $(".thumbnailContainer ul li.selected a").attr("href");
		var imageBigger = $(".thumbnailContainer ul li.selected a").attr("largeUrl");
		$("#viewLarge img", objModal).attr("src", imageBigger);
		try {
			objModal.dialog('open');
		} catch(e){}
	});
}

// Method for binding events for Slide Show
function bindSlideShowEvents()
{
	if ( $('.slideShowModal').length > 0 && $("body > .ui-dialog .slideShowModal").length == 0 ){
		$('.slideShowModal').eq(0).dialog({
			bgiframe: true,
			autoOpen: false,
			width: 700,
			modal: true,
			resizable: false,
			position: 'center',
			closeOnEscape: true
		});
	}
	
	$('.viewSlideShow').unbind("click").bind('click', function() {
		var objModal = $("body > .ui-dialog .slideShowModal");
        $("#control>li.play").addClass('current');		
		try {
			objModal.dialog('open');
		} catch(e){}
	});	
	
	
	/* OLD
	// To highlight the slide show button when user hovers over them
	$("#control>li" ).hover(
    function () 
	{
	    $(this).addClass('active');
	},
	function () 
	{
		$(this).removeClass('active');
	});	
	*/
	
    // Strats the slide show when user clicks on "View Slide Show"
    $(".viewSlideShow").click(function ()
    {
		_slideshowInProgress = true;
		
		$('.previewImageWrap').hide();
		
        // Emptying the div which contains images for slide show
        $('#slideshow').html("");
        
        // build the two placeholder images
        var img1 = document.createElement("img");
        img1.className = "active";
        $('#slideshow').append(img1);
        var img2 = document.createElement("img");
        $('#slideshow').append(img2);
        
        // Initializing slideshow counter to zero when slide show is started
        slideShowCounter = 0;
        
        // set the active image = the selected image
        var largeImg = $(".thumbnailContainer ul li.selected a").attr("largeUrl");
        $("#slideshow .active").attr("src", largeImg);
        
        var $captionDiv = $('#slideShowControl div.slideshowCaption');
        var $nextCaption = $(".thumbnailContainer ul li.selected div.photoInfoThumbnail").html();
        $captionDiv.html($nextCaption);
        
        // Setting this variable to true to make the ajax call work
        getMoreImages = true;


		// bind the controls
		// next button
		$("#divSlideshowPaginationContentArea a.linkNext").unbind("click").bind("click", function(event) 
		{
			event.preventDefault(); 
			
			// pause the timer while we do our thing
			clearInterval(slideShowTimer);			
			
			var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);    
			var lastPhotoNumber = parseInt($(".thumbnailContainer ul li:last div.photoInfoThumbnail span.photoNumber").html(),10);
			var currentPhotoNumber = parseInt($(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html(),10);
	        
			// If current photo number is equal to total number of photos then nothing should happen on click of the link
			if (currentPhotoNumber != totalPhotos)
			{
				// Last photo number is equal to current photo number then the thumbnails should be reloaded
				if((lastPhotoNumber == currentPhotoNumber))
				{
					thumbnailSet = thumbnailSet+1;
					categoryName = $(".searchBoxContent .categoryInfo .categoryTitle").html();
					categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();            
					displayPhotoGallery(categoryName, categoryCount);
				}
				// Else only the selection should change 
				else
				{ 
					$(".thumbnailContainer ul li.selected").next("li").addClass("selected");
					$(".thumbnailContainer ul li.selected").prev("li").removeClass("selected");     
					setSelectedThumbnail();
					slideSwitch(true);
				}
			}
	   });
	   
	   // previous button
	   $("#divSlideshowPaginationContentArea a.linkPrevioius").unbind("click").bind("click", function(event) 
		{
			event.preventDefault();
			
			// pause the timer while we do our thing
			clearInterval(slideShowTimer);	
			
			var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);    
			var firstPhoto = parseInt($(".thumbnailContainer ul li:first div.photoInfoThumbnail span.photoNumber").html(),10);
			var currentPhotoNumber = parseInt($(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html(),10);
	        
			// If user is on photo number one of the gallery then nothing should happen on click of the link
			if(currentPhotoNumber != 1)
			{
				// If first photo number is equal to current photo number then the thumbnails should be reloaded
				if(firstPhoto == currentPhotoNumber)
				{
					thumbnailSet = thumbnailSet-1;
					lastSelected = true;
					categoryName = $(".searchBoxContent .categoryInfo .categoryTitle").html();
					categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();            
					displayPhotoGallery(categoryName, categoryCount);
				}
				// Else only the selection should change 
				else
				{
					$(".thumbnailContainer ul li.selected").prev("li").addClass("selected");
					$(".thumbnailContainer ul li.selected").next("li").removeClass("selected");     
					setSelectedThumbnail();
					slideSwitch(true);
				}
			}
		});
		
		// play/pause button
		$("#divSlideshowPaginationContentArea a.linkPlayPause").html("Pause");
		_slideshowIsPaused = false;
		$("#divSlideshowPaginationContentArea a.linkPlayPause").unbind("click").bind("click", function(event) 
		{
			event.preventDefault();
			var playPause = $("#divSlideshowPaginationContentArea a.linkPlayPause");
			var currentText = (playPause.html());
			
			if (currentText.toUpperCase() == "PAUSE") {
				playPause.html("Play");
				clearInterval(slideShowTimer);
				_slideshowIsPaused = true;
			}
			else if (currentText.toUpperCase() == "PLAY") {
				playPause.html("Pause");
				_slideshowIsPaused = false;
				slideSwitch(true);				
			}	
			else {
				clearInterval(slideShowTimer);
				playPause.html("Pause");
				_slideshowIsPaused = false;
				thumbnailSet = 1;
				categoryName = $(".searchBoxContent .categoryInfo .categoryTitle").html();
				categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();            
				displayPhotoGallery(categoryName, categoryCount);
			}
			
		});


	    // Setting the interval for slide show
	    slideShowTimer = setInterval( "slideSwitch()", _slideshowTimeInMilliseconds );
	    
	    var objModal = $("body > .ui-dialog .slideShowModal");
	    try {			
			objModal.bind('dialogclose', function(event, ui) {
				clearInterval(slideShowTimer);
				_slideshowInProgress = false;		
				$('.previewImageWrap').show();		
			});
			objModal.dialog('open');
		} 
		catch(e){}
    
    
    /* OLD
        // Emptying the div which contains images for slide show
        $('#slideshow').html("");
        
        // Initializing slideshow counter to zero when slide show is started
        slideShowCounter = 0;
        
        // Setting this variable to true to make the ajax call work
        getMoreImages = true;

	    // Setting the interval for slide show
	    slideShow = setInterval( "slideSwitch()", 7000 );
	    
	    // Binding the click events for buttons for slide show
	    $("#control>li").bind("click", function()
	    {
            $("#control>li").removeClass('current');
            var currentId = $(this).attr("class");
            
            // If pause is pressed
            if (currentId == "pause active")
            {
                clearInterval(slideShow);
                $(this).addClass('current');
            }

            // If play is pressed
            if (currentId == "play active")
            {
                clearInterval(slideShow);
                slideShow = setInterval( "slideSwitch()", 7000 );
                $(this).addClass('current');
            }

            // If stop is pressed
            if (currentId == "stop active" )
            {
                clearInterval(slideShow);
                $("#slideshow>img").each(function()
                {
	                var activeClass = $(this).attr("class")
	                if (activeClass =="active")
	                {
		                $(this).removeClass("active");
		            }
                })
                $('#slideshow IMG:first').addClass("active");
                $(this).addClass('current');
            }

            // If forward is pressed
            if (currentId == "forward active" )
            {
                clearInterval(slideShow);
                var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);
                if((totalPhotos == $("#slideshow img").length) && $("#slideshow img:last").hasClass("active"))
                {
                    $("#slideshow>img.active").removeClass("active");
                    $("#slideshow img:first").addClass("active");
                }
                else
                {
                    $("#slideshow>img.active").next().addClass("active");
                    $("#slideshow>img.active").prev().removeClass("active");
                }
                slideShow = setInterval( "slideSwitch()", 7000 );
            }
            
            // If backward is pressed
            if (currentId == "backward active" )
            {
                clearInterval(slideShow);
                var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);
                if((totalPhotos == $("#slideshow img").length) && $("#slideshow img:first").hasClass("active"))
                {
                    $("#slideshow>img.active").removeClass("active");
                    $("#slideshow img:last").addClass("active");
                }
                else
                {
                    $("#slideshow>img.active").prev().addClass("active");
                    $("#slideshow>img.active").next().removeClass("active");
                }
                slideShow = setInterval( "slideSwitch()", 7000 );
            }
        })
        */
    });    
}

// Slide show control
function slideSwitch(fromCallback) 
{	    
	var $active = $('#slideshow IMG.active');
	var $captionDiv = $('#slideShowControl div.slideshowCaption');

    if ( $active.length == 0 ) $active = $('#slideshow IMG:last');

    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next() : $('#slideshow IMG:first');
    
    if (fromCallback) {
		var $nextImgSrc = $(".thumbnailContainer ul li.selected a").attr("largeUrl");
		var $nextCaption = $(".thumbnailContainer ul li.selected div.photoInfoThumbnail").html();
    }
    else {
		var $nextImgSrc = $(".thumbnailContainer ul li.selected").next("li").children("a").attr("largeUrl");
		var $nextCaption = $(".thumbnailContainer ul li.selected").next("li").children("div.photoInfoThumbnail").html();
	}
    
    if ($(".thumbnailContainer ul li.selected").next("li") && $nextImgSrc && $nextImgSrc.length > 0) {
		$next.attr("src", $nextImgSrc);
		  
        if (fromCallback) { }
        else {
			$(".thumbnailContainer ul li.selected").next("li").addClass("selected");
			$(".thumbnailContainer ul li.selected").prev("li").removeClass("selected");   
			setSelectedThumbnail();
		}
        $active.addClass('last-active');

		$next.css({opacity: 0.0})
			.addClass('active')
			.animate({opacity: 1.0}, 500, function() {
				$active.removeClass('active last-active');
				$captionDiv.html($nextCaption);
			});
			
		slideShowCounter = $(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html();
		
		if (fromCallback && !_slideshowIsPaused) {
			slideShowTimer = setInterval( "slideSwitch()", _slideshowTimeInMilliseconds );
		}
	}
	else {
		// ajax call to get more images
		clearInterval(slideShowTimer);
		
		var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);    
        var firstPhoto = parseInt($(".thumbnailContainer ul li:first div.photoInfoThumbnail span.photoNumber").html(),10);
        var currentPhotoNumber = parseInt($(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html(),10);
		var lastPhotoNumber = parseInt($(".thumbnailContainer ul li:last div.photoInfoThumbnail span.photoNumber").html(),10);
		
		if (currentPhotoNumber != totalPhotos)
        {
            // Last photo number is equal to current photo number then the thumbnails should be reloaded
            if((lastPhotoNumber == currentPhotoNumber))
            {
                thumbnailSet = thumbnailSet+1;
                categoryName = $(".searchBoxContent .categoryInfo .categoryTitle").html();
				categoryCount = $(".photoTabs li.tabs-selected span.categoryCount").html();            
				displayPhotoGallery(categoryName, categoryCount);
            }
        }
	}
	
	/* OLD
	
    // If this variable is true then get image using ajax call.
    if(getMoreImages)
    {
        displaySlideShowImage();
    }
        
    // Image with current active class
    var $active = $('#slideshow IMG.active');
     
    if ( $active.length == 0 )
    {
        $active = $('#slideshow IMG:last');
    }

    // Pulling the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
	    : $('#slideshow IMG:first');
                
    $active.addClass('last-active');           
    
    // Aplying class for showing current image
    $next.addClass('active');
    
    // Hiding the current and showing the next image
    $next.css({opacity: 0.0})				
	    .animate({opacity: 1.0}, 1000, function() {
		    $active.removeClass('active last-active');
	    });
    
    // Showing the description of the image
    var imgDescription = $active.attr("title");
    $(".descritpionImg").text(imgDescription)
    
    */
}


// Method for calling the service to get the data for loading the thumbnails
function displaySlideShowImage()
{
	// Extracting the category name	
	var category = $(".searchBoxContent .categoryInfo .categoryTitle").html();	
	
	var photoNumber;
	
	// If this method is called for the first time
	if(slideShowCounter == 0)
    {
        getMoreImages = true;
        slideShowCounter = $(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html(); 
        firstImageSlideShowNumber = slideShowCounter;
        $('#slideshow').html(""); 
        $(".descritpionImg").text("");
    }
      
    // Get More images if this variable is true
    if(getMoreImages)
    {
	    // URL for service call
	    var photoSlideShowURL= "/vailresorts/sites/breckenridge/WebServices/PhotoGalleryService.svc/GetImageForSlideShow";
	    
	    // Get More images if this variable is true
	    if(getMoreImages)
	    {
	        // AJAX call for getting the data to be loaded in the thumbnails
	        $.ajax(
	        {
	            type: "POST",
	            url: photoSlideShowURL,
	            data: "{\"category\" : \"" + category + "\",\"imageNumber\" : \"" + slideShowCounter + "\"}",
	            contentType: "application/json; charset=utf-8",
	            dataType: "json",
	            success: function(msg) {
	                $('#slideshow').append(msg.d);

	                // If slideShowCounter has reached the last image of the gallery, then it should start from the beginning
	                if (slideShowCounter == $(".totalNumberOfPhotos").html()) {
	                    slideShowCounter = 1;
	                }
	                else {
	                    slideShowCounter = parseInt(slideShowCounter) + parseInt("1", 10);
	                }

	                // If user has again reached the moment where current image is same as first image
	                // then no more ajax calls should be made to load images
	                if (firstImageSlideShowNumber != slideShowCounter) {
	                    getMoreImages = true;
	                }
	                else {
	                    getMoreImages = false;
	                }
	            },
	            error: function(xhr, status, error) {
	                handlePhotoGalleryError(xhr, status, error);
	            }
	        });
	    }
	}
}

// Setting/Resetting the no results box 
function setPreviewImage(){
	$(".loading").hide();
	 
    if ( $.trim( $(".totalNumberOfPhotos").html() ) == "0" ){
        //$("#previewImageContainer, #divPaginationContentArea, .decription, .categoryPagingNumber").hide();
        //$(".noResultPlaceholder").show();
        
        $("#divPaginationContentArea, .thumbnailPagination, .decription, .categoryPagingNumber, .viewLargerLink, .viewSlideShow, #thumbnailContainer .divThumbnailImages").hide();
        $(".noResultPlaceholder").show();
        
    } else {
        //$("#previewImageContainer, #divPaginationContentArea, .decription, .categoryPagingNumber").show();
        //$(".noResultPlaceholder").hide();
        
        $("#divPaginationContentArea, .thumbnailPagination, .decription, .categoryPagingNumber, .viewLargerLink, .viewSlideShow, #thumbnailContainer .divThumbnailImages").show();
        $(".noResultPlaceholder").hide();
    }
}

function setDefaultSearchText(){
    $("#txtSearchPhoto").unbind("focus").bind("focus", function(){
        if ( $(this).val() == "Search Photos" ){
            $(this).val("");
        }
    });
    $("#txtSearchPhoto").unbind("blur").bind("blur", function(){
        if ( $(this).val() == "" ){
            $(this).val("Search Photos");
        }
    });
}

//Hide or Display navigation buttons for Thumbnails 
function displayThumbnailNavigation()
{   
    if ($(".divShowPagination").html() == "False")
    {
        $('.thumbnailPagination').addClass("hideDiv");        
    }
    else if($(".divShowPagination").hasClass("hideDiv"))
    {
        $('.thumbnailPagination').removeClass("hideDiv");        
    }
}

//This function handles the navigation links (previous & next) on page.
function setNavigationLinksForPhotos()
{
    var totalPhotos = parseInt($(".totalNumberOfPhotos").html(),10);    
    var lastPhotoNumber = parseInt($(".thumbnailContainer ul li:last div.photoInfoThumbnail span.photoNumber").html(),10);
    var currentPhotoNumber = parseInt($(".thumbnailContainer ul li.selected div.photoInfoThumbnail span.photoNumber").html(),10);
  
    //*** Main Area ***//
    //If currentPhotoNumber is last then disable the next link for main page
    if(currentPhotoNumber==totalPhotos || totalPhotos==0)
    {
        $("#divPaginationContentArea span.btnPrimary").addClass("spanNextDisabled");
		$("#divPaginationContentArea a.linkNext").addClass("linkPhotoNextDisable");
        $("#divPaginationContentArea a.linkNext").css("cursor", "default");
    }
    else
    {
        $("#divPaginationContentArea span.btnPrimary").removeClass("spanNextDisabled");
		$("#divPaginationContentArea a.linkNext").removeClass("linkPhotoNextDisable");
        $("#divPaginationContentArea a.linkNext").css("cursor", "pointer");
    } 
    
    //If currentPhotoNumber is first then disable the previous link for main page
    if(currentPhotoNumber==1)
    {
       $("#divPaginationContentArea span.btnPrimaryBack").addClass("spanPrevDisabled");
	   $("#divPaginationContentArea a.linkPrevioius").addClass("linkPhotoPrevDisable");
       $("#divPaginationContentArea a.linkPrevioius").css("cursor", "default");
    }
    else
    {
        $("#divPaginationContentArea span.btnPrimaryBack").removeClass("spanPrevDisabled");
		$("#divPaginationContentArea a.linkPrevioius").removeClass("linkPhotoPrevDisable");
        $("#divPaginationContentArea a.linkPrevioius").css("cursor", "pointer");
    }
    
    //*** Thumbnail Area ***//
    var totalPages = getTotalPhotoPages();

    //If currentPhotoNumber is last then disable the next link for thumb area
    if((thumbnailSet == totalPages) || (totalPages==0))
    {
      // $("#divPaginationThumbnailArea a.linkNext").addClass("linkPhotoNextDisable");
       //$("#divPaginationThumbnailArea a.linkNext").css("cursor", "default");
    }
    else
    {
      // $("#divPaginationThumbnailArea a.linkNext").removeClass("linkPhotoNextDisable");
       //$("#divPaginationThumbnailArea a.linkNext").css("cursor", "pointer");
    } 
    
    //If currentPhotoNumber is first then disable the previous link for thumb area
    if(thumbnailSet==1)
    {
       $("#divPaginationThumbnailArea a.linkPrevioius").addClass("linkPhotoPrevDisable");
       $("#divPaginationThumbnailArea a.linkPrevioius").css("cursor", "default");
    }
    else
    {
       $("#divPaginationThumbnailArea a.linkPrevioius").removeClass("linkPhotoPrevDisable");
       $("#divPaginationThumbnailArea a.linkPrevioius").css("cursor", "pointer");
    }
}

// This function returns the total number of photo pages.
function getTotalPhotoPages()
{
    var totalPhotos=getTotalPhotos();
       
    if(totalPhotos==totalPhotoImagesPerPage)
    {
        return 0;
    }
        
    return parseInt(totalPhotos/totalPhotoImagesPerPage);
}

// This function returns the total number of photos.
function getTotalPhotos()
{
    var totalPhotos = parseInt($("div.totalNumberOfPhotos").html());
	if(isNaN(totalPhotos))
	{
	    totalPhotos=0;
	}
	
	return totalPhotos;
}
var idx = 0;
function checkSelected() {
	if (idx == 0) {
		return "selected";
	}
	else {
		return "";
	}
}
function incrementIdx() {
	idx++;
}
function resetIdx() {
	idx = 0;
}
