/**** DEFS ****/

INVUE_TIMEOUT = 600000; // on site in vue ad timeout
INVUE_BROWSE_TIMEOUT = 300000; // on site without hitting confirm page
INVUE_PAGE_TIMEOUT = 210000; // on a single page
MAX_VIEWED_HOTELS = 15; // show an in vue add if the user has seen more than this number of hotel overviews
SHORT_VIEWED_HOTELS = 8; // show an in vue add if the user has seen more than this number of hotel overviews
SHORT_TIMEOUT = 15000; // on page in vue timeout

//BOOK_HOST = '10.19.89.18'; // secure booking domain
BOOK_HOST = 'www.res99.com'; // secure booking domain

var DYNA_WIDTH, DYNA_HEIGHT;
INVUE_WIDTH_1 = 345; // width of invue ad
INVUE_HEIGHT_1 = 300; // height of invue ad
INVUE_TYPE_1 = 'iframe';
INVUE_TARGET_1 = 'http://www.ratebooker.com/search/compare/hotels/accept.jsp';
INVUE_WIDTH_2 = 300;
INVUE_HEIGHT_2 = 300;
INVUE_TYPE_2 = 'image';
INVUE_TARGET_2 = 'http://www.ratebooker.com/search/compare/hotels/accept.jsp';
INVUE_WIDTH_3 = 300;
INVUE_HEIGHT_3 = 300;
INVUE_TYPE_3 = 'iframe';
INVUE_TARGET_3 = 'http://www.ratebooker.com/search/compare/hotels/accept.jsp';
INVUE_WIDTH_4 = 300;
INVUE_HEIGHT_4 = 300;
INVUE_TYPE_4 = 'image';
INVUE_TARGET_4 = 'http://www.ratebooker.com/search/compare/hotels/accept.jsp';

INVUE_PREFIX = '/invue_ad_';

POPUP_WIDTH = 507; // width of popunder ad
POPUP_HEIGHT = 303; // height of popunder ad
POPUP_TOP = (window.screen.height/2)-(POPUP_HEIGHT/2); // offset position of popunder ad from top of screen
POPUP_LEFT = (window.screen.width/2)-(POPUP_WIDTH/2); // offset position of popunder ad from left of screen 
POPUP_OPTS = 'location=no,menubar=no,toolbar=no,status=no,titlebar=no'; // popunder window options
POPUP_TARGET = 'http://www.ratebooker.com/search/compare/hotels/accept.jsp';

if(window.location.protocol == 'https:') {
	//POPUP_IMAGE = 'https://www.ratebooker.com/search/compare/hotels/images/pop_under_ad_01.gif';
	POPUP_IMAGE = 'https://images.wctravel.com/images-general/WCT_montage_fnl.jpg';
	TRACK_POPUP_IMAGE = 'https://'+BOOK_HOST+'/nexres/start-pages/gateway.cgi?engine=batpopup';
}
else {
	//POPUP_IMAGE = 'http://www.ratebooker.com/search/compare/hotels/images/pop_under_ad_01.gif';
	POPUP_IMAGE = 'http://images.wctravel.com/images-general/WCT_montage_fnl.jpg';
	TRACK_POPUP_IMAGE = 'http://'+BOOK_HOST+'/nexres/start-pages/gateway.cgi?engine=batpopup';
}

var searchPageName   = /\/.*\/power_search|search_results\.cgi/gi;  // regular expression to match the search page
var overviewPageName = /\/.*\/availability\.cgi|\/.*\/(\d+)-(\d+).\.html|\/.*\/mylist\.cgi|\/.*\/mylist\.cgi|\/.*\/input_dates\.cgi|\/.*\/prop_page\.cgi/gi;  // regular expression to match the hotel overview page
var bookPageName = /\/.*\/reserve_form\.cgi/gi; // regular expression to match the booking form page
var confirmPageName = /\/.*\/reserve\.cgi/gi;  //regular expression to match the booking confirmation page

/**** CODE ****/

var inTime = new Date();
var viewedHotels = new Array();
var lastPage = getCookie('BAT_last_page');
var srcId;
var saId;

var invueDiv;

var windowText;

var clCounter = new Array();
var clHost;
var BAT_clickedHost;
var searchStartDate;

if(getCookie('BAT_no_popup') == '1') {
	var dontPopup = 1
}
else {
	var dontPopup = 0;
}

var dontPop = 0;

var adType = 4;

function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27');
}

function URLdecode(sStr) {
    return unescape(sStr.replace(/\+/g, ' '));
}

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "; path=/") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
	if (begin != 0) return '';
	} else
		begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function getVar(varName) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		
		if(pair[0] == varName) {
			if(URLdecode(pair[1])) {
				return URLdecode(pair[1]);
			}
			else {
				return "";
			}
		}
	}
	return '';
}

function initBATPage() {
	changeLinks();
	srcId = encrypt_src(getSrcId());
        if(document.location.pathname.match(searchPageName)) {
            setCookie('BAT_last_page', 'searchPage');
			setCookie('BAT_search_string', getCurrentSearchString());
			checkDateLimit();
            checkFailedBook();
            initBATTimeouts();
			checkSearchDates();
			checkSearchPage();
	}
        else if(document.location.pathname.match(bookPageName)) {
            setCookie('BAT_last_page', 'bookPage');
			setCookie('BAT_tried_booking', 1);
			checkSearchDates();
            checkNumHotels();
        }
        else if(document.location.pathname.match(confirmPageName)) {
            setCookie('BAT_last_page', 'confirmPage');
			setCookie('BAT_no_popup', '1');
			dontPopup = 1;
	}
        else if(document.location.pathname.match(overviewPageName)) {
			checkDateLimit();
            setCookie('BAT_last_page', 'overviewPage');
            checkFailedBook();
            initBATTimeouts();
			checkSearchDates();
            checkNumHotels();
        }
        else {
            setCookie('BAT_last_page', 'other');
            checkFailedBook();
            initBATTimeouts();
	}
	// query string for tracking purposes
	var mquery = "&src=" + escape(getSrcId()) + "&src_aid=" + escape(saId);
	//var pop_target = POPUP_TARGET + "?" + getFwdVars();
	var pop_target = "/nexres/start-pages/gateway.cgi?engine=redirectbatpopup"+ mquery + getFwdVars();
	// Now doing a dynamic text that may include the client's desired destination
	var destination_string = "Still Searching for a Hotel";
	var dest = getCookie('BAT_search_string');
	if(dest != null && dest.length > 1)
	{	// include destination if available in the cookie
		destination_string += " in " + dest;
	}
	destination_string += "?";

	if(navigator.appName == "Microsoft Internet Explorer")
	{
		DYNA_HEIGHT = document.body.offsetHeight
		DYNA_WIDTH  = window.screen.availWidth
	}
	else
	{ // Navigator coordinates
			DYNA_HEIGHT = screen.height;
			DYNA_WIDTH = screen.width;
	}	
	windowText = "<html><head><style type=\"text/css\"><!-- #mover {cursor: hand;} --></style><script type=text/javascript>function  close_me(){window.close();}</script></head><body style=\"padding: 0px; margin: 0px;\" onClick=\"setTimeout(close_me,200);\"><table width=\"505\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" id=\"mover\"><tr><td align=\"center\" bgcolor=\"#CC9933\"><font style=\"font-family: Arial Black, Helvetica, sans-serif; font-size: 14pt; color: #FFFFFF\">" + destination_string + "</font></td></tr><tr><td><table width=\"100%\" cellpadding=\"1\" cellspacing=\"0\" border=\"0\" id=\"mover\"><tr><td bgcolor=\"#000099\" align=\"center\" ><a href=\"" + pop_target + "\" target=\"_blank\"><img width=\"505\" height=\"275\" border=\"0\" src=\"" + POPUP_IMAGE + "\"></a></td></tr></table><td></tr></table><img src=\"/nexres/start-pages/gateway.cgi?engine=batpopup&served=1" + mquery + "\" width=\"1\" heigth=\"1\" name=\"bathiddenimage\"></body></html>";
}

function initBATTimeouts() {
    setTimeout(displayInvue, INVUE_PAGE_TIMEOUT);

    BAT_inTime = parseInt(getCookie('BAT_inTime'));

    if(BAT_inTime) {
       inTime = new Date(BAT_inTime);
    }
    else {
       setCookie('BAT_inTime', inTime.getTime());
    }
    
    if(getInvueTimeout() > 0) {
        setTimeout(displayInvue, getInvueTimeout());
    }
    else {
        displayInvue();
    }
}

function getInvueTimeout() {
    currTime = new Date();
    
    BAT_tried_booking = parseInt(getCookie('BAT_tried_booking'));
    
    if(BAT_tried_booking) {
    	return INVUE_TIMEOUT - (currTime.getTime() - inTime.getTime());
    }
    else {
    	return INVUE_BROWSE_TIMEOUT - (currTime.getTime() - inTime.getTime());
    }
}

function displayInvue() { //  DISABLED
    /*BAT_invue_shown = parseInt(getCookie('BAT_invue_shown'));

    if(!BAT_invue_shown && !dontPop) {
        if(!invueDiv) {
		createInvueAd();
	}
	invueDiv.style.visibility='visible';
    }*/
    return true;
}

function checkNumHotels() {
	thisHotelId = getCurrentHotelId();

	BAT_viewed_hotels = getCookie('BAT_viewed_hotels');

	if(BAT_viewed_hotels) {
		viewedHotels = BAT_viewed_hotels.split(',');
	}
	else viewedHotels = new Array();

	noAdd = 0;
	for(i=0; i < viewedHotels.length; i++) {
		if(viewedHotels[i] == thisHotelId) {
			noAdd = 1;
		}
	}
	if(!noAdd) {
		viewedHotels[viewedHotels.length] = thisHotelId;
	}
	setViewedHotelsCookie();

	if(viewedHotels.length > MAX_VIEWED_HOTELS) {
		adType = 1;
		displayInvue();
	}
	else if(viewedHotels.length > SHORT_VIEWED_HOTELS) {
		adType = 1;
		setTimeout(displayInvue, SHORT_TIMEOUT);
	}
}

function setViewedHotelsCookie() {
    /*outString = '';

    for(i=(viewedHotels.length-1); i >= 0; i--) {
    	if(parseInt(viewedHotels[i])) {
        	outString += ',' + viewedHotels[i];
	}
    }

    setCookie('BAT_viewed_hotels', outString.substr(1));*/
    
    setCookie('BAT_viewed_hotels', getCurrentHotelId());
}

function getSrcId() {
	saId = getVar('src_aid');
	if(saId) {
		setCookie('BAT_saId', saId);
	}
	
	BAT_inTime = parseInt(getCookie('BAT_inTime'));
	exDate = new Date(BAT_inTime + (60 * 60 * 24 * 30 * 3));

	if(document.location.pathname.match(overviewPageName)) {
		testSrcId = document.location.pathname.replace(overviewPageName, "$1");
		if(testSrcId) {
			setCookie('BAT_srcId', testSrcId, exDate);
			return testSrcId;
		}
		else {
			setCookie('BAT_srcId', getVar('src'), exDate);
			return getVar('src');
		}
	}
	else {
		setCookie('BAT_srcId', getVar('src'), exDate);
		return getVar('src');
	}
}

function getCurrentHotelId() { // *** SITE SPECIFIC FUNCTION ***

    testHotelId = document.location.pathname.replace(overviewPageName, "$2");
    if(testHotelId && testHotelId.match(/\d+/gi)) {
    	return testHotelId;
    }

    testHotelId = getVar('hotels_id');
    if(testHotelId && testHotelId.match(/\d+/gi)) {
    	return testHotelId;
    }
    
    return null;
}

function getCurrentSearchString() { // *** SITE SPECIFIC FUNCTION ***
    return getVar('city');
}

function getCurrentSearchDates() { // *** SITE SPECIFIC FUNCTION ***
    if(getVar('in_date') && getVar('out_date')) {
    	tempString = getVar('in_date');
	tempString = tempString.split('-');
	
	if(tempString.length != 3) return null;
	
	inDay = tempString[2];
	inMonth = tempString[1];
	inYear = tempString[0];
	
	tempString = getVar('out_date');
	tempString = tempString.split('-');
	
	if(tempString.length != 3) return null;
	
	outDay = tempString[2];
	outMonth = tempString[1];
	outYear = tempString[0];
    }
    else {
	inDay = getVar('doa_dd');
	inMonth = getVar('doa_mm');
	inYear = getVar('doa_yy');
	
	outDay = getVar('dod_dd');
	outMonth = getVar('dod_mm');
	outYear = getVar('dod_yy');
    }
    
    if(!inDay) return null;
    if(!inMonth) return null;
    if(!inYear) inYear = inTime.getFullYear();
    if(!outDay) return null;
    if(!outMonth) return null;
    if(!outYear) outYear = inTime.getFullYear();
    
    searchStartDate = new Date(inMonth + '/' + inDay + '/' + inYear);
    
    return inMonth + '/' + inDay + '/' + inYear + '-' + outMonth + '/' + outDay + '/' + outYear;
}

function getCurrentPage() { // *** SITE SPECIFIC FUNCTION ***
    rowOffset = parseInt(getVar('rows'));
    
    if(!rowOffset) {
    	return 2;
    }
    else {
    	return Math.round((rowOffset-26) / 15) + 2;
    }
}

function checkDateLimit() {
	getCurrentSearchDates()
	
	if(searchStartDate) {
		if(((searchStartDate.getTime() - inTime.getTime()) / 1000 / 60 / 60 / 24) > 90) {
			dontPop = 1;
		}
	}
}

function checkFailedBook() {
    if(lastPage == 'bookPage') {
    	adType = 3;
        displayInvue();
    }
}

function checkSearchDates() {
    BAT_search_dates = getCookie('BAT_search_dates');

    currentSearchDates = getCurrentSearchDates();

    if(currentSearchDates) {
        setCookie('BAT_search_dates', currentSearchDates);
    }
}

function checkSearchLocation() {
    BAT_search_string = getCookie('BAT_search_string');

    currentSearchString = getCurrentSearchString();

    if((BAT_search_string && currentSearchString) && (BAT_search_string != currentSearchString)) {
        setTimeout(displayInvue, SHORT_TIMEOUT);
    }

    if(currentSearchString) {
        setCookie('BAT_search_string', currentSearchString);
    }
}

function checkSearchPage() {
    if(getCurrentPage() > 4) {
    	adType = 2;
	displayInvue();
    }
}

function createInvueAd() {
	invueDiv = document.createElement('DIV');
	
	eval('adWidth = INVUE_WIDTH_' + adType);
	eval('adHeight = INVUE_HEIGHT_' + adType);
	eval('adStyle = INVUE_TYPE_' + adType);
	
	invueDiv.style.position = 'absolute';
	invueDiv.style.width = adWidth;
	invueDiv.style.height = adHeight;
	invueDiv.style.visibility='hidden';
	
	invueDiv.innerHTML += "<table width=100%><tr><td align=right width=100%><a href=\"javascript:closeFloater()\">[X]</a></td></tr></table>";
	
	if(adStyle == 'iframe') {
		invueDiv.appendChild(getAdIframe());
	}
	else if(adStyle == 'image') {
		invueDiv.appendChild(getAdImage());
	}
	
	document.body.appendChild(invueDiv);
	updateFloaterPos();
	
	setInterval(updateFloaterPos, 50);
}

function getAdIframe() {
	eval('adWidth = INVUE_WIDTH_' + adType);
	eval('adHeight = INVUE_HEIGHT_' + adType);
	eval('adStyle = INVUE_TYPE_' + adType);

	linkObj = document.createElement('iframe');
	linkObj.style.overflowX = 'hidden';
	linkObj.style.overflowY = 'hidden';
	linkObj.width = adWidth-2;
	linkObj.height = adHeight-2;
	linkObj.src = INVUE_PREFIX + adType + '.html';
	
	return linkObj;
}

function getAdImage() {
	eval('adWidth = INVUE_WIDTH_' + adType);
	eval('adHeight = INVUE_HEIGHT_' + adType);
	eval('adStyle = INVUE_TYPE_' + adType);	
	eval('adTarget = INVUE_TARGET_' + adType);

	linkObj = document.createElement('a');
	linkObj.href = adTarget + '?' + getFwdVars();
	
	imageObj = new Image();
	imageObj.border = 0;
	imageObj.align = 'top';
	imageObj.src = INVUE_PREFIX + adType + '.jpg';
	
	linkObj.appendChild(imageObj);
	
	return linkObj;
}

function updateFloaterPos() {
	eval('adWidth = INVUE_WIDTH_' + adType);
	eval('adHeight = INVUE_HEIGHT_' + adType);

	newTop = document.body.scrollTop + ((document.body.clientHeight - adHeight) / 2);
	newLeft = document.body.scrollLeft + ((document.body.clientWidth - adWidth) / 2);
	
	if(newTop > 0) {
		invueDiv.style.top = newTop;
	}
	else {
		invueDiv.style.top = 0;
	}
	invueDiv.style.left = newLeft;
	
	
	selects = document.getElementsByTagName('select');
	
	
	for(i=0; i < selects.length; i++) {
		passed = 0;
		if(getBottom(selects[i]) >= getTop(invueDiv)) {
			passed++;
		}
		if(getTop(selects[i]) <= getBottom(invueDiv)) {
			passed++;
		}
		if(getRight(selects[i]) >= getLeft(invueDiv)) {
			passed++;
		}
		if(getLeft(selects[i]) <= getRight(invueDiv)) {
			passed++;
		}
		if(invueDiv.style.visibility == 'visible') {
			passed++;
		}
		
		if(passed >= 5) {
			selects[i].style.visibility='hidden';
		}
		else {
			selects[i].style.visibility='visible';
		}
	}
	//invueDiv.innerHTML = 'select[4] ' + getTop(selects[4]) + ', ' + getLeft(selects[4]) + ' ' + getBottom(selects[4]) + ', ' + getRight(selects[4]) + '<br>' + 'invueDiv ' + getTop(invueDiv) + ', ' + getLeft(invueDiv) + ' ' + getBottom(invueDiv) + ', ' + getRight(invueDiv); 
}

function getTop(checkElement) {
	theElement = checkElement;
	newTop = 0;
	while(theElement.offsetParent) {
		newTop  += theElement.offsetTop;
		theElement = theElement.offsetParent;
	}
	return newTop;
}

function getBottom(element) {
	if(parseInt(element.style.height)) {
		return (getTop(element) + parseInt(element.style.height));
	}
	else {
		return (getTop(element) + element.clientHeight);
	}
}

function getLeft(checkElement) {
	theElement = checkElement;
	newLeft = 0;
	while(theElement.offsetParent) {
		newLeft  += theElement.offsetLeft;
		theElement = theElement.offsetParent;
	}
	return newLeft;
}

function getRight(element) {
	if(parseInt(element.style.width)) {
		return (getLeft(element) + parseInt(element.style.width));
	}
	else {
		return (getLeft(element) + element.clientWidth);
	}
}

function closeFloater() {	
	setCookie('BAT_invue_shown', '1');	
	
	invueDiv.style.visibility='hidden';
}

function forwardUser() {
	window.onunload=null;
	document.body.onunload=null;

	fwdQS = getFwdVars();
	
	document.location = getForwardAddress() + '?' + fwdQS;
}

function getFwdVars() {
	thisPage = getCookie('BAT_last_page');
	viewedHotels = getCookie('BAT_viewed_hotels');
	searchDates = getCookie('BAT_search_dates');
	searchString = getCookie('BAT_search_string');
	
	fwdQS = "&ID=" + escape(srcId);
	fwdQS += "&SA=" + escape(saId);
	fwdQS += "&SS=" + escape(searchString);
	fwdQS += "&VH=" + escape(viewedHotels);
	fwdQS += "&SD=" + escape(searchDates);
	fwdQS += "&LP=" + escape(lastPage);
	fwdQS += "&TP=" + escape(thisPage);
	
	return fwdQS;
}

function getForwardAddress() {
	return fwdAddress;
}

function changeLinks() {
	theLinks = document.getElementsByTagName('a');
	
	for(i = 0; i < theLinks.length; i++) {
		if(theLinks[i].onclick) {
			theLinks[i].tempAttr = theLinks[i].onclick;
		}
		
		theLinks[i].onclick=setClickedHost;
	}
	
	theLinks = document.getElementsByTagName('form');
	
	for(i = 0; i < theLinks.length; i++) {
		if(theLinks[i].onsubmit) {
			theLinks[i].tempAttr = theLinks[i].onsubmit;
		}
		
		theLinks[i].onsubmit=setSubmitHost;
	}
}

function setClickedHost(e) {
	if(!e) e=window.event;
	
	if(e.srcElement) {
		sEl = e.srcElement;
	}
	else {
		sEl = e.target;
	}
	
	while(sEl && sEl.tagName != 'A') {
		sEl = sEl.parentNode;
	}
	
	newLoc = document.createElement('A');
	newLoc.href = sEl.href;
	if(newLoc.protocol == 'javascript:') {
		BAT_clickedHost = '';
	}
	else {
		BAT_clickedHost = newLoc.hostname.toLowerCase();
	}
	
	if(sEl.tempAttr) {
		return sEl.tempAttr();
	}
	
}

function setSubmitHost(e) {
	if(!e) e=window.event;
	
	if(e.srcElement) {
		sEl = e.srcElement;
	}
	else {
		sEl = e.target;
	}
	
	newLoc = document.createElement('A');
	newLoc.href = sEl.action;
	
	if(!newLoc.hostname) {
		BAT_clickedHost = document.location.hostname.toLowerCase();	
	}
	else if(newLoc.protocol == 'javascript:') {
		BAT_clickedHost = '';
	}
	else {
		BAT_clickedHost = newLoc.hostname.toLowerCase();
	}
	
	if(sEl.tempAttr) {
		return sEl.tempAttr();
	}
}

function doPopUnder(e) {

	tempArr = document.location.hostname.toLowerCase().split('.');
	if(tempArr.length > 1) {
		currDomain = tempArr[tempArr.length-2] + '.' + tempArr[tempArr.length-1];
	}
	else {
		currDomain = document.location.hostname.toLowerCase();
	}

	if(BAT_clickedHost) {
		tempArr2 = BAT_clickedHost.split('.');
	}
	else {
		BAT_clickedHost = '***dopop***';
		tempArr2 = new Array();
	}
	
	if(tempArr2.length > 1) {
		nextDomain = tempArr2[tempArr2.length-2] + '.' + tempArr2[tempArr2.length-1];
	}
	else {
		nextDomain = BAT_clickedHost;
	}

	var mquery = "&src=" + escape(getSrcId()) + "&src_aid=" + escape(saId);
	document.bathiddenimage.src = TRACK_POPUP_IMAGE + mquery;

	popUnderWindow = window.open('', 'bat_popup', 'width=' + POPUP_WIDTH +',height=' + POPUP_HEIGHT +',top=' + POPUP_TOP +',left=' + POPUP_LEFT +',' + POPUP_OPTS);

	popUnderWindow.blur();
	window.focus();

	try {
			popUnderWindow.document.write(windowText);			
			popUnderWindow.setTimeout("try {if(window.opener.document.location.hostname == document.location.hostname) {window.close();}} catch(oException) {window.focus()}", INVUE_TIMEOUT);
		}
	catch(oException) {
			popUnderWindow.close();
		}

}
try
	{
	var mform = document.getElementById('chk_in').form;
	}
catch (e)
	{
	}

if (window.addEventListener) { // DOM method for binding an event
	try
	{
		mform.addEventListener("submit", doPopUnder, false);
		window.addEventListener("load", initBATPage, false);
	}
	catch (e)
	{
	}
}
else if (window.attachEvent) { // IE exclusive method for binding an event
	try
	{
		mform.attachEvent("onsubmit", doPopUnder);
		window.attachEvent("onload", initBATPage);
	}
	catch (e)
	{
	}
}

