
var _airPreferredCT = new Array("EXPEDIA","TVLOCITY","PRICLINE");

var _visSpans = new Array();
_visSpans["flight"] = new Array();
_visSpans["car"] = new Array();
_visSpans["cruise"] = new Array();
_visSpans["hotel"] = new Array();
_visSpans["vacation"] = new Array();

var _prefCT = new Array();
_prefCT["flight"]= new Array("EXPEDIA","TVLOCITY","PRICLINE");
_prefCT["car"]= new Array("CARRNTLS","PRICLINE","EXPEDIA");
_prefCT["cruise"] = new Array("CRZNMORE","CRUISE","AVC");
_prefCT["hotel"] = new Array("HOTWIRE","HOTELSDC","EXPEDIA");
_prefCT["vacation"] = new Array("BOOKIT","TVLOCITY","CHEAPCBN");


    function isPreferred(provider, preferreds) {
    	var i = 0;
    	for(i=0;i<preferreds.length;i++) {

    		if(provider.id.indexOf(preferreds[i]) > -1) {
    			return true;
    		}	
    	}
    	return false;
    }

 // CODE TO TURN COMPARE TO STUFF ON OFF

    function getCmp2Args() {
    
    	var id=document.getElementById('selectedSideBar').value;
    	var args;
    	if (id == 0) {
				form = document.kFlightForm;
				args="ptype=flights";
				args += "&depart_date=" + form["depart_date"].value;
		        args += "&return_date=" + form["return_date"].value;
		        args += "&origin=" + form["l1name"].value;
		        args += "&origincode=" + form["l1"].value;
		        args += "&destination=" + form["l2name"].value;
		        args += "&destcode=" + form["l2"].value;
		        args += "&cabin=e";
			} else if (id == 1) {
				form = document.kHotelForm;
				args= "ptype=hotels";
	            args += "&checkin_date=" + form["checkin_date"].value;
	            args += "&checkout_date=" + form["checkout_date"].value;
	            args += "&location=" + form["ctid"].value;
	            args += "&citycode=" + form["ctid"].value;
			} else if (id == 2) {
				form = document.kykCarForm;
				args= "ptype=cars";
				args += "&pickup_date=" + form["d1"].value;
	            args += "&dropoff_date=" + form["d2"].value;
	            args += "&location1=" + form["ctid"].value;
	            args += "&citycode1=" + form["ctid"].value;
			} else if (id == 3) {
				form = document.CruiseSearchCityForm;
				args= "ptype=cruises";
				args += "&depart_date=" + form["cruise_date"].value;
		        args += "&destination=" + form["cruiseDest"].value;
			} else if (id == 4) {
				form = document.kVacationForm;
				args= "ptype=vacations";
				args += "&depart_date=" + form["vacaton_depart_date"].value;
		        args += "&return_date=" + form["vacation_return_date"].value;
		        args += "&origin=" + form["vacl1name"].value;
		        args += "&origincode=" + form["l1"].value;
		        args += "&destination=" + form["vacl2name"].value;
		        args += "&destcode=" + form["l2"].value;
			} else {
               return;
        }
 		return args;
    }
    
    function _runPresetSearch(input, locParam, searchType, language, cc)
	{
	    if (sbHttp==null) {sbHttp = new R9HTTPXml();}
	    if (!sbHttp.inprogress)
	    {
	
	        var buffer = "where=" + encodeURIComponent(locParam);
	        var sbHttp = new R9HTTPXml();
	        buffer += "&lc="+language+"&lc_cc="+cc;
	        var cb;
	        if (searchType == "flight") {
	            buffer += "&s=1";
	            cb= new lpFlightInputInitCallback(input);
	        } else if (searchType == "car") {
	            buffer += "&s=2";
	            cb= new lpCarInputInitCallback(input);
	        } else if (searchType == "hotel") {
	            buffer += "&s=3";
	            cb= new lpHotelInputInitCallback(input);
	        } else if (searchType == "any") {
	            buffer += "&s=4";
	        } else if (searchType == "cruises") {
	            buffer += "&s=5";
	        } else if (searchType == "crcg") {
	            buffer += "&s=6";
	        } else if (searchType == "deal") {
	            buffer += "&s=7";
	        } else if (searchType == "crcga") {
	            buffer += "&s=8";
	        } else {
	            buffer+="&s="+searchType;
	            cb= new lpFlightInputInitCallback(input);
	        }
	        if (_sbcountrycode != null && _sbcountrycode.length > 0) {
	            buffer += "&cc=" + _sbcountrycode;
	        }
	
	        // html format
	        buffer += "&f=h";
	
	        // extra args
	        buffer += _sbextraargs;
	
	        sbHttp.init(_kayakSmartUrl, buffer);
	        try {
	            sbHttp.setTimeout(10000);
	            sbHttp.asyncGET(cb);
	        } catch (e) {
	        }
    }
}
    

    function lpInputInit(input, locParam,searchType, language, cc) {
    	_runPresetSearch(input,locParam, searchType, language, cc);
    }

	
	function getFlightLocValueFromSB(payload) {

		var idx = payload.indexOf('id="');
		var dashIdx = -1;
		var slashIdx = -1;
		var val = null;
		if(idx > -1) {
			val = payload.substring(idx+4,payload.indexOf('"',idx+4));
			dashIdx = val.indexOf('-');
			slashIdx = val.indexOf('/');
			if(dashIdx > -1 && slashIdx > -1 && dashIdx < slashIdx) {
				val = val.substring(dashIdx+1,slashIdx);
			} else {
				return null;
			}
		}
	    return val;

	}
	
	function getHotelLocValueFromSB(payload) {

		var idx = payload.indexOf('id="');
		var dash1Idx = -1;
		var dash2Idx = -1;
		var val = null;
		if(idx > -1) {
			val = payload.substring(idx+4,payload.indexOf('"',idx+4));
			dash1Idx = val.indexOf('-');
			dash2Idx = val.indexOf('-',dash1Idx+1);
			if(dash1Idx > -1 && dash2Idx > -1 && dash1Idx < dash2Idx) {
				val = val.substring(dash1Idx+1,dash2Idx);
			} else {
				return null;
			}
		}
	    return val;

	}
	
	function getCarLocValueFromSB(payload) {

		var idx = payload.indexOf('id="');
		var dashIdx = -1;
		var val = null;
		if(idx > -1) {
			val = payload.substring(idx+4,payload.indexOf('"',idx+4));
			dashIdx = val.indexOf('-');
			if(dashIdx > -1 ) {
				val = val.substring(dashIdx+1,val.length);
			} else {
				return null;
			}
		}
	    return val;

	}

    // Uses the 3 letter airport code

    function lpFlightInputInitCallback(field) {
     	prepost();
    	this.onError = function(status,statusText) { }
    	this.onLoad=function done(client) {
	    	var lpInputItemCount;
	        window.status = "";
	        if (!client.cancelled)
	        {
	            var locValue = getFlightLocValueFromSB(client.getText());
	            if(locValue != null) {
		            field.value = locValue;
		            compare2chk();
	            }
	        }
    	}

    }
    // Uses airport/cityid
    
    function lpCarInputInitCallback(field) {
     	prepost();
    	this.onError = function(status,statusText) { }
    	this.onLoad=function done(client) {
	    	var lpInputItemCount;
	        window.status = "";
	        if (!client.cancelled)
	        {
	            var locValue = getCarLocValueFromSB(client.getText());
	            if(locValue != null) {
		            field.value = locValue;
		            compare2chk();
	            }
	        }
    	}

    }
    //uses cityid
    
    function lpHotelInputInitCallback(field) {
     	prepost();
    	this.onError = function(status,statusText) { }
    	this.onLoad=function done(client) {
	    	var lpInputItemCount;
	        window.status = "";
	        if (!client.cancelled)
	        {
	            var locValue = getHotelLocValueFromSB(client.getText());
	            if(locValue != null) {
		            field.value = locValue;
		            compare2chk();
	            }
	        }
    	}

    }
    
    
    var compare2initializing = true;
    function compare2chk(callbackOverride)
    {
        if (compare2initializing) return;
			var form;
			var id = document.getElementById('selectedSideBar').value;
			if (id == 0) {
				form = document.kFlightForm;
			} else if (id == 1) {
				form = document.kHotelForm;
			} else if (id == 2) {
				form = document.kykCarForm;
			} else if (id == 3) {
				form = document.CruiseSearchCityForm;
			} else if (id == 4) {
				form = document.kVacationForm;
			} else {
               return;
            }
            var cbToUse = setCmp2Count();
            if (typeof callbackOverride == "function") {
                // Timing issue with IE, pause for a bit
                cbToUse = callbackOverride;
            }
            
            
            
            document.getElementById('visibleCompareToCt').value = 0;
            jQuery.getScript("/s/cmp2chk?" + getCmp2Args(id, form), cbToUse);

    }


    function allcmp2set(isOK)
    {
		var productType = document.getElementById('selectedSideBarName').value;
        try {
            var span = document.getElementById(productType+"compareToRow");
            if (isOK) {
                if (span.style.display == "none") {
                    span.style.display = "";
                }
            } else {
                span.style.display = "none";
            }
        } catch (ignored) {}
    }

    function cmp2set(isOK, code)
    {

		if (code != null && code.indexOf("KAYAK") == 0) return;

        var productType = document.getElementById('selectedSideBarName').value;

        var compareToRow = document.getElementById(productType+"compareToRow");
		var productSpans = _visSpans[productType];
		var preferredCTs = _prefCT[productType];
		var oneFound = false;
		var comparetoMax = document.getElementById('comparetoMax').value;
        try {
            var span = document.getElementById(productType+"site" + code);
            var checkbox = document.getElementById(productType+"cb" + code);
            var lbel = document.getElementById(productType+"label" + code);
            if(span != null) {
            	oneFound = true;
            }

            if (oneFound == true && isOK) {
            
                span.style.display="";
                lbel.innerHTML=lbel.innerHTML;
                compareToRow.style.display="";
                
                document.getElementById('visibleCompareToCt').value = parseInt(document.getElementById('visibleCompareToCt').value)+1;
                addSpan(productSpans,span);
                
                if (span.style.display != "none") {
                    checkbox.checked = checkbox.defaultChecked;
                    // Set code to code in case it has been swapped
                    checkbox.value = code;
                } else {
                	checkbox.checked = false;
                	span.style.display = "none";
            	}
            	
            	if(countVisible(productSpans) > comparetoMax) {
            		var i = 0;
            		for(i=0;i<productSpans.length;i++) {
            			if(countVisible(productSpans) > comparetoMax) {
            				var ctSpan = productSpans[i];
	            			if(isPreferred(ctSpan,preferredCTs) == false) {
	            				ctSpan.style.display = 'none';
	            				var cbId = ctSpan.id.replace("site","cb");
	            				var cbCheck = document.getElementById(cbId);
	            				cbCheck.checked = false;
	            				document.getElementById('visibleCompareToCt').value = countVisible(productSpans);
	            			}
	            		}
            		}
            	}
            	
            } else {
                checkbox.checked = false;
                span.style.display = "none";
                if(countVisible(productSpans) == 0) {
                	compareToRow.style.display="none";
                }
            }
            document.getElementById('visibleCompareToCt').value = countVisible(productSpans);
        } catch (ignored) {}
    }
    
    function addSpan(spans, span) {
        var i = 0;
    	for(i=0;i<spans.length;i++) {
    		if(spans[i].id == span.id) {
    			return;
    		}
    	}
    	spans.push(span);
    }
    
    function countVisible(spans) {
    	var ct = 0;
    	var i = 0;
    	for(i=0;i<spans.length;i++) {
    		if(spans[i].style.display == 'none') {
    		} else {
    			ct = ct+1;
    		}
    	}
    	return ct;
    }

    // This function takes an original code that was present, enables it, then changes the value
    // For now used to swap EXPEDIA domestic and international codes
    function cmp2swap(origcode, newcode)
    {
        // Turn it on just in case
        cmp2set(true, origcode);
        // Swap the code
        var productType = document.getElementById('selectedSideBarName').value;
        try {
            var checkbox = document.getElementById(productType+"cb" + origcode);
            checkbox.value = newcode;
        } catch (ignored) {}
    }

    // This function adjusts the prechecked state of the checkbox
    function cmp2precheck(isChecked, code)
    {
        try {
        	var productType = document.getElementById('selectedSideBarName').value;
            var checkbox = document.getElementById(productType+"cb" + code);
            checkbox.checked = isChecked;
        } catch (ignored) {}
    }
    
    
    function prepost() {
    
        // initialize the compare-to
        compare2initializing = false;

    
    }
    
