/* Logo subtext animation */
var logo_subtext_curr = 0;
var logo_subtext = ['Объединяем участников арендного рынка', 
                    'Информационная поддержка арендной отрасли', 
                    'Повышаем эффективность арендного бизнеса', 
                    'Универсальное решение для арендной отрасли', 
                    'Помогаем развивать арендный бизнес'];
                    
function changeLogoSubtext() {
    if(logo_subtext_curr+1 >= logo_subtext.length) {
        logo_subtext_curr = 0;
    } else {
        logo_subtext_curr++;
    }
    $("#logo_subtext").fadeOut("slow", function() {
        $(this).text(logo_subtext[logo_subtext_curr]);
    });
    $("#logo_subtext").fadeIn("slow");
}

/* Translit */

var rusChars = new Array(
	'а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х','ч','ц','ш','щ','э','ю','\я','ы','ъ','ь',' ','  ');
var transChars = new Array(
	'a','b','v','g','d','e','jo','zh','z','i','j','k','l','m','n','o','p','r','s','t','u','f','h','ch','c','sh','csh','e','ju','ja','y','','','-','-');
var from = "";

// Generate content-item's name
function convert(){
    var from = $("form input[name='title']").val().replace(".htm", "").toLowerCase();
    var to = "";
    var len = from.length;
    var character, isRus;
    for(i=0; i < len; i++) {
        character = from.charAt(i,1);
        isRus = false;
        for(j=0; j < rusChars.length; j++) {
            if(character == rusChars[j]) {
            	isRus = true;
            	break;
            }
        }
        to += (isRus) ? transChars[j] : character;
    }
    to = to.replace (/[^a-z0-9\-]*/gm, '')
    to = to.replace (/[-]+/gm, '-')
    if(to.length) {
      $("form input[name='name']").val(to + ".htm");
    } else {
      $("form input[name='name']").val("");
    }
}

function browserLessThanIE7(){
	return (/MSIE ((5\\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
}

function browserIE7(){
	return (/MSIE ((7)|\\.7)/.test(navigator.userAgent) && navigator.platform == "Win32");
}

/* News Carousel */
var newsCarousel = {
	_obj: null,
	_timer: null,
	_len: 0,
	_curr: 0,
	_side: 'next',
	_offset: 8,

	Init: function() {
		var me = this;
		if(browserIE7()) {
			me._offset = 12;
		}
		me._obj = $('.news_carousel .news_carousel_list');
		me._len = me._obj.find('li').size();
		me._obj.css('width', 352*me._len+'px');
		me._obj.parent(".news_carousel").find(".gray_arrow_left").addClass("gray_arrow_left-off");
		if(me._len <= 5) {
		    me._obj.parent(".news_carousel").find(".gray_arrow_right").addClass("gray_arrow_right-off");
		}
		$('.news_carousel').hover(function() {
			clearTimeout(me._timer);
		}, function() {
			me.Timer();
		});
		me.Timer();
	},

	Timer: function() {
	  var me = this;
	  var seconds = 14;
	  var side = (me._side == 'next') ? 'right' : 'left';
	  clearTimeout(me._timer);
		me._timer = setTimeout(function() { 
	    $('.news_carousel .gray_arrow_' + side).trigger('click'); me.Timer();
	  }, seconds * 1000);
	},

	Next: function() {
		var me = this;
		if(me._len <= 1 || me._curr >= me._len-2) {
		    return false;
		}
		me._obj.parent(".news_carousel").find(".gray_arrow_left").removeClass("gray_arrow_left-off");
		me._curr++;
		me._obj.animate({ 
	        marginLeft: (-me._curr*352 + me._offset) + 'px'
	    }, 1000 );
	    if(me._curr >= me._len-2) {
			me._side = 'prev';
			me._obj.parent(".news_carousel").find(".gray_arrow_right").addClass("gray_arrow_right-off");
		}
	},

	Prev: function() {
		var me = this;
		if(me._len <= 1 || me._curr <= 0) {
		    return false;
		}
		me._obj.parent(".news_carousel").find(".gray_arrow_right").removeClass("gray_arrow_right-off");
		me._curr--;
		me._obj.animate({ 
	        marginLeft: (-me._curr*352 + me._offset) + 'px'
	    }, 1000 );
	    if(me._curr <= 0) {
			me._side = 'next';
			me._obj.parent(".news_carousel").find(".gray_arrow_left").addClass("gray_arrow_left-off");
		}
	}
};

/* Video Carousel */
var videoCarousel = {
	_obj: null,
	_timer: null,
	_len: 0,
	_curr: 0,
	_side: 'next',
	_offset: 17,

	Init: function() {
		var me = this;
		me._obj = $('.video_carousel_container .video_carousel_list');
		me._len = me._obj.find('li').size();
		me._obj.css('width', 139*me._len+'px');
		me._obj.parent(".video_carousel_container").find(".video_arrow_left").addClass("video_arrow_left-off");
		if(me._len <= 5) {
		    me._obj.parent(".video_carousel_container").find(".video_arrow_right").addClass("video_arrow_right-off");
		}
	},

	Timer: function() {
	  var me = this;
	  var seconds = 10;
	  var side = (me._side == 'next') ? 'right' : 'left';
	  clearTimeout(me._timer);
		me._timer = setTimeout(function() { 
	    $('.news_carousel .gray_arrow_' + side).trigger('click'); me.Timer();
	  }, seconds * 1000);
	},

	Next: function() {
		var me = this;
		if(me._len <= 1 || me._curr >= me._len-5) {
		    return false;
		}
		me._obj.parent(".video_carousel_container").find(".video_arrow_left").removeClass("video_arrow_left-off");
		me._curr++;
		me._obj.animate({ 
	        marginLeft: (-me._curr*139 + me._offset) + 'px'
	    }, 1000 );
		if(me._curr >= me._len-5) {
			me._side = 'prev';
			me._obj.parent(".video_carousel_container").find(".video_arrow_right").addClass("video_arrow_right-off");
		}
	},

	Prev: function() {
		var me = this;
		if(me._len <= 1 || me._curr <= 0) {
		    return false;
		}
		me._obj.parent(".video_carousel_container").find(".video_arrow_right").removeClass("video_arrow_right-off");
		me._curr--;
		me._obj.animate({ 
	        marginLeft: (-me._curr*139 + me._offset) + 'px'
	    }, 1000 );
        if(me._curr <= 0) {
			me._side = 'next';
			me._obj.parent(".video_carousel_container").find(".video_arrow_left").addClass("video_arrow_left-off");
		}
	}
};

/* Project Carousel */
var projectCarousel = {
	_obj: null,
	_timer: null,
	_len: 0,
	_curr: 0,
	_side: 'next',
	_offset: 25,
	_itemWidth: 0,

	Init: function() {
		var me = this;
		if(browserIE7()) {
			//me._offset = 12;
		}
		me._obj = $('.b-project-slider .ps__container');
		me._len = me._obj.find('.ps__frame-i').size();
		me._itemWidth = (me._obj.width()) ? me._obj.width() : me._itemWidth;
		me._obj.css('width', (me._itemWidth+20)*me._len+'px');
		me._obj.parent(".ps__frame").find(".ps__frame-left").addClass("ps__frame-left-off");
		if(me._len <= 1) {
		    me._obj.parent(".ps__frame").find(".ps__frame-right").addClass("ps__frame-right-off");
		}
		$('.ps__frame').hover(function() {
			clearTimeout(me._timer);
		}, function() {
			me.Timer();
		});
		me.Timer();
	},

	Timer: function() {
	  var me = this;
		var seconds = 9;
	  var side = (me._side == 'next') ? 'right' : 'left';
	  clearTimeout(me._timer);
		me._timer = setTimeout(function() { 
	    $('.b-project-slider .ps__frame .ps__frame-' + side).trigger('click'); me.Timer();
	  }, seconds * 1000);
	},

	Next: function() {
		var me = this;
		if(me._len <= 1 || me._curr >= (me._len-1)) {
		    return false;
		}
		me._obj.parent(".ps__frame").find(".ps__frame-left").removeClass("ps__frame-left-off");
		me._curr++;
		me._obj.animate({ 
	        marginLeft: (-me._curr*me._itemWidth + me._offset) + 'px'
	    }, 1000 );
		if(me._curr >= (me._len-1)) {
			me._side = 'prev';
			me._obj.parent(".ps__frame").find(".ps__frame-right").addClass("ps__frame-right-off");
		}
	},

	Prev: function() {
		var me = this;
		if(me._len <= 1 || me._curr <= 0) {
		    return false;
		}
		me._obj.parent(".ps__frame").find(".ps__frame-right").removeClass("ps__frame-right-off");
		var temp_offset = me._offset;
		me._curr--;
		temp_offset = (me._curr < 1) ? temp_offset : temp_offset;
		me._obj.animate({ 
	        marginLeft: (-me._curr*me._itemWidth + temp_offset) + 'px'
	    }, 1000 );
		if(me._curr <= 0) {
			me._side = 'next';
			me._obj.parent(".ps__frame").find(".ps__frame-left").addClass("ps__frame-left-off");
		}
	}
};

/* Initialize */

$(document).ready(function() {
  // Preload Tabs
  $("<img>").attr("src", "/b2b_inform/images/tabs/sprite_tab_bodies.png");
  
  // Flashing text in Logo
  if(logo_subtext.length > 0) {
      setInterval(changeLogoSubtext, 4000);
  }
  
  // Set image's subtext width (old formatting)
  if($(".b-content .con__img-wrapper").html()) {
      $(".b-content .con__img-wrapper .subtext").each(function() {
          var h2 = $(this).parent(".con__img-wrapper").parent("h2");
          if(h2.html()) {
              h2.after(h2.html()).remove();
          }
          $(this).css("width", ($(this).parent(".con__img-wrapper").width()-8)+"px");
      });
  }
  
  // Dropdown list on Search page
  if($(".b-dropset").html()) {
    $(".b-dropset a.select").click(function() {
      var obj = $(".b-dropset");
      if(obj.hasClass("off_dropset")) {
        obj.removeClass("off_dropset");
      } else {
        obj.addClass("off_dropset");
      }
      return false;
    });
  }
  
  // Project Carousel
  if($('.b-project-slider').html()) {
	  projectCarousel.Init();
	  $('.b-project-slider .ps__frame-right').bind('click', function() {
	    projectCarousel.Next();
	    return false;
	  });
	  $('.b-project-slider .ps__frame-left').bind('click', function() {
	    projectCarousel.Prev();
	    return false;
	  });
  }
  
  // News Carousel
  if($('.news_carousel').html()) {
	  newsCarousel.Init();
	  $('.news_carousel .gray_arrow_right').bind('click', function() {
	    newsCarousel.Next();
	    return false;
	  });
	  $('.news_carousel .gray_arrow_left').bind('click', function() {
	    newsCarousel.Prev();
	    return false;
	  });
  }
  
  // Video Carousel
  if($('.video_carousel_container').html()) {
	  videoCarousel.Init();
	  $('.video_carousel_container .video_arrow_right').bind('click', function() {
	    videoCarousel.Next();
	    return false;
	  });
	  $('.video_carousel_container .video_arrow_left').bind('click', function() {
	    videoCarousel.Prev();
	    return false;
	  });
  }
  
  // Auto translit content title in admin-module (pages, news, etc.)
  if($("form input[name='title']").parent("label").html()) {
      $("form input[name='title']").bind('keyup', function() {
	    convert();
	  });
  }
  
  // Lightbox for Weekphoto
  if($(".b-box .weeks_photo_img").html()) {
    $(".b-box .weeks_photo_img").lightBox({
	    imageLoading: '/b2b_inform/images/jq-plugins/lightbox-ico-loading.gif',
	    imageBtnClose: '/b2b_inform/images/jq-plugins/lightbox-btn-close.gif',
	    imageBtnPrev: '/b2b_inform/images/jq-plugins/lightbox-btn-prev.gif',
	    imageBtnNext: '/b2b_inform/images/jq-plugins/lightbox-btn-next.gif',
	    imageBlank: '/b2b_inform/images/jq-plugins/lightbox-blank.gif'
    });
    
    $(".b-box .box__bottom-link .ajax_link").lightBox({
	    imageLoading: '/b2b_inform/images/jq-plugins/lightbox-ico-loading.gif',
	    imageBtnClose: '/b2b_inform/images/jq-plugins/lightbox-btn-close.gif',
	    imageBtnPrev: '/b2b_inform/images/jq-plugins/lightbox-btn-prev.gif',
	    imageBtnNext: '/b2b_inform/images/jq-plugins/lightbox-btn-next.gif',
	    imageBlank: '/b2b_inform/images/jq-plugins/lightbox-blank.gif'
    });
  }
  
  // Rating alert
  if($(".b-box #js_rating_alert").html()) {
    $(".b-box #js_rating_alert input:checkbox").bind('change', function(e) {
	    if($(".b-box #js_rating_alert input:checked").size() > 5) {
	      $(e.target).removeAttr("checked");
	      alert("Вы можете проголосовать не более чем за 5 позиций.");
	    }
	  });
  }
});

function resizeOnMain() {
  // Resize height of News or Weekphoto blocks on Main page
  if($(".video_carousel_container").html()) {
    var newsBlock = $(".mc__content .h-grid:first");
    var rightBlocks = $(".mc__content .h-grid__r:first");
    var offsetHeight = newsBlock.height() - rightBlocks.height();
    if(offsetHeight > 0) {
      var rBL = rightBlocks.find(".b-box:last").find(".box__content");
      var rBLb = rBL.find(".box__bottom-link");
      rBL.height(rBL.height() + offsetHeight);
      rBLb.css("margin-top", (10+offsetHeight)+"px");
    } else if(offsetHeight < 0) {
      var mBl = newsBlock.find(".b-box:last").find(".box__content");
      var mBlb = mBl.find(".box__bottom-link");
      mBl.height(mBl.height() - offsetHeight);
      mBlb.css("margin-top", (6-offsetHeight)+"px");
    }
  }
}

