// Не совсем хорошие браузеры.
var msie6 = false, msie7 = false, msie8 = false;

var img0 = new Image(); img0.src = '/i/textarea_bg.png';
var img1 = new Image(); img1.src = '/i/input_bg.png';
var img2 = new Image(); img2.src = '/i/select_bg.png';
var img3 = new Image(); img3.src = '/i/loading.gif';

$(document).ready(function() {
  
  // Сразу забираем jQuery объекты.
  var
    contactFormSelectText = $('#contactFormSelectText'),
    contactFormSelectTextP = $('#contactFormSelectText p'),
    contactFormSelect = $('#contactFormSelect'),
    contactFormSelectP = $('#contactFormSelect p'),
    contactFormSelectElement = $('#contactForm select'),
    phonePSpan = $('#phone p span'),
    footer = $('#footer'),
    footerOffsetTop = parseInt(footer.offset().top),
    contactCloser = $('#contactCloser'),
    hideable = $('#hideable'),
    hideable2 = $('#hideable2'),
    body = $('body'),
    mainBlock = $('#mainBlock'),
    footerWrap = $('#footerWrap'),
    hideableHidden = true,
    navActive2 = $('#nav .active2'),
    navActive3 = $('#nav .active3'),
    navImg = $('#nav img'),
    navActive = false,
    navUl = $('#nav ul'),
    navCloser = $('#navCloser'),
    listSlider = $('#listSlider'),
    photoContainerInnerInner = $('#photoContainerInnerInner'),
    photoContainerInner = $('#photoContainerInner'),
    photoContainer = $('#photoContainer'),
    listSliderWrap = $('#listSliderWrap'),
    navCloser = $('#navCloser'),
    galPh = $('.galPh'),
    nextPhoto = $('#nextPhoto'),
    prevPhoto = $('#prevPhoto'),
    photoFrameWrap = $('#photoFrameWrap'),
    galMouseOutAnimation = false,
    galMouseOverAnimation = false,
    listNext = $('#listNext'),
    listPrev = $('#listPrev'),
    listNextActive = false,
    listPrevActive = false,
    listNextInterval = 0,
    listPrevInterval = 0,
    photoFrameInner = $('#photoFrameInner'),
    photoFrameInnerImg = $('#photoFrameInner img'),
    currentPhoto = 0,
    wrap1 = $('#wrap1'),
    wrap2 = $('#wrap2'),
    contactForm = $('#contactForm');
    
/*------------------------------------------------------------------------------------------------*/
  
  // Предзагрузка изображений.
  var preloadFilenames = [
    'loading.gif', 'footer_bg.png', 'footer_bg_grey.png', 'hand_closed.ico', 'hand_opened.ico',
  ], preloadImages = [];
  for(var i = 0; i < preloadFilenames.length; i++) {
    preloadImages[i] = new Image();
    preloadImages[i].src = '/i/' + preloadFilenames[i];
  }
  
/*------------------------------------------------------------------------------------------------*/
  
  // Кнопка — отрывает комбобокс вида фотографии.
  contactFormSelectText.click(function(e) {
    contactFormSelect.show();
    contactFormSelectText.hide();
    e.stopPropagation();
  });

  // Выбор типа вида фотографии. Скрываем элементы комбобокса.
  contactFormSelectP.click(function() {
    contactFormSelectTextP.text($(this).text());
    contactFormSelectElement.val($(this).text()).attr('selected', 'selected');
    contactFormSelect.hide();
    contactFormSelectText.show();
  });
  
  // Если кликаем по пустой области, то значит комбобокс надо свернуть.
  hideable.click(function() {
    contactFormSelect.hide();
    contactFormSelectText.show();
  });
  
  // Кнопка вверху вправа, открывает контакты.
  phonePSpan.click(function(e) {
    e.stopPropagation();
    
    if (!hideableHidden) {
      // Прячем, если открыто.
      hideableHidden = true;
      contactCloser.fadeOut(500);
      if (!msie6)
        body.css('overflow', 'hidden');
      hideable.fadeOut(500);
      footerWrap.animate({ 'margin-top': '0' }, 500, 'easeInOutQuint', function() {
        if (!msie6)
          body.css('overflow', 'visible');
        footerWrap.css('height', 'auto');
        if (msie6)
          footerWrap.height('75px');
        contactFormSelect.hide();
        contactFormSelectText.show();
        if (body.hasClass('about'))
          footer.css('background-image', 'url(/i/footer_bg_grey.png)');
        if (body.hasClass('gallery') || body.hasClass('express'))
          hideable2.show();
      });
      return;
    }
    
    // Открываем, если спрятано.
    hideableHidden = false;
    contactCloser.fadeIn(500);
    if (!msie6)
      body.css('overflow', 'hidden');
    hideable.fadeIn(500);
    //footerWrap.height(parseInt(footer.offset().top) - 27);
    footerWrap.height(footerOffsetTop - 27);
    if (body.hasClass('about'))
      footer.css('background-image', 'url(/i/footer_bg.png)');
    if (body.hasClass('gallery') || body.hasClass('express'))
      hideable2.hide();
    footerWrap.animate({
      //'margin-top': (-parseInt(footer.offset().top) + 125) + 'px'
      'margin-top': (-footerOffsetTop + 125) + 'px'
    }, 500, 'easeInOutQuint', function() {
      body.css('overflow', 'visible');
    });
  });
  
  // Крестик в контактах, закрывающий контакты.
  var contactCloserClick = function() {
    if (hideableHidden)
      return;
    
    // Прячем, если открыто.
    hideableHidden = true;
    contactCloser.fadeOut(500);
    if (!msie6)
      body.css('overflow', 'hidden');
    hideable.fadeOut(500);
    footerWrap.animate({ 'margin-top': '0' }, 500, 'easeInOutQuint', function() {
      body.css('overflow', 'visible');
      footerWrap.height('auto');
      if (msie6)
        footerWrap.height('75px');
      contactFormSelect.hide();
      contactFormSelectText.show();
      if (body.hasClass('about'))
        footer.css('background-image', 'url(/i/footer_bg_grey.png)');
      if (body.hasClass('gallery') || body.hasClass('express'))
        hideable2.show();
    });
  };
  contactCloser.click(contactCloserClick);
  
  // При клике по фону — скрываем контакты.
  wrap1.click(contactCloserClick);
  wrap2.click(contactCloserClick);
  
/*------------------------------------------------------------------------------------------------*/

  // Кнопка — открывает навигацию по галерее.
  navActive2.click(function(e) {
    e.stopPropagation();
    
    if (navActive) {
      navActive = false;
      navActive2.removeClass('superactive');
      navActive3.show();
      navImg.show();
      navUl.hide();
      navCloser.hide();
      return;
    }
    
    navActive = true;
    navActive2.addClass('superactive');
    navActive3.hide();
    navImg.hide();
    navUl.show();
    navCloser.show();
  });
  
  // Кнопка — закрывает навигацию по галерее.
  var navCloserClick = function() {
    if (!navActive)
      return;
    navActive = false;
    navActive2.removeClass('superactive');
    navActive3.show();
    navImg.show();
    navUl.hide();
    navCloser.hide();
  };
  navCloser.click(navCloserClick);
  
  // При клике по фону — скрываем навигацию.
  wrap1.click(navCloserClick);
  wrap2.click(navCloserClick);
  
/*------------------------------------------------------------------------------------------------*/
  
  // Слайдер в галерее, который можно тянуть.
  listSlider.draggable({
    axis: 'x',
    containment: '#listSliderWrap',
    cursor: 'url(/i/hand_closed.ico), move',
    drag: function(event, ui) {
      var
        position = parseInt(listSlider.css('left')) / (parseInt(listSliderWrap.width()) - listSlider.width()),
        width = parseInt(photoContainer.width());
      photoContainerInnerInner.css('margin-left', -position * (91 * galPh.size() - width));
    }
  });
  
  // При клике на сам слайдер запрещаем перемещение его.
  listSlider.click(function(e) {
    e.stopPropagation();
    return false;
  });
  
  // При клике на полоску под слайдером перемещаем слайдер и фотки.
  listSliderWrap.click(function(e) {
    var pixelPosition = parseInt(e.pageX - listSliderWrap.offset().left);
    
    if (pixelPosition > parseInt(listSliderWrap.width()) - parseInt(listSlider.width()))
      pixelPosition = parseInt(listSliderWrap.width()) - parseInt(listSlider.width());
      
    var
      percentPosition = pixelPosition / (parseInt(listSliderWrap.width()) - listSlider.width()),
      width = parseInt(photoContainer.width());
    
    photoContainerInnerInner.css('margin-left', -percentPosition * (91 * galPh.size() - width));
    listSlider.css('left', pixelPosition);
  });
  
  if (!msie6 && !msie7 && !msie8) {
    // Когда мышка над фоткой — показываем стрелки в галерее.
    photoFrameWrap.mouseenter(function() {
      if (galMouseOverAnimation)
        return;
      galMouseOverAnimation = true;
      nextPhoto.animate({ 'opacity': '1.0' }, 200, 'linear', function() { galMouseOverAnimation = false; });
      prevPhoto.animate({ 'opacity': '1.0' }, 200, 'linear', function() { galMouseOverAnimation = false; });
    });
    
    // Когда мышка не над фоткой — показываем стрелки в галерее.    
    photoFrameWrap.mouseleave(function() {
      if (galMouseOutAnimation)
        return;
      galMouseOutAnimation = true;
      nextPhoto.animate({ 'opacity': '0' }, 200, 'linear', function() { galMouseOutAnimation = false; });
      prevPhoto.animate({ 'opacity': '0' }, 200, 'linear', function() { galMouseOutAnimation = false; });
    });
  }
  
/*------------------------------------------------------------------------------------------------*/
  
  // Кнопка около слайдера — двигает слайдер правее.
  listNext.mouseenter(function() {
    listNextActive = true;
    listPrevActive = false;
    clearInterval(listNextInterval);
    clearInterval(listPrevInterval);
  });
  listNext.mouseleave(function() {
    listNextActive = false;
    listPrevActive = false;
    clearInterval(listNextInterval);
    clearInterval(listPrevInterval);
  });
  listNext.mousedown(function() {
    if (!listNextActive)
      return;
    listNextInterval = setInterval(function() {
      var sliderPosition = parseInt(listSlider.css('left')) + 25;
      if (sliderPosition < 0)
        sliderPosition = 0;
      if (sliderPosition > parseInt(listSliderWrap.width()) - parseInt(listSlider.width()))
        sliderPosition = parseInt(listSliderWrap.width()) - parseInt(listSlider.width());
      listSlider.css('left', sliderPosition);
      
      var
        position = sliderPosition / (parseInt(listSliderWrap.width()) - listSlider.width()),
        width = parseInt(photoContainer.width());
      photoContainerInnerInner.css('margin-left', -position * (91 * galPh.size() - width));
    }, 50);
  });
  listNext.mouseup(function() {
    clearInterval(listNextInterval);
    clearInterval(listPrevInterval);
  });

  // Кнопка около слайдера — двигает слайдер левее.
  listPrev.mouseenter(function() {
    listNextActive = false;
    listPrevActive = true;
    clearInterval(listNextInterval);
    clearInterval(listPrevInterval);
  });
  listPrev.mouseleave(function() {
    listNextActive = false;
    listPrevActive = false;
    clearInterval(listNextInterval);
    clearInterval(listPrevInterval);
  });  
  listPrev.mousedown(function() {
    if (!listPrevActive)
      return;
    listPrevInterval = setInterval(function() {
      var sliderPosition = parseInt(listSlider.css('left')) - 25;
      if (sliderPosition < 0)
        sliderPosition = 0;
      if (sliderPosition > parseInt(listSliderWrap.width()) - parseInt(listSlider.width()))
        sliderPosition = parseInt(listSliderWrap.width()) - parseInt(listSlider.width());
      listSlider.css('left', sliderPosition);
      
      var
        position = sliderPosition / (parseInt(listSliderWrap.width()) - listSlider.width()),
        width = parseInt(photoContainer.width());
      photoContainerInnerInner.css('margin-left', -position * (91 * galPh.size() - width));
    }, 50);
  });
  listPrev.mouseup(function() {
    clearInterval(listNextInterval);
    clearInterval(listPrevInterval);
  });

/*------------------------------------------------------------------------------------------------*/
  
  photoFrameInnerImg.load(function() {
    photoFrameInner.fadeIn(200);
  });
  
  var updateThumbsShade = function() {
    galPh.each(function(i) {
      var image = images[i];
      if ($(this).hasClass('active'))
        $('img', this).attr('src', '/_' + image.type + '/thumb/' + image.filename);
      else
        $('img', this).attr('src', '/_' + image.type + '/dim/' + image.filename);
    });
  };
  
  // Обходим каждый тумбнейл и устанавливаем индекс.
  galPh.each(function(i) {
    $(this).data('index', i);
  });
    
  // При клике на тумбнейл фотки — меняем большую фотку.
  galPh.click(function() {
    // Пересчитываем номер текущей фотки.
    var
      index = parseInt($(this).data('index')),
      image = images[index];
    currentPhoto = index;
    
    // Меняем активный тумбнейл.
    galPh.removeClass('active');
    $(this).addClass('active');
    
    // Меняем большую фотку с эффектом.
    var image = images[currentPhoto];
    photoFrameInner.fadeOut(200, function() {
      photoFrameInnerImg.attr('src', '/_' + image.type + '/' + image.filename);
      //photoFrameInner.fadeIn(200);
    });
    
    updateThumbsShade();
  });
  
  // Клик по самой фотке — следующая фотка.
  photoFrameInnerImg.click(function() {
    // Пересчитываем номер текущей фотки.
    currentPhoto++;
    if (currentPhoto >= images.length) {
      currentPhoto = 0;
      photoContainerInnerInner.css('margin-left', '0px');
    }
    
    // Меняем большую фотку с эффектом.
    var image = images[currentPhoto];
    photoFrameInner.fadeOut(200, function() {
      photoFrameInnerImg.attr('src', '/_' + image.type + '/' + image.filename);
      //photoFrameInner.fadeIn(200);
    });
    
    // Меняем активный тумбнейл.
    galPh.removeClass('active');
    $(galPh.get(currentPhoto)).addClass('active');
    
    // Двигаем область просмотра тумбнейлов.
    var marginLeft = parseInt(photoContainerInnerInner.css('margin-left')); 
    if (currentPhoto > 3 && currentPhoto < images.length - 4) 
      photoContainerInnerInner.css('margin-left', marginLeft - 91);      
    else if (currentPhoto <= 3)
      photoContainerInnerInner.css('margin-left', '0px');
    else if (currentPhoto >= images.length - 4)
      photoContainerInnerInner.css('margin-left', (-91 * (images.length - 8)) + 'px');
    
    // Двигаем слайдер внизу.
    marginLeft = parseInt(photoContainerInnerInner.css('margin-left'));
    var percentPosition = -marginLeft / ((images.length - 8) * 91);
    listSlider.css('left', percentPosition * (parseInt(listSliderWrap.width()) - parseInt(listSlider.width())));
    
    updateThumbsShade();
  });
  
  // Большая кнопка левее большой фотки.
  prevPhoto.click(function() {
    // Пересчитываем номер текущей фотки.
    currentPhoto--;
    if (currentPhoto < 0) {
      currentPhoto = images.length - 1;
      photoContainerInnerInner.css('margin-left', (-91 * (images.length - 8)) + 'px');
    }
    
    // Меняем большую фотку с эффектом.
    var image = images[currentPhoto];
    photoFrameInner.fadeOut(200, function() {
      photoFrameInnerImg.attr('src', '/_' + image.type + '/' + image.filename);
      //photoFrameInner.fadeIn(200);
    });
    
    // Меняем активный тумбнейл.
    galPh.removeClass('active');
    $(galPh.get(currentPhoto)).addClass('active');
    
    // Двигаем область просмотра тумбнейлов.
    var marginLeft = parseInt(photoContainerInnerInner.css('margin-left'));
    if (currentPhoto > 3 && currentPhoto < images.length - 4)
      photoContainerInnerInner.css('margin-left', marginLeft + 91);
    else if (currentPhoto <= 3)
      photoContainerInnerInner.css('margin-left', '0px');
    else if (currentPhoto >= images.length - 4)
      photoContainerInnerInner.css('margin-left', (-91 * (images.length - 8)) + 'px');
    
    // Двигаем слайдер внизу.
    marginLeft = parseInt(photoContainerInnerInner.css('margin-left'));
    var percentPosition = -marginLeft / ((images.length - 8) * 91);
    listSlider.css('left', percentPosition * (parseInt(listSliderWrap.width()) - parseInt(listSlider.width())));
    
    updateThumbsShade();
  });
  
  // Большая кнопка правее большой фотки.
  nextPhoto.click(function() {
    // Пересчитываем номер текущей фотки.
    currentPhoto++;
    if (currentPhoto >= images.length) {
      currentPhoto = 0;
      photoContainerInnerInner.css('margin-left', '0px');
    }
    
    // Меняем большую фотку с эффектом.
    var image = images[currentPhoto];
    photoFrameInner.fadeOut(200, function() {
      photoFrameInnerImg.attr('src', '/_' + image.type + '/' + image.filename);
      //photoFrameInner.fadeIn(200);
    });
    
    // Меняем активный тумбнейл.
    galPh.removeClass('active');
    $(galPh.get(currentPhoto)).addClass('active');
    
    // Двигаем область просмотра тумбнейлов.
    var marginLeft = parseInt(photoContainerInnerInner.css('margin-left'));
    if (currentPhoto > 3 && currentPhoto < images.length - 4)
      photoContainerInnerInner.css('margin-left', marginLeft - 91);
    else if (currentPhoto <= 3)
      photoContainerInnerInner.css('margin-left', '0px');
    else if (currentPhoto >= images.length - 4)
      photoContainerInnerInner.css('margin-left', (-91 * (images.length - 8)) + 'px');
    
    // Двигаем слайдер внизу.
    marginLeft = parseInt(photoContainerInnerInner.css('margin-left'));
    var percentPosition = -marginLeft / ((images.length - 8) * 91);
    listSlider.css('left', percentPosition * (parseInt(listSliderWrap.width()) - parseInt(listSlider.width())));
    
    updateThumbsShade();
  });
  
/*------------------------------------------------------------------------------------------------*/
  
  // Когда наводим мышку на неактивный тумбнейл, то он становится ярче.
  galPh.mouseover(function() {
    if ($(this).hasClass('active'))
      return;
    var image = images[parseInt($(this).data('index'))];
    $('img', this).attr('src', '/_' + image.type + '/thumb/' + image.filename);
  });
  
  // Когда наводим мышку на неактивный тумбнейл, то он становится темнее.
  galPh.mouseout(function() {
    if ($(this).hasClass('active'))
      return;
    var image = images[parseInt($(this).data('index'))];
    $('img', this).attr('src', '/_' + image.type + '/dim/' + image.filename);    
  });

/*------------------------------------------------------------------------------------------------*/

  // Когда форма отправлена успешно.
  var contactFormSuccess = function(response, status, xhr, form) {
    $('#contactForm textarea, #contactForm input.std').removeClass('error');
    $('input.submit', contactForm).removeAttr('disabled').css('color', '#333333');
    $('#loadingGif').hide();
    
    // Update CSRF token.
    csrfToken = response.YII_CSRF_TOKEN;
    
    //if (jQuery.isEmptyObject(response)) {
    if (response.status == 1) {
      alert('Сообщение отправлено');
      
      /*
      contactForm.unbind().submit(function() { return false; });
      $('input.submit', contactForm).attr('disabled', 'disabled').css('color', '#999999');
      $('input, textarea, select', contactForm).attr('readonly', 'readonly');
      contactFormSelectText.unbind();
      */
      
      $('input, textarea, select', contactForm).removeAttr('readonly').val('');
      $('input.submit', contactForm).attr('disabled', 'disabled').css('color', '#333333').val('Отправить');
      
      return;
    }
    
    for (var name in response)
      $('#ContactForm_' + name).addClass('error');
  };
  
  // Когда пользователь пытается отправить форму на сервер.
  contactForm.submit(function() {
    $('input.submit', contactForm).attr('disabled', 'disabled').css('color', '#999999');
    $('input, textarea, select', contactForm).attr('readonly', 'readonly');
    $('#loadingGif').show();
    
    contactForm.ajaxSubmit({
      success: contactFormSuccess,
      dataType: 'json',
      data: { 'YII_CSRF_TOKEN': csrfToken }
    });
    return false;
  });
  
  // Проверочка на валидность формы.
  $('input.submit', contactForm).attr('disabled', 'disabled').css('color', '#999999');
  setInterval(function() {
    var
      valid = true,
      emailRegexp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    
    if ($('#ContactForm_name').val().length == 0 || $('#ContactForm_phone').val().length == 0 ||
        $('#ContactForm_message').val().length == 0 || !emailRegexp.test($('#ContactForm_email').val()))
      valid = false;    
    
    if (valid)
      $('input.submit', contactForm).removeAttr('disabled').css('color', '#333333');
    else
      $('input.submit', contactForm).attr('disabled', 'disabled').css('color', '#999999');
  }, 250);
  
/*------------------------------------------------------------------------------------------------*/
  
}); // document ready

