/* compare me to */

var compare_validated = false;
var compare_validated_baseurl = '';
var valid_providers = new Array();

function compare_validate_parse(base_url, validation_data) {
    var status_rows = validation_data.split("|");
    if (status_rows[0]) {
	var status = status_rows[0].split(":");
	if (status[1] == "fail") {
	    compare_validated = false;
	    return;
	} else {
	    valid_providers = new Array();
	    compare_validated = true;
	    /* here's where we'll pick out the providers that passed */
	    if (status_rows.length > 1) {
	        for (var i=1; i<status_rows.length; i++) {
		    valid_providers[i] = status_rows[i];
		}
	    }
	    return;
	}
    } else {
	compare_validated = false;
	return;
    }
}

function open_compare_window() {
    if (typeof(open_compare_window.times_called) == 'undefined') {
	open_compare_window.times_called = 0;
    }
    open_compare_window.times_called++;
    if (!compare_validated) {
	if (open_compare_window.times_called == 1) {
	    // unvalidated parameters, and the first time we've called this
	    // attempt to validate
	    document.getElementById("submit_button").innerHTML = "<span style=\"font-size:16px;font-weight:bold;padding-right:10px;color:#ff6600;\">Please wait </span><img src=\"images/work_indicator.gif\">";
	    compare_validate();
	    setTimeout('open_compare_window()', 750)
	    return false;
	} else {
	    // invalid parameters (or timed out), start the usual search
	    run_mobi_search();
	    return true;
	}
    }

    try {
	var comp_array = new Array();
	var comp_index = 0;
	// check if the checkbox is checked

	if (valid_providers.length > 0) {
	    for (var i = 0; i < document.compare_search.comp_box.length; i++) {
		if (document.compare_search.comp_box[i].checked) {
		    id = document.compare_search.comp_box[i].value;
		    if (id != "dummy_checkbox") {
			for (var j=0; j<valid_providers.length; j++) {
			    if (valid_providers[j] == id) {
				priority = 0; // set default
				if (document.getElementById('priority_comp_'+id).value) {
				    priority = document.getElementById('priority_comp_'+id).value;
				}
				comp_array[comp_index] = new Array();
				comp_array[comp_index]["id"] = id;
				comp_array[comp_index]["priority"] = priority;
				comp_index++;
			    }
			}
		    }
		}
	    }
	} else {
	    for (var i = 0; i < document.compare_search.comp_box.length; i++) {
		if (document.compare_search.comp_box[i].checked) {
		    id = document.compare_search.comp_box[i].value;
		    if (id != "dummy_checkbox") {
			priority = 0; // set default
			if (document.getElementById('priority_comp_'+id).value) {
			    priority = document.getElementById('priority_comp_'+id).value;
			}
			comp_array[comp_index] = new Array();
			comp_array[comp_index]["id"] = id;
			comp_array[comp_index]["priority"] = priority;
			comp_index++;
		    }
		}
	    }
	}
	comp_array.arsort('priority');
	var base_url = compare_validated_baseurl;

	comp_array.each(function(obj, index) {
	    var url = base_url + "&id=" + obj.id;
	    var window_name = obj.id.replace("-","_") + Math.floor(Math.random()*100);
	    //var w = window.open(url,'','width=600,height=600,resizable=yes,scrollbars=yes,toolbar=yes,location=yes,status=yes,menubar=yes');
	    var w = window.open(url, window_name,'width=600,height=600,resizable=yes,scrollbars=yes,toolbar=yes,location=yes,status=yes,menubar=yes');
	    w.blur();
	});
    } catch (e) { }
    if (open_compare_window.times_called > 1) {
	// if this is our second time through, start search by hand
	// this condition can probably be removed
	run_mobi_search();
    }
    return true;
}

function open_compare_result_window(id) {
    var depCity = escape(document.getElementById('depCity').value);
    var retCity = escape(document.getElementById('retCity').value);
    var depMonth = document.getElementById('depMonth').value;
    var depDay = document.getElementById('depDay').value;
    var retMonth = document.getElementById('retMonth').value;
    var retDay = document.getElementById('retDay').value;
    var NumTix = document.getElementById('numTix').value;
    var Class = document.getElementById('tixClass').value;
    if (document.getElementById('roundtrip').checked) {
	var Type = "roundtrip";
    } else {
	var Type = "oneway";
    }
   
    var url = "compare_to.php?depCity=" + depCity + "&retCity=" + retCity + "&depMonth=" + depMonth + "&depDay=" + depDay + "&retMonth=" + retMonth + "&retDay=" + retDay + "&NumTix=" + NumTix + "&Type=" + Type + "&Class=" + Class + "&searchtype=" + searchtype + "&id=" + id + "&page=results";
    var window_name = id + Math.floor(Math.random()*100);
    var w = window.open(url, window_name,'width=600,height=600,resizable=yes,scrollbars=yes,toolbar=yes,location=yes,status=yes,menubar=yes');
    w.blur();

}

function open_compare_result_hotel_window(id) {
    var depCity = escape(document.getElementById('depCity').value);
    var retCity = escape(document.getElementById('retCity').value);
    var depMonth = document.getElementById('depMonth').value;
    var depDay = document.getElementById('depDay').value;
    var retMonth = document.getElementById('retMonth').value;
    var retDay = document.getElementById('retDay').value;
    var NumTix = document.getElementById('numTix').value;
   
    var url = "compare_to.php?dest=" + retCity + "&arrMonth=" + depMonth + "&arrDay=" + depDay + "&depMonth=" + retMonth + "&depDay=" + retDay + "&numGuests=" + NumTix + "&numRooms=1&searchtype=hotel&id=" + id + "&page=results";
    var window_name = id + Math.floor(Math.random()*100);
    var w = window.open(url, window_name,'width=600,height=600,resizable=yes,scrollbars=yes,toolbar=yes,location=yes,status=yes,menubar=yes');
    w.blur();

}


Array.prototype.arsort = function(key) {
    this.sort(function(a, b) {
	return (a[key] < b[key]) ? 1 : -1;
    });
}



function compare_validate() {
    var searchtype = document.getElementById('searchtype').value;
    if (searchtype == "air") {
	if (document.getElementById('roundtrip').checked) {
	    var Type = "roundtrip";
	} else {
	    var Type = "oneway";
	}
	var depCity = escape(document.getElementById('depCity').value);
	var retCity = escape(document.getElementById('retCity').value);
	var depMonth = document.getElementById('depMonth').value;
	var depDay = document.getElementById('depDay').value;
	var retMonth = document.getElementById('retMonth').value;
	var retDay = document.getElementById('retDay').value;
	var NumTix = document.getElementById('numTix').value;
	var Class = document.getElementById('tixClass').value;
	var ssid = document.getElementById('sessionid').value;

	var base_url = "compare_to.php?depCity=" + depCity + "&retCity=" + retCity + "&depMonth=" + depMonth + "&depDay=" + depDay + "&retMonth=" + retMonth + "&retDay=" + retDay + "&NumTix=" + NumTix + "&Type=" + Type + "&Class=" + Class + "&ssid=" + ssid + "&searchtype=" + searchtype;
	var validate_url = base_url + "&mode=validate";
    } else if (searchtype == "hotel") {
	var dest = escape(document.getElementById('dest').value);
	var arrMonth = document.getElementById('arrMonth').value;
	var arrDay = document.getElementById('arrDay').value;
	var depMonth = document.getElementById('depMonth').value;
	var depDay = document.getElementById('depDay').value;
	var numGuests = document.getElementById('numGuests').value;
	var numRooms = document.getElementById('numRooms').value;
	var ssid = document.getElementById('sessionid').value;

	var base_url = "compare_to.php?dest=" + dest + "&arrMonth=" + arrMonth + "&arrDay=" + arrDay + "&depMonth=" + depMonth + "&depDay=" + depDay + "&numGuests=" + numGuests + "&numRooms=" + numRooms + "&ssid=" + ssid + "&searchtype=" + searchtype;
	var validate_url = base_url + "&mode=validate";
    } else if (searchtype == "car") {
	var pulocation = escape(document.getElementById('pulocation').value);
	if (document.getElementById('atairport').checked) {
	    var atairport = true;
	} else {
	    var atairport = false;
	}
	var pickupMonth = document.getElementById('pickupMonth').value;
	var pickupDay = document.getElementById('pickupDay').value;
	var pickupHour = document.getElementById('pickupHour').value;
	var dropoffMonth = document.getElementById('dropoffMonth').value;
	var dropoffDay = document.getElementById('dropoffDay').value;
	var dropoffHour = document.getElementById('dropoffHour').value;
	var cartype = document.getElementById('cartype').value;
	var ssid = document.getElementById('sessionid').value;

	var base_url = "compare_to.php?pulocation=" + pulocation + "&atairport=" + atairport + "&pickupMonth=" + pickupMonth + "&pickupDay=" + pickupDay + "&pickupHour=" + pickupHour + "&dropoffMonth=" + dropoffMonth + "&dropoffDay=" + dropoffDay + "&dropoffHour=" + dropoffHour + "&cartype=" + cartype + "&ssid=" + ssid + "&searchtype=" + searchtype;
	var validate_url = base_url + "&mode=validate";
    }

    /* set the global base URL */

    compare_validated_baseurl = base_url;
    var request;
    if (window.XMLHttpRequest) { // Mozilla, etc
	request = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
	request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (!request) { /* request failed, just submit the form */
        return true;
    }
    request.onreadystatechange = function() {
	if (request.readyState == 4) {
	    if (request.status == 200) {
		var data = request.responseText;
		compare_validate_parse(base_url, data);
	    }
	}
    }
    request.open('GET', validate_url, true);
    request.send(null);

    /* XXX -- put a timeout here for the validator */
    return false;
}


function toggleCheckbox(cbId, cbKey, ffId) {
    if (cbKey==0||cbKey==32){
	var cbFF = document.getElementById(ffId);
	var cbFFValue = cbFF.checked;
	var compName = cbFF.value;
	var loc = location.href;
	if (loc.match("search_airfare")){
	    var search_type = "air";
	} else if (loc.match("search_hotel")) {
	    var search_type = "hotel";
	} else if (loc.match("search_car")) {
            var search_type = "car";
	}

	var comp_full_name = "compare_" + search_type + "_" + compName;
	comp_cookie = getCookie("compare_check_status");
	if(cbId.className.indexOf("comp_checked")<0) {
	    var checkBoxType = cbId.className.replace("comp_unchecked","");
	    cbFF.checked=true;
	    cbId.className="comp_checked";
	    if (comp_cookie.match(comp_full_name)) {
		comp_cookie = comp_cookie.replace(comp_full_name, "");
	    }
	} else {
	    var checkBoxType = cbId.className.replace("comp_checked","");
	    cbFF.checked=false;
	    cbId.className="comp_unchecked";
	    if (!comp_cookie.match(comp_full_name)) {
		//comp_cookie += "," + comp_full_name;
		comp_cookie += comp_full_name + ",";
	    }
	}
	if (comp_cookie.length > 0 && comp_cookie.charAt(0) == ",") {
	    comp_cookie = comp_cookie.replace(/\,/, "");
	}
	comp_cookie = comp_cookie.replace(/\,\,/, "\,");
	setCookie("compare_check_status",comp_cookie,365); 
	return false;
    }
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toUTCString()) + ";path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
	c_start = document.cookie.indexOf(c_name + "=");
	if (c_start != -1) {
	    c_start = c_start + c_name.length+1;
	    c_end = document.cookie.indexOf(";",c_start);
	    if (c_end == -1) {
		c_end=document.cookie.length;
	    }
	    return unescape(document.cookie.substring(c_start,c_end));
	}
    }
    return "";
}

function comp_set_all(set_to) {
    var selection_trigger = true;
    if (set_to == 'selected') {
	selection_trigger = false;
    }
    var compare_divs = document.getElementsByClassName("comp_checkbox"); 
    for (var i=0; i < compare_divs.length; i++) {
	var cds = compare_divs[i].childNodes;
	for (var j=0; j < cds.length; j++) {
	    if (cds[j].name == "comp_box") {
		var checkbox = cds[j];
		var id = checkbox.value;
	    }
	}
	var a_element = compare_divs[i].getElementsByTagName("a")[0];
	
	if (id != 'dummy_checkbox' && checkbox.checked == selection_trigger) {
	    toggleCheckbox(a_element, '', "comp_" + id);
	}
    }
}

/* compat functions; remove later */
function comp_select_all() { comp_set_all('selected'); }
function comp_unselect_all() { comp_set_all('unselected'); }

function InitialiseCheckboxes() {
    var inputFields = document.getElementsByTagName("span");
    var checkboxIndex = 0;
    for (var inputIndex = 0; inputIndex < inputFields.length; inputIndex++) {
	if (inputFields[inputIndex].className.indexOf("comp_checkbox")==0) {
	    var styleType = "";
	    styleType = inputFields[inputIndex].className.replace("comp_checkbox","");
	    if(styleType == "comp_checkbox"){styleType="";};
	    inputFields[inputIndex].className = styleType;

	    var inputCurrent = inputFields[inputIndex].getElementsByTagName("input").item(0);
	    if(inputCurrent.getAttribute("type")=="checkbox") {
		inputCurrent.className = "InputHidden";
		inputCurrent.setAttribute("id","comp_checkbox"+checkboxIndex);

		if(navigator.appName.indexOf("Internet Explorer")>0||navigator.userAgent.indexOf("Netscape")>0) {
		    //Internet Explorer
		    var inputHTML = inputFields[inputIndex].innerHTML;
		    var styledHTML = "<a"//href=\"#\""
		    styledHTML+=" tabindex=\""+inputIndex+"\"";

		    if(inputCurrent.hasAttribute){
			if(inputCurrent.hasAttribute("title")){
			    styledHTML+=" title=\""+inputCurrent.getAttribute("title")+"\"";
			}
		    }

		    if (inputCurrent.checked) {
			styledHTML+=" class=\"comp_checked\""
		    } else {
			styledHTML+=" class=\"comp_unchecked\""
		    }

		    styledHTML+=" onClick=\"toggleCheckbox(this,'','comp_checkbox"+checkboxIndex+"');return false;\""
		    styledHTML+=" onKeyPress=\"return toggleCheckbox(this,event.keyCode,'comp_checkbox"+checkboxIndex+"');\""

		    if(navigator.userAgent.indexOf("Netscape")>0) {
			styledHTML+="><img src=\"formStyle.gif\" /></a>"
		    } else {
			styledHTML+="></a>"
		    }

		    inputFields[inputIndex].innerHTML = inputHTML+styledHTML;
		    inputFields[inputIndex].className = "Radiobox"+styleType;
		} else {
		    var styledCheckbox = document.createElement("a"); 
		    styledCheckbox.setAttribute("href","#");

		    if(inputCurrent.hasAttribute){
			if(inputCurrent.hasAttribute("title")){
			    styledCheckbox.setAttribute("title",inputCurrent.getAttribute("title"));
			}
		    }

		    styledCheckbox.setAttribute("onClick","toggleCheckbox(this,'','comp_chechbox"+checkboxIndex+"');return false;");
		    styledCheckbox.setAttribute("onKeyPress","return toggleCheckbox(this,event.keyCode,'comp_checkbox"+checkboxIndex+"');");
		    if (inputCurrent.checked) {
			styledCheckbox.className="comp_checked"+styleType;
		    } else {
			styledCheckbox.className="comp_unchecked"+styleType;
		    }
		    inputFields[inputIndex].appendChild(comp_checkbox);
		}

		checkboxIndex++;
	    }
	}
    }	
}

function checkImages() {
    if (document.getElementById) {
	var x = document.getElementById('formStyleTestImage').offsetWidth;
	if (x == '1'||x == '7') {
	    document.getElementById('formStyleTestImage').style.display='none';
	    return true;
	}else{
	    return false;
	}
    }
}


function preloadImages() {
    img1 = new Image();img1.src = "external/images_nonmobi/checkbox_none.png";
    img1 = new Image();img1.src = "external/images_nonmobi/checkbox_grey.png";
    img1 = new Image();img1.src = "external/images_nonmobi/checkbox_orange.png";
}

function Initialise() {
    if(checkImages()){
	preloadImages();
	InitialiseCheckboxes();
	//InitialiseRadioboxes();
    }
}

window.onload = Initialise;

