//
// RSS Feed Fetching
//



// entry point
function feedMe(baseUrl, div) {
  var url = '/xmlget.cgi?label=' + div + '&url=' + escape(baseUrl);
  loadXML(url, onFetchedRSSCb, div);
}

function rssFeed0() {
  var url = 'http://www.kayak.com/h/rss/deals?n=3';
  var div = 'rssFeed0';
  feedMe(url,div);
}

function rssFeed1() {
  var url = 'http://wikitravel.org/rss/english.rss';
  var div = 'rssFeed1';
  feedMe(url,div);
}



//
// stagger the loads so they don't all smush at once.
//
function myRssLoad() {
  setTimeout("rssFeed0()", 500);
  setTimeout("rssFeed1()", 1000);
}


//
// to process a single line-item from the RSS feed.
// this would change for each type of RSS feed to
// be displayed since it's dependent upon the div etc.
//
function onFetchedRSSLineItem(sentinel,iTitle,iLink,iDesc,div) {

  if (sentinel == "initial") {
    setDivText(div, '');
    return;
  } else if (sentinel == "termination") {
    return;
  }

  var ll = iTitle.length;
  var tLen = 50;
  if (ll > tLen) {
    iTitle = iTitle.substring(0, tLen) + " ...";
  } 

  var msg = '<li><a class="link" href="' + iLink + '">';
  msg += iTitle+ '<' + '/a></li>'; 
  appendDivText(div, msg);
}

function fmErrorMsg(msg) {
  alert(msg);
}

//
// called when done loading the URL.
// liCb -- is callback for each line-item
// this is generic code.
//
function onFetchedRSSCb(xmldoc,url,divName) {

  var maxDisplayCnt = 3;

  if ((! xmldoc) || (!xmldoc.xml)) {
    fmErrorMsg('0 bytes returned for ' + url);
    return;
  }

  var cElement = xmldoc.getElementsByTagName("channel");
  if (1 != cElement.length) {
    fmErrorMsg('no channel found within ' + url);
    return;        
  }

  cElement = cElement[0];

  var cTitle = getSingleChildObjValue(cElement, 'title');
  if (! cTitle) {
    fmErrorMsg('title not found within ' + url);
    return;         
  }

  var cDesc = getSingleChildObjValue(cElement, 'description');
  if (! cDesc) {
    cDesc = 'No description found';
  }

  var cLink = getSingleChildObjValue(cElement, 'link');
  if (! cLink) {
    fmErrorMsg('link not found within ' + url);
    return;         
  }

  var itemList = xmldoc.getElementsByTagName("item");
  var itemCnt = itemList.length;

  onFetchedRSSLineItem('initial',null,null,null,divName);
  for (var i = 0; ((i < itemCnt ) && (i < maxDisplayCnt)); i++) {
    var item = itemList[i];
    var iTitle = getSingleChildObjValue(item, 'title');
    var iLink = getSingleChildObjValue(item, 'link');
    var iDesc = getSingleChildObjValue(item, 'description');
    if ((! iDesc) || (0 == iDesc.length)) {
      iDesc = iTitle;    
    }

    onFetchedRSSLineItem('line-item',iTitle,iLink,iDesc,divName);
  }
  onFetchedRSSLineItem('termination',null,null,null,divName);
}



// this function gets the cookie, if it exists
function Get_Cookie( name ) {
	
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
	{
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

//
// drives this application
//

//
function buzzLookup() {
   var l1 = new String(Get_Cookie("homeAirport")) || "BOS";
   var l2 = new String(Get_Cookie("destAirport")) || "SFO";
   if (l1 && l2) {
     rssBuzzPair(l1,l2);
   }
}


//
//
//
function onPagePostLoad() {
   var lastHomeAirPort = Get_Cookie("homeAirport");  
   var lastDestAirPort = Get_Cookie("destAirport");  

   var lastDepartDate = Get_Cookie("departDate");  
   var lastReturnDate = Get_Cookie("returnDate");  

   var lastDestCity = Get_Cookie("destCity");

   if ((!lastDepartDate) || (0 == lastDepartDate.length) ) {
     var today = new Date();
     var mm = today.getMonth() + 1;
     var dd = today.getDate();
     var yyyy = today.getFullYear();		
     lastDepartDate = mm + "/" + dd + "/" + yyyy;
   }
  Set_Cookie("departDate",lastDepartDate,90);

   if (!lastReturnDate || (0 == lastReturnDate.length)) {
     var today = new Date();
     today.setDate(today.getDate()+7);
     var mm = today.getMonth() + 1;
     var dd = today.getDate();
     var yyyy = today.getFullYear();		
     lastReturnDate = mm + "/" + dd + "/" + yyyy;

   }
   Set_Cookie("returnDate",lastReturnDate,90);

   if ((! lastHomeAirPort) || (0 == lastHomeAirPort)) {
     lastHomeAirPort = "BOS";
     Set_Cookie("homeAirport",lastHomeAirPort,90);
   }

   if ((! lastDestAirPort) || (0 == lastDestAirPort)) {
     lastDestAirPort = "LAS";
     Set_Cookie("destAirport",lastDestAirPort,90);
   }

   document.kykFlightForm.l1.value = lastHomeAirPort;
   document.kykFlightForm.l2.value = lastDestAirPort;

   document.kykFlightForm.d1.value = lastDepartDate;
   document.kykFlightForm.d2.value = lastReturnDate;

   document.kykHotelForm.d1.value = lastDepartDate;
   document.kykHotelForm.d2.value = lastReturnDate;

   document.kykCarForm.d1.value = lastDepartDate;
   document.kykCarForm.d2.value = lastReturnDate;

   document.kykHotelForm.crc.value = lastDestCity;
   document.kykCarForm.crc.value = lastDestCity;
   if (! document.kykHotelForm.crc.value) {
     document.kykHotelForm.crc.value = getGeoAddr();
     document.kykCarForm.crc.value =  document.kykHotelForm.crc.value;
   }


   myRssLoad();

   return;
}

function updateHistory() {
  var d1 = Get_Cookie("departDate");  
  var d2 = Get_Cookie("returnDate");  
  var l1 = Get_Cookie("homeAirport");  
  var l2 = Get_Cookie("destAirport");  

  var title = l1 + ' to ' + l2;
  var link = 'http://kayak.com/s/search/air?do=n&ai=giza&l1=';
	link += l1 + '&l2=' + l2;
  link += '&d1=' + escape(d1);
  link += '&d2=' + escape(d2);
  var u = '<a target=newW class=link href="' + link + '">' + title + '</a>';
  setDivText('airHist', 'Flights from ' + u);

  var crc =  document.kykHotelForm.crc.value;
  d1 =  document.kykHotelForm.d1.value;
  d2 =  document.kykHotelForm.d2.value;
  title = crc;
  link = 'http://kayak.com/s/search/hotel?do=n&ai=giza&crc=';  	
  link += escape(crc);
  u = '<a target=newW class=link href="' + link + '">' + title + '</a>';
  setDivText('hotelHist', 'Hotels in ' + u);

  crc =  document.kykCarForm.crc.value;
  d1 =  document.kykCarForm.d1.value;
  d2 =  document.kykCarForm.d2.value;
  title = crc;
  link = 'http://kayak.com/s/search/car?do=n&ai=giza&crc=';  	
  link += escape(crc);
  u = '<a target=newW class=link href="' + link + '">' + title + '</a>';

  setDivText('carHist', 'Rental cars in ' + u);

}

// only shows if the div is visible.
function debugMsg(msg) {
  appendDivText('debugArea', msg + "<br/>");
}

// only shows if the div is visible.
function errMsg(msg) {
  appendDivText('errorArea', msg + "<br/>");
}

// intercepts the Search button.
function onAppSearch(k) {

  var homeAirport = "";
  var destAirport = "";

  var lastHomeAirport = "";
  var lastDestAirport = "";

  var destCity = "";

  var d1 = "";
  var d2 = "";

  // air
  if (1 == k) {
    homeAirport = fixAirport(document.kykFlightForm.l1.value);
    destAirport = fixAirport(document.kykFlightForm.l2.value);

    d1 = document.kykFlightForm.d1.value;
    d2 = document.kykFlightForm.d2.value;
  } 

  // hotel
  else if (2 == k) {
    destCity = document.kykHotelForm.crc.value;

    d1 = document.kykHotelForm.d1.value;
    d2 = document.kykHotelForm.d2.value;
  }

  // car
  else if (3 == k) {
    destCity = document.kykCarForm.crc.value;

    d1 = document.kykCarForm.d1.value;
    d2 = document.kykCarForm.d2.value;
  }

  if (homeAirport) {
    Set_Cookie("homeAirport",homeAirport,90);
  }

  if (destAirport) {
    Set_Cookie("destAirport",destAirport,90);
  }

  if (destCity) {
    Set_Cookie("destCity",destCity,90);
  }

  if (d1) {
    Set_Cookie("departDate",d1,90);
  }

  if (d2) {
    Set_Cookie("returnDate",d2,90);
  }

//  updateHistory();
//  buzzLookup();


  return kwidOnSubmit(k);
}

//
// trim a string
//
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
}


//
// the input may be a long smarty name which has description
// and not just 3 character airport code.  we prefer the shorter.
//
function fixAirport(aName) {
  if (!aName || 0==aName.length) {
    return "";
  }

  aName = aName.trim();
  if (3 == aName.length) {
    return aName.toUpperCase();	
  }

  var i = aName.indexOf("(");
  var j = aName.indexOf(")");
  if ((-1 == i) || (-1 == j) || (4 != (j-i))) {
    return aName;
  }

  return aName.substring(i+1,j).toUpperCase();
}

function appendDivText(divid, txt) {
  var obj = getObj(divid);
  obj.innerHTML += txt;
}

// upon load of page, a server side include exec cmd
// sets the city/state/country in div named geoip 
function getGeoAddr() {
  var obj = getObj('geoip');
  return(obj.innerHTML.trim());
}

function prependDivText(divid, txt) {
  var obj = getObj(divid);
  obj.innerHTML = txt + obj.innerHTML;
}

//
// This starts the fetch of the RSS feed which is then
// processed asynchronously.
//
function rssBuzzPair(from,to) {
 var baseUrl = 'http://www.kayak.com/h/rss/fare?code=' + from + '&dest=' + to;  
 var url = '/xmlget.cgi?label=buzzTo' + '&url=' + escape(baseUrl);
 debugMsg("rssBuzzPair(): " + url);
 loadXML(url, onFetchedRSSCb, onFetchedRSSLineItem);
}



// additional smartbox related functionality.

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
}

function onCityFocus(textbox, searchtype, idfield) {
  initSmartBox(textbox, idfield, searchtype, 20, 175);
  clearSbCountryCode();
}


   /* Copyright Kayak.com 2007
 * Kayak Developer Network
 */


//
// When user cycles through tabs.
//
function kwidOnChangeTab(tabIdx) {

  // hide all other panes and tabs.
  for (var i = 0; i <= 5; i++) {
    var x = 'kykPane' + i;
    if (getObjStyle(x)) {
      hideDivById(x);
    }

    x = 'kykTab' + i;
    if (getObj(x)) {
      setClassById(x, 'kykTabUnsel');
    }    
  }

  // Activate this pane and tab.
  unhideDivById('kykPane' + tabIdx);
  setClassById('kykTab' + tabIdx, 'kykTabSel');
}

//
// User has pushed the submit button.
//
function kwidOnSubmit(tabIdx) {

  if (1 == tabIdx) {
    kwidFlightOnSearch();
  } 

  else if (2 == tabIdx) {
    kwidHotelOnSearch();
  } 

  else if (3 == tabIdx) {
    kwidCarOnSearch();
  } 

  else if (4 == tabIdx) {
    kwidCruiseOnSearch();
  } 

  else {
    alert('not yet ' + tabIdx);
  }
}

//
// Links to the kayak front door.
//
function kwidKayakHome() {
  var kayakUrl = 'http://www.kayak.com/s/search/air?x=y';
  return kwidSubmitGet(kayakUrl);
}

//
// Process the Hotel search form.
//
function kwidHotelOnSearch() {
  var fn = 'kykHotelForm';
  var form = getObj(fn);
  if (!form) {
    alert("Invalid page structure " + fn);
    return false;
  }

  if (!form.ai || !form.ai.value) {
    //alert("Missing required affiliate id");
    return false;
  }

  if (!form.crc) {
    alert("Invalid page structure: missing crc");
    return false;       
  }

  var kayakUrl = 'http://usatoday.kayak.com/s/search/hotel?' + kwUnpackForm(form);

  // Looks for "?&" within qstring and if found, replaces with "?"
  if (kayakUrl.match(/\?\&/g)) {
    kayakUrl = kayakUrl.replace(/\?\&/g,"?");
  }

  return kwidSubmitGet(kayakUrl);
}

//
// Process the Car search form.
//
function kwidCarOnSearch() {
  var fn = 'kykCarForm';
  var form = getObj(fn);
  if (!form) {
    alert("Invalid page structure " + fn);
    return false;
  }

  if (!form.ai || !form.ai.value) {
    //alert("Missing required affiliate id");
    return false;
  }

  if (!form.crc) {
    alert("Invalid page structure: missing crc");
    return false;       
  }

  var kayakUrl = 'http://usatoday.kayak.com/s/search/car?' + kwUnpackForm(form);

  // Looks for "?&" within qstring and if found, replaces with "?"
  if (kayakUrl.match(/\?\&/g)) {
    kayakUrl = kayakUrl.replace(/\?\&/g,"?");
  }

  return kwidSubmitGet(kayakUrl);
}

//
// Process the Cruise search form.
//
function kwidCruiseOnSearch() {
  var fn = 'kykCruiseForm';
  var form = getObj(fn);
  if (!form) {
    alert("Invalid page structure " + fn);
    return false;
  }

 if (!form.ai || !form.ai.value) {
    //alert("Missing required affiliate id");
   return false;
  }

  if (!form.dest) {
    alert("Invalid page structure: missing dest");
    return false;       
  }

  var o = getObj('kCruise55');
  form.sr.value = 'n';
  if (o.checked) {
    form.sr.value = 'y';
  }

  form.dt.value = form.d1.value;

  var kayakUrl = 'http://usatoday.kayak.com/s/search/cruise?' + kwUnpackForm(form);

  // Looks for "?&" within qstring and if found, replaces with "?"
  if (kayakUrl.match(/\?\&/g)) {
    kayakUrl = kayakUrl.replace(/\?\&/g,"?");
  }

  return kwidSubmitGet(kayakUrl);
}


//
// Process the Flight search form.
//
function kwidFlightOnSearch() {
  var fn = 'kykFlightForm';
  var form = getObj(fn);
  if (!form) {
    alert("Invalid page structure " + fn);
    return false;
  }

  if (!form.ai || !form.ai.value) {
    //alert("Missing required affiliate id");
    return false;
  }

  if (!form.l1 || !form.l2) {
    alert("Invalid page structure: missing l1 or l2");
    return false;       
  }

  var kayakUrl = 'http://usatoday.kayak.com/s/search/air?' + kwUnpackForm(form);

  // Looks for "?&" within qstring and if found, replaces with "?"
  if (kayakUrl.match(/\?\&/g)) {
    kayakUrl = kayakUrl.replace(/\?\&/g,"?");
  }

  return kwidSubmitGet(kayakUrl);
}

//
// generic method to grab all the form fields.
//
function kwUnpackForm(form) {
  var s = "";
  for (var i = 0; i < form.elements.length; i++) {
    var nm = form.elements[i].name;
    var vl = form.elements[i].value;
    if (nm && vl) {
      s += "&" + nm + "=" + escape(vl);
    }
  }
  return wgFixDate(s);
}

//
// tidy the date field.
//
function wgFixDate(argList) {
  if (argList.match(/\//g)) {
    argList = argList.replace(/\//g,"%2F");
  }
  return argList;
}

//
// Route all URL redir through here so that the URLs are properly
// converted to linkshare format if we're within a linkshare affiliate's
// page.
//
function kwidSubmitGet(url) {

  if (isLinkShare()){
    url = lsn_click + '&tmpid=2304&RD_PARM1=' + escape(escape(url));
  }   

  window.open(url);
  return true;
}

/* If we're in the linkShare environment, the variable lsn_clk will be
 * defined and this function will respond in the affirmative.
 */
function isLinkShare() {
  try {
    lsn_click;
    return true;
  } catch(err) {
    return false;
  }
}
