var map;
var searchText = 'поиск';
var menuPosition;
var offsetMainPic;
var currWOneOtr;
var optionsOpinion = {
   beforeSubmit:  showRequestOpinion,
   success: showResponseOpinion
};

$(document).ready(function() {
   $(".pngFix").pngFix();
   if (typeof window['checkFlash'] == 'function') checkFlash();
   htmlOptions = { src: "image/top-logo_fl4.swf", width: '306', height: '83', wmode: 'transparent', replace: '<a href="./" title="Наборы инструмента, профессиональный инструмент, инструмент оптом, ручной инструмент — Мастер Ключ"><img src="image/top-logo.png" width="306" height="83" alt="Наборы инструмента, профессиональный инструмент, инструмент оптом, ручной инструмент — Мастер Ключ" /></a>' };
   $('#topLogo').flash(htmlOptions, pluginOptions);
   if ($("#gallery a[rel=fancy]").length) $("#gallery a[rel=fancy]").fancybox({ 'hideOnContentClick': true, 'overlayShow': true, 'overlayOpacity': 0.5, 'speedIn': 1000, 'speedOut': 600, 'titlePosition': 'inside', 'transitionIn': 'elastic', 'transitionOut': 'elastic' });
   if ($("#galleryBig a[rel=fancyBig1]").length) $("#galleryBig a[rel=fancyBig1]").fancybox({ 'hideOnContentClick': true, 'overlayShow': true, 'overlayOpacity': 0.5, 'speedIn': 1000, 'speedOut': 600, 'titlePosition': 'inside', 'transitionIn': 'elastic', 'transitionOut': 'elastic' });
   if ($("#galleryBig a[rel=fancyBig2]").length) $("#galleryBig a[rel=fancyBig2]").fancybox({ 'hideOnContentClick': true, 'overlayShow': true, 'overlayOpacity': 0.5, 'speedIn': 1000, 'speedOut': 600, 'titlePosition': 'inside', 'transitionIn': 'elastic', 'transitionOut': 'elastic' });
   if ($(".cloud-zoom").length) $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
   if ($("#opShow").length) $("#opShow").fancybox({ 'titleShow': false });
   $('#opinionForm').submit(function() {
      $(this).ajaxSubmit(optionsOpinion);
      return false;
   });

   $(".tm1").css('width', '96px').click(function() { document.location.href = 'about.htm'; });
   $(".tm2").css('width', '138px').click(function() { document.location.href = 'catalog.htm'; });
   $(".tm3").css('width', '98px').click(function() { document.location.href = 'wherebuy.htm'; });
   $(".tm4").css('width', '95px').click(function() { document.location.href = 'contacts.htm'; });

   //JPlayer
   $(".tm5").css('width', '41px').click(function() {
      var off = $(".topRight").offset();
      if ($(".jp-audio").css('top') == '30px') $(".jp-audio").css({'top': '-200px'});
      else {
         $(".jp-audio").css({'top': '30px'});
      }
   });
   $('.jp-close-btn').click(function(e) { $(".jp-audio").css({'top': '-200px'}); });
   $('.jp-playlist').click(function(e) { $('.jp-playlist').toggleClass('jp-playlist-expanded'); });
   $(document).click(function(e) { if (!$(e.target).hasClass('jp-playlist-item')) $('.jp-playlist').removeClass('jp-playlist-expanded'); });
   $("#jp_container_1").bind($.jPlayer.event.play, function(event) {
      $(".tm5").css('background', 'url("image/i-audi.gif") no-repeat left top');
   });
   $("#jp_container_1").bind($.jPlayer.event.pause, function(event) {
      $(".tm5").css('background', 'none');
   });
   $("#jp_container_1").bind($.jPlayer.event.ended, function(event) {
      $(".tm5").css('background', 'none');
   });
   //

   $(".sliderRight").click(function() {
      var val = $("#slider").slider("option", "value") + $("#slider").slider("option", "step");
      var max = $("#slider").slider("option", "max");
      if (val <= max) {
         $("#slider").slider("value", val);
         moveSlide(val, max);
      }
   });
   $(".sliderLeft").click(function() {
      var val = $("#slider").slider("option", "value") - $("#slider").slider("option", "step");
      var max = $("#slider").slider("option", "max");
      if (val >= 0) {
         $("#slider").slider("value", val);
         moveSlide(val, max);
      }
   });

   $(".im1").css({'width': '76px'}).click(function() { setMenuItem(1); });
   $(".im2").css({'width': '86px'}).click(function() { setMenuItem(2); });
   $(".im3").css({'width': '130px'}).click(function() { setMenuItem(3); });
   $(".im4").css({'width': '120px'}).click(function() { setMenuItem(4); });
   $(".im5").css({'width': '93px'}).click(function() { setMenuItem(5); });

   initPlus();
   $(".plus1").click(function() {
      var isView = ($(this).children().attr('src') == 'image/plus-a.png' ? true : false);
      if (isView) {
         $(this).children().attr('src', 'image/plus.png');
         $(".plus1Text").hide();
      }
      else {
         $(this).children().attr('src', 'image/plus-a.png');
         $(".plus1Text").css({'left': (520 + offsetMainPic['left']), 'top': (70 + offsetMainPic['top'])}).show();
      }
   });
   $(".plus2").click(function() {
      var isView = ($(this).children().attr('src') == 'image/plus-a.png' ? true : false);
      if (isView) {
         $(this).children().attr('src', 'image/plus.png');
         $(".plus2Text").hide();
      }
      else {
         $(this).children().attr('src', 'image/plus-a.png');
         $(".plus2Text").css({'left': (20 + offsetMainPic['left']), 'top': (340 + offsetMainPic['top'])}).show();
      }
   });
   $(".plus3").click(function() {
      var isView = ($(this).children().attr('src') == 'image/plus-a.png' ? true : false);
      if (isView) {
         $(this).children().attr('src', 'image/plus.png');
         $(".plus3Text").hide();
      }
      else {
         $(this).children().attr('src', 'image/plus-a.png');
         $(".plus3Text").css({'left': (360 + offsetMainPic['left']), 'top': (520 + offsetMainPic['top'])}).show();
      }
   });
   $(".plus4").click(function() {
      var isView = ($(this).children().attr('src') == 'image/plus-a.png' ? true : false);
      if (isView) {
         $(this).children().attr('src', 'image/plus.png');
         $(".plus4Text").hide();
      }
      else {
         $(this).children().attr('src', 'image/plus-a.png');
         $(".plus4Text").css({'left': (730 + offsetMainPic['left']), 'top': (430 + offsetMainPic['top'])}).show();
      }
   });
   $('#TOP').waypoint(function(event, direction) {
		event.stopPropagation();
	});
   $(".star").hover(
      function() {
         var idS = $(this).attr('id').match(/^star([1-5])$/)[1];
         for (var j = 1; j <= 5; j ++) {
            if (j <= idS) $("#star"+j).children().attr('src', 'image/i-reiting-a.png');
            else $("#star"+j).children().attr('src', 'image/i-reiting.png');
         }
      },
      function() {
         //$(".star").each(function() { $(this).children().attr('src', 'image/i-reiting.png'); });
         return;
      }
   ).
   click(function() {
      var idP = $(this).parent().attr('id').match(/^position([1-9][0-9]*)$/)[1];
      if ($.cookie("masterkey_item"+idP)) {
         alert("Ваш голос уже учтён. Спасибо.");
      }
      else {
         var idS = $(this).attr('id').match(/^star([1-5])$/)[1];
         $.cookie("masterkey_item"+idP, "1", { expires: 365 });
         $.ajax({
          type: "POST",
          url: "scripts/set-rating.php",
          data: 'count='+idS+'&idP='+idP,
          success: function(response) {
             $(".starsCount").html(response);
          }
         });
      }
   });
   setSlider();
   if ($(".innerItemPic").length) setLength();
   if ($('.scrollPane').length) ReinitScroll();
   if ($("#map").length) initialize();
   $(".numSel").hover(
      function() {
         unSelPosItemS();
         var num = $(this).children().attr('class').match(/num([1-9][0-9]*)/)[1];
         selPosItem(num);
      },
      function() {
         unSelPosItemS();
         var num = $(this).children().attr('class').match(/num([1-9][0-9]*)/)[1];
         unSelPosItemCount(num);
      }
   );
   $(".numSelImg").hover(
      function() {
         unSelPosItemS();
         var num = $(this).attr('class').match(/numImg([1-9][0-9]*)/)[1];
         selPosItem(num);
      },
      function() {
         var num = $(this).attr('class').match(/numImg([1-9][0-9]*)/)[1];
         unSelPosItemCount(num);
      }
   );
   $(".innerItemPic img").hover(
      function() {},
      function() { unSelPosItemS(); }
   );
});

$(window).resize(function() {
   setSlider();
   initPlus();
});

function setSlider() {
   var minWidth = 35;
   var countSl = Number($(".countLine").text());
   var currPos = Number($(".currPos").text());
   var countOtr = countSl - 1;
   var currW = $(".content").width() - 92;
   currWOneOtr = Math.floor(currW / countOtr);
   if (currWOneOtr < minWidth) {
      currWOneOtr = minWidth;
      countOtr = Math.floor(currW / currWOneOtr);
      countSl = countOtr + 1;
   }
   var currWOkr = currWOneOtr*countOtr;
   var realW = (currWOkr <= currW ? currWOkr : (currWOkr - currWOneOtr));
   var idP = 0;
   if ($("#star1").length) idP = $("#star1").parent().attr('id').match(/^position([1-9][0-9]*)$/)[1];
   $("#sliderTD").css('width', realW+'px');
   $(".lineSl").css('width', ((currPos - 1) * currWOneOtr));
   $("#slider").slider({
      value: (currPos ? ((currPos - 1) * currWOneOtr) : 0),
      min: 0,
      max: realW,
      step: currWOneOtr,
      slide: function(event, ui) {
         moveSlide(ui.value, realW);
      }
   });
   initSliderStr((currPos ? ((currPos - 1) * currWOneOtr) : 0), realW);
   var sendSl = countSl;
   $.ajax({
    type: "POST",
    url: "scripts/slider.php",
    data: 'count='+sendSl+'&currWOneOtr='+currWOneOtr+'&wWidth='+$(window).width()+'&idP='+idP,
    success: function(response) {
       $("#sliderInner").html(response);
    }
   });
}

function moveSlide(val, max) {
   $(".numberSl").removeClass('n_active');
   var indThisTmp = 0;
   $(".numberSl").each(function() {
      var lenTmp = $(this).text().length;
      $(this).css('left', ((indThisTmp * currWOneOtr) - (lenTmp == 3 ? 5 : 0)));
      indThisTmp = indThisTmp + 1;
   });
   $(".picturesSl").hide();
   var indThis = (val / currWOneOtr);
   $(".lineSl").css('width', (indThis * currWOneOtr));
   var len = $(".n_"+indThis).text().length;
   $(".n_"+indThis).addClass('n_active').css('left', ((indThis * currWOneOtr) - (len == 2 ? 5 : 10)));
   if ($(".i_"+indThis).hasClass('pLeft')) {
      $(".i_"+indThis).css('left', ((indThis * currWOneOtr) - 200)).show();
   }
   else $(".i_"+indThis).css('left', ((indThis * currWOneOtr) - 40)).show();
   initSliderStr(val, max);
   return;
}

function initSliderStr(val, max) {
   if (val < max) $(".sliderRight").attr('src', 'image/begun-right2.gif');
   else $(".sliderRight").attr('src', 'image/begun-right2-na.gif');
   if (val > 0) $(".sliderLeft").attr('src', 'image/begun-left.gif');
   else $(".sliderLeft").attr('src', 'image/begun-left-na.gif');
}

function setLength() {
   var w1 = $(".innerItemPic").children().width();
   var w2 = $(".outsideItemPic").children().width();
   var max = (w1 > w2 ? w1 : w2);
   $(".innerItemPic").css('width', max+'px');
   $(".outsideItemPic").css('width', max+'px');
   var hI1 = $(".innerItemPic").children().height();
   var hI2 = $(".outsideItemPic").children().height();
   var maxI = (hI1 > hI2 ? hI1 : hI2) - 150;
   $(".scrollPane").css({'width': ($(".content").width() - max - 100)+'px', 'height': maxI+'px'});
}

function initPlus() {
   if ($(".mainPic").length) { offsetMainPic = $(".mainPic img").offset(); }
   if ($(".plus1").length) $(".plus1").css({'left': (630 + offsetMainPic['left']), 'top': (30 + offsetMainPic['top'])}).show();
   if ($(".plus2").length) $(".plus2").css({'left': (130 + offsetMainPic['left']), 'top': (300 + offsetMainPic['top'])}).show();
   if ($(".plus3").length) $(".plus3").css({'left': (470 + offsetMainPic['left']), 'top': (480 + offsetMainPic['top'])}).show();
   if ($(".plus4").length) $(".plus4").css({'left': (840 + offsetMainPic['left']), 'top': (390 + offsetMainPic['top'])}).show();
}

function ReinitScroll() {
   $('.scrollPane').each(function() {
      $(this).jScrollPane({ showArrows: true, verticalDragMinHeight: 19, verticalDragMaxHeight: 19 });
      var api = $(this).data('jsp');
      var throttleTimeout;
      $(window).bind('resize', function() {
         if ($.browser.msie) {
            if (!throttleTimeout) {
               throttleTimeout = setTimeout(function() {
                  api.reinitialise();
                  throttleTimeout = null;
               }, 50);
            }
         } else api.reinitialise();
      });
   });
}

function setMenuItem(id) {
   if (id == 1) {
      $(".outsideItemPic").hide();
      $(".innerItemPic").show();
      $(".outsideItem").hide();
      $(".betterItem").hide();
      $(".picturesItem").hide();
      $(".opinionsItem").hide();
      $("#butOp").hide();
      $(".innerItem").show();
      $(".menuItem").css('background', 'url("image/menu-work2.gif") no-repeat left top');
      $("#galleryBig").show();
      $("#galleryBigNone").hide();
   }
   else if (id == 2) {
      $(".innerItemPic").hide();
      $(".outsideItemPic").show();
      $(".innerItem").hide();
      $(".betterItem").hide();
      $(".picturesItem").hide();
      $(".opinionsItem").hide();
      $("#butOp").hide();
      $(".outsideItem").show();
      $(".menuItem").css('background', 'url("image/menu-work2.gif") no-repeat left -27px');
      $("#galleryBig").hide();
      $("#galleryBigNone").show();
   }
   else if (id == 3) {
      $(".innerItem").hide();
      $(".outsideItem").hide();
      $(".betterItem").show();
      $(".picturesItem").hide();
      $(".opinionsItem").hide();
      $("#butOp").hide();
      $(".menuItem").css('background', 'url("image/menu-work2.gif") no-repeat left -54px');
      $("#galleryBig").hide();
      $("#galleryBigNone").show();
   }
   else if (id == 4) {
      $(".innerItem").hide();
      $(".outsideItem").hide();
      $(".betterItem").hide();
      $(".opinionsItem").hide();
      $("#butOp").hide();
      $(".picturesItem").show();
      $(".menuItem").css('background', 'url("image/menu-work2.gif") no-repeat left -81px');
      $("#galleryBig").hide();
      $("#galleryBigNone").show();
      if ($(".cloud-zoom").length) $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
   }
   else if (id == 5) {
      $(".innerItem").hide();
      $(".outsideItem").hide();
      $(".betterItem").hide();
      $(".picturesItem").hide();
      $(".opinionsItem").show();
      $("#butOp").show();
      $(".menuItem").css('background', 'url("image/menu-work2.gif") no-repeat left -108px');
      $("#galleryBig").hide();
      $("#galleryBigNone").show();
   }
   ReinitScroll();
   return;
}

function initialize() {
   var Arr = [];
   var currGmx = 55.342032;
   var currGmy = 37.841034;
   if (Number(currGmx) && Number(currGmy)) {
      Arr[0] = currGmx;
      Arr[1] = currGmy;
   }
   else {
      Arr[0] = 55.755786;
      Arr[1] = 37.61763300000007;
   }
   var latlng = new google.maps.LatLng(Number(Arr[0]), Number(Arr[1]));

   var myOptions = {
      zoom: 12,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };

   map = new google.maps.Map(document.getElementById("map"), myOptions);
   if (Number(currGmx) && Number(currGmy)) {
      addMarker(latlng);
   }
}

/* добавление маркера */
function addMarker(location) {
    var NewMarker = new google.maps.Marker({
        position: location,
        map: map
    });
}

function GetNewCalendar(lang) {
   $.ajax({
    type: "POST",
    url: "scripts/viewcalendar.php",
    data: 'month='+$("#monthNews option:selected").val()+'&year='+$("#yearNews option:selected").val()+'&lang='+lang,
    success: function(response) {
       $("#calendarTable").html(response);
    }
   });
}

function fnCheckSearchForm(f) {
   if (!f.search.value.match(/^.+$/) || f.search.value == searchText) {
      alert("Укажите поисковый запрос!");
      f.search.focus();
      return false;
   }
   return true;
}

function fnCheckSubscribeForm(f) {
   if (!f.email.value.match(/^[0-9A-Za-z\._-]+@([0-9a-z\._-]+\.)+[a-z]{2,4}$/)) {
      alert("Укажите правильно Ваш e-mail!");
      f.email.focus();
      return false;
   }
   return true;
}

function fnCheckRegistrationForm(f) {
   if (!f.fio.value.match(/(.+)/)) {
      alert("Укажите ФИО!");
      f.fio.focus();
      return false;
   }
   if (!f.email.value.match(/^[0-9A-Za-z._-]+@([0-9a-z_-]+\.)+[a-z]{2,4}$/)) {
      alert("Укажите правильный E-mail!");
      f.email.focus();
      return false;
   }
   if (!f.password.value.match(/(.+)/)) {
      alert("Укажите пароль!");
      f.password.focus();
      return false;
   }
   if (f.password.value != f.re_password.value) {
      alert("Подтверждение пароля не совпадает с основным паролем!");
      f.re_password.focus();
      return false;
   }
   return true;
}

function fnCheckOrders(obj) {
   var is_ok = false;
   for (i = 0; i < obj.length; i++) {
      if (obj[i].type == "text") {
         if (!obj[i].value.match(/^([1-9][0-9]*)?$/)) {
            alert("Введено некорректное значение!");
            obj[i].focus();
            return false;
         }
         if (is_ok == false) {
            if (obj[i].value) {
               is_ok = true;
            }
         }
      }
   }
   if (is_ok == false) {
      alert("Укажите количество заказываемых позиций!");
      return false;
   }
   return true;
}

function fnCheckOrderForm(f) {
   if (!f.fio.value.match(/(.+)/)) {
      alert('Укажите ФИО!');
      f.fio.focus();
      return false;
   }
   if (!f.phones.value.match(/(.+)/)) {
      alert('Укажите контактные телефоны!');
      f.phones.focus();
      return false;
   }
   if (!f.email.value.match(/^[a-zA-Z0-9._-]+\@[^\s:,]+\.[^\s:,]+$/i)) {
      alert('Укажите правильный e-mail!');
      f.email.focus();
      return false;
   }
   if (!f.address.value.match(/(.+)/)) {
      alert('Укажите адрес!');
      f.address.focus();
      return false;
   }
   return true;
}

function addToBasket(id) {
  if (!$("#countItems"+id).val().match(/^[1-9][0-9]*$/)) {
     alert("Введено некорректное значение!");
     $("#countItems"+id).focus();
     return false;
  }
  var dataSend = 'id='+id+'&count='+$("#countItems"+id).val();
  $.ajax({
    type: "POST",
    url: "orders_doajax.htm",
    data: dataSend,
    success: function(response) {
       alert(response);
    }
  });
  return false;
}

function selPosItem(num) {
   var numBgr = (num - 1)*21;
   $(".num"+num).css('background-position', '-21px '+(numBgr > 0 ? '-'+numBgr+'px' : 0));
   var offset = $(".innerItemPic img").offset();
   var text = $(".num"+num).parent().find('span').html();
   if (!$(".pi"+num).length) $("body").append('<div class="pa posItemDescr pi'+num+'" onmouseover="selPosItem('+num+');" onmouseout="unSelPosItemS();" style="z-index: 50; left: '+(offset['left'] + positionsPicture[num]['left'])+'px; top: '+(offset['top'] + positionsPicture[num]['top'])+'px;"><div class="num'+num+'Sel mb5"></div><div class="posItemDescrText">'+text+'</div></div>');
   else $(".pi"+num).show();
   return;
}

function unSelPosItemCount(num) {
   var numBgr = (num - 1)*21;
   $(".num"+num).css('background-position', '0 '+(numBgr > 0 ? '-'+numBgr+'px' : 0));
   return;
}

function unSelPosItemS() {
   if ($(".posItemDescr").length) $(".posItemDescr").each(function() { $(this).hide() });
   if ($(".numSel").length) {
      $(".numSel").each(function() {
         var num = $(this).children().attr('class').match(/num([1-9][0-9]*)/)[1];
         var numBgr = (num - 1)*21;
         $(".num"+num).css('background-position', '0 '+(numBgr > 0 ? '-'+numBgr+'px' : 0));
      });
   }
}

/*function fnCheckOpinionsForm(form_name) {
    if (!form_name.name.value.match(/(.+)/)) {
      alert("Укажите ФИО!");
      form_name.name.focus();
      return false;
    }
    if (!form_name.text.value.match(/(.+)/)) {
      alert("Укажите текст отзыва!");
      form_name.text.focus();
      return false;
    }
    if (!form_name.code.value.match(/([0-9]+)/)) {
      alert("Укажите код!");
      form_name.code.focus();
      return false;
    }
   return true;
}

function checkOp(f) {
   if (fnCheckOpinionsForm(f)) { alert('good'); }
   else return false;
}*/

function selTopMenu(classN, id) {
   $("."+classN).parent().css('background-position', 'left '+(id > 0 ? '-' : '')+(id*27)+'px');
}

function unselTopMenu(classN, id) {
   $("."+classN).parent().css('background-position', 'left '+(id > 0 ? '-' : '')+(id*27)+'px');
}

function showRequestOpinion(formData, jqForm, options) {
   for (var i = 0; i < formData.length; i++) {
      if (formData[i].name == 'name' && !formData[i].value.match(/(.+)/)) {
         jqForm[0].name.focus();
         alert('Укажите ФИО!');
         return false;
      }
      else if (formData[i].name == 'text' && !formData[i].value.match(/(.+)/)) {
         jqForm[0].text.focus();
         alert('Укажите текст отзыва!');
         return false;
      }
      else if (formData[i].name == 'code' && !formData[i].value.match(/^([0-9]+)$/)) {
         jqForm[0].code.focus();
         alert('Укажите код!');
         return false;
      }
   }
   return true;
}

function showResponseOpinion(text) {
   if (!text.match(/^Неверно/) && !text.match(/^Укажите/) && !text.match(/^Ошибка/)) {
      $.fancybox.close();
      if ($('#opinionForm').length) $('#opinionForm').clearForm();
   }
   if (text.match(/^Неверно/)) {
      $("#field_code").attr('value', '');
      $("#field_code").focus();
      $("#capchaPic").attr('src', 'captcha.php?i='+Math.random(1000));
   }
   alert(text);
   return;
}
