/// <reference path="~/jquery-1.3.2-vsdoc.js />
///<remarks>
///====================================================================
/// Name: Lodging.cs
/// Javascript function for Loading details
/// Construction Date: 03/18/2009
/// Author: Naveen Kumar
/// Last Revision Date: 04/02/2009
/// Last Revision By:  
/// Last Revision Change: 
/// ====================================================================
/// Copyright (c) 2009 Vail Resorts, Inc.
/// ====================================================================
///</remarks>

var selectedNeighbours = '';
var selectedLodgingType = '';
var selectedAmenities = '';
var filterCriteria = '';
var compareValidatorFound = false;
var ratingEnd = 5;
var ratingStart = 0;
var returnDate = '';
var departDate = '';
var MaxAllowedRoom = 9;
var qsParm=new Array();
var qsParmUpper=new Array();
var lodgingURL='';
var deepLinkStartDate=new Date()+7;
var deepLinkEndDate=deepLinkStartDate+3;
var deepLinkAdult=2;
var deepLinkChild=0;
var deepLinkChildAges='';
var searchString = new Array();
var filterCriteriaString=new Array();
var filterLocation=new Array();
var filterRoomType=new Array();
var filterAmenitiesType=new Array();
var lastsearch=new Array();
var filterCriteriaFound=false;

$(document).ready(function() {
	$(".lodgingList tr:first td.firstColumn").addClass('topBackgoundImage');
	$(".lodgingList tr:last td.firstColumn").addClass('bottomBackgoundImage');	
    if ($("input[id$=hdnIsLodgingSaleable]").val() == 'True') {
        if ($(".modalWindow").length > 0) {
            $(".saveItemToTripFooter .footerBtnText").bind("click", function() {
                window.parent.closeModalDialog("#saveToTripDialog");
            });
        } else {
            attachDialogBoxLodgingDetails("ul.infoBoxes .datesTravelers .btnGrey", "click");
            attachDialogBox(".ddlKids select", "change");
            attachDialogBoxCalendar("td.LodgingCalendar", "click");

            saveToTripDialog();

            ratingFilter(0.5, 5);

            SelectedValue = $(".lodgingListFilter select").val();
            if (typeof (SelectedValue) != 'undefined') {
            
            // Artifact artf1020242 :Change by Naveen 
             var query = window.location.search.substring(1).toLowerCase();
             var queryUpper = window.location.search.substring(1);
             
            var parms = query.split('&');
            var paramsUpper=queryUpper.split('&');
           
            for (var i=0; i<parms.length; i++) 
            {
                var pos = parms[i].indexOf('=');
                if (pos > 0) 
                {
                    var key = parms[i].substring(0, pos);
                    var val = parms[i].substring(pos + 1);
                    var keyUpper = paramsUpper[i].substring(0, pos);
                    var valUpper = paramsUpper[i].substring(pos + 1);
                    qsParm[key] = val;
                    qsParmUpper[keyUpper] = valUpper;
                }
            }
            if (qsParm['search'] != undefined) {
            searchString=qsParm['search'].split(',');
            deepLinkStartDate=searchString[0];
            deepLinkEndDate=searchString[1];
            deepLinkAdult=searchString[2];
            deepLinkChild=searchString[3];
            if (deepLinkChild>1)
            {
                deepLinkChildAges=searchString[4];
            }
           if (qsParm['ratingstart'] != undefined) 
           {
                ratingStart=qsParm['ratingstart']
           }
           if (qsParm['ratingend'] != undefined) 
           {
                ratingEnd=qsParm['ratingend'];
           }
           
                dropdown = document.getElementById('ddlResultPerPage');
                // Artifact artf1020242 :Change by Naveen 
                if (qsParmUpper['lastsearch'] != undefined) 
                {
                    lastsearch=qsParmUpper['lastsearch'].split(',');
                    $(".lodgingListFilter select").val(lastsearch[0]);
                    SelectedValue = $(".lodgingListFilter select").val();
                    $("#ddlResultPerPage").val(lastsearch[3]); 
                    selectedIndex = dropdown.selectedIndex;
                    PageFrom = lastsearch[1];
                    PageTo = lastsearch[2];
                    ResultPerPage = lastsearch[3];
                   
                }
                else
                {
                    selectedIndex = dropdown.selectedIndex;
                    PageFrom = 0;
                    PageTo = 10;
                    ResultPerPage = 10;
                }
                  //Rating Slider Control
                 attachSliderControl();
                 if (qsParm['filtercriteria'] != undefined) 
                   {
                   filterCriteria=qsParm['filtercriteria'];
                   if (filterCriteria!='0|0')
                   {
                    filterCriteriaString=filterCriteria.split('|');
                   }
                   filterCriteriaFound=true;
                  
               }
               
                renderDeepLinkLodgingFilter();
                //RenderOutputForLodgingFilter();
                
               
                $("#starRatingFilter").slider("values", 0, ratingStart)
                $("#starRatingFilter").slider("values", 1, ratingEnd)
                lodgingURL=$(".emailVacationLink").attr("href");
            }
            else
            {
                dropdown = document.getElementById('ddlResultPerPage');
                selectedIndex = dropdown.selectedIndex;
                PageFrom = 0;
                PageTo = 10;
                ratingEnd = 5;
                ratingStart = 0;
                ResultPerPage = 10;
                 //Rating Slider Control
                 attachSliderControl();
                 lodgingURL=$(".emailVacationLink").attr("href");
                 
                 //Performance | 
                 renderLodgingFilter();
                 RenderOutput();
                }
            }

           

            //This method is used to render the control as json object
            //sorting by sort dropdown list selection 
            $('.lodgingListFilter select').change(function() {
            removeBubbles();//ps
                SelectedValue = $(".lodgingListFilter select").val();
                dropdown = document.getElementById('ddlResultPerPage');
                selectedIndex = dropdown.selectedIndex;
                PageTo = $("#ddlResultPerPage").val();
                ResultPerPage = $("#ddlResultPerPage").val();
                PageFrom = 0;
                RenderOutput();
            });

            //End Sort

            //Result Per page 
            $('#ddlResultPerPage').change(function() {
                SelectedValue = $(".lodgingListFilter select").val();
                PageTo = $("#ddlResultPerPage").val();
                ResultPerPage = $("#ddlResultPerPage").val();
                ratingEnd = 5;
                RenderOutput();
                removeBubbles();//ps
            });
        }
    }
    else {
        //removeBubbles();//ps
        $(".lodgingFilterContainer").addClass("hideDiv");
        $(".contentContainer").addClass("hideDiv");
        $(".tripleColumn").addClass("hideDiv");
            attachDialogBoxLodgingDetails("ul.infoBoxes .datesTravelers .btnGrey", "click");
            attachDialogBox(".ddlKids select", "change");
            attachDialogBoxCalendar("td.LodgingCalendar", "click");
            saveToTripDialog();
    }
     $('[id$=txtCheckInDate]').bind("change", function(){
        //artf1001884 fixed by adding ValidDate check.     
        if(ValidDate($('[id$=txtCheckInDate]').val()))
        {
            var NewDate=new Date( $('[id$=txtCheckInDate]').val());
            NewDate.setDate(NewDate.getDate()+1);
                   
            $('[id$=txtCheckOutDate]').datepicker('option', 'minDate', NewDate );
            $('[id$=txtCheckOutDate]').datepicker('setDate', NewDate);            
           
        }
    });
    $('[id$=txtCheckInDate]').datepicker("option", "onSelect", function(){
        //artf1001884 fixed by adding ValidDate check.
        if(ValidDate($('[id$=txtCheckInDate]').val()))
        {
            var NewDate=new Date( $('[id$=txtCheckInDate]').val());
            NewDate.setDate(NewDate.getDate()+1);
            
            $('[id$=txtCheckOutDate]').datepicker('option', 'minDate', NewDate );
            $('[id$=txtCheckOutDate]').datepicker('setDate', NewDate);     
        }

    });

    /* modify to fix - artf1019242 : K | Lodging | UI Issues on results page [SA] */
    if($('#keystone').length >0){    
            $('.singleColumn .lodgingFilterContainer').css('padding','0 10px');
          }
    /* end of fix - artf1019242 [SA] */


});     //document ready ends here

//End Sort

function closeModalDialog(sel){
    $(sel).dialog("close");
}


//This method will use to get the current page number and based on that render that page and disable the current link
function PopulatePageNumber(CurrentPageNumber) {
	dropdown = document.getElementById('ddlResultPerPage');
	selectedIndex = dropdown.selectedIndex;
	SelectedValue = $(".lodgingListFilter select").val();
	ResultPerPage = $("#ddlResultPerPage").val();
	PageFrom = ResultPerPage * (CurrentPageNumber - 1);
	PageTo = $("#ddlResultPerPage").val() * CurrentPageNumber;
	RenderOutput();
}



function SelectAllFilterStatusTab(classNames,checkedStatus,typeofFilter)
{
        removeBubbles();//ps
        var filterValue = '';
        selectedNeighbours = '';
	    selectedLodgingType = '';
	    selectedAmenities = '';
        var documentInput = document.getElementsByTagName("input");
	    for (var counter = 0; counter < documentInput.length; counter++) 
	    {
		var Comparision = documentInput[counter];
        if (Comparision.className == classNames) 
		{
			if (Comparision.disabled == false) 
			{
			
			    Comparision.checked = checkedStatus;
				
			}
			
			if (Comparision.checked == true) 
			{
				filterValue += Comparision.value + ','

			}
		}
		
		
		
		if (Comparision.className == 'chkBox chkboxNeighbours') 
		{
				if (Comparision.disabled == false && Comparision.checked == true) 
				{
				    selectedNeighbours += Comparision.value + ','
                }
				
		}
		else if (Comparision.className == 'chkBox checkboxLodgingType') 
		{
			if (Comparision.checked == true) {
				selectedLodgingType += Comparision.value + ','

			}
		}
		else if (Comparision.className == 'chkBox checkboxAmenities') {
			if (Comparision.checked == true) {
				selectedAmenities += Comparision.value + ','

			}
		}
		
	}
		
    if  (typeofFilter=='Neighbours')
    {
        var checkedall=document.getElementById('chkAll');
        checkedall.checked=checkedStatus;
        selectedNeighbours=filterValue;
    }
    else if (typeofFilter=='LodgingType')
    {
    selectedLodgingType=filterValue;
    }
    else if (typeofFilter=='Amenities')
    {
    selectedAmenities=filterValue;
    }


		
	selectedNeighbours = (selectedNeighbours == '') ? selectedNeighbours: selectedNeighbours.substring(0, (selectedNeighbours.length - 1)) + '|';
	selectedLodgingType = (selectedLodgingType == '') ? selectedLodgingType: selectedLodgingType.substring(0, (selectedLodgingType.length - 1)) + '|';
	selectedAmenities = (selectedAmenities == '') ? selectedAmenities: selectedAmenities.substring(0, (selectedAmenities.length - 1)) + '|';
	if (selectedNeighbours == '' || selectedLodgingType == '') 
	{
		filterCriteria = '0|0|';
	}
	else {
		filterCriteria = selectedNeighbours + selectedLodgingType + selectedAmenities;
	}
	
    var URLFilter=lodgingURL+"_separator_ratingStart="+ratingStart+"_separator_ratingEnd="+ratingEnd + "_separator_filterCriteria="+filterCriteria;
    $(".emailVacationLink").attr("href", URLFilter);
	RenderOutputForLodgingFilter();
	return false;

}
//This method is used the display the results based on result per page dropdown selection
function CheckedAllLocationTab(chkboxid) {
removeBubbles(); //ps
//fix artf965578 - By Naveen on 13-07-2009
$(".lodgingTableContainer [id$=errorMessage]").hide();
	selectedNeighbours = '';
	selectedLodgingType = '';
	selectedAmenities = '';
	var documentInput = document.getElementsByTagName("input");
	for (var counter = 0; counter < documentInput.length; counter++) {
		var Comparision = documentInput[counter];
		if (Comparision.className == 'chkBox chkboxNeighbours') {
			if (chkboxid.checked == true) {
				if (Comparision.disabled == false) {
					Comparision.checked = true;
				}
			}
			else {
				Comparision.checked = false;
			}
			if (Comparision.checked == true) {
				selectedNeighbours += Comparision.value + ','

			}
		}
		else if (Comparision.className == 'chkBox checkboxLodgingType') {
			if (Comparision.checked == true) {
				selectedLodgingType += Comparision.value + ','

			}
		}
		else if (Comparision.className == 'chkBox checkboxAmenities') {
			if (Comparision.checked == true) {
				selectedAmenities += Comparision.value + ','

			}
		}
	}

	selectedNeighbours = (selectedNeighbours == '') ? selectedNeighbours: selectedNeighbours.substring(0, (selectedNeighbours.length - 1)) + '|';
	selectedLodgingType = (selectedLodgingType == '') ? selectedLodgingType: selectedLodgingType.substring(0, (selectedLodgingType.length - 1)) + '|';
	selectedAmenities = (selectedAmenities == '') ? selectedAmenities: selectedAmenities.substring(0, (selectedAmenities.length - 1)) + '|';
	if (selectedNeighbours == '' || selectedLodgingType == '') 
	{
		filterCriteria = '0|0|';
	}
	else {
		filterCriteria = selectedNeighbours + selectedLodgingType + selectedAmenities;
	}
	
	 
    var URLFilter=lodgingURL+"_separator_ratingStart="+ratingStart+"_separator_ratingEnd="+ratingEnd + "_separator_filterCriteria="+filterCriteria;
    $(".emailVacationLink").attr("href", URLFilter);
	RenderOutputForLodgingFilter();
}

//This method is used the display the results based on result per page dropdown selection
function ChangePageNumber() {
    removeBubbles();//ps
	dropdown = document.getElementById('ddlResultPerPage');
	selectedIndex = dropdown.selectedIndex;
	var CurrentPage = dropdown.options[selectedIndex].value;
	SelectedValue = $(".lodgingListFilter select").val();
	PageTo = CurrentPage;
	ResultPerPage = CurrentPage;
	PageFrom = 0;
	RenderOutput();

}
//Common function to remove the amenities filter
function removeBubbles()
{
    $('.hoverBubble').remove(); //ps
    $(".hoverBubMiddle ul").remove();//ps
    $("#divHoverBubble .amenitiesList").removeClass("hideDiv");//ps
}

function handlePnB_Lodging_Error(xhr, status, error)
{
    var errMsg = getErrorMessage(xhr,status,error);
    $("#ajaxContentContainer").html('<div class="lodgingTableContainer"><span class="errorMessage">' + errMsg + '</span></div>');

    if ($(".loadingPlaceholder").length > 0) {
        $(".loadingPlaceholder").hide();
    }
}

//Common function to load the control through web web service
function RenderOutput() {
	$("#ajaxContentContainer").showLoading({loadingStr: "Please wait a moment while we search for your results", autoFocus: false});
	$.ajax({
		type: "POST",
		url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetLodgingDetails",
		data: "{\"sortType\" : \"" + SelectedValue + "\",\"recordFrom\" : \"" + PageFrom + "\",\"recordTo\" : \"" + PageTo + "\",\"resultPerPage\" : \"" + ResultPerPage + "\",\"filterCriteria\" : \"" + filterCriteria + "\",\"ratingStart\" : \"" + ratingStart + "\",\"ratingEnd\" : \"" + ratingEnd + "\"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		 success: function(msg) {setTimeout( function() {
			$('#ajaxContentContainer').removeClass('loading');
			$('#ajaxContentContainer').html(msg.d);
			$('.paginationContainer').prepend("<div class='boxPaginationLeft'></div>");
			$('.paginationContainer').append("<div class='boxPaginationRight'></div>");
            if ($('.hoverBubble').length >=1 )//ps
			{
                addRemoveHoverBubble();//ps
			}			
			$('#ddlResultPerPage').attr('selectedIndex', selectedIndex);
        	$(".lodgingList tr:first td.firstColumn").addClass('topBackgoundImage');
	        $(".lodgingList tr:last td.firstColumn").addClass('bottomBackgoundImage');
	        $(".lodgingList tr:last td.firstColumn").css('borderBottom', 'none');
	        $("table.lodgingList tr:last").css('background','none');
	        $('.amenities').unbind('click').bind('click',function(){
                loadAmenities($(this).attr('id'));
            })
	        //Omnitue Taging
	        BindLodgingData();
	        FirstTimeAllCHKSelection();
			hideInterstitial();
	        },100 );
		},
		error: function(xhr, status, error) {
			handlePnB_Lodging_Error(xhr, status, error);
	    }
	});
}

//This method is used to display the Amenitites list on bubble hover 

function loadAmenities(linkAmenities) {
    $("#divHoverBubble").appendTo("body");
    
    var obj = $('#'+linkAmenities); /*added to fix - artf1002573 [SA]*/
    var linkAmenities = document.getElementById(linkAmenities);
    var pos = $(linkAmenities).offset();
			$("#divHoverBubble").css("top" , pos.top +20+ "px");
			//if ($.browser.msie && $.browser.version.substr(0,1)<7){
			  //  $("#divHoverBubble").css("left" , pos.left-140+ "px");
			    //}else{
			    $("#divHoverBubble").css("left" , pos.left + "px");
			 /*added to fix - artf1002573 [SA]*/
			  if(obj.parents(".lodgingListView").length > 0){               
			    $("#divHoverBubble .hoverBubMiddle").css("width","112px");  
			    $("#divHoverBubble .hoverBubTop").css("width","104px"); 
			    $("#divHoverBubble .hoverBubBottom").css("width","104px");  
			    }
			  /*end of fix - artf1002573 [SA]*/
			    //}
			
			$("#divHoverBubble").hide().slideDown(350);
				
			$(".hoverBubMiddle ul").remove();
			$(linkAmenities).next("ul").clone().appendTo('.hoverBubMiddle');
			$("#divHoverBubble .amenitiesList").addClass("lodginglistAmenitiesIcon");
			$("#divHoverBubble .amenitiesList").removeClass("hideDiv");			
			//$("#divHoverBubble .amenitiesList").css("background-image", "url(/VailResorts/sites/PlanningAndBooking/assets/img/logdinglistbubbleBg.png);");     
			//$("#divHoverBubble .amenitiesList").css("background-position", "right top;");     
			$(document).click(function(e){
				if (!e) var e = window.event;
				if (e.target) targ = e.target;
				else if (e.srcElement) targ = e.srcElement;
				if (targ.nodeType == 3) // defeat Safari bug
					targ = targ.parentNode;
					
				if ( !$(targ).hasClass("amenities") )
					$("#divHoverBubble").hide();
			});
			
	
}





//Update the unit price based on unit available
function UpdatePrice(price, dropdown, pricevalue) {
	var price = document.getElementById(price);
	var dropdown = document.getElementById(dropdown);
	selectedIndex = dropdown.selectedIndex;
	selectedValue = dropdown.options[selectedIndex].value
	$(price).html("$" +  Math.round((selectedValue * pricevalue)*100)/100 + "(avg per night)");
	return false;

}

//This method is used to redirect to any url
function redirectToURL(dropID,lodgingFilterRedirecturl) {
    var value = $("#" + dropID).val();
	var Url = lodgingFilterRedirecturl + value;
	document.location.href = Url;
}

function FillConditionalFilterForDeepLink(location,roomtype) 
{
    var locationCounter=0;
    var roomTypeCounter=0;
    var unCheckedLocationCounter=0;
    var checkAll=document.getElementById('chkAll');
    if (location.length>0)
    {
        location=location+',0';
        roomtype=roomtype+',0'
        selectedNeighbours = '';
	    selectedLodgingType = '';
	    selectedAmenities = '';
	    filterLocation=location.split(',');
	    filterRoomType=roomtype.split(',');
	    var documentInput = document.getElementsByTagName("input");
	    
	    for (var counter = 0; counter < documentInput.length; counter++) {
		var Comparision = documentInput[counter];
		if (Comparision.className == 'chkBox chkboxNeighbours') 
		{
		   if (filterLocation[locationCounter]!= undefined)
		   {
		       if (Comparision.value==filterLocation[locationCounter])
		       {
		        locationCounter++;
    		        Comparision.checked=true;
		       }
		       else
		       {
		           
		            Comparision.checked=false;
		       
		       }
			    if (Comparision.checked == true) 
			    {
				    selectedNeighbours += Comparision.value + ','

			    }
			    else
			    {
			        unCheckedLocationCounter=unCheckedLocationCounter+1;
			    }
		    }
		}
		    else if (Comparision.className == 'chkBox checkboxLodgingType') 
		    {
		        if (filterRoomType[roomTypeCounter]!= undefined)
		        {
		           if (Comparision.value==filterRoomType[roomTypeCounter])
		           { 
		                roomTypeCounter++;
    		            Comparision.checked=true;
		           }
		           else
		           {
		                Comparision.checked=false;
		           }
		        }
			    if (Comparision.checked == true) 
			    {
				    selectedLodgingType += Comparision.value + ','

			    }
		    }
		
	}
	
    }
    
     if (unCheckedLocationCounter>0)
     {
      checkAll.checked=false;

      }
    else
    {
        checkAll.checked=true;
    }
	selectedNeighbours = (selectedNeighbours == '') ? selectedNeighbours: selectedNeighbours.substring(0, (selectedNeighbours.length - 1)) + '|';
	selectedLodgingType = (selectedLodgingType == '') ? selectedLodgingType: selectedLodgingType.substring(0, (selectedLodgingType.length - 1)) + '|';
	selectedAmenities = (selectedAmenities == '') ? selectedAmenities: selectedAmenities.substring(0, (selectedAmenities.length - 1)) + '|';
	if (selectedNeighbours == '' || selectedLodgingType == '') {
		filterCriteria = '0|0|';
	}
	else {
		filterCriteria = selectedNeighbours + selectedLodgingType + selectedAmenities;
	}
	
}
//This method is used to find the selected value of list filters of lodging
function FillConditionalFilter() {
removeBubbles();//ps
//fix artf965578 - By Naveen on 13-07-2009
$(".lodgingTableContainer [id$=errorMessage]").hide();
var checkAll=document.getElementById('chkAll');
	selectedNeighbours = '';
	selectedLodgingType = '';
	selectedAmenities = '';
	var unCheckedLocationCounter=0;
	var documentInput = document.getElementsByTagName("input");
	for (var counter = 0; counter < documentInput.length; counter++) {
		var Comparision = documentInput[counter];
		if (Comparision.className == 'chkBox chkboxNeighbours') {
			if (Comparision.checked == true) {
				selectedNeighbours += Comparision.value + ','

			}
			else
			{
			    unCheckedLocationCounter=unCheckedLocationCounter+1;
			}
		}
		else if (Comparision.className == 'chkBox checkboxLodgingType') {
			if (Comparision.checked == true) {
				selectedLodgingType += Comparision.value + ','

			}
		}
		else if (Comparision.className == 'chkBox checkboxAmenities') {
			if (Comparision.checked == true) {
				selectedAmenities += Comparision.value + ','
			}
		}
	}
   
    if (unCheckedLocationCounter>0)
    {
        checkAll.checked=false;

    }
    else
    {
    checkAll.checked=true;
    }
	selectedNeighbours = (selectedNeighbours == '') ? selectedNeighbours: selectedNeighbours.substring(0, (selectedNeighbours.length - 1)) + '|';
	selectedLodgingType = (selectedLodgingType == '') ? selectedLodgingType: selectedLodgingType.substring(0, (selectedLodgingType.length - 1)) + '|';
	selectedAmenities = (selectedAmenities == '') ? selectedAmenities: selectedAmenities.substring(0, (selectedAmenities.length - 1)) + '|';
	if (selectedNeighbours == '' || selectedLodgingType == '') {
		filterCriteria = '0|0|';
	}
	else {
		filterCriteria = selectedNeighbours + selectedLodgingType + selectedAmenities;
	}
	
	 
    var URLFilter=lodgingURL+"_separator_ratingStart="+ratingStart+"_separator_ratingEnd="+ratingEnd + "_separator_filterCriteria="+filterCriteria;
    $(".emailVacationLink").attr("href", URLFilter);
	RenderOutputForLodgingFilter();

}

//Function to disable and enable the checkboxes, if checkbox selection is more than 3    
function ValidateComparisonCheckBox(chkbox, selectedChkboxText, unselectedChkboxText) {

	var selected = '';
	var foundSelectedValue = false;
	var TotalSelected;
	var maxCounter = 0;

	//If Check box is Selected then the Checkbox text should change to given value with Underline.
	if (chkbox.checked == true) {
		$(chkbox).next("label").html("<u>" + selectedChkboxText + "</u>");
	}
	else // Otherwise, restore it to the orignal text
	{
		$(chkbox).next("label").html(unselectedChkboxText);
	}

	var documentInput = document.getElementsByTagName("input");

	for (var counter = 0; counter < documentInput.length; counter++) {
		var Comparision = documentInput[counter];

		if (Comparision.id == 'chkboxCompare') {
			if (Comparision.checked == true) {
				selected += Comparision.value + ','
				foundSelectedValue = true;
				maxCounter = maxCounter + 1;
			}
		}
	}
	if (maxCounter > 2) {
		for (var counter = 0; counter < documentInput.length; counter++) {
			var Comparision = documentInput[counter];
			if (Comparision.id == 'chkboxCompare') {
				if (Comparision.checked == false) {
					//Comparision.disabled = true;
				}

			}
		}
	}
	else {
		for (var counter = 0; counter < documentInput.length; counter++) {
			var Comparision = documentInput[counter];
			if (Comparision.id == 'chkboxCompare') {
				if (Comparision.checked == false) {
					//Comparision.disabled = false;
				}

			}
		}
	}

}

// sorts by star rating using slider
function ratingFilter(minStar, maxStar) {
	var arrRows = $(".lodgingList tr");
	arrRows.find(".prodDescription h4 span:first").each(function(i) {
		if ($(this).html() >= minStar && $(this).html() <= maxStar) {
			$(arrRows[i]).show();
		} else {
			$(arrRows[i]).hide();
		}
	});
}

// This function displays as many child age drop down as required by the customer.
function BindKidsAge() {

	var loopCount = 0;
	var innerLoop = 0;
	var dropDowns = document.getElementsByTagName("li");
	var selector = $(".ddlKids select").val();
	var selector = Number(selector);
	$("#addDropBox li").addClass("adultsKids hideDiv");
	$("#addDropBox li:lt(" + selector + ")").removeClass("hideDiv");

}


function attachDialogBoxLodgingDetails(selector, event) {

	if ($("#ddlKids").length > 0) {
		$("#ddlKids select").unbind("change", BindKidsAge);
		$("#ddlKids select").bind("change", BindKidsAge);
	}

	$(selector).unbind(event);
	$(selector).bind(event,
	function(e) {
	        //e.preventDefault();
		// BindKidsAge();
		if ($('div#editDates').parents(".ui-dialog").length > 0) {} else {
			$('div#editDates').dialog("destroy");
			$('div#editDates').dialog({
				width: 700,
				bgiframe: true,
				autoOpen: false,
				modal: true,
				resizable: false,
				position: 'center',
				closeOnEscape: true
			});
		}
		    $("#editDates input").datepicker('disable');
		    $('div#editDates').dialog("open");
		    $("#editDates").removeClass("hideDiv");
		    $("#editDates input").datepicker('enable');
	});
}

function attachDialogBox(selector, event) {

	if ($("#ddlKids").length > 0) {
		$("#ddlKids select").unbind("change", BindKidsAge);
		$("#ddlKids select").bind("change", BindKidsAge);
	}

	$(selector).unbind(event);
	$(selector).bind(event,
	function() {
		// BindKidsAge();
		if ($('div#editDates').parents(".ui-dialog").length > 0) {} else {
			$('div#editDates').dialog("destroy");
			$('div#editDates').dialog({
				width: 700,
				bgiframe: true,
				autoOpen: false,
				modal: true,
				resizable: false,
				position: 'center',
				closeOnEscape: true
			});
		}

	    var ddlKidsSelectedValue=$(".ddlKids select").val();
		if (ddlKidsSelectedValue!=null && ddlKidsSelectedValue>0)
		{
		    $('div#editDates').dialog("open");
		    $("#editDates").removeClass("hideDiv");
		}

	});
}

//Method to open the popup for calendar
function attachDialogBoxCalendar(selector, event) {
	$(selector).find('a').each(function(){
        if( !$(this).hasClass('disabledText') )
        {
            $(this).unbind(event).bind(event, function() {
            if ( $('div#lodgingCalendar').length > 0 && $('body > .ui-dialog div[id=lodgingCalendar]').length == 0 ){
                $('div#lodgingCalendar').eq(0).dialog({
				    width: 700,
				    bgiframe: true,
				    autoOpen: false,
				    modal: true,
				    resizable: false,
				    position: 'center',
				    closeOnEscape: true
			    });
		    }
    		
		    var objDialog = $('body > .ui-dialog div[id=lodgingCalendar]');
            try {
                objDialog.dialog("open");
            } catch(e){}
		    objDialog.removeClass("hideDiv");
	    });
	        
       }
    });
}

//validate the require field
function ValidateSearchCriteria(val, args) {
	var result = true;
	for (i = 0; i < Page_Validators.length; i++) {
		if (Page_Validators[i].isvalid == false) {
			var cntrlID = Page_Validators[i].controltovalidate;
			$("#" + cntrlID).parents("li").eq(0).find("label").addClass("required");
			result = false;
		}
	}
	returnDate = document.getElementById(txtCheckOutDate).value;
	departDate = document.getElementById(txtCheckInDate).value;
	compareValidatorFound = (returnDate.length < 1 || departDate.length < 1) ? false: true;
	if (result == false && compareValidatorFound == false) {
		args.IsValid = false;
		$(".summary").addClass("required");
		$(".summary").html("").show();
		$("<ul></ul>").appendTo(".summary");
		setTimeout(function() {
			$("<li>Please fill all required fields.</li>").appendTo(".summary ul");
		},
		1);
		return (false);
	}
	else {
		return (args.IsValid = true);
	}
}

//Validate the traveller details like departure date should be less then return date.
function ValidateTravellerDetails(returnDate, departDate, todaysDt, args) {
	var result = true;
	var message = '';
	$(".checkOut").find("label").removeClass("required");
	$(".checkIn").find("label").removeClass("required");
	$(".filterTripDetail").find("label").removeClass("required");
	if (compareDates(returnDate, departDate) > 0) {
		$(".checkOut").find("label").addClass("required");
		message = "CheckOut Date should greater than CheckIn Date.";
		args.IsValid = false;
		compareValidatorFound = true;
		result = false;
	}

	if (compareDates(departDate, todaysDt) > 0) {
		$(".checkIn").find("label").addClass("required");
		message = "CheckIn Date should greater than Today's Date.";
		args.IsValid = false;
		compareValidatorFound = true;
		result = false;
	}
	if (result == false) {
		args.IsValid = false;
		$(".summary").addClass("required");
		$(".summary").html("").show();
		$("<ul></ul>").appendTo(".summary");

		setTimeout(function() {
			$("<li>" + message + "</li>").appendTo(".summary ul");
		},
		2);

		return (false);
	}
	return false;

}


//Update the offer details date
function UpdateLodgingOfferDetailsDate()
{

	var errorMessage = document.getElementById('errorMessagePopup');
	errorMessage.innerHTML = '';
	$(".checkIn").find("label").removeClass("required");
	$(".checkOut").find("label").removeClass("required");
	var adultCount = $(".adults select").val();
	var checkInDate =$(".checkIn input").val();
	var checkOutDate = $(".checkOut input") .val();
	returnDate = $(".checkIn input") .val();
	departDate = $(".checkOut input") .val();
    var pageUrl=document.getElementById('pageName').innerHTML;
	var offerCode=document.getElementById('offerName').innerHTML;
	var todaysDt = new Date();
	if (compareDates(checkOutDate, checkInDate) > 0) {
		$(".checkOut").find("label").addClass("required");
		errorMessage.innerHTML = " CheckOut Date should greater than CheckIn Date.";

	}

	if (compareDates(checkInDate, todaysDt) > 0) {
		$(".checkIn").find("label").addClass("required");
		errorMessage.innerHTML = "CheckIn Date should greater than Today's Date.";
	}
	if (checkInDate == '') {
		$(".checkIn").find("label").addClass("required");
		errorMessage.innerHTML = "Please fill all required fields.";
	}
	if (checkOutDate == '') {

		$(".checkOut").find("label").addClass("required");
		errorMessage.innerHTML = "Please fill all required fields.";
	}    
	if (errorMessage.innerHTML.length < 1) {
		$("#editDates").removeClass("hideDiv");
		$('div#editDates').dialog("close");
	    BindKidsAge();
		var childAge = '';
		var loopCount = 0;
		var innerLoop = 0;
		var dropDowns = document.getElementsByTagName("li");
		var selector =$(".ddlKids select").val();
		var selector = Number(selector);
		for (loopCount = 0; loopCount < dropDowns.length; loopCount++) 
		{
			if (dropDowns[loopCount].id.indexOf("childAgeRepeater") > -1) {
				for (innerLoop = loopCount; innerLoop < (loopCount + selector); innerLoop++) {

					if (document.getElementById(dropDowns[innerLoop].id).className == 'adultsKids') {
						var dropdownIndex = document.getElementById(dropDowns[innerLoop].id).id;
						childAge += $("#" + dropdownIndex + " select").val() + "|";
					}
				}
				break;
			}
		}        
		var pageToRedirect=pageUrl+"?ProductID="+offerCode + "&Search="+checkInDate+","+checkOutDate+","+adultCount+","+selector+","+childAge;
		document.location.href = pageToRedirect;
	}
		
	
}
//Update lodging details date
function UpdateLodgingDetailsDate() {
	var errorMessage = document.getElementById('errorMessagePopup');
	errorMessage.innerHTML = '';
	$(".checkIn").find("label").removeClass("required");
	$(".checkOut").find("label").removeClass("required");
	var checkInDate = document.getElementById('columnRight_ctl00_LodgingDetail_txtCheckInDate').value;
	var checkOutDate = document.getElementById('columnRight_ctl00_LodgingDetail_txtCheckOutDate').value;
	returnDate = document.getElementById('columnRight_ctl00_LodgingDetail_txtCheckOutDate').value;
	departDate = document.getElementById('columnRight_ctl00_LodgingDetail_txtCheckInDate').value;	
	var todaysDt = new Date();
	//artf997131 Fixed
	todaysDt.setDate(todaysDt.getDate() + 1); 
if ((checkInDate == '') || (checkOutDate == ''))
	{		
	    if ((checkInDate == '') && (checkOutDate == ''))
	    {
	        errorMessage.innerHTML = "Please complete the required fields:<br/>Check In.<br/>Check Out.";
	    }
	    else
	    {
	        if (checkInDate == '') {
		        errorMessage.innerHTML = "Please complete the required fields:<br/>Check In.";
	        }

	        if (checkOutDate == '') {			
		        errorMessage.innerHTML = "Please complete the required fields:<br/>Check Out.";
	        }
	    }	
	}
else
    { 
        if(!ValidDate(checkInDate) || !ValidDate(checkOutDate))
        {
            if(!ValidDate(checkInDate) && !ValidDate(checkOutDate))
            {
                errorMessage.innerHTML = "You have entered the following invalid data:<br/>CheckIn - CheckIn Date should be in MM/DD/YYYY format.<br/>CheckOut - CheckOut Date should be in MM/DD/YYYY format.<br/>Please re-enter your data.";
            }
            else 
            {
                if(!ValidDate(checkInDate))
                {
                    errorMessage.innerHTML = "You have entered the following invalid data:<br/>CheckIn - CheckIn Date should be in MM/DD/YYYY format.<br/>Please re-enter your data.";
                }
                
                if(!ValidDate(checkOutDate))
                {
                    errorMessage.innerHTML = "You have entered the following invalid data:<br/>CheckOut - CheckOut Date should be in MM/DD/YYYY format.<br/>Please re-enter your data.";
                }
            }   
        }	
	    else if ((compareDates(checkOutDate, checkInDate) > 0) && (compareDates(checkInDate, todaysDt) > 0))
	    {
	        errorMessage.innerHTML = "You have entered the following invalid data:<br/>CheckIn - CheckIn Date should greater than Today's Date.<br/>CheckOut - CheckOut Date should greater than CheckIn Date.<br/>Please re-enter your data.";
	    }
	    else if (eval((Date.parse(checkOutDate)-Date.parse(checkInDate))/(24*60*60*1000))>28)
	    {
	          var dateDiff=(Date.parse(checkOutDate)-Date.parse(checkInDate))/(24*60*60*1000);
              errorMessage.innerHTML = "Your stay cannot exceed 28 nights.<br/>Please re-enter your data.";
            
	    }
	    else
	    {
	        if (compareDates(checkOutDate, checkInDate) > 0) {
		        errorMessage.innerHTML = "You have entered the following invalid data:<br/>Check Out - CheckOut Date should greater than CheckIn Date.<br/>Please re-enter your data.";
	        }

	        if (compareDates(checkInDate, todaysDt) > 0) {			
		        errorMessage.innerHTML = "You have entered the following invalid data:<br/>CheckIn - CheckIn Date should greater than Today's Date.<br/>Please re-enter your data.";
	        }
	    }	
	}
	var kidsCount = document.getElementById('columnRight_ctl00_LodgingDetail_ddlKids').value;
	var adultCount = document.getElementById('columnRight_ctl00_LodgingDetail_ddlAdult').value;
	if ((parseInt(adultCount) + parseInt(kidsCount)) > 19)
	{
	   errorMessage.innerHTML = "The maximum number of travelers allowed is 19";
	}

  
	if (errorMessage.innerHTML.length < 1) {

		$("#editDates").removeClass("hideDiv");
		$('div#editDates').dialog("close");
		$("#lodgingCalendar").removeClass("hideDiv");
	    $('div#lodgingCalendar').dialog("close");
		BindKidsAge();
		var childAge = '';
		var loopCount = 0;
		var innerLoop = 0;
		var dropDowns = document.getElementsByTagName("li");
		var selector = document.getElementById('columnRight_ctl00_LodgingDetail_ddlKids').value;
		var selector = Number(selector);
		for (loopCount = 0; loopCount < dropDowns.length; loopCount++) {
			if (dropDowns[loopCount].id.indexOf("childAgeRepeater") > -1) {
				for (innerLoop = loopCount; innerLoop < (loopCount + selector); innerLoop++) {

					if (document.getElementById(dropDowns[innerLoop].id).className == 'adultsKids') {
						var dropdownIndex = document.getElementById(dropDowns[innerLoop].id).id;
						childAge += $("#" + dropdownIndex + " select").val() + ",";
					}
				}
				break;
			}
		}        
		var dropDowns = document.getElementsByTagName("li");
		var selector = document.getElementById('columnRight_ctl00_LodgingDetail_ddlKids').value;
		//var kidsCount = document.getElementById('columnRight_ctl00_LodgingDetail_ddlKids').value;
		var checkInDate = document.getElementById('columnRight_ctl00_LodgingDetail_txtCheckInDate').value;
		var checkOutDate = document.getElementById('columnRight_ctl00_LodgingDetail_txtCheckOutDate').value;		
		//var adultCount = document.getElementById('columnRight_ctl00_LodgingDetail_ddlAdult').value;
		var hdnProductCode = $(".hdnProductCode").val();		
		$("#ajaxContentContainer").showLoading({loadingStr: "Please wait a moment while we search for your results", autoFocus: false});
		$.ajax({
			type: "POST",
			url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetUpdatedLodgingDetails",
			data: "{\"arrivalDate\" : \"" + checkInDate + "\",\"departDate\" : \"" + checkOutDate + "\",\"adultsCount\" : \"" + adultCount + "\",\"productCode\" : \"" + hdnProductCode + "\",\"childAge\" : \"" + childAge + "\",\"kidsCount\" : \"" + kidsCount + "\"}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg) {			
				$('#ajaxDetailsContainer').html(msg.d);
				 $("#lodgingCalendar #divCalendarPrice").html("");
				$("#editDates").remove();
				$('body > .ui-dialog div[id=lodgingCalendar]').remove();
			    openEmailWindow();
				attachDialogBoxLodgingDetails("ul.infoBoxes .datesTravelers .btnGrey", "click");
				attachDialogBoxCalendar("td.LodgingCalendar", "click");
				$("#tab1").addClass("tabs-show");
				$(".mainTabsPnB").children(":first").addClass("tabs-selected");
				$(".mainTabsPnB :first-child").children(":first").addClass("tabs-selected");
				$(".contentContainer").children(":first").addClass("tabs-show");
				$(".mainTabsPnB>li").each(function() {
					$(this).click(function(event) {
						var pickId = $(this).children(":first").attr("href");
						event.preventDefault();
						$(".mainTabsPnB>li").removeClass("tabs-selected")
						$(".mainTabsPnB>li a").removeClass("tabs-selected")
						$(this).addClass("tabs-selected");
						$(this).children(":first").addClass("tabs-selected");
						$(".contentContainer div").removeClass("tabs-show");
						$(pickId).addClass("tabs-show");

					})
				})
				hideInterstitial();
			},
		    error: function(xhr, status, error) {
			    handlePnB_Lodging_Error(xhr, status, error);
		    }
		});
	}
}


function CloseKidsWindow()
{
$("#editDates").removeClass("hideDiv");
		$('div#editDates').dialog("close");
}
//Update search criteria
    function UpdateCriteria(lodgingListRedirecturl) {
    
    //fix artf965578 - By Naveen on 13-07-2009
    ResetConditionalFilter();
    var lastRatingStart=ratingStart;
    var lastRatingEnd=ratingEnd;
    $(".lodgingTableContainer [id$=errorMessage]").hide();
   	var checkInDate = document.getElementById(txtCheckInDate).value;
	var checkOutDate = document.getElementById(txtCheckOutDate).value;
	returnDate = document.getElementById(txtCheckOutDate).value;
	departDate = document.getElementById(txtCheckInDate).value;
	var todaysDt = new Date();	

	var kidsCount = document.getElementById(ddlKids).value;
	var adultCount = document.getElementById(ddlAdults).value;
	var errorMessage = document.getElementById('errorMessage');

	if (errorMessage.innerHTML.length < 1) {

		var childAge = '';
		var loopCount = 0;
		var innerLoop = 0;
		var dropDowns = document.getElementsByTagName("li");
		var selector = document.getElementById(ddlKids).value;
		var selector = Number(selector);
		for (loopCount = 0; loopCount < dropDowns.length; loopCount++) {
			if (dropDowns[loopCount].id.indexOf("childAgeRepeater") > -1) {
				for (innerLoop = loopCount; innerLoop < (loopCount + selector); innerLoop++) {

					if (document.getElementById(dropDowns[innerLoop].id).className == 'adultsKids') {

						var dropdownIndex = document.getElementById(dropDowns[innerLoop].id).id;
						childAge += $("#" + dropdownIndex + " select").val() + ",";
					}
				}
				break;
			}
		}

		childrenAges = childAge.replace(/,/g, "|");
		url = lodgingListRedirecturl + checkInDate + ',' + checkOutDate + ',' + adultCount + ',' + kidsCount + ',' + childrenAges;
		lodgingURL=url;
		$(".emailVacationLink").attr("href", url); 
		var selector = document.getElementById(ddlKids).value;
		if (checkOutDate != '' && checkInDate != '') {
			dropdown = document.getElementById('ddlResultPerPage');
			if (dropdown == null) {
				selectedIndex = 0;
			}
			else {
				selectedIndex = dropdown.selectedIndex;
			}
			PageFrom = 0;
			PageTo = 10;
			ResultPerPage = 10;
	    	initInterstitial();
			$("#ajaxContentContainer").showLoading({loadingStr: "Please wait a moment while we search for your results", autoFocus: false});
			
			$.ajax({
				type: "POST",
				url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetUpdatedLodgingCriteria",
				data: "{\"arrivalDate\" : \"" + checkInDate + "\",\"departDate\" : \"" + checkOutDate + "\",\"adultsCount\" : \"" + adultCount + "\",\"kidsCount\" : \"" + kidsCount + "\" ,\"childAge\" : \"" + childAge + "\"}",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function(msg) {
					$('#ajaxContentContainer').removeClass('loading');
					$('#ajaxContentContainer').html(msg.d);
					$('.paginationContainer').prepend("<div class='boxPaginationLeft'></div>");
					$('.paginationContainer').append("<div class='boxPaginationRight'></div>");
                    if ($('.hoverBubble').length >=1 )  //ps
		            {
                        addRemoveHoverBubble();//ps
		            }		
		            $('#ddlResultPerPage').attr('selectedIndex', selectedIndex);
					$(".lodgingList tr:first td.firstColumn").addClass('topBackgoundImage');
	                $(".lodgingList tr:last td.firstColumn").addClass('bottomBackgoundImage');
	                $(".lodgingList tr:last td.firstColumn").css('borderBottom', 'none');
	                $("table.lodgingList tr:last").css('background','none');
	                //fix artf949571 - By Naveen on 13-07-2009
	                $('.lodgingListFilter select').attr('selectedIndex', 0);
					BindKidsAge();
					 $('.amenities').unbind('click').bind('click',function(){
                        loadAmenities($(this).attr('id'));
                        })
					hideInterstitial();
				},
		        error: function(xhr, status, error) {
			        handlePnB_Lodging_Error(xhr, status, error);
		        }
			});
			initInterstitial();
			$("#divMainFilterCriteria").showLoading({loadingStr: "Please wait a moment while we search for your results", autoFocus: false});
			$.ajax({
				type: "POST",
				url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetUpdatedLodgingFilter",
				data: "{}",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function(msg) {
				$('#divMainFilterCriteria').html(msg.d);
				if (filterCriteria!='0|0')
                   {
				    filterCriteriaString=filterCriteria.split('|');
				    ResetConditioanFilterAfterUpdate(filterCriteriaString[0],filterCriteriaString[1],filterCriteriaString[2]);
                    RenderOutputForLodgingFilter();
                  }
                    
					attachSliderControl();
					$("#starRatingFilter").slider("values", 0, lastRatingStart);
                    $("#starRatingFilter").slider("values", 1, lastRatingEnd);
					attachExpandCollapse();
					hideInterstitial();
				},
		        error: function(xhr, status, error) {
			        handlePnB_Lodging_Error(xhr, status, error);
		        }
			});

		}
	}
}

//Attach Slider control to lodging list

function attachSliderControl() {
	$("#starRatingFilter").slider({
		animate: true,
		range: true,
		min: 1,
		max: 5,
		step: 0.5,
		values: [1, 5],
		slide: function(event, ui) {
		    removeBubbles();//ps
			ratingStart = ui.values[0];
			ratingEnd = ui.values[1];
			SelectedValue = $(".lodgingListFilter select").val();
			dropdown = document.getElementById('ddlResultPerPage');
			if (dropdown == null) {
				selectedIndex = 0;
				PageTo=10;
				ResultPerPage=10;
			}
			else {
				selectedIndex = dropdown.selectedIndex;
				PageTo = $("#ddlResultPerPage").val();
			    ResultPerPage = $("#ddlResultPerPage").val();
			}
			    if($("ul.mainTabsPnB li:first").hasClass("tabs-selected"))
	            {
	                FillConditionalFilter();
			        PageFrom = 0;
			        RenderOutput();;
	            }
	            else
	            {
	                 GetMapFilter();
	            }
			
		}
	});
}

    
function resetstarRatingFilter(minVal,maxVal){
    ratingStart = minVal;
	ratingEnd = maxVal;
    $("#starRatingFilter").slider("values", 0, minVal)
    $("#starRatingFilter").slider("values", 1, maxVal)
    FillConditionalFilter();
    PageFrom = 0;
	PageTo = $("#ddlResultPerPage").val();
	ResultPerPage = $("#ddlResultPerPage").val();
    RenderOutput();
    }
    
    
    function CloseSaveToTripModalWindow()
    {
        window.parent.closeModalDialog("#saveToTripDialog");
    }
   
//opening modal window for saveItemToTrip
    function saveToTripDialog(){
	
    $(".saveLink").live("click", function (e)
    {
    var room = $(this).closest("tr").find("td:eq(3) select").val();
    if(room > MaxAllowedRoom)
    {
        var msg = $("[id$=hdnErrorMsg]").val();
        SetMaxAllowedRoomErrorMessage(msg); 
        scroll(0,0);
        return false;           
    }

        e.preventDefault();
        var saveToTripDialog = $("#saveToTripDialog");
        /*
        if ( saveToTripDialog.length == 0 ){
            $("body").append([''
                ,'<div id="saveToTripDialog">'
                ,    '<iframe marginwidth="0" marginheight="0" frameborder="0" width="0" height="0" style="background: white;"></iframe>'
                ,'</div>'
            ].join(''));
            saveToTripDialog = $("#saveToTripDialog");
        }
        */
        if ( saveToTripDialog.parents(".ui-dialog").length == 0 ){
            saveToTripDialog.dialog({
                width: 960, // 500, 700, 960
                height: 690,
	            bgiframe: true,
	            autoOpen: false,
	            modal: true,
	            resizable: false,
	            position: 'center',
	            closeOnEscape: true
            });
        }
		var urlContent = $(this).attr('href');
		urlContent=urlContent+"&NumberOfRooms="+room;
	  	saveToTripDialog.find("iframe")
		    .attr('src',urlContent)
		    .attr('width','100%')
		    .attr('height','100%')
		    .attr('scrolling','no');
		saveToTripDialog.dialog('open');
		
		
		return false;
    });    
}

function ValidDate(checkInDate)
{
    if(checkInDate == "")
    {
       return false;
    }
    try
    {
        var myDate = new Date(checkInDate);
        // In IE it was giving NaN value. So handle it.
        if(myDate == "Invalid Date" || myDate == "NaN")
        {
            return false;
        }  
        var inputDate = checkInDate.split("/");
        if ( inputDate.length == 3 )
        {
            var monthfield= inputDate[0];
            var dayfield  = inputDate[1];
            var yearfield = inputDate[2];
            if ((myDate.getMonth()+1 != monthfield) || (myDate.getDate() != dayfield) || (myDate.getFullYear() != yearfield) )
                return false;
        }  
        else
            return false; 
     }
     catch(err)
     {  
        return false;   
     }     
     return true;
}

function SetNoResultsErrorMessage()
{      
     $("#lblNoResults").html('<strong>The property you have searched for does not have availability for the dates you have specified. Please revise your search criteria</strong>');
     $("#lblNoResults").css('color','red');
}

function SetNoResultsMessage(msg)
{     
    var errorMsgLabel = document.getElementById('lblNoResults');    
    $("#lblNoResults").html('<strong>' + msg + '</strong>');
    $("#lblNoResults").css('color','red');
    $("#fragment-1").addClass("tabs-container");
    $("#fragment-1").css('display','block');
    $("#fragment-2").addClass("tabs-container tabs-hide");
    $("#fragment-3").addClass("tabs-container tabs-hide");
    $("#fragment-4").addClass("tabs-container tabs-hide");
}


function SetMaxAllowedRoomErrorMessage(msg)
{      
    var errorMsgLabel = document.getElementById('lblNoResults');        
    errorMsgLabel.style.color = 'red';
    errorMsgLabel.innerHTML = '<strong>' + msg + '</strong>';
}

function redirectToLodgingDetail (url)
{
    document.location=url;
}


//Funtion called when button Continue is clicked 
function SaveToCart(me, ProductSKU)
{
    //var room = $(".tagcontforcart").closest("tr").find("td:eq(3) select").val();
    var room = $("#"+me).closest("tr").find("td:eq(3) select").val();
    
    if(room > MaxAllowedRoom)
    {
        var msg = $("[id$=hdnErrorMsg]").val();
        SetMaxAllowedRoomErrorMessage(msg);            
    }
    else
    {
        maskMe( "#" + me );
        var productId = "";
        var productCode = "";
        // Get the url.
        var fullURL = unescape(parent.document.URL);
        fullURL = fullURL.toLowerCase();
        if(fullURL.indexOf('cartproductid=') != -1)
        {
            // Get the search string from url.
            var extractURL = fullURL.substring(fullURL.indexOf('cartproductid=')+14, fullURL.length);
            productId = extractURL;
                
            if(extractURL.indexOf('&') >= 0)
            {
                productId = extractURL.substring(0, extractURL.indexOf('&'));  
                                  
            }            
        }
        
        if(fullURL.indexOf('code=') != -1)
        {
            // Get the search string from url.
            var extractURL = fullURL.substring(fullURL.indexOf('code=')+5, fullURL.length);
            productCode = extractURL;
                
            if(extractURL.indexOf('&') >= 0)
            {
                productCode = extractURL.substring(0, extractURL.indexOf('&'));  
            }            
        }
            if(productCode.indexOf('#') >= 0)
            {
                productCode=productCode.substring(0,productCode.indexOf('#'));
            }
        
        var checkInDate = $("[id$=lblCheckIn]").html();
        var checkOutDate = $("[id$=lblCheckOut]").html();
      // $("#ajaxContentContainer").showLoading({loadingStr: "Please wait a moment while we search for your results"});
        $.ajax
         ({
                type: "POST",
                url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/AddLodgingToCart",
                //async: false,
                data: "{\"SKU\" : \""+ProductSKU+"\",\"cartProductId\": \"" + productId + "\",\"productCode\": \"" + productCode + "\",\"checkInDate\": \"" + checkInDate + "\",\"checkOutDate\": \"" + checkOutDate + "\",\"rooms\": \"" + room + "\"}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg)
                {   
                    window.location.href = msg.d;          
                },
		        error: function(xhr, status, error) {
			        handlePnB_Lodging_Error(xhr, status, error);
		        }
        });
        
    }
    
     scroll(0,0);
     return false;    
}

function addRemoveHoverBubble()//ps
{
    $('.hoverBubble div').removeClass('hoverBubTop');
	$('.hoverBubble div').removeClass('hoverBubBottom');
    
    $('.hoverBubble').prepend("<div class='hoverBubTop'></div>");
    $('.hoverBubble').append("<div class='hoverBubBottom'></div>");
}

function RenderOutputForLodgingFilter() {
	$("#ajaxContentContainer").showLoading({loadingStr: "Please wait a moment while we search for your results", autoFocus: false});
	$.ajax({
		type: "POST",
		url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetLodgingDetails",
		data: "{\"sortType\" : \"" + SelectedValue + "\",\"recordFrom\" : \"" + PageFrom + "\",\"recordTo\" : \"" + PageTo + "\",\"resultPerPage\" : \"" + ResultPerPage + "\",\"filterCriteria\" : \"" + filterCriteria + "\",\"ratingStart\" : \"" + ratingStart + "\",\"ratingEnd\" : \"" + ratingEnd + "\",\"isFilter\" : \"" + "true" + "\"}",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg) {
			$('#ajaxContentContainer').removeClass('loading');
			$('#ajaxContentContainer').html(msg.d);
			$('.paginationContainer').prepend("<div class='boxPaginationLeft'></div>");
			$('.paginationContainer').append("<div class='boxPaginationRight'></div>");
            if ($('.hoverBubble').length >=1 ) //ps
			{
                addRemoveHoverBubble();//ps
			}	
			$('#ddlResultPerPage').attr('selectedIndex', selectedIndex);
        	$(".lodgingList tr:first td.firstColumn").addClass('topBackgoundImage');
	        $(".lodgingList tr:last td.firstColumn").addClass('bottomBackgoundImage');
	        $(".lodgingList tr:last td.firstColumn").css('borderBottom', 'none');
	        $("table.lodgingList tr:last").css('background','none');
	         $('.amenities').unbind('click').bind('click',function(){
                loadAmenities($(this).attr('id'));
	        })
	        //Omnitue Taging
	        BindLodgingData();
			hideInterstitial();
		},
        error: function(xhr, status, error) {
	        handlePnB_Lodging_Error(xhr, status, error);
        }
	});
}


function renderLodgingFilter()
{
	$("#divMainFilterCriteria").showLoading({loadingStr: "Please wait a moment while we search for your results", autoFocus: false});
    $.ajax({
	    type: "POST",
	    async: "false",
	    url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetUpdatedLodgingFilter",
	    data: "{}",
	    contentType: "application/json; charset=utf-8",
	    dataType: "json",
	    success: function(msg) {
		    $('#divMainFilterCriteria').html(msg.d);
		    $("#starRatingFilter").slider("values", 0, 1)
            $("#starRatingFilter").slider("values", 1, 5)
		    attachSliderControl();
		    attachExpandCollapse();
			hideInterstitial();
	    },
        error: function(xhr, status, error) {
            handlePnB_Lodging_Error(xhr, status, error);
        }
    });
}


function renderDeepLinkLodgingFilter()
{
	$("#divMainFilterCriteria").showLoading({loadingStr: "Please wait a moment while we search for your results", autoFocus: false});
    $.ajax({
	    type: "POST",
	    async: "false",
	    url: "/vailresorts/sites/PlanningAndBooking/WebServices/LodgingWebService.svc/GetUpdatedLodgingFilter",
	    data: "{}",
	    contentType: "application/json; charset=utf-8",
	    dataType: "json",
	    success: function(msg) {
		    $('#divMainFilterCriteria').html(msg.d);
		    $("#starRatingFilter").slider("values", 0, 1)
            $("#starRatingFilter").slider("values", 1, 5)
		    attachSliderControl();
		    if (filterCriteriaFound)
		    {
		    FillConditionalFilterForDeepLink(filterCriteriaString[0],filterCriteriaString[1]);
		    }
		    RenderOutputForLodgingFilter();
		    $("#starRatingFilter").slider("values", 0, ratingStart)
             $("#starRatingFilter").slider("values", 1, ratingEnd)
             attachExpandCollapse();
			hideInterstitial();
	    },
        error: function(xhr, status, error) {
            handlePnB_Lodging_Error(xhr, status, error);
        }
    });
}

function attachExpandCollapse(){
	$("#divMainFilterCriteria img.collapsibleLink").unbind("click").bind("click", function () {
		var current = this;
		var container = $(this).parent().next();
		if ($(container).css("display") == "none") {
			$(current).attr('src', '/VailResorts/sites/PlanningAndBooking/assets/img/iconMinus.gif');
			$(container).toggle();
		} else {
			$(current).attr('src', '/VailResorts/sites/PlanningAndBooking/assets/img/iconPlus.gif');
			$(container).toggle();
		}
	});
}


function openEmailWindow()
{
$('.openModal').click(function(e) {
	    e.preventDefault();
	    var urlContent = $(this).attr('href');
		var objDialog = $('body > .ui-dialog .iFrameModalEmail');
		$('iframe', objDialog)
			.attr('src',urlContent)
			.attr('width','100%')
			.attr('height','100%')
			.attr('scrolling','no');
		try { $('.iFrameModalEmail').dialog('open'); } catch (e){}
		return false;
	});	
}



//This method is used to find the selected value of list filters of lodging
//Artifact artf1050050 : All | Lodging - Update trip Details should not reset filters 
function ResetConditionalFilter() {
//fix artf965578 - By Naveen on 13-07-2009
$(".lodgingTableContainer [id$=errorMessage]").hide();
var checkAll=document.getElementById('chkAll');
	selectedNeighbours = '';
	selectedLodgingType = '';
	selectedAmenities = '';
	var unCheckedLocationCounter=0;
	var documentInput = document.getElementsByTagName("input");
	for (var counter = 0; counter < documentInput.length; counter++) {
		var Comparision = documentInput[counter];
		if (Comparision.className == 'chkBox chkboxNeighbours') {
			if (Comparision.checked == true) {
				selectedNeighbours += Comparision.value + ','

			}
			else
			{
			    unCheckedLocationCounter=unCheckedLocationCounter+1;
			}
		}
		else if (Comparision.className == 'chkBox checkboxLodgingType') {
			if (Comparision.checked == true) {
				selectedLodgingType += Comparision.value + ','

			}
		}
		else if (Comparision.className == 'chkBox checkboxAmenities') {
			if (Comparision.checked == true) {
				selectedAmenities += Comparision.value + ','
			}
		}
	}
   
    if (unCheckedLocationCounter>0)
    {
        checkAll.checked=false;

    }
    else
    {
    checkAll.checked=true;
    }
	selectedNeighbours = (selectedNeighbours == '') ? selectedNeighbours: selectedNeighbours.substring(0, (selectedNeighbours.length - 1)) + '|';
	selectedLodgingType = (selectedLodgingType == '') ? selectedLodgingType: selectedLodgingType.substring(0, (selectedLodgingType.length - 1)) + '|';
	selectedAmenities = (selectedAmenities == '') ? selectedAmenities: selectedAmenities.substring(0, (selectedAmenities.length - 1)) + '|';
	
	if (selectedNeighbours == '')
	{
	selectedNeighbours='0|';
	}
	if (selectedLodgingType == '')
	{
	selectedLodgingType='0|';
	}

	if (selectedNeighbours == '' || selectedLodgingType == '') {
	
		filterCriteria = '0|0|';
	}
	else {
		filterCriteria = selectedNeighbours + selectedLodgingType + selectedAmenities;
	}
	
	 
    var URLFilter=lodgingURL+"_separator_ratingStart="+ratingStart+"_separator_ratingEnd="+ratingEnd + "_separator_filterCriteria="+filterCriteria;
    $(".emailVacationLink").attr("href", URLFilter);
	
}


function ResetConditioanFilterAfterUpdate(location,roomtype,amenitiesType) 
{
    var locationCounter=0;
    var roomTypeCounter=0;
    var amenitiesTypeCounter=0;
    var unCheckedLocationCounter=0;
    var checkAll=document.getElementById('chkAll');
    if (location.length>0)
    {
        location=location+',0';
        roomtype=roomtype+',0';
        amenitiesType=amenitiesType+',0';
        selectedNeighbours = '';
	    selectedLodgingType = '';
	    selectedAmenities = '';
	    filterLocation=location.split(',');
	    filterRoomType=roomtype.split(',');
	    filterAmenitiesType=amenitiesType.split(',');
	    var documentInput = document.getElementsByTagName("input");
	    for (var counter = 0; counter < documentInput.length; counter++) {
		var Comparision = documentInput[counter];
		if (Comparision.className == 'chkBox chkboxNeighbours') 
		{
		   if (filterLocation[locationCounter]!= undefined)
		   {
		       if (Comparision.value==filterLocation[locationCounter])
		       {
		            locationCounter++;
		            if (Comparision.disabled == false) 
			         {
    		            Comparision.checked=true;
    		         }
		       }
		       else
		       {
		           
		            Comparision.checked=false;
		       
		       }
			    if (Comparision.checked == true) 
			    {
				    selectedNeighbours += Comparision.value + ','

			    }
			    else
			    {
			        unCheckedLocationCounter=unCheckedLocationCounter+1;
			    }
		    }
		}
		    else if (Comparision.className == 'chkBox checkboxLodgingType') 
		    {
		        if (filterRoomType[roomTypeCounter]!= undefined)
		        {
		           if (Comparision.value==filterRoomType[roomTypeCounter])
		           { 
		                roomTypeCounter++;
    		            if (Comparision.disabled == false) 
			             {
    		                Comparision.checked=true;
    		             }
		           }
		           else
		           {
		                Comparision.checked=false;
		           }
		        }
			    if (Comparision.checked == true) 
			    {
				    selectedLodgingType += Comparision.value + ','

			    }
		    }
		    
		    
		    else if (Comparision.className == 'chkBox checkboxAmenities') 
		    {
		        if (filterAmenitiesType[amenitiesTypeCounter]!= undefined)
		        {
		           if (Comparision.value==filterAmenitiesType[amenitiesTypeCounter])
		           { 
		                amenitiesTypeCounter++;
    		            if (Comparision.disabled == false) 
			             {
    		                Comparision.checked=true;
    		             }
		           }
		           else
		           {
		                Comparision.checked=false;
		           }
		        }
			    if (Comparision.checked == true) 
			    {
				    selectedAmenities += Comparision.value + ','

			    }
		    }
		
	}
	
    }
    
     if (unCheckedLocationCounter>0)
     {
      checkAll.checked=false;

      }
    else
    {
        checkAll.checked=true;
    }
	selectedNeighbours = (selectedNeighbours == '') ? selectedNeighbours: selectedNeighbours.substring(0, (selectedNeighbours.length - 1)) + '|';
	selectedLodgingType = (selectedLodgingType == '') ? selectedLodgingType: selectedLodgingType.substring(0, (selectedLodgingType.length - 1)) + '|';
	selectedAmenities = (selectedAmenities == '') ? selectedAmenities: selectedAmenities.substring(0, (selectedAmenities.length - 1)) + '|';
	if (selectedNeighbours == '' || selectedLodgingType == '') {
		filterCriteria = '0|0|';
	}
	else {
		filterCriteria = selectedNeighbours + selectedLodgingType + selectedAmenities;
	}
	var URLFilter=lodgingURL+"_separator_ratingStart="+ratingStart+"_separator_ratingEnd="+ratingEnd + "_separator_filterCriteria="+filterCriteria;
    $(".emailVacationLink").attr("href", URLFilter);
}


function maskMe(target){
    var thisButton = $(target);
    var buttonLayer = $("<img src='/VailResorts/sites/global/assets/img/blank.gif' alt='' class='buttonLayer' />");
    buttonLayer.appendTo("body").css({
        position: "absolute",
        width: $(thisButton).outerWidth(),
        height: $(thisButton).outerHeight(),
        left: $(thisButton).offset().left,
        top: $(thisButton).offset().top
    }).show();
}

//First time CHK Selection
function FirstTimeAllCHKSelection() 
{
      var unCheckedLocationCounter=0;
        var checkAll=document.getElementById('chkAll');
	    var documentInput = document.getElementsByTagName("input");
	    for (var counter = 0; counter < documentInput.length; counter++) 
	    {
		    var Comparision = documentInput[counter];
		if (Comparision.className == 'chkBox chkboxNeighbours') 
		{
		   if (Comparision.checked!=true)
		   {
		   
		      unCheckedLocationCounter=unCheckedLocationCounter+1;
		    }
			 	    
		}
	    }
	
	 if (unCheckedLocationCounter>0)
     {
        checkAll.checked=false;

     }
    else
    {
        checkAll.checked=true;
    }
	    
	
}




