var validRoute = Array();
var stations = Array();
stations[0] = 'Wrexham General';
stations[1] = 'Ruabon';
stations[2] = 'Chirk';
stations[3] = 'Gobowen';
stations[4] = 'Shrewsbury';
stations[5] = 'Wellington';
stations[6] = 'Telford';
stations[7] = 'Cosford';
stations[8] = 'Tame Bridge Parkway';
stations[11] = 'Leamington Spa';
stations[10] = 'Banbury';
stations[9] = 'London Marylebone';
validRoute[0] = Array();
validRoute[0][0] = '9';
validRoute[0][1] = '10';
validRoute[0][2] = '11';
validRoute[0][3] = '';
validRoute[1] = Array();
validRoute[1][0] = '9';
validRoute[1][1] = '10';
validRoute[1][2] = '11';
validRoute[1][3] = '';
validRoute[2] = Array();
validRoute[2][0] = '9';
validRoute[2][1] = '10';
validRoute[2][2] = '11';
validRoute[2][3] = '';
validRoute[3] = Array();
validRoute[3][0] = '9';
validRoute[3][1] = '10';
validRoute[3][2] = '11';
validRoute[3][3] = '';
validRoute[4] = Array();
validRoute[4][0] = '9';
validRoute[4][1] = '10';
validRoute[4][2] = '11';
validRoute[4][3] = '';
validRoute[5] = Array();
validRoute[5][0] = '9';
validRoute[5][1] = '10';
validRoute[5][2] = '11';
validRoute[5][3] = '';
validRoute[6] = Array();
validRoute[6][0] = '9';
validRoute[6][1] = '10';
validRoute[6][2] = '11';
validRoute[6][3] = '';
validRoute[7] = Array();
validRoute[7][0] = '9';
validRoute[7][1] = '10';
validRoute[7][2] = '11';
validRoute[7][3] = '';
validRoute[8] = Array();
validRoute[8][0] = '9';
validRoute[8][1] = '10';
validRoute[8][2] = '11';
validRoute[8][3] = '';
validRoute[11] = Array();
validRoute[11][0] = '0';
validRoute[11][1] = '0';
validRoute[11][2] = '1';
validRoute[11][3] = '1';
validRoute[11][4] = '2';
validRoute[11][5] = '2';
validRoute[11][6] = '3';
validRoute[11][7] = '3';
validRoute[11][8] = '4';
validRoute[11][9] = '4';
validRoute[11][10] = '5';
validRoute[11][11] = '5';
validRoute[11][12] = '6';
validRoute[11][13] = '6';
validRoute[11][14] = '7';
validRoute[11][15] = '7';
validRoute[11][16] = '8';
validRoute[11][17] = '8';
validRoute[10] = Array();
validRoute[10][0] = '0';
validRoute[10][1] = '1';
validRoute[10][2] = '2';
validRoute[10][3] = '3';
validRoute[10][4] = '4';
validRoute[10][5] = '5';
validRoute[10][6] = '6';
validRoute[10][7] = '7';
validRoute[10][8] = '8';
validRoute[9] = Array();
validRoute[9][0] = '0';
validRoute[9][1] = '1';
validRoute[9][2] = '2';
validRoute[9][3] = '3';
validRoute[9][4] = '4';
validRoute[9][5] = '5';
validRoute[9][6] = '6';
validRoute[9][7] = '7';
validRoute[9][8] = '8';
var disabledDates = ["07-09-2010","08-09-2010","09-09-2010","10-09-2010","11-09-2010","12-09-2010","13-09-2010","14-09-2010","15-09-2010","16-09-2010","17-09-2010","18-09-2010","19-09-2010","20-09-2010","21-09-2010","22-09-2010","23-09-2010","24-09-2010","25-09-2010","26-09-2010","27-09-2010","28-09-2010","29-09-2010","30-09-2010","01-10-2010","02-10-2010","03-10-2010","04-10-2010","05-10-2010","06-10-2010","07-10-2010","08-10-2010","09-10-2010","10-10-2010","11-10-2010","12-10-2010","13-10-2010","14-10-2010","15-10-2010","16-10-2010","17-10-2010","18-10-2010","19-10-2010","20-10-2010","21-10-2010","22-10-2010","23-10-2010","24-10-2010","25-10-2010","26-10-2010","27-10-2010","28-10-2010","29-10-2010","30-10-2010","31-10-2010","01-11-2010","02-11-2010","03-11-2010","04-11-2010","05-11-2010","06-11-2010","07-11-2010","08-11-2010","09-11-2010","10-11-2010","11-11-2010","12-11-2010","13-11-2010","14-11-2010","15-11-2010","16-11-2010","17-11-2010","18-11-2010","19-11-2010","20-11-2010","21-11-2010","22-11-2010","23-11-2010","24-11-2010","25-11-2010","26-11-2010","27-11-2010","28-11-2010","29-11-2010"];
var lastDay;
var lastMonth;
var day;
var month;
var dayArr = Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
$(document).bind("ready", function() {
    // initialise the "Select date" link    
    lastDay = latestDate.getDate();
    if (lastDay < 10) {
        lastDay = '0'+lastDay;
    }
    lastMonth = latestDate.getMonth() + 1;
    if (lastMonth < 10) {
        lastMonth = '0'+lastMonth;
    }
    day = earliestDay.getDate();
    if (day < 10) {
        day = '0'+day;
    }
    month = earliestDay.getMonth() + 1;
    if (month < 10) {
        month = '0'+month;
    }
    $('#outDatePick')
        .datePicker(
            // associate the link with a date picker
            {
                createButton:false,
                startDate: day+'/'+month+'/'+earliestDay.getFullYear(),
                endDate: lastDay+'/'+lastMonth+'/'+latestDate.getFullYear()
            }
        ).bind(
            // when the link is clicked display the date picker
            'click',
            function()
            {
                $(this).dpDisplay();
                return false;
            }
        ).bind(
            // when a date is selected update the SELECTs
            'dateSelected',
            function(e, selectedDate, $td, state)
            {
                updateOutSelects(selectedDate);
                $('#outDatePick').dpSetSelected(selectedDate.asString());
            }
        ).bind(
            'dpClosed',
            function(e, selected)
            {
                updateOutSelects(selected[0]);
                
                if ($('#returnDatePick').dpGetSelected() < $('#outDatePick').dpGetSelected()) {
                    var d = new Date(selected[0]);
                    d.addDays(1);
                    $('#returnDatePick').dpSetSelected(d.asString());
                    updateReturnSelects(d);
                }
            }
        );
        
    var updateOutSelects = function (selectedDate)
    {
        selectedDate = new Date(selectedDate);
        var d = selectedDate.getDate();
        var m = selectedDate.getMonth();
        var y = selectedDate.getFullYear();
        ($('#outDay')[0]).selectedIndex = d - 1;
        ($('#outMonth')[0]).selectedIndex = m;
        $('#outYear').val(y);
        $('#outDow').text(dayArr[selectedDate.getDay()]);
    }
    // listen for when the selects are changed and update the picker
    $('#outDay, #outMonth')
        .bind(
            'change',
            function()
            {
                $('#errors').remove();
                $('#outDate').removeClass("red");
                var d = new Date(
                            $('#outYear').val(),
                            $('#outMonth').val()-1,
                            $('#outDay').val()
                        );
                //if (d.getDayOfYear() >= earliestDay.getDayOfYear()) {
                    $('#outDatePick').dpSetSelected(d.asString());  
                    var outDate = new Date();
                    outDate.setFullYear($('#outYear').val(),($('#outMonth').val()-1),$('#outDay').val());
                    $('#outDow').text(dayArr[outDate.getDay()]);

                    if ($('#returnDatePick').dpGetSelected() < $('#outDatePick').dpGetSelected()) {
                        d.addDays(1);
                        $('#returnDatePick').dpSetSelected(d.asString());
                        updateReturnSelects(d);
                    }
                /*} else {
                    var errorText = '<div id="errors">'+
                            '<div class="header">Sorry</div>'+
                            '<div class="contents">'+
                                '<strong>The following errors occured whilst trying to process your request:</strong>'+
                                '<br />'+
                                '<br />' +
                                'You can\'t select this date. The earliest you can travel is '+day+'/'+month+'/'+earliestDay.getFullYear()+'</div>'+
                                    '</div>';

                    $('#stage1Form').before(errorText);
                    $('#outDate').addClass("red");
                    window.scroll(0, 0);
                    updateOutSelects($('#outDatePick').dpGetSelected()[0]);

                    setTimeout("clearErrors()", 5000 );
                }*/
            }
        );
    
    $('#returnDatePick')
        .datePicker(
            // associate the link with a date picker
            {
                createButton:false,
                startDate: day+'/'+month+'/'+earliestDay.getFullYear(),
                endDate: lastDay+'/'+lastMonth+'/'+latestDate.getFullYear()
            }
        ).bind(
            // when the link is clicked display the date picker
            'click',
            function()
            {
                $(this).dpDisplay();
                return false;
            }
        ).bind(
            // when a date is selected update the SELECTs
            'dateSelected',
            function(e, selectedDate, $td, state)
            {
                updateReturnSelects(selectedDate);
                $('#returnDatePick').dpSetSelected(selectedDate.asString());
            }
        ).bind(
            'dpClosed',
            function(e, selected)
            {
                updateReturnSelects(selected[0]);

                if ($('#returnDatePick').dpGetSelected() < $('#outDatePick').dpGetSelected()) {
                    var d = new Date(selected[0]);
                    $('#outDatePick').dpSetSelected(d.asString());
                    updateOutSelects(selected[0]);
                }
            }
        );
        
    var updateReturnSelects = function (selectedDate)
    {
        selectedDate = new Date(selectedDate);
        var d = selectedDate.getDate();
        var m = selectedDate.getMonth();
        var y = selectedDate.getFullYear();

        ($('#returnDay')[0]).selectedIndex = d;
        ($('#returnMonth')[0]).selectedIndex = m + 1;
        $('#returnYear').val(y);
        $('#returnDow').text(dayArr[selectedDate.getDay()]);
    }
    // listen for when the selects are changed and update the picker
    $('#returnDay, #returnMonth')
        .bind(
            'change',
            function()
            { 
                if (($('#returnDay').val() == "" || $('#returnMonth').val() == "") && (($(this)).val() == "")) {
                    ($('#returnDay')[0]).selectedIndex = 0;
                    ($('#returnMonth')[0]).selectedIndex = 0;
                    $('#returnDow').text("-");
                    $('#returnYear').val("");
                } else {
                    if ($('#returnDay').val() == "" && this.id != 'returnDay' && $(this).val() != "") {
                        ($('#returnDay')[0]).selectedIndex = ($('#outDay')[0]).selectedIndex + 1;
                    } else if ($('#returnMonth').val() == "" && this.id != 'returnMonth' && $(this).val() != "") {
                        ($('#returnMonth')[0]).selectedIndex = ($('#outMonth')[0]).selectedIndex + 1;
                    }

                    $('#errors').remove();
                    $('#returnDate').removeClass("red");
                    var d = new Date(
                                $('#returnYear').val(),
                                $('#returnMonth').val()-1,
                                $('#returnDay').val()
                            );
                    
                    $('#returnDatePick').dpSetSelected(d.asString());  
                    $('#returnDow').text(dayArr[d.getDay()]);
                    $('#returnYear').val($('#outYear').val());
                }
            }
        );
    if ($('#single').attr("checked") == true) {
        $('#returnJourney').hide();
    }
    
    $('#outDatePick').dpSetSelected($('#outDay').val()+"/"+$('#outMonth').val()+"/"+$('#outYear').val());

    var outDate = new Date();
    outDate.setFullYear($('#outYear').val(),($('#outMonth').val()-1),$('#outDay').val());
    $('#outDow').text(dayArr[outDate.getDay()]);
    if ($('#returnMonth').val() != "") {
        var returnDate = new Date();
        returnDate.setFullYear($('#returnYear').val(),($('#returnMonth').val()-1),$('#returnDay').val());
        $('#returnDow').text(dayArr[returnDate.getDay()]);
        $('#returnDatePick').dpSetSelected($('#returnDay').val()+"/"+$('#returnMonth').val()+"/"+$('#returnYear').val());
    } else {
        $('#returnDow').text("-");
    }
});

function clearErrors() {
    $('.error').removeClass("error");
    $('.errorMessage').html("");
    $('.errorMessage').addClass("hidden");
}

function validateStage1() {
    // remove any old error messages
    clearErrors();
    var errorCount = 0;
    var error = new Array();
    
    // validate dates
    if (parseInt($('#outYear').val()+$('#outMonth').val()+$('#outDay').val()) < parseInt(earliestDay.getFullYear()+month+day)) {
        $('#outDate').parent("fieldset").addClass("error");
        $('#outDate').addClass("error");
        $('#dateError').html("You cannot select a journey date in the past.");
        $('#dateError').removeClass("hidden");
        errorCount++;
    }

    if (parseInt($('#outYear').val()+$('#outMonth').val()+$('#outDay').val()) > parseInt(""+latestDate.getFullYear()+lastMonth+lastDay)) {
        $('#outDate').parent("fieldset").addClass("error");
        $('#outDate').addClass("error");
        $('#dateError').html("You cannot select a journey date that far in the future.");
        $('#dateError').removeClass("hidden");
        errorCount++;
    }

    if ($('#return:checked').length == 1 && ($('#returnYear').val()+$('#returnMonth').val()+$('#returnDay').val() > 0)) {
        if ($('#returnYear').val()+$('#returnMonth').val()+$('#returnDay').val() < $('#outYear').val()+$('#outMonth').val()+$('#outDay').val()) {
            $('#outDate').parent("fieldset").addClass("error");
            $('#returnDate').addClass("error");
            $('#dateError').html("You cannot select a return date before your departure date.");
            $('#dateError').removeClass("hidden");
            errorCount++;
        }

        if ($('#returnYear').val()+$('#returnMonth').val()+$('#returnDay').val() > latestDate.getFullYear().toString()+lastMonth.toString()+lastDay.toString()) {
            
            alert($('#returnYear').val()+$('#returnMonth').val()+$('#returnDay').val());
            alert(latestDate.getFullYear()+lastMonth+lastDay);
            
            $('#outDate').parent("fieldset").addClass("error");
            $('#returnDate').addClass("error");
            $('#dateError').html("You cannot select a journey date that far in the future, please try an open return instead.");
            $('#dateError').removeClass("hidden");
            errorCount++;
        }
    }

    // validate number of passengers
    if ($('#adults').val() == 0 && $('#children').val() == 0) {
        $('label[for="adults"]').parent("fieldset").addClass("error");
        $('label[for="adults"]').addClass("error");
        $('label[for="children"]').addClass("error");
        $('#passengerError').html("Please select at least one passenger to travel");
        $('#passengerError').removeClass("hidden");
        errorCount++;
    }

    if ((parseInt($('#adults').val()) + parseInt($('#children').val())) > 6) {
        $('label[for="adults"]').parent("fieldset").addClass("error");
        $('label[for="adults"]').addClass("error");
        $('label[for="children"]').addClass("error");
        $('#passengerError').html("Please select 6 passengers or less to travel");
        $('#passengerError').removeClass("hidden");
        errorCount++;
    }

    if ((parseInt($('#adults').val()) + parseInt($('#children').val())) < parseInt($('#numRailcards').val())) {
        $('label[for="railcard"]').parent("fieldset").addClass("error");
        $('label[for="railcard"]').addClass("error");
        $('label[for="numRailcards"]').addClass("error");
        $('#railcardError').html("You can't travel with more railcards than passengers.");
        $('#railcardError').removeClass("hidden");
        errorCount++;
    }

    if (parseInt($('#numRailcards').val()) > 0 && jQuery.trim($('#railcard').val()) == "") {
        $('label[for="railcard"]').parent("fieldset").addClass("error");
        $('label[for="railcard"]').addClass("error");
        $('label[for="numRailcards"]').addClass("error");
        $('#railcardError').html("Please select a railcard to travel with.");
        $('#railcardError').removeClass("hidden");
        errorCount++;
    }

    if ((parseInt($('#numRailcards').val()) == 0) && (jQuery.trim($('#railcard').val()) != "")) {
        $('label[for="numRailcards"]').parent("fieldset").addClass("error");
        $('label[for="numRailcards"]').addClass("error");
        $('label[for="numRailcards"]').addClass("error");
        $('#railcardError').html("Please select the number of railcards to travel with.");
        $('#railcardError').removeClass("hidden");
        errorCount++;
    }

    if (errorCount > 0) { 

        rounded();      
        return false;
    } else {
        return true;
    }
}

function hideReturn() {
    $('div#returnJourney').slideUp("fast");
}

function showReturn() {
    $('div#returnJourney').slideDown("fast");
}
$("#from").change(function() {
    $("body").focus();
    var oldTo = $("#to").val();
	var fromTo = $('#from').val();

    var optionString = '';
    for(var i = 0; i < validRoute[fromTo].length; i++) {
        if (validRoute[fromTo][i] != "") {
            if (oldTo == validRoute[fromTo][i]) {
                optionString += '<option selected="selected" value="'+validRoute[fromTo][i]+'">'+stations[validRoute[fromTo][i]]+'</option>';
            }
            else {
                optionString += '<option value="'+validRoute[fromTo][i]+'">'+stations[validRoute[fromTo][i]]+'</option>';
            }
        }
    }
    $('#to').html(optionString);
});
$("#to").change(function() {
    $("body").focus();
    var oldTo = $("#to").val();
	var fromTo = $('#from').val();

    var optionString = '';
    for(var i = 0; i < validRoute[fromTo].length; i++) {
        if (validRoute[fromTo][i] != "") {
            if (oldTo == validRoute[fromTo][i]) {
                optionString += '<option selected="selected" value="'+validRoute[fromTo][i]+'">'+stations[validRoute[fromTo][i]]+'</option>';
            }
            else {
                optionString += '<option value="'+validRoute[fromTo][i]+'">'+stations[validRoute[fromTo][i]]+'</option>';
            }
        }
    }
    $('#to').html(optionString);
});