$(document).ready(function() {
    $(window).load(function(){
        hideInterstitial();
    });
	
	 $('[id$=txtStartDate]').bind("change", function(){
	   if($('[id$=txtStartDate]').val() != ''){
            var NewDate=new Date( $('[id$=txtStartDate]').val());
            NewDate.setDate(NewDate.getDate()+1);
            $('[id$=txtEndDate]').datepicker('option', 'minDate', NewDate );
            $('[id$=txtEndDate]').datepicker('setDate', NewDate);            
        }
    });
    $('[id$=txtStartDate]').datepicker("option", "onSelect", function(){
        if($('[id$=txtStartDate]').val() != ''){
            var NewDate=new Date( $('[id$=txtStartDate]').val());
            NewDate.setDate(NewDate.getDate()+1);
            $('[id$=txtEndDate]').datepicker('option', 'minDate', NewDate );
            $('[id$=txtEndDate]').datepicker('setDate', NewDate);            
        }

    });
	//cart footer rounded box
	//$(".chromeFooterList").gBox({ theme:"whiteBox"});
	
	//Collapse button for right filterb
	$("img.collapsibleLink").click(function(){
		var current = this;
		var container = $(this).parents().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();
		}
	});

	// show Calender Control with respect to Textbox control
	$(".withCalendar1").datepicker({
		showOn: 'both',
		buttonImage: '/VailResorts/sites/PlanningAndBooking/assets/img/icon-calander.gif',
		buttonImageOnly: true,
		maxDate: '+1y',
		minDate: '2',
		 onSelect: function(dateText, inst) {
	            //alert('Hi'+dateText);
	            $('[id$=txtCheckInDate]').trigger('change')
	            return false;
	        }				
	});
	
	saveToTripDialog();
	
	//Email Modal Start
	$('.iFrameModalEmail').dialog({
		bgiframe: true,
		autoOpen: false,
		width: 700,
		height: 425,
		modal: true,
		resizable: false,
		position: 'center',
		closeOnEscape: true,
		draggable:false
	});
	$('.EmailopenModal').click(function(e) {
	     e.preventDefault();
	    var urlContent = $(this).attr('href');
		$('#iframeEmail').attr('src',urlContent).attr('width','100%').attr('height','100%').attr('scrolling','no');
		$('.iFrameModalEmail').dialog('open');
		return false;
	});	
	//Email modal end
	
	if ($(".modalWindow").length > 0){
	    var height = $("body").height();
	    $(window.parent.document).find(".iFrameModalEmail").height(height);
	}
	
	$('.iFrameTravellerModal').dialog({
		bgiframe: true,
		autoOpen: false,
		width: 960,
		height: 560,
		modal: true,
		resizable: false,
		position: 'center',
		closeOnEscape: true,
		draggable:false
	});
	
	$('.openModalForTraveller').unbind('click').bind('click',function(e) {
	       e.preventDefault();
	     var urlContent =  $(this).attr('href');
	  	$('#iframeload')
		    .attr('src',urlContent)
		    .attr('width','100%')
		    .attr('height','100%')
		    .attr('scrolling','no');
		$('.iFrameTravellerModal').dialog('open');
		return false;
	});	
	
	function closeModalDialog(){
    $('.iFrameTravellerModal').dialog('close');
}

    /* 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] */

});


function saveToTripDialog(){
    $(".saveLink").live("click", function (e){
        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: 855,
	            bgiframe: true,
	            autoOpen: false,
	            modal: true,
	            resizable: false,
	            position: 'center',
	            closeOnEscape: true
            });
        }
		var urlContent = $(this).attr('href');
		
	  	saveToTripDialog.find("iframe")
		    .attr('src',urlContent)
		    .attr('width','100%')
		    .attr('height','100%')
		    .attr('scrolling','no');
		saveToTripDialog.dialog('open');
		
		return false;
    });    
}


//This method posts an AJAX Call for getting the SeasonPasses from the database.
function GetOffers(startDate,
                   category,
                   //sortBy, 
                   pageFrom, 
                   resultCount,
                   channel,
                   productType,showinitInterstitial)
{


    //If the SortBy parameter is passed then find the control specifed by SortBy and pass
    // the data to webservice wlse pass blank.
    if(sortBy != "")
    {
        sortByVar = document.getElementById(sortBy); 
        if(sortByVar)
        {
            sortBy = sortByVar.value;            
        }
        else
        {
            sortBy = "";
        }
    }        
    //If the resultCount parameter is passed then find the control specifed by resultCount and pass
    // the data to webservice else pass blank. In case value 10 is passed, the script will try to find
    //the control with that Id. If the control is not found then the same vaue as passed in the parameter will
    //be passed to the We Service.
    if(resultCount != "")
    {
        var resultCountVar = document.getElementById(resultCount);
        if(resultCountVar)
        {
            resultCount = resultCountVar.value;
        }
        else
        {
            if (document.getElementById("hdChkUserSelection"))
            {
                document.getElementById("hdChkUserSelection").value = 1;
            }
        }
    }    

    if (document.getElementById("hdChkUserSelection") != null)
    {
        if ($("input[id$=hdChkUserSelection]").val() == 0 )
        {
            startDate = "";
        }
    }
    //If the StartDate parameter is passed then find the control specifed by StartDate and pass
    // the data to webservice else pass blank.
    var blChkDate = true;
    if(startDate != "")
    {
        var errorMessage = "<span>You have entered the following invalid data:<br><ul><li>Trip Start Date - Date Should be in MM/DD/YYYY format</li></ul></span>"
        var startDateVar = document.getElementById(startDate);
        if(startDateVar)
        {
       
            startDate = startDateVar.value;
             
            if(startDate == '')
            {
                $(".OfferError").html("<span>Please complete the required fields:<br><ul><li>Trip Start Date</li></ul></span>");

                blChkDate = false;
                
            }
            else
            {
                if(!validateDate(startDate))
                {
                    $(".OfferError").html(errorMessage);
                    blChkDate = false;
                }
                else
                {
                    var todaysDt = new Date();
                    todaysDt.setDate(todaysDt.getDate()+1);                      
                    if(compareDates(todaysDt,startDate) < 1)
                    {     
                           $(".OfferError").html("<span>You have entered the following invalid data:<br><ul><li>Trip Start Date - Date Should be greater than " + (todaysDt.getMonth()+1) + "/" + todaysDt.getDate() + "/" + todaysDt.getFullYear() + ".</li></ul></span>");
                          blChkDate = false;
                    }
                    else
                    {
                        if(IsMaximumDateRange(startDate))
                        {                              
                              $(".OfferError").html("<span>You have entered the following invalid data:<br><ul><li>Trip Start Date should not be more then 365 days from now.</li></ul></span>");
                               blChkDate = false;                                                
                        }
                        else
                        {
                            $(".OfferError").html("");
                            
                        }
                    }
                }
            }
      }
      else
      {
          startDate = "";
      }
    } 
    
    if (!blChkDate)
    {
       document.getElementById("hdChkUserSelection").value = 0;
       return false; 
    }
    
    if (document.getElementById("hdChkUserSelection") != null)
    {
        if (document.getElementById("hdChkUserSelection").value == 0 )
        {
            startDate = $("input[id$=hdtxtCheckInDate]").val();
            //Create Category string for filtering   
            category = CreateCategoryGetOfferCriteria('chkListCategory');            
        }
    }  
    
    // If request come from Summary of Checkout Detail by click on Edit Hyperlink
    if ( sortBy == "" )
    {        
        var fullURL = parent.document.URL;    
        if (fullURL.indexOf('Search=') != -1) {    
            // Get the search string from url.
            var extractURL = fullURL.substring(fullURL.indexOf('Search=') + 7, fullURL.length);

            if (extractURL != "") {                            
                    startDate = extractURL;
                    startDate = startDate.replace('%20',' ');
                    startDate = startDate.replace('%20',' '); 
            }
        }
    }       
    
    dataString = "{\"startDate\" : \""+startDate
                +"\",\"category\": \"" + category
                +"\",\"sortBy\": \"" + sortBy
                +"\",\"pageFrom\": \"" + pageFrom
                +"\",\"resultCount\": \"" + resultCount 
                +"\",\"channel\": \"" + channel
                +"\",\"productType\": \"" + productType    
                 +"\",\"showinitInterstitial\": \"" + showinitInterstitial
                +"\"}";
//Show loading icon on ajax call 
$(".topShadowDivider").html("");
$('[id$=lblError]').html("");
$('[id$=paginateControl_divPagination]').html("");
if (showinitInterstitial=="true")
{
    initInterstitial();
}
$("#divAjax").showLoading({loadingStr: "Please wait a moment while we search for your results", autoFocus: false});
    $.ajax({
              type: "POST",
              url: "/vailresorts/Sites/PlanningAndBooking/WebServices/OfferService.svc/GetOffersJSON",
              //url:"/vailresorts/sites/PlanningAndBooking/layouts/LiftTicketDetails.aspx/GetLiftTicketData",
              data: dataString,
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function(msg) {setTimeout( function() {
                $('#divData').html(msg.d); 
                //$('.darkGreyBoxContainer').prepend("<div class='darkGreyBoxTop'></div>");   
                //$(".whiteBox").gBox({ theme:"whiteBox"});   
                //$(".lightGreyBox").gBox({ theme:"lightGreyBox"});  
                //pageLoadHandlers();
                hideInterstitial();
                },200 );
              },
              error: function(xhr, status, error) {
                    handlePnB_Offers_Error(xhr, status, error);
              }
          });
          
          return false;
 }

function handlePnB_Offers_Error(xhr, status, error)
{
    var errMsg = getErrorMessage(xhr,status,error);
    document.getElementById('errorMessageOffer').innerHTML = errMsg;
}

//This method is used for Filtering the Offers
function FilterOffers(startDate,
                      category,
                      sortBy, 
                      pageFrom, 
                      resultCount,
                      channel,
                      productType)
{
    //If the SortBy parameter is passed then find the control specifed by SortBy and pass
    // the data to webservice wlse pass blank.
    if(sortBy != "")
    {
        sortByVar = document.getElementById(sortBy); 
        if(sortByVar)
        {
            
            sortBy = sortByVar.value;
        }
        else
        {
            sortBy = "";
        }
    }    

    //Create Category string for filtering
    if(category != "")
         category = CreateCategoryFilterCriteria(category);

    //If the resultCount parameter is passed then find the control specifed by resultCount and pass
    // the data to webservice else pass blank. In case value 10 is passed, the script will try to find
    //the control with that Id. If the control is not found then the same vaue as passed in the parameter will
    //be passed to the We Service.
    if(resultCount != "")
    {
        var resultCountVar = document.getElementById(resultCount);
        if(resultCountVar)
        {
            resultCount = resultCountVar.value;
        }
    }       

    startDate = $("input[id$=txtCheckInDate]").val();
    dataString = "{\"startDate\" : \""+startDate
                +"\",\"category\": \"" + category
                +"\",\"sortBy\": \"" + sortBy
                +"\",\"pageFrom\": \"" + pageFrom
                +"\",\"resultCount\": \"" + resultCount 
                +"\",\"channel\": \"" + channel
                +"\",\"productType\": \"" + productType    
                +"\"}";
$(".topShadowDivider").html("");
$('[id$=lblError]').html("");
//initInterstitial();
$("#divAjax").showLoading({loadingStr: "Please wait a moment while we search for your results", autoFocus: false});
    $.ajax({
              type: "POST",
              url: "/vailresorts/Sites/PlanningAndBooking/WebServices/OfferService.svc/FilterOffers",
              //url:"/vailresorts/sites/PlanningAndBooking/layouts/LiftTicketDetails.aspx/GetLiftTicketData",
              data: dataString,
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function(msg) {setTimeout( function() {
                $('#divData').html(msg.d);    
                //$('.darkGreyBoxContainer').prepend("<div class='darkGreyBoxTop'></div>");            
               //$(".whiteBox").gBox({ theme:"whiteBox"});   
               //$(".lightGreyBox").gBox({ theme:"lightGreyBox"});  
               hideInterstitial();
               },100 );
              },
              error: function(xhr, status, error) {
                    var errMsg = getErrorMessage(xhr, status, error);
			if(errMsg != ' ')                    
			{
				
			}
              }
          });
          
          return false;
 }
 
 
 //The method propagates to all the CategoryCheckBox list.
 //Creates the string with the selected value
 function CreateCategoryFilterCriteria(chkId)
 {
    categoryList = "";
    if(chkId != "")
    {
        var inputControls = document.getElementsByTagName("input");
        if(inputControls)
        {
            for(i=0; i< inputControls.length; i++)
            {
                if(inputControls[i].id.indexOf(chkId) > -1)
                {   
                    if(inputControls[i].checked)
                    {
                        lblControl = inputControls[i].parentNode.getElementsByTagName("label");
                        if(lblControl != null)
                        {
                            categoryList = lblControl[0].innerHTML +"||"+ categoryList;
                        }
                    }
                }
            }
        } 
    }
    categoryList = categoryList.substr(0, categoryList.length-2);
    return categoryList;
 }
 
 
 
 //The method propagates to all the CategoryCheckBox list.
 //Creates the string with the selected value
 function CreateCategoryGetOfferCriteria(chkId)
 {
    categoryList = "||||";
    if(chkId != "")
    {
        var inputControls = document.getElementsByTagName("input");
        if(inputControls)
        {
            for(i=0; i< inputControls.length; i++)
            {
                if(inputControls[i].id.indexOf(chkId) > -1)
                {   
                    if(inputControls[i].checked)
                    {
                        lblControl = inputControls[i].parentNode.getElementsByTagName("label");
                        if(lblControl != null)
                        {
                            categoryList = lblControl[0].innerHTML +"||"+ categoryList;
                        }
                    }
                }
            }
        } 
    }
    categoryList = categoryList.substr(0, categoryList.length-2);
    return categoryList;
 }
 
 
 
 //The method selects or deselects all the checkboxes.
 function SelectDeselectAllCategories(id, check)
 {
    if(id != "")
    {
        var inputControls = document.getElementsByTagName("input");
        if(inputControls)
        {
            for(i=0; i< inputControls.length; i++)
            {
                if(inputControls[i].id.indexOf(id) > -1)
                {   
                    inputControls[i].checked =check ;
                }
            }
        } 
    }
 }
 
 function validateDate(startDate)
 {
    var myDate = new Date(startDate);        
    if(myDate == "Invalid Date" || myDate=="NaN")
    {
        return false;
    }
    else if (IsDateMMDDYYYY(startDate)==false)
    {
        return false;
    }
    else 
    {
       return true;
    } 
 }

