/* -------------------------------------------------------------
 *	@Project: Frankfurt Airport City
 *	@Author: Florian Ludwig (triplesense.de)
 *	@Created: 2008-12-12
 *	@Last edited: Jürgen Bäckmann, 2009-03-13
 * ------------------------------------------------------------- */


/**
 * ViewController for flight search frontend application
 */
function ViewController() 
{
	var page; // current page 
	var items; // nr of items to be displayed
	var searchtype; // current type of search(arrival or departure)
	var iata; // current selected airport
	var flight;// current selected flight
    var airline;// current selected airline
	var baseurl;
	var init_arrival;
	var init_departure;
	var loading;                                          
	var context; // 0 Startseite, 1 Arrivals, 2 Departures
	var language; // en, de                                         
	var date_out;
    var typ;  // p=pax, c=cargo

	var detailpanel; // Zeiger auf geöffnete Detailansicht
	
	// Text-Platzhalter
	
	var html_loading;
	var text_flightnumber;
	var text_airport;
	
	ViewController.prototype.init = function (url,lng)
	{
		this.page = 1;
		this.items= 12;
		this.iata = '';
		this.flight ='';
        this.airline = '';
		this.baseurl = url;
		this.init_arrival=0;
		this.init_departure=0;
		this.loading=false;
		this.language = lng;
		this.detailpanel =false;
		this.date_out = '';
        this.date_return = '';
        this.typ = 'p';

		if (this.language=="de")
		{
			this.html_loading = '<p class="loading">Einen Moment bitte, die Daten werden geladen</p>';
			this.text_flightnumber = 'Flugnummer';
			this.text_airport ='Bitte Ort eingeben';
			this.html_error ='<p class="error">Die Flugsuche ist zurzeit nicht verfügbar.<br />Bitte versuchen Sie es gleich noch mal, indem Sie die Ansicht aktualisieren.</p><ul class="linklist nomarginbottom float-left"><li><a href="#" class="reloadbutton">Ansicht aktualisieren</a></li></ul>';
		}
		else
		{
			this.html_loading = '<p class="loading">Please wait. Loading flights data ...</p>';
			this.text_flightnumber = "Flight number";
			this.text_airport ="Please enter destination";
			this.html_error ='<p class="error">The Flight information system is temporary not availiable.<br/>Please try again later by updating the current view.<br /></p><ul class="linklist nomarginbottom float-left"><li><a href="#" class="reloadbutton">Update view</a></li></ul>';

		}
		
		// Default-Werte eintragen
		
		$("#arrival_flightnumber").val(this.text_flightnumber);
		$("#arrival_location").val(this.text_airport);
		$("#departure_flightnumber").val(this.text_flightnumber);
		$("#departure_location").val(this.text_airport);

        if (typeof(timeframes) != 'undefined' )
        {
            $("#arrival_time").val(timeframes[0].n);
            $("#departure_time").val(timeframes[0].n);
        }
        
		// Ehemals ermittelte Autocomplete-Werte, werden onClick gelöscht
		$("#arrival_flightnumber").click(function()
		{
			fVc.flight ='';
			return false;
		});
		$("#departure_flightnumber").click(function()
		{
			fVc.flight ='';
			return false;
		});
		$("#arrival_location").click(function()
		{
			fVc.iata ='';
			return false;
		});
		$("#departure_location").click(function()
		{
			fVc.iata ='';
			return false;
		});

		this.initSwapValues();

		$(".flightsearch1 .flightsearch").submit(function(){
			fVc.page=1;
			fVc.search("init","true");
			return false;
		});
		
		$(".flightsearch1 .itemcount").click(function(){
			var cHref = $(this).attr("href");
			fVc.items = cHref.substr(1);
			$(".flightsearch1 .itemcount").removeClass("active");
			$(this).addClass("active");
			fVc.search();
			return false;
		});                                                                                         

        if($("#saisonflugplan_form").length==1)
        {
            this.context=3;
        }
		else if($("#arrival_flightnumber").length==1) // Wir könnten auf der Home, der Arrivals oder der Flugübersichts-Seite sein
		{
			this.context=0;
			if($("#departure_flightnumber").length==0) // Wir sind auf der Arrivals-Seite
			{
				this.items=30;
				this.context=1;
			}
			if($(".flightsearch2").length==1) // Flugübersichtsseite
			{
				this.context=3;
                this.items=12;
			}
			this.switch2Arrivals();
		}
		else
		{
			if($("#departure_flightnumber").length==1) // Wir sind auf der Departures-Seite
			{
				this.context=2;
				this.items=30;
				this.switch2Departures();
			}
		}

        if ( ignoreinit )
        {                                             
            $(".flightsearch1").each(function(){this.style.display="none";} );
            ignoreinit = false;
        }
	}
	
	ViewController.prototype.switch2Arrivals = function ()
	{
		this.searchtype = 'arrival';
		$("#"+this.searchtype+"_flightnumber").val(this.text_flightnumber);
		$("#"+this.searchtype+"_location").val(this.text_airport);
        if ( typeof(timeframes) != 'undefined' )
    		$("#"+this.searchtype+"_time").val(timeframes[0].n);
		this.initAutoComplete();
	};
	
	ViewController.prototype.switch2Departures = function ()
	{
		this.searchtype = 'departure';
		$("#"+this.searchtype+"_flightnumber").val(this.text_flightnumber);
		$("#"+this.searchtype+"_location").val(this.text_airport);
        if ( typeof(timeframes) != 'undefined' )
    		$("#"+this.searchtype+"_time").val(timeframes[0].n);
		this.initAutoComplete();
	};
	
	ViewController.prototype.initAutoComplete = function ()
	{
		this.page = 1;
		this.iata = '';
		this.flight ='';

		var doinit=false;
		if (this.searchtype=="arrival" )
		{
            if ( this.init_arrival==0 )
            {
			    this.init_arrival=1;
			    doinit=true;
            }
            if ( typeof(flightsarrival) != 'undefined' )
            {
                $("#"+this.searchtype+"_flightnumber").flushCache();
                $("#"+this.searchtype+"_flightnumber").autocomplete(flightsarrival,
                    {
                        autoFill: true,
                        matchContains:true,
                        cacheLength: 1,
                        formatItem: function(row, i, max) {return row.n;},
                        formatMatch: function(row, i, max) {return row.n;},
                        formatResult: function(row) {return row.n;}
                    }
                );
            }
		}
		if (this.searchtype=="departure")
		{
            if (  this.init_departure==0 )
            {
			    this.init_departure=1;
			    doinit=true;
            }
            if ( typeof(flightsdeparture) != 'undefined' )
            {
                $("#"+this.searchtype+"_flightnumber").flushCache();
                $("#"+this.searchtype+"_flightnumber").autocomplete(flightsdeparture,
                    {
                        autoFill: true,
                        cacheLength: 1,
                        matchContains:true,
                        formatItem: function(row, i, max) {return row.n;},
                        formatMatch: function(row, i, max) {return row.n;},
                        formatResult: function(row) {return row.n;}
                    }
                );
            }
		}
		if (doinit)
		{
			if ( typeof(airports) != 'undefined' )
			{
				$("#"+this.searchtype+"_location").autocomplete(airports,
				{
					autoFill: true,
					matchContains:true,
					formatItem: function(row, i, max) {return row.n + " ("+row.i+")";},
					formatMatch: function(row, i, max) {return row.n + " ("+row.i+")";},
					formatResult: function(row) {return row.n;}
				}
				);
			}

            if ( typeof(timeframes) != 'undefined' )
            {
    			$("#"+this.searchtype+"_time").autocomplete(timeframes,
					{
						autoFill: true,
						matchContains:true,
						formatItem: function(row, i, max) {return row.n;},
						formatMatch: function(row, i, max) {return row.n;},
						formatResult: function(row) {return row.i;}
					}
				);
            }
			
			$("#"+this.searchtype+"_location").result(function(event, data, formatted) 
			{
				if (data)
				{
					fVc.iata =data.i;
					fVc.flight='';
					fVc.page=1;
					$("#"+fVc.searchtype+"_flightnumber").val(fVc.text_flightnumber);
					// Direkt nach Autocomplete Suche auslösen
					fVc.search("init","true");
				}
				else
				{
					fVc.iata ='';
				}
				
			});
			
			$("#"+this.searchtype+"_flightnumber").result(function(event, data, formatted) 
			{
				if (data)
				{
					fVc.flight =data.i;
					fVc.iata='';
					fVc.page=1;
					$("#"+fVc.searchtype+"_location").val(fVc.text_airport);           
					// Direkt nach Autocomplete Suche auslösen
					fVc.search("init","true");
				}
				else
				{
					fVc.flight ='';
				}
			});
			$("#"+this.searchtype+"_time").result(function(event, data, formatted) 
			{
				if (data)
				{
					fVc.search("init","true");
				}
				else
				{
					fVc.flight ='';
				}
			});
		}
		fVc.search("init","true");
	};
	
	ViewController.prototype.initSwapValues = function ()
	{
		swapValues = [];
		$(".swap_value").each(function(i)
		{
			swapValues[i] = $(this).val();
		 	$(this).focus(function()
		 	{
		 		if ($(this).val() == swapValues[i]) 
		 		{
		 		$(this).val("");
				}
			});
		 	$(this).blur(function()
			{
				if ($.trim($(this).val()) == "") 
				{
					$(this).val(swapValues[i]);
				}
			});
		 	$(this).click(function()
					{
		 		$(this).val("");
					});
		});
	};
	
	ViewController.prototype.initPager = function ()
	{
		$(".flightsearch1 .reloadbutton").click(
		function()
		{
			fVc.search();
			return false;
		}
		);
		$(".flightsearch1 .page-browser a").click(
		function()
		{
			var cHref = $(this).attr("href");
            var pos = cHref.indexOf('#');
            if ( pos != -1)
                cHref = cHref.substring(pos);
			fVc.page = cHref.replace(/[^0-9]/g,'');

			fVc.search("usepager","true");
		}
		);
	};

	ViewController.prototype.search = function (paraname,paravalue)
	{
        var currentsearchtype = this.searchtype;
        if ( this.context==3) currentsearchtype="arrival";

		// Wenn gerade schon eine Suche gestartet wird, wird die zweite unterdrückt (z.B. bei Autocomplete+Return)
		if (this.loading || ignoreinit )
		{
			// Um bei Netzwerkhängern die Funktionalität nicht zu gefährden, wird das aber gleich wieder aufgehoben
			this.loading=false;
			return false;
		}

        this.loading=true;

		$("#current-"+currentsearchtype+"s .content-container").html(this.html_loading);

		var time = $("#"+this.searchtype+"_time").val();
        if ( !time )
        {
            if ( $('#time_out').length > 0)
                time = $("#time_out").val();
        }

        if ( $('#airlines').length > 0)
            fVc.airline = $("#airlines").val();

        if ( $('#flight_number').length > 0)
            fVc.flight = $("#flight_number").val();

        $("#page1").val(fVc.page);

        var flightval= fVc.flight?escape(fVc.flight):"";
	    var airlineval= fVc.airline?escape(fVc.airline):"";
        var timeval = time?escape(time.replace(/[^0-9:]/g,'')):"";

		var url = this.baseurl+"?" +"type="+escape(fVc.searchtype)+"&typ="+escape(fVc.typ)+"&iata="+escape(fVc.iata)+"&flight="+flightval+"&time="+timeval+"&page="+escape(fVc.page)+"&items="+escape(fVc.items)+"&context="+escape(fVc.context)+"&sprache="+escape(fVc.language)+"&airlines="+airlineval;
        if ( paraname && paravalue)
        {
            url = url + "&"+paraname+"="+escape(paravalue);
        }
        if ( this.date_out && this.date_out != '')
        {
            url = url + "&dateout="+escape(this.date_out);
        }

		// User-Sucheingabe anhängen
		url = url + "&search_location=" + escape($("#"+this.searchtype+"_location").val())+ "&search_flight=" + escape($("#"+this.searchtype+"_flightnumber").val())

		$("#current-"+currentsearchtype+"s .content-container").load(url, null ,function(responseText, textStatus, XMLHttpRequest){
			if(textStatus!="success")
			{
				$("#current-"+currentsearchtype+"s .content-container").html(fVc.html_error);
			}
			fVc.initPager();
			initdetailview();
            fVc.correctButtons();
			fVc.loading=false;
			
		});

		return false;
	};

    ViewController.prototype.correctButtons = function()
    {
        $("input.button").each(function(){
            var cssClasses = $(this).attr("class");
            var btnType = $(this).attr("type");
            var val = $(this).val();

            if ($(this).attr("type").toLowerCase() != "button") {
                cssClasses += " " + $(this).attr("type").toLowerCase();
            }

            var ff2fixstyle = ($.browser.mozilla && ($.browser.version < '1.9')) ? 'style="margin-right: -2px"' : '';

            $(this).replaceWith("<button class=\"" + cssClasses + "\" type=\"" + btnType + "\">" +
            "<span class=\"text\">" + val + "</span><span "+ ff2fixstyle  +" class=\"br\">&nbsp;</span>" +
            "</button>");                    
        });

        $("button.selectflight").click(function()
        {
            sendform=true;
        });
    };
}



var fVc;                                                          
$(document).ready(
function ()                                                                         
{
    var url = "/flugplan/suche";
    fVc = new ViewController();
    fVc.init(url,sprache);

    try
    {
        if ( typeof(initpage) != 'undefined' )
        {
            fVc.initPager();
            initdetailview();
            fVc.correctButtons();
            fVc.loading=false;

            //fVc.iata=$('#airports option:selected').val();
            fVc.date_out=$('#date_out').val();
            fVc.searchtype = $('input[name=direction]:checked').val();
        }
    } catch ( Exception ){}
});
