function strpos( haystack, needle, offset){ // Find position of first occurrence of a string
    var i = haystack.indexOf( needle, offset ); // returns -1
    return i >= 0 ? i : -1;
}
function strtolower( str ) {    // Make a string lowercase
    return str.toLowerCase();
}
function strlen( string ){  // Get string length
    return string.length;
}
function trimLeft(str) {
  return str.replace(/^\s+/, '');
}
function trimRight(str) {
  return str.replace(/\s+$/, '');
}
function trim(str) {
  return trimRight(trimLeft(str));
}
function trimSpaces(str) {
  return str.replace(/\s{2,}/g, ' ');
}

function update_timetable(){
    $('#js_timetable_loader').removeClass('hidden');
    $('#js_timetable_form').ajaxSubmit({
        dataType : "html",
        cache : true,
        success: function (data, textStatus) {
            setElementHTMLById('js_timetable', data);
            $('#js_timetable_loader').addClass('hidden');
        }
    });
}

$(document).ready(function(){

    /* DAY SELECTION FILTER */
    $('#js_day_selection_head').click(function(){
        var cinema_list = $(this).parent();
        var list_body =  $('#js_day_selection_choices');
        if (list_body.css('display')=='none'){
            $('.list_body:visible').hide();
            list_body.slideToggle(0);
        }
        else{
           $('.list_body:visible').hide();  
        }

    });
    $('.js_day_selection_choice').click(function(){
        var value = $(this).html();
        var id =  $(this).attr('id');
        var list_body = $('#js_day_selection_choices');
        var list_head = $('#js_day_selection_head');
        var list_hidden =  list_body.parent().children('input');
        list_body.hide();
        list_head.html(value);
        list_hidden.attr('value', id);
        $('#js_day_selection_input').val(id.slice(5));
        update_timetable();           
    });

    $(document).click(function(e){
        if($(e.target).parents().filter('.list_body:visible').length!=1 && $(e.target).parents().filter('.js_day_selection').length!=1){
            $('.list_body:visible').hide();
        }
    });
    
    /* CINEMA NAME SELECTION FILTER */
    var timeout;

    $('#js_input_cinema_for_movie').keyup(function(){
        clearTimeout(timeout);
        timeout = setTimeout(update_timetable, 1000);
    });
    
    
    /*METRO SEARCH*/
    var metro_title='';
    // приходится кэшировать, ибо ie опять тормозит словно баран
    var $js_input_metro = $("#js_input_metro");
    var $js_station_chooser_popup = $("#js_station_chooser_popup");
    
    $js_input_metro.focus(function(){
        // обнуляем выбор пользователя
        $(this).val('');
        metro_title='';
        $(this).addClass('active');
    })
    $js_input_metro.blur(function(){
        // ставим в соответствие выбору пользователя станцию метро из списка
        // Скрываем окно
        setTimeout(function(){
            var text = $js_input_metro.val()
            var old_metro_id = $("#metro_id").val();
            var new_metro_id = '';
            $("#metro_id").val('');
            $js_input_metro.val('');
            for (var key in metro){
                if (strtolower(metro[key]) == strtolower(text) ){
                    $("#metro_id").val(key);
                    $js_input_metro.val(metro[key]);
                    new_metro_id = key;
                }
            }
            
            // при необходимости обновляем расписание
            if(old_metro_id != new_metro_id){
                update_timetable();
            }

            $js_station_chooser_popup.hide();
            setElementHTMLById('js_station_chooser_popup','');

            // Сами показываем приглашение, на случай, если обработчик запускался ранее
            if (! new_metro_id){
                $(this).parents('.js_input_with_prompt').find('.js_input_prompt').show();
            }

        }, 200); // меньше задержка дает сбой на некоторых машинах
    })
    $js_input_metro.keyup(function(event){
        var keycode = event.keyCode;
        if (keycode=='40' && $js_station_chooser_popup.css('display')!='none'){       //key = down arror
            var cur_line = $js_station_chooser_popup.find('li.active');
            var next_line = cur_line.next();
            if (next_line.length!=0){
                cur_line.removeClass('active');
                next_line.addClass('active');
                metro_title = next_line.children('span.label').text();
            }
            $js_input_metro.val($js_input_metro.val()); // Простой способ передвинуть указатель в конец строки ввода
            return false;
        }
        else if (keycode=='38' && $js_station_chooser_popup.css('display')!='none'){  //key = up arror
            var cur_line = $js_station_chooser_popup.find('li.active');
            if (cur_line.prev().length!=0){  
                cur_line.removeClass('active');
                cur_line.prev().addClass('active');  
                metro_title = cur_line.prev().children('span.label').text();
            }
            $js_input_metro.val($js_input_metro.val()); // Простой способ передвинуть указатель в конец строки ввода
            return false;
        }
        else if(keycode=='13'){ //key = enter
            $js_input_metro.val(metro_title);
            $js_input_metro.blur();            
        }
        else{  // any other key
            var text = trim($(this).val());
            var data = '';
            var counter = 0;
            for (var key in metro) {      //analog to foreach
                var val = metro[key];
                var pos = strpos(strtolower(val), strtolower(text),-1);
                if (pos !=-1) { 
                    var start_str = val.substring(0,pos);
                    var needle = val.substring(pos,pos+strlen(text));
                    var end_str = val.substring(pos+strlen(text));
                    var add_class = '';
                    if (data==''){
                        add_class=' class="active"';
                        metro_title = val;
                    }
                    data += '<li'+add_class+'><span class="label">'+start_str+'<i>'+needle+'</i>'+end_str+'</span><span class="hidden">' + val +'</span></li>';
                    if (++counter == 10){
                        break;
                    }
                }
            }
            setElementHTMLById('js_station_chooser_popup','<ul>' + data + '</ul>');
            $js_station_chooser_popup.find('ul li').click(function(){
                $js_input_metro.val($(this).find('span.hidden').text());
            });
            if (data!='' && text!=''){
                $js_station_chooser_popup.show();
            }
            else{
               $js_station_chooser_popup.hide(); 
            }
        }
         
    });
    
    $js_station_chooser_popup.mouseover(function(){
        $js_station_chooser_popup.find('li.active').removeClass('active');
    }).mouseout(function(){
        $js_station_chooser_popup.find('li:first').addClass('active');
    });
    
    /*END OF METRO SEARCH*/
});

