// 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 isNumberPagination=false;

var totalPhotoThumbnail=0;
var currentPhotoThumbnail=1;

var _photoResponseObject = new Array();
var _slideshowTimeInMilliseconds = 5000;
var _slideshowIsPaused = false;

// Total Photo Images to be displayed on a page. This variable will initialize in $(document).ready(function()
var totalPhotoImagesPerPage=0;

var liAdded=false;
var carouselSize=0;

// This method is executed on page load
$(document).ready(function() {

	
//    setTimeout( function() {
        $(".overlayDiv").bgiframe();
	    var carouselWidth = 0;
	    
	    $('ul#mycarousel li').each(function(){ carouselWidth += $(this).width() });
	    /* $('ul#mycarousel li').each(function(){ 
	        $(this).click(function(){
	          var idx = $("#mycarousel li").index( $(this).closest("li") );
		        var right_CarouselClip=$('.jcarousel-clip').position().left + $('.jcarousel-clip').width() ;
		        var right_li = $(this).closest("li").width() + $(this).closest("li").position().left + 10;
		        var left_CarouselClip=$('.jcarousel-clip').position().left;
		        var left_li = $(this).closest("li").position().left + 10;
			    if(right_CarouselClip<right_li){
			        tabCarousel.scroll(idx - 3);}
			    else if(left_CarouselClip<left_li){
			        tabCarousel.scroll(idx+1);}
	        });
	    carouselWidth += $(this).width() }); */
	             
	    //Get the Number of Thumbnails per page. 
	    totalPhotoImagesPerPage= $('.divThumbnailsPerPage').html();
	  
	    //Get the value from div that Control have NumberPagination or not 
    	isNumberPagination=$('.isNumberPagination').html();
    	
    	if(isNumberPagination=="false")
    	{
	        var imageWidth = $('.previewImage').width();
    		//alert(imageWidth);
    		//alert(carouselWidth);
	        if (carouselWidth > imageWidth) {
				//alert("turn on");
				$('.jcarousel-prev, .jcarousel-next').show();				
			}
	        else {
				//alert("hide");
				$('.jcarousel-prev, .jcarousel-next').hide();
			}			
	    }
	    else 
	    {
	        setNumberPagination();
	    }
    	
//    }, 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;
            displayPhotoGallery();
        }
    });

    // 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;
            displayPhotoGallery();
        }
   });

    // 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;
                displayPhotoGallery();
            }
            // Else only the selection should change 
            else
            { 
	            $(".thumbnailContainer ul li.selected").next("li").addClass("selected");
                $(".thumbnailContainer ul li.selected").prev("li").removeClass("selected");     
                setSelectedThumbnail();
            }
        }
   });

    // 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;
                displayPhotoGallery();
            }
            // Else only the selection should change 
            else
            {
                $(".thumbnailContainer ul li.selected").prev("li").addClass("selected");
                $(".thumbnailContainer ul li.selected").next("li").removeClass("selected");     
	            setSelectedThumbnail();
            }
        }
    });
   
    // 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();
	
	var carouselWidth = 0;
	$('ul#mycarousel li').each(function(){ carouselWidth += $(this).outerWidth() });
	if (carouselWidth > 695) $('.jcarousel-prev, .jcarousel-next').show();
	else $('.jcarousel-prev, .jcarousel-next').hide();
});

function handleGlobalPhotoGalleryError(xhr, status, error) {
    var errMsg = getErrorMessage(xhr, status, error);

    if ($("#slideShowControl".length != 0)) {
        if ($("#slideShowControl").is(":visible")) {
            $("#slideShowControl").html('<div class="largeGboxContainer"><span class="errorMessage">' + errMsg + '</span></div>');
        }
    }
    if ($("#pageCategory").length != 0) {
        $("#pageCategory").html('<div class="largeGboxContainer"><span class="errorMessage">' + errMsg + '</span></div>');
    }

    $(".loading").css("display", "none");
}


function ShowPagination(me, clickedItem)
{
    $(me).addClass("selected");
	if((currentPhotoThumbnail!=clickedItem) || (thumbnailSet!=clickedItem)) //after paginating to next page and clicking on '1' should take user back to page 1
    {
        thumbnailSet = clickedItem;
        currentPhotoThumbnail=clickedItem;
        displayPhotoGallery();
    }
    else 
    {
        return;
    }
}
function showWallpaperDownload()
{
    currentCategory = $(".photoTabs li.tabs-selected a").html();

    if(($(".viewWallpaperDownload").html() == "true") && ($(".wallpaperCategory").html() == currentCategory))
    {
        $("#divWallpaper").removeClass("hideDiv");
        bindWallpaperEvent();
    }
    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/Global/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) {
	        handleGlobalPhotoGalleryError(xhr, status, error);
	    }
	});
}

function bindDateEvent()
{
	$("#filterByDate").click(function(event){
		// MJS: reset the thumbnail set
		thumbnailSet = 1;
		$("#txtSearchPhoto").val("Search Photos");
        searchTab = false;
        ajaxCallForFilteringByDate = true;
        displayPhotoGallery();        
    });
}

// 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:contains(Search Results)").length <= 0)
				{
					var strings = "<li jcarouselindex=\"1\" class=\"first hideDiv jcarousel-item0 jcarousel-item jcarousel-item-horizontal jcarousel-item-1-horizontal\" style=\"\"><a href=\"javascript:void(0)\">Search Results</a></li>";
					$("#mycarousel").prepend(strings);
					carouselSize=tabCarousel.size();
					tabCarousel.size(carouselSize+1);
					liAdded=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;
    	            // remove "first" class from what is now the second tab
    	            $("#mycarousel li:nth-child(2)").removeClass("first");
	            }
	            
                $("#mycarousel li").removeClass("tabs-selected");
                $("#mycarousel li:first").addClass("tabs-selected");
	            
	            thumbnailSet = 1;
	            resetDateFilter();
		        displayPhotoGallery(true);
		        //initialize();
		        setSelectedThumbnail();
		        //displayDates();
            }
			
			 //Artifact artf1019233 : BC | Scroll bar not appearing with search results tab and last tab not displayed properly 
			 var carouselWidth = 0;
			 $('ul#mycarousel li').each(function(){ carouselWidth += $(this).outerWidth() });
			 if (carouselWidth > 695) $('.jcarousel-prev, .jcarousel-next').show();
			 else $('.jcarousel-prev, .jcarousel-next').hide();
			 setTimeout(function() {tabCarousel.reload();}, 1);
			 
		}
    });
}

// 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() );
		var left = eval( $("#mycarousel").position().left );
		if(left!=0){
			left +=eval( $("#mycarousel li:first").outerWidth())
		}
        $("#mycarousel li:first").addClass("hideDiv");
		
    	$("#mycarousel").css("width", width - 2 + "px");
		$("#mycarousel").css("left", left + "px");
        
        isTabGenerated = false;
        
        // add "first" class from what is now the second tab
    	$("#mycarousel li:nth-child(2)").addClass("first");
    }
}

// Method for binding click event for tabs
function bindTabs()
{
    // Looping through all the photo tabs
    $(".photoTabs a").each(function() {
        if ($(this).html() != "Search Results") {
            // Click event for the tabs
            $(this).click(function(event) {
                event.preventDefault();
                $(".photoTabs a").parent().removeClass("tabs-selected");
                var activeClass = $(this).parent().attr("class")
                $(this).parent().addClass("tabs-selected");
                //Set the Search Photo to default text 
                $("#txtSearchPhoto").val("Search Photos");
                thumbnailSet = 1;
                searchTab = false;
                //removeTab();
				if(liAdded==true){
					tabCarousel.size(carouselSize);
					$('#mycarousel li:contains(Search Results)').remove();
					liAdded=false;
					tabCarousel.reload();
				}
                isTabGenerated = false;
                resetDateFilter();
                displayPhotoGallery(true);
                //initialize();
                setSelectedThumbnail();
                //displayThumbnailNavigation();
                //displayDates();
                setDefaultSearchText();
                showWallpaperDownload();
            });
        }
    });
}

// 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();	
    }); 
	/*
	$("#thumbnailContainer ul.thumbnails li" ).hover(
		function () {
			$(this).addClass('selected');					
		},
		function () {
			$(this).removeClass('selected');
		}
	);
	*/
}
	
// 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", 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);
	$("#viewLargeCaption").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 .linkNext").addClass("linkPhotoNextDisable");
	    $("#divSlideshowPaginationContentArea .linkNext").addClass("linkPhotoNextDisable");
	    $("#divSlideshowPaginationContentArea .linkPlayPause").html("Start Over");
	} else {
	    $("#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 .linkPrevioius").addClass("linkPhotoPrevDisable");
	    $("#divSlideshowPaginationContentArea .linkPrevioius").addClass("linkPhotoPrevDisable");
	} else {
	    $("#divPaginationContentArea .linkPrevioius").removeClass("linkPhotoPrevDisable");
	    $("#divSlideshowPaginationContentArea .linkPrevioius").removeClass("linkPhotoPrevDisable");
	}
	
	if ( lastPhotoNumber == totalCategoryPhotos ){
	    $("#divPaginationThumbnailArea .linkNext").addClass("linkPhotoNextDisable");
	} else {
	    $("#divPaginationThumbnailArea .linkNext").removeClass("linkPhotoNextDisable");
	}
	
	if ( firstPhotoNumber == 1 ){
	    $("#divPaginationThumbnailArea .linkPrevioius").addClass("linkPhotoPrevDisable");
	} else {
	    $("#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(newCategory)
{
	// Extracting the category name
	var category = $(".photoTabs li.tabs-selected a").html();
		
	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)
	{
		//$("#divPaginationContentArea, .thumbnailPagination, .decription, .categoryPagingNumber, .viewLargerLink, .viewSlideShow, #thumbnailContainer .divThumbnailImages").hide();
		$(".thumbnailPagination, #thumbnailContainer .divThumbnailImages").hide();
        $(".noResultPlaceholder").hide();
		$(".loading").show();
	    // URL for service call
	    //var photoThumbnailURL= "/vailresorts/sites/Global/WebServices/PhotoGalleryService.svc/LoadThumbnailsForPhotoGallery"
	    var photoThumbnailURL= "/vailresorts/sites/Global/WebServices/PhotoGalleryService.svc/LoadThumbnailsForPhotoGalleryIntoTemplate";
	    var photoGalleryId  = $(".photoGalleryId").html();
	    var totalNumberOfPhotos = $(".totalNumberOfPhotos").html();
	    var totalNumberOfPhotosInCategory = 1;
	    var numberOfThumbnailsPerPage = $(".divThumbnailsPerPage").html();
	    
	    // AJAX call for getting the data to be loaded in the thumbnails
	    $.ajax(
	    {
	        type: "POST",
	        url: photoThumbnailURL,
	        // public string LoadThumbnailsForPhotoGalleryIntoTemplate(string id, string category, int thumbnailSet, string searchTerm, string date, int numberOfThumbnailsPerPage, int totalNumberOfPhotosInCategory)
	        data: "{\"id\" : \"" + photoGalleryId + "\",\"category\" : \"" + category + "\",\"thumbnailSet\" : \"" + thumbnailSet + "\",\"searchTerm\" : \"" + searchTerm + "\",\"date\" : \"" + date + "\",\"numberOfThumbnailsPerPage\" : \"" + numberOfThumbnailsPerPage + "\",\"totalNumberOfPhotosInCategory\" : \"" + totalNumberOfPhotosInCategory + "\"}",
	        contentType: "application/json; charset=utf-8",
	        dataType: "json",
	        success: function(msg) {
	            // replace this with jtemplate
	            //$('#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;
	            }
	            $(".totalNumberOfPhotos").html(totalNumberOfPhotos);
	            if (parseInt(totalNumberOfPhotos) > parseInt(numberOfThumbnailsPerPage)) {
	                $(".divShowPagination").html("True");
	            }
	            else {
	                $(".divShowPagination").html("False");
	            }

	            $('#thumbnailContainer .divThumbnailImages').setTemplateURL('/vailresorts/sites/global/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');
						}
				);

	            //initialize();
	            // 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();
	                currentPhotoThumbnail = 1;
	            }

	            if (isNumberPagination == "true") {
	                setTimeout(function() { setNumberPagination() }, 100)
	            }
	        },
	        error: function(xhr, status, error) {
	            handleGlobalPhotoGalleryError(xhr, status, error);
	        }
	    });
	}
}


// Method for calling the service to get the data for loading the thumbnails
function displayDates()
{
	// Extracting the category name
	var category = $(".photoTabs li.tabs-selected a").html();
	
	// bind date filters
	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: _largeModalWidth, 
			/* width:'auto', */
			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,
			width: _largeModalWidth,
			modal: true,
			resizable: false,
			position: 'center',
			closeOnEscape: true
		});
	}
	
	$('.viewSlideShow').unbind("click").bind('click', function() {
		var objModal = $("body > .ui-dialog .slideShowModal");
		
        try {
			
			objModal.dialog('open');
		} 
		catch(e){}
	});	
	
	
    // Strats the slide show when user clicks on "View Slide Show"
    $(".viewSlideShow").unbind("click").bind("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;
					displayPhotoGallery();
				}
				// 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;
					displayPhotoGallery();
				}
				// 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;
				displayPhotoGallery();
			}
			
		});


	    // 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){}
		
		setSelectedThumbnail();
	    
	    /* OLD
	    
	    // 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;
                displayPhotoGallery();
            }
        }
	}

    
        
        
/* 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'); //pn - artf959434 : Keystone | Photos | Issues with slide show
                
    $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');
	    });

	//pn - artf959434 : Keystone | Photos | Issues with slide show 
	if (!(getMoreImages))
	{
		// Showing the description of the image
		var imgDescription = $next.attr("title");
		$(".descritpionImg").text(imgDescription);
	}    
	
*/
    
}


// Method for calling the service to get the data for loading the thumbnails
function displaySlideShowImage()
{

/* OLD

	// Extracting the category name
	var category = $(".photoTabs li.tabs-selected a").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/Global/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);
					$(".descritpionImg").text($('#slideshow img.active:last').attr("title")); //pn					
					

                    // 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;
						//pn
						$('#slideshow IMG').removeClass('active');
						$('#slideshow IMG:last-child').addClass('active');
						setTimeout( function() { } , 7000 );
     
			        }
		        }
	        });
	    }
	}
*/

}

// Setting/Resetting the no results box 
function setPreviewImage(){
    $(".loading").hide();
        
    if ( $.trim( $(".totalNumberOfPhotos").html() ) == "0" ){
		/*var offset = $(".previewImageWrap").offset();
		var top = offset.top;
		var left = offset.left;
		var width = $(".previewImageWrap").outerWidth();
		var height = $(".previewImageWrap").outerHeight();
		$(".noResultPlaceholder").css({
			position: "absolute",
			top: "1px",
			left: "17px",
			width: width + "px",
			height: height + "px"
		});*/

        //$("#previewImageContainer, #divPaginationContentArea, .decription, .categoryPagingNumber").hide();
        $("#divPaginationContentArea, .thumbnailPagination, .decription, .categoryPagingNumber, .viewLargerLink, .viewSlideShow, #thumbnailContainer .divThumbnailImages").hide();
        $(".noResultPlaceholder").show();
    } else {
        //$("#previewImageContainer, #divPaginationContentArea, .decription, .categoryPagingNumber").show();
        $("#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(isNumberPagination=="false")
    {
        var showPagination = $(".divShowPagination").html();
        if ($(".divShowPagination").html() == "False")
        {
            $('.thumbnailPagination').addClass("hideDiv");
        }
        else if($(".divShowPagination").hasClass("hideDiv"))
        {
            $('.thumbnailPagination').removeClass("hideDiv");
        }
    }
}


function setNumberPagination()
{
     totalPhotoThumbnail=parseInt($('.totalNumberOfPhotos').html(),10);
	 var counter = parseInt(totalPhotoThumbnail/totalPhotoImagesPerPage,10);
     counter++;
	 var photoCounter;
	 var anchorTagCollection="";
     if(counter>1)
     {
	    anchorTagCollection="<ul>";
	    for(photoCounter=1;photoCounter<=counter;photoCounter++)
	    {  
	        if (photoCounter == currentPhotoThumbnail){
	            var className = " class='selectedPhotoThumbnail'";
	        } else {
	            var className = "";
	        }
	      anchorTagCollection += "<li><a href='javascript:void(0);' onclick='ShowPagination(this, " + photoCounter + ");'" + className + ">" + photoCounter + "</a></li>"; //  Creating Pagination in format of <ul><li><a  /*Links are here*/ ></a></li></ul>
	    }
	    anchorTagCollection+="</ul>";
	    //alert(anchorTagCollection);
	 }
	    $('#divPaginationThumbnailArea').html(anchorTagCollection);
	 
}

var idx = 0;
function checkSelected() {
	if (idx == 0) {
		return "selected";
	}
	else {
		return "";
	}
}
function incrementIdx() {
	idx++;
}
function resetIdx() {
	idx = 0;
}