var StationList;
var acSelect;
$(document).ready(function(){
    $('#schedule_search').trigger('reset');
    $.ajax({
        async : false,
        cache: false,
        dataType: "json",
        url : "/ajax/stations/",
        success: function(resp){
            StationList = resp;
        }
    });
   
    $('#station1txt,#station2txt').autocomplete({
        minLength: 1,
        autoFocus: true,
        source: function(request,response) {
            var blankSearch = false;
            var stations = StationList['all'];
            var term = $.trim(request.term).replace(/[^A-Za-z0-9 ]/g," ");
            var termSplit = $.trim(term).toUpperCase().split(/\s+/);
            if(termSplit.length > 0){
                var foundIt = -1;
                for(i in StationList){
                    foundIt = $.inArray(i,termSplit);
                    if(foundIt != -1){
                        stations = StationList[i];
                        termSplit.splice(foundIt, 1);
                        blankSearch = true;
                        break;
                    }
                }
            }
            var searchTerm = $.trim(termSplit.join(" "));
            var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(searchTerm),"i");
            response($.grep( stations, function( value ) {
                value = value.stationname;
                return matcher.test(value) || (blankSearch && searchTerm == "");
            }));
        },
        create: function(event,ui) {
            $('.ui-autcomplete').css({
                "z-index" : "12"
            });
        },
        select:  function(ev,ui){
            $targ = $(this).attr('rel');
            $other = $(this).attr('rel')
            SetStation(ui,$targ);
            acSelect = true;
        },
        close : function(ev,ui){
            $targ = $(this).attr('rel');
            if(ev.originalEvent != undefined && ev.originalEvent.type == "blur"){
                $(this).val("");
                SetStation(null,$targ);
            }
        }
    }).blur(function(){
        $targ = $(this).attr('rel'); 
        if($(this).val() == "")
            SetStation(null,$targ);
    }).click(function(){
        $(this).select();
    }).keypress(function(e){
        if (e.keyCode === 13 && !acSelect){
            $('#schedule_search').submit();
        }else
            acSelect = false;
    });

    $('#station1txt').data("autocomplete")._renderItem = fancyDD;
    $('#station2txt').data("autocomplete")._renderItem = fancyDD;
        
    function fancyDD( ul, item ) {
        return $("<li></li>")
        .data( "item.autocomplete", item )
        .append(item.logo != "" ? $("<img />").prop('src',item.logo).css({
            'float':'right',
            'margin-top':'8px'
        }) : "" )
        .append( "<a>" + item.stationname + "<br>" + item.carrier + "</a>" )
        .appendTo( ul );
    };
    $dateMax = new Date();
    $dateMax.setDate($dateMax.getDate() + 10);
    $('#searchdate').datepicker({
        dateFormat : "mm-dd-yy",
        minDate:  new Date(),
        maxDate:  $dateMax,
        hideIfNoPrevNext : true,
        constrainInput : true
    });
    
    $('#searchtime').focus(function(){
        $('#searchcont').show();
        $('#searchtime').select();
        return false;
    }).click(function(){
        $(this).focus();
        return false;
    });
    

    $('#schedule_search input:not("#searchtime")').focus(function(){
        $('#searchcont').hide(500);
    });
     
    $(document).click(function(ev){
        if($(ev.target).attr('id') != "searchcont" && $(ev.target).closest('#searchcont').length < 1 && $(ev.target).attr('id') != "searchtime"){
            $('#searchcont').hide(500);
        }
    });
    
    $('#searchtime_slid').slider({
        value: $('#searchtime').val() != "" ? $('#searchtime').val() : hrsToMins(),
        min: 0,
        max: 1439,
        step: 15,
        //orientation : 'vertical',
        slide: function( event, ui ) {
            var myDate = minsToDate(ui.value);
            $('#searchtime').val(dateToTime(myDate)).select();
        },
        create: function(){
            /*if($('#searchtime').val() != "")
                $(this).slider('value',$('#searchtime').val());*/
            var myDate = minsToDate($(this).slider('value'));
            $('#searchtime').val(dateToTime(myDate));
            return false;
        },
        change: function(ev){
            var myDate = minsToDate($(this).slider('value'));
            $('#searchtime').val(dateToTime(myDate));
        }
    });
    
    $('.timelink').click(function(){
        $('#searchtime_slid').slider('value',$(this).attr('rel'));
        var myDate = minsToDate($('#searchtime_slid').slider('value'));
        $('#searchtime').val(dateToTime(myDate));
    });
    
    
    $('#mappick1,#mappick2').fancybox({
        onComplete: function() {
            getgmap();
        }
    });
    
    var errmessages = {
        station1 : "Choose a station by typing and selecting from the dropdown",
        station2 : "Choose a station by typing and selecting from the dropdown"
    }
    
    $('a.searchbutton').click(function(){
        $('#schedule_search').submit();
    });
    
    $('#schedule_search').validate({
        debug : true,
        ignore: ":disabled",
        rules: {
            station1 : {
                required:true
            },
            station2 : {
                required:true
            }
        },
        messages : errmessages,
        submitHandler : function() {
            var mydate = $('#searchdate').datepicker('getDate');
            var datestr = mydate.getFullYear() + "-" + (mydate.getMonth() + 1) + "-" + mydate.getDate();
            datestr = datestr + " " + $('#searchtime').val();
            $data = {
                carrier1 : $('#carrier1').val(),
                carrier2 : $('#carrier2').val(),
                station1 : $('#station1').val(),
                station2 : $('#station2').val(),
                departarrive : $('#departarrive').val(),
                date : datestr,
                json : 1
            }
            for(i in $data){
                $.cookie('schedule_' + i,$data[i],{
                    expires: i == 'date' ? undefined : 7 , 
                    path : "/"
                });
            }
            
            if($('#redirect').val() == 1)
                document.location.href = "/schedules/";
            else{
                doFlap();
                ajaxGetSchedule();
            }
            
            return false;
        },
        errorPlacement: function() {
            return false;
        },
        invalidHandler : function(frm,validator) {
            for(i in validator.errorList){
                $elem = $(validator.errorList[i].element).prop('id');
                $targ = $(validator.errorList[i].element).attr('rel');
                $("#" + $targ).addClass('error').attr('title',errmessages[$elem]);
            }
            
            $("#" + $(validator.errorList[0].element).attr('rel')).focus();          
        }
    });
    
    $('.deparr a.checkbox').click(function(){
        if($('#departarrive').val() != $(this).attr('rel')){
            $('#departarrive').val($(this).attr('rel'));
            $('.deparr a.checkbox').removeClass('checked');
            $(this).addClass('checked');
        }
    });
    
    
   /* if($('#station1txt').val() == ""){
        $('#station1txt').addClass('help');  
        $('#station1txt').val("Departing Station"); 
    }
    if($('#station2txt').val() == ""){
        $('#station2txt').addClass('help');  
        $('#station2txt').val("Arriving Station"); 
    } */
    
    $('#station1txt,#station2txt').focus(function(){
        if($(this).hasClass('help')){
            $(this).removeClass('help').val('');
        }
    }).blur(function(){
        if($(this).val() == ""){
            if($(this).attr('id') == "station1txt")
                $(this).val("Departing Station"); 
            else if($(this).attr('id') == "station2txt")
                $(this).val("Arriving Station"); 
            $(this).addClass('help')
        }
        else
            $(this).removeClass('help')
    });
    
    $('.fliplink a').click(function(){
        $sta1 = $('#station1').val();
        if($sta1 != "")
            $sta1txt = $('#station1txt').val();
        else
            $sta1txt = "";
        $carr1 = $('#carrier1').val();
        
        $sta2 = $('#station2').val();
        if($sta2 != "")
            $sta2txt = $('#station2txt').val();
        else
            $sta2txt = "";
        $carr2 = $('#carrier2').val();
        
        $('#station1').val($sta2);
        $('#station2').val($sta1);
        $('#station1txt').val($sta2txt);
        $('#station2txt').val($sta1txt);
        $('#carrier1').val($carr2);
        $('#carrier2').val($carr1);
        $('#station1txt,#station2txt').blur();
        /*if($('#redirect').val() == 0)
            $('#schedule_search').submit();*/
        
    });
    
});
    


