/*! 
 *  Thomas Cook - Javascript Document
 *
 *  URI         : http://www.thomascook.de
 *  Version     : v0.2
 *  Version Date: Friday, November 26, 2010
 */

var tempDate = '';
var dateDiff = 22;
var now = new Date();
now = new Date(now.getFullYear(), now.getMonth(), now.getDate());

jQuery(function($){
	//on document click hide option list of duration dropdown 
	$(document).click(function(){
		$(".stayDropdown").hide();
	});
    //destination input wrapper
    jQuery(".destinationLayerContainer input.swArrowIcon").wrap("<div class='swArrowIconWrapper' tabindex='-1'></div>");
	var initSelect=$(".staySelect option:selected").text();
	var stayWidth=$(".staySelect").outerWidth();
	stayWidth=stayWidth-2;
	if(initSelect.substr(0,10)!="Reisedauer"){
		jQuery(".staySelect").find("option:first").remove();
		jQuery(".staySelect").next("span.replacementSelect").hide();
	}else{
			jQuery(".staySelect").find("option:first").remove();
			$(".staySelect").each(function() {
				$(this).attr('selectedIndex', '-1'); 
			});
	}
	var $options = $("#durationSelect").children(),
	$dropdown = $('<ul class="stayDropdown" style="display:none; width:'+stayWidth+'px;"/>');  
	$options.each(function() {
		if($(this).is("optgroup")){
			$dropdown.append('<p style="padding-left:2px;">'+$(this).attr("label")+'</p>');
		}else{
			$dropdown.append('<li id="'+$(this).val()+'">'+ $(this).text() + '</li>');
		}
	});
	$dropdown.insertAfter(".replacementSelect");
	if ( $.browser.msie ){
		$(".stayDropdown").css("height", "380px");
	} 
	if ($.browser.webkit) {
		var userAgent = navigator.userAgent.toLowerCase();
		if ( userAgent.indexOf("chrome") === -1 ) { 
			$(".stayDropdown").css("height", "310px");
			$(".stayDropdown li").css("line-height", "15px");
		}
	}
	$(".replacementSelect").click(function(e){
		e.stopPropagation();
		$(this).next(".stayDropdown").toggle();

	});
	$(".staySelect").click(function(e){
		$(this).next().next(".stayDropdown").hide();
	});
	$(".stayDropdown li").click(function(){
		var value=$(this).attr("id");
		$(this).parent().prev().prev(".staySelect").each(function(){
			$('option[value="'+value+'"]',this).attr("selected", "selected");
		});
		$(this).parent().hide();
		$(this).parent().prev("span.replacementSelect").hide();
	});
	jQuery(".staySelect").change(function(){
		jQuery(this).next("span.replacementSelect").hide();
	});
	jQuery("#spTabs li a").mousedown(function(){
		jQuery("span.replacementSelect:hidden").show('fast', function(){
				$(".staySelect").attr('selectedIndex', '-1'); 
		});	
	});
	jQuery('form[action*=deDestinationRegions]').submit(function() {
		jQuery('.staySelect').each(function(){
			var selVal=jQuery(this).val();
			if(!selVal){
				jQuery('option[value="-1"]', this).attr('selected', 'selected'); 
			}
		});
	});
	//navigator.userAgent.indexOf('MSIE');	
	jQuery('.subSearchPanel input[disabled]').css('background-color','#E5E5E5');
	jQuery('.subSearchPanel select[disabled]').css('background-color','#E5E5E5');	
	if($.browser.msie && parseInt($.browser.version) === 6){
		jQuery('#mainMenu li ul').bgiframe();
		$('#mainMenu li').hover(
			function(){
				$(this).addClass('sfhover');
			},
			function(){
				$(this).removeClass('sfhover');
			}
		);
	}
	highLight();
	thumbView();
	jQuery(".spKalInput, .sspKalInput").click(function(){
		tempDate = jQuery(this).val() || '';
		jQuery(this).focus();
		jQuery(this).select();
	});
	jQuery(".spKalInput, .sspKalInput").change(function(){
		var dateText = jQuery(this).val() || '';
		if(getTimestampFromString(dateText,true) == -1){				
				var defDate = new Date(getTimestampFromString(tempDate));
				jQuery(this).datepicker("setDate", defDate);
		} else{
			var deDate = new Date(getTimestampFromString(dateText));
			jQuery(this).datepicker("setDate", deDate);
		}
		formChanged = true;
	});
	jQuery(".spKalInput").datepicker({
		minDate: +1,
		maxDate: +450,
		beforeShow: function(input, inst){
			tempDate = input.value || '';
			tempID = jQuery(this).attr('class').split(' ')[2] || '';
			if(jQuery(this).hasClass('toDate')){
				var dDate = new Date(jQuery('#'+ tempID + ' .fromDate').datepicker('getDate')).getTime();				
				dDate = Math.ceil((dDate - new Date().getTime())/(1000 * 60 * 60 * 24));				
				jQuery(this).datepicker('option','minDate', +dDate);
			}
		},
		onSelect: function(dateText, inst){			
			if(jQuery(this).hasClass('fromDate')){				
				tempID = jQuery(this).attr('class').split(' ')[2] || '';
				var dDate = new Date(jQuery('#'+ tempID + ' .toDate').datepicker('getDate')).getTime();
				dDate = Math.ceil((dDate - getTimestampFromString(dateText))/(1000 * 60 * 60 * 24));
				if(dDate <= 0){					
					dDate = Math.floor((getTimestampFromString(dateText) - now.getTime())/(1000 * 60 * 60 * 24));					
					dDate += dateDiff;
					if(dDate >= jQuery(this).datepicker('option','maxDate')){
						jQuery('#'+ tempID + ' .toDate').datepicker('option','maxDate', +451);
					}
					jQuery('#'+ tempID + ' .toDate').datepicker('setDate', +dDate);
				}
			}
		}
	});
	jQuery(".sspKalInput").datepicker({ 
		minDate: +1,
		maxDate: +450,
		beforeShow: function(input, inst){
			tempDate = input.value || '';
			if(jQuery(this).hasClass('toDate')){
				var dDate = new Date(jQuery('.fromDate').datepicker('getDate')).getTime();				
				dDate = Math.ceil((dDate - new Date().getTime())/(1000 * 60 * 60 * 24));				
				dDate += 0; 
				jQuery(this).datepicker('option','minDate', +dDate);
			}
		},
		onSelect: function(dateText, inst){
			if(jQuery(this).hasClass('fromDate')){
				var dDate = new Date(jQuery('.toDate').datepicker('getDate')).getTime();
				dDate = Math.ceil((dDate - getTimestampFromString(dateText))/(1000 * 60 * 60 * 24));
				if(dDate <= 0){
					dDate = Math.floor((getTimestampFromString(dateText) - now.getTime())/(1000 * 60 * 60 * 24));					
					dDate += dateDiff;
					if(dDate >= jQuery(this).datepicker('option','maxDate')){
						jQuery('.toDate').datepicker('option','maxDate', +451);
					}
					jQuery('.toDate').datepicker('setDate', +dDate);
				}
			}
			formChanged = true;
		}
	});
	/*
	jQuery('form[action*=deDestinationRegions]').submit(function(e){
		var durationValue = jQuery('#durationSelect').val();
		if(durationValue == -1) jQuery('#durationSelect').val('1');
	});
	*/
	/** START  OF CODE MODIFICATION FOR DE – 1958:
	 * Description: js code corrected to open the result popup for hotelinfos
	 * AUTHOR: Madhan
	**/
	jQuery('.resortListSelected .colD .linkNext').live('click', function(event){
		event.preventDefault();
		var currResortID = jQuery(this).parent().children('img').attr('id');
		currResortID = currResortID.replace("LINK","#ID");
		currResortID = currResortID + " .colD .linkNext";
		jQuery(currResortID).trigger('onclick');
	});
	/**  END  OF  CODE MODIFICATION FOR DE – 1958:
	**/
	
});

/* Footer Links */
function toggleOneFooter(div)
{
	var option=['ofn1','ofn2','ofn3','ofn4','ofn5']; 
	for(var i=0; i<option.length; i++) { 
		obj=document.getElementById(option[i]);
		obj.style.display=(option[i]==div) && !(obj.style.display=="block")? "block" : "none"; 
	}
}

/* Tool Tip */
function tipText(txt){
	jQuery('.toolTipText').tooltip({
		track: true,
		bodyHandler: function(){
			return txt;
		},
		showURL: false
	});
}

/* Home Search Panel */
function hspTabs(){
	jQuery('#spTabs a').click(function() {
		var currID = jQuery(this).text();
		var parameter = jQuery(this).attr('rel');
		document.getElementById(parameter+'PageId').value = parameter;
		if(!jQuery(this).hasClass('inactiveTabs')){
			jQuery('#spTabs li').removeClass('activeSPTabs');
			jQuery(this).parent('li').addClass('activeSPTabs');
			jQuery('.spWrap').hide();
			currID = '#' + currID;								
			jQuery(currID).show();
			jQuery(currID).find('form').get(0).reset();
            AjaxSearchTools.resetSearchBean()
		}
		
	});
}

/* Reisen Search Panel */
function rspTabs(){
	jQuery('#reisenSPTabs a').click(function() {
		var currRSPID = jQuery(this).text();
		//var parameter = jQuery(this).attr('rel');
		//document.getElementById(parameter+'PageId').value = parameter;
		if(!jQuery(this).hasClass('inactiveTabs')){
			jQuery('#reisenSPTabs a').removeClass('activeReisenSPTabs');
			jQuery(this).addClass('activeReisenSPTabs');
			jQuery('.reisenSP').hide();
			currRSPID = '#' + currRSPID;								
			jQuery(currRSPID).show();
            //AjaxSearchTools.resetSearchBean()
		}
	});
}

/* Hotelauswahl - Thumbnail View */
function thumbView(){
	jQuery('.hotelSelection .hotelThumb').hover(
		function(){
			var img = jQuery(this).children('a').children('img').attr('src');
			if(img.indexOf("booking_thumbs_w_mi")>=0) {
				img = img.replace('booking_thumbs_w_mi','booking_thumbs_gr');
			} else if(img.indexOf("FW_thumbs_w_mi")>=0) {
				img = img.replace('FW_thumbs_w_mi','FW_thumbs_w_gr');
			}
			var pos = jQuery(this).offset();
			jQuery('#hotelBig').html('<div><img src="' + img + '" alt="" /></div>')
			jQuery('#hotelBig').css({
				'position': 'absolute',
				'top': pos.top,
				'left': (pos.left + 185)
			}).show();
		}, 
		function () {
			jQuery('#hotelBig').empty().hide();
		}
	);
}

/* Reisetermin - Wait Page */
var  previousId = -1;
var  cancel = false;
function waitPage(flag, text, id, bookingId,IFF,pageId,supplier,hotelInfo,bookingUrl,roomsInfo,pageUrlName,airportName,bookingCode,tourOpCode,strDuration,omniDate,airportDepCode,cntRegion){
	if(!formChanged){
		cancel = false;
		text = (typeof text != 'undefined')? text : '';
		jQuery('#pleaseWaitTxt').html(text);
		jQuery('#bjOverlay').css({
			'top': jQuery(window).scrollTop(),
			'height': jQuery(window).height()
		});
		if(pageId=='hotel' || pageId=='wellness' || pageId=='holidayHomes')
			jQuery('#bjOverlay .bjWait').addClass('bjHotelWait');
		(flag)? jQuery('#bjOverlay').show() : jQuery('#bjOverlay').hide();
		
		/*if(previousId != -1) {
			jQuery('#ID'+previousId).show();
			jQuery('#RESULT'+previousId).hide();
		}*/
		
		reCost(id,bookingId,IFF,pageId,supplier,hotelInfo,bookingUrl,roomsInfo,pageUrlName,airportName,bookingCode,tourOpCode,strDuration,omniDate,airportDepCode,cntRegion);
		previousId = id;
	} else{
		alert("Sie haben Ihre Suchparameter geändert.\n Bitte klicken Sie auf 'Reise suchen' zum Aktualisieren der Ergebnisliste!");
	}
}

function cancelWaitPage(){	
	jQuery('#bjOverlay').hide();
	cancel = true;
}

var formChanged = false;
function formCheck(){
	//jQuery('.subSearchPanel').find(':input:not([type=hidden])').serializeArray();
	var fr = jQuery('.subSearchPanel');
    fr.find(':input, select, :checkbox, :radio').not(":submit, :reset, :image, [disabled], [type=hidden]").change(function(){
		formChanged = true;
	});
}

/* Flug + Hotel - Search Panel */
function switchMaskStR(obj) {
	if (typeof obj != 'undefined') {
		if (obj == "hotel") {
			jQuery('#toStaedtereisen').attr('value', '');
			jQuery('#frStaedtereisen').attr('value', '');
			jQuery('#reisezielHotelStaedtereisen').attr('value', '  Reiseziel');
			jQuery('#partBetaDeuterosQuickMask').show();
			jQuery('#partBetaQuickMask').hide();
			jQuery('#labelToDate').text('Abreise');
			jQuery('#labelFromDate').text('Anreise');
			jQuery('#numSeniorStaedtereisen').css('visibility','hidden');
		} else if (obj == "hotelMietwagen") {
			jQuery('#toStaedtereisen').attr('value', '');
			jQuery('#frStaedtereisen').attr('value', '');
			jQuery('#reisezielHotelStaedtereisen').attr('value', '  Reiseziel');
			jQuery('#partBetaDeuterosQuickMask').show();
			jQuery('#partBetaQuickMask').hide();
			jQuery('#labelToDate').text('Abreise');
			jQuery('#labelFromDate').text('Anreise');
			jQuery('#numSeniorStaedtereisen').css('visibility','visible');
		} else { 
			jQuery('#partBetaQuickMask').show();
			jQuery('#reisezielHotelStaedtereisen').attr('value', '');
			jQuery('#partBetaDeuterosQuickMask').hide();
			jQuery('#toStaedtereisen').attr('value', strAnkunftflugh);
			jQuery('#frStaedtereisen').attr('value', strAbflughafen);
			/** START OF CODE MODIFICATION FOR DE – DE-1705: 
			* Description: html code added for Ruckflug
			* AUTHOR: Madan
			**/
			jQuery('#labelToDate').html('R&#252;ckflug');
			/** END OF CODE MODIFICATION FOR DE – DE-1705: 
			**/
			jQuery('#labelFromDate').text('Hinflug');
			jQuery('#numSeniorStaedtereisen').css('visibility', 'visible');
		}
		return true;
	} else {
		return false;
	}
}

function cleanDisplay(obj,str,alternative) {
    if (typeof obj == 'undefined' || obj == "") {
        return false;
    }
    if (obj.value == str || obj.value == alternative) {
        obj.value = '';
    }
    return true;
}

function reactivateDisplay(obj,str) {
    if (typeof obj == 'undefined' || obj == "") {
        return false;
    }
    if (obj.value == "") {
        obj.value = str;
    }
    return true;
}

/********* Date Functionality */
function toDate(eObj){
	var dDate = new Date();
	var mEpoch = parseInt(eObj); 
	if(mEpoch<10000000000) mEpoch *= 1000; // convert to milliseconds (Epoch is usually expressed in seconds, but Javascript uses Milliseconds)
	dDate.setTime(mEpoch);
	return dDate;
}

function getTimestampFromString(sTermin,flag){
  if(typeof sTermin == 'undefined') return false;
  var day   = 0;
  var month = 0;
  var year  = 0;
  if(sTermin.search(/(Mo|Di|Mi|Do|Fr|Sa|So)\. (\d{2})\.(\d{2})\.(\d{4})/i)!=-1){
    day   = parseInt(RegExp.$2, 10);
    month = parseInt(RegExp.$3, 10);
    year  = parseInt(RegExp.$4, 10);
  }else if(sTermin.search(/(\d{2})[\.\/]?(\d{2})[\.\/]?(\d{4})/)!=-1){
    day   = parseInt(RegExp.$1, 10);
    month = parseInt(RegExp.$2, 10);
    year  = parseInt(RegExp.$3, 10);
  }else if(sTermin.search(/(\d{2})[\.\/]?(\d{2})[\.\/]?(\d{2})/)!=-1){
    day   = parseInt(RegExp.$1, 10);
    month = parseInt(RegExp.$2, 10);
    year  = parseInt(RegExp.$3, 10);
    year = year>20?(1900+year):(2000+year);
  }
  if (day >= 1 && day <= 31 && month >= 1 && month <= 12 && year >= 1920 && year < 2020) {
    var dt = new Date(year,month-1,day,12,0,0);
  } else {
	flag = (typeof flag == 'undefined')? false : flag;
	if(!flag){
		var dt = new Date();
		dt.setHours(12,0,0,0);
	} else{
		return -1;
	}
  }
  return dt.getTime();
}

/********* Window Popup */
function openInfoBox(url){
	var favorit = window.open(url,'info','height=700,width=738,scrollbars=yes,status=yes,toolbar=no,menubar=no,location=no,resizable=yes'); 
    favorit.focus(); 
    return false;
}

function openPopup(url,w,h){
	h = (h > screen.height-40)? screen.height-40 : h; 
	var x = (screen.width/2) - (w/2);
	var y = (screen.height/2) - (h/2);
	var op = 'height='+ h +',width=' + w + ',scrollbars=yes,status=yes,toolbar=no,menubar=no,location=no,resizable=yes'
	var winPOP = window.open(url,'info',op);
	winPOP.moveTo(x,y);
	winPOP.focus();
}

/********* Return Query String Parameter Value */
function urlParam(urlTxt){
	var results = new RegExp('[\\?&]' + urlTxt + '=([^&#]*)').exec(window.location.href);
	if(!results){ return 0; }
	return results[1] || 0;
}

/********* Main Navigation Highlight */
var currPageIndex = -1;
function highLight(){
	currPage = window.location.href;
	replaceTxt = window.location.protocol + "//" + window.location.host + "/";
	currPage = currPage.replace(replaceTxt,'');
	currPage = currPage.substring(0, currPage.indexOf('/'));
	//currPage = currPage.replace(/-/g,' ');
	currPage = currPage.toLowerCase();
	if(currPage == ''){ 
		jQuery(jQuery('.menuWrap li[id*="tab"]')[0]).addClass('menuActive'); 
	} else{
		returnIndex(currPage);
		if(currPageIndex == -1) returnIndex(urlParam('page_url_name'));
		if(currPageIndex >= 0){
			jQuery(jQuery('.menuWrap li[id*="tab"]')[currPageIndex]).addClass('menuActive');
		}
	}	
}
function returnIndex(txt){
	jQuery('.menuWrap li[id*="tab"]').each(function(ind){
		var elemTxt = jQuery(this).children('a').attr('class');
		elemTxt = elemTxt.toLowerCase();
		elemTxt = jQuery.trim(elemTxt);
		if(elemTxt == txt){ 
			currPageIndex = ind;
			return false;
		}
	});
	return false;
}

function findPageId(txt){	
	switch(txt){
		case 'package': returnIndex('pauschalreise'); break;
		case 'lastminute': returnIndex('lastminute'); break;
		case 'flight': 
		case 'charterflight': returnIndex('flug'); break;
		case 'hotel': 
		case 'cityhotel': 
		case 'clubholidays':
		case 'hotelcar':   
		case 'wellness': returnIndex('hotel'); break;
		case 'flighthotel': 
		case 'flighthotelcar': returnIndex('flug + hotel'); break;
		case 'flightcity': 
		case 'nurhotel': 
		case 'flughotel': 
		case 'cityhotellondon': 
		case 'cityhotelparis':
		case 'cityhotelny':
		case 'cityhotelberlin': returnIndex('städtereise'); break;
		case 'holidayHomes': returnIndex('ferienhaus'); break;
		default: break;
	}
	if(txt == 0){ returnIndex('start'); }
}

// This function will call when selected package was sold out.
// This method is changed for DEBAU-143 Author:Harsh
var  cancel = false;
function callNext(id,bookingId,IFF,pageId,supplier,hotelInfo,bookingUrl,roomsInfo,pageUrlName,airportName,bookingCode,tourOpCode,strDuration,omniDate,airportDepCode,cntRegion) {
	var newId = id+1;
	var hiddenObject = jQuery('#bookId'+newId);
	var omniHdnObject = jQuery('#OmniData_'+newId);
	if(hiddenObject) {
		jQuery('#ID'+id).show();
		jQuery('#ID'+id).addClass('resortListDisabled');
		jQuery('#RESULT'+id).hide();
		bookingId = hiddenObject.attr('value');
		if(omniHdnObject && omniHdnObject.attr('value') != null && omniHdnObject.attr('value')!=''){
			arrOmniData = omniHdnObject.attr('value').split('_');
			
			if(arrOmniData != null && arrOmniData.length == 4){
			
				strDuration = arrOmniData[0];
				omniDate = arrOmniData[1];
				supplier = arrOmniData[2];
				airportDepCode = arrOmniData[3];
			}
		}
		previousId = newId;

		if((hiddenObject.attr('value') != null) && (! jQuery('#ID'+newId).hasClass('resortListDisabled'))){
		if(!cancel){
		reCost(newId,bookingId,IFF,pageId,supplier,hotelInfo,bookingUrl,roomsInfo,pageUrlName,airportName,bookingCode,tourOpCode,strDuration,omniDate,airportDepCode,cntRegion);
		}
	}
		else{
			jQuery('#bjOverlay').hide();
		}
	}
}


function callReload(no) {
	var address =  window.location+"" ;	
	if(document.getElementById('searchParam').value == '')
	{
	window.location =  address.split("?")[0] + "?check="+no+"&pageId="+document.getElementById('pageIdentifier').value;
	}else{
	window.location =  address.split("?")[0] + "?check="+no+"&pageId="+document.getElementById('pageIdentifier').value+"&search="+document.getElementById('searchParam').value;
	}

}
	
function setEvents(events) {
	s.events = s.events+ events;
}
function populateDays(count){		
	var theDropDown = document.getElementById("childdays"+count);
	var previoudSelected = theDropDown.value;
	var numberOfOptions = theDropDown.options.length;  
	for (i=0; i<numberOfOptions; i++) {  
		theDropDown.remove(0);  
	}  
	var val = document.getElementById("childage"+count).value;
	var element = val.split(".");	
	var days = 32 - new Date(element[1], element[0]-1, 32).getDate();
	optn = document.createElement("OPTION");
	optn.text = "--";
	optn.value = "";
	document.getElementById("childdays"+count).options.add(optn);
	for(var i = 1 ; i<=days ; i++) {
		var optn = document.createElement("OPTION");
		optn.text = i;
		optn.value = i;
		document.getElementById("childdays"+count).options.add(optn);
	}
	document.getElementById("childdays"+count).value = previoudSelected;
}

function sortBy(val){
	document.getElementById("sortBy").value=val;
	document.forms[1].submit();
}

/**
* This function will open the pop up window for facilities
*/
function openFacilityWindow(url){
	var favorit = window.open(url,'info','height=410,width=425,scrollbars=yes,status=yes,toolbar=no,menubar=no,location=no,resizable=yes'); 
	favorit.focus(); 
	return false;
}


function checkemail(val){
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
		if(filter.test(val)) {
			return true 
		}
		else{
			return false;
		}
	}

/**
 * This function will display the response message when credit card is selected as payment.
 **/
	function populateMsg(cardType){
		var resMsg = null;
		if(cardType == null || cardType.length == 0){
			resMsg = document.getElementById("default_msg").innerHTML;
		}else{
			var idVal = cardType +'_msg';
			resMsg = document.getElementById(idVal).innerHTML;
		}
		if(resMsg != null && document.getElementById('resMsgDiv') != null){
			document.getElementById('resMsgDiv').innerHTML=resMsg;
		}
		
	}
