//Opens popup window with airport list
function OpenAirportPopUpWindow(type, lang)
{
	if (type=="from")
		window.open("http://www.pamediakopes.gr/dreamflight/AirportsList.aspx?type=from&lang="+lang,null,"width=712,height=600,status=no,toolbar=no,scrollbars=yes");
	else if (type=="to")	
		window.open("http://www.pamediakopes.gr/dreamflight/AirportsList.aspx?type=to&lang="+lang,null,"width=712,height=600,status=no,toolbar=no,scrollbars=yes");
}


function CheckAllValidations() {
	var isValid = true;
	if($('#from').val().length < 3) {
		isValid = false;
	}
	if($('#to').val().length < 3) {
		isValid = false;
	}
	if($('#from').val().toLowerCase() == $('#to').val().toLowerCase()) {
		isValid = false;		
	}
	if(parseInt($('#adults').val(),10) + parseInt($('#children').val(),10) + parseInt($('#infants').val(),10) > 8) {
		isValid = false;		
	}
	if(parseInt($('#adults').val(),10) < parseInt($('#infants').val(),10)) {
		isValid = false;		
	}

	return isValid;
}


function SubmitNewSearchFlightsHomePage() {
	if(CheckAllValidations()) {
		
	    	var tmpDepDate   = $('#depDate').val().split("/");
    		var depDay   = tmpDepDate[0];
	    	var depMonth = tmpDepDate[1];
    		var depYear  = tmpDepDate[2];
		$('#completeDepDate').val(depYear + '-' + depMonth + '-' + depDay);
		
		var tmpRetDate   = $('#retDate').val().split("/");
    		var retDay   = tmpRetDate[0];
	    	var retMonth = tmpRetDate[1];
    		var retYear  = tmpRetDate[2];
		$('#completeRetDate').val(retYear + '-' + retMonth + '-' + retDay);

		//Hack Netvolution submit page
		$('#__VIEWSTATE').remove();
		$('#NetvolutionPage').attr("method","get"); 
		$('#SearchFlightForm').attr("method","get"); 
		var pathname = location.pathname;
		pathname = pathname.toLowerCase();
		var action = $('#SearchFlightForm').attr("action");
		action = action.toLowerCase();
		if(pathname.match("dreamflightstage")) {
			action = action.replace("dreamflight","dreamflightstage");
			$('#SearchFlightForm').attr("action",action ); 
		}

		//Set aid if aid was passed as a param in the url
		var aidValue = $(document).getUrlParam("aid");  
		try {
			var aidInt = parseInt(aidValue,10);
			if(aidInt > 0) {
				$('#aid').val(aidValue);		
			}
		}
		catch (err) {}
		
		//$('#NetvolutionPage').attr("action",$('#SearchFlightForm').attr("action")); 	
		//$('#NetvolutionPage').submit();
		$('#SearchFlightForm').submit();
		
	}
}


function init() {
    /* Date format used in date <-> string conversions using the datepicker functions */
    var dateFormat = 'dd/mm/yy',
        /* data from the flightsearchform cookie. This stores the date and place selections */
        cookieDataRaw = $.cookie("flightsearchform"),
        /* Parsed cookie data */
        cookieData,
        /* Splitted cookie data */
        expandedCookie;
    
    /* Set Defauls for radio button */
	$("#flighttype_1").attr("checked", "checked"); 
	
    /* Function: customRange
     * Description: Link the start and end date fields on both calendars.
     *   When you select a starting date. The ending date has to be bigger than it.
    */
    function customRange(input) {
        var minimum = 0;

        if (input.id == 'retDate') {
            minimum = $('#depDate').datepicker("getDate");
            minimum.setDate(minimum.getDate());
        }
        return {
            minDate: minimum
        };
    }
     
     /* If we have a cookie with previous data, we recover it */
     
     if (typeof(cookieDataRaw) == "string") {
        expandedCookie = cookieDataRaw.split("\t");
        cookieData = {
            place: expandedCookie[0],
            start: expandedCookie[1],
            end: expandedCookie[2]
            };
     }
        
    /* Configures the datepicker */    
    $.datepicker.setDefaults({ 
        dateFormat: dateFormat, 
        numberOfMonths: 2,
        mandatory: true,
        minDate:0,
        firstDay: 1, 
        changeFirstDay: false, 
        showOn: "both", 
        buttonImage: "http://www.pamediakopes.gr/homepageassets/theme/images/calendar.gif",
        buttonImageOnly: true
    });      
    $("#retDate").datepicker({ 
        beforeShow: customRange,
        onSelect: function (datetext) {
            var newend = $.datepicker.parseDate(dateFormat,datetext);
        }

    });
    $("#depDate").datepicker({
        beforeShow: customRange,
        /* This will make the ending date as bigger as the starting date if the starting
        date changs */
        onSelect: function(datetext,datebox) {
            
            var newstart = $('#depDate').datepicker('getDate');
            var end = $('#retDate').datepicker('getDate');
            
            if (newstart >= end) {
                /* If you select a starting date bigger than the ending date, the ending date
                 * will be CHANGED to depDate + 3 days */
                newstart.setDate(newstart.getDate()+3);
                document.getElementById('retDate').value = $.datepicker.formatDate(dateFormat, newstart);
            }
        }
    });
    
    /* Start with today + 1 week, and end 3 days after */
    var today = new Date();
    var shouldstart = new Date();
    shouldstart.setDate(today.getDate() +7);
    
    /* Let's validate the stored dates from the cookies. 
     * previous date: this date was stored in the cookie and has been recovered.
     * proposed date: default initialization date.
     *
     * It can hapen that even if we have a date, this date is older than the default initial date.
     * In this case, even if we have a previous date, we choose the proposed date
     */
    function shouldIUseTheCookie(previous,proposed) {
        if(previous && $.datepicker.parseDate(dateFormat,previous) > proposed) return true;
        return false;
    }
    
    /* If we have previous data, we use it, if not, we get todays date */
    var usecookie = false;
    if (cookieData)
        usecookie = shouldIUseTheCookie(cookieData.start, today);
    
    document.getElementById('depDate').value = (usecookie) ? cookieData.start : $.datepicker.formatDate(dateFormat, shouldstart);
    shouldstart.setDate(shouldstart.getDate()+3);
    document.getElementById('retDate').value = (usecookie) ? cookieData.end : $.datepicker.formatDate(dateFormat, shouldstart);
    
	// Datepicker
	$('#depDate').datepicker({inline: true});
	$('#retDate').datepicker({inline: true});

	//Enable Return Datepicker if the flighttype_1 radio button is clicked  
	$('#flighttype_1').bind(
		'click',
		function()
		{
			$('#retDate').datepicker("enable");
			$('#timeRet').removeAttr("disabled", "disabled");
		}
	);
	
	//Disable Return Datepicker if the flighttype_2 radio button is clicked  
	$('#flighttype_2').bind(
		'click',
		function()
		{
			$('#retDate').datepicker("disable");
			$('#timeRet').attr("disabled", "disabled");
		}
	);

	$('.link_red_airport').hover(
		function() {
        	$(this).addClass('cursor-hand');
      	},
		function() {
	        $(this).removeClass('cursor-hand');
		}
	);
	
	//Validations and Error messages start here!
	
	//Check airport textboxes for error
	$('#from').blur(function(){
		if($('#from').val().length < 3) {		
			$("#error-from-is-empty").show();
		}
		else {
			$("#error-from-is-empty").hide();
		}
	}); 
	
	$('#to').blur(function(){
		if($('#to').val().length < 3) {		
			$("#error-to-is-empty").show();
		}
		else {
			$("#error-to-is-empty").hide();
		}
		
		if($('#from').val().toLowerCase() == $('#to').val().toLowerCase()) {		
			$("#error-from-and-to-are-the-same").show();
		}
		else {
			$("#error-from-and-to-are-the-same").hide();
		}
	}); 
	
	//Check total number of passengers is 8 or less
	$('#adults, #children, #infants').blur(function(){
		if(parseInt($('#adults').val(),10) + parseInt($('#children').val(),10) + parseInt($('#infants').val(),10) > 8) {	
			$("#error-too-many-passengers").show();
		}
		else {
			$("#error-too-many-passengers").hide();
		}
	}); 

	//Check the number of infants is not more than the number of adults
	$('#infants').blur(function(){
		if(parseInt($('#adults').val(),10) < parseInt($('#infants').val(),10)) {	
			$("#error-too-many-infants-for-adults").show();
		}
		else {
			$("#error-too-many-infants-for-adults").hide();
		}
	}); 

	$('#findFlight').bind(
		'click',
		SubmitNewSearchFlightsHomePage
	);

	//show links after thickbox related stuff has loaded

	$('#airport-select-from-link').css('display','inline');
	$('#airport-select-to-link').css('display','inline');


}


/* Attach event for DOM ready even */
$(document).ready(function(){
	init();
});