var timer;
var galleryRequest;

/*===============================
  ---------------------------------
  Tesoro Javascript File
  Prepared by: CDG Interactive
  ===============================*/

  /*===============================
  ---------------------------------
  JQuery Functions
  ===============================*/
 

$(document).ready(function(){
						   
//separate picker for Euro date format for Spanish version added by JN 2-15-10					   
// Calendar
if(window.location.href.indexOf('tesororesorts.com.mx') == -1) {

$('#f_date_c1').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true}); 
$('#f_date_c2').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true});

var ourDateEn = generateDateEn();
var ourDateOutEn = generateDateOutEn()
//$('#f_date_c1').attr('value') = ourDate;
document.getElementById('f_date_c1').value = ourDateEn;
document.getElementById('f_date_c2').value = ourDateOutEn;


}
 
else {
//alert('test');
$('#f_date_c1').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true, dateFormat:'dd/mm/yy'}); 
$('#f_date_c2').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true, dateFormat:'dd/mm/yy'});
var ourDate = generateDate();
var ourDateOut = generateDateOut()
//$('#f_date_c1').attr('value') = ourDate;
document.getElementById('f_date_c1').value = ourDate;
document.getElementById('f_date_c2').value = ourDateOut;

}


//Booking Form Calendar - Added 10/02/08				
$('#date1').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true}); 
$('#date2').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true});

	/* Booking Form - Added 10/02/08 */
	$('div.bookairfareform a').click(function() {
		$('span.bookingscreen').css('display','block');
     	$('div.bookinglayer').css('display','block');
   });

	$('div#itravel_booking_engine a.closewindow').click(function() {
     	$('span.bookingscreen').css('display','none');
     	$('div.bookinglayer').css('display','none');
		return false;
   });
	
		var cover = $('body').height();
	
	$('span.bookingscreen').css('height', cover + 'px');
	$('div.bookinglayer').css('height', cover + 'px');
	/* Added 10/02/08 */

// GETS THE CURRENT PAGE'S UNIQUE IDENTIFIER
	var docId = $('.background').attr('id');	

/*	Flash Stuff 
	 ----------------------------*/
	if (docId == 'homepage-flash' || docId == 'adventure-flash') 
		$('.background').flash({ 
					src: '/frame-images/tesoro_com/flash/tesoro_frame.swf',
					//width: 1185,
					//height: 703,
					width: 1000,
					height: 593,
					wmode: 'transparent'
				},
				{version: 8.0},
				function(htmlOptions) {
           		 	$this = $(this);
            		htmlOptions.flashvars.selectPAGE = parseInt(document.getElementById('navVar').innerHTML);
            		$this.append($.fn.flash.transform(htmlOptions));	
					$(this).css('background-image', 'none');	
					
        		}
		);		
		
	else {
		$('.flash-nav').flash({ 
					src: '/frame-images/tesoro_com/flash/tesoro_nav_landing.swf',
					width: 923,
					height: 100,
					wmode: 'transparent'
				},
				{version: 8.0},
				function(htmlOptions) {
           		 	$this = $(this);					
            		htmlOptions.flashvars.selectPAGE = parseInt(document.getElementById('navVar').innerHTML);
            		$this.append($.fn.flash.transform(htmlOptions));						
        		}
		);
		
		
		
	}
	
	// featured destinations control
	if($(".featured")) {
			$(".featured a").click(		
		function() {	
		$(this).siblings("a").removeClass("hit");
				$(this).addClass("hit");
		}
	  );
	};	
	
	if($("#photoGalleryControl")) {
			$("#prevControl").click(		
		function() {	
		if(timer) {
		 getPhotoGalleryContent('-','on');			 
		}
		else {
		 getPhotoGalleryContent('-','off');	
		}
		}
	  );
	};
	
	if($("#photoGalleryControl")) {
			$("#nextControl").click(		
		function() {	
		if(timer) {
		 getPhotoGalleryContent('-','on');			 
		}
		else {
		 getPhotoGalleryContent('-','off');	
		}
		}
	  );
	};	
	
	if($(".slideshow")) {
			$(".slideshow a").click(		
		function() {			
			if(!timer) {			
			 document.getElementById('slideShowToggleImg').src=document.getElementById('slideShowToggleImg').src.replace(/off/,"on");
			 startSlideShow();
			}
			else {			 			 
			 stopSlideShow();				 
			 document.getElementById('slideShowToggleImg').src=document.getElementById('slideShowToggleImg').src.replace("\/on\/","/off/");
			}
		
		}
	  );
	};
	
	$(".col-1 ul li a img").hover(	
		function() {			
		 offImg = $(this).attr('src');
		 overImg = $(this).attr('src').replace('Nav_Images/off/','Nav_Images/on/');
		 $(this).attr('src', overImg);		
		},		
		function() {	
		 $(this).attr('src', offImg);	
		}		
	);
	$("input.submit, input.sub, a.sub img").hover(	
		function() {
			offImg = $(this).attr('src');					
			overImg = offImg.replace('buttons/off/', 'buttons/on/');									
			$(this).attr('src', overImg);	
			//alert(offImg + "   " + overImg);
		},
		function() {		
			$(this).attr('src', offImg);
		}
	);
	$(".col-3 .center img").hover(	
		function() {
			offImg = $(this).attr('src');					
			overImg = offImg.replace('headers', 'headers/on');									
			$(this).attr('src', overImg);	
			//alert(offImg + "   " + overImg);
		},
		function() {		
			$(this).attr('src', offImg);
		}	
		
	);
	
	$(".package_details ul li.last img").hover(	
		function() {
			offImg = $(this).attr('src');					
			overImg = offImg.replace('buttons/off/', 'buttons/on/');									
			$(this).attr('src', overImg);
		},
		function() {		
			$(this).attr('src', offImg);	
		}	
		
	);
	
	
	
	
	
	
	
	
	
	
	
	
	
/*	Background Picker
 	 ----------------------------
		var bgImg = new Array ('images/html/one.html', 'images/backgrounds/resort-landing.jpg')
		var i = 0;
		var numOfImgs = bgImg.length;
		//alert(bgImg[i]);
		$('a.next').click(function(){
				//alert(i);
			var imgNum = numOfImgs - 1;
			if (i < 0) {
				//alert(i);
				//alert(imgNum);
				return i = imgNum;
			}
			var bgImgPath = 'url(' + bgImg[i] + ')';
			$('.background').css('background-image', bgImgPath);	
			
			//alert(imgNum);
			return i = i + 1;
		});
		$('a.prev').click(function(){
			//alert(i);
			var imgNum = numOfImgs - 1;
			if (i < 0) {
				//alert(i);
				//alert(imgNum);
				return i = imgNum;
			}
			var bgImgPath = 'url(' + bgImg[i] + ')';
			$('.background').css('background-image', bgImgPath);	
			
			//alert(imgNum);
			return i = i - 1;
			
		});*/
		

		
/* Flash Content Clipper
   ------------------------------------------*/


  
  
function clipPage(){



// GETS THE WIDTH OF THE VIEWING PORT	
	var de = document.documentElement;     
	var bodyWidth = window.innerWidth-20 || self.innerWidth-20 || (de&&de.clientWidth) || document.body.clientWidth;  

		
// REPRESENTS THE WIDTH OF THE CONTENT BEING DISPLAYED	
		var contentWidth = parseInt(1000);
		if ( contentWidth >= bodyWidth){	
			var clipLength = (0 - ((contentWidth - bodyWidth) / 2));
			$('.background').css('margin-left', clipLength);
		}
		
		else {
			var clipLength = parseInt([bodyWidth - contentWidth] / 2);
			$('.background').css('margin-left', clipLength);
		}
	}
		
// EXECUTES ONLY IF THE CURRENT PAGE IS THE HOMEPAGE		
		if (docId == 'homepage-flash' || docId == 'adventure-flash'){{
			clipPage();
			
			$(window).resize( function() {
				var de = document.documentElement;  
				var bodyWidth = window.innerWidth-20 || self.innerWidth-20 || (de&&de.clientWidth) || document.body.clientWidth;  
				clipPage();	
			});	
		}}
/*  Roll over image
    ------------------------------------------------ */
	
	$(".col-1 ul li a img").hover(	

		function() {
			var offImg = $(this).attr('src');
			
			var overImg = offImg.replace('nav_images/off/','nav_images/on/');
			
																							
			$(this).attr('src', overImg);	
		},		
		function() {		
		//alert(offImg);
			$(this).attr('src', offImg);
		}		
	);
	
/*	add JN 062608*/
	                $(".rfpsubmit").hover(        
                                function() {                                         
                                                off_img = $(this).attr('src');                                         
                                                over_img = off_img.replace('off/','on/');                                                                                                                                                                                                                                                                                                              
                                                $(this).attr('src', over_img);                        
                                },                             
                                function() {                         
                                                $(this).attr('src', off_img);
                                }
                );
/*	end add JN 062608*/
	
	
	
	
	//$('#f_date_c1').datepicker({showOn: 'both', buttonImage: '/frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true}); 
    //$('#f_date_c2').datepicker({showOn: 'both', buttonImage: '/frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true});
	
});  /*end of ready function JN*/

function getPage(url) { 
 var temp = url.split("=");
 var pageID = temp[1];	

  AjaxRequest.get(
  {
   'url':'/actions/getContent.cfm?parm1='+pageID
   ,'onSuccess':function(req){ displayContent(req.responseText,pageID); }
   ,'onError':function(req){ errorHandler(req.responseText);  }   
  }
  );	 	    
 
}

function displayContent(str,pageID) { 
 // pages dynamically retrieved from the home page
 
 //document.write(str);
 if(document.getElementById('homepage-flash')) {	
  // if the pageID is homepage check for homepage container
  if(pageID == 10) {
   if(!document.getElementById('homepage')) {  
	document.getElementById('adventure').setAttribute('id','homepage');     
   }
  }
  else {
   if(!document.getElementById('adventure')) {
	document.getElementById('homepage').setAttribute('id','adventure');
   }  
  }  
 }
 // pages dynamically retrieved from the interior
 else {	  
  // if the pageID is homepage check for homepage container
  if(pageID == 10) {
   if(!document.getElementById('homepage')) {
    document.getElementById('adventure').setAttribute('id','homepage');  	   
   }
  }
  else {
   if(!document.getElementById('adventure')) {
	document.getElementById('homepage').setAttribute('id','adventure');
   }	  
  }   
 } 
 $(document.getElementById('loadContainer')).hide();      	  
 document.getElementById('loadContainer').innerHTML=str;
 $(document.getElementById('loadContainer')).show();
 bindEvents();
}

function getFeaturedDestination(pageID) { 
  AjaxRequest.get(
  {
   'url':'/actions/getFeaturedDestination.cfm?pageID='+pageID
   ,'onSuccess':function(req){ displayFeaturedDestination(req.responseText,pageID); }
   ,'onError':function(req){ errorHandler(req.responseText);  }   
  }
  );	
}

function displayFeaturedDestination(str) {
	//alert('test');
// $(document.getElementById('loadFeaturedDestination')).hide();    
 
 document.getElementById('loadFeaturedDestination').style.display='none';
 
 document.getElementById('loadFeaturedDestination').innerHTML=str;
 //$(document.getElementById('loadFeaturedDestination')).fadeIn(1000); 
 document.getElementById('loadFeaturedDestination').style.display='inline';
 //$(this).className('hit');
}

function calendar(ids) {	
	var i = 1;
	for (i=1; i<=ids; i++) {	
	    Calendar.setup({
	        inputField     :    "f_date_c"+i,     // id of the input field, "f_date_c" with "i" suffix
	        ifFormat       :    "%m/%d/%Y",      // format of the input field (MM/DD/YYYY)
	        button         :    "f_trigger_c"+i,  // trigger for the calendar (button ID), "f_trigger_c" with "i" suffix
	        align          :    "Tr",           // alignment (defaults to "Bl")
	        singleClick    :    true,
			weekNumbers	   :    false			//showing week numbers - default is true
	    });				
	}			
}

function bindEvents() {		
	//alert('test');
	
	$('#f_date_c1').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true}); 
$('#f_date_c2').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true});
	
	$('#date1').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true}); 
$('#date2').datepicker({showOn: 'both', buttonImage: 'frame-images/tesoro_com/buttons/calendar.gif', buttonImageOnly: true});
	
	
	
	$('div.bookairfareform a').click(function() {	
	   $('span.bookingscreen').css('display','block');
       $('div.bookinglayer').css('display','block');
   });	
	
	if($(".featured")) {
			$(".featured a").click(		
		function() {	
		$(this).siblings("a").removeClass("hit");
				$(this).addClass("hit");
		}
	  );
	};
	
	if($("#photoGalleryControl")) {
			$("#prevControl").click(		
		function() {	
		if(timer) {
		 getPhotoGalleryContent('-','on');			 
		}
		else {
		 getPhotoGalleryContent('-','off');	
		}
		}
	  );
	};
	
	if($("#photoGalleryControl")) {
			$("#nextControl").click(		
		function() {	
		if(timer) {
		 getPhotoGalleryContent('-','on');			 
		}
		else {
		 getPhotoGalleryContent('-','off');	
		}
		}
	  );
	};
	
	if($(".slideshow")) {
			$(".slideshow a").click(		
		function() {			
			if(!timer) {			
			 document.getElementById('slideShowToggleImg').src=document.getElementById('slideShowToggleImg').src.replace(/off/,"on");
			 startSlideShow();
			}
			else {			 			 
			 stopSlideShow();				 
			 document.getElementById('slideShowToggleImg').src=document.getElementById('slideShowToggleImg').src.replace("\/on\/","/off/");
			}
		
		}
	  );
	};
	//alert('test');
	//calendar(2);
}

function getPhoto(direction) {
 var maxImageIdx = parseInt(document.getElementById('maxImgIdx').innerHTML);	
 var currentIdx = parseInt(document.getElementById('imgIdx').innerHTML); 
 var imageSource = document.getElementById('srcDirectory').innerHTML;
 var newIdx;
 
 switch(direction) {
  case '-':
   if(currentIdx != 1) {
    newIdx = currentIdx - 1;
   } 
   else {
	newIdx = maxImageIdx;   
   }
   break;
  case '+':
   if(currentIdx != maxImageIdx) {
    newIdx = currentIdx*1+1;
   }
   else {
	newIdx = 1;   
   }
   break; 
 }
 document.getElementById('imgIdx').innerHTML=newIdx;
 
AjaxRequest.get(
  {
   'url':'/actions/getPhoto.cfm?imageSource='+escape(imageSource)+'&imageIdx='+newIdx
   ,'onSuccess':function(req){ changePhoto(req.responseText); }
   ,'onError':function(req){ errorHandler(req.responseText);  }   
  }
  );
 
	
}


function changePhoto(str) {

 $(document.getElementById('photoLoadContainer')).hide();      	   
 document.getElementById('photoChangerImg').src = str;	
 $(document.getElementById('photoLoadContainer')).fadeIn(1000); 
}

function getPhotoGalleryContent(control,sh) {	
	var navID = parseInt(document.getElementById('photoGalleryContainerID').innerHTML);
	var idx = parseInt(document.getElementById('photoGalleryIdx').innerHTML);
	
	 var newIdx = 1;
	 if(control == '-') {
      	 
	  newIdx = idx*1-1;	
	 }
	 else {
	  newIdx = idx*1+1;	 
	  
	 }
	
	 galleryRequest = AjaxRequest.get(
  {
   'url':'/actions/getPhotoGallery.cfm?navID='+navID+'&idx='+newIdx+'&sh='+sh
   ,'onSuccess':function(req){ displayPhotoGalleryContent(req.responseText); }
   ,'onError':function(req){ errorHandler(req.responseText);  }   
  }
  );	
	 
	}


function displayPhotoGalleryContent(str) {
 document.getElementById('photoGalleryLoadContainer').style.display='none'; 
 document.getElementById('photoGalleryLoadContainer').innerHTML=str; 
 document.getElementById('photoGalleryLoadContainer').style.display='inline'; 
 $(document.getElementById('photoGalleryImageContainer')).fadeIn(1000);
 bindEvents();
}

function startSlideShow(navID,idx,control) {	
 timer = window.setInterval("getPhotoGalleryContent('+','on');",5000);	  
}

function stopSlideShow() {	
 timer = clearInterval(timer);
 timer = null; 

}


function requestReservation() {
 if(validateReservation()) {  
  pageTracker._trackPageview('/synxis/https://reservations.synxis.com/XBE/rez.aspx?Hotel='+document.getElementById('destination').value+'&Chain=5150&template=GCO&shell=Def&locale=en-US&arrive='+document.getElementById('f_date_c1').value+'&depart='+document.getElementById('f_date_c2').value+'&adult='+document.getElementById('adults').value+'&child='+document.getElementById('children').value+'&promo='+document.getElementById('promotionCode').value);
  if(window.location.href.indexOf('tesororesorts.com.mx') == -1) {
  window.open('https://gc.synxis.com/rez.aspx?Hotel='+document.getElementById('destination').value+'&Chain=5150&template=GCO&shell=Def&locale=en-US&arrive='+document.getElementById('f_date_c1').value+'&depart='+document.getElementById('f_date_c2').value+'&adult='+document.getElementById('adults').value+'&child='+document.getElementById('children').value+'&promo='+document.getElementById('promotionCode').value);
		}
		
  else {
   
   window.open('https://gc.synxis.com/rez.aspx?Hotel='+document.getElementById('destination').value+'&Chain=5150&template=GCO&shell=Def&locale=es-MX&arrive='+document.getElementById('f_date_c1').value+'&depart='+document.getElementById('f_date_c2').value+'&adult='+document.getElementById('adults').value+'&child='+document.getElementById('children').value+'&promo='+document.getElementById('promotionCode').value);
  }
  
 }	
 return false;
}

function validateReservation() {
 clearErrors();
 var checkInDate = 	getJSDate(document.getElementById('f_date_c1').value);
 var checkOutDate = getJSDate(document.getElementById('f_date_c2').value);
 var todaysDate = new Date();
 
 if(dateCompare(checkInDate,todaysDate) < 0) {
  setError('f_date_c1','Check in date must be today or later.'); 
 }
 else if(dateCompare(checkInDate,checkOutDate) != -1) {
  setError('f_date_c1','');
  setError('f_date_c2','Check out date must be a date later than check in date.');
 }
 if(isBlank(document.getElementById('destination'))) {
  setError('destination','Destination is a required field.');  
 }
 
 if(formHasErrors()) {
  displayErrorMessages();
  return false;
 }
 return true; 
}

function getJSDate(strDate) {
 var temp = strDate.split("/");	
 var month = temp[0]-1;
 var day = temp[1];
 var year = temp[2];
 var dateObj = new Date();	
 dateObj.setDate(1);
 dateObj.setFullYear(year);
 dateObj.setMonth(month);
 dateObj.setDate(day);
 
 return dateObj; 
	
}

function emailSignUp() {
 if(validateEmailSignUp()) {
	 AjaxRequest.get(
  {
   'url':'/actions/emailSignup.cfm?email='+document.getElementById('email').value
   ,'onSuccess':function(req){ evaluateEmailSignUpResponse(req.responseText); }
   ,'onError':function(req){ errorHandler(req.responseText);  }   
  }
  );
	 
	 
 }
	
}

function validateEmailSignUp() {
 clearErrors2();
 if(!isValidEmail(document.getElementById('email'))) {
  setError('email','Email address is a required field.');  
 }
 if(formHasErrors()) {
  displayErrorMessages2();
  return false;
 }
 return true; 
	
}

function  evaluateEmailSignUpResponse(str) { 
 document.getElementById('email').value='';
 alert("registration Complete");	
}



function validateTAContact() {
	clearErrors4();
	
	if(isBlank(document.getElementById('f_firstName'))){
		setError('f_firstName','First Name is a required field.');
	}
	if(isBlank(document.getElementById('f_lastName'))){
		setError('f_lastName','Last Name is a required field.');
	}
	if(isBlank(document.getElementById('f_email'))){
		setError('f_email','Email address is a required field.');
	}
	else if(!isValidEmail(document.getElementById('f_email'))) {
  		setError('f_email','Email should be in the correct format.');  
 	}
	if(isBlank(document.getElementById('f_city'))){
		setError('f_city','City is a required field.');
	}
	if(isBlank(document.getElementById('f_state'))){
		setError('f_state','State is a required field.');
	}
	if(isBlank(document.getElementById('f_phone1'))){
		setError('f_phone1','Daytime Phone is a required field.');
	}
	
	
	if(formHasErrors()) {
		displayErrorMessages4();
		return false;
	}
	return true;
}

function validateTOContact() {
	clearErrors4();
	
	if(isBlank(document.getElementById('f_firstName'))){
		setError('f_firstName','First Name is a required field.');
	}
	if(isBlank(document.getElementById('f_lastName'))){
		setError('f_lastName','Last Name is a required field.');
	}
	if(isBlank(document.getElementById('f_email'))){
		setError('f_email','Email address is a required field.');
	}
	else if(!isValidEmail(document.getElementById('f_email'))) {
  		setError('f_email','Email should be in the correct format.');  
 	}
	if(isBlank(document.getElementById('f_zip'))){
		setError('f_zip','Zip is a required field.');
	}	
	
	if(formHasErrors()) {
		displayErrorMessages4();
		return false;
	}
	return true;
}


function  generateDate() { 

var date = new Date();
var d  = date.getDate();
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;

var eurodate = day + "/" + month + "/" + year;
//alert('hi');
//alert(eurodate);

return eurodate
}


function  generateDateOut() { 

var date = new Date();
var d  = date.getDate() + 3;
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;

var eurodateOut = day + "/" + month + "/" + year;
//alert('hi');
//alert(eurodate);

return eurodateOut
}

function  generateDateEn() { 

var date = new Date();
var d  = date.getDate();
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;

var eurodate = month + "/" + day + "/" + year;
//alert('hi');
//alert(eurodate);

return eurodate
}


function  generateDateOutEn() { 

var date = new Date();
var d  = date.getDate() + 3;
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;

var eurodateOut = month + "/" + day + "/" + year;
//alert('hi');
//alert(eurodate);

return eurodateOut
}
