/**
* Gets the logotype from the travel agent
* @access public
* @return string logotypesho
**/
LG.getAgentLogo = function(agent){
	var agentLogo = 'default.jpg';
	$.each(LG.agentData, function(agentIndex, a){ 
		if(agent == a.name){
			agentLogo = a.logo;
			return false;
		}
	});                  
	return agentLogo;  
};


/**
* Gets the full city name from iata
* @access public
* @param string IATA code
* @return string full name
**/
LG.getNameFromIATA = function(iata){
	fullname = iata;
	$.each(LG.iatamatch, function(iataind, i){
		if(iata == i.iata){
			fullname = i.iname;
			return false;
		}
	});                   
	return fullname;
};

/**
* Cleans up the time data given to us
* @access public
* @return string time as minutes
**/
LG.cleanTime = function(timeString){
	if(timeString === "error"){
		return(parseInt('9999',10));
	} 
	timeString = String(timeString);
	var h = parseInt(timeString.split(/[a-z]/g)[0],10);
	var min = parseInt(timeString.split(/[a-z]/g)[1],10);
	mins = h*60+min;
	return(parseInt(mins,10));
};

/**
* Sorts results by price
* @access public
* @return void
**/
LG.sortResultsByPrice = function(a, b){
	return parseFloat(a.price).toFixed(2) - parseFloat(b.price).toFixed(2); 
};

/**
* Sorts results by transfer time
* @access public
* @return void
**/
LG.sortResultsByTime = function(a, b){
	return LG.cleanTime(a.totalTime[0]) > LG.cleanTime(b.totalTime[0]); 
};  
    
/**
* Shows groups
* @access public
* @param mixed caller object
* @return void
**/
LG.showGroupFlights = function(obj){
	var gname = obj.attr('id');
	var groupName  = gname.substr(gname.indexOf('_') + 1, gname.length);
	groupsToShow = $.find('#searchresults .group_'+groupName);
	$.each(groupsToShow, function(gind, g){
		$(g).show();
	});
}; 

/**
* Hides groups
* @access public
* @param mixed caller object
* @return void
**/
LG.hideGroupFlights = function(obj){
	gname = obj.attr('id');
	groupName  = gname.substr(gname.indexOf('_') + 1, gname.length);
	groupsToHide = $.find('#searchresults .group_'+groupName);
	counter = 0;
	$.each(groupsToHide, function(gind, g){
		$(g).hide();
	}); 
};

/**
* Displays number of flights in group
* @access public
* @return void
**/
LG.updateGroupCounts = function(){
	$.each(LG.agentData, function(intin, s){
		tempArr = LG.renderedSuppliers[s.name]; 
		if(tempArr && tempArr[1] > 1){
			tempDiv = $('#more_' + tempArr[0]);
			tempDiv.html('<span class="groupmore" id="grpshow_'+s.name+'">1/' + tempArr[1] + ' (visa alla)</span>');
			tempDiv.data('show', true);
		}                                             
	});
};  
/**
* Gets departure time
* @access public
* @param mixed json representation of flight
* @return void
**/
LG.getOutTime = function(obj){
	segmentCount = 0;  
	if(obj.length > 0){  
		if(obj[0].segment.length > 0){ 
			return(obj[0].segment[0]);
			
		}
		return(obj[0].segment);	
	} else { 
		if(obj.segment.length > 0){
			return(obj.segment[0]);
		}
		return(obj.segment);
	}
};   
/**
* Gets arrival time
* @access public
* @param mixed json representation of flight
* @return void
**/
LG.getInTime = function(obj){
	if(obj.length > 0){
		if(obj[0].segment.length > 0){ 
			return(obj[0].segment[obj[0].segment.length - 1]);
		}
		return(obj[0].segment);	
	} else {
		if(obj.segment.length > 0){
			return(obj.segment[obj.segment.length - 1]);
		}
		return(obj.segment);
	}
};

LG.getOutFlightNumber = function(obj){
	if(obj.length > 0){
		if(obj[0].segment.length > 0){ 
			return(obj[0].segment[obj[0].segment.length - 2]);
		}
		return(obj[0].segment);	
	} else {
		if(obj.segment.length > 0){
			return(obj.segment[obj.segment.length - 2]);
		}
		return(obj.segment);
	}
};

/**
* Is it a direct flight?
* @access public
* @param mixed caller object
* @return string
**/
LG.checkDirectFlight = function(obj){
	if(obj && obj.length > 1){
		if(obj[0].segment.length){
			return('EJ DIREKT');
		}
	}
	return('DIREKT'); 
};
/**
* Render the results
* @access public 
* @param mixed data object with results
* @param boolean should we display all?
* @return void
**/
LG.renderResults = function(data, renderAll){
	var counter = 0;
	LG.renderedSuppliers = [];
	$("#searchresults").empty(); 
	$.each(data, function(flightIndex, d){

		/*
		if (LG.getAgentLogo(d.agent) != 'http://www.flygresor.se/images/logos/se_a2btrvl.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_aobtrav.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_mytrip.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_resfebr.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_travlnk.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_brvofly.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_travelstart.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_travelpartner.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_supersavertravel.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_seat24.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_flygvaruhuset.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_budjet.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_travelfinder.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_travellink.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_opodoflyg.gif') {
		*/
		
		if (LG.getAgentLogo(d.agent) != 'http://www.flygresor.se/images/logos/se_a2btrvl.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_mytrip.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_travlnk.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_brvofly.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_travelstart.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_travelpartner.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_supersavertravel.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_seat24.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_flygvaruhuset.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_budjet.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_travelfinder.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_sembo.gif' && LG.getAgentLogo(d.agent) 
		!= 'http://www.flygresor.se/images/logos/se_opodoflyg.gif') {

			if(counter < LG.resultLimit || renderAll){  
				LG.renderAll = renderAll;
				LG.limitedResult.push(d);
				d.flightI = flightIndex;
				d.agentLogo =  LG.getAgentLogo(d.agent);
				d.inf = d['in'];
				d.isOutDirect = LG.checkDirectFlight(d.out);
		
				if(LG.isReturn == '1'){
					d.isInDirect = LG.checkDirectFlight(d['in']); 	
				}
				//if(LG.renderedSuppliers[d.agent] !== undefined){
		            //$.tmpl( LG.flightTemplateSingle, d ).appendTo("#flight_"+LG.renderedSuppliers[d.agent]);
					//$("#flight_"+flightIndex).show();
					//LG.renderedSuppliers[d.agent][1] += 1;
				 
				//else {
					$.tmpl(LG.flightTemplateGroup, d).appendTo("#searchresults");
				   	LG.renderedSuppliers[d.agent] = Array(flightIndex, 1);
				//} 
				counter++;
			} else {
				return false;
			}

		}

	});                    
	LG.updateGroupCounts(); 
	$('#flightstotalresults').show();
};

/**
* Prepare and parse the results
* @access public
* @return void
**/
LG.prepareResults = function(sortIndex, renderAll){
	var rAll = (renderAll == undefined) ? false : true; 
	sortIndex = typeof(sortIndex) != 'undefined' ? sortIndex : 'price';
	if(sortIndex == 'price'){
		LG.rawData.sort(LG.sortResultsByPrice);
	}                                                        
	if(sortIndex == 'time'){
		LG.rawData.sort(LG.sortResultsByTime);
	}
	$('#numresults').html(LG.rawData.length);
	if(LG.rawData.length > 0){
		$('#searchmeta').show();
	}
	$('#numresultscontainer').show();
	$('#flightstotalresults').html(LG.rawData.length); 
	LG.renderResults(LG.rawData, rAll);
};

/**
* Renders link to show alternatives, if any
* @access public
* @return string
**/    
LG.flightAlternatives = function(flightIndex, inout){
	var flightObj = null;
	if(LG.renderAll){
	   flightObj = LG.limitedResult[flightIndex][inout];
	} else {
	   flightObj = LG.rawData[flightIndex][inout];
	}
	var fString = '';
	
	if(flightObj && flightObj.length > 1){
		fString = '<a class="showalts" id="alt_' + flightIndex + '_' + inout + '"><img src="/assets/images/plus_sign.png" alt="Visa alternativ"/></a>'; 
	}
	return(fString); 
}; 

/**
* Renders flight alternatives
* @access public
* @return string
**/
LG.getFlightAlternatives = function(flightIndex, inout){
	var flightObj = null;
	var resultString = ""; 
	
	if(LG.renderAll){
	   flightObj = LG.limitedResult[flightIndex];
	} else {
	   flightObj = LG.rawData[flightIndex];
	}
	if(inout == 'in'){
		resultString += '<div class="altin dirtable"><table>'; 
		
		$.each(flightObj.inf, function(ii, a){
			if(ii == 0){ 
				return('');
			} 
			//console.log(flightIndex + '---' + ii);
			//console.log(ii);
			if(a.segment && a.segment.departureDate){
				resultString += '<tr><td width="105">&nbsp;</td><td width="106">' + a.segment.departureDate.substr(11,15) + '</td><td width="110">('+ a.segment.flight + ')</td><td width="22">&nbsp;</td><td width="108">' + a.segment.arrivalDate.substr(11,15) + '</td><td width="100">(' + a.segment.flight + ')</td></tr>';
			} else {   
				if(a.length > 1){
					resultString += '<tr><td width="105">&nbsp;</td><td width="106">' +  a[0].departureDate.substr(11,15) + '</td><td width="110">('+ a[0].flight + ')</td><td width="22">&nbsp;</td><td width="108">' + a[0].arrivalDate.substr(11,15) + '</td><td width="100">(' + a[0].flight + ')</td></tr>';
				} else {  
					if(a.departureDate){
						resultString += '<tr><td width="105">&nbsp;</td><td width="106">' +  a.departureDate.substr(11,15) + '</td><td width="110">('+ a.flight + ')</td><td width="22">&nbsp;</td><td width="108">' + a.arrivalDate.substr(11,15) + '</td><td width="100">(' + a.flight + ')</td></tr>'; 	
					} else {
						if(a.segment){
							 resultString += '<tr><td width="105">&nbsp;</td><td width="106">' + a.segment[0].departureDate.substr(11,15) + '</td><td width="110">('+ a.segment[0].flight + ')</td><td width="22">&nbsp;</td><td width="108">' + a.segment[0].arrivalDate.substr(11,15) + '</td><td width="100">(' + a.segment[0].flight + ')</td></tr>'; 
						}
					}
					
				}
				
			}	   
		});                                   
		resultString += '</table></div>';
	}
	if(inout == 'out'){
		resultString += '<div class="altout dirtable"><table>';
		$.each(flightObj.out, function(ii, a){
			if(ii == 0){
				return;
			}   
			
			if(a.segment && a.segment.departureDate){
				resultString += '<tr><td width="105">&nbsp;</td><td width="106">' + a.segment.departureDate.substr(11,15) + '</td><td width="110">('+ a.segment.flight + ')</td><td width="22">&nbsp;</td><td width="108">' + a.segment.arrivalDate.substr(11,15) + '</td><td width="100">(' + a.segment.flight + ')</td></tr>';
			} else {
				if(a.length > 1){
					resultString += '<tr><td width="105">&nbsp;</td><td width="106">' + a[0].departureDate.substr(11,15) + '</td><td width="110">('+ a[0].flight + ')</td><td width="22">&nbsp;</td><td width="108">' + a[0].arrivalDate.substr(11,15) + '</td><td width="100">(' + a[0].flight + ')</td></tr>';
				} else {
					if(a.departureDate){
						resultString += '<tr><td width="105">&nbsp;</td><td width="106">' + a.departureDate.substr(11,15) + '</td><td width="110">('+ a.flight + ')</td><td width="22">&nbsp;</td><td width="108">' + a.arrivalDate.substr(11,15) + '</td><td width="100">(' + a.flight + ')</td></tr>';	
					} else {
						if(a.segment){
							 resultString += '<tr><td width="105">&nbsp;</td><td width="106">' + a.segment[0].departureDate.substr(11,15) + '</td><td width="110">('+ a.segment[0].flight + ')</td><td width="22">&nbsp;</td><td width="108">' + a.segment[0].arrivalDate.substr(11,15) + '</td><td width="100">(' + a.segment[0].flight + ')</td></tr>';
						}
					}
					
				}
			} 
			   
		});                                   
		resultString += '</table></div>';
	}                                     
	return(resultString);
};

/**
* Cancels search
* @access public
* @return void
**/
LG.cancelSearch = function(){
	searchStatus = 'complete';
	if(LG.rawData.length >= LG.resultLimit){
		$('#flightsshowmore').show();
	}
	$('#searchstats').hide();	
	$('#searchagain').show();
};
 
$('#searchresults .gotobook').live('click', function(d){
	var thisID = $(this).attr('id');
	var bookNum = thisID.substr(5, thisID.length);
	LG.track('external', '/result/'+bookNum);
	return true;
});
// add click handler to all groupmore links
$('#searchresults .groupmore').live('click', function(d){   
	LG.track('internal', '/toggle/group/'+$(this).attr('id'));
    if($(this).data('show') == undefined){
		LG.showGroupFlights($(this));
		$(this).data('show', 'true');
		//$(this).toggleClass('groupless');   
	} else {
		LG.showGroupFlights($(this));
		$(this).removeData('show');
		//$(this).toggleClass('groupless');
	}   
}); 

$('#searchresults .showalts').live('click', function(d){
	var thisID = $(this).attr('id');
	var altIDS = thisID.split('_');  
	if($(this).data('show') === undefined){ 
		$(this).data('show', 'true'); 
		thisIMG = $(this).children()[0];
		$(thisIMG).attr('src', base_url + 'assets/images/minus_sign.png');
	} else {
		$(this).removeData('show');
		thisIMG = $(this).children()[0];
		$(thisIMG).attr('src', base_url + 'assets/images/plus_sign.png');
	}
    LG.track('internal', '/toggle/flightinformation/' + altIDS[1]);
	$('#flightalt_' + altIDS[1] + '_' + altIDS[2]).toggle();
}); 

$('#searchagainbtn').live('click', function(d){
	$('#noresults').hide();
	$('#searchagain').show();
});

// add click handler to the sort buttons
$('#sortbyprice, #sortbytime').live('click', function(b){ 
	if($(this).attr('id') == 'sortbyprice'){
		LG.prepareResults();
		$(this).attr('src', base_url + 'assets/images/priceon.png');
        LG.track('internal', '/sort/byprice');
		$('#sortbytime').attr('src', base_url + 'assets/images/timeoff.png');
	} else {
		LG.prepareResults('time');
		$(this).attr("src", base_url + 'assets/images/timeon.png');
        LG.track('internal', '/sort/bytime');
		$('#sortbyprice').attr('src', base_url + 'assets/images/priceoff.png');
	}
});
