var cache = {
  'ya' : '',
  'on' : '',
  'relat' : ''
};
var pics = [];
pics['on'] = '';
pics['ya'] = '';

function init() {
  cache.ya = $('#ya_tim').val();
  cache.on = $('#on_tim').val();
  cache.relat = $('#relat').val();
  draw_tim('on', cache.on);
  draw_tim('ya', cache.ya);
}

function clear(tar, full) {
  if(pics[tar].rel !== undefined) {
    $.each(pics[tar].rel, function(i,pair){
      $('.show_'+tar+' .show_tim' + ' .'+ pair.asp).removeClass(pair.func);
      $('.fun_'+tar+' .show_fun' + ' .'+ pair.func).removeClass(pair.asp);
      $('.show_'+tar+' .wrap_for_funs'+ ' .'+ pair.func).removeClass(pair.asp);
      $('.show_title .title_'+tar).html('');
    });
    if (full) {
      cache.relat = '';
      $('.rel_res').html('');
      $('#relat option[value=""]').attr({'selected': true});
      $('#'+tar+'_tim option[value=""]').attr({'selected': true});
      if (tar == "on") { cache.on = "";} else { cache.ya = "";}
      $('.show_'+tar+' .wrap_for_funs').removeClass('show_fun_name');
    }
  }
}

function get_asp(tar, val) {
  var tim_div = '.show_'+tar+' .show_tim';
  var fun_div = '.fun_'+tar+' .show_fun';
  var anim_div = '.anim_'+tar;
  var title_div = '.show_title .title_'+tar;
  var load = false;
  $(anim_div).animate({ opacity: 0 }, 700, function() {
    if (!load) {// поскольку анимируются сразу три объекта, аяксовый запрос тоже стартует три раза. я блондинко :(
      clear(tar,false);
      $(tim_div).attr("id", tar+'_'+val);
      $(fun_div).attr("id", tar+'_'+val);
      $('.show_'+tar+' .wrap_for_funs').addClass('show_fun_name');
      $.getJSON("get_asp.php", { 'a' : val }, function(data){
        pics[tar] = data;
        $.each(data.rel, function(i,pair){
          $(tim_div + ' .'+ pair.asp).addClass(pair.func);
          $(fun_div + ' .'+ pair.func).addClass(pair.asp);
          $('.show_'+tar+' .wrap_for_funs'+ ' .'+ pair.func).addClass(pair.asp);
          $(title_div).html(data.title +', ' +data.kvadra);
        });
        $(anim_div).animate({ opacity: 1 }, 700).removeClass('hide'); 
      });
    }
    load = true;
  });
}

function draw_tim(tar,val) {
  var tim_div = '.show_'+tar+' .show_tim';
  var fun_div = '.fun_'+tar+' .show_fun';
  if (!($(tim_div).is('#'+tar+'_'+val))) {
    if (val !== '') {
      get_asp(tar, val);
    } else {
      $(tim_div).attr("id", '');
      $(fun_div).attr("id", '');
      $('.show_'+tar+' .wrap_for_funs').removeClass('show_fun_name');
      clear(tar,true);
    }
  }
}

function cache_it(ya, on, rel) {
  if (ya !== "") cache.ya = ya;
  if (on !== "") cache.on = on;
  if (rel !== "") cache.relat = rel;
}

function print_info() {
  if (cache.ya != '' && cache.on != '' && cache.relat != '') {
    ya_text = $('#ya_tim option[value='+cache.ya+']').text();
    on_text = $('#on_tim option[value='+cache.on+']').text();
    rel_text = $('#relat option[value='+cache.relat+']').text();
    $('.rel_res').html('');
    var rel = cache.relat;
    if (cache.relat == 'podkontrol') rel = 'kontrol';
    if (cache.relat == 'podzakaz') rel = 'zakaz';
    $('.rel_res').load('../descr/rel_descr/'+rel+'.html', function() {
      $('.rel_res').prepend('<h4>'+ya_text+' > '+on_text+' = '+rel_text+'</h4>').append('<div class="all_pairs"></div>');
      if (cache.relat != 'tozhd') {
        $.get("get_all.php", { 'rel' : cache.relat }, function(data){
          $('.all_pairs').append(data);
        });
      }
    });
  }
}

function find_rel(ya, on) {
  $.getJSON("find_rel.php", { 'ya' : ya, 'on' : on }, function(data){
    $('#relat option[value="'+data.rel+'"]').attr({ 'selected': true});
    cache_it(ya, on, data.rel);
    print_info();
  });
}

function find_tim(tim, rel, tar) {
  if (rel !== '') {
    $.getJSON("find_tim.php", { 'tim' : tim, 'rel' : rel}, function(data){
      $('#'+tar+'_tim option[value="'+data.tim+'"]').attr({ 'selected': true});
      if (tar == "ya") cache.ya = data.tim;
      if (tar == "on") cache.on = data.tim;
      print_info(tim, data.tim, rel);
      draw_tim(tar, data.tim);
    });
  } else {
    clear("on", true);
  }
}

$(function(){    

  init();

  $('#ya_tim').change( function() {
    var ya_val = $(this).val();
    cache.ya = ya_val;
    draw_tim('ya', ya_val);
    if (cache.on !== '') {
      find_rel(cache.ya, cache.on);
    } else {
      find_tim(cache.ya, cache.relat, 'on');
    }
  //if (ya_val == '') {
  //  find_tim(cache.on, cache.relat, "ya");
  //}
  });//.change();
  
  $('#on_tim').change( function() {
    var on_val = $(this).val();
    cache.on = on_val;
    draw_tim('on', on_val);
    if (cache.ya !== '') {
      find_rel(cache.ya, cache.on);
    } else {
      if (cache.relat !== '') find_tim(cache.on, cache.relat, "ya" );
    }
  });//.change();

  $('#relat').change( function() {
    var relat_val = $(this).val();
    cache.relat = relat_val;
    if (cache.ya !== '') {
      find_tim(cache.ya, cache.relat, 'on');
    } else {
      find_tim(cache.on, cache.relat, "ya" );
    }
  }).change();
  
  $('select').change( function() {
    //console.log(cache);
    $('body').focus();
    $('.hack_focus').focus();
  });
  
  $('.show_fun p').hover(function(){
    var arr = $(this).attr("class").split(" ");
    var fun = arr[0];
    var asp = arr[1];
    //$('.show_tim .' + asp).addClass('highlight_asp');
    $('.wrap_for_funs .' + asp).addClass('show');
  },function(){
    var arr = $(this).attr("class").split(" ");
    var fun = arr[0];
    var asp = arr[1];
    //$('.show_tim .' + asp).removeClass('highlight_asp');
    $('.wrap_for_funs .' + asp).removeClass('show');
  })
  
  $('.show_fun p').click(function(){
    var tim =  $(this).parent().attr('id').slice(3);
    var tar = $(this).parent().attr('id').slice(0,2);
    var arr = $(this).attr("class").split(" ");
    var asp =  arr[1];
    var title = pics[tar].title+': '+$(this).attr('alt');
    if (tar == "on") var shift = "right_shift";
    if (tar == "ya") var shift = "left_shift";
    var cl = tim + ' ' + asp + ' ' + shift;
    var file = '../descr/tim_descr/'+tim+'_'+asp+'.html';
    $('.dialog_box').append('<div class="dialog" title="'+title+'"></div>');
    $('.dialog_box div').append('<p></p>').load(file, function() {
      $('.dialog').dialog({
        autoOpen: false,
        bgiframe: true,
        width: 450,
        dialogClass: cl ,
        close: function(ev, ui) {
          $(this).remove();
        }
      }).dialog('open');
    });
  });

  jQuery.each(jQuery.browser, function(i) {
    if(($.browser.msie)||($.browser.opera)){
      $("body").addClass('border_img');
    }
  });
  
  $('.up_link').click(function(){
    var coor = $('.outer').offset().top - 5;
    $("html, body").animate({
      scrollTop: coor
    }, 1200, function() {} );
    return false;
  });

});