var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

if ( IE6 )
  DD_belatedPNG.fix('#header-content, .we_call_you, #bottom_menu-wrapper, #callback div, #callback fieldset, .ann-page-links div, .catalog .item-content .order_tip i');

(function($){

  var comuterIsSlow = true;
  
  /*
   *   DOM Ready section
   */
  $(function(){


  $('.print_version').each(function(){
    if ( window.print ) {
      $(this)
        .show()
        .click(function(){
          window.print();
          return false;
        });
    }
  });

  if ( IE6 ) {
    $('.furnit_catalog a').hover(function(){
      $(this).find('.border').show();
    },function(){
      $(this).find('.border').hide();
    })
  }


  $('form[name=filter]').each(function(){
    var $form = $(this);
    $form.find('select').change(function(){
      //if ( $(this).find('option:selected').val() != '' )
      $form.submit();
    });
  });
  
  $('form[name=frm]').each(function(){
    var $form = $(this);
    $form.find('select').change(function(){
      //console.log($(this).val());
      location.href = $(this).val()
    });
  });


  $('#magazine-pages').contentScroller({
    contentQuery: '#magazine-pages-viewport',
    scrollUpBtnQuery: '#magazine-pages-prev',
    scrollDownBtnQuery: '#magazine-pages-next',
    scrollDir: 'horizontal',
    scrollEasing: 'linear',
    scrollDuration: 200,
    scrollLength: .3
  });

  /*
   * initialize magazine flash viewer (with address plugin)
   */
  /*if ( $('#magazine_flash').length > 0 ) {
    var magazine_path = '/megazine/';

    var updatePages = function(evt) {
      var $pages = $('#magazine-pages');
      var $pages_next = $pages.find('th:last');
      $pages.find('td').remove();
      $.ajax({
        type: "GET",
        url: magazine_path + "getxml.php?data=" + evt.parameters.data,
        dataType: "xml",
        success: function(xml) {
          $(xml).find('page img').each(function(num){
            if ( num == 0 || num % 2 != 0 )
              $pages_next.before('<td><a href="#?data=' + evt.parameters.data + '&page=' + (num + 1) +  '"><img src="' + magazine_path + 'thumb.php?sizex=41&sizey=57&file=' + $(this).attr('src') + '" alt="" /></a></td>');
            else
              $pages_next.prev().find('a').append('<img src="' + magazine_path + 'thumb.php?sizex=41&sizey=57&file=' + $(this).attr('src') + '" alt="" />');
          });
        }
      });
    }

    $.address.init(function(evt){
      var flashvars = {
        xmlFile: evt.parameters.data,
        wmode: "transparent"
      };
      var params = {
        menu: "false",
        scale: "noScale",
        allowFullscreen: "false",
        allowScriptAccess: "always"
      };
      var attributes = {
        id: "magazine_flash"
      };
      swfobject.embedSWF(magazine_path + "preloader.swf", "magazine_flash", "100%", "560px", "9.0.115", "/js/expressInstall.swf", flashvars, params, attributes);
      updatePages(evt);
    });

    $.address.change(function(evt){
      var flash = (navigator.appName.indexOf("Microsoft") != -1 ? window : document)["magazine_flash"];
      if ( typeof evt.parameters.data != 'undefined' && typeof flash.sendFromJS == 'function' ) {
        var page = evt.parameters.page != 'undefined' ? evt.parameters.page : 1;
        flash.sendFromJS(evt.parameters.data);
        updatePages(evt);
      }
    });
  }*/


  $('.furnit_catalog div>a, .furnit_catalog div div a').each(function(){
    var ratio = 191/300;
    var $block = $(this);
    var $image = $(this).find('img');

    var freezSize = function() {
      $block.css({
        height: $block.width() * ratio
      });
      $image.css({
        height: $block.width() * ratio,
        width: $block.width()
      });
      //$image.height($(this).width() * ratio);
    }

    freezSize();
    $(window).resize(freezSize);
  });


  /*
   *   Запрос телефонного звонка
   */
    $('#callback button').submitable(function(XMLHttpRequest, textStatus){
      if ( XMLHttpRequest.status == 200 )
        eval("var data = " + XMLHttpRequest.responseText);
      else
        var data = {text: 'Произошла непредвиденная ошибка при выполнении запроса, попробуйте повторить ваш запрос.'}
      showMessage(data.text);
    }, function(){
      showMessage('Подождите, идет отправка запроса...', false);
    });

  /*
   *   Min height
   */
  $('#content').each(function(){
    var $content = $(this);
    var $columns_container = $content.find('.columns_container:first');

    fixMinHeight = function(){
      var cHeight = $content.height();
      var ccHeight = $columns_container.height();
    }
  });

  /*
   *   ANN
   */
  $('#ann').each(function(){
    var $ann = $(this);
    var $annPages = $ann.find('.ann-page');
    var $annThumbs = $ann.find('#ann-control-inner table a');
    var $bntNext = $ann.find('#ann-control-right');
    var $bntPrev = $ann.find('#ann-control-left');

    $('.ann-page-ill').contentScroller({
      contentQuery: '.brands-wrapper:first',
      scrollUpBtnQuery: '.brands-left:first',
      scrollDownBtnQuery: '.brands-right:first',
      scrollDir: 'horizontal',
      scrollEasing: 'linear',
      scrollDuration: 200,
      scrollLength: .3
    });
    
    $annThumbs.each(function(num){
      $(this).click(function(){
        if( $(this).hasClass('selected') ) return false;
        $annPages.filter('.ann-page-selected').removeClass('ann-page-selected');
        $annPages.eq(num).addClass('ann-page-selected');
        $annThumbs.filter('.selected').removeClass('selected');
        $(this).addClass('selected');

        return false;
      });
    });

    $bntNext.click(function(){
      var $next = $annThumbs.filter('.selected').parent('td').next('td').find('a');
      if ( $next.length > 0 )
        $next.trigger('click');
      else
        $annThumbs.first().trigger('click');
      return false;
    });

    $bntPrev.click(function(){
      var $prev = $annThumbs.filter('.selected').parent('td').prev('td').find('a');
      if ( $prev.length > 0 )
        $prev.trigger('click');
      else
        $annThumbs.last().trigger('click');
      return false;
    });
  });

  /*
   *   GUIDE
   */
  $('#guide').each(function(){
    var $guide = $(this);
    var $guide_content = $guide.find('#guide-content');
    var $quide_pages = $guide_content.find('.guide-page');
    var $guide_thumbs = $guide.find('#guide-thumbs-list td a');
    var $guide_icons = $guide.find('#guide-control-list ul li a');
    var $guide_list_viewport = $('#guide-thumbs-list');

    var swapEasing = 'linear',
        swapDuration = 300;

    $('#guide-control').contentScroller({
      contentQuery: '#guide-thumbs-list',
      scrollUpBtnQuery: '#guide-control-left',
      scrollDownBtnQuery: '#guide-control-right',
      scrollDir: 'horizontal',
      scrollEasing: 'easeOutQuint',
      scrollDuration: 700,
      scrollLength: 230
    });

    $guide_icons.each(function(num){
      $(this).click(function(){
        if ( $(this).hasClass('selected') ) return false;
        $guide_icons.removeClass('selected');
        $guide_icons.eq(num).addClass('selected');
        $guide_thumbs.eq(num).trigger('click');
        var scrollTo = 230 * (num + 1) - $guide_list_viewport.width() / 2 - 230 /2;
        $guide_list_viewport.stop().animate({scrollLeft: scrollTo}, 700, 'easeOutQuint');
        return false;
      });
    });

    $guide_thumbs.each(function(num){
      $(this).click(function(){
        $quide_pages.removeClass('guide-page-selected');
        $quide_pages.eq(num).addClass('guide-page-selected');
        /*var $oldPage = $quide_pages.filter('.guide-page-selected').css({
          'opacity': 1, // set it explicitly for ie
          'z-index': 2
        });

        $quide_pages.eq(num).css({
          'opacity': 1,
          'z-index': 1
        }).addClass('guide-page-selected');

        $oldPage.animate({opacity: 0}, swapDuration, swapEasing, function(){
          $(this).removeClass('guide-page-selected');
        });*/
        
        return false;
      });
    });

  });


  /*
   *  Add to cart buttons on item page and in catalogue
   */

    $('a.add_to_cart, a.order').each(function(){
      var $basketLink = $('#bottom_menu-content .keept_stuff:first');
      var $bottom = $('#bottom_menu-wrapper');
      var $tip = $('<div class="item_tip"><img src="/img/s.gif" alt=""/></div>');
      var $link = $(this);
      $link.click(function(){
        var $loader = $('<span class="basket_loader"></span>').appendTo($link);
        if ( $link.hasClass('order') )
          $link.addClass('order_loading');
        $.post($link.attr('href') + ( $('#order_quant').length > 0 ? '&cnt=' + $('#order_quant').val() : ''), function(data){
          $loader.remove();
          if ( $link.hasClass('order') )
            $link.removeClass('order_loading');
          $basketLink.removeClass('empty');
          $basketLink.text('ВЫ ОТЛОЖИЛИ ' + data + ' ТОВАРОВ');
          var img_src = '';
          var $item_thumb = $('.gallery_show-thumbs-list td a.selected img');
          var $catalog_item = $link.parents('.item-content:first');
          if ( $item_thumb.length > 0) {
            img_src = $item_thumb.attr('src');
          }
          if ( $catalog_item.length > 0 ) {
            img_src = $catalog_item.find('img:first').attr('src')
          }
          if ( img_src != '' ) {
            $tip.find('img:first').attr('src', img_src);
            $tip.appendTo($bottom);
            setTimeout(function(){ $tip.fadeOut(function(){ $(this).remove() }); }, 2000);
          }
        });
        return false;
      })
    });

    //$('#content').get(0).scrollTop = $('#content').get(0).scrollHeight;

    /*
     * --------------  Fix hovers for IE  --------------
     */
    //if ( $.browser.msie )
    //  $('.brands table td').hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')})

    /*(function(){

      var $images = $('img.flexible');

      var fixImgSize = function(img){
        $images.each(function(){
          var $img = $(this);
          $img.css('width', '100%');
          setTimeout(function(){$img.css('width', $img.width())}, 1);
        })
      }
      fixImgSize();
      $(window).resize(fixImgSize);
    })();*/

    /*
     * --------------  Gallery  --------------
     */
showHugeImage = function(_thumbCurrent, $thumbList) {
    var settings = {
      overlayApperSpped: 200,
      panelApperSpead: 100,
      panelDisapperSpead: 800,
      panelApperEasing: 'easeInQuad',
      thumbFadeOutSpeed: 200,
      thumbFadeInSpeed: 100,
      thumbFadeOutEasing: 'easeInQuad',
      thumbFadeInEasing: 'linear',
      thumbWidth: 43,
      thumbMargin: 12,
      moveInterval: 50,
      moveStep: 3
    }

    var $html = $('\
        <div id="huge_gallery_overlay"><div id="huge_gallery_wrapper">\
          <div id="huge_gallery_image_viewport"><img src="/img/s.gif" alt="" class="image" style="z-index: 1;" /></div>\
          <a href="#" id="huge_gallery_prev"></a>\
          <a href="#" id="huge_gallery_next"></a>\
          <div id="huge_gallery_panel_top_wrapper"><div id="huge_gallery_panel_top">\
            <a href="#" id="huge_gallery_back"></a>\
            <div id="huge_gallery_nav">\
                <a href="#" id="huge_gallery_nav_prev"></a>\
                <a href="#" id="huge_gallery_nav_next"></a>\
            </div>\
            <a href="#" id="huge_gallery_close"></a>\
          </div></div>\
          <div id="huge_gallery_panel_wrapper"><div id="huge_gallery_panel">\
            <a href="#" id="huge_gallery_control_play"></a>\
            <div id="huge_gallery_control">\
              <a href="#" class="prev"></a>\
              <a href="#" class="next"></a>\
              <div id="huge_gallery_control_viewport_wrapper"><div id="huge_gallery_control_viewport">\
                <table><tbody><tr>\
                </tr></tbody></table>\
              </div></div>\
            </div>\
          </div></div>\
        </div></div>\
    ');

    var $wrapper = $html.find('#huge_gallery_wrapper');
    var $image_viewport = $html.find('#huge_gallery_image_viewport');
    var $prev = $html.find('#huge_gallery_nav_prev');
    var $next = $html.find('#huge_gallery_nav_next');
    var $btnClose = $html.find('#huge_gallery_close');
    var $back = $html.find('#huge_gallery_back');
    var $play = $html.find('#huge_gallery_control_play');
    var $panel = $html.find('#huge_gallery_panel');
    var $panel_top = $html.find('#huge_gallery_panel_top');
    var $thumbViewport = $html.find('#huge_gallery_control_viewport');
    var $thumbContainer = $html.find('#huge_gallery_control_viewport tr');
    var preloadedImage = null;
    var $thumbCurrent = null;
    var pageSize = null;
    var timer = null;
    var cursor = null;
    var $newImage = $image_viewport.find('.image');
    var currentScrollTop = 0;
    var notIEWidnowWidthCorrection = 15;

    var playerTimer = null;
    var playerSpeed = 5000;

    var activityTimer = null;
    var activityTimeout = 2000;

    /*if ( $thumbList.length > 1 ) {
      $prev.add($next).show();
    }*/

    var updatePageSizeInfo = function(){
      pageSize = getPageSize();
      if ( ! $.browser.msie )
        pageSize[2] += notIEWidnowWidthCorrection;
      $(document.body).css({height: pageSize[3]});
      $image_viewport.height(pageSize[3] - 110);
    }

    var updateMouseCoords = function(evt){
      cursor = mouseXY(evt);
    }

    var panel_show = function() {
      $panel.add($panel_top).stop().animate({opacity: 1},  settings.panelApperSpead, settings.panelApperEasing);
    }

    var panel_hide = function() {
      $panel.add($panel_top).stop().animate({opacity: 0}, settings.panelDisapperSpead, settings.panelAppearEasing);
    }

    var play = function() {
      playerTimer = setTimeout(function(){
        showNext();
      }, playerSpeed);
    }

    var pause = function() {
      clearInterval(playerTimer);
    }

    var switchPlay = function() {
      if ( $play.hasClass('huge_gallery_control_play_pause') ) {
        $play.removeClass('huge_gallery_control_play_pause');
        play();
      } else {
        $play.addClass('huge_gallery_control_play_pause');
        pause();
      }
      return false;
    }

    $play.click(switchPlay);

    var close = function() {
      pause();
      $html.fadeOut(settings.overlayApperSpped, function(){
        $html.remove();
        $(document.body)
          .css({
            overflow: 'auto',
            height: 'auto'
          });
        $('html').css('overflow', 'auto');
        $('html, body').attr('scrollTop', currentScrollTop);
        //show bottom panel
        $('#bottom_menu').show();
      });
      $(window).unbind('resize', updatePageSizeInfo);
      $wrapper.unbind('mousemove', updateMouseCoords);
      $wrapper.unbind('mousemove', panelAutoHide);
      return false;
    }

    var panelAutoHide = function() {
      clearTimeout(activityTimer);
      panel_show();
      activityTimer = setTimeout(function(){
        panel_hide();
      }, activityTimeout);
    }

    var open = function() {
      //hide bottom panel
      $('#bottom_menu').hide();

      $back.text('Вернуться к ' + $('h1').text());

      updatePageSizeInfo();
      $(window).bind('resize', updatePageSizeInfo);
      $wrapper.bind('mousemove', updateMouseCoords);
      $wrapper.bind('mousemove', panelAutoHide);

      currentScrollTop = Math.max($('body').attr('scrollTop'), $('html').attr('scrollTop'));
      $('html, body').attr('scrollTop', 0);
      $('html').css('overflow', 'hidden');
      $(document.body)
        .css({
          overflow: 'hidden',
          height: pageSize[3]
        })
        .append($html);
      $( $.browser.msie ? document.body : window )
        .keydown(function(e){
          switch (e.keyCode) {
            case 27:close();break; //esc
            case 37:showPrev();break; //arrow left
            case 39:showNext();break; //arrow right
            // to avoid scroll down by keybord
            case 34: //page down
            case 40:return false;break; //arrow down
          }
        });

      $thumbList.each(function(num){
        var $image = $(this).find('img');
        var imageRatio = 43 / Math.min($image.width(), $image.height());
        var imageSrc = this.href.substr(this.href.indexOf('#') + 1);
        var $thumb = $('<td><a href="#" _href="' + imageSrc + '" num="' + num + '"><i></i><img src="' + $image.attr('src') + '" width="' + $image.width()*imageRatio + '" height="' + $image.height()*imageRatio + '" alt="" />"</a></td>');
        $thumb.find('a')
          .click(function(){thumbClick($(this));return false;})
          .bind("contextmenu dragstart",function(){return false;});
        $thumb.appendTo($thumbContainer);
        if ( this == _thumbCurrent ) {
          $thumbCurrent = $thumb.find('a');
          thumbClick($thumbCurrent);
        }
      });

      //thumbClick($thumbCurrent.find('a'));

      $html.fadeIn(settings.overlayApperSpped, function(){
        panel_show();
      });

      panelAutoHide();

      $html.contentScroller({
        contentQuery: '#huge_gallery_control_viewport',
        scrollUpBtnQuery: '#huge_gallery_control .prev',
        scrollDownBtnQuery: '#huge_gallery_control .next',
        scrollDir: 'horizontal',
        scrollEasing: 'linear',
        scrollDuration: 200,
        scrollLength: .3
      })

    }

    var onLoad = function($thumb) {
      var $oldImage = $image_viewport.find('.image');
      var $newImage = $('<img src="' + $thumb.attr('_href') + '" class="image" />');
      $oldImage.fadeOut(function(){
        $(this).remove();
      });
      $newImage
        .css({
          top: (parseInt(pageSize[3]) - parseInt(preloadedImage.height)) / 2,
          left: (parseInt(pageSize[2]) - parseInt(preloadedImage.width)) / 2
        })
        .hide()
        .appendTo($image_viewport);
      $newImage.bind("contextmenu mousedown dragstart",function(){
        return false;
      });
      clearInterval(timer);
      timer = setInterval(function(){
        if ( cursor == null ) return;
        var imageExceedHeight = parseInt($image_viewport.height()) - parseInt($newImage.get(0).height);
        var imageExceedWidth = parseInt(pageSize[2]) - parseInt($newImage.get(0).width);
        $newImage
        .css({
          top: imageExceedHeight > 0 ? imageExceedHeight / 2 : parseInt($newImage.css('top')) * ( 1 - 1 / settings.moveStep ) + ( imageExceedHeight * cursor.y / parseInt(pageSize[3]) ) / settings.moveStep,
          left: imageExceedWidth > 0 ? imageExceedWidth / 2 : parseInt($newImage.css('left')) * ( 1 - 1 / settings.moveStep ) + ( imageExceedWidth * cursor.x / parseInt(pageSize[2]) ) / settings.moveStep
        })
      }, settings.moveInterval);

      $newImage.fadeIn();
      if ( !$play.hasClass('huge_gallery_control_play_pause') )
        play();
    }

    var thumbClick = function($thumb) {
      if ( $thumb.hasClass('opened') ) return false;
      if ( $thumb.attr('num') == 0 )
        $prev.hide();
      else
        $prev.show();
      if ( $thumb.attr('num') == $thumbList.length - 1 )
        $next.hide();
      else
        $next.show();
      $thumbCurrent.removeClass('opened');
      var $loader = $thumb.find('i');
      // abort onload event if image is already loading
      if ( preloadedImage != null ) {
        preloadedImage.onload = null;
        $thumbCurrent.removeClass('loading');
      }
      $thumbCurrent = $thumb;
      //center thumbs list as possible
      /*if ( $thumbContainer.width() - $thumbViewport.width() > 0 ) {
        if ( $thumbCurrent.attr('num') <= 3 )
          $thumbViewport.stop().animate({scrollLeft: 0});
        else if ( $thumbContainer.find('td').length - $thumbCurrent.attr('num') <= 4 )
          $thumbViewport.stop().animate({scrollLeft: $thumbContainer.width() - $thumbViewport.width() - settings.thumbMargin});
        else
          $thumbViewport.stop().animate({scrollLeft: ( settings.thumbWidth + settings.thumbMargin ) * ( $thumbCurrent.attr('num') - 3 )});
      }*/

      pause();
      //load a huge image
      preloadedImage = new Image();
      preloadedImage.onload = function() {
          $thumb.removeClass('loading').addClass('opened');
          onLoad($thumb);
          preloadedImage.onload = null; /* not sure it's necessary because of the next line */
          preloadedImage = null;
      };
      preloadedImage.src = $thumb.attr('_href');
      if ( preloadedImage != null )
          $thumb.addClass('loading');
      return false;
    }

    var showNext = function() {
      if ( $thumbCurrent.parents('td:first').next().length > 0 )
        thumbClick($thumbCurrent.parents('td:first').next().find('a'));
      else
        thumbClick($thumbContainer.find('td:first a'));
      return false;
    }

    var showPrev = function() {
      if ( $thumbCurrent.parents('td:first').prev().length > 0 )
        thumbClick($thumbCurrent.parents('td:first').prev().find('a'));
      else
        thumbClick($thumbContainer.find('td:last a'));
      return false;
    }

    /*$next.click(function(){
      if ( !$play.hasClass('huge_gallery_control_play_pause') )
        pause();
      showNext();
      if ( !$play.hasClass('huge_gallery_control_play_pause') )
        play();
    });
    $prev.click(function(){
      if ( !$play.hasClass('huge_gallery_control_play_pause') )
        pause();
      showPrev();
      if ( !$play.hasClass('huge_gallery_control_play_pause') )
        play();
    });*/
    $next.click(showNext);
    $prev.click(showPrev);
    $btnClose.add($back).click(close);

    open();

  };
  
    $('.gallery_show').each(function(){
      var $gallery = $(this);
      var $thumbs_td = $gallery.find('.gallery_show-thumbs-list table td');
      var $thumbs = $thumbs_td.find('>a');
      var $hugeImageList = $thumbs.filter(function(){return this.href.indexOf('#') >= 0});
      var $thumbsContainer = $gallery.find('.gallery_show-thumbs:first');
      var $btnNext = $gallery.find('.gallery_show-thumbs a.next:first');
      var $btnPrev = $gallery.find('.gallery_show-thumbs a.prev:first');
      var $thumbList = $gallery.find('.gallery_show-thumbs-list:first');
      var $imageReflectionView = $gallery.find('.gallery_show-image-ref');
      var $imageReflection = $imageReflectionView.find('.ref-image:first');
      var $imageView = $gallery.find('.gallery_show-image:first');
      var $image = $imageView.find('img:first');

      var thumbsScrollDuration = 200;
      var thumbsScrollEasing = 'linear';
      var slideUpDuration = 200;
      var slideUpEasing = 'linear';
      var slideDownDuration = 200;
      var slideDownEasing = 'linear';

      var maxHeight = $gallery.parents('.exposition_gallery:first').length > 0 ? 600 : 461;
      var maxWidth = $gallery.parents('.exposition_gallery:first').length > 0 ? 900 : 600;


      //add prev/next overimage buttons
      var $prevImage = $('<a href="#" class="gallery_show-image-prev"><span></span></a>');
      var $nextImage = $('<a href="#" class="gallery_show-image-next"><span></span></a>');
      var $largeImage = $('<a href="#" class="gallery_show-image-large"><span></span></a>');
      $imageView.append($prevImage).append($largeImage).append($nextImage);

      $largeImage.hover(function(){
        $largeImage.animate({opacity: 1}, 200);
      },function(){
        $largeImage.animate({opacity: 0.4}, 200);
      })

      if ( $.browser.msie && $.browser.version < 7 ) {
        $prevImage.add($nextImage).each(function(){
          var $span = $(this).find('span:first');
          $(this).hover(function(){
            $span.show();
          },function(){
            $span.hide();
          })
        })
      }

      $prevImage.click(function(){
        var $prevThumb = $thumbs.filter('.selected').parent().prev().find('>a:first');
        if ( $prevThumb.length > 0 )
          $prevThumb.trigger('click');
        return false;
      })

      $nextImage.click(function(){
        var $nextThumb = $thumbs.filter('.selected').parent().next().find('>a:first');
        if ( $nextThumb.length > 0 )
          $nextThumb.trigger('click');
        return false;
      })

      // fix thumbs hover for ie6
      if ( $.browser.msie && $.browser.version < 7 )
        $thumbs.each(function(){
          var $span = $(this).find('span');
          $(this).hover(function(){
            if ( !$(this).hasClass('selected'))
              $span.show();
          }, function(){
            if ( !$(this).hasClass('selected'))
              $span.hide();
          });
        });

      //thumbs scrolling
      var scrollQuant = 1;
      var thumbWidth = $thumbs_td.get(0).offsetWidth;
      var thumbsScrollDif = $thumbList.get(0).scrollWidth - $thumbList.get(0).offsetWidth;
      var refreshControl = function(scrollTo) {
        if ( scrollTo >= thumbsScrollDif || thumbsScrollDif < 1 )
          $btnNext.addClass('next-disabled');
        else
          $btnNext.removeClass('next-disabled');
        if ( scrollTo <= 0 || thumbsScrollDif < 1 )
          $btnPrev.addClass('prev-disabled');
        else
          $btnPrev.removeClass('prev-disabled');
      }
      refreshControl(0);
      $btnNext.click(function(){
        if ( $(this).hasClass('next-disabled') ) return false;
        $thumbList.animate({scrollLeft: $thumbList.scrollLeft() + thumbWidth * scrollQuant}, thumbsScrollDuration, thumbsScrollEasing);
        refreshControl($thumbList.scrollLeft() + thumbWidth * scrollQuant);
        return false;
      });

      $btnPrev.click(function(){
        if ( $(this).hasClass('prev-disabled') ) return false;
        $thumbList.animate({scrollLeft: $thumbList.scrollLeft() - thumbWidth * scrollQuant}, thumbsScrollDuration, thumbsScrollEasing);
        refreshControl($thumbList.scrollLeft() - thumbWidth * scrollQuant);
        return false;
      })

      // thumb reflections
      $thumbs_td.each(function(){
        var $ref = $(this).find('div:first');
        var $img = $(this).find('img:first');
        $ref.reflection($img.attr('src'), {
          opacityTop: 0.3,
          opacityBottom: 0,
          height: 58
        });
      });

      var preloadImg = new Image();

      //thumb click event
      $thumbs.click(function(){
        var $thumb = $(this);
        var $loader = null;
        if ( $thumb.hasClass('selected') ) return false;

        //stop other loading
        preloadImg.onload = null;
        $thumbs.find('i:first').remove();

        //start loading
        var loaderTimeout = setTimeout(function(){
          $loader = $('<i></i>').appendTo($thumb);
        }, 100);

        //hide zoom button
        $largeImage.hide();

        preloadImg.onload = function() {
          //hide loader
          if ( $loader == null )
            clearTimeout(loaderTimeout);
          else
            $loader.remove();
          //calculate image size
          var width = this.width;
          var height = this.height;
          var wI = maxWidth / width;
          var hI = maxHeight / height;
          var mI = Math.min(wI, hI, 1);
          height = height * mI;
          width = width * mI;
          //resize window
          $imageView.animate({
            height: height,
            width: width
          },
            slideDownDuration,
            slideDownEasing
          );
          // fix thumbs moving for ie
          if ( $.browser.msie ) {
            $thumbsContainer.animate({
              top: height - 9
            },
              slideDownDuration,
              slideDownEasing);
          }
          $imageReflectionView.animate({
            width: width
          },
            slideDownDuration,
            slideDownEasing
          );
          //swap image
          $image.animate({bottom: -$image.height()}, slideDownDuration, slideDownEasing, function(){
            $image
              .hide()
              .attr('src', preloadImg.src)
              .css({
                bottom: -height,
                height: height,
                width: width
              })
              .show()
              .animate({bottom: 0}, slideUpDuration, slideUpEasing, function(){
                $gallery.find('.gallery_show-thumbs').css('bottom', '1px').css('bottom', '0px');
                var thumbHref = $thumb.attr('href');
                var hugeSrc = thumbHref.indexOf('#') >= 0 ? thumbHref.substr(thumbHref.indexOf('#') + 1) : '#';
                if ( hugeSrc != '#' ) {
                  $largeImage.unbind('click').click(function(){

                    showHugeImage($thumb.get(0), $hugeImageList);
                    return false;
                  }).show();
                }
              });
          });
          //swap reflection
          $imageReflection.animate({top: -$image.height()}, slideDownDuration, slideDownEasing, function(){
            $imageReflection
              .find('img, canvas').remove().end()
              .hide()              
              .css({
                top: -height,
                width: width
              })
              .flip(preloadImg.src, {
                height: height,
                width: width
              })
              .show()
              .animate({top: 0}, slideUpDuration, slideUpEasing);
          });
          this.onload = null;
        }
        preloadImg.src = $thumb.attr('href');
        if ( $.browser.msie && $.browser.version < 7 )
           $thumbs.filter('.selected').find('span').hide();
        $thumbs.filter('.selected').removeClass('selected');
        $thumb.addClass('selected');

        var $prevThumb = $thumb.parent().prev().find('>a:first');
        var $nextThumb = $thumb.parent().next().find('>a:first');
        if ( $prevThumb.length > 0 )
          $prevImage.show();
        else
          $prevImage.hide();
        if ( $nextThumb.length > 0 )
          $nextImage.show();
        else
          $nextImage.hide();


        var pos = 0;
        $thumbs.each(function(num){
          if ( $(this).hasClass('selected') ) {
            pos = num;
            return false;
          }
        });
        pos = pos == 0 ? 1 : pos;
        pos = pos == ($thumbs.length - 1) ? $thumbs.length : pos;
        var scrollTo = thumbWidth * ( pos - 1 );
        $thumbList.animate({scrollLeft: scrollTo}, thumbsScrollDuration, thumbsScrollEasing);
        refreshControl(scrollTo);

        return false;
      });

      //show first image
      $thumbs.eq(0).trigger('click');

      $imageReflection.flip($image.attr('src')).css('opacity', .3);

      //avoid accidental image selecting
      disableSelection(this);

      
    });    

    /*
     * --------------  Cart  --------------
     */
    $('.keept_stuff').live('click', function(){
      if ( $(this).hasClass('empty') ) return false;
      var win = window.open(this.href, "", "dependent,resizable=no,scrollbars=no,menubar=no,status,width=600,height=670");
      win.focus();
      return false;
    });

    /*
     * --------------  Send message  --------------
     */
    $('.send_message, .check_price, .reserve_place').live('click', function(){
      var win = window.open(this.href, "", "dependent,resizable=no,scrollbars=no,menubar=no,status,width=600,height=670");
      win.focus();
      return false;
    });

    /*
     * Open basket links in main window
     */
    $('.page-orderlist-item-info .name a').click(function(){
      opener.location.href = this.href;
      opener.window.focus();
      return false;
    })
    /*
     * Pages
     */
    $('#order-content').pages();

    /*
     * Decor chackboxes
     */
    $('#order-content input[type=checkbox]').checkbox();

    /*
     * Order list
     */
    $('#order-content').each(function(){
      var $this = $(this);
      var $removeBtn = $this.find('.item-remove');

      $this.find('.page-orderlist-item-comment').each(function(){
        var $text = $(this).find('textarea');
        $(this).find('a').click(function(){
          $text.slideToggle(100);
          return false;
        })
      });

      $this.find('.page-orderlist-header .checkbox_label').click(function(){
        var $c = $(this).parent().find('.checkbox');
        $c.trigger('click');
        if ( $c.hasClass('checkbox-checked') )
          $(this).text('Убрать выделение');
        else
          $(this).text('Выделить все');
      })

      $this.find('.page-orderlist-header .checkbox').click(function(){
        var $label = $(this).parent().find('.checkbox_label');
        if ( $(this).hasClass('checkbox-checked') ) {
          $this.find('.page-orderlist-content input').attr('checked', true).trigger('change');
          $this.find('.page-orderlist-content .checkbox').addClass('checkbox-checked');
          $label.text('Убрать выделение');
        } else {
          $this.find('.page-orderlist-content input').attr('checked', false).trigger('change');
          $this.find('.page-orderlist-content .checkbox').removeClass('checkbox-checked');
          $label.text('Выделить все');
        }
      });

      $this.find('.page-orderlist-content input').change(function(){
        if ( $this.find('.page-orderlist-content input:checked').length > 0 )
          $removeBtn.removeClass('item-remove');
        else
          $removeBtn.addClass('item-remove');
      });

      $removeBtn.click(function(){
        if ( !$(this).hasClass('item-remove') )
          if ( confirm('Вы действительно хотите удалить выбранные позиции?') ) {
            var items = new Array();
            $this.find('.page-orderlist-content input:checked').each(function(){
              items.push('item[]=' + $(this).val());
              $(this).parents('.page-orderlist-item:first').slideUp(function(){
                $(this).remove();
                $('#order-title span').text($this.find('.page-orderlist-item').length);
              });
            });
            $(this).addClass('item-remove');
            $.post($removeBtn.attr('href'), items.join('&'));
          }
        return false;
      })

    });

    /*
     * Order form
     */
    $('#order a.submit_ajax').submitable(function(XMLHttpRequest, textStatus){
      eval("var data = " + XMLHttpRequest.responseText);
      $(document.body)
        .html('')
        .append('<table class="centered"><tr><td>' + data.text + '<br /><br /><a href="javascript:self.close()">Закрыть окно</a></td></tr></table>');
       setTimeout(function(){self.close()}, 5000);
    }, function(){
      $(document.body)
        .html('')
        .append('<table class="centered"><tr><td><h1>Подождите, идет отправка...</h1></td></tr></table>');
    });

    $('#order a.close').click(function(){
      self.close();
      return false;
    });

    /*
     * Form fields labels
     */
    $('input.label, textarea.label').each(function(){
      var $field = $(this);
      var label_text = $field.val();

      $field.bind('focus', function(){
        if ( $field.hasClass('label') ) {
          $field.val('');
          $field.removeClass('label');
        }
      });

      $field.bind('blur', function(){
        if ( $.trim($field.val()) == '' ) {
          $field.val(label_text);
          $field.addClass('label');
        }
      });

    });

    /*
     * --------------  we recomend  --------------
     */

    $('.we_recomend .item').each(function(){
      var $item = $(this);
      var $img = $item.find('img:first');
      var $content = $item.find('.item-content:first');
      var $reflection = $item.find('.item-title-ref:first')

      $content.showInfo($content.find('.info:first'), {
        $leftIsWidthOf: $content
      });

      $reflection.reflection($img.attr('src'), {
        opacityTop: 0.5,
        opacityBottom: 0,
        height: 38
      });

      $content.hover(function(){
        $img.animate({opacity: 1}, 100);
        //$reflection.css('visibility', 'hidden');
        $reflection.animate({opacity: 0}, 100);
      }, function(){
        $img.animate({opacity: .9}, 100);
        //$reflection.css('visibility', 'visible');
        $reflection.animate({opacity: 1}, 100);
      });
    });

    /*
     * --------------  Navigation menu  --------------
     */
    $('.subnav').each(function(){
      var $subnav = $(this);
      var $link = $subnav.find('>a');
      if ( $link.length < 1 ) return;
      var $ul = $link.next('ul:first');
      var link_text = $link.text();

      var setArr = function() {
        if ( $subnav.hasClass('opened') )
          $link.get(0).innerHTML = link_text + '<span>&nbsp;&darr;</span>';
        else
          $link.get(0).innerHTML = link_text + '<span>&nbsp;&uarr;</span>';
      }
      setArr();
      
      $link.click(function(){
        $ul.slideToggle(100, function(){
          $subnav.toggleClass('opened');
          setArr();
          // fix bottom toolbar width cause open menu can cause scrollbars
          if ( !$.browser.mise ) $('#bottom_menu').width($('#contentPaddingMeasurerForIE').width());
        });
        return false;
      });
    });

    /*
     * --------------  Catalog items  --------------
     */
     $('.catalog').each(function(){
      var $items = $(this).find('.item');
      var $item_images = $(this).find('.item-image');
      var image_list = [];
      var defRatio = 210/278;
      var height = Math.floor($item_images.eq(0).width() * defRatio)+1;
      // fix right border overlaing by image in IE
//      if ( $.browser.msie )
//        $item_images.wrap('<div class="ieFix"></div>');
       var fillImage = function(index, data){
//         console.log(data);
         var $item_image = data.$img.parent(),
              ratio = data.img.height/data.img.width;
          if ( ratio < defRatio ) {
            data.$img.height(height);
            data.$img.css('width','auto');
          } else {
            data.$img.width('width',Math.floor(height/ratio)+1);
            data.$img.css('height','auto');
          }          
          $item_image.scrollLeft( ( data.$img.width() - $item_image.width() ) / 2 );
          $item_image.scrollTop( ( data.$img.height() - $item_image.height() ) / 2 );
       }
      var fillImages = function() {
        height = Math.floor($item_images.eq(0).width() * defRatio); 
//        console.log(height);
        $items.height(height+4);
        $item_images.height(height);
        $.each(image_list, fillImage)
      }
      $item_images.find('img').each(function(){
        var preload = new Image();
        var $img = $(this);
        preload.onload = function() {
          fillImage(0, {$img: $img, img: preload});
          image_list.push({$img: $img, img: preload});
          preload.onload = null;
        }
        preload.src = this.src;
      });
      fillImages();
      $(window).resize(fillImages);
    });

    var $itemImages = $('.catalog .item .item-image');
    
    $('.catalog .item').each(function(){
      var $item = $(this);
      var $content = $item.find('.item-content:first');
      var $image = $item.find('.item-image:first');
      if ( $image.length < 1 ) return ;

      var $toCart = $item.find('.item-data .order:first');
      var $toCartTip = $('<span class="order_tip"><span><i></i></span></span>');
      var tipDuration = 100;
      var tipEasing = 'linear';
      $toCart.before($toCartTip);

      $toCart.hover(function(){
        $toCartTip.animate({width: 66}, tipDuration, tipEasing);
      }, function(){
        $toCartTip.animate({width: 1}, tipDuration, tipEasing);
      });

      /*var imageScroller = new ContentScroller($image.get(0), {
        stepFrequency: 50,
        stepQuont: 2,
        controlSpace: $content.get(0),
        autoenable: false
      });*/

      $content.showInfo($content.find('.info:first'), {
        autoalign: false,
        $leftIsWidthOf: $content,
        left: 3
      });

      $content.mouseover(function(){
        $item.addClass('item-selected');
        //imageScroller.enable();
      });
      
      $item.mouseleave(function(){
        //imageScroller.disable();
        $item.removeClass('item-selected');
        //$image.scrollTop(0).scrollLeft( ( $image.find('img').width() - $image.width() ) / 2 );
      });      
    });


    /*
     * --------------  Brands grid: cells hover and sizes  --------------
     */
    $('.brands').each(function(){
      var cells = new Array();
      var hoverColor = '#9f9f9f';
      var normalColor = '#d3d3d3';
      var rows = $(this).find('tr').length - 1;
      var columns = $(this).find('tr:first td').length - 1;

      $(this).find('tr').each(function(row){
        cells[row] = new Array();
        $(this).find('td').each(function(column){
          cells[row][column] = this;
          $(this).hover(function(){
            $(this).css({
              borderColor: hoverColor
            });
            if ( row > 0 )
              $(cells[row-1][column]).css('borderBottomColor', hoverColor);
            if ( column > 0 )
              $(cells[row][column-1]).css('borderRightColor', hoverColor);
            if ( row < rows )
              $(cells[row+1][column]).css('borderTopColor', hoverColor);
            if ( column < columns )
              $(cells[row][column+1]).css('borderLeftColor', hoverColor);
          }, function(){
            $(this).css({
              borderColor: normalColor
            });
            if ( row > 0 )
              $(cells[row-1][column]).css('borderBottomColor', normalColor);
            if ( column > 0 )
              $(cells[row][column-1]).css('borderRightColor', normalColor);
            if ( row < rows )
              $(cells[row+1][column]).css('borderTopColor', normalColor);
            if ( column < columns )
              $(cells[row][column+1]).css('borderLeftColor', normalColor);
          });
        });
      });
    })

    /*
     * --------------  Slideshowt  --------------
     */
    var Slideshow = {};

    $('.fot_you_content-tiile').each(function(){
      var $slideLinks = $(this).find('.button_square');
      var $inner = $(this).parents('.fot_you_content, .ann-page-inner');
      var $container = $inner.find('.slideshow');
      var $body = $inner.find('.ann-page-body');
      var slideDuration = 500;
      var slideEasing = 'linear';
      var interval = null;
      var goInterval = 3000;
      
      /**
       * resize inner block to fit 630 x 360 image
       */
      function resizeInner() {
        var $active_ill = $('.ann-page-selected .ann-page-ill:first');
        if ( $container.length > 0 )
          $body.height($active_ill.width()/630*360);
      }
      
      $(window).resize(resizeInner);
      resizeInner();

      if ( $slideLinks.length < 1 )
        return ;
      if ( $slideLinks.filter('.loading').length < 1 )
        $slideLinks.last().addClass('loading');
      
      var goToNext = function() {
        var $next = $slideLinks.filter('.loading').prev('.button_square');
        if ( $next.length == 0 )
          $next = $slideLinks.last();
        var preloadNext = new Image();
        stop();
        preloadNext.onload = function() {
          showSlide.call($next.get(0));
          run();
        }
        preloadNext.src = $next.attr('href');
      }
      var run = function() {
        interval = setInterval(goToNext, goInterval);
        //console.log('run');
      }
      Slideshow.run = run;

      var stop = function() {
        clearInterval(interval);
        //console.log('stop');
      }
      Slideshow.stop = stop;
      
      var slideTo = function(src) {
        var $curImage = $container.find('.image');
        var $newImage = $('<img src="' + src + '" class="image">');
        $curImage.css('z-index', 2);
        $newImage.css('z-index', 1);
        $newImage.appendTo($container);
        $curImage.animate({opacity: 0}, slideDuration, slideEasing, function(){
          $(this).remove();
        })
      }

      var showSlide = function(){
        if ( !$(this).hasClass('loading') ) {
          $slideLinks.filter('.loading').removeClass('loading');
          $(this).addClass('loading');
          slideTo(this.href);
        }
      }

      $slideLinks.click(function(){
        stop();
        showSlide.call(this);
        run();
        return false;
      });

      run();
    });

    /*
     * --------------  For you list  --------------
     */
    $('ul.for_you_list').each(function(){
      var $links = $(this).find('li');
      var $contents = $('.fot_you_content-container .fot_you_content');
      var interval = null;
      var goInterval = 5000;
      var $expoTab = $links.first();

      var goToNext = function() {
        var $next = $links.filter('.selected').next('li');
        if ( $next.length == 0 )
          $next = $links.eq(0);
        selectItem.call($next.get(0));
      }

      var selectItem = function(){
        if ( !$(this).hasClass('selected') ) {
          $links.filter('.selected').removeClass('selected');
          $(this).addClass('selected');
          $contents.filter('.selected').removeClass('selected');
          $contents.eq($(this).attr('_num')).addClass('selected');
          if ( $expoTab.hasClass('selected') )
            Slideshow.run()
          else
            Slideshow.stop()
        }
      }

      var run = function() {
        interval = setInterval(goToNext, goInterval);
      }

      var stop = function() {
        clearInterval(interval);
      }

      $('.fot_you_content-container').add(this).hover(function(){
        stop();
      }, function(){
        run();
      });

      $links.each(function(num){
        $(this).attr('_num', num);
      });

      $links.mouseover(selectItem);

      run();
    });

    /*
     * --------------  Content scroll to top button  --------------
     */

    $(document).mousewheel(function() {
      $('html, body').stop();
	  });

    $('a.scroll_top').click(function(){
      $('body, html').animate({
        scrollTop : 0
      }, Math.max($('body').get(0).scrollTop, $('html').get(0).scrollTop) * .5, 'easeOutQuint');
      return false;
    });
    
    function filter(link) {
      return link.href && link.hash && (/.*#.+/.test(link.href));
    };
    
    $('a[href*=#]').each(function() {
      if (filter(this)) {
        var $targetId = $(this.hash);
        var $targetAnchor = $('a[name=' + this.hash.slice(1) + ']');
        var $target = $targetId.length ? $targetId : $targetAnchor.length
            ? $targetAnchor
            : false;
        if ($target) {
          $(this).click(function() {
                var targetOffset = $target.offset().top;
                var linkOffset = $(this).offset().top;
                var duration = Math.abs(targetOffset - linkOffset);
                $('html, body').animate({
                      scrollTop : targetOffset
                    }, duration * .7, 'easeOutQuint');
                return false;
              });
        }
      }
    });


    /*
     * --------------  Bottom menu resize width fo NON IE browsers --------------
     */
    if ( !$.browser.mise ) {
      $('#bottom_menu').each(function(){
        var $bottom_menu = $(this);
        $bottom_menu.width($('#contentPaddingMeasurerForIE').width());
        $(window).resize(function(){
          $bottom_menu.width($('#contentPaddingMeasurerForIE').width());
        });
      });
    }

    /*
     * --------------  Search by selector --------------
     */
    $('#search_by').each(function(){
      var $search_by = $(this);
      var $value = $search_by.find('input:first');
      var $text = $('#search_by_input td.search_by');
      var $input = $('#search_by_input td.search_by_query input:first');
      $search_by.find('a').click(function(){
        $value.val(this.hash.slice(1));
        $text.get(0).innerHTML = this.innerHTML.replace('- ','') + " |&nbsp;";
        $input.focus();
        return false;
      });
      $search_by.hover(function(){
        $search_by.addClass('opened')
      }, function(){
        $search_by.removeClass('opened')
      })
    });


    /* 
     * --------------  Top menu --------------  
     */
    $('#header').each(function(){
      var fadeSpeed = 200;
      var $header = $(this);
      var $header_content = $('#header-content');
      var $header_wrapper = $(this).find('.main_wrapper:first');
      var $top_menu = $('#top_menu');
      var $submenus = $top_menu.find('td ul');
      var $links = $top_menu.find('td>a');
      var $content_real = $('#content-real');
      var preloadBg = new Image();
      preloadBg.src = '/img/bg_opened_menu.png';
      $links.mouseover(function(){
        /*if ( location.href.match(/#version_1/i) )
          $header_content.css('background', '#181717');
        else*/
          //$header_content.css('background', 'url(/img/bg_opened_menu.png)');
          //$header_content.css('background-color', '#141212');
        //$header_wrapper.css('paddingBottom', '24px');
        //if ( !location.href.match(/#version_2/i) )
        //  $header_wrapper.css('background', 'url(/img/btn_close_header_menu.gif) no-repeat center bottom');
        //$top_menu.css('height', 'auto');
        //$submenus.show();
        if ( !comuterIsSlow )
          $content_real.stop().animate({opacity: 0}, fadeSpeed);
        else {
          /*if ( location.href.match(/#version_1/i) ) {
            $content_real.css('opacity', .1);
          } else if ( location.href.match(/#version_2/i) ) {
            
          } else {
            $content_real.css('visibility', 'hidden');
          }*/
        }
      });
      var closeMenu = function(){
        if ( !comuterIsSlow )
          $content_real.stop().animate({opacity: 1}, fadeSpeed, function(){
            $header_content.css('background', 'transparent');
          });
        else {
          /*if ( location.href.match(/#version_1/i) ) {
            $content_real.css('opacity', 1);
          } else if ( location.href.match(/#version_2/i) ) {

          } else {
            $content_real.css('visibility', 'visible');
          }*/
          //$header_content.css('background', 'transparent');
        }
        //$header_wrapper.css('paddingBottom', '0');
        //$header_wrapper.css('background', 'transparent');
        //$top_menu.css('height', '60px');
        //$header.removeClass('opened_top_menu');
        return false;
      };

      if ( location.href.match(/#version_3/i) ) {
        $('<a href="#" style="height: 24px; width: 173px; display: block; position: absolute; left: 50%; margin-left: -86px; bottom: 0;"></a>')
          .click(closeMenu)
          .appendTo($header_wrapper);
      } else {
        $header_content.mouseleave(closeMenu);
      }
    });

    /*
     * bookmarks
     */
    $('.bookmarks-list').each(function() {
      var $li = $(this).find('li');
      var $div = $(this).parents('.bookmarks-container').eq(0)
          .find('.bookmarks-content');
      var num = 0;

      $li.each(function() {
            var $this = $(this);
            var $content = $div.slice((function() {
                  return num
                })(), (function() {
                  return num + 1
                })());

            $this.click(function() {
                  if ($this.hasClass('selected'))
                    return false;
                  $li.removeClass('selected');
                  $div.removeClass('bookmarks-selected');
                  $this.addClass('selected');
                  $content.addClass('bookmarks-selected');

                  return false;
                })
            num++;
          });
    })

  // document ready end
  });

/**
 *            Easing functions
 */
/*
 * 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.
 *
*/
jQuery.extend(jQuery.easing, {
  easeOutQuint : function(x, t, b, c, d) {
    return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
  },
  easeOutQuad: function (x, t, b, c, d) {
          return -c *(t/=d)*(t-2) + 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;
  },
  easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + 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.
 *
 */

/**
 * Returns an object with mouse cursor position
 *
 * @param {Event} [evt]
 * @return {} {x:, y:}
 */
function mouseXY(evt) {
	if (evt.pageX && evt.pageY)
		return {
			x : evt.pageX,
			y : evt.pageY
		};
	else if (evt.clientX && evt.clientY)
		return {
			x : evt.clientX
					+ (document.documentElement.scrollLeft
							? document.documentElement.scrollLeft
							: document.body.scrollLeft),
			y : evt.clientY
					+ (document.documentElement.scrollTop
							? document.documentElement.scrollTop
							: document.body.scrollTop)
		};
	else
		return null;
}

/**
 * Scroll block content depend on mouse cursor position
 *
 * NOTE it's scroll automaticaly on window resize because of setInterval wich call scroll function
 * REQUIRE mouseXY function and jQuery.offset() method ot equal
 *
 * @param {HTMLElement} [obj] block to scroll content
 * @param {Object} [settings] settings obeject which can contain:
 *  - stepFrequency: (default 50) how offen we refresh content scroll in milliseconds
 *  - stepQuont: (default 3) now much steps we use to reach new cursor position when we move mouse
 *  - controlSpace: (default [obj]) a space where mouse shoould move to scroll [obj] content
 *
 */
  ContentScroller = function(obj, settings) {
    this.obj = obj;

    // private
    this.mouseCoords = {
      x: 0,
      y: 0
    };
    this.interval = null;

    // settings
    this.settings = {};
    this.settings.stepFrequency = 50;
    this.settings.stepQuont = 3;
    this.settings.controlSpace = obj;
    this.settings.autoenable = true;

    // apply object settings
    for ( var option in settings )
      this.settings[option] = settings[option];

    this.init();
  }

  ContentScroller.prototype = {
    /*
	 * scroll content depend on omuse cursor position
	 */
    scroll: function() {
      // scroll horizontally
      var scrollDistanceX = this.obj.scrollWidth - this.obj.offsetWidth;
      if (scrollDistanceX > 0){
        var scrollX = this.mouseCoords.x / this.settings.controlSpace.offsetWidth * scrollDistanceX;
        var stepX = ( scrollX - this.obj.scrollLeft ) / this.settings.stepQuont;
        if ( Math.abs(stepX) > 1 )
          this.obj.scrollLeft += Math.round(stepX);
      }
      //console.log(this.obj.offsetWidth, this.obj.scrollWidth, this.mouseCoords.x, scrollX);

      // scroll vertically
      var scrollDistanceY = this.obj.scrollHeight - this.obj.offsetHeight;
      if (scrollDistanceY > 0 ) {
        var scrollY = this.mouseCoords.y / this.settings.controlSpace.offsetHeight * scrollDistanceY;
        var stepY = ( scrollY - this.obj.scrollTop ) / this.settings.stepQuont;
        if ( Math.abs(stepY) > 1 )
          this.obj.scrollTop += Math.round(stepY);
      }
    },
  
    /*
	 * track mouse cursor position and act appropriately
	 */
    init: function() {
      var self = this;

      // refresh mouse cursor position
      $(this.settings.controlSpace).mousemove(function(/* Event */evt) {
        var mouseCusor = mouseXY(evt);
        // TODO avoid using offset() function by using evt.layerX - W3C, evt.offsetX - IE
        var spacePos = $(self.settings.controlSpace).offset();
        if ( mouseCusor )
          self.mouseCoords = {
            x: mouseCusor.x - spacePos.left,
            y: mouseCusor.y - spacePos.top
            };
      //console.log(evt.layerX, evt.layerY);
      });
      if ( this.settings.autoenable )
        this.enable();
    },

    enable: function() {
      var self = this;
      // call scroll function with defined frequency
      this.interval = setInterval(function(){
        self.scroll()
        }, this.settings.stepFrequency);
    },

    disable: function() {
      clearInterval(this.interval);
    }
  }

$.fn.checkbox = function(){
  return this.each(function(){
    var $real = $(this);
    var $decor = $('<span class="checkbox"></span>');

    $decor.click(function(){
      if ( $real.attr('checked') ) {
        $decor.removeClass('checkbox-checked');
        $real.attr('checked', false).trigger('change');
      } else {
        $decor.addClass('checkbox-checked');
        $real.attr('checked', true).trigger('change');
      }
    });

    $real.hide();
    $decor.insertAfter($real);
  });
};

// implemented for two pages only
$.fn.pages = function(){
  return this.each(function(){
    var $container = $(this);
    var $pages = $('.page', $container);
    var scrollSpeed = 500;
    var scrollEasing = 'easeInOutQuart';

    $container.find('.page-next').click(function(){
      $container.css('left', '0'); /* should be redefined for several pages */
      $container.animate({left: '-=' + $pages.eq(0).width() + 'px'}, scrollSpeed, scrollEasing, function(){
        $container.css('left', '-100%');  /* should be redefined for several pages */
      });
      return false;
    });

    $container.find('.page-prev').click(function(){
      $container.css('left', -$pages.eq(0).width());  /* should be redefined for several pages */
      $container.animate({left: '+=' + $pages.eq(0).width() + 'px'}, scrollSpeed, scrollEasing, function(){
        $container.css('left', '0');  /* should be redefined for several pages */
      });
      return false;
    });

  });
};

$.fn.showInfo = function($info, settings){
  return this.each(function(){
    var $content = $('#content-real .main_content:first');
    var $space = $(this);
    var $infoBg = $info.find('.info-bg:first');
    var isIE6 = $.browser.msie && $.browser.version < 7;
    settings = $.extend({
      autoalign: true,
      top: 0,
      left: 0,
      $leftIsWidthOf: null
    }, settings);
    $info.appendTo($content);
    if ( isIE6 ) {
      var $infoRight = $('<div class="info-right"></div>').appendTo($infoBg);
    }
    $space.hover(function(){
      var offset = realOffset(this);
      if ( offset.left < $content.width() / 2 || !settings.autoalign ) {
        $info.css({
          background: 'url(/img/bg_info-left.png) no-repeat',
          left: offset.left + settings.left + ( settings.$leftIsWidthOf != null ? settings.$leftIsWidthOf.width() : 0),//offset.left + settings.left,
          right: 'auto',
          padding: '0 0 0 8px'
        });
        $infoBg.css({
          padding: '0 2px 4px 0'
        });
        if ( isIE6 ) {
          $infoRight.hide();
          $info.css({background: ''});
          $info.get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/img/bg_info-left.png',sizingMethod='crop')";          
        }
      } else {
        $info.css({
          background: 'url(/img/bg_info-right.png) no-repeat right top',
          right: $content.width() - 54 - offset.left + settings.left + ( settings.$leftIsWidthOf != null ? settings.$leftIsWidthOf.width() : 0) ,
          left: 'auto',
          padding: '0 8px 0 0'
        });
        $infoBg.css({
          padding: '0 0 4px 2px'
        });
        if ( isIE6 ) {
          $infoRight.show();
          $info.css({background: ''});
          $info.get(0).runtimeStyle.filter = "";
        }
      }
      $info
        .css({
          top: offset.top + settings.top
        })
        .show();
      if ( isIE6 ) {
        $infoRight.css({height: $info.height()});
      }
    }, function(){
      $info.hide();
    });
  });
};

$.fn.submitable = function(callback, callforward) {
  return this.each(function(){
    var $submit = $(this);
    var $form = null;
    if ( $submit.parents('form:first').length > 0 )
      $form = $submit.parents('form:first');
    else
      $form = $submit.prev('form');
    var isActive = false;
    var submitClass = $submit.hasClass('submit') ? 'submit' : 'submit_ajax';

    $submit.click(function(){
      try {
        var data = $form.serializeArray(),
            type = $form.attr('method'),
            url = $form.attr('action') + ( $form.attr('action').indexOf('?') >= 0 ? '&' : '?') + 'nobot=1';
        if ( isActive ) {
          if ( typeof callback != 'function' )
            $form.submit();
          else {
            if ( typeof callforward == 'function' )
              callforward.call();
            //console.log('test', data);
            $.ajax({
              data: data,
              type: type,
              url: url,
              complete: callback
            })
          }
        }
      } catch (e) {
      
      }
      return false;
    });

    $form.validate(function(){
        $submit.removeClass(submitClass);
        isActive = true;
      },
      function(){
        $submit.addClass(submitClass);
        isActive = false;
      }
    );
    });
}

$.fn.validate = function(/* Function */onValid, /* Function */onInvalid){
    var $form = $(this);
    var events = 'change focus keyup';
    var fieldsStates = new Array();
    var groupStates = new Array();

    var isValidField = function() {
      var isValid = true;
      var value = $(this).val();

      if ( $(this).hasClass('label') )
        value = '';

      if ( $(this).hasClass('v-required') ) {
        isValid = isValid && value != '';
      }

      if ( $(this).hasClass('v-email') ) {
        isValid = isValid && /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(value);
      }

      return isValid;
    }

    var isValidForm = function() {
      var isValid = true;
      var isGroupValid;
      var i;
      for ( i in groupStates ) {
        isGroupValid = false;
        for ( k = 0; k < groupStates.length; k++ )
          isGroupValid = isGroupValid || groupStates[i][k];
        isValid = isValid && isGroupValid;
      }
      for ( i = 0; i < fieldsStates.length; i++ )
        isValid = isValid && fieldsStates[i];
      return isValid;
    }

    $form.find('.v-email, .v-required').each(function(){
      var group = this.className.match(/v\-required\-(\d+)/);
      if ( group == null )
        fieldsStates.push(false);
      else {
        if ( typeof groupStates[group[1]] != 'object' ) {
          groupStates[group[1]] = new Array();
        }
        groupStates[group[1]].push(false);
      }

      (function(num){
        $(this).bind(events, function(){
          if ( group == null ) {
            fieldsStates[num] = isValidField.call(this);
          } else {
            groupStates[group[1]][num] = isValidField.call(this);
          }
          if ( isValidForm() )
            onValid();
          else
            onInvalid();
        });
      }).call(this, group == null ? fieldsStates.length - 1 : groupStates[group[1]].length - 1 );

    });

    // if form have not validatable fields
    if ( fieldsStates.length < 1 && groupStates.length < 1 )
       onValid();

  return this;
};

$.fn.reflection = function(img_src, settings) {
  return this.each(function(){
    var image = new Image();
    var d = this;
    image.onload = function() {
      image.onload = null; // for ie
      try {
        var reflectionHeight = parseFloat(settings.height) < 1 ? Math.floor( image.height *  parseFloat(settings.height) ) : parseInt(settings.height);
        var reflectionWidth = image.width;

        if (document.all && !window.opera) {
          var reflection = document.createElement('img');
          reflection.src = image.src;
          reflection.style.width = '100%';
          reflection.style.display = 'block';
          reflection.style.height = image.height+"px";
          reflection.style.filter = 'flipv progid:DXImageTransform.Microsoft.Alpha(opacity=' + (settings.opacityTop * 100) + ', style=1, finishOpacity=' + (settings.opacityBottom * 100) + ', startx=0, starty=0, finishx=0, finishy=' + (reflectionHeight) + ')';
          d.runtimeStyle.height = reflectionHeight + 'px';
          d.appendChild(reflection);
        } else {
          var canvas = document.createElement('canvas');
          if (canvas.getContext) {
            var context = canvas.getContext("2d");

            canvas.style.height = reflectionHeight+'px';
            canvas.style.width = reflectionWidth+'px';
            canvas.height = reflectionHeight;
            canvas.width = reflectionWidth;

            d.appendChild(canvas);

            context.save();

            context.translate(0,image.height-1);
            context.scale(1,-1);

            context.drawImage(image, 0, 0, reflectionWidth, image.height);

            context.restore();

            context.globalCompositeOperation = "destination-out";
            var gradient = context.createLinearGradient(0, 0, 0, reflectionHeight);

            gradient.addColorStop(1, "rgba(255, 255, 255, " + (1 - settings.opacityBottom) + ")");
            gradient.addColorStop(0, "rgba(255, 255, 255, " + (1 - settings.opacityTop)   + ")");

            context.fillStyle = gradient;
            context.rect(0, 0, reflectionWidth, reflectionHeight*2);
            context.fill();
          }
        }
      } catch (e) {
      }
    }
    //on image load
    image.src = img_src;
  });
}

$.fn.flip = function(img_src, settings) {
  return this.each(function(){
    var image = new Image();
    var d = this;
    image.onload = function() {
      settings = $.extend({
        width: image.width,
        height: image.height
      }, settings);
      image.onload = null; // for ie
      try {
        if (document.all && !window.opera) {
          var flip = document.createElement('img');
          flip.src = image.src;
          flip.style.height = settings.height+"px";
          flip.style.width = settings.width + "px";
          flip.style.display = 'block';
          flip.style.filter = 'flipv';
          d.appendChild(flip);
        } else {
          var canvas = document.createElement('canvas');
          if (canvas.getContext) {
            /* Copy original image's classes & styles to div */
            var context = canvas.getContext("2d");

            canvas.style.height = settings.height + "px";
            canvas.style.width = settings.width + "px";
            canvas.height = settings.height;
            canvas.width = settings.width;

            d.appendChild(canvas);

            context.save();

            context.translate(0, settings.height-1);
            context.scale(1,-1);

            context.drawImage(image, 0, 0, settings.width, settings.height);

            context.restore();            
          }
        }
      } catch (e) {
      }
    }
    //on image load
    image.src = img_src;
  });
}
  /**
   *  contentScroller
   */
  $.fn.contentScroller = function(settings)
  {
    return this.each(function(){
      settings = $.extend({
        contentQuery: '.content',
        scrollUpBtnQuery: '.sroll_up',
        scrollDownBtnQuery: '.sroll_down',
        scrollUpBtnDisabled: 'sroll_up-disabled',
        scrollDownBtnDisabled: 'sroll_down-disabled',
        scrollEasing: 'linear',
        scrollDuration: 200,
        scrollDir: 'vertical',
        scrollLength: .4
      }, settings);

      var $self          = $(this),
          $content       = $self.find(settings.contentQuery),
          $scrollUpBtn   = $self.find(settings.scrollUpBtnQuery),
          $scrollDownBtn = $self.find(settings.scrollDownBtnQuery);

      var scroll = function(dir) {
        var scrollLength = 0;
        var scrollDiff = 0;

        // stop all animations
        $content.stop();

        if ( settings.scrollDir == 'vertical' ) {

          scrollLength = settings.scrollLength < 1 ? $content.height() * settings.scrollLength : settings.scrollLength;
          scrollDiff = $content.get(0).scrollHeight - $content.get(0).offsetHeight;
          if ( $content.get(0).scrollTop + dir*scrollLength > scrollDiff || scrollDiff == 0 ) {
            $scrollDownBtn.addClass(settings.scrollDownBtnDisabled);
          } else {
            $scrollDownBtn.removeClass(settings.scrollDownBtnDisabled);
          }
          if ( $content.get(0).scrollTop + dir*scrollLength < 0 || scrollDiff == 0 ) {
            $scrollUpBtn.addClass(settings.scrollUpBtnDisabled);
          } else {
            $scrollUpBtn.removeClass(settings.scrollUpBtnDisabled);
          }
          $content.animate({scrollTop: $content.get(0).scrollTop + dir*scrollLength}, settings.scrollDuration, settings.scrollEasing);

        } else {

          scrollLength = settings.scrollLength < 1 ? $content.width() * settings.scrollLength : settings.scrollLength;
          $content.animate({scrollLeft: $content.get(0).scrollLeft + dir*scrollLength}, settings.scrollDuration, settings.scrollEasing);

        }
      }
      // end of scroll function

      $scrollUpBtn.click(function(){
        $content.stop();
        scroll(-1);
        return false;
      });

      $scrollDownBtn.click(function(){
        $content.stop();
        scroll(1);
        return false;
      });

      $content.mousewheel(function(event, delta){
        if (delta > 0) {
					scroll(-1);
        } else if (delta < 0) {
					scroll(1);
        }
        // if we reach the end of content allow to scroll page
        //if ( !$scrollDownBtn.hasClass(settings.scrollDownBtnDisabled) && !$scrollUpBtn.hasClass(settings.scrollUpBtnDisabled)  )
          return false;
      });

    });
  }

  showMessageTimeout = null;

  showMessage = function(text, closeOnClick) {
    var settings = {
      overlaySpeed:   200,
      overlayBgColor: '#000',
      overlayOpacity: '0.9',
      closeTimeout:   3000
    }

    if ( typeof closeOnClick == 'undefined' )
      closeOnClick = true;

    var $msgOverlay = $('#msgOverlay');
    var $msgWin = $('#msgWin');
    
    if ( $msgOverlay.length < 1 ) {
      $msgOverlay = $('<div id="msgOverlay" style="display:none; height: 100%; left: 0; position: absolute; top: 0; width: 100%; z-index: 1000;"></div>');
      $msgWin = $('<div id="msgWin" style="display:none; background: #f00; color: #fff; font: bold 14px Arial; padding: 15px; position: absolute; z-index: 1001;"></div>');
      $('body').append($msgOverlay).append($msgWin);
    }

    var arrPageSizes = getPageSize();
    var arrPageScroll = getPageScroll();
    
    $msgOverlay
      .css({
        backgroundColor:  settings.overlayBgColor,
        opacity:          settings.overlayOpacity,
        width:            arrPageSizes[0],
        height:           arrPageSizes[1]
      });

    $msgOverlay.filter(':hidden').fadeIn(settings.overlaySpeed);

    $msgWin
      .html(text)
      .css({
        top:              arrPageScroll[1] + arrPageSizes[3] / 2 - $msgWin.height() / 2 - 15,
        marginLeft:       '-15%',
        left:             '50%',
        width:            '30%'
      })
      .show();

    //$msgWin.animate({top: arrPageScroll[1] + arrPageSizes[3] / 2 - $msgWin.height() / 2 });

    clearTimeout(showMessageTimeout);
    if ( closeOnClick ) {
      showMessageTimeout = setTimeout(hideMessage, settings.closeTimeout);
      $msgOverlay.add($msgWin).bind('click', hideMessage);
    } else {
      $msgOverlay.add($msgWin).unbind('click', hideMessage);
    }
    
  }

  hideMessage = function() {
    var settings = {
      overlaySpeed:   200
    }

    var $msgOverlay = $('#msgOverlay');
    var $msgWin = $('#msgWin');

    clearTimeout(showMessageTimeout);
    $msgWin.hide();
    $msgOverlay.fadeOut(settings.overlaySpeed);
    return false;
  }
  
})(jQuery);

function realOffset(obj) {
  var curleft = 0;
  var curtop = 0;
  if( obj.offsetParent )
    while(1) {
      //console.log(obj, obj.offsetLeft);
      if( obj.id == 'content-real' )
        break;
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
      if( !obj.offsetParent )
        break;
      obj = obj.offsetParent;
    }
  else if ( obj.x && obj.y ) {
    curleft += obj.x;
    curtop += obj.y;
  }
  //console.log(curleft, curtop);
  return {left: parseInt(curleft), top: parseInt(curtop)};
}

function disableSelection(target){
  if (typeof target.onselectstart!="undefined") //IE route
    target.onselectstart=function(){return false}
  else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
    target.style.MozUserSelect="none"
  else //All other route (ie: Opera)
    target.onmousedown=function(){return false}
  target.style.cursor = "default"
}

/*
 *  IE onDomReady function which is used to tun expression after DOM is loaded
 */

(function(){

  var
  DOMready = setInterval(function(){
    try{
      document.documentElement.doScroll("left");
      clearInterval(DOMready);
      DOMready = true;
      for (var f in fn){
        fn[f]();
      }
    }catch(e){}
  }, 10),
  
  fn = [];

  window.onIEDomReady = function(el, func){
    if (!el) return;
    if ( typeof func != 'function' ) return;
    if (DOMready === true){
      func.call(el);
    } else {
      fn.push(function(){
        func.call(el);
      });
    }
  }
  
})()

/**
 * Returns page and window size
 * @return Array(pageWidth,pageHeight,windowWidth,windowHeight)
 */
getPageSize = function() {
  var xScroll, yScroll;
  if (window.innerHeight && window.scrollMaxY) {
          xScroll = window.innerWidth + window.scrollMaxX;
          yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
          xScroll = document.body.scrollWidth;
          yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
          xScroll = document.body.offsetWidth;
          yScroll = document.body.offsetHeight;
  }
  var windowWidth, windowHeight;
  if (self.innerHeight) {	// all except Explorer
          if(document.documentElement.clientWidth){
                  windowWidth = document.documentElement.clientWidth;
          } else {
                  windowWidth = self.innerWidth;
          }
          windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
          windowWidth = document.documentElement.clientWidth;
          windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
          windowWidth = document.body.clientWidth;
          windowHeight = document.body.clientHeight;
  }
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
          pageHeight = windowHeight;
  } else {
          pageHeight = yScroll;
  }
  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){
          pageWidth = xScroll;
  } else {
          pageWidth = windowWidth;
  }
  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
  return arrayPageSize;
};

/**
 / THIRD FUNCTION
 * getPageScroll() by quirksmode.com
 *
 * @return Array Return an array with x,y page scroll values.
 */
function getPageScroll() {
        var xScroll, yScroll;
        if (self.pageYOffset) {
                yScroll = self.pageYOffset;
                xScroll = self.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
                yScroll = document.documentElement.scrollTop;
                xScroll = document.documentElement.scrollLeft;
        } else if (document.body) {// all other Explorers
                yScroll = document.body.scrollTop;
                xScroll = document.body.scrollLeft;
        }
        arrayPageScroll = new Array(xScroll,yScroll);
        return arrayPageScroll;
};
