var stopspec = false;

function nextSpecOffer(){
  var marquee = $('div.roller-wrap');
  var pic = $('div.spec');
  marquee.children().removeClass('current');
  stopspec = true;
  marquee.animate({scrollLeft:marquee.children(":first").width()},{
    duration : "slow",
    complete : function(){
      var img = marquee.children().eq(0);
      img.remove();
      marquee.append(img);
      marquee.scrollLeft(0);

      marquee.children().eq(1).addClass('current');
      stopspec = false;
    }
  });
  pic.animate({scrollLeft:300},{
    duration : "slow",
    complete : function(){
      var img = pic.children().eq(0);
      img.remove();
      pic.append(img);
      pic.scrollLeft(0);
    }
  });
}

function prevSpecOffer(){
  var marquee = $('div.roller-wrap');
  var pic = $('div.spec');
  marquee.children().removeClass('current');
  stopspec = true;
  marquee.scrollLeft(marquee.children(":last").width()).children(":last").prependTo(marquee);
  pic.scrollLeft(300).children(":last").prependTo(pic);
  marquee.animate({scrollLeft:0},{
    duration : "slow",
    complete : function(){
      marquee.children().eq(1).addClass('current');
      stopspec = false;
    }
  });
  pic.animate({scrollLeft:0},{
    duration : "slow",
    complete : function(){
    }
  });
}


$(document).ready(function() {  
  /*$('form.spec-search-form span.cal input').each(function(){
    $(this).datepicker({
      dateFormat: 'dd.mm'
    });
  });
*/

  $('div.spec-roller').each(function(){

    $(this).hover(function(){$(this).addClass('show')},function(){$(this).removeClass('show')});
    
    $.preloadImages($(this).find('.roller-wrap a'));

    var specOfferInterval = setInterval(function (){
      nextSpecOffer();
    },3000);

    $(this).find('a.next').click(function(){
      if (!stopspec) {
        clearInterval(specOfferInterval);
        nextSpecOffer();
        specOfferInterval = setInterval(function (){
          nextSpecOffer();
        },3000);
      }
      return false;
    });

    $(this).find('a.prev').click(function(){
      if (!stopspec) {
        clearInterval(specOfferInterval);
        prevSpecOffer();
        specOfferInterval = setInterval(function (){
          nextSpecOffer();
        },3000);
      }
      return false;
    });
  });

  $('.tyr-offers-block').each(function(){    
    var $header = $(this).find('h5');
    var $link = $header.find('a');
    var text;
    var limit = 34;

    if ($header.height() > limit) {
      $link.attr('alt',$link.text()).attr('title',$link.text());
      text = $link.text().split(' ');
      var len = text.length;
      var acc = text[0];

      $link.text(text[0]);

      for (var i = 1; i < len; i++) {
        $link.text($link.text().substr(0, $link.text().length - 3) + ' ' + text[i] + '...');
        if ($header.height() > limit) {
          $link.text(acc + '...');
          return false;
        }
        acc += ' ' + text[i];
      }
    }
  });


  $('div.spec-off').css('height', $('div.spec-off ul').height()+'px');
  if ($.browser.msie && $.browser.version == '6.0')$('div.spec-off .b').css('bottom','-1px');
  $('form.spec-search-form span.cal').click(function(){
    $(this).children('input').datepicker('show');
  });

  $('form.spec-search-form a.extend').click(function(){
    $('form.spec-search-form').toggleClass('spec-opened');
    $(this).toggleClass('opened');
    $(this).closest('form').find('fieldset.extended').toggle();
    return false;
  });

  $('form.spec-search-form a.convert').click(function(){
    $(this).siblings('a.convert').removeClass('activated');
    $(this).addClass('activated');
    return false;

  });
  
  //document.onselectstart=new Function("return false");document.ondragstart=new Function("return false");

  $('ul.adds-options li a.ads-sec').click(function() {
	
		if ($(this).hasClass('cls')) {
				$(this).parent().parent().children('div.add-block-opt').show();
				$(this).addClass('opn');
				$(this).removeClass("cls");
				return false;
				} else {
					$(this).parent().parent().children('div.add-block-opt').hide();  
					$(this).addClass('cls');
					$(this).removeClass("opn");
					return false;
				}
			}
		)

		$('#tyr-s li a.sb').click(function() {
	
		if ($(this).hasClass('cls')) {
				$(this).parents('div.text-block').find('.spy-tyr').show();
				$(this).next('.str-b').attr('src','/images/strelka.gif');
				$(this).addClass('opn');
				$(this).removeClass("cls");
				return false;
				} else {
					$(this).parents('div.text-block').find('.spy-tyr').hide();  
					$(this).next('.str-b').attr('src','/images/strelka-d.gif');
					$(this).addClass('cls');
					$(this).removeClass("opn");
					return false;
				}
			}
		)

	$('.block-city-rolovers a.city-block-closer').click(function() {
    
		$(this).parent('.block-city-rolovers').find('.top-city-rolovers').hide();
		$(this).parent('.block-city-rolovers').find('.bottom-city-rolovers').hide();
		$(this).parent('.block-city-rolovers').find('.razv-city').show();
		$(this).parent('.block-city-rolovers').find('.city-block-opener').show();
		$(this).hide();
		return false;
			}
		)
	$('.block-city-rolovers a.city-block-opener').click(function() {
		$(this).parent('.block-city-rolovers').find('.razv-city').hide();
		$(this).parent('.block-city-rolovers').find('.top-city-rolovers').show();
		$(this).parent('.block-city-rolovers').find('.bottom-city-rolovers').show();
		$(this).parent('.block-city-rolovers').find('.city-block-closer').show();
		$(this).hide();
		return false;
			} 
		)
	$('div.psi').mouseover(function(){$(this).children('.bonaman-block').show();}).mouseout(function(){$(this).children('.bonaman-block').hide();});
	
	$('div.enter-partners-link a').click(function() {return true;});
	
  $('.with_converter a.convert').click(function(){

    var parent = $(this).parent();
    $('.convert', parent).removeClass('activated');
    
    from = $.trim($('.base_currency', parent).attr('rel'));
    to = $(this).attr('rel');
    $(this).addClass('activated');
    value = $.trim($('.base_currency', parent).text());

    //alert('from =' + from + ', to='+ to + ' nominal='+value);
    $('.current_currency', parent).html(getCurrencyNameCode(to).name);
    $('.current_price', parent).html(convertCurrency(from, to, value));
    return false;
  })

  $('.with_converter a.convert[rel="r"]').trigger('click');

  $('.separate-number').each(function(){
    $(this).text(addSeparator($(this).text()));
  })


  $('#pop_form_check_status').submit(function(){
    var form = $(this);
    $('#result_status').html('Идет запрос ...');
    $.ajax({
      type:     'POST',
      data:     form.serialize(),
      url:      form.attr('action'),
      success:  function(data){
        $('#result_status').show().html(data);
      }
      
    });
    return false;
  });
  
  
  $('#pop_check_status').click(function(){
      
      if ($('#pop_form_check_status').css('display') == 'none') {
        $('#pop_form_check_status').show();
        
        $('body').bind('click.status', function(e){
          if ($(e.target).parents('#pop_form_check_status').size() == 0 && e.target.id != 'pop_form_check_status') {
            $('#pop_form_check_status').hide();
            $('body').unbind('click.status');
          }
        });
        
        $('#pop_form_check_status input:last').focus();
        
      } else {
        $('#pop_form_check_status').hide();
      }
      return false;
    });


  $('.red-btn-fluid .zakaz-name').click(function(){
    var $btn = $('.zakaz-open');
    var $this = $(this);
    if ($btn.css('display') == 'none') {
      $('.red-btn-fluid').addClass('red-btn-opn');
      $('body').bind('click.btn', function(){$this.trigger('click')});     
    } else {
      $('.red-btn-fluid').removeClass('red-btn-opn');
      $('body').unbind('click.btn');
    }
    return false;
  });

  $('a[href="http://online.bonaman.ru/masterwebstandart/ServiceStatus.aspx"]').click(function(){
    $('html,body').animate({scrollTop: $(document).height()}, 500);
    $('#pop_check_status').click();
    return false;
  });
  

       /* directions paginator */

  if ($('#directions-wrp').size() > 0) {
    var prev_page  = 1;
    var cur_page = 1;
    var directions_per_page = parseInt($('#directions_per_page').text());
    directions_per_page = directions_per_page ? directions_per_page : 5;
    var pageHeight = 225 * directions_per_page;


    var showPage = function () {
      var index;
      var all = $('#dir-paginator a').size() - 2;

      if ($(this).hasClass('current')) return false;

      $('#dir-paginator a').removeClass('disabled');

      if ($(this).text() != '') {
        cur_page = parseInt($(this).text());

        $('#directions-wrp').animate({scrollTop: (cur_page - 1) * pageHeight}, 500, '', function(){$('html').animate({scrollTop: 200}, 500)} );
        $(this).siblings().removeClass('current');
        $(this).addClass('current');
        index = $(this).prevAll().size() - 1;
      } else {
        index = $('#dir-paginator a.current').prevAll().size() - 1;

        if ($(this).hasClass('larr') && index > 0) {
          $('#dir-paginator a').eq(index).trigger('click');
          index--;
        } else if ($(this).hasClass('rarr') && index < all - 1) {
          $('#dir-paginator a').eq(index + 2).trigger('click');
          index++;
        }

      }

      if (index == 0) {$('#dir-paginator a.larr').addClass('disabled');}
      if (index == all - 1) {$('#dir-paginator a.rarr').addClass('disabled');}

      return false;
    }

    function initPaginator()
    {      
      $('#dir-paginator').empty();
      $('#directions-wrp').css('height', 'auto');
      var h = $('#directions-wrp').height();
      /*if ($.browser.opera && h > pageHeight) h = h + 814;*/
      var pages = h/pageHeight;


      $('#directions-wrp').height(pageHeight);

      if (pages < 1) return false;

      $('#dir-paginator').append('<a id="sw-prew" class="larr disabled" href="#"></a>');
      for (i = 0; i <= pages; i++) {
        page = i+1;        
        if (page == cur_page) li = '<a class="current" href="#">' +page + '</a>';
        else li = '<a href="#">' + page + '</a>';
        $('#dir-paginator').append(li);
      }
      $('#dir-paginator').append('<a id="sw-next" class="rarr" href="#"></a>');
      
      $('#dir-paginator a').click(showPage);

    }

    initPaginator();
  }
  
  
  
  var stopit = false;
  $('div.spec-off li a').mouseover(function(e){

    var obj = $(this);

    e.stopPropagation();

    if (obj.prev('img.pic').css('display') == 'none') 
    if (!stopit) {
      stopit = true;

      var pic = obj.prev('img.pic');

      obj.closest('ul').find('li img.pic:visible').slideUp(150)
      pic.slideDown(150, function(){
        stopit = false
      });      
    }
  });

  $('div.spec-off ul').mouseleave(function(e){
    if ($('div.spec-off').find('li img.pic:visible').parent().prevAll().length > 0)
    if (!stopit) {
      stopit = true;
      var pic = $('div.spec-off').find('li').eq(0).find('img.pic');

      $('div.spec-off').find('li img.pic:visible').slideUp(150,function(){
        pic.slideDown(150, function(){stopit = false});
      });
    }
  });


});

function showFullText(obj) {
  var text = $(obj).parents('div.bonaman-block-bg').children('div.bonamania_full_text').html();
  $('#bonamania-text').html(text);
  var targetOffset = $('#bonamania-text').offset().top + 200;
  $('html,body').animate({scrollTop: targetOffset}, 500);
  return false;

}


function getCurrencyNameCode(str)
{
  var c_name, c_code;
  switch (str) {
    case 'р': case 'р.': case 'руб.': case 'r':
     c_name = 'р.';
     c_code = 'RUB';
    break;
    case '$': case 'd':
      c_name = '$';
      c_code = 'USD';
    break;
    case 'e': case '€':
      c_name = '€';
      c_code = 'EUR';
    break;
  }
  return {name: c_name, code: c_code};
}


function convertCurrency(from, to, nominal)
{
  var from_code = getCurrencyNameCode(from).code;
  var to_code = getCurrencyNameCode(to).code;
  var nominal = removeCommasSpaces(nominal);
  var rate_factor = parseFloat(rates[from_code]/rates[to_code]);
  
  if (isNaN(rate_factor)) rate_factor = 1;
  var output = Math.round(parseFloat(nominal * rate_factor));

  
  return addSeparator(output);
}

// приводит отбитое число к номральному виду
function removeCommasSpaces(aNum)
{
  // remove commas
  aNum = aNum.replace(/,/g,"");

  // remove spaces
  aNum = aNum.replace(/\s/g,"");

  return aNum;
}

// отбивает тысячи
function addSeparator(nStr)
{
	var separator = ' ';
  nStr += '';
  // на случай десятичной части
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + separator + '$2');
	}
	return x1 + x2;
}

// pluralForm($n, "письмо", "письма", "писем");
function pluralForm($n, $form1, $form2, $form5)
{
  $n = Math.abs($n) % 100;
  $n1 = $n % 10;
  if ($n > 10 && $n < 20) return $form5;
  if ($n1 > 1 && $n1 < 5) return $form2;
  if ($n1 == 1) return $form1;
  return $form5;
}

/*  styled select */

var selectWidth = "190";


/* No need to change anything after this */


document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');

var Custom = {
  init: function() {
    var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
    for(a = 0; a < inputs.length; a++) {
      if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
        span[a] = document.createElement("span");
        span[a].className = inputs[a].type;

        if(inputs[a].checked == true) {
          if(inputs[a].type == "checkbox") {
            position = "0 -" + (checkboxHeight*2) + "px";
            span[a].style.backgroundPosition = position;
          } else {
            position = "0 -" + (radioHeight*2) + "px";
            span[a].style.backgroundPosition = position;
          }
        }
        inputs[a].parentNode.insertBefore(span[a], inputs[a]);
        inputs[a].onchange = Custom.clear;
        if(!inputs[a].getAttribute("disabled")) {
          span[a].onmousedown = Custom.pushed;
          span[a].onmouseup = Custom.check;
        } else {
          span[a].className = span[a].className += " disabled";
        }
      }
    }
    inputs = document.getElementsByTagName("select");
    for(a = 0; a < inputs.length; a++) {
      if(inputs[a].className == "styled") {
        option = inputs[a].getElementsByTagName("option");
        active = option[0].childNodes[0].nodeValue;
        textnode = document.createTextNode(active);
        for(b = 0; b < option.length; b++) {
          if(option[b].selected == true) {
            textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
          }
        }
        span[a] = document.createElement("span");
        span[a].className = "select";
        span[a].id = "select" + inputs[a].name;
        span[a].appendChild(textnode);
        inputs[a].parentNode.insertBefore(span[a], inputs[a]);
        if(!inputs[a].getAttribute("disabled")) {
          inputs[a].onchange = Custom.choose;
        } else {
          inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
        }
      }
    }
    document.onmouseup = Custom.clear;
  },
  
pushed: function() {
    element = this.nextSibling;
    if(element.checked == true && element.type == "checkbox") {
      this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
    } else if(element.checked == true && element.type == "radio") {
      this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
    } else if(element.checked != true && element.type == "checkbox") {
      this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
    } else {
      this.style.backgroundPosition = "0 -" + radioHeight + "px";
    }
  },
 
 check: function() {
    element = this.nextSibling;
    if(element.checked == true && element.type == "checkbox") {
      this.style.backgroundPosition = "0 0";
      element.checked = false;
    } else {
      if(element.type == "checkbox") {
        this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
      } else {
        this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
        group = this.nextSibling.name;
        inputs = document.getElementsByTagName("input");
        for(a = 0; a < inputs.length; a++) {
          if(inputs[a].name == group && inputs[a] != this.nextSibling) {
            inputs[a].previousSibling.style.backgroundPosition = "0 0";
          }
        }
      }
      element.checked = true;
    }
  },

  clear: function() {
    inputs = document.getElementsByTagName("input");
    for(var b = 0; b < inputs.length; b++) {
      if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
        inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
      } else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
        inputs[b].previousSibling.style.backgroundPosition = "0 0";
      } else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
        inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
      } else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
        inputs[b].previousSibling.style.backgroundPosition = "0 0";
      }
    }
  },

  choose: function() {
    option = this.getElementsByTagName("option");
    for(d = 0; d < option.length; d++) {
      if(option[d].selected == true) {
        document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
      }
    }
  }
}
window.onload = Custom.init



//Скрипт очищающий форму от текста при нажатии на нее курсора 
function doClear(theText) { if (theText.value == theText.defaultValue) { theText.value = "";  } }
function doDefault(theText) { if (theText.value == "") { theText.value = theText.defaultValue;  } }

function doClearp(theText) { if (theText.value == theText.defaultValue) { theText.value = ""; $('#label-pass').css('visibility','hidden'); } }
function doDefaultp(theText) { if (theText.value == "") { theText.value = theText.defaultValue; $('#label-pass').css('visibility','visible'); } }
/*
function doClear(theText) { if (theText.value == theText.defaultValue) { theText.value = ""; $('#label-pass').css('display','none'); } }
*/



$.preloadImages = function(images) {
  images.each(function(){
    $("<img>").attr("src", $(this).attr('href'));
  });
};








