//----------------------------- NEW PART -----------------------------------
/* open ajax forms - work */
function windowWorkSize(){
var wwSize = new Array();
	if (window.innerHeight !== undefined) wwSize= [window.innerWidth,window.innerHeight]    // для основных браузеров
		else	
			{	// для "особо одарённых" (ИЕ6-8)
				wwSizeIE = (document.body.clientWidth) ? document.body : document.documentElement;
				wwSize= [wwSizeIE.clientWidth, wwSizeIE.clientHeight-1800];
				
			};
	return wwSize;
};
//wsize = windowWorkSize();
$(".ajax-windows-form").live("click", function(){
	wsize = windowWorkSize();
	ElemHei =  $('#simplemodal-container').attr('offsetHeight');
	//alert($('#simplemodal-container').attr('offsetHeight'));
	var _this   = $(this);
  var  formid = _this.attr("formid");
	var  type   = _this.attr("type");
  var _params = _this.attr("params");
	var _modal = $.modal("<div class='webform-loader'>Пожалуйста, подождите!<br/><img src='/images/ajax/webform.gif' /></div>", {
                          containerCss: 
                              {
                                width:  "200px",
                                height: "140px",
                                border: "5px ridge #990098",
																position: "absolute"
                              },
                          modal: (type=="modal"),
                          position: [""+wsize[1]/2 - 694/2 + (document.body.scrollTop || document.documentElement.scrollTop) + "px"]
                         });
                         
  $.ajax({
    type: 'GET',
    url:  '/dcontent/?action=form&id='+formid+(_params!=""?"&params="+_params:""),
    dataType: "html",
    cache: false,
    success: function(data) {
      //alert();
      var _parent = $(".webform-loader").parent();
      $(".webform-loader").remove();
      _parent.append(data);
      var _obj = _parent.parents("#simplemodal-container");
      _obj.css({
                width:    ($.browser.msie && $.browser.version.substr(0,1)<7)?"1px":"auto",
                height:   "auto",
                position: "absolute"
              });
      _obj.css("left", (1 - _obj.width()/$(window).width())*50+"%");

      var jqForm = _obj.find(".master-form form");
      /* ajax event for form */
      jqForm.ajaxForm({
        dataType: "html",
        success: ajaxFormResponse
      });
      
      /* init radio buttons, and set first button as default */
      var allOneVariants = jqForm.find("input.switch-variant");
      for(var i=0;i<allOneVariants.length;i++)
      {
        var variants = allOneVariants.eq(i).parents("form div.border").find("input.switch-variant");
        
        if(variants.attr("name") == "switch-variant")
        {
          variants.eq(0).attr("checked",true).trigger("click");
          variants.attr("name", variants.attr("name")+i);
        }
      }
    }
  });
  return false;
});
function ajaxFormResponse(responseText, statusText, xhr, $form)
{
	$form.parents(".master-form").html(responseText).find(".master-form form").ajaxForm({
        dataType: "html",
        success: ajaxFormResponse
      });
  $("#simplemodal-container").css('top',wsize[1]/2 - 200/2 + (document.body.scrollTop || document.documentElement.scrollTop) + "px")
  /* validator form master-form(just check for empty fields)*/
  //$("#simplemodal-container").css("top","40%");
	$(".master-form form").live("submit", function(){
		return false;
  });
}

/* form's elements control and cheking */
$("div.master-form input.switch-variant").live("click", function(){
  /* get all block with from's elements */
  $(this).parents("form div.border").find("div.form-row div").find("select, input").attr("disabled", true);
  $(this).parents("form div.form-row").find("select, input").attr("disabled", false);
})

/* cherck for each fields - about which type use */
var _cn_timer = null;
$("input.check-to-numeric").live("keyup", function(){
  var _this = $(this);
  var _val  = _this.val();
  var re = /\D/;
  if (re.test(_val))  
  {
    _this.val(_val.replace(/\D/g, ""));
    if(!_this.next().hasClass("d-error-message"))
    {
      var _error = $("<small class='d-error-message' style='margin-left:-"+(parseInt(_this.width())+3)+"px;margin-top:"+(parseInt(_this.height())+3)+"px;'>Вы ввели не число</small>");
      _this.after(_error);
      
      //clearTimeout(_cn_timer);
      _cn_timer = setTimeout(function () {
                     $("small.d-error-message").animate({
                        opacity: 0.0
                      }, 300, function() {
                        $("small.d-error-message").remove();
                      });
                }, 1000);
    }
  }
});

$(document).ready(function() {
  
  /* init addedToBasket window*/
  $('body').append($('<div class="window-added-goods"><a href="javascript:void(0);" class="close"></a><div class="info">Товар добавлен в корзину</div><div class="order"><a href="/private/basket/">Оформить покупку</a></div></div>'));
  
  /* close addedToBasket window*/
  $("div.window-added-goods a.close").live("click", function(){
    $(this).parent().hide();
  });

  $("#registration-agree-submit").attr("disabled", "disabled");
  /* registartion agree with license check */
  $("#registration-agree-checkbox").live("change", function(){
    if(this.checked == true)
      $("#registration-agree-submit").removeAttr("disabled");
    else
      $("#registration-agree-submit").attr("disabled", "disabled");
  })
});

var arr_pic_sizes = null;
function getCorrectedSize(jq_pic, size, correct)
{
  if(arr_pic_sizes == null)
    arr_pic_sizes = $.parseJSON(my_pic_sizes);
  
  if(arr_pic_sizes[size] == undefined || arr_pic_sizes[size] == null)  
    return false;
    
  var result = {
    width:  jq_pic[0].naturalWidth,
    height: jq_pic[0].naturalHeight,
    style:        "",
    marginTop:    0,
    marginBottom: 0
  };
  
  if(jq_pic[0].naturalHeight > arr_pic_sizes[size]['h'])
  {
    var c = arr_pic_sizes[size]['h'] / jq_pic[0].naturalHeight;
    result.height = arr_pic_sizes[size]['h'];
    result.width  = Math.floor(c * jq_pic[0].naturalWidth);
  }
 
	if(result.width > arr_pic_sizes[size]['w'])
  {
		var c = arr_pic_sizes[size]['w'] / result.width;
    result.width  = arr_pic_sizes[size]['w'];
    result.height = Math.floor(c * result.height);
  }
  
  if(correct == true)
  {
    var _div_height = arr_pic_sizes[size]['h'] - result.height;
    if(_div_height > 0)
    {
      result.marginTop    = Math.ceil(_div_height/2);
      result.marginBottom = Math.floor(_div_height/2);
      result.style        = "margin-top:"+result.marginTop+"px;margin-bottom:"+result.marginBottom+"px;";
    }
  }
  
  //console.log(result);
  return result;
} // -= function getCorrectedSize =-

$(document).ready(function() {

  refreshIcons(false);
  $.ajax({
    type: 'GET',
    url:  '/dcontent/?action=maingeneralstatus',
    dataType: "json",
    cache: false,
    success: refreshIcons
    });
   
  /* 3 goods icons control */
  $("a.goods-btn-basket").live("click", function(){
    var _this = $(this);
    if(getBlockStatus(_this)) return false;
    showILoader($(this));
    
    $.ajax({
      type: 'GET',
      url:  '/dcontent/?action=addtobasket&id='+goodsID($(this).parents(".tbl-goods")),
      dataType: "json",
      cache: false,
      success: refreshIcons
    });
    $.ajax({
      type: 'GET',
      url:  'http://www.googleadservices.com/pagead/conversion/1013764152/?label=JOV5CIDa_gIQuKCz4wM&guid=ON&script=0',
      dataType: "html",
      cache: false,
    });
    return false;
  });
  
  $("a.goods-btn-compare").live("click", function(){
    var _this = $(this);
    if(getBlockStatus(_this)) return false;
    showILoader($(this));
    
    $.ajax({
      type: 'GET',
      url:  '/dcontent/?action=addcompare&id='+goodsID($(this).parents(".tbl-goods")),
      dataType: "json",
      cache: false,
      success: refreshIcons
    });
    return false;
  });
  $("a.goods-btn-fav").live("click", function(){
    var _this = $(this);
    if(getBlockStatus(_this)) return false;
    showILoader($(this));
    
    $.ajax({
      type: 'GET',
      url:  '/dcontent/?action=addfav&id='+goodsID($(this).parents(".tbl-goods")),
      dataType: "json",
      cache: false,
      success: refreshIcons
    });
    return false;
  });

	// hack for IE
	$('#basket_window a').eq(0).click(function() {
		$(this).parent().remove();
		return false;
	});
	
}); // -= $(document).ready(function() { =-

/*
	------------------------------- START - BLOCK FOR CONTROL BASKET ----------------------------------------------
*/
/*
  Show/hide loader on icon
*/
function showILoader(jqIcon)
{
  jqIcon.css("cursor", "wait");
  if($.browser.msie && $.browser.version.substr(0,1)<7) {}
  else {
    jqIcon.hide();
    jqIcon.after($("<img src='/images/ajax/icon-mini.gif' alt='' class='"+jqIcon.attr("class")+"' style='float:left' />"));
  }
}
function hideILoader(id, action)
{
  if(id == undefined || !(id > 0)) return false;
  $(".p-"+id+" div.icons a.goods-btn-"+action).css("cursor","pointer").show();
  $(".p-"+id+" div.icons img.goods-btn-"+action).remove();
}
/*
  get block-status for link
*/
function getBlockStatus(jqIcon)
{
  return (jqIcon.css("cursor")=="wait");
}
/*
  get goods id from goods-table
*/
function goodsID(goodsTable)
{
  return goodsTable.attr("class").match(/p-(\d*)/i)[1];
}
/*
  refreshs status icons from array
  Данные лушче держать в куках!!!!
*/
function refreshIcons(d)
{
  if(d == false || d==null || d==undefined)
  {
    var d = {
      cntBasket:    $.cookie('basket-caption'),
      itemsBasket:  ($.cookie('basket-ids') != null)?$.cookie('basket-ids').split(/,/ig):(new Array()),
      cntCompare:   $.cookie('compare-caption'),
      itemsCompare: ($.cookie('compare-ids')!= null)?$.cookie('compare-ids').split(/,/ig):(new Array()),
      cntFav:       $.cookie('fav-caption'),
      itemsFav:     ($.cookie('fav-ids')!=null)?$.cookie('fav-ids').split(/,/ig):(new Array())
    };
  }
  
  /* ajax loaders */
  if(d.cntBasket  != undefined) 
  { 
    $.cookie('basket-caption', d.cntBasket);
    $.cookie('basket-ids',     d.itemsBasket);
    hideILoader(d.id, "basket");  
    changeIcons(d.itemsBasket, "recycle");  
    addedToBasket(d.id);
  }
  
  if(d.cntCompare != undefined) 
  { 
    $.cookie('compare-caption', d.cntCompare);
    $.cookie('compare-ids',     d.itemsCompare);
    hideILoader(d.id, "compare"); 
    changeIcons(d.itemsCompare, "compare"); 
  }
  
  if(d.cntFav     != undefined) 
  {
    $.cookie('fav-caption', d.cntFav);
    $.cookie('fav-ids',     d.itemsFav);
    hideILoader(d.id, "fav");
    changeIcons(d.itemsFav, "heart");
  }
  
  if(d.cntBasket != "" && d.cntBasket != undefined)
  {
    $("#id-basket-count-goods").html(d.cntBasket);
    $("#id-basket-count-goods").show();
  } else 
    if(d.cntBasket != undefined)
      $("#id-basket-count-goods").html("<div>Ваша корзина пуста</div>");
    
  if(d.cntCompare != "" && d.cntCompare != undefined)
  {
    $("#id-compare-count-goods").html(d.cntCompare);
    $("#id-compare-count-goods").show();
  } else
    if(d.cntCompare != undefined)
      $("#id-compare-count-goods").hide();
  
  if(d.cntFav != "" && d.cntFav != undefined)
  {
    $("#id-favority-count-goods").html(d.cntFav);
    $("#id-favority-count-goods").show();
  } else
    if(d.cntFav != undefined)
      $("#id-favority-count-goods").hide();
      
  /* cheking - maybe need user set information */
  if(d.userAuth != undefined && d.userAuth != "")
    $('#auth').html(d.userAuth);
} /* function end*/

/* deactivate/activate icon*/
function changeIcons(arr, action)
{
  if(arr != undefined)
  {
    $(".tbl-goods div.icons a."+action+"-active-icon").removeClass(action+"-active-icon").addClass(action+"-noactive-icon");
    for(var i=0;i<arr.length;i++)
      $(".p-"+arr[i]+" div.icons a."+action+"-noactive-icon").removeClass(action+"-noactive-icon").addClass(action+"-active-icon");
  }
}
/* 
	window for go to basket and make order 
*/
var saveAddTOBasketTimer = null;
function addedToBasket(pid)
{
  if(pid != undefined)
  {
    $("div.window-added-goods").css({
                                  top:      $(".p-"+pid+" div.icons").offset().top  + "px",
                                  left:     $(".p-"+pid+" div.icons").offset().left + "px",
                                  display: "block"
                                });
    
    setTimeout(function(){
                $("div.window-added-goods").hide(); 
              }, 5000);
  }
}
/*
	------------------------------- END - BLOCK FOR CONTROL BASKET ----------------------------------------------
*/

//----------------------------- END of NEW PART -----------------------------------

"use strict";
/*global $, window, console, alert, deliveryPrice*/
var idxsumm = 0;
var switchIndex = false;
/**
 * Format string
 * Example: "Hello, {0}".format("world");
 * @return string
 */
String.prototype.format = function () {
  var pattern = /\{\d+\}/g;
  var args = arguments;

  return this.replace(pattern, function (capture) {
    return args[capture.match(/\d+/)];
  });
};

function formatPrice(value) {
  var digits = value.toString().split('').reverse();
  value = [];
  for (var i = 1; i <= digits.length; i += 1) {
    value.push(digits[i - 1]);
    if (i % 3 === 0 && i !== digits.length + 1) {
      value.push(' ');
    }
  }
  return value.reverse().join('');
}
function getNumber(num, w1, w2, w3) {
  num += '';
  var last_char = num.charAt(num.length - 1);
  var w_res = w3;

  if (num >= 11 && num <= 14) {
    w_res = w3;
  } else if (last_char === 1) {
    w_res = w1;
  } else if (last_char >= 2 && last_char <= 4) {
    w_res = w2;
  }

  return num + '&nbsp;' + w_res;
}

function parseParam(value, key) {
  var re = new RegExp(key + '-(\\S*)');
  var match = value.match(re);
  return match ? match[1] : null;
}

function getParam($el, name, use_id) {
  var attr = typeof(use_id) !== 'undefined' ? 'id' : 'class';
  return parseParam($el.attr(attr), name);
}
function debug(message) {
  try {
    console.log(message);
  } catch (e) {
    alert(message);
  }
}
var Application = {
  init: function () {
    this.bindEvents();
    this.UI();
  },
  params: {
    guruPriceMin: 1000,
    guruPriceMinDef: 2000,
    guruPriceMax: 50000,
    guruPriceMaxDef: 50000,

    guruDiagonalMin: 3,
    guruDiagonalMinDef: 21,
    guruDiagonalMax: 108,
    guruDiagonalMaxDef: 69,

    goodsCarouselCount: 3,
    goodsCarouselItemWidth: 220
  },
  bindEvents: function () {
    $('.expander-name, .expander a.img:first-child').live('click', function () {
      $(this).parent().find('.expander-block').toggle();
      
      if($(this).parent().find('.expander-block')[0].style.display == "none")
      {
        $(this).parent().find('.expander-block').find('input').attr("disabled", true);
        $(this).parent().find('.expander-block').find('select').attr("disabled", true);
      }
      else
      {
        $(this).parent().find('.expander-block').find('input').removeAttr("disabled");
        $(this).parent().find('.expander-block').find('select').removeAttr("disabled");
      }
        
      $(this).parent().find('a.img:first-child').toggleClass("expand collapse");
      return false;
    });

    //guru
    $("#guru-price-from, #guru-price-to").live("change", function () {
      setTimeout(function () {
        $("#slider-price").trigger('onSet');
      }, 100);
    });
    
    $("#guru-diagonal-from, #guru-diagonal-to").live("change", function () {
      setTimeout(function () {
        $("#slider-diagonal").trigger('onSet');
      }, 100);
    });
    
    $("#guru-price-from").live("change", function () {
      var val = parseInt($(this).val(), 10) || Application.params.guruPriceMin;
      var toValue = parseInt($("#guru-price-to").val(), 10) || Application.params.guruPriceMax;
      if (val < Application.params.guruPriceMin) {
        val = Application.params.guruPriceMin;
      } else if (val > toValue || val > Application.params.guruPriceMax) {
        val = toValue;
      }
      $(this).val(val);
    });
    $("#guru-price-to").live("change", function () {
      var val = parseInt($(this).val(), 10) || Application.params.guruPriceMax;
      var toValue = parseInt($("#guru-price-from").val(), 10) || Application.params.guruPriceMin;
      if (val > Application.params.guruPriceMax) {
        val = Application.params.guruPriceMax;
      } else if (val < toValue || val < Application.params.guruPriceMin) {
        val = toValue;
      }
      $(this).val(val);
    });
    
    $("#guru-diagonal-from").live("change", function () {
      var val = parseInt($(this).val(), 10) || Application.params.guruDiagonalMin;
      var toValue = parseInt($("#guru-diagonal-to").val(), 10) || Application.params.guruDiagonalMax;
      if (val < Application.params.guruDiagonalMax) {
        val = Application.params.guruDiagonalMax;
      } else if (val > toValue || val > Application.params.guruDiagonalMax) {
        val = toValue;
      }
      $(this).val(val);
    });
    $("#guru-diagonal-to").live("change", function () {
      var val = parseInt($(this).val(), 10) || Application.params.guruDiagonalMax;
      var toValue = parseInt($("#guru-diagonal-from").val(), 10) || Application.params.guruDiagonalMin;
      if (val > Application.params.guruDiagonalMax) {
        val = Application.params.guruDiagonalMax;
      } else if (val < toValue || val < Application.params.guruDiagonalMin) {
        val = toValue;
      }
      $(this).val(val);
    });
    //!guru

    
    //popups
    //$(".product-img a#cbox, #goods-imgs #slider-preview a").colorbox({
		$(".product-img a#cbox, #slider-preview a").colorbox({
			width: "950px",
			close: "", 
			scrolling: false, 
			opacity: "0.75",
			//html:$("#product-popup").html()
			onComplete:function()
			{
				if ($(this).attr("id").search(/prev\d+/)!=-1)
				{
					$(".overview .pr").removeClass("active");
					$("#"+$(this).attr("id")).addClass("active");
					$("#big img, #viewer img").attr("src",$(this).children().attr("src")).attr("width",$(this).attr("wwidth")).attr("height",$(this).attr("hheight"));
				}
        $("#popup-content-3d_model .popup_3d .box").html($("#tab-3dmodel").html());
        if($("#popup-content-3d_model .popup_3d .box #model_").size() > 0 || $("#popup-content-3d_model .popup_3d .box #MTD_PRODUCT").size() > 0) $("#Model3d_p").show();
			}
		});

    $('#popup-images a').live('click', function (){
      $("#popup-images li").removeClass('active');
      var $a = $(this).parent().addClass('active').find('a');
      $("#popup-image").html($('<img />').attr('src', $a.attr('href')).attr({width: $a.attr('wwidth'), height: $a.attr('hheight')}) );
      return false;
    });
    $('#popup-image img').live('click', function () {
      $.fn.colorbox.close();
    });
		//!popups

    //tooltip
    $('.tooltip tr').live('mouseenter', function () {
      var dimension = $(this).offset();
      var leftOffset = (getParam($(this).closest('table'), 'type') === 'left') ? -245 : 550;
      $(this).find(".product-info").css({ "left": dimension.left + leftOffset, "top": dimension.top - 3 }).show();
    }).live('mouseleave', function () {
      $(this).find('.product-info').hide();
    });

    //tabs
    $('#novelty ul a').live('click', function () {
      //#########
      $("#novelty li.active").removeClass('active');
      var index = $(this).parent().addClass('active').index();
      $('#novelty-tabs .novelty-tab').removeClass('visible').eq(index).addClass('visible');
      
      var $tab = $('.novelty-tab').filter('.visible');
      var $goods = $tab;
      var count = $goods.find('.item').length;
      
      if(count > 3)
        {
          var index = $goods.find('.item').not('.not-visible').last().index();
          if (index === count - 1) {
            $('#novelty-tabs .type-right').addClass('arrow-right-noactive').removeClass('arrow-right-active');
          } else {
            $('#novelty-tabs .type-right').addClass('arrow-right-active').removeClass('arrow-right-noactive');
          }
          if (index + 1 - Application.params.goodsCarouselCount === 0) {
            $('#novelty-tabs .type-left').addClass('arrow-left-noactive').removeClass('arrow-left-active');
          } else {
            $('#novelty-tabs .type-left').addClass('arrow-left-active').removeClass('arrow-left-noactive');
          }
          
          switchIndex = true;
          
          
          $('#novelty-tabs .arrow').show();  
        }
      else
        $('#novelty-tabs .arrow').hide();
      
    });

    //recycle
    $("#productsinrecycle span").live('click', function () {
    });
    
    $("#productsinrecycle .count input").live("keypress", function (e) {
    });
    
    $("#productsinrecycle .count input").live('change, keyup', function () {
    });
    
    $("input[name=deliverytype]").live('change', function () {
    });
    //order
    $('.add-address').live('click', function () {
    });

    $('.remove-address').live('click', function () {
    });
    
    // Доставка
    $("#courier-delivery").live('onchange', function() {
    });
	
    //personal office order
    $('#tab-pastpurchase .arrows a').live('click', function () {
      var tr = $(this).parent().parent().next();
      if (tr.hasClass('expandable')) {
        tr.toggleClass('hidden-row visible-row');
        $(this).toggleClass('expand collapse');
      }
      return false;
    });

    //goods carousel - new version
    var offsetCounter = 0;
    $('#novelty-tabs .arrow').live('click', function () {
      var type = getParam($(this), 'type');
      var $tab = $('.novelty-tab').filter('.visible');
      
      // if not load data - loading their
      var vsid = $tab.attr('vsid')
      if(parseInt(vsid) > 0)
      {
        var _this = $(this);
        _this.css("cursor","wait");
        //console.log(location);
        $.ajax({
          url: '/dcache/'+location.host+location.pathname+'new_goods_'+vsid+'.0.html',
          success: function(data) {
                    $tab.find(".precache").eq(0).after(data);
                    $tab.find(".precache").remove();
                    $tab.attr('vsid','0');
                    refreshIcons(false);
                    _this.css("cursor","pointer");
                    _this.trigger("click");
                  },
					error: function(jqXHR, textStatus, errorThrown){
            _this.css("cursor","pointer");
					}
        });
        return false;
      }
      
      var $goods = $tab.find('.novelty-goods');
      var count = $goods.find('.item').length;

			// compatibility with old version
      var $goodsDesc = $tab.find('.novelty-goods-descr');
			
      var reStyle = function (index) 
      { 
        var start = index - 2;
        var style = function (i) {
          if (i >= start && i <= index) {
            $(this).removeClass('not-visible');
          } else {
            $(this).addClass('not-visible');
          }
					
					if($goodsDesc.length > 0)
					{
						if (i === (start + 1)) {
							$(this).addClass('center-item');
						} else {
							$(this).removeClass('center-item');
						}
					}
					
        };

        $goods.find('.item').each(style);
        if($goodsDesc.length > 0)
					$goodsDesc.find('.item').each(style);

        if (index === count - 1) {
          $('#novelty-tabs .type-right').addClass('arrow-right-noactive').removeClass('arrow-right-active');
        } else {
          $('#novelty-tabs .type-right').addClass('arrow-right-active').removeClass('arrow-right-noactive');
        }
        if (index + 1 - Application.params.goodsCarouselCount === 0) {
          $('#novelty-tabs .type-left').addClass('arrow-left-noactive').removeClass('arrow-left-active');
        } else {
          $('#novelty-tabs .type-left').addClass('arrow-left-active').removeClass('arrow-left-noactive');
        }
      }; // function reStyle()

      var move = function (offset) {
        $goods.css('left', offset + 'px');
				
				if($goodsDesc.length > 0)
					$goodsDesc.css('left', offset + 'px');
      };

      var moveLeft = function (index) {
        var leftOffset = (Application.params.goodsCarouselCount - index) * Application.params.goodsCarouselItemWidth;
        move(leftOffset);
      };
      var moveRight = function (index) {
        var leftOffset = (Application.params.goodsCarouselCount - index - 2) * Application.params.goodsCarouselItemWidth;
        move(leftOffset);
      };

      if (count > Application.params.goodsCarouselCount) {
        var index = $goods.find('.item').not('.not-visible').last().index();
        if (type === 'left' && (index + 1 - Application.params.goodsCarouselCount) > 0) {
          moveLeft(index);
          reStyle(index - 1);
        } else if (type === 'right' && index + 1 < count) {
          moveRight(index);
          reStyle(index + 1);
        }
      }
      
      if(offsetCounter < 2)
      {
        offsetCounter++;
        $(this).trigger("click");
      } else offsetCounter=0;
      
      return false;
    });
  },
  
  calculateRowTotal: function ($row) {
  },
  calculateTotal: function ($table) {
  },
  
  calculateDelivery: function (sum) {
  },
  clearRecycle: function () {
  },
  changeTab: function (hash) {  	  	
    $('#tabs li.active-tab').removeClass('active-tab');
    $('#tabs li > a[href="#' + hash + '"]').parent().addClass('active-tab');
    $('#tabs > div').removeClass('visible').filter("#tab-" + hash).addClass('visible');
    $('#tabs2 li.active-tab').removeClass('active-tab');
    $('#tabs2 li > a[href="#' + hash + '"]').parent().addClass('active-tab');
    $('#tabs2 > div').removeClass('visible').filter("#tab2-" + hash).addClass('visible');
    if(hash=='specifications'){
    	document.getElementById('tab2-shortspecifications').className = 'visible';
    	document.getElementById('short-li').className = 'active-tab';
    }
    if(hash=='accessories'){
    	document.getElementById('tab2-table').className = 'visible';
    	document.getElementById('table-li').className = 'active-tab';
    }
    if(hash=='colors'){
    	document.getElementById('tab3-table').className = 'visible';
    	document.getElementById('colors-table-li').className = 'active-tab';
    }
  },
  
  UI: function () {
    Application.zebra('table.zebra');
  },
  zebra: function (selector) {
    $(selector).find('tbody > tr').removeClass('odd');
    $(selector).find('tbody > tr:odd').not('.summary').addClass("odd");
  }
};
var ApplicationRouter = {
  history: [],
  init: function () {
    $(window).bind('hashchange', $.proxy(this.route, this));
    $(window).trigger('hashchange');
  },
  routes: [{
    pattern: /^(specifications|opinions|video|similar|accessories|review|colors|personaldata|pastpurchase|favorites|notice|address|3dmodel)$/,
    action: function (hash) {
      Application.changeTab(hash);
    }
  }],
  route: function (e) {
    var hash = window.location.hash.replace(/^#/, '');
    for (var i = 0; i < this.routes.length; i += 1) {
      var r = this.routes[i];
      if (r.pattern.test(hash) && this.shouldExecute(hash)) {
        r.action(hash);
        this.history.push(hash);
      }
    }
  },
  shouldExecute: function (hash) {
    return !this.history.length || (this.history[this.history.length - 1] !== hash);
  }
};
$(function () {
  Application.init();
  ApplicationRouter.init();
});

function setImgSize(img,maxwidth,maxheight)
{
	var img_width = img.attr("wwidth");
	var img_height = img.attr("hheight");
	//console.log(img_width);
	//console.log(img_height);
	
	//if(console != undefined)
		//console.log(img.width());
	if (img_height > maxheight)
	{
		koeff = maxheight/img_height;
		img_height = maxheight;
		img_width = Math.floor(koeff*img_width);
	}
	//console.log(img_width);
	//console.log(img_height);
	
	if (img_width > maxwidth)
	{
		koeff = maxwidth/img_width;
		img_width = maxwidth;
		img_height = Math.floor(koeff*img_height);
	}
	//console.log(img_width);
	//console.log(img_height);
	
	return {
		width: img_width,
		height: img_height
	};
	//img.attr("width",img_width+"px");
	//img.attr("height",img_height+"px");
} // -= setImgResize =-


