// JavaScript Document
var cmMonthArray = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

$(document).ready(function(){ 
 
 loadBookingDate();
 managePolicySelection($("#groupID").val()); 
 manageHasPromotionalCode();
 
 $("#groupID").change(function(){   
  managePolicySelection($("#groupID").val()); 
 });
 
 $("input[name=hasPromotionalCode]").click(function(){   
  manageHasPromotionalCode();
 });
 
 $("#departureDate").datepicker({
   showOn: 'button', 
   buttonImage: '/files/images/icons/icon-calendar.gif', 
   buttonImageOnly: true,
   numberOfMonths: 2,
   showButtonPanel: true,
   dateFormat: 'dd/mm/yy'			
 });
 
 
 
 $("#returnDate").datepicker({
   showOn: 'button', 
   buttonImage: '/files/images/icons/icon-calendar.gif', 
   buttonImageOnly: true,
   numberOfMonths: 2,
   showButtonPanel: true,
   dateFormat: 'dd/mm/yy'	
 }); 
 
  $("#departureDate").change(function(){ 										 			
	copyValueToDateOfReturn();
 });
  
   $("#over65Lnk").hover(function(e) {		
			x = e.pageX-101;		
			$('#over65Help').css("left", x + "px");
		},function() {		
			$('#over65Help').css("left", "-9999px");			
 });
   
  
 $("#quoteForm").validate({ focusInvalid: false, focusCleanup: false,

   submitHandler: function(form) {	  
	 if(businessRulesAreValid()) {		  
	  $.nyroModalManual({
       type: 'form',
	   modal: true,
	   autoSizable: true,
 	   content: getProgressDialog('Validating Quote','Please wait while we validate your information...'),
	   resizable: true, 
       autoSizable: true,
	   minWidth: 350,
	   minHeight: 170		
	  });	
	  $("#quoteForm").ajaxSubmit( { url:'/ajax/post/_validateQuote.cfm', type: 'post', success: evaluateResponse, error: evaluateResponse }); 	 
	  // document.getElementById('quoteForm').submit();  	 
	 }		
   },	
    rules: { 
	  province: "required",
	  groupID: "required",	  
	  tripPurchaseLength: {
	      required: function(element) {		   	  
	       return isTripPurchaseLengthRequired(); 
          }
	  },
	  
	  averageTripCost: {
	      required: function(element) {		   	  
	       return isAverageTripCostRequired(); 
          },
		  digits: true
	  },
	  
	 
	  
	  departureDate: "required",	 
	  returnDate: {
	      required: function(element) {		   	  
	       return isReturnDateRequired(); 
          }
	  },	  
	  oldestTraveler: "required"  
    },
	messages: {
	  province: "Please select a province",	
	  groupID: "Please select a type of insurance",	  
	  tripPurchaseLength: "Please select when you purchased your trip",
	  departureDate: "The departing field must be set with the type of policy you've selected.",
	  returnDate: "The returning field must be set with the type of policy you've selected.",	 
	  oldestTraveler: "Please select the Age of Eldest Traveller"	  
	}, 
	errorPlacement: function(error, element) {  
	  if(element.attr('id') == 'groupID') {
		 error.prependTo($('#errorMsgContainer'));
	     $('<span class="clear">&nbsp;</span>').appendTo($('#errorMsgContainer'));    
	  // window.scrollTo(0,0); 
	  }
	  else {		
	   error.appendTo($('#errorMsgContainer'));
	   $('<span class="clear">&nbsp;</span>').appendTo($('#errorMsgContainer'));  
	   //window.scrollTo(0,0); 
	  }		  
	  
	},
	showErrors: function(errorMap, errorList) {
	 this.defaultShowErrors();
	 window.scrollTo(0,0);
	}

 });
 
});


function managePolicySelection(groupID) { 
 switch(parseInt(groupID)) {
  case 31:  
   $('label[for=departureDate]').text('Departing *');	
   $('#tripPurchaseLengthContainer').css('display','block');
   $('#returningDateContainer').css('display','block'); 
   $('#totalTripCostContainer').css('display','block'); 
   if(!isDate($('#returnDate').val())) {
    $('#returnDate').val('');   
   }
   break;
  case 32: 
   $('#returnDate').val('');    
   $('#averageTripCost').val('');
   $('label[for=departureDate]').text('Start Date *');
   $('#tripPurchaseLength_1').attr('checked','');   
   $('#tripPurchaseLength_2').attr('checked','');   
   $('#tripPurchaseLengthContainer').css('display','none');
   $('#returningDateContainer').css('display','none');
   $('#totalTripCostContainer').css('display','none');
   break;
  default:
   $('label[for=departureDate]').text('Departing *');
   $('#tripPurchaseLength_1').attr('checked','');   
   $('#tripPurchaseLength_2').attr('checked','');
   $('#tripPurchaseLengthContainer').css('display','none');
   $('#returningDateContainer').css('display','block'); 
   $('#totalTripCostContainer').css('display','block'); 
   if(!isDate($('#returnDate').val())) {
    $('#returnDate').val('');   
   }
   break;
 } 
 if($('#returnDate').val() == "") {	
  copyValueToDateOfReturn();
 }
}

function manageHasPromotionalCode() {
 if($('#hasPromotionalCode_1').attr('checked')) {
	$('#promotionalCodeContainer').css('display','block');    
 }
 else if($('#hasPromotionalCode_2').attr('checked')) {
	$('#promotionalCodeContainer').css('display','none'); 
	$('#promotionCode').val('');
 }
	
}

function copyValueToDateOfReturn() { 
  if($("#groupID").val() != '32') {  
   $('#returnDate').val($('#departureDate').val());		 
  }
}

function isReturnDateRequired() {
 if($('#returningDateContainer').css('display') == 'block') {
   return true;	 
 }
 return false;	
}
function departureDateIsValid() {
 var departureDateStr = $('#departureDate').val(); 
 var tmp = departureDateStr.split("/");
 var dMonth = tmp[1]-1;  
 var dDay = tmp[0];
 var dYear =tmp[2];
 var todaysDate = new Date();
 var departureDate = new Date();
 departureDate.setMonth(dMonth);
 departureDate.setDate(dDay);
 departureDate.setFullYear(dYear); 
 if(dateCompare(todaysDate,departureDate) > 0) {
  $('<label class="error">Your Departure date must occur on or after today’s date.</label>').appendTo($('#errorMsgContainer')); 
  $('#departureDate').addClass("error");
  return false;
 } 
 return true; 
}

function returnDateIsValid() {
 var departureDateStr = $('#departureDate').val();
 var returnDateStr = $('#returnDate').val();
 var tmp = departureDateStr.split("/");
 var tmp2 = returnDateStr.split("/");
 var dMonth = tmp[1]-1;  
 var dDay = tmp[0];
 var dYear = tmp[2];
 var rMonth = tmp2[1]-1;  
 var rDay = tmp2[0];
 var rYear = tmp2[2];
 var todaysDate = new Date();
 var departureDate = new Date();
 var returnDate = new Date();
 var errorMsg = "";
 departureDate.setMonth(dMonth);
 departureDate.setDate(dDay);
 departureDate.setFullYear(dYear);
 returnDate.setMonth(rMonth);
 returnDate.setDate(rDay);
 returnDate.setFullYear(rYear); 
 if(dateCompare(departureDate,returnDate) > 0) {
  $('<label class="error">Returning date must occur on or after your Departing date.</label>').appendTo($('#errorMsgContainer')); 
  $('#returnDate').addClass("error");
  return false;	 
 }
 return true;
}


function businessRulesAreValid() {
 var result = true; 
   if(!departureDateIsValid()) {
	 result = false;
   }
 
 if(isReturnDateRequired()) {
  if(!returnDateIsValid()) {	 
   result = false;
  }
 } 
 return result;
}

function dateCompare(date1,date2) {	
 var result = 0;	
 if(Date.parse(date1) < Date.parse(date2)){
  result = -1;							   
 }
 else if(Date.parse(date1) == Date.parse(date2)){
  result = 0;							   
 }
 else if(Date.parse(date1) > Date.parse(date2)){
  result = 1;							   
 }  
 return result;
}

function dateDiff(date1,date2) { 
 var diff = Math.ceil((date2.getTime()-date1.getTime()))/(1000*60*60*24);
 return diff;
}

function loadBookingDate() {
 var todaysDate = new Date();
 var formattedDate = todaysDate.getMonth()*1+1+'/'+todaysDate.getDate()+'/'+todaysDate.getFullYear();
 $('#bookingDate').val(formattedDate);
}


function evaluateResponse(response) {
 var response = $.trim(response);
 document.getElementById('quoteForm').submit(); 
 /*if(response == 'success') {
  document.getElementById('quoteForm').submit(); 
 }
 else {
  updateDialog('error','There are issues with your quote information.'); 	 
  $('#errorMsgContainer').html(response);
  window.scroll(0,0);
 }*/
 //document.write(response);
}

function getProgressDialog(title,msg) {
 var oContainerDiv = document.createElement("div");
 var oHeaderDiv = document.createElement("div");
 var oTitleDiv = document.createElement("div"); 
 var oActionDiv = document.createElement("div");
 var oInteriorDiv = document.createElement("div");
 var oButtonsDiv = document.createElement("div");
 
 oHeaderDiv.className='modalHeader';
 oTitleDiv.className='modalTitle';
 oActionDiv.className='modalAction';
 oInteriorDiv.className='modalInterior progress';
 oButtonsDiv.className='modalButtons';
 
 oTitleDiv.innerHTML='<h2>'+title+'</h2>';
 oActionDiv.innerHTML='';
 oHeaderDiv.appendChild(oTitleDiv);
 oHeaderDiv.appendChild(oActionDiv);
 oInteriorDiv.innerHTML=msg; 
 oButtonsDiv.innerHTML='<input type="button" value="0K" onclick="$.nyroModalRemove();" id="primaryDialogButton" />';
 
 oContainerDiv.appendChild(oHeaderDiv);
 oContainerDiv.appendChild(oInteriorDiv);
 oContainerDiv.appendChild(oButtonsDiv);
 
 return oContainerDiv.innerHTML;
}

function updateDialog(type,msg) {
 switch(type) { 
  case 'error':   
   $('.modalInterior').removeClass("progress");
   $('.modalInterior').addClass("error");
   $('.modalInterior').html(msg);
   $('.modalButtons').css('display','block');	
   break;  
 case 'expire':
   $('.modalInterior').removeClass("progress");
   $('.modalInterior').addClass("error");
   $('.modalInterior').html(msg);
   $("#primaryDialogButton").click(function(){								
     top.window.location=location.href;											
     return false;
   });
   $('.modalButtons').css('display','block');	   
   break;
 }  
}

function isTripPurchaseLengthRequired() {
 if($("#groupID").val() == '31') {  
   return true;
 }	
 return false;	
}

function isAverageTripCostRequired() {
 if($("#groupID").val() ==	'31') {  
   return true;
 }	
 return false;	
}

function isDate(dateStr) {	
 var tmp = dateStr.split("/");  
 if(tmp.length != 3) {
  return false; 
 }
 else {	 
  var month = tmp[1]-1;  
  var day = tmp[0]; 
  var year = tmp[2];
  
  
  
  if(isValidDate(month,day,year) != true) {	
    if(isValidDay(day, month)) {
	 return true;	
	}
	else {
     return false;
	}	   
  }
  else {
	return true;  
  }
 } 	
}

function isValidDate(month,day,year) { 
 if(year < 1900 || year > 9999 || isNaN(year)) { 
  return 'year';
 }
 if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {	
  cmMonthArray[1] = "29";
 }  
 if(month < 1 || month > 12 || isNaN(month)) { 
  return 'month';
 } 
 if(day < 1 || day > cmMonthArray[(month-1)] || isNaN(day)) {  
  return 'day';
 }
 //alert(cmMonthArray[(month-1)]);
 return true;
}

function isValidMonth(month) {
 if(isNaN(month) || month < 1 || month > 12) {
  return false;
 }
 return true;
}

function isValidDay(day, month) {	
 if(isNaN(day) || day < 1 || day > cmMonthArray[month]) {  
  return false;
 }
 return true;
}

function isValidYear(year) {
 var date = new Date();
 var topYear = date.getFullYear()*1+10;
  
 if(isNaN(year) || year < 2006 || year > topYear) {   
  return false;
 }
 return true;  
}
