﻿/* Attach event for DOM ready even */
$(document).ready(function() {

    /* store initial origin data */
    
    $("input.location#destinationLocation_1").data('curOrigin', $("input.location#originLocation_1").val())

    var urlParam = encodeURI(document.getElementById('originLocation_1').value);
    $.getJSON($("#baseUrlString").attr("content") + "/DestinationJSONData.aspx", urlParam, function(data) {    
        var mergedOptions = $.extend(defaultAutocompleteOptions, { list: data });
        $("input.location[id*=estinationLocation_]").autocomplete(mergedOptions);
    });
    

    /* Datepickers */
    SetUpStandardDatePickers();
    $("#multiLegInputs input.datepicker").datepicker({ beforeShow: function() { return 4; } });

    var defaultAutocompleteOptions = {    
        list: customarray,
        timeout: 0,
        threshold: 30,
        matcher: function(typed) { return typed; },
        match: function(element, typed) { return AutocompleteMatch(element, typed); },
        insertText: function(obj) { return obj.text },
        templateText: "<li><%= pre_match %><span class='matching' ><%= matched_text %></span><%= post_match_text %></li>"
    };

    // Autocompletions
    // The defaults first
    $("input.location").autocomplete(defaultAutocompleteOptions);

    /* Event Handling for Autocomplete (show only possible destinations */
    $("input.location[id*=riginLocation_]").bind("activated.autocomplete", function() {

        // if origin hasn't changed, return
        if ($("input.location#originLocation_1").val() == $("input.location#destinationLocation_1").data('curOrigin'))
            return;

        // store new origin
        $("input.location#destinationLocation_1").data('curOrigin', $("input.location#originLocation_1").val())

        var urlParam = encodeURI(document.getElementById('originLocation_1').value);
        $.getJSON($("#baseUrlString").attr("content") + "/DestinationJSONData.aspx", urlParam, function(data) {
            var mergedOptions = $.extend(defaultAutocompleteOptions, { list: data });
            $("input.location[id^=destinationLocation_]").autocomplete(mergedOptions);
        });
    });
    $("input.location[id^=multiLegOriginLocation_]").bind("activated.autocomplete", function() {
        var relOrigin = 'multiLegOriginLocation_' + this.id.charAt(this.id.length - 1), // related Origin textbox
            selectedId = this.id;   // Destination textbox id
            destinationId = 'multiLegDestinationLocation_' + this.id.charAt(this.id.length - 1)

        // if origin hasn't changed, return
        if (document.getElementById(relOrigin).value == $('input.location[id=' + selectedId + ']').data('curOrigin'))
            return;

        // store new origin
        $('input.location[id=' + selectedId + ']').data('curOrigin', document.getElementById(relOrigin).value)

        var urlParam = encodeURI(document.getElementById(relOrigin).value);
        $.getJSON($("#baseUrlString").attr("content") + "/DestinationJSONData.aspx", urlParam, function(data) {            
            $('input.location[id=' + destinationId + ']').autocomplete($.extend(defaultAutocompleteOptions, { list: data }));
        });
    });

    /* Multi-leg rows */
    SetUpMultiLegInputs();

    /* Enable the trip type selectors */
    SetUpTripTypeSelector();

    /* Validations */
    SetUpValidations();

    /* Submit button */
    $('#find_trips').click(SubmitNewSearch);

    /* Set the trip type */
    $("#triptype_return").trigger("click");

    /* Set Colorboxes */
    
    $("#modalOrigin_1").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=originLocation_1" });
    $("#modalMultiOrigin_1").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=multiLegOriginLocation_1" });
    $("#modalMultiOrigin_2").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=multiLegOriginLocation_2" });
    $("#modalMultiOrigin_3").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=multiLegOriginLocation_3" });
    $("#modalMultiOrigin_4").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=multiLegOriginLocation_4" });
    $("#modalDestination_1").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=destinationLocation_1" });
    $("#modalMultiDestination_1").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=multiLegDestinationLocation_1" });
    $("#modalMultiDestination_2").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=multiLegDestinationLocation_2" });
    $("#modalMultiDestination_3").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=multiLegDestinationLocation_3" });
    $("#modalMultiDestination_4").colorbox({ iframe: true, width: 680, height: "80%", href: $("#baseUrlString").attr("content") + "/Portslist.aspx?type=multiLegDestinationLocation_4" });
});

function SetUpStandardDatePickers(){
/* Date format used in date <-> string conversions using the datepicker functions */
    var dateFormat = 'dd/mm/yy';

    /* 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 = 1;

        if (input.id == 'ferriesRetDate') {
            minimum = $('#ferriesDepDate').datepicker("getDate");
            minimum.setDate(minimum.getDate());
        }
        return {
            minDate: minimum
        };
    }

    /* General settings for 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,
        inline: true
    });
    
    $("#ferriesRetDate").datepicker({ 
        beforeShow: customRange,
        onSelect: function (datetext) {
            var newend = $.datepicker.parseDate(dateFormat,datetext);
        }
    });
    $("#ferriesDepDate").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 = $('#ferriesDepDate').datepicker('getDate');
            var end = $('#ferriesRetDate').datepicker('getDate');
            
            if (newstart >= end) {
                /* If you select a starting date bigger than the ending date, the ending date
                 * will be CHANGED to ferriesDepDate + 2 days */
                newstart.setDate(newstart.getDate() + 2);
                $('#ferriesRetDate').val($.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);
    
    document.getElementById('ferriesDepDate').value = $.datepicker.formatDate(dateFormat, shouldstart);
    shouldstart.setDate(shouldstart.getDate()+3);
    document.getElementById('ferriesRetDate').value = $.datepicker.formatDate(dateFormat, shouldstart);
}

function SetUpMultiLegInputs(){
    // Show the plus / minus buttons (override the css)
    $('#multiLegInputs span.addLeg').show();
    $('#multiLegInputs span.removeLeg').show();
        
    // Hide rows 3 & 4
    $('#multiLegInputs #leg_3_header').hide();
    $('#multiLegInputs #leg_3_row').hide();
    $('#multiLegInputs #leg_4_header').hide();
    $('#multiLegInputs #leg_4_row').hide();

    // Try to guess options for leg #2
    $('#multiLegInputs #leg_1_row #multiLegDestinationLocation_1').blur(function(){
        var originalOrigin = $('#multiLegInputs #leg_2_row #multiLegOriginLocation_2').val();
        var wannabeOrigin = $(this).val();
        if (originalOrigin == null || originalOrigin == ""){
            $('#multiLegInputs #leg_2_row #multiLegOriginLocation_2').val(wannabeOrigin);
            // trigger autocomplete to bind selections for destinations
            $('#multiLegInputs #leg_2_row #multiLegOriginLocation_2').trigger("activated.autocomplete");
        }
    });
    
    // Try to guess options for leg #3
    $('#multiLegInputs #leg_2_row #multiLegDestinationLocation_2').blur(function(){
        var originalOrigin = $('#multiLegInputs #leg_3_row #multiLegOriginLocation_3').val();
        var wannabeOrigin = $(this).val();
        if (originalOrigin == null || originalOrigin == ""){
            $('#multiLegInputs #leg_3_row #multiLegOriginLocation_3').val(wannabeOrigin);
            // trigger autocomplete to bind selections for destinations
            $('#multiLegInputs #leg_3_row #multiLegOriginLocation_3').trigger("activated.autocomplete");
        }
    });
    
    // Try to guess options for leg #4
    $('#multiLegInputs #leg_3_row #multiLegDestinationLocation_3').blur(function(){
        var originalOrigin = $('#multiLegInputs #leg_4_row #multiLegOriginLocation_4').val();
        var wannabeOrigin = $(this).val();
        if (originalOrigin == null || originalOrigin == ""){
            $('#multiLegInputs #leg_4_row #multiLegOriginLocation_4').val(wannabeOrigin);
            // trigger autocomplete to bind selections for destinations
            $('#multiLegInputs #leg_4_row #multiLegOriginLocation_4').trigger("activated.autocomplete");
        }
    });
    
    // Enable plus buttons
    $('#multiLegInputs #addThirdLeg').click(function(){
        $('#multiLegOriginLocation_3').removeAttr("disabled");
        $('#multiLegDestinationLocation_3').removeAttr("disabled");
        $('#multiLegDepDate_3').removeAttr("disabled");
        
        $('#multiLegInputs #addThirdLeg').hide();
        $('#multiLegInputs #leg_3_header').show();
        $('#multiLegInputs #leg_3_row').show();
        
        $('#multiLegInputs #leg_3_row #multiLegOriginLocation_3').val($('#multiLegInputs #leg_2_row #multiLegDestinationLocation_2').val());
    });
    $('#multiLegInputs #addForthLeg').click(function(){
        $('#multiLegOriginLocation_4').removeAttr("disabled");
        $('#multiLegDestinationLocation_4').removeAttr("disabled");
        $('#multiLegDepDate_4').removeAttr("disabled");
        
        $('#multiLegInputs #addForthLeg').hide();
        $('#multiLegInputs #removeThirdLeg').hide();
        $('#multiLegInputs #leg_4_header').show();
        $('#multiLegInputs #leg_4_row').show();
        $('#multiLegInputs #leg_4_row #multiLegOriginLocation_4').val($('#multiLegInputs #leg_3_row #multiLegDestinationLocation_3').val());
    });

    // Enable minus buttons
    $('#multiLegInputs #removeThirdLeg').click(function(){
        $('#multiLegOriginLocation_3').attr("disabled",true);
        $('#multiLegDestinationLocation_3').attr("disabled",true);
        $('#multiLegDepDate_3').attr("disabled",true);
        
        $('#multiLegInputs #addThirdLeg').show();
        $('#multiLegInputs #leg_3_header').hide();
        $('#multiLegInputs #leg_3_row').hide();
        $('#multiLegInputs #leg_3_row input').each(function(){
            $(this).val(null);
        });
    });
    $('#multiLegInputs #removeForthLeg').click(function(){
        $('#multiLegOriginLocation_4').attr("disabled",true);
        $('#multiLegDestinationLocation_4').attr("disabled",true);
        $('#multiLegDepDate_4').attr("disabled",true);
        
        $('#multiLegInputs #addForthLeg').show();
        $('#multiLegInputs #removeThirdLeg').show();
        $('#multiLegInputs #leg_4_header').hide();
        $('#multiLegInputs #leg_4_row').hide();
        $('#multiLegInputs #leg_4_row input').each(function(){
            $(this).val(null);
        });
    });

    // Store Origin Data for multiLeg
    $("input.location[id^=multiLegDestinationLocation_]").data('curOrigin', "");
}

function SetUpTripTypeSelector(){
    // One way
    $('#triptype_oneway').click(function(){
	    $('#multiLegInputs').hide();
	    $('#simpleTripInputs').show();
	    
	    $('#originLocation_1').removeAttr("disabled");
	    $('#destinationLocation_1').removeAttr("disabled");
	    
	    $('#ferriesDepDate').datepicker("enable");
	    $('#ferriesRetDate').datepicker("disable");
	    
	    $('#multiLegInputs input').attr("disabled", "disabled");
    });
    
    // Round-trip
	$('#triptype_return').click(function(){
	    $('#multiLegInputs').hide();
	    $('#simpleTripInputs').show();
	    
	    $('#simpleTripInputs input').removeAttr("disabled");
	    $('#multiLegInputs input').attr("disabled", "disabled");
	    
	    $('#ferriesDepDate').datepicker("enable");
		$('#ferriesRetDate').datepicker("enable");
	});
	
	// Multi-leg
	$('#triptype_multileg').click(function(){
	    $('#multiLegInputs').show();
	    $('#simpleTripInputs').hide();
	    
	    $('#multiLegInputs input').removeAttr("disabled");
	    $('#simpleTripInputs input').attr("disabled", "disabled");
	    
	    $('#multiLegOriginLocation_3').attr("disabled",true);
        $('#multiLegDestinationLocation_3').attr("disabled",true);
        $('#multiLegDepDate_3').attr("disabled",true);
        $('#multiLegOriginLocation_4').attr("disabled",true);
        $('#multiLegDestinationLocation_4').attr("disabled",true);
        $('#multiLegDepDate_4').attr("disabled",true);
	    
	    $('#ferriesDepDate').datepicker("disable");
		$('#ferriesRetDate').datepicker("disable");
	});
}

function SetUpValidations(){
    var orginRequiredMessage = $('#origin_required').text();
    var destinationRequiredMessage = $('#destination_required').text();
    var departureDateRequiredMessage = $('#dep_date_required').text();
    var returnDateRequiredMessage = $('#ret_date_required').text();
    
    $("#SearchFerriesForm").validate({
        //set the rules for the field names
        rules: {
            originLocation: {
                required: true,
                minlength: 3
            },
            destinationLocation: {
                required: true,
                minlength: 3
            },
            ferriesDepDate: {
                required: true,
                minlength: 8
            },
            ferriesRetDate: {
                required: true,
                minlength: 8
            }
        },
        onkeyup: false,
        //set messages to appear inline
        messages: {
            originLocation: orginRequiredMessage,
            destinationLocation: destinationRequiredMessage,
            ferriesDepDate: departureDateRequiredMessage,
            ferriesRetDate: returnDateRequiredMessage
        },
        errorContainer: "#ErrorMessages",
        errorLabelContainer: "#ErrorMessages ul",
        wrapper: "li",
        onkeyup: false,
        onfocusout: false,
        highlight: function(element, errorClass) {
            $(element).fadeOut(function() {
                $(element).addClass("invalid_input").fadeIn();
            });
        },
        unhighlight: function(element, errorClass) {
            $(element).removeClass("invalid_input");
        }
    });
    
    // Same for HomeSearchFerriesForm
    $("#HomeSearchFerriesForm").validate({
        //set the rules for the field names
        rules: {
            originLocation: {
                required: true,
                minlength: 3
            },
            destinationLocation: {
                required: true,
                minlength: 3
            },
            ferriesDepDate: {
                required: true,
                minlength: 8
            },
            ferriesRetDate: {
                required: true,
                minlength: 8
            }
        },
        onkeyup: false,
        //set messages to appear inline
        messages: {
            originLocation: orginRequiredMessage,
            destinationLocation: destinationRequiredMessage,
            ferriesDepDate: departureDateRequiredMessage,
            ferriesRetDate: returnDateRequiredMessage
        },
        errorContainer: "#ErrorMessages",
        errorLabelContainer: "#ErrorMessages ul",
        wrapper: "li",
        onkeyup: false,
        onfocusout: false,
        highlight: function(element, errorClass) {
            $(element).fadeOut(function() {
                $(element).addClass("invalid_input").fadeIn();
            });
        },
        unhighlight: function(element, errorClass) {
            $(element).removeClass("invalid_input");
        }
    });
}

function SubmitNewSearch() {
    if( $('#triptype_return').attr("checked") == true ) {
        $('#originLocation_2').val($('#destinationLocation_1').val())
        $('#destinationLocation_2').val($('#originLocation_1').val())
    }
    
    // submit whichever of the two forms is present
	$('#SearchFerriesForm').submit();
	$('#HomeSearchFerriesForm').submit();
}

function AutocompleteMatch(element, typed) {
    element.typed = ferries.utils.removeAccents(typed).toLowerCase();
	element.pre_match = element.text;
	element.matched_text = element.post_match_text = '';

	if (!element.ajax && !element.typed || element.typed.length == 0) { return true; }
	var match_at = ferries.utils.removeAccents(element.text).toLowerCase().search(new RegExp(element.typed, "i"));
	if (match_at != -1) {
		element.pre_match = element.text.slice(0, match_at);
		element.matched_text = element.text.slice(match_at, match_at + element.typed.length);
		element.post_match_text = element.text.slice(match_at + element.typed.length);
		return true;
	}
	else {
		for (var aliasIndex = 0; aliasIndex < element.alias.length; aliasIndex++) {
			var alias = element.alias[aliasIndex];
			var alias_match_at = ferries.utils.removeAccents(alias).toLowerCase().search(new RegExp(element.typed, "i"));
			if (alias_match_at != -1) {
				element.pre_match = element.text.slice(0, alias_match_at);
				element.matched_text = element.text.slice(alias_match_at, alias_match_at + element.typed.length);
				element.post_match_text = element.text.slice(alias_match_at + element.typed.length);
				return true;
			}
		}
	}
	return false;
}
