// autocomplete
// fixme grouping
// fixme debug av mrjet, doodle + adda travelpartner
// progressindikator ?

var strSid = '';
var isSearching = 0;
var isDownloading = 0;
var nDwn = 0;
var oDwnTimer = 0;
var progressInterval = 0;
 
/**********************************************************************************************************************************************************/

function print_r(theObj,indent){
var output="";
if (indent == undefined) { indent = " "; } else { indent += " "; }
if(theObj.constructor == Array || theObj.constructor == Object) {
for(var p in theObj){
if(theObj[p].constructor == Array|| theObj[p].constructor == Object){
var type = (theObj[p].constructor == Array) ? "Array" : "Object";
output += indent+"["+p+"]("+type+")=>\n";
output += print_r(theObj[p],indent);
} else { output += indent+"["+p+"]:"+theObj[p]+"\n"; }
}
}
return output;
} 

function IncProgress()
{
	myJsProgressBarHandler.setPercentage('element1', '+1');
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = '';//x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function addZeroes(nStr)
{
	if(nStr == 0) return "00";
	if(nStr < 10) return "0"+nStr;
	return nStr;
}

	function toggleCalendar2(visible)
	{
		if(!visible) {
			YAHOO.example.calendar.call_2.oDomContainer.style.visibility = "hidden";
			document.getElementById("cal2").style.visibility = "hidden";
			}
		else {
			YAHOO.example.calendar.call_2.oDomContainer.style.visibility = "visible";
			document.getElementById("cal2").style.visibility = "visible";
		}
	}

/**********************************************************************************************************************************************************/
// initiate the search
var StartObject = {	
	handleSuccess:function(obj){
		//alert("Succeded with starting search");
		//isSearching = 0;   
		//isDownloading = 0;
		YAHOO.log("Finished, success");
		this.setTimer(); // download one last time
	},

	handleFailure:function(o){ 
		//alert("Failed to start search");
		//isSearching = 0;   
		//isDownloading = 0;
		YAHOO.log("Finished, failure");
		this.setTimer();
	},

	startRequest:function() {
		var today = new Date();
		document.getElementById("progressbar").style.visibility = "visible";
		myJsProgressBarHandler.setPercentage('element1', '0');
		progressInterval = setInterval('IncProgress()', 500);
		
  		strSid = today.getTime() + Math.round(Math.random()*1000) + Math.round(Math.random()*1000); 
				
	    var postData = 'strFrom=' + encodeURIComponent(document.getElementById("strFrom").value) + '&' + 
	   'strTo=' + encodeURIComponent(document.getElementById("strTo").value) + '&' +
	   'nAdults=' + encodeURIComponent(document.getElementById("nAdults").value) + '&' +
	   'nKids=' + encodeURIComponent(document.getElementById("nKids").value) + '&' +
	   'strChildList=' + encodeURIComponent(document.getElementById("strChildList").value) + '&' +
	   'bReturn=' + encodeURIComponent(document.getElementById("bReturn").value) + '&' +
	   'selMY1=' + encodeURIComponent(document.getElementById("selMY1").value) + '&' +
	   'selDay1=' + encodeURIComponent(document.getElementById("selDay1").value) + '&' +
	   'strSid=' + encodeURIComponent(strSid) + 
	   
	   (document.getElementById("bReturn").value ? 
	   '&selMY2=' + encodeURIComponent(document.getElementById("selMY2").value) + '&' +
	   'selDay2=' + encodeURIComponent(document.getElementById("selDay2").value) : '');

		//document.getElementById("dwn").value = postData;

		var DwnCallback =
		{
			success:this.handleSuccess,
			failure:this.handleFailure,
			scope: this,
			timeout: 5000,
			cache: false
		};
	   YAHOO.util.Connect.asyncRequest('POST', 'run.php', DwnCallback, postData);
	  
	   // timer to download data
	   this.setTimer();
	   
	   isSearching = 1;
	   
	   pageTracker._trackPageview("/search-start");
	},
	
	setTimer : function() {
		oDwnTimer = setTimeout("SearchObject.startRequest()", 5000); 
	},
	
	cancelTimer : function() {
		clearTimeout(oDwnTimer);
	}
};


/**********************************************************************************************************************************************************/
var SearchObject = {

	theCallback : function(oRequest, oResponse, oPayload) {
		//alert("callback: "+print_r(oResponse));	
		if(oResponse.results.length == 0) return;
		YAHOO.example.datatable.myDataTable.deleteRows(0, 99999);
		
		YAHOO.example.datatable.myDataTable.addRows(oResponse.results);
		document.getElementById("xml").style.visibility = "visible";
		//alert("state: " + print_r(YAHOO.example.datatable.myDataTable.getState()));
		
		
		//var oState = YAHOO.example.datatable.myDataTable.get("sortedBy");
		//alert("before state");
		
		//var column = YAHOO.example.datatable.myDataTable.getColumn("Price"); // Done on server since we fetch all results
		// YAHOO.example.datatable.myDataTable.sortColumn(column, YAHOO.widget.DataTable.CLASS_ASC); // state.sortedBy.dir
		
		// try to sort the result....
		//alert("Dwn: "+ print_r(oResponse.meta));
		//alert("Left: "+ (oResponse.meta['TotalAgents']-oResponse.meta['DwnAgents']));
		
		if(oResponse.meta['TotalAgents'] == oResponse.meta['DwnAgents']) {
			pageTracker._trackPageview("/search-finish");
			clearInterval(progressInterval);
		}
		myJsProgressBarHandler.setPercentage('element1', parseInt(100 * (oResponse.meta['DwnAgents'] / oResponse.meta['TotalAgents'])))
	},
	
	handleSuccess:function(obj){
		isDownloading = 0;
		if(isSearching) 
			StartObject.setTimer();
	
		var invData = new YAHOO.util.LocalDataSource(obj.responseXML);
		invData.responseType = YAHOO.util.DataSource.TYPE_XML;

		invData.responseSchema = {
            resultNode: "Result",
            fields: ["Price", "Stops", "TotalTime", "Out", "In", "ItinId", "Agent", "AgentUrl", "Airline"],
            metaFields: { DwnAgents : "DwnAgents", TotalAgents : "TotalAgents" }
        };

   	var DSCallback =
	{
	success:this.theCallback,
	failure:this.handleFailure,
	scope: this,
	cache: false
	};
       
    invData.sendRequest("any", DSCallback); // will call theCallback with the parsed XML data 
	},

	handleFailure:function(o){ 
		isDownloading = 0;
		if(isSearching) 
			StartObject.setTimer();
	},

	startRequest:function() {
		
		if(isDownloading) return; // dont start download if it's already running
		
		var DwnCallback =
		{
		success:this.handleSuccess,
		failure:this.handleFailure,
		scope: this,
		cache: false
		};
	   
		var args = 'strSid=' + encodeURIComponent(strSid) + "&nRnd=" + Math.floor(100000*Math.random());
		//document.getElementById("info").value = args;
		
	   	YAHOO.util.Connect.asyncRequest('POST', 'getdata.php', DwnCallback, args);
	  	nDwn ++;
//		alert("startRequest, before asyncReq");
//		YAHOO.util.Connect.asyncRequest('GET', 'sample4.xml', DwnCallback);
	  
	   isDownloading = 1;
	}
};
/**********************************************************************************************************************************************************/





//YAHOO.util.Event.addListener(window, "load", StartDataDwn);

function StartDataDwn() {
    YAHOO.example.XHR_XML = new function() {
        
    	this.formatUrl = function(elCell, oRecord, oColumn, sData) {
            elCell.innerHTML = "<a href='" + oRecord.getData("ClickUrl") + "' target='_blank'>" + sData + "</a>";
        };
       
        this.formatAgent = function(elCell, oRecord, oColumn, sData) {
            elCell.innerHTML =  "<a href='" + oRecord.getData("AgentUrl") + "' target='_blank'>Mer info...<br /><img src='/images/agency/" + sData + ".png' width='57' height='20' /></a>";
        };
        
        this.formatItinerary = function(elCell, oRecord, oColumn, sData) {
        	if(sData != undefined)
        		elCell.innerHTML = sData.replace(/[|]/g, '<br />').replace(/[-]/g, '&#10132;'); // fix arrows
        	else elCell.innerHTML = '';
        };
        
        this.formatPrice = function(elCell, oRecord, oColumn, sData) {
            elCell.innerHTML =  "<p style='font-size: 14px; font-weight: bold'>" + addCommas(sData) + "</p>"; // FIXME!!! 
        };
        
        this.formatTotalTime = function(elCell, oRecord, oColumn, sData) {
        	var nDays = Math.floor(sData / 1440);
        	var nHours = Math.floor((sData % 1440) / 60);
        	if(nDays == 0) nDays = ""; 
        	else if(nDays==1) {
        		nDays = nDays + " d ";
        		nHours = addZeroes(nHours);
        	}
        	else {
        		nDays = nDays + " d ";
        		nHours = addZeroes(nHours);
        	}
            elCell.innerHTML = nDays + nHours + " h " + addZeroes(sData % 60) + " m"; 
        };
        
        this.formatStops = function(elCell, oRecord, oColumn, sData) {
            elCell.innerHTML = (sData == '0'? '-' : sData);
        };
        
        this.sortPrice = function(a, b, desc) {
            // Deal with empty values
            if(!YAHOO.lang.isValue(a)) {
                return (!YAHOO.lang.isValue(b)) ? 0 : 1;
            }
            else if(!YAHOO.lang.isValue(b)) {
                return -1;
            }
             var comp = YAHOO.util.Sort.compare; 
             var result = 0;
			
             result = comp(parseInt(a.getData('Price')), parseInt(b.getData('Price')), desc);
			if(result) return result;
			
			result = comp(a.getData('Out'), b.getData('Out'), desc);
			if(result) return result;
			
			result = comp(a.getData('In'), b.getData('In'), desc);
			if(result) return result;
			
			result = comp(parseInt(a.getData('Stops')), parseInt(b.getData('Stops')), desc);
			if(result) return result;
			
        };
        
        this.sortTime = function(a, b, desc) {
            // Deal with empty values
            if(!YAHOO.lang.isValue(a)) {
                return (!YAHOO.lang.isValue(b)) ? 0 : 1;
            }
            else if(!YAHOO.lang.isValue(b)) {
                return -1;
            }
             var comp = YAHOO.util.Sort.compare; 
			return comp(parseInt(a.getData('TotalTime')), parseInt(b.getData('TotalTime')), desc);
        };
 
        var myColumnDefs = [
            {key:"Price", label:"Price", sortable:true, formatter:this.formatPrice, sortOptions:{sortFunction:this.sortPrice}},
            {key:"TotalTime", label:"TotalTime", sortable:true, formatter:this.formatTotalTime, sortOptions:{sortFunction:this.sortTime}},
            {key:"Out", sortable:true, formatter:this.formatItinerary},
            {key:"In", sortable:true, formatter:this.formatItinerary},
            {key:"Stops", label:"Stops", sortable:true, formatter:YAHOO.widget.DataTable.formatNumber},
            {key:"Agent", label: "Agent", sortable:true, formatter:this.formatAgent}
            //,{key:"ItinId", label: "ItinId", sortable:true}
            ];

            
        var url = 'getdata.php?strSid=' + encodeURIComponent(strSid);
			   
        this.myDataSource = new YAHOO.util.DataSource(url);
        this.myDataSource.connMethodPost = true;
        this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_XML;
        
        this.myDataSource.responseSchema = {
            resultNode: "Result",
            fields: ["Price", "Stops", "TotalTime", "Out", "In", "ItinId", "Agent", "AgentUrl", "Airline"]
        };
		
        document.getElementById("xml").style.visibility = "hidden";
        YAHOO.namespace("example.datatable");
        YAHOO.example.datatable.myDataTable = new YAHOO.widget.DataTable("xml", myColumnDefs,
                this.myDataSource, {initialRequest:""});     
        YAHOO.example.datatable.myDataTable.MSG_EMPTY = "Sökning pågår...";
        
    };
    
}




/* ************************************************************************************************************************************************* */