(function($){


$(document).ready(function(){

  $('.add_to_cart_block-heel, .add_to_cart_block-default').each(function(){
    var $win = $(this),
        type = this.className.match(/add\_to\_cart\_block\-([^\s\"\']+)/)[1],
        $sum = $win.find('.sum'),
        $quant = $win.find('input[type=text]'),
        $color = $win.find('input[name=color]'),
        $price = $win.find('.price'),
        $price_hidden = $win.find('input[name=price]');

    var recalcSum = function() {
      var sum = 0;
      $quant.each(function(){
        sum += parseInt($(this).val() != '' ? $(this).val() : 0);
      })
      // not black color heel is one grivna expensive
      $sum.text(sum * parseInt($price.text()) + currency);
    }

    var setPrice = function() {
      if ( $color.length > 0 )
        $price.text(parseInt($price_hidden.val()) + ( $color.val() == 'black' ? 0 : 1 ) + currency);
      else
        $price.text(parseInt($price_hidden.val()) + currency);
    }

    $quant.keypress(function(e){
      if ( e.which <= 31 || (e.which >= 48 && e.which <= 57) ) {
        return true;
      } else {
        $(this).stop().css({backgroundColor: '#FFAEB1'}).animate({backgroundColor: '#FFFFFF'});
        return false;
      }
    });

    $quant.keyup(recalcSum);

    $win.bind('update', function(){
      setPrice();
      recalcSum();
    });
    
    $color.change(function(){
      setPrice();
      recalcSum();
    });
    
  });

  $('.show_detail').each(function(){
    var $content = $(this).parents('.history_item:first').find('.history_item_content:first');
    $(this).click(function(){
      $(this).toggleClass('show_detail-opened');
      $content.slideToggle(100);
      return false;
    })
  })

  $('.small_form').each(function(){
    var $tabs = $(this);
    $tabs.find('.form_title a').each(function(tab_num){
      var $link = $(this);
      $link.click(function(){
        if ( ! $(this).hasClass('selected_tab') ) {
          $tabs.find('form.selected_tab_form').removeClass('selected_tab_form');
          $tabs.find('.form_title a.selected_tab').removeClass('selected_tab');
          $tabs.find('form:eq(' + tab_num + ')').addClass('selected_tab_form');
          $(this).addClass('selected_tab');
        }
        return false;
      });
    });
  });

  /*$('#wlpeLoginForm').ajaxForm(function(){
    alert('ok :)');
  });*/

  $('.colors').each(function(){
    var $colors = $(this).find('a');
    var $value = $(this).find('input');
    $colors.click(function(){
      if ( $(this).hasClass('color-selected') ) return false;
      $colors.filter('.color-selected').removeClass('color-selected');
      $(this).addClass('color-selected');
      $value.val(this.hash.slice(1)).trigger('change');
      return false;
    });
  })

  $('#sendOrderToOneselfEmailButton').each(function(){
    var $win = $('#sendOrderToOnesEmailForm').appendTo(document.body);

    if ( $win.length > 0 ) {
      var $close = $win.find('a.close');
      var $send = $win.find('a.submit');

      $close.click(function(){
        $win.hideWindow();
        return false;
      });

      $send.click(function(){
        $win.showWindowLoader();
        $.post($(this).attr('href'), {email: $win.find('input[name=email]').val()}, function(data){
          $win.hideWindowLoader();
          $win.showWindowMessage(data + '<div class="black_but" style="margin-top: 10px;">\
               <div class="black_but_left"><a href="#" onclick="$(\'#sendOrderToOnesEmailForm\').hideWindow().hideWindowMessage(); return false;">Закрыть</a></div>\
               <div class="black_but_rght"></div>\
            </div>');
        });
        return false;
      });

      $(this).click(function(){
        $win.showWindow();
        return false;
      });
    } else {
      $(this).click(function(){
        $.post($(this).attr('href'), function(data){
          alert(data);
        });
        return false;
      });
    }
  });

  $('#sendSetToOneselfEmailButton').each(function(){
    var $win = $('#sendSetToOnesEmailForm').appendTo(document.body);

    if ( $win.length > 0 ) {
      var $close = $win.find('a.close');
      var $send = $win.find('a.submit');

      $close.click(function(){
        $win.hideWindow();
        return false;
      });

      $send.click(function(){
        $win.showWindowLoader();
        $.post($(this).attr('href'), $('form[name=match]').serialize() + '&email=' + $win.find('input[name=email]').val(), function(data){
          $win.hideWindowLoader();
          $win.showWindowMessage(data + '<div class="black_but" style="margin-top: 10px;">\
               <div class="black_but_left"><a href="#" onclick="$(\'#sendSetToOnesEmailForm\').hideWindow().hideWindowMessage(); return false;">Закрыть</a></div>\
               <div class="black_but_rght"></div>\
            </div>');
        });
        return false;
      });

      $(this).click(function(){
        $win.showWindow();
        return false;
      });
    } else {
      $(this).click(function(){
        $.post($(this).attr('href'), function(data){
          alert(data);
        });
        return false;
      });
    }
  });

  $('#sendSetToShoppingCartButton').each(function(){
    $(this).click(function(){
      $.post($(this).attr('href'), $('form[name=match]').serialize());
      alert('Комплект отправлен в корзину');
      return false;
    })
  });

  $('#sendOrderToManagerButton').each(function(){
    var $win = $('#sendOrderToManagerForm').appendTo(document.body);

    if ( $win.length > 0 ) {
      var $close = $win.find('a.close');
      var $send = $win.find('a.submit');

      $close.click(function(){
        $win.hideWindow();
        return false;
      });

      $send.click(function(){
        $win.showWindowLoader();
        $.post($(this).attr('href'), {
            email: $win.find('input[name=email]').val(),
            fullname: $win.find('input[name=fullname]').val(),
            phone: $win.find('input[name=phone]').val()
          }, function(data){
          $win.hideWindowLoader();
          $win.showWindowMessage(data + '<div class="black_but" style="margin-top: 10px;">\
               <div class="black_but_left"><a href="#" onclick="$(\'#sendOrderToManagerForm\').hideWindow().hideWindowMessage(); return false;">Закрыть</a></div>\
               <div class="black_but_rght"></div>\
            </div>');
        });
        return false;
      });

      $(this).click(function(){
        $win.showWindow();
        return false;
      });
    } else {
      $(this).click(function(){
        $.post($(this).attr('href'), function(data){
          alert(data);
        });
        return false;
      });
    }
  });

  // login/register form
  $('#loginRegisterForm, #loginRegisterFormInline').each(function(){
    var $win = $(this);
    var $close = $win.find('a.close');
    var personalButtons = '#menu5>a, #footermenu5>a, a.personal, #loginButton';
    var $link = null;

    var showForm = function(){
      $link = $(this);
      $win.hideWindowMessage();
      $win.showWindow();
      return false;
    };

    $(personalButtons).click(showForm);

    $close.click(function(){
      $win.hideWindow();
      return false;
    });

    $win.find('.loginFormEnter').click(function(){
      $win.showWindowLoader();
      $(this).parents('form:first').ajaxSubmit(function(responseText, statusText){
        $win.hideWindowLoader();
        var message = responseText;
        if ( message == '') {
          $(personalButtons).unbind('click', showForm);
          message = 'Вход выполнен.'
          /*'<div class="black_but">\
               <div class="black_but_left"><a href="#" onclick="$(\'#loginRegisterForm\').hideWindow(); return false;">Закрыть</a></div>\
               <div class="black_but_rght"></div>\
            </div>'*/
          window.location = $link != null ? $link.attr('href') : window.location;
        }
        $win.showWindowMessage(message);
      });
      return false;
    });
    
    $win.find('.loginFormRegister').click(function(){
      $win.showWindowLoader();
      var $form = $(this).parents('form:first');
      $form.find('input[name=username]').val($form.find('input[name=email]').val());
      $form.ajaxSubmit(function(responseText, statusText){
        $win.hideWindowLoader();
        $win.showWindowMessage(responseText +
          '<br/>Вы можете <a href="#" onclick="jQuery(\'#loginRegisterForm, #loginRegisterFormInline\').hideWindowMessage(); return false;">повторить попытку</a> регистрации.'
        );
      });
      return false;
    });
    
  });

});

// Проверяет поля формы на правильность и выводит сообщения об ошибках
isValidForm = function(id) {
  var $form = $('#'+id);
  var isValid = true;
  var $place = $('.errors');

  $form.find('input.required, textarea.required').each(function(){
    var labelText = $(this).parent('div').find('label:first').text();
    var fieldId = $(this).attr('name')+'_error_required';
    if ( $(this).val() == '' && $('#'+$(this).attr('name')+'_error_email').length < 1 ) {
      isValid = false;
      if ( $place.length < 1 ) {
        $place = $('<div class="errors margin_left"><p><strong>Заполните пожалуйста форму полностью:</strong></p></div>');
        $place.insertBefore($form);
      }
      if ( $('#'+fieldId).length < 1 )
          $place.append('<p id="'+fieldId+'" style="display: none;">Поле «'+labelText+'» должно быть заполнено.</p>')
            .find('p:last')
            .slideDown(100);
    } else {
      $('#'+fieldId)
        .slideUp(100, function(){
          $(this).remove();
        });
    }
  });

  $form.find('input.email').each(function(){
    var labelText = $(this).parent('div').find('label:first').text();
    var fieldId = $(this).attr('name')+'_error_email';
    if ( ! /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test($(this).val()) && $(this).val().length > 0 && $('#'+$(this).attr('name')+'_error_required').length < 1 ) {
      isValid = false;
      if ( $place.length < 1 ) {
        $place = $('<div class="errors margin_left"><p><strong>Заполните пожалуйста форму полностью:</strong></p></div>');
        $place.insertBefore($form);
      }
      if ( $('#'+fieldId).length < 1 )
        $place.append('<p id="'+fieldId+'" style="display: none;">Поле «'+$(this).prevAll('label:first').text()+'» содержит неверный e-mail.</p>')
          .find('p:last')
          .slideDown(100);
    } else {
      $('#'+fieldId)
        .slideUp(100, function(){
          $(this).remove();
        });
    }
  });

  if ( isValid )
    $form.find('input.with_example_data').each(function(){
      this.value = '';
    });

  return isValid;
}

// функция отправки формы
sendForm = function(id) {
  if ( isValidForm(id) )
    $('#'+id).submit();
}

openEditShoppingCartRecordWindow = function(recType, itemData, scRecId)
{
  var $win = $('.add_to_cart_block-' + recType);
  var $typeName = $win.find('.set_head .title');
  var $article = $win.find('.set_head .name');
  var $add_to_cart = $win.find('.add_to_cart');
  var $version = $win.find('input[name=version]');
  var $price = $win.find('.price'),
      $price_hidden = $win.find('input[name=price]');
  var $sum = $win.find('.sum');
  var $quant = $win.find('input[type=text]');
  var $color = $win.find('input[name=color]');
  var $colors = $win.find('.colors a');

  //refresh color value to default
  if ( $colors.length > 0 ) {
    $colors.filter('.color-selected').removeClass('color-selected');
    $colors.first().addClass('color-selected');
    $color.val($colors.first().get(0).hash.slice(1))
  }

  //update from scRecData
  if ( typeof scRecId != 'undefined' ) {
    if ( $('input[name=scRecData_' + scRecId + '_quantity]').length > 0 ) {
      var quants = $('input[name=scRecData_' + scRecId + '_quantity]').val().split('&');
      $quant.each(function(i){
        $(this).val(quants[i]);
      })
    }
    if ( $('input[name=scRecData_' + scRecId + '_color]').length > 0 ) {
      $color.val($('input[name=scRecData_' + scRecId + '_color]').val());
      $colors.filter('.color-selected').removeClass('color-selected');
      $colors.filter('[href=#' + $color.val() + ']').addClass('color-selected');
    }
    if ( $('input[name=scRecData_' + scRecId + '_version]').length > 0 ) {
      $version.each(function(){
        $(this).removeAttr('checked');
        if ( $(this).val() == $('input[name=scRecData_' + scRecId + '_version]').val() )
          $(this).attr('checked', 'checked');
      });
      //$version.val($('input[name=scRecData_' + scRecId + '_version]').val());
    }
    $add_to_cart
      .unbind('click')
      .text('обновить')
      .click(function(){
        var quantity = new Array();
        var quantSum = 0;
        $quant.each(function(num){
          quantity.push($(this).val());
          quantSum += parseInt($(this).val() != '' ? $(this).val() : 0);
        });
        if ( parseInt($sum.text()) <= 0 )
          alert('Для того чтобы сделать заказ, нужно указать ненулевое количество позиций.');
        else {
          shoppingCart.updateInCart(
          scRecId,
          {
            id: itemData.id,
            color: $color.val(),
            version: $version.filter(':checked').val(),
            quantity: quantity.join('&')
          });
          $win.hideWindow();
          if ( $('input[name=scRecData_' + scRecId + '_quantity]').length > 0 )
            $('input[name=scRecData_' + scRecId + '_quantity]').val(quantity.join('&'));
          if ( $('input[name=scRecData_' + scRecId + '_color]').length > 0 )
            $('input[name=scRecData_' + scRecId + '_color]').val($color.val());
          if ( $('input[name=scRecData_' + scRecId + '_version]').length > 0 )
            $('input[name=scRecData_' + scRecId + '_version]').val($version.filter(':checked').val());
          $('#scRecId_' + scRecId + ' .order_price .order_value').text($price.text());
          $('#scRecId_' + scRecId + ' .order_quant .order_value').text(quantSum);
          $('#scRecId_' + scRecId + ' .order_summ .order_value').text($sum.text());
        }
        return false;
      })
  } else {
    $quant.val('');
    $add_to_cart
    .unbind('click')
    .click(function(){
      var quantity = new Array();
      $quant.each(function(num){
        quantity.push($(this).val());
      });
      if ( parseInt($sum.text()) <= 0 )
        alert('Для того чтобы сделать заказ, нужно указать ненулевое количество позиций.');
      else {
        shoppingCart.addToCart({
          id: itemData.id,
          color: $color.val(),
          version: $version.filter(':checked').val(),
          quantity: quantity.join('&')
        });
        $win.hideWindow();
      }
      return false;
    })
  }
  
  // close button
  $win.find('a.close').click(function(){
    $win.hideWindow();
    return false;
  });

  if ( itemData.typeName )
    $typeName.text(itemData.typeName + ':');
  $article.text(itemData.article);
  $price_hidden.val(itemData.price);
  if ( recType == 'default' )
    $win.trigger('update')
  else
    $color.trigger('change');
  //setPrice();
  //recalcSum();

  $win.showWindow();
}

delFromHistory = function(orderId) {
  var $order = $('#history_order_' + orderId);
  if ( confirm('Вы действительно хотите удалить ' + $order.find('.head_line .head_text strong:first').text() + '?') ) {
    $.post($order.find('.close:first').attr('href'), {
      poaction: 'deleteOrderFromHistory',
      orderId: orderId
    });
    $order.slideUp(function(){
      $(this).remove();
      if ( $('#history div.history_item').length < 1 ) {
          $('#history').append('<p>У вас не сохранено ни одного заказа.</p>');
        }
    });
  }
}

delFromShoppingCart = function(scRecId, itemText) {
  if ( confirm('Вы действительно хотите удалить ' + itemText + '?') ) {
    shoppingCart.delFromCart(scRecId);
    $('#scRecId_' + scRecId).slideUp(function(){
        $(this).remove();
        if ( $('#content_inner div.order_item').length < 1 ) {
          $('#content_inner h2 a').remove();
          $('#buttons_block').slideUp();
          $('#content_inner').append('<p>Ваша корзина пуста.</p>');
        }
    })
  }
}

sendOrderToOneselfEmail = function(def) {
  var email = '';
  if ( email = prompt('Введите пожалуйста, Ваш e-mail адрес на который Вы хотите получить содержимое заказа.', def ? def : '' ) ) {
    if ( /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(email) && email.length > 10 ) {
      $.post($(this).attr('href'),{
        email: email
      });
      alert('Заказ был успешно отправлен на адрес ' + email);
    } else {
      alert('Вы ввели неверный e-mail адрес, можете повторить попытку еще раз.');
      sendOrderToOneselfEmail(email);
    }
  }
}

sendOrderToManager = function() {
  $.post($(this).attr('href'), function(data){
    alert(data);
  });
}

$.fn.showWindow = function() {
  return this.each(function(){
    var $win = $(this);
    var $overlay = $('#overlay');
    if ( $overlay.length < 1 )
      $overlay = $('<div id="overlay"></div>').appendTo(document.body);
    $overlay.show();
    $win.css({
      visibility: 'hidden'
    });
    $win.show();
    var w = $win.width();
    var h = $win.height();

    // width and height of the viewport
    var ar = getPageSize();
    var wScr = ar[2];
    var hScr = ar[3];

    // correct coords according to scroll bars position
    var scr = getScrollXY();
    var y = (hScr>h ? Math.floor(Math.abs((hScr - h)/2)) : 0) + scr[1];
    var x = (wScr>w ? Math.floor(Math.abs((wScr - w)/2)) : 0) + scr[0];

    $win.css({
      top: y+ "px",
      left: x+ "px",
      visibility: 'visible'
    });
  });
}

$.fn.hideWindow = function() {
  return this.each(function(){
    $(this).hide();
    $('#overlay').hide();
  })
}

$.fn.showWindowLoader = function() {
  return this.each(function(){
    var $loader = $('#windowLoader');
    var $win = $(this);
    if ( $loader.length < 1 )
      $loader = $('<div id="windowLoader"></div>').appendTo(document.body);
    var offset = $win.offset();
    $loader.css({
      left: offset.left,
      top: offset.top,
      width: $win.width() + parseInt($win.css("padding-left"), 10) + parseInt($win.css("padding-right"), 10) + parseInt($win.css("borderLeftWidth"), 10) + parseInt($win.css("borderRightWidth"), 10),
      height: $win.height() + parseInt($win.css("padding-top"), 10) + parseInt($win.css("padding-bottom"), 10) + parseInt($win.css("borderTopWidth"), 10) + parseInt($win.css("borderBottomWidth"), 10)
    })
    .show();
  })
}

$.fn.hideWindowLoader = function() {
  return this.each(function(){
    $('#windowLoader').hide();
  })
}

$.fn.showWindowMessage = function(source) {
  return this.each(function(){
    $(this).find('.windowContent').hide();
    $(this).find('.windowMessages').html(source).show();
  })
}

$.fn.hideWindowMessage = function(source) {
  return this.each(function(){
    $(this).find('.windowMessages').hide();
    $(this).find('.windowContent').show();
  })
}

$.fn.catalogItemScroll = function(settings) {
  return this.each(function(){
    settings = $.extend({
      preload: 1, // [number} || 'all'
      itemWidth: 395,
      blankItemSource: '<td><div class="catalogue_item_big invisible"><img src="/assets/js/x.gif" class="spacer"/></div></td>',
      scrollEasing: 'easeInCubic',
      scrollDuration: 200
    }, settings);

    var $viewport = $('#items_wrapper');
    var $itemCont = $viewport.find('table tr');
    var $currentItem = $itemCont.find('td>div.visible');
    var $btnNext = $('#items_container a.right_arr'), $btnPrev = $('#items_container a.left_arr');

    var initRotate = function() {
      var $wrapper = $(this);
      var $btnRotate = $wrapper.find('a.rotate_arr');
      if ( !$btnRotate ) return;
      var $photo = $wrapper.find('.item_photo:last');
      var isVisible = true;
      $btnRotate.click(function(){
        $photo.each(function(pos){
          if ( isVisible ) {
            $photo.stop().animate({opacity: 0});
            isVisible = false;
          } else {
            $(this).stop().animate({opacity: 1});
            isVisible = true;
          }
        });
        return false;
      })
    }

    var initSwitchViews = function() {
      var $wrapper = $(this);
      var $btnsSwitch = $wrapper.find('.change_view a');
      var $photos = $wrapper.find('.item_photo');
      if ( $btnsSwitch.length < 1 ) return;
      $btnsSwitch.each(function(pos){
        $(this).click(function(){
          if ( $(this).hasClass('selected_view') ) return false;
          $btnsSwitch.filter('.selected_view').removeClass('selected_view').addClass('unselected_view');
          $(this).removeClass('unselected_view').addClass('selected_view');
          $photos.each(function(ppos){
            if ( ppos == pos )
              $(this).show();
            else
              $(this).hide();
          });
          return false;
        });
      });
    }

    $viewport.find('.item_photos').each(initRotate);
    $viewport.find('td').each(initSwitchViews);
   
    // add blank previous and next items
    $(settings.blankItemSource).prependTo($itemCont);
    $(settings.blankItemSource).appendTo($itemCont);

    // initial scroll to the current element
    if ( settings.preload != 'all')
      $viewport.get(0).scrollLeft = settings.itemWidth * (settings.preload - 1) + $viewport.width() / 2;
    else
      $viewport.get(0).scrollLeft = settings.itemWidth * (settings.cachePageIds.indexOf(settings.currentPageId)) + $viewport.width() / 2;

    var hideInfo = function() {
      $currentItem = $itemCont.find('td>div.visible').removeClass('visible').addClass('invisible');
    }

    var showInfo = function(pos) {
      var $item = null;
      if ( pos > 0 )
        $item = $currentItem.parent('td').next('td').find('>div');
      else
        $item = $currentItem.parent('td').prev('td').find('>div');
      $currentItem = $item.removeClass('invisible').addClass('visible');
    }

    var refreshControl = function() {
      if ( $currentItem.parent('td').next('td').next('td').find('>div.invisible, >div.visible').length < 1 )
        $btnNext.addClass('right_arr-disabled');
      else
        $btnNext.removeClass('right_arr-disabled');
      if ( $currentItem.parent('td').prev('td').prev('td').find('>div.invisible, >div.visible').length < 1 )
        $btnPrev.addClass('left_arr-disabled');
      else
        $btnPrev.removeClass('left_arr-disabled');
    }

    refreshControl();

    $btnPrev.click(function(){
      if ( $(this).hasClass('left_arr-disabled') || $viewport.is(':animated') ) return false;
      hideInfo();
      $viewport.animate({scrollLeft: $viewport.get(0).scrollLeft - settings.itemWidth}, settings.scrollDuration, settings.scrollEasing, function(){
        showInfo(-1);
        refreshControl();
      });
      return false;
    })

    $btnNext.click(function(){
      if ( $(this).hasClass('right_arr-disabled') || $viewport.is(':animated') ) return false;
      hideInfo();
      $viewport.animate({scrollLeft: $viewport.get(0).scrollLeft + settings.itemWidth}, settings.scrollDuration, settings.scrollEasing, function(){
        showInfo(1);
        refreshControl();
      });

      return false;
    })

    $(window).resize(function(){
      var num = 0;
      $itemCont.find('td').each(function(pos){
        num = pos;
        if ( $(this).find('>div.visible').length > 0 )
          return false;
      })
      $viewport.scrollLeft( (num - 1) * settings.itemWidth + $viewport.width() / 2 );
    })

  })
}

})(jQuery);

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 *
 * Open source under the BSD License.
 *
 * Copyright В© 2008 George McGinley Smith
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;if ((t/=d)==1) return b+c;if (!p) p=d*.3;
		if (a < Math.abs(c)) {a=c;var s=p/4;}
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;if ((t/=d)==1) return b+c;if (!p) p=d*.3;
		if (a < Math.abs(c)) {a=c;var s=p/4;}
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;if ((t/=d/2)==2) return b+c;if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) {a=c;var s=p/4;}
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 *
 * Open source under the BSD License.
 *
 * Copyright В© 2001 Robert Penner
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/**
 * Get the page and viewport size
 * @return {Array} - ?????????? ?????? ?? ?????????? ?????? ? ?????? ????????
 *					? ?????? ? ?????? ??????? ????? ????????
 */
function getPageSize(){
	var xScroll, yScroll, windowWidth, windowHeight, b = document.body, de = document.documentElement;
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = b.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (b.scrollHeight > b.offsetHeight){ // all but Explorer Mac
		xScroll = b.scrollWidth;
		yScroll = b.scrollHeight;
	} else if (de && de.scrollHeight > de.offsetHeight){ // Explorer 6 strict mode
		xScroll = de.scrollWidth;
		yScroll = de.scrollHeight;
	} else { // Explorer Mac...would also work in Mozilla and Safari
		xScroll = b.offsetWidth;
		yScroll = b.offsetHeight;
	}

	if (self.innerHeight) { // all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (de && de.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = de.clientWidth;
		windowHeight = de.clientHeight;
	} else if (b) { // other Explorers
		windowWidth = b.clientWidth;
		windowHeight = b.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	var pageHeight = (yScroll < windowHeight)? windowHeight : yScroll;

	// for small pages with total width less then width of the viewport
	var pageWidth = (xScroll < windowWidth)? windowWidth : xScroll;

	return [pageWidth,pageHeight,windowWidth,windowHeight];
}

/**
 * Get coords of scroll bars
 * @return {Array} - {coord horizontal, coord vertical}
 */
function getScrollXY() {
	var scrOfX = 0, scrOfY = 0, b = document.body, de = document.documentElement;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( b && ( b.scrollLeft || b.scrollTop ) ) {
		//DOM compliant
		scrOfY = b.scrollTop;
		scrOfX = b.scrollLeft;
	} else if( de && ( de.scrollLeft || de.scrollTop ) ) {
		//IE6 Strict
		scrOfY = de.scrollTop;
		scrOfX = de.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
    };
}
