dojo.require("dojo.fx");
dojo.require("dojo.NodeList-fx");
dojo.require("dojo.date");
dojo.require("dojo.io.script");

// Constants
var DUR_FADE = 400;
var DUR_WIPE = 400;
var PANE = "destSelector";
var LIST = "destList";
var RADIO = "destRadio";
var DETAILS = "destInfo";
var RESULTS = "destResults";

// Global vars
var sDestSelected = "a"; //All
var sDestIATA = null;
var bFirstRun = true;
var SPECIAL_DAYS = null;
var bDestListShowing = true;
var sDefaultHeader = dojo.byId("pageheaderWrapper").innerHTML;
var iListHeight = dojo.style(LIST, "height");
var bRenderDivider = false;
var selectedDate = null;
var targetDate = null;
//Panoramio vars and constants

var  NUMBEROFPICTURES = 25;	
var squareImages = null;
var mediumImages = null;



// Customize layout for scriptable browsers
dojo.style("destResults", "display", "none");
dojo.style("destWrapperNoBorder", "borderTop", "none");
dojo.query("#destSelector #destList .type.a").style("display","block");

if (sAirportType == "L") {
	dojo.query("#destSelector .menu").style("display","block");
	dojo.style("downarrow","display","block");
	dojo.style(LIST, "height", "80px");
	var bExpanded = false;
	dojo.byId(PANE).onmouseover = function() {
		if (!bExpanded) {
			dojo.fadeOut({
				node: "downarrow",
				duration: 400,
				onEnd: function() {
					dojo.style("downarrow","display","none");
					dojo.style("destWrapperNoBorder","marginBottom","10px");
				}
			}).play();
			dojo.fx.wipeIn({
				node: LIST,
				duration: 800
			}).play();
		}
		bExpanded = true;
	}
} else if (sAirportType == "S") {
	dojo.query("#destSelector").style("display","none");
} else {
	//All other airports, types "M" and "S"
	dojo.query("#destSelector .menu").style("display","block");
	//dojo.style("destWrapperNoBorder", "borderTop", "1px solid #c9c9c9");
	dojo.style("destWrapperNoBorder","marginBottom","10px");
}

dojo.style(LIST, "display", "block");

dojo.addOnLoad(function() {							//Initialization
	if(preselected != null && preselected.length > 0) {
		showDest(preselected, sFromAirportname, preselectedName);
		getDestinationInfo(preselected, preselectedName);		
	}

	if (domestic != null && domestic.length > 0) {
		filterFlights(domestic);
	} 

	dojo.byId("datefield").value = sCurrentDate;	//Populate hidden field with current date

	var splitDate = sCurrentDate.split(".");
	
	if (splitDate[1].length == 1) {
      	splitDate[1] = "0" + splitDate[1];
    }
	dojo.byId("flightSelectionDate").innerHTML = getFormattedDate(new Date());	//Populate date field with current date
	dojo.query("#destList div div a").onclick(		//Initialize click actions
		function(e) {
			var airportName = e.target.innerHTML;
			showDest(dojo.attr(e.target,"title"), sFromAirportname, e.target.innerHTML);
			getDestinationInfo(dojo.attr(e.target,"title"),airportName);
			e.target.blur();
			e.preventDefault();
		}
	)

	if (sAirportType == "S") {
		showDest(sIataCode, sFromAirportname, sDestination);
		getDestinationInfo(sIataCode, sDestination)
	}
				

});

function calendarSetup() {
	Calendar.setup({
		flat: "calendar-container",
		flatCallback: dateChanged,
		dateStatusFunc: ourDateStatusFunc,
		date: selectedDate,
		enableTodayForDisabledDates: true,
		showSelectedDayForDisabledDates: true
	});
}
function dateChanged(calendar) {
	   selectedDate = calendar.date;
    // Beware that this function is called even if the end-user only
    // changed the month/year.  In order to determine if a date was
    // clicked you can use the dateClicked property of the calendar: if (calendar.dateClicked) {}
  
      var y = calendar.date.getFullYear();
      var m = calendar.date.getMonth() + 1; // integer, 0..11
      var d = calendar.date.getDate();      // integer, 1..31
	
	  var selected = d + "." + m + "." + y
      dojo.byId("datefield").value = selected;
      dojo.byId("flightSelectionDate").innerHTML = getFormattedDate(selectedDate);	//Populate date field with current date
  
      if (sDestIATA != null) {
	      showDest(sDestIATA, sFromAirportname, dojo.byId("destInfoTo").innerHTML);
	  }
  };

function getFormattedDate(date) {
	var weekdayNo = ['søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'];
	var weekdayEn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
	var monthNo = ['januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember'];
	var monthEn = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
	
	var day = date.getDate();
	var month = date.getMonth();
	
	
	if (language == "en") {
		return weekdayEn[date.getDay()] + " " + monthEn[month] + " " + day + "th";
	} else {
		return weekdayNo[date.getDay()] + " " + day + ". " + monthNo[month];
	}
}

function dateIsSpecial(year, month, day) {
	if(!SPECIAL_DAYS)return false;
	var m = SPECIAL_DAYS[month];
	if (!m) return false;	
	for (var i in m){ 
		if (m[i] == day){
			return true;
		}
	}
	return false;
}
function ourDateStatusFunc(date, y, m, d) {
	if (dateIsSpecial(y, m, d)){
		return "special";
	} else {
		return true; // return true if you want to disable other dates
	}
}

//only works with text
function niceReplaceContent(theNode, theText) {
	dojo.fadeOut({
		node: theNode,
		duration: DUR_FADE,
		onEnd: function() {
			dojo.byId(theNode).innerHTML = theText;
			dojo.fadeIn({
				node: theNode,
				duration: DUR_FADE
			}).play();
		}
	}).play();
}
//works with a DOM node. 
function niceReplaceContentNode(theTargetNode, theNodeToBeInserted) {
	dojo.fadeOut({
		node: theTargetNode,
		duration: DUR_FADE,
		onEnd: function() {
			dojo.empty(theTargetNode);
			dojo.byId(theTargetNode).appendChild(theNodeToBeInserted);
			dojo.fadeIn({
				node: theTargetNode,
				duration: DUR_FADE
			}).play();
		}
	}).play();
}

function niceInsertDOMnode(theTargetNode, theNodeToBeInserted){
	dojo.style(theNodeToBeInserted,"opacity",0);
  	theTargetNode.appendChild(theNodeToBeInserted);
  	dojo.fadeIn({node:theNodeToBeInserted,duration:DUR_FADE}).play();
}


function showDestList() {
	niceReplaceContent("pageheaderWrapper", sDefaultHeader);
	dojo.fx.wipeIn({
		node: "destSelector",
		duration: DUR_WIPE
	}).play();
	dojo.fadeIn({
		node: "destSelector",
		duration: DUR_FADE
	}).play();
	bDestListShowing = true;
}

function showDest(sIATA, sFromAirportName, sDestName) {
	// Hide destination list
	//if (bDestListShowing && sAirportType == "L") {
	if (bDestListShowing) {
		niceReplaceContent("pageheaderWrapper", '<div class="headerDestName"><h1>' + sFromAirportName + " - " + sDestName + '</h1></div><div class="showdestlist"><span><a href="#" onclick="showDestList();return false">' + sSelectNewDest + '</a></span></div>')
		dojo.fx.wipeOut({
			node: "destSelector",
			duration: DUR_WIPE
		}).play();
		dojo.fadeOut({
			node: "destSelector",
			duration: DUR_FADE
		}).play();
		bDestListShowing = false;
	}
//	dojo.byId("datefieldVisible").innerHTML = dojo.byId("datefield").value;
	dojo.fadeOut({
		node: "destFlightsFade",
		duration: DUR_FADE,
		onEnd: function() {
			getFlights(sIATA, sDestName)
		}
	}).play();
	sDestIATA = sIATA;
}

function findNextFlightDate(dates){
	var jsDates = eval(dates);
	var today = new Date();
	targetDate = today;
	var returnDate = today;
	var addYear = 0;
	var lastMonth = null;
	var firstMonthInSpecDays = null;
	if(selectedDate!=null){
		targetDate = selectedDate;
		returnDate = targetDate;
	}
	var tst ="";
	var dateArray = new Array();
	var counter = 0;
	//Build array of dates
	for (var i in jsDates){
		if(firstMonthInSpecDays==null){
			firstMonthInSpecDays=eval(i);
		}
		if(eval(i)<today.getMonth()){
			addYear=1;
		}
		else{
			addYear=0;
		}
		
		for (var j in jsDates[i]){
			dateArray[counter] = new Date(today.getFullYear()+addYear,i,jsDates[i][j],0,0,0,0);
			counter++;
		}
	}
	dateArray.sort(NumCmp);
  	for (var i =0;i<dateArray.length;i++) {
    	if (dateArray[i]<=targetDate) {
      		if(i <dateArray.length-1){
	      		if (dateArray[i+1]>targetDate){
	        		if((targetDate-dateArray[i])>(dateArray[i+1]-targetDate)){
	        			returnDate=dateArray[i+1];
	        		}
	        		else{
	        			returnDate=dateArray[i];
	        		}
	      		}
	      	}
	      	else if (i==dateArray.length-1&&dateArray[i]<targetDate){
	      		returnDate=dateArray[i];
	      	}      	
    	}
  	}  
  	//case = target is before any of the dates in Array.
  	if(returnDate == targetDate){
  		returnDate=dateArray[0];
  	}
	return returnDate;
}
function NumCmp(a, b) { return a-b }

//sIata er destinasjonen vi har trykket på
function getDestinationInfo(sIATA, sDestName){
	
	//empty pictures for previous destination
	dojo.empty("destInfoPanoramio");
	//empty links for previous destination
	dojo.empty("destInfoMoreAbout");
	//make asynch content boxes show loading spinner
	renderSpinner("destInfoPanoramio");
	renderSpinner("toFromMap");
	renderSpinner("localTimeId");
	dojo.xhrGet({
	url: "/directflightscontent?iata=" + sIATA  + "&language=" + language,
	handleAs: "json",
	timeout: 5000,
    	load: function(response, ioArgs) {
    		
    		handleImages(response,picturesNotAvblText);
    		
    		var title = "";
    		var destUrlsJSON = response.destUrls;
    		var titleJSON = destUrlsJSON.title;
    		var imagesJSON = response.destUrls;
    		var latLngForDestinationAirport = response.latLngForDestAirport;
    		var timeZone = response.timeZone;
    		
    		if(titleJSON!=null){
    			if(titleJSON.length > 0)
    			title = titleJSON;
    		}
    		var urlsArray = new Array();
    		if(destUrlsJSON.urls!=null){
    		  if(destUrlsJSON.urls.length > 0){
    		 	for(i = 0; i < destUrlsJSON.urls.length; i++){
    		 		urlsArray[i] = destUrlsJSON.urls[i];
    		 	}
    		 }
    		}
   
			if(title==""){
					title = dojo.trim(sDestName);
					if(title.indexOf("/")>0){
						title=title.substring(0,title.indexOf("/"));
				}
			}
    		
    		/*if no urls from server - generate one manually*/
    		if(urlsArray.length < 1){
    		  var sDestNamePretty = dojo.trim(sDestName);
    		  if(sDestNamePretty.indexOf("/")>0){
						sDestNamePretty=sDestNamePretty.substring(0,sDestNamePretty.indexOf("/"));
				}   
    		  	var linkText = wikipediaTextUrl+sDestNamePretty;
    		  	var hrefText = wikipediaBaseLink+sDestNamePretty
    		  	urlsArray[0] = {
    								"href": hrefText,
    								"text": linkText,
    								"target":"_blank"
    						  };
    		}
    		
    		var localTime = "";
    		if(timeZone!=null){
    			localTime = timeZone.localTime;
    		}
    		else{
				localTime = localTimeNotAvblText;
    		}
    		
    		renderDestinationUrls(title,urlsArray);
    		updateLocalTime(localTime);
    		if(latLngForDestinationAirport!=null){
    			renderDestinationMap(latLngForDestinationAirport);	
    		}
    		else{
    			renderDestinationMapMessage(destMapNotAvblText);	
    		}
		},
        error: function(error) {
        	renderDestinationMapMessage(mapErrorMessage);
			renderDestinationImagesMessage(imagesErrorMessage);
			renderDestinationUrlMessage(destinationLinksErrorMessage);
		}
	});
}
function getFlights(sIATA, sDestName) {
	var sOutbound
	var sInbound;
	renderTravelTime(0,sFromAirportname,sDestName,sCurrentAirportName); // Showing while retrieving, and to display something if no flights.
	sDate = dojo.byId("datefield").value;
	renderSpinner("destFlightsFade");
	renderHeader(sDestName); // Change header immediately to show destination while retrieval is underway
	dojo.xhrGet({
		url: "/flightinfo?from=" + sCurrentAirportIATA + "&to=" + sIATA + "&date=" + sDate + "&language=" + language,
		handleAs: "xml",
		timeout: 10000,
        load: function(response, ioArgs) {
			if (response.getElementsByTagName("outbound").length > 0 || response.getElementsByTagName("inbound").length > 0) {
				sOutbound = renderFlights(response,"outbound");
				sInbound = renderFlights(response,"inbound");
				var minflighttime = response.getElementsByTagName("minflighttime")[0].firstChild.nodeValue;
				renderTravelTime(minflighttime,sFromAirportname,sDestName,sCurrentAirportName);
				if (sOutbound.length > 0 && sInbound.length > 0) {
					dojo.byId("destFlightsFade").innerHTML = sOutbound + "<hr />" + sInbound;
				} else {
					dojo.byId("destFlightsFade").innerHTML = sOutbound + sInbound;
				}
				if (dojo.byId("outboundFrom")) dojo.byId("outboundFrom").innerHTML = sCurrentAirportName;
				if (dojo.byId("inboundTo")) dojo.byId("inboundTo").innerHTML = sCurrentAirportName;
				if (dojo.byId("inboundFrom")) dojo.byId("inboundFrom").innerHTML = sDestName;
				if (dojo.byId("outboundTo")) dojo.byId("outboundTo").innerHTML = sDestName;
				renderHeader(sDestName); // Need to render header again in case user clicks on another destination mid-retrieval
			} else {
				renderErrorAndShowNextFlight(sErrorMessage["404"],findNextFlightDate(response.getElementsByTagName("specialdates")[0].firstChild.nodeValue));
			}
			sSpecialDays = response.getElementsByTagName("specialdates")[0].firstChild.nodeValue; //CDATA-field containing flightdates
			eval(sSpecialDays);
			refreshCalendar();
			return response;
		},
        error: function(response, ioArgs) {
			SPECIAL_DAYS = null;
        	var status = ioArgs.xhr.status;
			switch (status) {
				case 404:
					renderError(sErrorMessage["404"]);
					break;
				case 500:
					renderError(sErrorMessage["500"]);
					break;
				default:
					renderError(sErrorMessage["generalError"]);
			}
		}
	});
}
function refreshCalendar() {
	dojo.byId("calendar-container").innerHTML = "";
	calendarSetup();
}

function renderDestinationMap(latLngForDestinationAirport) {
	var destLat = latLngForDestinationAirport.lat;
	var destLng = latLngForDestinationAirport.lng;
	var destLatLng = new google.maps.LatLng(destLat, destLng);
	
	var currentLatLng = latLngCurrentAirport.split(",");
	var gCurrentLatLng = new google.maps.LatLng(currentLatLng[0], currentLatLng[1])
	
	var centerLat = (1*destLat + 1*currentLatLng[0])/2;
	var centerLng = (1*destLng + 1*currentLatLng[1])/2;

	var strokeColorForLocation = "0xE56020"

   	var center = centerLat + "," + centerLng;
   	var destMarker = destLat + "," + destLng;
   	var currentMarker = currentLatLng[0] + "," + currentLatLng[1];

	var anchorTag = "<a onclick=\"return hs.htmlExpand(this, { objectType: 'iframe', width: 850, height: 670, objectLoadTime: 'after'} )\" href=\"/resources/jsp/map.jsp?destLat=" + destLat + "&amp;destLng=" + destLng + "&amp;currentLat=" + currentLatLng[0] + "&amp;currentLng=" + currentLatLng[1] + "&amp;\" class=\"  \">";
   	var innerHTML = "<img border=\"0\" src=\"http://maps.google.com/maps/api/staticmap?center=" + center + "&amp;markers=color:blue|" + destMarker + "|" + currentMarker +"&amp;path=color:" + strokeColorForLocation + "|weight:5|" + destMarker + "|" + currentMarker + "&amp;size=236x198&amp;sensor=false\" onclick=\"recordEvent('Google Maps', '" + currentLatLng[0] + "," + currentLatLng[1] + "');\">";
	var anchorEnd = "</a>";
	var highslideContent = "<div id=\"highslide-map\" class=\"highslide-maincontent\"></div>";

   	var toFromMap = dojo.byId("toFromMap");
   	niceReplaceContent(toFromMap,anchorTag + innerHTML + anchorEnd + highslideContent);
   	
}

function renderDestinationMapMessage(messageText) {	
 	var messageContent = "<div class=\"notAvblMessage\">" + messageText + "</div>";
 	var toFromMap = dojo.byId("toFromMap");
 	niceReplaceContent(toFromMap,messageContent);
}

function renderDestinationImagesMessage(messageText){
	var messageContent = "<div class=\"notAvblMessage\">" + messageText + "</div>";
	var destImages = dojo.byId("destInfoPanoramio");
 	niceReplaceContent(destImages,messageContent);
}

function renderDestinationUrlMessage(messageText){
	var messageContent = "<div class=\"notAvblMessage\">" + messageText + "</div>";
	var destImages = dojo.byId("localTimeId");
 	niceReplaceContent(destImages,messageContent);
}

function renderDestinationUrls(title,urlsArray)
{
   var n = dojo.byId("destInfoMoreAbout");
   var nodeToBeInserted = dojo.create("SPAN");
   nodeToBeInserted.innerHTML = moreAboutMessage + title+":";
   var br1 = document.createElement("br");
   nodeToBeInserted.appendChild(br1);
   
   if(urlsArray.length > maxNumDestUrls){
    //remove elements if urlsArray is longer than the number of maximum allowed urls to be displayed
   	urlsArray.splice(maxNumDestUrls,urlsArray.length); 
   	}
   	
   for(var i=0; i < urlsArray.length; i++)
   {
   	var aSpan = dojo.create("span");
   	dojo.attr(aSpan,"class","destInfoMoreAboutIndividualLink");
   	var a1 = document.createElement("a");
   	a1.setAttribute('href', urlsArray[i].href);
	a1.setAttribute('onClick', "recordEvent('Wikipedia', '" + urlsArray[i].href + "');");
   	a1.setAttribute('target',urlsArray[i].target);
   	dojo.attr(a1,"title",urlsArray[i].text);
   	a1.innerHTML= urlsArray[i].text;
   	dojo.place(a1,aSpan);
   	//var br2 = document.createElement("br");
   	nodeToBeInserted.appendChild(aSpan);
   	//nodeToBeInserted.appendChild(br2);
   }
   niceReplaceContentNode(n,nodeToBeInserted);
}

function renderTravelTime(flighttime,sFromAirportName,sDestName,sCurrentAirportName){
	if(flighttime != "0"){
		if(isMSIE7orOlder()){
			dojo.byId("travelTimeId").innerHTML='<span class="infoText">' + shortesttimeMessage +' </span>' + flighttime;
		}
		else{
			niceReplaceContent(dojo.byId("travelTimeId"),'<span class="infoText">' + shortesttimeMessage +' </span>' + flighttime);
		}
	}
	else {
		dojo.byId("travelTimeId").innerHTML="";
	}
}
function updateLocalTime(time) {
	niceReplaceContent(dojo.byId("localTimeId"),time);
}
function renderFlights(flights, sDirection) {
	var sRows = "";
	var f = flights.getElementsByTagName(sDirection);
	if (f != null && f.length > 0) {
		/*
		var finnFrom = flights.childNodes[0].getAttribute("finnFrom");
		var finnTo = flights.childNodes[0].getAttribute("finnTo");
		var date = flights.childNodes[0].getAttribute("date");
		
		//Reverse direction for inbound flights
		if (sDirection == "inbound") {
			finnFrom = flights.childNodes[0].getAttribute("finnTo");
			finnDest = flights.childNodes[0].getAttribute("finnFrom");
		}
		*/
		var finnRow = '';
		
		/*
		if (finnFrom != '' && finnTo != '') {
			finnRow = '<tr><td class="finnInfo"><a href="http://www.finn.no/finn/travel/air/progress?userAction=search&newSearch=true&searchType=FLIGHT&asynchronous=true&incremental=false&externalSearch=true&locOriginCodes='+ finnFrom + '&locDestinationCodes=' + finnTo + '&oneWayOnly=true&depDate=' + date + '&retDate=' + date + '&outwardDirect=true&returnDirect=true' + '" target="_blank">Finn billigste pris</a></td></tr>';
		}
		*/
		
		var sRows = '<table id="' + sDirection + '"><tbody>' + finnRow + sTableHeader[sDirection] + '<tr><td class="directFlightTimeInfo" colspan="3">' + timeMessage + '</td></tr>' + sTableHeader["legend"];
		for (var i = 0; i < f.length; i++) {
			sRows += '<tr><td>' + f[i].getAttribute("flightno") + '</td>';
			sRows += '<td>' + f[i].getAttribute("departure") + '</td>';
			sRows += '<td>' + f[i].getAttribute("arrival") + '</td>';
			var airlineUrl = f[i].getAttribute("airlineurl");
			var charter = f[i].getAttribute("charter");
			
			if("null" != charter && null != charter) {
				if("null" == airlineUrl || null == airlineUrl){
					sRows += '<td>' + f[i].getAttribute("airline") + charter + '</td></tr>';
				}else{
					sRows += '<td><a target="_blank" href="' + airlineUrl + '">' + f[i].getAttribute("airline") + '</a>' + charter + '</td></tr>';
				}
			}
			else {
				if("null" == airlineUrl || "" == airlineUrl || null == airlineUrl){
					sRows += '<td>' + f[i].getAttribute("airline") + '</td></tr>';
				}else{
					sRows += '<td><a target="_blank" href="' + airlineUrl + '">' + f[i].getAttribute("airline") + '</a></td></tr>';
				}
			}
		}
		sRows += "</tbody></table>";
	}
	return sRows;
}
function renderHeader(sDestName) {
	var sDate = dojo.byId("datefield").value;
//	dojo.byId("datefieldVisible").innerHTML = sDate;
	dojo.byId("destInfoTo").innerHTML = sDestName;
	fadeInDest();
}
function renderError(message) {
	dojo.byId("destFlightsFade").innerHTML = '<table><tbody><tr><td class="error">' + message + '</td></tr></tbody></table>';
}

function renderErrorAndShowNextFlight(message, firstFlightDate){
	var formattedDate = getFormattedDate(firstFlightDate);
	var firstFlightDateString = firstFlightDate.toString();
	dojo.byId("destFlightsFade").innerHTML = '<table><tbody><tr><td class="error">' + message +'<br/>' + 
	nextDateAvailableText + " " + "<a class=\"nextDateAvbl\" onclick=\"goToFirstFlightDate('"+ firstFlightDateString + "');return false\" href=\"#\">"+formattedDate+"</a>.</td></tr></tbody></table>";
}

function goToFirstFlightDate(firstFlightDate){
	var dateFirstFlight = new Date(firstFlightDate); 
	selectedDate = dateFirstFlight;
	refreshCalendar();
	
	var y = dateFirstFlight.getFullYear();
    var m = dateFirstFlight.getMonth() + 1; // integer, 0..11
    var d = dateFirstFlight.getDate();      // integer, 1..31

    var selected = d + "." + m + "." + y
 	dojo.byId("datefield").value = selected;
    dojo.byId("flightSelectionDate").innerHTML = getFormattedDate(selectedDate);	//Populate date field with current date
    
	if (sDestIATA != null) {
	     showDest(sDestIATA, sFromAirportname, dojo.byId("destInfoTo").innerHTML);
	}
}

function fadeInDest() {
	if (bFirstRun) {
		dojo.style("destFlightsFade","opacity","0");
		dojo.style(RESULTS,"opacity","0");
		dojo.style(RESULTS,"display","block");
		dojo.style("destInfoAdditionalInfo","display","block");
		dojo.fx.chain([
			dojo.fadeIn({
				node: RESULTS,
				duration: DUR_FADE
			}),
			dojo.fadeIn({
				node: "destFlightsFade",
				duration: DUR_FADE
			}),
			dojo.fadeIn({
				node: "destInfoAdditionalInfo",
				duration: DUR_FADE
			})
		]).play();
	} else {
		dojo.fadeIn({
			node: "destFlightsFade",
			duration: DUR_FADE
		}).play();
	}
	bFirstRun = false;
}
function filterFlights(sType) {
	if (sType != sDestSelected) {
		dojo.query("#" + RADIO + "_" + sType).addClass("selected");
		dojo.query("#" + RADIO + "_" + sDestSelected).removeClass("selected");
		dojo.query("#" + PANE + " #" + LIST + " .type." + sDestSelected).fadeOut({
			duration: DUR_FADE,
			onEnd: function() {
				var oldHeight = dojo.style(LIST, "height");
				dojo.query("#" + PANE + " #" + LIST + " .type").style("display", "none");
				dojo.query("#" + PANE + " #" + LIST + " .type." + sType).style("display", "block");
				dojo.query("#" + PANE + " #" + LIST + " .type." + sType).fadeIn({
					duration: DUR_FADE
				}).play();
			}
		}).play();
		sDestSelected = sType;
	}
}

function renderSpinner(node) {
	dojo.byId(node).innerHTML = '<table><tbody><tr><td class="loading">&nbsp;</td></tbody></table>';			
}

//Panoramio related
//**************************
var handleImages = function(response,textNotAvbl){
	if(response.destImages.tridionImages!=null){
    	handleTridionPhotos(response);
    } 
    else if(response.destImages.imagesData!=null){
    	fetchPanoramioPhotos(response.destImages.imagesData.lat,response.destImages.imagesData.lng,response.destImages.imagesData.radiusWidth,response.destUrls.relCity);
    }
    else{
    	renderDestinationImagesMessage(textNotAvbl);
    }
 }


var handleTridionPhotos = function(res){
	var linktag;
	var tridionPhotosNode = dojo.create("SPAN");
	var tridionPhotosHeader = dojo.create("H3");
	tridionPhotosHeader.innerHTML = ""+picturesFrom+" "+res.destUrls.relCity;
	dojo.place(tridionPhotosHeader,tridionPhotosNode);
	for(i=0;i<res.destImages.tridionImages.length;i++){
				res.destImages.tridionImages[i].photo_file_url;
			  linktag = renderLinkTag(res.destImages.tridionImages[i].photo_file_url);
			  dojo.place(renderImgTagSizedWithTitle(res.destImages.tridionImages[i].photo_file_url,60,60,res.destImages.tridionImages[i].photo_title),linktag);
			  if(i>2){
					dojo.style(linktag,{"display":"none"});
				}
			  dojo.place(linktag,tridionPhotosNode,"last");				   
			  
		 	
	}
	dojo.empty("destInfoPanoramio");
	niceReplaceContentNode("destInfoPanoramio",tridionPhotosNode);
}


//x=lat, y=long,rad=radius
var fetchPanoramioPhotos = function(x,y,rad,city){
		
		var bbox = boundingBox(x,y,rad);
		var getmediumpics = {
			url: "http://www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to="+NUMBEROFPICTURES+"&minx="+bbox[1]+"&miny="+bbox[0]+"&maxx="+bbox[3]+"&maxy="+bbox[2]+"&size=medium",
			callbackParamName: "callback",
			load: function(data){
				handlePanoramioImages(data,city);
			}
		};
		dojo.io.script.get(getmediumpics);		
	}
	
var renderImgTagSized = function(url,x,y){
					 var img    = document.createElement('IMG');
					 img.setAttribute("src",url);
					 img.setAttribute("id","destInfoImages")
					 img.setAttribute("height",""+y);
					 img.setAttribute("width",""+x);
					 img.setAttribute('onClick', "recordEvent('Panoramio', '" + url + "');");
					 return img;
	}
	
var renderImgTagSizedWithTitle = function(url,x,y,title){
					var img    = document.createElement('IMG');
					 img.setAttribute("src",url);
					 img.setAttribute("id","destInfoImages")
					 img.setAttribute("height",""+y);
					 img.setAttribute("width",""+x);
					 img.setAttribute("title",""+title);
					 return img;
}
var renderLinkTag = function(url){
					 var a = document.createElement('a');
					 a.setAttribute("href",url);
					 a.setAttribute("class","highslide");
					 if(isMSIE7orOlder()){
						a.onclick= function() {return hs.expand(this, {thumbnailId: '1', slideshowGroup: '1',useBox: false})};
					 }
					 else{
					 	a.setAttribute("onclick","return hs.expand(this, {thumbnailId: '1', slideshowGroup: '1',useBox: false})");
					 }
					 a.setAttribute("id","1");
					 return a;
	}
	   		
var handlePanoramioImages = function(response,city){
	var linky;
	var panoramioNode = dojo.create("DIV");
	var panoramioHeader = dojo.create("H3");
	panoramioHeader.innerHTML = ""+picturesFrom+" "+city;
	dojo.place(panoramioHeader,panoramioNode);
	if(response != null){
			//her kan du starte  generere a-tagger..
			for(x=0;x<response.photos.length;x++){
			  linky = renderLinkTag(response.photos[x].photo_file_url);
			  dojo.place(renderImgTagSized(response.photos[x].photo_file_url,60,60),linky);
			  if(x>2){
					dojo.style(linky,{"display":"none"});
				}
			  dojo.place(linky,panoramioNode,"last");				   
			  dojo.place("<div class=\"highslide-caption\"><div><a href=\"http://www.panoramio.com/\" target=\"_blank\"><img src=\"\/resources\/images\/logo-tos.png\" /></a><br /><a href=\""+response.photos[x].photo_url+"\" target=\"_blank\">"+response.photos[x].photo_title+"</a><br />by <a href=\""+response.photos[x].owner_url+"\">"+response.photos[x].owner_name+"</a></div></div>",panoramioNode);
		 	}
		 	if(response.photos.length < 3)
		 		dojo.place("<br />",panoramioNode);
		 	dojo.place("<a href=\"http://www.panoramio.com/\" onclick=\"recordEvent('Panoramio', 'http://www.panoramio.com/');\" target=\"_blank\"><img src=\"\/resources\/images\/logo-tos.png\"/></a><br />Photos are copyrighted by their owners",panoramioNode,"last");
			dojo.empty("destInfoPanoramio");
  			niceReplaceContentNode(dojo.byId("destInfoPanoramio"),panoramioNode);		
			
	}
}   

// degrees to radians
function deg2rad(degrees){
    return Math.PI*degrees/180.0;
}
// radians to degrees
function rad2deg(radians){
    return 180.0*radians/Math.PI;
}
// Semi-axes of WGS-84 geoidal reference
var WGS84_a = 6378137.0; // # Major semiaxis [m]
var WGS84_b = 6356752.3;  //# Minor semiaxis [m]

// Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
function WGS84EarthRadius(lat){
    //http://en.wikipedia.org/wiki/Earth_radius
    var An = WGS84_a*WGS84_a * Math.cos(lat);
    var Bn = WGS84_b*WGS84_b * Math.sin(lat);
    var Ad = WGS84_a * Math.cos(lat);
    var Bd = WGS84_b * Math.sin(lat);
    return Math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) );
}
// Bounding box surrounding the point at given coordinates,
// assuming local approximation of Earth surface as a sphere
// of radius given by WGS84
function boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm){
    lat = deg2rad(latitudeInDegrees);
    lon = deg2rad(longitudeInDegrees);
    halfSide = 1000*halfSideInKm;

    //Radius of Earth at given latitude
    radius = WGS84EarthRadius(lat);
    // Radius of the parallel at given latitude
    pradius = radius*Math.cos(lat);

    latMin = lat - halfSide/radius;
    latMax = lat + halfSide/radius;
    lonMin = lon - halfSide/pradius;
    lonMax = lon + halfSide/pradius;
    var bbox = new Array();
    bbox[0]= rad2deg(latMin);
    bbox[1]= rad2deg(lonMin);
    bbox[2]= rad2deg(latMax);
    bbox[3]= rad2deg(lonMax);

    return bbox;
}
// End of Panoramio related

