//This function validates if total number of travelers is greater than 19.
$(document).ready(function() {
    attachChildrenAgesModal();
    //$(".whiteBox").gBox({ theme:"whiteBox"});
    //$(".chromeFooterList").gBox({ theme:"whiteBox"});
    //$(".gradientBox").gBox({ theme:"gradientBox"});
     $('[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);            
        }
    });
});

function ValidateTotalNumberOfTravelers(val,args) { 
   var TotalTraveler = parseInt(document.getElementById(val.controltovalidate).value) + parseInt(document.getElementById("columnRight_ctl00_drdChildren").value);       
   if ( TotalTraveler > MaximumPersons || TotalTraveler < MinimumPersons) {        
        args.IsValid = false;       
        return false;
   }    
    args.IsValid = true;        
 }

function configureOfferToggleDropDown(childAgeDropdown) {
    
    var loopCount = 0;
    var innerLoop = 0;
    var dropDowns = document.getElementsByTagName("li");
    var selector = document.getElementById(childAgeDropdown).value;
    
    var selector = Number(selector);
    if (selector>0)
    {
        for (loopCount = 0; loopCount < dropDowns.length; loopCount++) {
            if (dropDowns[loopCount].id.indexOf("childAgeRepeater") > -1) {
                document.getElementById(dropDowns[loopCount].id).className = 'adultsKids hideDiv';
            }
        }
        for (loopCount = 0; loopCount < dropDowns.length; loopCount++) {
            if (dropDowns[loopCount].id.indexOf("childAgeRepeater") > -1) {
                for (innerLoop = loopCount; innerLoop < (loopCount + selector); innerLoop++) {
                    document.getElementById(dropDowns[innerLoop].id).className = 'adultsKids';
                }
                break;
            }
        }
        $(".children").removeClass("hideDiv");
        
        
   }
   else
   {
    
    $(".children").addClass("children hideDiv");
   
   }
   // reSize window 
   autoAdjustIframeModalHeight();
}

//Close Compare window and redirect to Lodging Details page
function CloseWindowAndRedirectToLodgingInOffer(hdnVarLodgingUrl) {
    $('.iFrameTravellerModal').dialog('close');
    parent.location.href = hdnVarLodgingUrl;
}

function closeOfferModalWindow(){
   window.parent.$('.iFrameTravellerModal').dialog( 'close' );
}

function ConfigurePriceValidate(MinNight,WeekDay,MaxQty)
{   
    
    if(!Page_ClientValidate("RequiredValidation"))
    {
        document.getElementById('errorMessage').innerHTML = "";
        autoAdjustIframeModalHeight(); 
        return Page_ClientValidate("RequiredValidation") ;
    }
    
    if(!Page_ClientValidate("BusinessRuleValidation"))
    {
        document.getElementById('errorMessage').innerHTML = "";
        autoAdjustIframeModalHeight(); 
        return Page_ClientValidate("BusinessRuleValidation") ;
    }
        
    if(!Page_ClientValidate("BusinessRuleValidationNext"))  
    {
        document.getElementById('errorMessage').innerHTML = "";
        autoAdjustIframeModalHeight(); 
        return Page_ClientValidate("BusinessRuleValidationNext") ;  
    }
    
     if(!Page_ClientValidate("OfferRuleValidation"))  
    {
        document.getElementById('errorMessage').innerHTML = "";
        autoAdjustIframeModalHeight(); 
        return Page_ClientValidate("OfferRuleValidation");  
    }
   
    var t1 = document.getElementById("columnRight_ctl00_txtStartDate").value;    
    var t2 = document.getElementById("columnRight_ctl00_txtEndDate").value;    
    
    //Total time for one day
    var one_day = 1000*60*60*24; 
   
    //Here we need to split the inputed dates to convert them into standard format    
    var x = t1.split("/");     
    var y = t2.split("/");
    
        
    //date format(Fullyear,month,date) 
    //Adding -1 to the month part as the date is gets converted to next month.
    //e.g. 2009,11,29 gets converted to Tue Dec 29 2009 00:00:00 GMT+0530 (India Standard Time) which is incorrect, putting -1 will solve this problem.
    var date1 = new Date(x[2],eval(x[0])-1,(x[1]));    
    var date2 = new Date(y[2],eval(y[0])-1,(y[1]))        
    
    //Calculate difference between the two dates, and convert to days           
    var _Diff = Math.ceil((date2.getTime()-date1.getTime())/(one_day)); 
          
     if( (_Diff) > MaxQty)
    {       
        document.getElementById('errorMessage').style.display = 'block';
        document.getElementById('errorMessage').innerHTML = "Maximum night stay cannot be exceeded";  
        autoAdjustIframeModalHeight();           
        return false;   
    } 
    
        //Offer Mandatory Rules applied
   
     var DayWeekDayStart=date1.getDay();
     var BlackoutStartConsumptionDOW = $("input[id$=hdnBlackoutStartConsumptionDOW]").val();
     var MandatoryStartConsumptionDOW = $("input[id$=hdnMandatoryStartConsumptionDOW]").val();
     var MandatoryConsumptionDOW = $("input[id$=hdnMandatoryConsumptionDOW]").val();
     var BlackoutConsumptionDOW = $("input[id$=hdnBlackoutConsumptionDOW]").val();
    if (BlackoutStartConsumptionDOW.length>0)
    {
    
        if (BlackoutStartConsumptionDOW.match(DayWeekDayStart))
        {
            document.getElementById('errorMessage').style.display = 'block';
            
            document.getElementById('errorMessage').innerHTML = $("input[id$=hdnBlackoutStartConsumptionDOWMsg]").val();   
           if (document.getElementById('columnRight_ctl00_ValidationMessage')!= undefined)
                  {
                  document.getElementById('columnRight_ctl00_ValidationMessage').style.display = 'none';
                  
                  }
            autoAdjustIframeModalHeight();              
            return false; 
        }
    }
    
     if (MandatoryStartConsumptionDOW.length>0)
    {
    
        if (!MandatoryStartConsumptionDOW.match(DayWeekDayStart))
        {
            document.getElementById('errorMessage').style.display = 'block';
            document.getElementById('errorMessage').innerHTML = $("input[id$=hdnMandatoryStartConsumptionDOWMsg]").val();   
           if (document.getElementById('columnRight_ctl00_ValidationMessage')!= undefined)
                  {
                  document.getElementById('columnRight_ctl00_ValidationMessage').style.display = 'none';
                  
                  }
            autoAdjustIframeModalHeight();              
            return false; 
        }
    }
   
     if (BlackoutConsumptionDOW.length>0)
        {
        var currentDate= date1;
            for (var i=0;i<_Diff;i++)
            {
                var date2=new Date(document.getElementById("columnRight_ctl00_txtStartDate").value)
               currentDate.setDate(date2.getDate()+i);
                 var blackoutDateString=currentDate.getDay();
                 if (BlackoutConsumptionDOW.match(blackoutDateString))
                {
                  document.getElementById('errorMessage').style.display = 'block';
                  document.getElementById('errorMessage').innerHTML = $("input[id$=hdnBlackoutConsumptionDOWMsg]").val();   
                  if (document.getElementById('columnRight_ctl00_ValidationMessage')!= undefined)
                  {
                  document.getElementById('columnRight_ctl00_ValidationMessage').style.display = 'none';
                  
                  }
                  autoAdjustIframeModalHeight();              
                  return false; 
                }
            }
        }
       
        if (MandatoryConsumptionDOW.length>0)
        {
           var daysCounter=0;
           var MandatoryDaysRequired=new Array();
           MandatoryDaysRequired=MandatoryConsumptionDOW.split(',');
            var currentDate= date1;
            for (var i=0;i<_Diff;i++)
            {
               var date2=new Date(document.getElementById("columnRight_ctl00_txtStartDate").value)
               currentDate.setDate(date2.getDate()+i);
                 var blackoutDateString=currentDate.getDay();
                 if (MandatoryConsumptionDOW.match(blackoutDateString))
                {
                   daysCounter++;         
                }
            }
            
           
            if (daysCounter!=MandatoryDaysRequired.length)
            {
                  document.getElementById('errorMessage').style.display = 'block';
                  document.getElementById('errorMessage').innerHTML = $("input[id$=hdnMandatoryConsumptionDOWMsg]").val();   
                  if (document.getElementById('columnRight_ctl00_ValidationMessage')!= undefined)
                  {
                  document.getElementById('columnRight_ctl00_ValidationMessage').style.display = 'none';
                  
                  }
                  autoAdjustIframeModalHeight();    
                  return false; 
            }
            
        }
        
      // Offer Mandatory Rules End
    
    if( (_Diff) < MinNight)
    {       
      
        document.getElementById('errorMessage').style.display = 'block';
        document.getElementById('errorMessage').innerHTML = "Minimum Night Stay";  
           autoAdjustIframeModalHeight();           
        return false;   
    } 
    else
        document.getElementById('errorMessage').style.display = 'none';
        //If offer don't have any offer week day
     if (WeekDay<0)
         return true;
    
    var day = x[1]-1;
    var WeekDayFound = false;
    // Find WeekDay
    for (i=0; i < _Diff; i++)
    {
        date1 = new Date(x[2],x[0],day);  
        if ( date1.getDay() == WeekDay )
        {
            WeekDayFound = true;            
        }
        day = day + 1;  
    }
    
    if(!WeekDayFound)
    {       
        document.getElementById('errorMessage').style.display = 'block';
        document.getElementById('errorMessage').innerHTML = "Week Day";   
        autoAdjustIframeModalHeight();              
        return false;   
    } 
    else
    {
        document.getElementById('errorMessage').style.display = 'none';
    }
    
    
    autoAdjustIframeModalHeight();         
    return true;
}
//Show Offer un-availibility message
function SetNoAvailabilityMessage(msg)
{     
     document.getElementById('errorMessagePopup').innerHTML=msg;
     return false;
}

function attachChildrenAgesModal(){
	if ( $('.childrenAgesInfoDialog').length > 0 && $('body > .ui-dialog .childrenAgesInfoDialog').length == 0 ){
	    $('.childrenAgesInfoDialog').eq(0).dialog({
	        bgiframe: true,
	        autoOpen: false,
	        width: 960,
	        height: 620,
	        modal: true,
	        resizable: false,
	        position: 'center',
	        closeOnEscape: true,
			draggable: false
	    });
	}
	
	var objModal = $('body > .ui-dialog .childrenAgesInfoDialog');

	$('[id$=hlChildrenAgesInformation]').eq(0).unbind("click").bind("click",function(e) {
	    //e.preventDefault();
    
	       // grabs url from href and loads it into the modal window
	        var urlContent = $(this).attr('href') ;

	        $('iframe', objModal)
				.attr('src',urlContent)
				.attr('width','100%')
				.attr('height','100%')
				.attr('scrolling','no');
			
			try {
				objModal.dialog('open');
			} catch (e){}
	    
        return false;
	});
}
