var main_banner_timer;

$(document).ready(function() {
  make_spoilers();
  
  $('#spoilers div.titles a.unactive').hover(function() {
    $(this).addClass('hovered');
  }, function() {
    $(this).removeClass('hovered');
  });
  
  $('#spoilers div.titles a').click(function() {
    if ($(this).hasClass('unactive')) {
      $('#spoilers a.active').attr('class', 'unactive');
      $('#spoilers div.active_spoiler').attr('class', 'spoiler');
      $(this).attr('class', 'active');
      $('#'+ $(this).attr('id') +'_content').attr('class', 'active_spoiler');
    }
    return false;
  });
  
  $('#search_form input').focus(function() {
    if ($(this).val() == 'Поиск по сайту') {
      $(this).val('');
    }
  });
  $('#search_form input').blur(function() {
    if ($(this).val() == '') {
      $(this).val('Поиск по сайту');
    }
  });
  
  $('#t_kl').change(function() {
    $('div.connect_no, div.connect_yes, #order_form, #order_form_result').hide();
  });
  $('#street').focus(function() {
    if ($(this).parents('div.connect_check').length) {
      $(this).css('color', '#000');
      if ($(this).val() == 'Улица') {
        $(this).val('');
      }
      $('#home').val('Дом').css('color', '#999');
    } else {
      $('#home').val('');
    }
    $('#street_id').val('');
    $('#home_id').val('');
    $('div.connect_no, div.connect_yes, #order_form, #order_form_result').hide();
  });
  $('#home').focus(function() {
    if ($(this).parents('div.connect_check').length) {
      $(this).css('color', '#000');
      if ($(this).val() == 'Дом') {
        $(this).val('');
      }
    }
    $('#home_id').val('');
    $('div.connect_no, div.connect_yes, #order_form, #order_form_result').hide();
  });
  $('#street').blur(function() {
    if ($(this).parents('div.connect_check').length) {
      if ($(this).val() == '') {
        $(this).val('Улица').css('color', '#999');
      }
    }
  });
  $('#home').blur(function() {
    if ($(this).parents('div.connect_check').length) {
      if ($(this).val() == '') {
        $(this).val('Дом').css('color', '#999');
      }
    }
  });
  
  $('div.action #street').one('focus', function() {
    $('#street').val('');
  });
  
  $('#agree').click(function() {
    if ($(this).attr('checked')) {
      $('#submit_button').show();
    } else {
      $('#submit_button').hide();
    }
  });
  
  $('#channels_switcher').toggle(function() {
    $(this).addClass('active').text('Свернуть список');
    $('#channels div.for_switch').slideDown();
  }, function() {
    $(this).removeClass('active').text('Развернуть список');
    $('#channels div.for_switch').slideUp();
  });
  
  $('div.scrolling_menu div.links div.wrapper').width(function() {
    var width = 0;
    $.each($(this).find('a'), function(i, obj) {
      width += $(obj).outerWidth(true);
    });
    if ($('div.scrolling_menu div.links').width() < width) {
      $('div.scrolling_menu a.toright').addClass('active');
    }
    return width;
  });
  $('div.scrolling_menu a.control').click(function() {
    var parent_container = $(this).parents('div.scrolling_menu');
    var links_container = parent_container.find('div.links');
    if ($(this).hasClass('toleft')) {
      if (links_container.find('a:first').offset().left < links_container.offset().left) {
        var items = links_container.find('a');
        items.animate({left: '+='+ items.outerWidth(true) +'px'}, 500, function() {
          if (links_container.find('a:first').offset().left < links_container.offset().left) {
            parent_container.find('a.toleft').addClass('active');
          } else {
            parent_container.find('a.toleft').removeClass('active');
          }
          if (links_container.find('a:last').offset().left >= links_container.offset().left + links_container.outerWidth()) {
            parent_container.find('a.toright').addClass('active');
          } else {
            parent_container.find('a.toright').removeClass('active');
          }
        });
      }
    }
    if ($(this).hasClass('toright')) {
      if (links_container.find('a:last').offset().left >= links_container.offset().left + links_container.outerWidth()) {
        var items = links_container.find('a');
        items.animate({left: '-='+ items.outerWidth(true) +'px'}, 500, function() {
          if (links_container.find('a:first').offset().left < links_container.offset().left) {
            parent_container.find('a.toleft').addClass('active');
          } else {
            parent_container.find('a.toleft').removeClass('active');
          }
          if (links_container.find('a:last').offset().left >= links_container.offset().left + links_container.outerWidth()) {
            parent_container.find('a.toright').addClass('active');
          } else {
            parent_container.find('a.toright').removeClass('active');
          }
        });
      }
    }
    return false;
  });
  $('div.scrolling_menu div.links a').click(function() {
    var parent_container = $(this).parents('div.scrolling_menu');
    $('#services div.item').removeClass('active');
    parent_container.parent().addClass('active');
    parent_container.find('div.links a').removeClass('active');
    $(this).addClass('active');
    parent_container.siblings('div.description').html($(this).next('div.small_content').html());
    return false;
  });
  //$('div.scrolling_menu').last().find('div.links a').eq(0).click();
  
  $('#main_banner div.images_container').width(function() {
    var width = 0;
    $.each($(this).find('a'), function(i, obj) {
      width += $(obj).outerWidth(true);
    });
    if ($('div.scrolling_menu div.links').width() < width) {
      $('div.scrolling_menu a.toright').addClass('active');
    }
    return width;
  });
  
  /*if ($('#main_banner').length && $('#main_banner div.images_wrapper a').length > 1) {
    main_banner_timer = setInterval(change_main_banner, 10000);
    
    $('#main_banner div.images_wrapper a').hover(function() {
      clearInterval(main_banner_timer);
    }, function() {
      main_banner_timer = setInterval(change_main_banner, 10000);
    });
  }*/
  
  if ($('#game2011_top20').length) {
    setInterval(function() {
      $.getJSON('/home/game/getTop/', function(top) {
        if (typeof(top) == 'object' && top.length > 0) {
          var html = '<table><caption><b>TOP 20</b></caption><tr><th>Место</th><th>ID участника</th></tr>';//<th>Счет</th></tr>';
          $.each(top, function(num, item) {
            html += '<tr>' +
              '<td align="center">'+ (num + 1) +'</td>' +
              '<td>'+ item.login +'</td>' +
              //'<td align="center">'+ item.score +'</td>' +
            '</tr>';
          });
          html += '</table>';
          $('#game2011_top20').html(html);
        }
      });
    }, 60000);
  }
});

function change_main_banner() {
  var items_container = $('#main_banner div.images_wrapper');
  if (items_container.find('a:last').offset().left < items_container.offset().left + items_container.outerWidth()) {
    var last = items_container.find('a:last');
    var afters = items_container.find('a:not(a:last)').css({left: 0});
    last.css({left: 0}).after(afters);
  }
  var items = items_container.find('a');
  items.animate({left: '-='+ items.outerWidth(true) +'px'}, 300);
}

function make_spoilers() {
  var spoilers = $('table.spoiler');
  var cnt = spoilers.length;
  if (cnt) {
    $.each(spoilers, function(i, obj) {
      if (!i) { $(obj).before('<div id="spoilers"><div class="titles"></div><div class="body"><div class="right_top"><div class="top"></div></div><div class="left"><div class="right"><div class="inner"></div></div></div><div class="right_bottom"><div class="bottom"></div></div></div></div>'); }
      $('#spoilers div.titles').append('<a id="spoiler_'+ i +'" href="#"'+ (!i ? ' class="active"' : 'class="unactive"') +'><div class="left_top"><div class="right_top"><div class="top"></div></div></div><div class="left"><div class="right"><div class="title"><span>'+ $(obj).find('caption').eq(0).text() +'</span></div></div></div></a>');
      $('#spoilers div.inner').append('<div id="spoiler_'+ i +'_content"'+ (i ? ' class="spoiler"' : 'class="active_spoiler"') +'>'+ $(obj).find('td').eq(0).html() +'</div>');
      $(obj).remove();
    });
  }
}

function city_select() {
  $('#street').val('');
  $('#street_id').val('');
  $('#home').val('');
  $('#home_id').val('');
}

function street_search(request, response, only_text) {
  if (typeof(only_text) == 'undefined') {
    var input_obj = $('#street');
    var params = {search_string: request.term, city_id: $('#city_id').val()};
  } else {
    var input_obj = $('#street_text');
    var params = {search_string: request.term, city_id: $('#city_text_id').val()};
  }
  if (request.term.length) {
    input_obj.addClass('loading');
    $.post('/plugins/street/', params, function(result) {
      input_obj.removeClass('loading');
      if (typeof(result) != 'undefined') {
        if (typeof(result.error) != 'undefined') {
          //Обработка ошибок
        } else if (result.length) {
          response($.map(result, function(item) {
            return {label: item.street_name, value: item.street_id};
          }));
        }
      }
    }, 'json');
  }
}

function street_select(item, only_text) {
  if (typeof(only_text) == 'undefined') {
    $('#street').val(item.label);
    $('#street_id').val(item.value);
    $('#home').val('').focus();
    $('#home_id').val('');
  } else {
    $('#street_text').val(item.label);
    $('#street_text_id').val(item.value);
    $('#home_text').val('').focus();
    $('#home_text_id').val('');
  }
  return false;
}

function home_search(request, response, only_text) {
  if (typeof(only_text) == 'undefined') {
    var input_obj = $('#home');
    var params = {search_string: request.term, city_id: $('#city_id').val(), street_id: $('#street_id').val(), street: $('#street').val()};
  } else {
    var input_obj = $('#home_text');
    var params = {search_string: request.term, city_id: $('#city_text_id').val(), street_id: $('#street_text_id').val(), street: $('#street_text').val()};
  }
  if (request.term.length) {
    input_obj.addClass('loading');
    $.post('/plugins/home/', params, function(result) {
      input_obj.removeClass('loading');
      if (typeof(result) != 'undefined' && result) {
        if (typeof(result.error) != 'undefined') {
          //Обработка ошибок
        } else if (result.length) {
          response($.map(result, function(item) {
            return {label: item.home_name, value: item.id};
          }));
        }
      }
    }, 'json');
  }
}

function home_select(item, only_text) {
  if (typeof(only_text) == 'undefined') {
    $('#home').val(item.label);
    $('#home_id').val(item.value);
    $('#go_check').click();
  } else {
    $('#home_text').val(item.label);
    $('#home_text_id').val(item.value);
  }
  return false;
}

function connect_check() {
  $('#home').blur();
  if ($('#street').val() && $('#home').val()) {
    sheet('show');
    $.post('/plugins/check/', {city_id: $('#city_id').val(), t_kl: $('#t_kl').val(), street_id: $('#street_id').val(), street: $('#street').val(), home_id: $('#home_id').val(), home: $('#home').val()}, function(result) {
      sheet('hide');
      $('#order_city_id').val($('#city_id').val());
      $('#order_t_kl').val($('#t_kl').val());
      $('#order_street_id').val($('#street_id').val());
      $('#order_home_id').val($('#home_id').val());
      $('#order_street').val($('#street').val());
      $('#order_home').val($('#home').val());
      if (typeof(result) != 'undefined' && result) {
        if (result.result == 'YES') {
          $('#connect_no_'+ $('#t_kl').val()).hide();
          $('#connect_yes_'+ $('#t_kl').val() +', #order_form').show();
          if (typeof(result.emp_otv) == 'object') {
            var with_mko_obj = $('#connect_yes_'+ $('#t_kl').val() +' div.with_mko');
            with_mko_obj.find('.mko_name').text(result.emp_otv.name);
            with_mko_obj.find('.mko_phone').text(result.emp_otv.phone);
            with_mko_obj.find('.mko_email').attr('href', 'mailto:'+ result.emp_otv.email).text(result.emp_otv.email);
            $('#connect_yes_'+ $('#t_kl').val() +' div.default').hide();
            with_mko_obj.show();
          } else {
            $('#connect_yes_'+ $('#t_kl').val() +' div.with_mko').hide();
            $('#connect_yes_'+ $('#t_kl').val() +' div.default').show();
          }
          return;
        }
      }
      $('#connect_yes_'+ $('#t_kl').val()).hide();
      $('#connect_no_'+ $('#t_kl').val() +', #order_form').show();
    }, 'json');
  }
  return false;
}

function connect_check_order_sended() {
  $('div.connect_no, div.connect_yes, #order_form').hide();
  $('#order_form_result').show();
  sheet('hide');
}

function contract_process_go() {
  sheet('show');
  $('#contract_process').ajaxSubmit(function(answer) {
    if (Number(answer)) {
      $('#contract_process, #contract_process_pretext').hide();
      $('#contract_process_complete').show();
      $('#contract_process_id').text(' '+ answer +' ');
    } else {
      alert(answer);
    }
    sheet('hide');
  });
  return false;
}

function show_movie(movie) {
  $('#movie_container').css({
    'left': $(window).width() / 2 -  $('#movie_container').outerWidth() / 2,
    'top': $(window).height() / 2 -  $('#movie_container').outerHeight() / 2
  });
  $('#movie_sheet, #movie_container').show();
  $('#movie_block').attr('href', movie);
  flowplayer('movie_block', '/flowplayer/flowplayer-3.2.5.swf', {
    plugins:  {
      controls: {
        backgroundGradient: 'none',
        backgroundColor: '#3f3f3f',
        bufferColor: '#999999',
        progressColor: '#9eb535',
        buttonColor: '#9eb535',
        buttonOverColor: '#bed846',
        timeColor: '#bed846',
        autoHide: 'always',
        tooltips: {
          buttons: true,
          play: 'Старт',
          pause: 'Пауза',
          mute: 'Выключить звук',
          unmute: 'Включить звук',
          fullscreenExit: 'Выход из полноэкранного режима',
          fullscreen: 'На полный экран'
        },
        tooltipColor: '#3f3f3f',
        tooltipTextColor: '#ffffff'
      }
    },
    clip: {
      autoPlay: true,
      autoBuffering: true,
      scaling: 'fit'
    }
  });
  return false;
}

function hide_movie() {
  flowplayer('movie_block').close();
  $('#movie_sheet, #movie_container').hide();
  return false;
}
