var prevParams = false;
var curr_form = "#ExpressBkFltonly";

window.undefined = window.undefined;

$(function() {
	$('input').each(function(){
		this.defaultValue = this.value;
	}).blur(function(){
		if (this.value=='') this.value=this.defaultValue;
	});
	enableMCounter();

	$("#compare").click(compare);
	$("#class").change(function(){refreshMerchants();});
	$("#oneway").change(onewaySelection);
	$(".addSites").click(selectRandom);
	$("#email").focus(defaultHandler);
	$("#email").change(submitMail_new);
	$(".turnoff_pp img").click(function(){createWindow("popup_new");});
	$(".refreshMerchants").change(refreshMerchants);
	initHeight();
	$(".flags a").each(insertFlagLink);
});

/*	putted here beeing one of the most important functions	*/
function insertTracking(idRef, adId, idSec, addOutTrack, city1, city2, selectedCruiseLine, selectedCruiseDestination,sID) {
	idReferral = idRef;
	adid = adId;
	idSecondary = idSec;
	if (sID) subID = sID;
	else subID = 0;
	$('form input[@name=idReferral]').val(idRef);
	$('form input[@name=adid]').val(adId);
	$('form input[@name=idSecondary]').val(idSec);
	$('a[@href*=idReferral]').each(function() {
		newUrl = this.href.replace(/idReferral=[0-9]*/g, "idReferral="+idRef);
		if (sID) newUrl = newUrl.replace(/subID=[0-9]*/g, "subID="+sID);
		this.href = newUrl.replace(/adid=[^&]*/g, "adid="+adId);
	});
	if (sID)
		$('form input[@name=subID]').val(sID);
	/*$("div.footer_main a.flg").each(function() { this.href += "?idSecondary=1&idReferral="+idRef+"&adid="+adId});*/
	$("a.addTrack").each(function() { this.href += "?idReferral="+idRef+"&adid="+adId});
	/*if(addOutTrack)
		$("a.addOutTrack").each(function() { this.href += "?idReferral="+idRef+"&adid="+adId});*/
	/*$("a#flg_us").attr("href", $("a#flg_us").attr("href")+"&noRedirect=true");*/
	if(city1)
		$('form input[@name=inp_dep_arp_cd_1],form input[@name=airport],#cr_pck_up_cty_name,form input[@name=city1]').val(city1);
	if(city2)
		$('form input[@name=inp_arr_arp_cd_1],#cr_drp_off_cty_name,form input[@name=arr][@type=text]').val(city2);
	if(selectedCruiseLine)
		$('select#cruiseline option[@value='+selectedCruiseLine+']').get(0).selected = true;
	if(selectedCruiseDestination)
		$('select#destination option[@text='+selectedCruiseDestination+']').get(0).selected = true;
	return;
}

function insertFlagLink_old(){
	this.href = "?language="+this.href.substring(this.href.length-2, this.href.length);
};

function insertFlagLink(){ /*changed by tibi on jan 5, 2010*/
	var new_href = '';
	if (this.href.substring(this.href.length-2, this.href.length)=='de')
		new_href = document.location.href.replace('www.metafares.com','www.gobillig.de').replace('www.metafares.co.uk','www.gobillig.de');
	else if (this.href.substring(this.href.length-2, this.href.length)=='en')
		new_href = document.location.href.replace('www.metafares.com','www.metafares.co.uk').replace('www.gobillig.de','www.metafares.co.uk');
	else
		new_href = document.location.href.replace('www.metafares.co.uk','www.metafares.com').replace('www.gobillig.de','www.metafares.com');

	this.href = new_href+"?language="+this.href.substring(this.href.length-2, this.href.length);
};

function onewaySelection(){
	$("input[@name=ret_date]").attr('disabled',this.checked ? 'disabled' : '');
};

function enableMCounter(){
	$(".adv").click(function(){
		$(this).toggleClass("mSel");
		var tmp = $(".mSel");
		$(".nrSites .orng").html(tmp.length ? tmp.length : "0");
	});
};

function createWindow(win,callback) {
	/*$.post("/ajax/popupwindow.php",{'window' : win},function(data) {$(document.body).append(data);});*/
	$.ajax({
		'method' : 'post',
		'url' : '/ajax/popupwindow.php',
		'data' : 'window='+win,
		'success' : typeof(callback)=='function' ? callback : function(data) {
			$(document.body).append(data);
		}
	});
}

function initHeight(){
	$(".box2").css("height","");
	maxH = 0;
	$(".bx").each(function(){if ($(this).height()>maxH) maxH = $(this).height();});
	if (maxH) $(".box2").css("height",maxH);
};

function defaultHandler(){
	if (this.value==this.defaultValue) this.value='';
	else this.select();
	return;
};

function selectRandom(){
	/*var cnt = (4-$(".mSel").length) > 0 ? (4-$(".mSel").length) : 0;*/
	for (var i=0;i<2;i++) selectOne();
};

function selectOne(){
	var e = $(".adv").not(".mSel");
	e.filter(":eq("+(Math.floor(Math.random()*e.length))+")").click();
};

function updTzoo(fAir, tAir) {
	tzo=$('#tzDeals').get(0);
	if(tzo == undefined) return false;
	var nSrc=tzo.src;
	if(fAir) nSrc = nSrc.replace(/O=(.*)&/, 'O='+fAir+'&');
	if(tAir) nSrc = nSrc.replace(/D=(.*)/, 'D='+tAir);
	if(tzo.src==nSrc) return false;
	tzo.src=nSrc;
	return true;
}

function remErr(){
	$(this).removeClass("err").unbind('focus',remErr);
};

function submitMail_new() {
	inp = this;
	if(typeof(placement)=="undefined") placement="air";
	if (inp.value == inp.defaultValue || inp.value==inp.lastMail || inp.value == '') return false;
	inp.lastMail = inp.value;
	if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(inp.value))) {
		$(inp).addClass("err").focus(remErr);
		alert(errMsg['mailError']);
		return false;
	}

	var c1 = "";
	var c2 = "";

	var f = $("#fromAir").get(0);
	var t = $("#toAir").get(0);
	if( f && f.value && f.value!=f.defaultValue) f=f.value; else f="";
	if( t && t.value && t.value!=t.defaultValue) t=t.value; else t="";
	$(inp).addClass("aLoad");
	var strHost = document.location.host;
	strHost = strHost.replace(/www./, "");
	var s = (strHost == 'gobillig.de') ? "GOBI" : "META";
	/* request type changed from get to post by Cipri on 10 December 2009 */
	$.post("/ajax/subscribe.php",{source:s,deal:placement,city:f,city2:t,email:inp.value,searchsystem:searchsystem,idReferral:idReferral, adid:adid, forcejson:"true"},function(data) {
		$(inp).removeClass("aLoad");
		jsondata = eval("("+data+")");
		response = jsondata.msg;
		if(response) {
			if(response=="reactivate") {
				if(confirm("This email address was already unsubscribed.\n Do you wish to reactivate it?")) {
					$.post("/ajax/subscribe.php",{reactivate:"yes",source:s,deal:placement,city:f,city2:t,email:inp.value,searchsystem:searchsystem,idReferral:idReferral, adid:adid});
					$("label[for=email]").html("Thank you for registering.");
					$(inp).addClass("inpOk");
				}
			} else {
				$("label[for=email]").html(response);
				$(inp).addClass("inpOk");
			};
			if (jsondata.script!="") {
				var x=document.createElement('iframe');
				x.src=jsondata.script+"?rand="+Math.random();
				x.style.display="none";
				x.style.visibility="hidden";
				document.body.appendChild(x);
			}
		}
	});
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+100);
	document.cookie="news=yes;expires="+exdate;

};

function refreshMerchants() {
	ret = false;
	$(".validate").each(function(){
		if (this.value==this.defaultValue || this.value.length<3) ret = true;
	});
	if (ret) return false;

	var params = $(curr_form).serialize()+"&impId="+queryCode+"&searchsystem="+searchsystem+"&language="+lang;
	paramsToCheck = params.replace(/&dep_date=[^&]+/,'').replace(/&ret_date=[^&]+/,'') + '&in2days=' + in2days() + '&datediff30=' + datediff30();
	if (prevParams!=paramsToCheck) {
		$("#advCont").prepend("<div id='mLoad'>&nbsp;</div>");
		var a = $(".adv");
		$("#mLoad").height((a.height()+10)*Math.ceil(a.length/2));
		$("#advCont").find(".adv").css("display","none");
		$.post(merchantsRefreshFile,params,processResponse);
	};
	prevParams=paramsToCheck;
}

function in2days(){
	var dep = getTimestamp($("#dep_cal").val());
	var now = getTimestamp();
	var ret = dep-now<0 ? 0 : dep-now;
	ret = Math.ceil(ret/(1000*60*60*24));
	return ret>1 ? 0 : 1;
};

function datediff30(){
	var dep = getTimestamp($("#dep_cal").val());
	var arr = getTimestamp($("#arr_cal").val());
	var ret = arr-dep<0 ? 0 : arr-dep;
	ret = Math.ceil(ret/(1000*60*60*24));
	return ret>31 ? 1 : 0;
};

function getTimestamp(date){
	if (typeof(date)=='undefined') {
		var d = new Date();
		return d.getTime();
	};
	var d_a = date.split('/');
	if (lang.toLowerCase()=='def' || lang.toLowerCase()=='us') var d_o = new Date(d_a[2], d_a[0]-1, d_a[1], 0, 0, 0, 0);
	else var d_o = new Date(d_a[2], d_a[1]-1, d_a[0], 0, 0, 0, 0);
	return d_o.getTime();
};

function processResponse(rsp) {
	try {
		rsp = eval("("+rsp+")");
	} catch (err) {
		alert("We are sorry but our page has encountered an error");
	};

	classes = "";
	$(".mSel").each(function(){
		var patt = /c[0-9]+/i;
		classes += "."+patt.exec(this.className)+",";
	});
	if (rsp.merchants) {
		$("#advCont").replaceWith(rsp.merchants);
		enableMCounter()
		$(classes).not(".adv_bttm").click();
	} else {
		$("#advCont").find(".adv").css("display","");
		$("#mLoad").remove();
	};
	
	if (typeof(linkCounter)!='undefined' && linkCounter!='http://www.travelgrove.com/cgi-bin/link_counter_new.cgi') {
		$('img[@alt=Hotwire]:eq(0)').parent().not(".mSel, .adv_bttm").click();
	};
	
	/*$('img[@alt=cFares]:eq(0)').parent().not(".mSel").click();*/
	if (rsp.travelZoo) updTzoo(rsp.travelZoo.tzO, rsp.travelZoo.tzD);
	if(rsp.trackPxlUrl) {
		var d = new Date();
		trPxl=rsp.trackPxlUrl+'&idReferral='+idReferral+'&'+d.getTime();
		$.ajax({url:trPxl, type:"HEAD"});
	};
	initHeight();
	refreshTAN();

	return true;
}

function refreshTAN(){
	if(!$(".TAN300x250").length) return false;
	$(".TAN300x250").get(0).src += "&rand="+Math.random();
};

function compare() {
	var msg = validateBox($(curr_form));
	if (msg) {
		alert(msg);
		return false;
	};
	openMerchants();
	refreshMerchants();
	return true;
}

function openMerchants() {
	var msg = validateBox($(curr_form));
	if (msg) {
		alert(msg);
		return false;
	};
	windowsCanBeOpened = true;
	$(".mSel").each(function(){
		if (!windowsCanBeOpened) return false;
		var mName = $(this).find("img").attr("alt");
		var patt = /c[0-9]+/i;
		var mId = patt.exec(this.className);
		mId = mId.toString().substr(1);
		newWin = jump(mId, mName);
		if (!newWin) {
			if (typeof(showClickableMerchants)=='function') {
				showClickableMerchants(lastOpenedMerchantId);
				window.focus();
				windowsCanBeOpened = false;
				return false;
			};
			createWindow("popup_new");
			window.focus();
			windowsCanBeOpened = false;
			return false;
		};
		lastOpenedMerchantId = mId;
	});
	return true;
}

function jump(id, merchant, channel, lc_type) {
	if (typeof(newWinX)=="undefined") {
		newWinX = 20;
		newWinY = 20;
	};
	used_link_counter = linkCounter;
	if (typeof(lc_type)!='undefined' && lc_type==5) used_link_counter = "http://www.travelgrove.com/cgi-bin/vacation/link_counter_new.cgi";
	// if lc_type is set and it's 5, we are using the vacation link counter - used for merchants below the airfare merchants (AAVacations)
	var myWinWidth = screen.width * 0.8;
	var myWinHeight = screen.height * 0.7;
	var myWinCoord = "left="+newWinX+",top="+newWinY+",width="+(screen.width * 0.8)+",height="+(screen.height * 0.7)+",resizable = yes,scrollbars=yes, toolbar=yes, location=yes";
	newWinX += 20;
	newWinY += 20;
	channelParam = (channel == undefined) ? '' : '&channel='+channel;

	/*changed by tibi on dec. 15, 2009 - a perl error found when multiple variables were present in the link (channel)*/
	var params = $(curr_form).serialize();
	if (channel) params = params.replace(/channel=[0-9]./,'');
	var params = params+'&merchant='+merchant+'&logo='+logoImg+'&intitem='+id+'&idReferral='+idReferral+'&adid='+adid+'&querycode='+queryCode+'&subID='+subID+'&language='+lang+'&searchsystem='+searchsystem+'&trafficSource=metafares&lang='+lang+channelParam;

// 	var params = $(curr_form).serialize()+'&merchant='+merchant+'&logo='+logoImg+'&intitem='+id+'&idReferral='+idReferral+'&adid='+adid+'&querycode='+queryCode+'&subID='+subID+'&language='+lang+'&searchsystem='+searchsystem+'&trafficSource=metafares&lang='+lang+channelParam;
	var link = used_link_counter+"?"+params;
	return window.open(link,"_blank",myWinCoord);
}

function jump_vacation(id, merchant, channel){
	linkCounter = '';
	jump(id, merchant, channel, '');
	linkCounter = '';
}

/**
 * WHO: Tibi
 * WHEN: 2010
 * WHY: To implement new popup div for popup blocker alert
 * WHAT: function that makes an ajax request to a remote file, sending all the required parameters and appends the response to the body - evaluates all JS and CSS present in the response
*/
function showClickableMerchants(/*intitem for merchant which already was opened:*/clickedMerchant){
	popupParams = '';// list of merchants which will be showed in the popup
	$("#advCont .mSel:not(.c"+(clickedMerchant ? clickedMerchant : '0')+")").each(function(){// each mertchant which is selected, except the merchant that already was opened
		var intitem = this.className.match(/c([0-9]+)/);
		var i = $(this).children('img');
		var mName = i.attr('alt');
		var img = i.attr('src').substr(i.attr('src').lastIndexOf('/')+1);
		popupParams += '&intitem[]='+intitem[1]+'&mName[]='+mName+'&img[]='+img;
	});
	var placement = $("form.sform").attr('class').replace(/^.*(Air|Hotel|Car|Cruise|Vacation)?.*$/,'$1').toLowerCase();// retrieving the placement name from the class of the search form (the classname should be something like this: "sform sformHotel")
	if (!placement) placement='air';// default placement is air
	$.ajax({
		'method' : 'post',
		'url' : '/ajax/popupwindow.php',
		'data' : 'window=popup_merchants'+popupParams+'&'+$('form.sform').serialize()+'&placement='+placement,// sending params
		'success' : function(data) {
			$(document.body).append(data);// on success, outputing the response - every additional JS will be in the response and it will be automatically evaluated
		}
	});
};