var $j = jQuery.noConflict();
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000))}else{date=options.expires}expires='; expires='+date.toUTCString()}var path=options.path?'; path='+(options.path):'; path=/';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};
function printf(k){var l=function(a,b,c){var d='';for(var i=0;i<Math.abs(c);i++)d+=b;return c>0?a+d:d+a};var m=function(d,e,f,g){var h=function(a,b,c){if(b>=0){if(a.indexOf(' ')>=0)c=' '+c;else if(a.indexOf('+')>=0)c='+'+c}else c='-'+c;return c};var i=parseInt(e,10);if(e.charAt(0)=='0'){var j=0;if(d.indexOf(' ')>=0||d.indexOf('+')>=0)j++;if(f.length<(i-j))f=l(f,'0',f.length-(i-j));return h(d,g,f)}f=h(d,g,f);if(f.length<i){if(d.indexOf('-')<0)f=l(f,' ',f.length-i);else f=l(f,' ',i-f.length)};return f};var n=new Array();n['f']=function(a,b,c,d){iPrecision=parseInt(c);if(isNaN(iPrecision))iPrecision=6;rs=(Math.abs(d)).toFixed(iPrecision);if(rs.indexOf('.')<0&&a.indexOf('#')>=0)rs=rs+'.';return m(a,b,rs,d).replace(/\./,',')};farr=k.split('%');retstr=farr[0];fpRE=/^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;for(var i=1;i<farr.length;i++){fps=fpRE.exec(farr[i]);if(!fps)continue;if(arguments[i]!=null)retstr+=n[fps[4]](fps[1],fps[2],fps[3],arguments[i]);retstr+=fps[5]};return retstr}
Validation=function(options){this.options=options;this.form=$j(options.form);this.errors={};var me=this;this.form.submit(function(){return me.validate()});for(field in this.options.fields){var validator=(function(field2){return function(){if(this.pressed)me.validate_field(field2,true)}})(field);this.form.find(field).blur(validator);this.form.find(field).keypress(function(ev){if(ev.keyCode!=9)this.pressed=true})}};Validation.prototype={validate:function(){var me=this;for(field in this.options.fields){me.validate_field(field)};if(this.all_errors().length>0){this.show_errors();return false}else{return true}},validate_field:function(field,show_errors){var me=this;this.field=field;var value=this.form.find(field).removeClass("error").val();this.label_tag(field).find("small").remove();this.errors[field]=[];$j(this.options.fields[field]).each(function(){return this(value,me)});if(show_errors)this.show_errors_for_field(field)},error:function(message){if(!this.errors[this.field])this.errors[this.field]=[];this.errors[this.field].push(message)},all_errors:function(){var me=this;var all_errors=[];for(field in this.errors){$j(this.errors[field]).each(function(){all_errors.push(me.label_of(field)+" "+this)})};return all_errors},label_tag:function(field){return this.form.find("label[for="+field.replace(/^\#/,'')+"]")},label_of:function(field){return this.label_tag(field).html()},show_errors:function(){var me=this;var all_errors_container=me.form.find(".error-messages").show();if(all_errors_container.size()){var error_tag="p";if(all_errors_container.find("ul").size()>0){error_tag="li";all_errors_container=all_errors_container.find("ul")};all_errors_container.html(" ");$j(this.all_errors()).each(function(){var p=$j("<"+error_tag+">"+this+"</"+error_tag+">");all_errors_container.append(p)})}for(field in this.errors){this.show_errors_for_field(field)}},show_errors_for_field:function(field){if(this.errors[field].length==0)return false;var me=this;this.form.find(field).addClass("error");var label=this.label_tag(field);text=$j(this.errors[field]).map(function(){return"<small>"+this+""});label.append(text.get().join(",</small> ")+"</small>")}};Validation.presense=function(message){if(!message)message="необходимо заполнить";return function(value,object){if(value){return true}else{object.error(message);return false}}};Validation.length_in=function(f,t,message1,message2){if(!message1)message1="слишком короткое";if(!message2)message2="слишком длинное";return function(value,object){if(value.length<f){object.error(message1);return false};if(value.length>t){object.error(message2);return false}};return true};Validation.match=function(regexp,message){if(!message)message="имеет неверный формат";return function(value,object){if(value.match(regexp)){return true}else{object.error(message);return false}}};
if(!Array.indexOf){Array.prototype.indexOf = function(obj){for(var i=0; i<this.length; i++){if(this[i]==obj){return i;};};return -1;};};

function paginate_files(){
	
	$j("#main .text table").each(function() {
	  var table = $j(this);
	  var years = [];
	  table.find("td:first-child").each(function() {
	    var m = this.innerHTML.match(/20\d{2}/);
      if(m){
        var year = m[0]
        $j(this.parentNode).attr("year", year);
        if(years.indexOf(year) == -1) years.push(year);
      }
	  })
	  if(years.length == 1) return true;
	  
    var years_div = $j("<div class='years'></div>");
    table.before(years_div);
    var clicker = function() {
      var me = this.innerHTML;
      table.find("tr[year="+me+"]").show();
      table.find("tr[year!="+me+"]").hide();
      years_div.find("a").removeClass("active");
      this.className = "active";
    }
    $j(years).each(function() {
      var link = $j("<a href='javascript:void(0)'>"+this+"</a>");
      link.click(clicker);
      years_div.append(link);
    });
    
    table.find("tr[year!="+years[0]+"]").hide();
    years_div.find("a:contains("+years[0]+")").addClass("active");
	})
}

var location_dialog = {
  init: function() {
    $j("#location_dialog ul li a").click(location_dialog.select)
    location_dialog.init = false;
  },
  open: function() {
    if(location_dialog.init) location_dialog.init()
    
    $j("#location_dialog").show()
    $j("#location_dialog").css("top",$j(".informer.city").offset().top - 1)
    
    location_dialog.old_keydown = document.onkeydown
    document.onkeydown = function(e){ 	
  		if (e == null) keycode = event.keyCode;
  		else keycode = e.which;
  		if(keycode == 27) location_dialog.close();
  	}
  	document.onclick = function(e) {
  	  if(e == null) e = event;
  	  var target = e.target;
  	  var donotclose = false;
  	  while(target.parentNode){
  	    if(target.id == 'location_dialog') donotclose = true;
  	    target = target.parentNode;
  	  }
  	  if(!donotclose) location_dialog.close();
  	};
  	if($j.cookie("o")){
  	  var city = $j.cookie("o").split(";")[0]
  	  $j("#location_dialog ul li a").each(function() {
  	    var me = $j(this);
  	    if((me).html() == city) me.parent().addClass("current")
  	    else if(me.parent().hasClass("current")) me.parent().removeClass("current")
  	  })
  	}
  },
  close: function() {
    $j("#location_dialog").hide();
    document.onclick = null;
    document.onkeydown = location_dialog.old_keydown;
  },
  select: function() {
    var informer = $j(".informer div.city")
    var m;
    if(m = this.parentNode.id.match(/city-(\d+)$/)){
      informer.addClass("loading")
      informer.load("/city/" + m[1], function() {informer.removeClass('loading')})
    }else{
      if(location.href.match(/\/cities\//)){
        city.redirect($j(this).html());
      }else{
        city.choose($j(this).html());
      }
    }
    location_dialog.close()
    return false;
  }
}

var currency = {
  init_informer: function() {
    if(!$j.cookie("c")){
      var div = $j("#right .informer.exchange");
      div.addClass("loading")
      currency.load(function(data) {
        var bb;
        if(data.banks.bank && data.banks.bank.bik == 049401814){
          bb = [data.banks.bank]
        }else{
          bb = $j(data.banks).filter(function() {return this.bik == 049401814}).get() 
        }
        if(bb && bb[0]){
          bb = bb[0]
          var data = bb.usd.buy+","+bb.usd.sale+","+bb.eur.buy+","+bb.eur.sale;
          $j.cookie("c",data,  { path: '/', expires: 1.0/24/6 }) //10 minutes
          div.removeClass("loading")
          currency.write_informer(data);
        }
      })
    }else{
      currency.write_informer();
    }
  },
  
  write_informer: function(data) {
    var div = $j("#right .informer.exchange");
    if(!data) data = $j.cookie("c");
    data = data.split(",")
    var cells = div.find("td").get();
    cells = cells.slice(1,5);
    $j(data).each(function(i) {
      cells[i].innerHTML = printf("%3.2f",this);
    })
  },
  
  load: function(callback){
    if($j.browser.msie){
      $j.getJSON("/kurs.php?x="+Math.random(),function(data) { currency.data = data;callback(data) })
    }else{
      $j.getJSON("/kurs.php?_=1&e=utf-8",function(data) { currency.data = data;callback(data) })
    }
  },
  
  build_table: function() {
    var div = $j("#currency_table")
    if(!div.size()){
      div = $j("<div id='currency_table'></div>")
      $j("#main .main-layout").append(div)
    }
    div.load("/kurs.php",function() {
      var table = div.find("table")
      table.find("th.sortable").click(function() {
        var me = $j(this)
        var cls = this.className
        var cl = cls.split(' ')[0]
        var sorter = function(a,b) {return a.v > b.v ? 1 : -1 }
        table.find("th").removeClass("sort-asc").removeClass("sort-desc")
        this.className = cls;
        if(me.hasClass("sort-asc")){
          sorter = function(a,b) {return a.v < b.v ? 1 : -1 }
          me.addClass("sort-desc").removeClass("sort-asc")
        }else{
          me.addClass("sort-asc").removeClass("sort-desc")
        }
        var values = table.find("tr").map(function() {
          return {v: $j(this).find("td."+cl).html(), t: this}
        }).get()
        values = values.splice(2,99)
        values.sort(sorter)
        $j(values).each(function() {
          table.append(this.t);
        })
      })
      $j("usd-buy usd-sale eur-buy eur-sale".split(" ")).each(function() {
        var classes = ["min-value","max-value"]
        if(this.match(/sale/)) classes = ["max-value","min-value"]
        
        var cells = $j("td."+this);
        var vals = cells.map(function() { return parseFloat(this.innerHTML)})
        var max = Math.max.apply(Math,vals.get())
        var min = Math.min.apply(Math,vals.get())
        cells.each(function() {
          if(this.innerHTML == max) $j(this).addClass(classes[0])
          if(this.innerHTML == min) $j(this).addClass(classes[1])
        })
      })
      $j("td.title").filter(function() {return this.innerHTML.match(/БЫСТРОБАНК/)}).parent().addClass("bb")
      
    })
  }
}

var city = {
  init: function() {
    if(!$j.cookie("l")){
      $j.get("/geo.php",function(data) {
        city.choose(data)
      })
    }else if($j.cookie("o")){
      city.write_informer()
    }else{
      city.choose();
    }
  },
  
  find_in_list: function(data) {
    var info = $j(data).filter(function() {return this.title == $j.cookie("l")}).get();
    if(info && info[0]) $j.cookie("l",info[0].code); //если нашли то пишем в куки код, а иначе ищем по коду
    else info = $j(data).filter(function() {return this.code == $j.cookie("l")}).get();
    if(info && info[0]){
      info = info[0];
    };
    return info;
  },
  
  get: function(data) {
    var info, office;
    info = city.find_in_list(data);
    // находим город по названию
    if(info){
      if(info.offices){
        office = info.offices.office
        if(!office) office = info.offices[0]
      }else office = {phone: 'Нет местного телефона',title: ''}
      office.phone = office.phone.split(",")
      if(office.phone[0].length < 8) office.phone[0] += office.phone[1]
      office.phone = office.phone[0];
      str_data = info.title + ";" + office.phone + ";" + office.title + ";" + info.flag
      $j.cookie("o",str_data,{ path: '/', expires: 1 })
      city.write_informer(str_data)
    }
  },
  
  choose: function(town, callback) {
    if(town) $j.cookie("l",town, { path: '/', expires: 5 })
    $j.getJSON("/cites.php?_=1",function(data) { 
      city.get(data);
      places.hl_city();
      if(callback) callback();
    })
  },
  
  redirect: function(town) {
    city.choose(town,function() {
      new_link = $j("#right .informer.city p.office a").attr("href").replace(/#offices/,'');
      var m1 = new_link.match(/\/([^\/]+)\.html/);
      var m2 = location.href.match(/\/([^\/]+)\.html/);
      if(m1[1] != m2[1]){
        location.href = new_link;
      }
    })
  },
  
  write_informer: function(data) {
    var location_prefix = "/cities/";
    if(location.pathname.match(/^\/bank\//) || window.local_version) location_prefix = "/bank" + location_prefix
    var div = $j("#right .informer.city");
    if(!data) data = $j.cookie("o");
    data = data.split(";")
    var flag = "none"
    if(data[3]) flag = data[3];
    var alias = $j.cookie("l").toLowerCase().replace(/ /,'_');
    div.find("h4.city strong").html(data[0])
    div.find("h4.phone").html(data[1].replace(/\(/,"<small>(").replace(/\)/,")</small> "))
    div.find("p.office a").html(data[2]).attr("href",location_prefix + alias + ".html#offices")
    div.find("h4.city img").attr("class","flag flag-"+flag)
    div.find("ul li:first-child a").attr("href",location_prefix + alias + ".html#offices")
    div.find("ul li:last-child a").attr("href",location_prefix + alias + ".html#bankomats")
    $j("a.city-link").attr("href",location_prefix + alias + ".html")
    $j("a.city-link.bankomats").attr("href",location_prefix + alias + ".html#bankomats")
    $j("a.city-link.offices").attr("href",location_prefix + alias + ".html#offices")
  }
  
}

var informer = {
  init: function() {
    $j("#right_switcher a").click(informer.toggle)
  },
  toggle: function() {
    if($j("#right").css("overflow") == "hidden"){
      $j(this).removeClass("hidden")
      informer.show()
    }else{
      $j(this).addClass("hidden")
      informer.hide()
    }
  },
  step: function() {
    var me = $j(this);
    var w = parseInt(me.css("width"));
    $j("#main").css("padding-right",w)
    me.css("margin-right",-1*w)
  },
  hide: function() {
    $j("#right").css("overflow","hidden").animate({width: 20},{step: informer.step, finish: informer.step})
  },
  show: function() {
    $j("#right").animate({width: 250},{step: informer.step, complete: function(){
      informer.step.apply(this);
      $j(this).css("overflow","auto");
    } })
  }
}

var search = {
  init: function() {
    var qform = $j("#search form")
    var form = $j("form.full_search")
    var result = $j("#main div.search-results");
    var do_search = function() {
      try{
        var query = form.find("input.search").val()
        result.html("Производим поиск…")
        result.load("/srch.php",{q: query})
      }catch(e){
        console.info(e);
      }
      return false;
    }
    
    if(form.size()){
      var q = search.read_q()
      if(q){
        form.find("input.search").val(q);
        qform.find('input.search').val(q);
        do_search();
      }
      form.submit(do_search)
    }
  },
  read_q: function() {
    var q;
    q = location.search.match(/q=([^&]+)/)
    if(q) q = q[1];
    else return "";
    q = q.replace(/\+/gi,' ');
    return unescape(decodeURIComponent(q));
  }
}

var places = {
  init: function() {
    if($j.browser.opera) $j("#main .places p a small").css({position: "static", border: "none"});
    var div = $j("#main div.places")
    if(!div.size()) return;
    var places_links = div.find("p.places a");
    
    hl_offices = function() {
      if($j(this).hasClass("others")) return true;
      places_links.removeClass("current")
      $j(this).addClass("current")
      
      if(!div.find("ul").size()) return false;
      div.find("ul li").removeClass("active")

      var citclass = this.className.match(/\b(\w{3,7})\b/);
      if(citclass) citclass = citclass[0]
      else return false;
      div.find("ul li."+ citclass).addClass("active")
      
      return false;
    }

    
    div.find("p.places a.current").each(hl_offices);
    places_links.click(hl_offices);
    if(!div.find("ul").size()) return true;
    places.hl_city()
  },
  
  hl_city: function() {
    if($j("#bankomats-select").size()) return false;
    var places_links = $j("#main p.places a");
    $j("#main p.places i").remove()
    if(places_links.size()){
      var my = $j("#main p.places a."+$j.cookie("o").split(';')[3]);
      if(my.size()){
        my.click()
      }else if(places.test_redirect()){

      }else{
        $j("#main p.places").append("<i>(К&nbsp;сожалению, в Вашем городе эта услуга недоступна)</i>")
        places_links.removeClass("current")
        $j("#main div.places ul li.active").removeClass("active")
      }
      if(location.hash == '#static') location.hash = '#top';
    }
  },
  
  test_redirect: function() {
    if(!window.linked_pages) return false;
    var city, index, my_link;
    city = $j("#right .informer.city h4 strong").html();
    for(page_id in linked_pages){
      index = linked_pages[page_id].indexOf(city);
      if(index >= 0){
        my_link = $j("#link_pages_url .page-"+page_id);
        
        // static test
        if(location.href.match(/static$/)){
          var others_link = $j("#main p.places a.others")
          others_link.attr("href",my_link.attr("href"));
          others_link.html("Условия в городе " + city + "…")
          return true;
        }
        
        location.href = my_link.attr("href");
        return true;
      }
    }
    return false;
  }
}

var feedback = {
  init: function() {
    $j("#feedback .submit input").removeAttr("disabled");
    var validator = new Validation({
      form: "#feedback",
      fields: {
        "#feedback_name": [Validation.presense("Должно быть заполнено")],
        "#feedback_email": [Validation.presense("Должен быть заполнен"), Validation.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)],
        "#feedback_message": [Validation.presense("Должно быть заполнено")]
      }
    })
    $j("#feedback").submit(function() {
      if(!validator.validate()) return false;
      $j("#feedback .submit input").attr("disabled",'true');
      $j("#feedback_result").show().html("Сообщение отправляется…");
      $j.post("/eml.php",{name: $j("#feedback_name").val(), email: $j("#feedback_email").val(), message: $j("#feedback_message").val()}, function(data) {
        $j("#feedback_result").show().html(data);
      })
      return false;
    })
  }
}


var iefix6 = function() {
  $j("#breadcrumbs .line.expandable").hover(function() {
    $j(this).addClass("active")
    $j(this).find(".border-hack").width($j(this).width())
  },function() {
    $j(this).removeClass("active")
  })
  
  var inner = $j("#main .main-layout");
  var right = $j("#right")
  if(inner.height() < right.height()) inner.height(right.height())
  
  $j("#main table td:last-child").addClass("last-child")
  $j("#main table th:last-child").addClass("last-child")
}

var operafix = function(){
  $j("#breadcrumbs .line.expandable").hover(function() {},
  function() {
    var me = document.body
    me.style.display = 'none'
    setTimeout(function() {me.style.display = 'block' },1)
  })
}

var init = function() {
  $j("#breadcrumbs .line:first").removeClass("other").addClass("first")
  $j("#www13fru").attr("target","_blank")
  $j("#other_city_btn").click(function() {  	
  	location_dialog.open()
    return false;
  })
  
  if(navigator.userAgent.match(/MSIE 6/)){
    iefix6()
  } 
  if(navigator.userAgent.match(/MSIE 7/)){
    $j("#main table td:last-child").addClass("last-child")
  $j("#main table th:last-child").addClass("last-child")
  }
  
  if($j.browser.opera){
    operafix()
  }
  
  $j("#main .text p a[href^=http://]:not(:has(img))").addClass("ext-link").attr("target","_blank")
  var bad_links = $j("a[href^=bank/]")
  bad_links.each(function() { this.href = '/' + this.getAttribute('href') })
  if(bad_links.size() > 0){
    window.local_version = true;
    $j("a[href^=assets/]").each(function() { this.href = '/' + this.getAttribute('href') })
    $j("img[src*=assets]").each(function() { this.src = '/' + this.getAttribute('src') })
  }
  $j("#menu ul.icons a").each(function() {
    if(location.href == this.href){
      var img = $j(this).find("img");
      img.attr("src",img.attr("src").replace(/\.gif/,"-act.gif"));
    }
  })
  
  
  var o
  if(o = location.hash.match(/^#office(\d+)/)){
    $j(".offices tr").removeClass("bb")
    $j(".offices a[name=office"+o[1] + "]").parent().parent().addClass("bb")
  }
  
  currency.init_informer();
  // informer.init()
  city.init()
  search.init()
  places.init()
  
  if($j("#currency_table").size()) currency.build_table();
  
  
  if($j("#bankomats-select").size()){
    o = $j("#bankomats-select p.places a");
    o.click(function() {
      var me = $j(this);
      var val = me.text().replace(/,/,'');
      me.parent().parent().parent().find("table.bankomats tr td:first-child").each(function() {
        var p = $j(this).parent();
        if(val == "Все" || this.innerHTML.replace(/^\s+|\s+$/,'') == val) p.show()
        else p.hide()
      })
      return false;
    })
  }
  
  if(document.getElementById("feedback")) feedback.init();
}

$j(init)