// some globals
var globalTrIterator = 0;
var globalDataGetIterator = 0; // counts how many times the data has been added.

var airportDetails = ""; // this makes it globaly accessable - used inline to retrieve info, its an array of objects
var airlineDetails = "";
var travelAgent =  "";

var fileversion = 2;
 
var loadingMessage = "laddar resultat !";

// user adjustable vars
var showOnlyTor = 0;

document.observe("dom:loaded", function() {
	 
	// is there an idx? exportid that is
	if(idx=="" || idx == "null" || idx == "0" ){ 
		niceAlert('Ogiltigt Sökresultat!', 'Antagligen är detta resultat raderat eftersom det är för gammalt <br><br> <a href="#" onclick="PreparegetUrl(returntrip, userid); closeNiceAlertWin();" >Klicka här för att göra om sökningen!</a>');
	}
	
	// idx is set with php and globaly accessable
	// ingbar(0);
	result(idx, 'main', serverx);
	
	// fixes
	if(subresults==0){
		$('bottomlinksdiv').style.display = "none";
	}
	
	displayCorrectMainInfo('searchresultcontent', "maincont-bluebg", "resultchoice");
	
	Event.observe('resultchoice', 'click', 	function(event) {  		displayCorrectMainInfo('searchresultcontent', 		'maincont-bluebg', 	this.id); } );
 	Event.observe('matrixchoice', 'click', 	function(event) { 		displayCorrectMainInfo('pricematrix-onoffdiv',		'maincont-greenbg',	this.id); } );
 	Event.observe('pricechoice', 'click', 	function(event) { 		displayCorrectMainInfo('lowestfairs-outer',			'maincont-graybg',	this.id); } );
 	Event.observe('rentalchoice', 'click', 	function(event) { 		displayCorrectMainInfo('hotels-onoffdiv-outer',		'maincont-brownbg',	this.id); } );
 	Event.observe('searchhistorychoice', 'click', 	function(event) {  displayCorrectMainInfo('searchhistorycontent',	'maincont-bluebg',	this.id); } );

 	// Event.observe('searchhistorychoice', 'click', function(event) { displayCorrectMainInfo(this.id); } );

   
});

 

function togglec(thebgclass){ 
 
    var classArray = $('main-cont').classNames().toArray();
    for (var index = 0, len = classArray.size(); index < len; ++index) {
        $('main-cont').removeClassName(classArray[index]);
    }
    
    $('main-cont').addClassName(thebgclass);
 
}


function displayCorrectMainInfo(thefetchid, thebgclass , thisid){


	var mainContHead =  ' <div id="main-cont-inner">';
  
	// alert(theid);
	$('main-cont').innerHTML = mainContHead + $(thefetchid).innerHTML + '</div>';
 
	togglec(thebgclass);
 
	 
	// fix menu hightlight
	if(thisid != undefined){
		
		$("resultchoice").removeClassName('shactive');
		$("matrixchoice").removeClassName('shactive');
		$("pricechoice").removeClassName('shactive');
		$("rentalchoice").removeClassName('shactive');
		//$(searchhistorychoice).removeClassName('shactive');
		
		$(thisid).addClassName('shactive');
		
	} 
	 
}




/**
 * shows the alertwindow
 * @param headline
 * @param message
 * @return
 */
function niceAlert(headline, message){
	
	$('alerthead').innerHTML = '<img style="float:left;clear:none;position:relative;left:9px;top:9px;" src="http://static.flight24.com/images/popup-icon.png" /><div id="closebtn"></div><h4>' + headline + '</h4>';
	$('alertcontent').innerHTML = '<p>' + message + '</p>';
	
	middle("alertdiv");
	Effect.Appear('alertdiv', { duration: 0.1 });
	new Draggable('alertdiv', {   });


	
 	// get enviroment params
 
  
	Event.observe('closebtn', 'click', function(event) { closeNiceAlertWin(); });
/*	
	Event.observe(document, 'keypress', function(event){ 
		if(event.keyCode == Event.KEY_TAB) { closeNiceAlertWin(); }
		});

 */
	

}






/**
 * closes the alertwindow
 * @return
 */
function closeNiceAlertWin(){
	Effect.Fade('alertdiv', { duration: 0.2 });
}





/**
 * 
 * @return
 */
function filterForeign(){
	loadingMessage = "filtrerar resultat";
	if($('withforeign2').checked == true){ // only show direct
 
		if(globalDataGetIterator<2){ // to prevent unneccecary settimeout,  this doublechecks with the iterator, but fuck it

			wrappedAddMoreResults(idx);  // only adds once

			setTimeout (function(){
				toggleClassDisplayProperty('foreignacency', 'tr', '0'); // this removes "notdirectflight" class elements from result
			}, 1000 );

		}else{
		
			toggleClassDisplayProperty('foreignacency', 'tr', '0'); // this removes "notdirectflight" class elements from result
		
		}



	}else{ // show all, including non - direct flights
 
		toggleClassDisplayProperty('foreignacency', 'tr', '1');
 
	}

	
	setTimeout (function(){ // timed to make the heightadjustment after remove (1000ms)
		 
		$('main2').style.height = $('maintable').getHeight() + 400 + 'px';
		
		setTimeout (function(){ // timed to make the heightadjustment after remove (1000ms)
			$('main2').style.height = 'auto';
		}, 3000 );
 
	}, 1700 );
 
		if($('withreturn').checked == true){ // dont show not direct
 
			toggleClassDisplayProperty('notdirectflight', 'tr', '0'); // this removes "notdirectflight" class elements from result
			// console.log("removes notdirectflights");
		
		}
	 
}



/**
 * 
 * @return
 */
function filterNonStop(){
	loadingMessage = "filtrerar resultat";
	if($('withreturn').checked == true){ // only show direct
		
		if(globalDataGetIterator<2){ // to prevent unneccecary settimeout,  this is duplicate check with the iterator, but fuck it
		
			wrappedAddMoreResults(idx);  // only adds once

			setTimeout (function(){
				toggleClassDisplayProperty('notdirectflight', 'tr', '0'); // this removes "notdirectflight" class elements from result
			}, 1000 );
			
		}else{
			
			toggleClassDisplayProperty('notdirectflight', 'tr', '0'); // this removes "notdirectflight" class elements from result
		
		}
		

	}else{ // show all, including non - direct flights

		toggleClassDisplayProperty('notdirectflight', 'tr', '1');
 
	}

	
	setTimeout (function(){ // timed to make the heightadjustment after remove (1000ms)
		 
		$('main2').style.height = $('maintable').getHeight() + 400 + $('submenu').getHeight() +  'px';
 
	}, 1700 );
	 

		if($('withforeign2').checked == true){ // dont show foreign
		
			
			toggleClassDisplayProperty('foreignacency', 'tr', '0'); // this removes "foreignacency" class elements from result

		
		}	
	
}



 
 
/**
 * toggles display property on class (can be multiple)
 * is generic, v1 is not generic
 */
function toggleClassDisplayProperty(classid, element, show){
	// console.log(show);
	var myObjColl = getElementsByClassName(classid, element);

		for (var i = 0, j = myObjColl.length; i < j; i++) {

			if(show==0){		 		 
			 	myObjColl[i].style.display = 'none';
			}else{
			 	myObjColl[i].style.display = 'block';
			}
		}
 
	return false;
}










/**
 * 
 * @param onoff
 * @param text
 * @return
 */
function ingbar(onoff, text){
	
	middle2('ingbar');
	
	if(text!=""){$('ingbartext').innerHTML = text;};
	if(onoff==1){$('ingbar').style.display="block";};
	if(onoff==0){$('ingbar').style.display="none";};
	
}

 


/**
 * wrapper. Reason not to put directly in subfuntion is to be able to  multiple times later, if wanted
 * @return
 */
function wrappedAddMoreResults(theJsonDbId){
	// console.log(globalDataGetIterator);
	if(globalDataGetIterator<2){
		addMoreResults(theJsonDbId);
	}
	

}

/**
 * 
 * @param theJsonDbId
 * @return
 */
function addMoreResults(theJsonDbId){
 	
	ingbar(0);
	result(theJsonDbId, 'sub', serverx);

	// $('addmoreresultsa').style.display = "none";
 
	return false;

}


 




/**
 * 
 * @param idx
 * @param filex
 * @return
 */
function result(idx, filex, serverx){
	
	
	var evaledJson = "";;
 
	if(idx=="" || filex==""){return false;};
 
	 var url = "http://www.flygresor.se/_proxy/showresult_jsonfetch.php";
 
	ingbar(1,  loadingMessage );
	 
	//var url = "http://www.flygresor.se/_proxy/showresult_jsonfetch_dev.php";
	
	/*
	 * json structure
	 * 
	 * 
	 * - flights
	 *   - out
	 *     - alt
	 *     - segment
	 *     	 - [0]
	 *       - [1]
	 *   - in
	 *     - alt
	 *     - segment 
	 *     	 - [0]
	 *       - [1]
	 * 
	 */
	
	new Ajax.Request(url, {
	  method: 'get',
	  requestHeaders: {Accept: 'application/json'},
	  	
	  	parameters: {id: idx, file: filex, server: serverx},
	  	
	  	onSuccess: process,
		
		onCreate: function(){
	  		globalDataGetIterator++;  // increase each run
	  		//console.log(globalDataGetIterator);
	  		
	  		$('addmoreresultsa').style.display = "none";
	  		
			// if(globalDataGetIterator>1){ // first load
				$('loadingbar-resultset').style.display = "block";
			// }
 
			if(globalDataGetIterator==1 ){ // first load
				$('addmoreresultsa').style.display = "block";
			}	
 
		}, 
		
		
		onLoading: function(){
 
		},

		
		onComplete: function(transport){
			ingbar(0,  loadingMessage );
			
			$('loadingbar-resultset').style.display = "none";
			
			if(globalDataGetIterator==2){ // last load 
				$('addmoreresultsa').style.display = "none";
				setTimeout (function(){ // wait to allow dom load
 					$('redo').style.display = "block";
				}, 1000 );
			}
  
		},
		
		
		onFailure: function() { 
			ingbar(0,  loadingMessage );
			niceAlert('Fel!' ,"Ojdå, något gick fel, vi beklagar! Testa gärna igen!"); 
	    }
		
		
	});
	
	
}
 



/** 
 * 
 * @param oReq
 * @param oJSN
 * @return
 */
function process(oReq, oJSN) {
	
     //var data = eval(oReq.responseText);
	 
    // console.log("res: " );
	//if(oReq==""){ alert("fuck"); }
	
	// check for old data format..
	if(oReq.responseText.include('"meta":{"slow"')){
		fileversion = "2";
	}else{
		fileversion = "1";
	}
	
	// eval data 
	var evaledJson = oReq.responseText.evalJSON(true);

	
	 
	// error handling
	if(evaledJson=='e1'){ // e1 = no id in database coresponds ajax-fetch-id
		 
		// check for cause to error and show apropriate message to client
		if(isold){
			
			$('generalmessagediv').update('<p><img src="http://www.flygresor.se/images/excl-point.gif" />Utresedatum är före dagens datum.</p>');
       
			
			
		}else{ // default
			
			$('generalmessagediv').update('<p><img src="http://www.flygresor.se/images/excl-point.gif" />Sökresultatet är raderat för att det är för gammalt. <br><br> <a href="#" onclick="PreparegetUrl(returntrip, userid); closeNiceAlertWin();" >Klicka här för att göra om sökningen!</a></p>');
       

		}
        $('generalmessagediv').show();
		
		$('bottomlinksdiv').style.display="none";

	
	}
	
	// setup globaly accessable array
	if(globalDataGetIterator==1){ // first add
		airportDetails = evaledJson.airportDetails; // this makes it globaly accessable - used inline to retrieve info, its an array of objects
		airlineDetails = evaledJson.airlineDetails;
		travelAgent =  evaledJson.travelAgent;
	}	
	// run html generation
	generateTable(evaledJson);
	
	
	
 
}



/**
 * Iterates the airlineDetails array, and in the position of "value position"
 * really no need to pass airlineDetails array, but do it anyway, more solid.. 
 * @param evaledJson
 * @return
 */
function airlineInfo(airlineDetails, needleString ){
	//var airportDetails = evaledJson.airportDetails;
	 
	if(needleString==""){return "";};
 
	for(var object_properties in airlineDetails){
 
		if(object_properties == needleString){
				
			return airlineDetails[object_properties] ;  
			
		}
	 	 
	}
	
	return needleString;
 
}
 


/**
 * this returns imagename on agent, uses index
 * (returns objectname, not value and added suffix, as imagename)
 */
function agentImage(travelAgent, needle){
	for(var object_properties in travelAgent){
		if( travelAgent[object_properties] == needle){
			return String(object_properties) + '.gif';
		}
	}
}
/**
 * 
 * @param string
 * @return
 */
function removeSpaces(string) {
	return string.split(' ').join('');
}


/**
 * iterates the airportDetails array, and in the position of "value position"
 * really no need to pass airportDetails array, but do it anyway, more solid.. 
 * @param evaledJson
 * needleString = for instance ARN
 * valuepositon = 0, 1 or 2
 * @return
 */
function airportInfo(airportDetails, needleString, valuePosition){
	//var airportDetails = evaledJson.airportDetails;
	 
	if(needleString==""){return "";};
 
	for(var object_properties in airportDetails){
 
		if(object_properties == needleString){
	 
			if(valuePosition==0){return airportDetails[object_properties].city; }
			if(valuePosition==1 ){return airportDetails[object_properties].country; }
			if(valuePosition==2){return airportDetails[object_properties].airportName; }
		 
		}
	 	 
	}
	
	return needleString;
 
 
}


/**
 * 
 * @param evaledJson
 * @return
 */
function generateTable(evaledJson){
	
	var table = "";
	var flights = evaledJson.flights;
	
	// console.log(flights.length);
	

	// Creates tablerows
	// loops all flights in the evaled json array
	for (var index = 0, len = flights.length; index < len; ++index) {
		
		var item = flights[index]; // a flight
		var tr = "";
		
		globalTrIterator++;


		// flightdata
		var price = String(item.price);
		//price = Math.round(price.gsub(',', '.'));
		price =  (price);
		
		var agent = item.agent;
		var bookingUrl = item.bookingUrl;
		var code = item.code;
		var stop = item.stop; //
		var foreignAgency = item.foreign;
		//console.log(stop);
		//var stops = 0;  
		var nonstopOrDirectClass = (stop==0) ? ' directflight ' : ' notdirectflight ';
		
		var foreignOrNotForeignClass = (foreignAgency==1) ? ' foreignacency ' : ' notforeignacency ';
		// [stops] => 1
		
		
		var aImage = agentImage(travelAgent, agent);
		
		// console.log(aImage);
		
		// generate outgoing tds
		// var outTds = makeOutTd(item.flights.out.alt);
		
		// alts
		
		// New header
		tr ='	<tr class="headparttr">' + 
			'		<td style="padding-bottom:0px;" class="headparttd" colspan="2">' +
			'			<div class="headparttdinner"> ' + 
			'		 		<h5 class="shadow">' + price + ' kr </h5> ' +
			'				<h6>Totalpris inklusive skatter och avgifter.</h6> ' +
			'	 			<a alt="Till resa" id="btn'+r()+'"  class="thegotobtn" href="'+bookingUrl+'" onClick="javascript: pageTracker._trackPageview(\'klick.php\');" rel="nofollow" target="_blank"></a> ' +
			'				<div class="logocont"><img src="images/logos/'+aImage+'" border="0" alt="'+aImage+'"/></div>' +
			'				<div class="emailbtn" onclick="return emailForm(\'' + globalTrIterator + '\', \''+price+'\', \''+import_id+'\')"> <img src="http://www.flygresor.se/images/contactbtn.png" alt="email result" id="emailbtntr_' + globalTrIterator + '"> </div> ' +
			'				<div class="expanderbtn" onclick="return expander(\'tr_' + globalTrIterator + '\')"> <img src="http://www.flygresor.se/images/btn_toggleflight_on2.png" alt="Växla mellan att se och inte se mer flyginfo" id="imagetr_' + globalTrIterator + '"> </div> ' +
			' 			</div>';
			'		</td>' +
			'	</tr>';
		
		
		
		
		
		tr+= '<tr id="tr_' + globalTrIterator + '" name="tr_' + globalTrIterator + '" valign="top" class="lowclass ' + nonstopOrDirectClass + foreignOrNotForeignClass + '" >' +


			 '	<td class="margin marginnew" width=" "> ' +
 
			 	 	 makeOutboundTd(item, globalTrIterator) + 
			 '	</td>';
		
		tr+= '	<td class="margin marginnew" width=" " >' +
	 			 '			 ' ;
						if(returntrip==1){ // only add if outbound 
				 			  tr+= makeInboundTd(item, globalTrIterator) ;
						}
		tr+= '  </td>' +
			 '</tr>';
		
		tr+= '<tr class="">' +
		 '	<td class="result-bottom-left-corner" height="8" width="375" ></td>' +
		 '	<td class="result-bottom-right-corner" height="8" width="380" ></td>' +
		 '</tr>'; 
		
		tr+= '<tr class=" '+nonstopOrDirectClass+foreignOrNotForeignClass +' ">' +
			 '	<td height="14" width="375" ></td>' +
			 '	<td height="14" width="380" ></td>' +
			 '</tr>';
		 
		table+=tr; 
		
	}

var homeoff = (returntrip==0) ? ' class="classoff" ' : '' ;

var tableHeader = 
'<tr height="0px" style="padding:0;margin:0">' +
'<td width="375" height="0" style="padding:0;margin:0"></td>' +
'<td width="380" height="0" style="padding:0;margin:0"></td>' +
'</tr>';
 


// Element.addClassName(element, className)   Element
	if($('maintable').hasClassName('hastableheader')){
	}else{
		table = tableHeader + table;
		$('maintable').addClassName('hastableheader');
	}
 
	var currenttable = $('maintable').innerHTML; 
	$('maintable').update(currenttable+table);
	
	// appends results...  
	// var currenttable = $('maintable').innerHTML; 
	
	
   
  // fix scroll and potential get of more results
	if( (import_trid!="") && ($('tr_'+import_trid)==undefined) ){ // has value, but is not present
		 wrappedAddMoreResults(idx);	
		 //scrollToId(import_trid, 1500);
		// console.log(import_trid);
	}else if((import_trid!="")){
		 //console.log("running2");
		 scrollToId(import_trid, 1500);
	}
	
	
	
 
	
}



/**
 * compiles segments - this is the same in inbound and outbound
 * param #1 is the array of segments
 * @return
 */
function compileSegments(segment, globalTrIterator, meta){
 
	
  
	var i = 0;
 
	
	var trips = "";
	var amountOfSegments = segment.length;
	
	// loop segments (flight steps)
	segment.each(function(item){
		
		// Your code working on item here...
		
		var flight = item.flight;
 
		var arrivalAirport = item.arrivalAirport;
		var departureAirport = item.departureAirport;
		
		var arrivalDate = item.arrivalDate;
		var arrivalDateArray = arrivalDate.split(' ')
		var arrivalTime = arrivalDateArray[1];
 
		var departureDate = item.departureDate;
		var departureDateArray = departureDate.split(' ')
		var departureTime = departureDateArray[1];
		
		var line = "";
		 
		// highlight departure place
		if(i==0){ 
			line+= '<span class="sharper">' + departureTime + ' ' + airportInfo(airportDetails, departureAirport, 0) + '</span>'; 
		}else{
			line+= '<span class="">' + departureTime + ' ' +airportInfo(airportDetails, departureAirport, 0)  + '</span>';
		}
		
		line+= '<img class="separator-arrow-showresult" src="images/arrow.gif" alt="tillbaka"/>';
			 
		// highlight destination place
		if( i == amountOfSegments-1 ){
			line+= '<span class="sharper">'+arrivalTime+' '+airportInfo(airportDetails, arrivalAirport, 0)+'</span>';
		}else{
			line+= '<span class="">'+arrivalTime+' '+airportInfo(airportDetails, arrivalAirport, 0)+'</span>';
		}
 	 
		trips+=  
		'		<li>'+
				line +
		'			<div class="tr_'+globalTrIterator+' morefinfo-outer " id="'+r()+'" style="display:none">' +
		'				<span class="moreinfo-flight" >Flight:<br />' + flight + '</span>' +
		'				<span class="moreinfo">' + airportInfo(airportDetails, departureAirport, 2) + ' (' + departureAirport + ') ' +  '<br />' + departureDate + '</span>' +
		'				<span class="moreinfo norborder" > <img src="http://www.flygresor.se/images/arrow-thicker-showresult.gif" /> </span>' +
		'				<span class="moreinfo">'  + airportInfo(airportDetails, arrivalAirport, 2) + ' (' + arrivalAirport + ') ' + ' <br /> ' + arrivalDate + '</span>' +
		'			</div>' +
		'		</li>';
		
		// console.log(i);
		i++;
	}); // ends segmentloop
 
	return trips;

}



/**
 * 
 * @param item
 * @param globalTrIterator
 * @return
 */
function makeInboundTd(item, globalTrIterator){
	  
	var td = "";
	 
	// return 0;
	// loop several outbound here later
	/*
	var outalternatives = item.out;
	console.log(outalternatives);
	outalternatives.each(function(item){
		console.log('x ');
	});
	*/
	
	// alts data (data about the specific flight)
	var alts = item.inbound.alt;
 
	var altCount = alts.count;
	//var altIsSlow = alts.slow; 
	var altHasStop = alts.stops;
	//var altTravelTime = alts.traveltime; 
	var airline = alts.airline; 
 
	var company = airlineInfo(airlineDetails, airline);
	
 	
	segmentArr = item.inbound.segment;
	
	var tripIterator = 1;
	 
	segmentArr.each(function(item){
		
		var	altTravelTime = "";
		var altIsSlow = "";
		var	slowClass = "";
		var	slowClassText = "";
		 
		var	imeta ="";
		var	isegments ="";
 
		if(fileversion=="2"){ // new result
			  
			  altTravelTime = item.meta.traveltime; 
			  altIsSlow = item.meta.slow;
			  slowClass = (altIsSlow=="1") ? ' slowclass ' : "";
			  slowClassText = (altIsSlow=="1") ? ' Observera! Detta resealternativ innehåller byten, där väntetiden på flygplatsen överstiger 12 timmar. ' : "";
			  isegments = item.segments;
			  imeta = item.meta;
			  
		}else{ // old
		    
			var	imeta = "";
			var	isegments = item;
		    
		}
			
		td+=
		'	<div class="whiteroomheader"><h4>Hemresa alt '+tripIterator+': <span class="sharp">  '+company+' </span> ' + timetextSquare(altTravelTime) + ' </h4></div>' +
		'	<ul id="randomid'+r()+'" onmouseover="hover(this.id, \'ffffff\', \'727272\', \'http://www.flygresor.se/images/moreinfo_on.gif\');"  onmouseout="hover(this.id, \'ffffff\', \'B9B9B9\', \'http://www.flygresor.se/images/moreinfo_off.gif\');"  title="'+slowClassText+'" class="whiteroom '+slowClass+'"  >' +
		'		<li style="display:none;" id="" class="moreinfoli tr_'+globalTrIterator+'">' +
 
				infoSquare(altIsSlow, altTravelTime) + 	
 
		'		</li>' +
				compileSegments(isegments, globalTrIterator, imeta) +
		'	</ul>' ;
		
		tripIterator++;
	});
	
	return td;
 
}

/**
 * 
 * @param altIsSlow
 * @param altTravelTime
 * @return
 */
function infoSquare(altIsSlow, altTravelTime){
	  
	
	var time = String(altTravelTime / 60 / 60 );
	var timeArr = time.split('.');
	var minutes ="";
	if(timeArr.length==2){	
		minutes = 'och ' + Math.round((Number('0.' + String(timeArr[1])))*60)+'m';
	}
	var hours = timeArr[0];
	var timesString = 'Total restid ca '+hours+'h '+minutes;	
 
	
	var square = "";// '<span class="timeexp"> ' + timesString + ' </span>';
	
	if(altIsSlow=="1"){
		square+= '<div class="morefinfo-outer slowexplanation" id="681848503" style=""><span class="slowwarning"> <img class="showresultsmallexcl" src="http://www.flygresor.se/images/smallexcl.gif" /> <b>Obs!</b> - I detta resealternativ finns minst ett byte med mer än 12 timmars väntan!</span><br /></div>';
	}else{
		 
	}
	
	 
	if(altTravelTime==""){square = "";}
	return square;
	
}
/**
 * 
 
 * @param altTravelTime
 * @return
 */
function timetextSquare(altTravelTime){
	  
	
	var time = String(altTravelTime / 60 / 60 );
	var timeArr = time.split('.');
	var minutes ="";
	if(timeArr.length==2){	
		minutes = ' '  + Math.round((Number('0.' + String(timeArr[1])))*60)+'m ';
	}
	
	var hours = timeArr[0];
	var timesString = 'Restid: <strong>'+hours+'h ' + ' ' + minutes + '</strong>';	
 
	
	var square =   '<span class="timeexp"> ' + timesString + ' </span>';
	
	 return square;
	
}



/**
 * Makes outbound td
 * @return
 */
function makeOutboundTd(item, globalTrIterator){
	  
	var td = "";
	
	
	// loop several outbound here later
	/*
	var outalternatives = item.out;
	console.log(outalternatives);
	outalternatives.each(function(item){
		console.log('x ');
	});
	*/
	
	// alts data (data about the specific flight)
	var alts = item.outbound.alt;

	var altCount = alts.count;
 	//var altHasStop = alts.stops;
	var airline = alts.airline; 

	var company = airlineInfo(airlineDetails, airline);
	
 
	
	segmentArr = item.outbound.segment;  
	

	// loops each outbound alternative
	var tripIterator = 1;
	segmentArr.each(function(item){
		
		var	altTravelTime = "";
		var altIsSlow = "";
		var	slowClass = "";
		var	slowClassText = "";
		 
		var	imeta ="";
		var	isegments ="";
 
		if(fileversion=="2"){ // new result
			  
			  altTravelTime = item.meta.traveltime; 
			  altIsSlow = item.meta.slow;
			  slowClass = (altIsSlow=="1") ? ' slowclass ' : "";
			  slowClassText = (altIsSlow=="1") ? ' Observera! Detta resealternativ innehåller byten, där väntetiden på flygplatsen överstiger 12 timmar. ' : "";
			  isegments = item.segments;
			  imeta = item.meta;
			  
		}else{ // old
		    
			var	imeta = "";
			var	isegments = item;
		    
		}
	 
	   
 
		// put together and return
		td+= 
			'	<div class="whiteroomheader"><h4>Utresa alt '+tripIterator+': <span class="sharp"> ' + company + ' </span> ' + timetextSquare(altTravelTime) + ' </h4></div>' +
			'	<ul id="randomid' + r() + ' "  onmouseover="hover(this.id, \'ffffff\', \'727272\', \'http://www.flygresor.se/images/moreinfo_on.gif\');"  onmouseout="hover(this.id, \'ffffff\', \'B9B9B9\', \'http://www.flygresor.se/images/moreinfo_off.gif\');"   title="'+slowClassText+'" class="whiteroom '+slowClass+'" > '+
			'		<li style="display:none;" id="62625494" class="moreinfoli tr_'+globalTrIterator+'">' +
 
							infoSquare(altIsSlow, altTravelTime) +  
 
			'		</li>' + 
					compileSegments(isegments, globalTrIterator, imeta) +
			'	</ul>'; 
		
		tripIterator++;
	});
	return td;
	
}

/**
 * returns a random integer
 */
function r(){
	return Math.ceil(1000000*Math.random())
}


/*
 
	function doAjaxSearch(tdId, leavedate, returndate, fromIata, toIata ){
		 
		
		if(totalActiveSearches<=2){
		totalActiveSearches++;

		//$(tdId).innerHTML = '<img src="ajax-er.gif" />';
		$(tdId).innerHTML = flashIt();
 

 		//var url = "http://www.flygresor.se/inc/_ajaxresponse/tesresrert.php";
 		var url = "http://www.flygresor.se/inc/_ajaxresponse/getPriceMatrix.php";
		new Ajax.Request(url, {
			//parameters: {leavedate: leavedate, returndate: returndate, fromta: '<?=$from?>', tota : '<?=$to?>'},
			parameters: {leavedate: leavedate, returndate: returndate, fromta: fromIata, tota : toIata},
			method:'get',
			onSuccess: function(transport) {
				
				var priceAnd = transport.responseText;
				var theArr = priceAnd.split("##") 

				// update price
				totalActiveSearches = totalActiveSearches - 1;
				new Effect.Highlight(tdId, { startcolor: '#ffe400', endcolor: '#ffffff' });
				$(tdId).innerHTML = "<a style='color:#D6281D' href='/showresult.php?id=" + theArr[1] + "' target='_blank'>" + theArr[0] + " kr</a>";  
 
				// just add tooltip to newly created price result
				new Tip($(tdId), "Pris: " + theArr[0] + " kr Utresa: " + leavedate + "  Hemresa: " + returndate + "  ", {
					title: "Information!",
					style: 'protogrey',
					stem: 'topLeft',
					hook: { mouse: true, tip: 'topLeft' },
					offset: { x: 10, y: 16 },
					width: 250
				});
				
				
			}
			 
		});
 
 
		 
								
		

		}else{
			
			alert("max 3 söknigar samtidigt är tillåtet, vänta några sekunder till någon är klar och testa igen!");

		}
		
	}
	
	*/




/**
 * turns the hotel-bar on and off
 */
function togglePriceMatrix(from, to, leavedate, returndate){
		 
	var hoteldiv = $('pricematrix-onoffdiv');
	var plusminus = $('matrix-menu-icon');

	if(hoteldiv.style.display == 'block'){

		hoteldiv.style.display = 'none';
		plusminus.src = 'http://www.flygresor.se/images/latest-menu-icon.gif';

	}else{
		
		plusminus.src = 'http://www.flygresor.se/images/latest-menu-icon-minus.gif';
		hoteldiv.style.display = 'block';
		var url = 'http://www.flygresor.se/inc/pricematrix/matrix.php?from='+from+'&to='+to+'&leavedate='+leavedate+'&returndate='+returndate+'';
		$('matrixiframe').src = url;
			
	}
 
	return false;
 
	
}





/**
 * 
 * @param id
 * @param price
 * @param import_id
 * @return
 */
function emailForm(id, price, import_id){

	 
	var import_idsent = '&import_id='+import_id;
 
 	// builds AJAX - passed varbles
 //var homedate = '';
	//var leavdate = '';
	// var price = '&price=' + '';
	var price = '&price=' + price;
	var travelagency = '&travelagency=' +  travelagency;
	/*
	var tafrom = '';
	var from = '';
	var fromcountry = '';
	var tato = '';
	var to = '';
	var tocountry = '';
	*/
	//var import_id = '&import_id=' + import_id;  
	//var adults = '<?=htmlspeclchars($adults)?>';
	if( adults != "" && adults != "0"){var adultsText = adults + " vuxna "; }else{adultsText="";};
	
	//var children = '<?=htmlspeclchars($children)?>';
	if( children != "" && children != "0"){var childrenText = children + " barn "; }else{childrenText="";};
	
	//var infants = '<?=htmlspeclchars($infants)?>';
	if( infants != "" && infants != "0"){var infantsText = infants + " spädbarn "; }else{infantsText="";};
	
	// var teens = '<?=htmlspeclchars($teens)?>'
	//var returntrip = '<?=htmlspeclchars($returntrip)?>';
	if( returntrip==1 ){ var concerns = "  tur och returresa "; }else{ var concerns = " enkelresa "; };
	 
	//var nonstop = '<?=htmlspeclchars($nonstop)?>';
	//var searchtimestamp = '<?=htmlspeclchars($searchtimestamp)?>';
	var searchedFromTo = '&searchedFromTo=' + 'Priset avser en ' + concerns + ' från ' + from + ' i ' + fromcountry + ' till ' + to + ' i ' + tocountry + ' för ' + adultsText + '. ' + childrenText + '. ' + infantsText;

	if(returntrip==1){

		var triptTimes = '&triptTimes=' + ' Utresa sker: ' + leavdate + ' och hemresa: ' + homedate + '. ' ;
		
	}else{

		var triptTimes = '&triptTimes=' + ' Utresa sker: ' + leavdate ;
 
	}


	var priceConcerns = '&priceConcerns=' + '<br /> Priset avser ' + concerns + ' för ' + adultsText + '. ' + childrenText + '. ' + infantsText + '. ' ; 
    var searchMade =  '&searchMade=' + '<br /> Sökningen gjordes för 2 dagar och 3 timmar sedan. ';
    
	// searchedFromTo = searchedFromTo;

	// builds emailform
	var explanation = 	'<p id="emptext">Detta e-postformulär skickar det valda priset med länk till en vald e-postadress. Du kan exempelvis skicka det dig själv eller en kamrat.</p>';
	var messageBody = 	'<label for="recieveradress">Mottagarens e-post:</label><input id="emrecieveradress" type="text" name="recieveradress" /><label for="yourcomment">Din kommentar / ditt namn: <i>(frivilligt)</li></label><textarea id="emyourcomment" name="yourcomment" rows="2" cols="20"></textarea> ' ;
	var messageHead = 	'<img id="emailformemailimage" src="http://www.flygresor.se/images/small_gray_email_logo.gif" /> Skicka detta sökresultat';
	var buttons = 		'<div id="sendbtn" class="abtnon" > Skicka </div> ';
	var pageUrl = "http://www.flygresor.se/showresult.php?id=" + import_id + '&trid='+id;
	var pasteUrl = '<span style="font-size:11px;">Adress till detta sökresultat</span><br><input  style="font-size:11px;" id="urlstring" type="text" value="' + pageUrl + '" onclick="this.select();"/>' ;
	
	var message = '<div id="messavgeDivInner"><div id="messagehead"><h3>' + messageHead + '</h3><div id="emailclosebtn"> </div></div><div id="emailMessageBody">' + explanation + messageBody + pasteUrl + '<div id="emresponsdiv"></div>' + buttons + '</div>' + ' </div></div>';
 	
 
 	// $('MessageDiv').innerHTML = message ;
	$('MessageDiv').update(message);
	
	middle2("MessageDiv");
	//Effect.Appear('MessageDiv', { duration: 0.1 });

	$('MessageDiv').style.display = "block";
	 
	// Effect.Opacity('MessageDiv', { from: 1.0, to: 0.3, duration: 0.5 });
	
	new Draggable('MessageDiv');
 
	// get enviroment params

 
	Event.observe('emailclosebtn', 'click', function(event) { closeemailForm(); });

	//  Event.observe('cancelbtn', 'click', function(event) {   $('emrecieveradress').value  =""; $('emyourcomment').value  ="";});

	Event.observe('sendbtn', 'click', function(event) {
											   
			//var headline = '&headline=' + $('emheadline').value;		   
			var recieveradress = '&recieveradress=' + $('emrecieveradress').value;
			var yourcomment = '&yourcomment=' + $('emyourcomment').value;
			 
			//var yourcomment = '&yourcomment=' + $('emyanourcomment').value;
			
		var pars = "id=" + id +     recieveradress + yourcomment + searchedFromTo + priceConcerns + triptTimes + searchMade + travelagency + price +  import_idsent  ;							   
		new Ajax.Request('http://www.flygresor.se/inc/_ajaxresponse/emailform_showresult.php', {
						   method: 'get',
						   parameters:  (pars),

  			onSuccess: function(transport) {
				 if(transport.responseText=="1"){
				 	$('emailMessageBody').innerHTML =   '<p><span style="color:#008c10"><b>E-post skickat! </b><br /> Om det inte kommer fram, glöm inte att kontrollera din spam-brevlåda.</span></p>'; 
				 	
				 }else{
					if(transport.responseText=="error1"){$('emptext').innerHTML = '<span style="color:#ff000c"><b>Fel!</b><br />Epostmeddelandet skickades inte på grund av att adressen inte ser ut att stämma. </span>';}
					//alert(transport.responseText);
				 }
  		}
		});
		
		 
	});
  
}




/**
 * "ändra" button, shows change cal, and the correct iframe if returntrip != 1
 */
function turnOffReturnCal(){
			 
		// set return-calendar disabled
		if (returntrip != "1"){ 
			var datechangeiframe = document.getElementById('gToday:normal:agenda.js:gfFlat_2');
			datechangeiframe.src= "http://www.flygresor.se/inc/disabledsmallcal.html";
		 } 

		document.getElementById('display-onoff').style.display ='none';
		document.getElementById('searchfield').style.display ='block';

}




/**
 * hides searchfield and redirect.. 
 */
function PreparegetUrl(returntrip, userid){

	var ok = getUrl2(returntrip, userid, '', '', '', '');
	if(ok==true){
		document.getElementById('searchfield').style.display ='none';
	}

	
}

 

	
/**
 * v2
 * @param returntrip, bool
 */
function getUrl2(returntrip, userid, feed, filter, mainfrom, mainto){
 
		var from = escape(unescape($('fromfield').value));
		var to = escape(unescape($('tofield').value));
		var returntrip;
		
		
		if (mainto == ""){

			if (to == ""){ niceAlert('Info!' ,"Fyll i destinationsort"); return false; }
 		}else{
 			

 			to = mainto;
 			
 		}
 		



		if (mainfrom == ""){

			if (from == ""){ niceAlert('Info!' ,"Fyll i avreseort"); return false; }
 		}else{
 		
 			
 			from = mainfrom;
 			
 		}
  

  
		var adults = 	$('adults').value;
		var teens = 0;
		var children = 	$('children').value;
		var infants = 	$('infants').value;
		
		// uses hidden formfields to store data when user changes values in calendar... we retrieve them here !
		var deptDate_day = 		addZero($('arrDate_day').value);
		var deptDate_month = 	addZero($('arrDate_month').value);
		var deptDate_year = 	addZero($('arrDate_year').value);
		var arrDate_day = 		addZero($('deptDate_day').value);
		var arrDate_month = 	addZero($('deptDate_month').value);
		var arrDate_year = 		addZero($('deptDate_year').value);
		var url;

		var compdatedept = 		deptDate_year + deptDate_month + deptDate_day;
		var compdatearr = 		arrDate_year + arrDate_month + arrDate_day;
		
		var urlreturn = "returntrip=1&homecity=" + from + "&destcity="+ to +"&homeleaveday=" + deptDate_day + "&homeleavemonth=" + deptDate_year + "-" + deptDate_month + "&destleaveday=" + arrDate_day + "&destleavemonth=" + arrDate_year + "-" + arrDate_month + "&adults=" + adults + "&infants=" + infants + "&children=" + children + "&teens=" + teens + "&view=air&version=03&userid=" + userid + "&feed=" + feed + "&filter=" + filter;
		var urloneway = "returntrip=0&homecity=" + from + "&destcity="+ to +"&homeleaveday=" + deptDate_day + "&homeleavemonth=" + deptDate_year + "-" + deptDate_month + "&destleaveday=" + deptDate_day + "&destleavemonth=" + deptDate_year + "-" + deptDate_month + "&adults=" + adults + "&infants=" + infants + "&children=" + children + "&teens=" + teens + "&view=air&version=03&userid=" + userid + "&feed=" + feed+ "&filter=" + filter;
		
		if (returntrip == "1"){ // has returntrip
		
			url = urlreturn;
		
			if (compdatedept == compdatearr){ // same dates, AND returntrip
				
				var answerBool = confirm("Vill du verkligen söka en tur&retur-resa med utresa och hemresa samma dag? Klicka OK för att söka returresa eller Avbryt/Cancel för att söka en enkelresa.");
			
				if (answerBool){ // if "yes" is clicked.. should almost never be
					// "no"!, so do nothing
				}else{
				    
					if(isShowresult){ 
						
						$("display-onoff").style.display = "block";
						
					}else{
					
					    $("returresa").className = "inactive2";
	        			$("enkelresa").className = "active2";
	        			$("areturresa").className = "";
	        			$("aenkelresa").className = "current2";
	        			$("returntrip").value = "0"; // 
	 					$("enkel").value = "1";
	 					
					}
 
					url = urloneway;
 
				}
 
			}
		
	 
			//kontrollera datum
			if(compdatedept > compdatearr){
				niceAlert('Varning!',"Hemresedatum måste vara efter utresedatum.");
				if(isShowresult){
					$("display-onoff").style.display = "block";
				}
				return;
			}

		
		}else{
			url = urloneway;
			

		}

		
		  
      var httpRequest = createXMLHttpRequestObject();
 
      toggleDisplay("anim");

      httpRequest.open('GET', '/fetchresult.php?' + url, true);
      httpRequest.send(null);
      httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
    
      return true;
 
}
 

function scrollToId(trid, timeout){
	//console.log("tr_"+trid);
	setTimeout (function x(){
		window.scrollBy(0,($("tr_"+trid).cumulativeOffset()[1]));
	}, timeout );
};


/**
 * not in use?
 * @return
 */
function changedatearr(){
	 
	theform = document.getElementById('demoform');

	var deptDate_day = theform.deptDate_day.value;
	var deptDate_month = theform.deptDate_month.value;
	var deptDate_year = theform.deptDate_year.value;
	var arrDate_day = theform.arrDate_day.value;
	var arrDate_month = theform.arrDate_month.value;
	var arrDate_year = theform.arrDate_year.value;

	gfFlat_arrDate.fSetCal(deptDate_year,deptDate_month,deptDate_day,1);

	gfFlat_deptDate.fSetCal(arrDate_year,arrDate_month,arrDate_day,1);

}








/**
 * returns weather any menuitem is visible
 */
function isAnyVisible(){
	
	if( $('pricematrix-onoffdiv') != undefined  ){ var one = $('pricematrix-onoffdiv').visible(); }
	if( $('charter-onoffdiv') != undefined  ){ var one = $('charter-onoffdiv').visible(); }
	var two = $('lowestfairs-onoffdiv2').visible();
	var three = $('hotels-onoffdiv').visible();
	var four = $('rentalcars-onoffdiv').visible();

	if(one || two || three || four){return true;}else{return false;};
	
}

 



function clickSubmenu(x, buttonid, extrasId){

	// click on open btn to close
	if(extrasId == globalisItemVisible){
		$(x).hide();
		$(extrasId).hide();
		globalisItemVisible = 0;
		$('submenubar').show();
		$(buttonid).removeClassName('active');
		return;
	}

	// hide the onoffdivs
	if( $('pricematrix-onoffdiv') != undefined  ){ $('pricematrix-onoffdiv').hide(); }
	if( $('charter-onoffdiv') != undefined  ){ $('charter-onoffdiv').hide(); 	} 
	$('lowestfairs-onoffdiv2').hide();
	$('hotels-onoffdiv').hide();
	$('rentalcars-onoffdiv').hide();

	// hide the subdivs
	if( $('sub-pmatrix') != undefined  ){  	$("sub-pmatrix").removeClassName('active'); }
	if( $('sub-charter') != undefined  ){ $("sub-charter").removeClassName('active'); 	}
	$("sub-lowprice").removeClassName('active');
	$("sub-hotels").removeClassName('active');
	$("sub-rentalcar").removeClassName('active');

	// hide the outer menues
	$('rentalcars-menu-outer').hide();
	$('lowestfairs-menu-outer').hide();
	$('hotels-menu-outer').hide(); 
	if( $('matrix-menu-outer') != undefined  ){ $('matrix-menu-outer').hide(); }
	if( $('charter-menu-outer') != undefined  ){ $('charter-menu-outer').hide(); }
 
	$(extrasId).show();
	$(x).show();
	$(buttonid).addClassName('active');
 
	if(globalisItemVisible==0 ) { 

		globalisItemVisible = extrasId;

	}else{ 
		 
		globalisItemVisible = 0 ;

	}


	if(isAnyVisible()){ // 
		$('submenubar').hide();
	}else{
		$('submenubar').show();
	}
 
}
 
  
		
	
	function hoverSubmenu(id, buttonid){
	 
		 
			
				
	 
	}
	
		
	function hoverOutSubmenu(id, buttonid){
		  
		 
	}
	
	
 

 

