
if (!window.console)
{
  window.console = {
    log : function(){},
    dir : function(){},
    info : function(){},
    error : function(){}
  }
}


(function($) {$(document).ready(function() {
    
    $('.architector-works a').hugeGallery();
    
  if ( typeof _gaq == 'undefined' ) {
    _gaq = [];
    currLength = _gaq.length;
    $('<div id="alert" style="position:absolute; left:50%;top:50%; z-index:100;background:red;color:white;"></div>').appendTo(document.body); 
    setInterval(function() {
      //console.log(_gaq);
      if ( currLength < _gaq.length ) {
        for ( var i = currLength; i < _gaq.length; i++ )
          console.info(_gaq[i]);
        currLength = _gaq.length;
      }
    },100);  
  }

  // insert religious calendar
  $('#ch_calendar').each(function(){
    var $this = $(this);
    var $iFrame = $('<iframe src="http://'+ window.location.hostname + '/days_calendar.html" style="display: none;" id="days_calendar"></iframe>');  
    $iFrame.load(function(){        
      var $cont = $(this).contents();
      $cont.find('script').remove()
      $this.append($cont.find('body').html());
    }).appendTo(document.body);
  });
  
	/*
	 * slow scrolling to anchor
	 */
	function filter(link) {
		return link.href && link.hash && (/.*#.+/.test(link.href));
	};

	$(document).mousewheel(function() {
				$('html, body').stop();
			});

	$('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;
						});
			}
		}
	});

	/*
	 * 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++;
				});
	})
	
	/*
	 * top menu
	 */

  $.fn.dropdownMenuCalculate = function(self) {
        var tdcw = self.$tdc.get(0).offsetWidth,
            tdlw = self.$tdl.get(0).offsetWidth,
            tdrw = self.$tdr.get(0).offsetWidth;
        var pos = self.$tdl.offset();
        pos = {x: pos.left, y: pos.top};
        var fullPos = {left: 0, top: 0};//$table1.offset();
        self.block_link_marginLeft = (self.$list.hasClass('full') ? pos.x - 18 : 0 )
        /*self.$li_a
            .css({
              paddingLeft: tdlw + 1,
              paddingRight: tdlw + 1
            });*/
        self.$block_link
          .css({
 						marginLeft: self.block_link_marginLeft,
            paddingLeft: tdlw + 1,
            width: tdcw + tdrw - 2
          });
        self.$block
          .css({
            top: pos.y + self.top_fix,
            left: (self.$list.hasClass('full') ? 18 : (pos.x + self.left_fix) ),
       			width: (self.$list.hasClass('full') ? $('#goods_by').width() - 36 /* margings sum */ : 'auto')
          });
  }

  $.fn.dropdownMenuClose = function(self) {
       self.$block
         .hide()
         .remove();
       $(document).unbind('mousemove', self.overcontrol);
  };

  $.fn.dropdownMenuControl = function(self, evt) {
          var mouse = mouseXY(evt);
          var left = parseInt(self.$block.css('left')),
              top = parseInt(self.$block.css('top'));
          if ( mouse.x < left ||
               mouse.x > left + self.$block.width() ||
               mouse.y < top ||
               mouse.y > top + self.$block.height() )
            $.fn.dropdownMenuClose(self);

          if ( ( mouse.x < left + self.block_link_marginLeft||
               mouse.x > left + self.block_link_marginLeft + self.$block_link.get(0).offsetWidth ) &&
               mouse.y > top &&
               mouse.y < top + self.$block_link.height() )
            $.fn.dropdownMenuClose(self);
  };

  $.fn.dropdownMenuOpen = function(self, manual) {
        self.$list = self.$link.next('.dropmenu').clone();
        if ( self.$list.length < 1 ) return;
        $('a.submit', self.$list).submitable();
        self.left_fix =( $.browser.msie || $.browser.safari || $.browser.opera ) ? 0 : -1;
        self.top_fix = 0;
        self.$block = $('<div class="dropdown-container' + (self.$list.hasClass('info_menu') ? ' info_menu' : '') + '"><a href="' + self.$link.attr('href') + '" class="'+ self.$link.get(0).className +' dropdown-close">'+ self.$link.html() +'</a></div>');
   			if ( self.$list.hasClass('full') ) {
    			self.$block.addClass('full');
      	}
        self.$li_a = self.$list.find('li>a');
        self.$block_link = self.$block.find('.dropdown-close');
        self.block_link_marginLeft = 0;

        $.fn.dropdownMenuCalculate(self);

        self.overcontrol = function(evt){$.fn.dropdownMenuControl(self, evt)};
        
        if ( typeof manual == 'undefined' || manual == false )
          $(document).mousemove(self.overcontrol);

        self.$list
          .appendTo(self.$block)
          .css({display: 'block'});
        self.$block
          .appendTo('body')
          .show();//.width(Math.max($block.width(), $block_link.width()));
        if ( $.browser.msie ) {
        	if ( ! self.$list.hasClass('full') ) {            
        		var tdlw = self.$tdl.get(0).offsetWidth,
            		tdrw = self.$tdr.get(0).offsetWidth;
            if ( $.browser.version < 7 ) {
              var $basket_button = self.$list.find('a.button');
              self.$li_a.css('width',self.$block.width() - ( $basket_button.length > 0 ? 60 : 20 ) /* borders */);
              $basket_button.width(self.$block.width() - 20);
            }           
          	// set width explicitly
        		var old_width = self.$block.width();
        		var new_width = Math.max(self.$block.width(), self.$block_link.width() + tdlw + 1);

        		self.$block.width( ( old_width == new_width ? new_width + 1: new_width ) );
        	} else {
        		self.$list.width(self.$block.width());
        	}
        };
  }

  $.fn.dropdownMenuInit = function(this_) {
      var self = {
        $link: $(this_),
        $tdc: null,
        $tdl: null,
        $tdr: null,
        $list: null,
        $li_a: null,
        $block_link: null,
        $block: null,
        block_link_marginLeft: 0,
        top_fix: 0,
        left_fix: 0,
        overControl: null
      }

      self.$tdc = self.$link.parent('td');
      self.$tdl = self.$tdc.prev('td');
      self.$tdr = self.$tdc.next('td');

      return self;
  }

  $.fn.dropdownMenu = function(settings) {
    return this.each(function(){
      var self = $.fn.dropdownMenuInit(this);
      
      self.$link.bind('mouseover', function(){
        $.fn.dropdownMenuOpen(self);
      });
    })
  }
	
	$('#goods_by td>a, #info_menu td>a').dropdownMenu();

  /*
	 * manufacturer list
	 */
  $('#manufacturers-link').each(function() {  	
  	var $block = $('#manufacturers-list');
    var $link = $(this);
  	$link.mouseover(function(){
      $link.addClass('hover');
  		$block
  			.width($('#goods_by').width()-36)
  			.slideDown(150, function() {
  				$(document).mousemove(overControl);
  			});  		
  	})
  	var close = function() {
      $link.removeClass('hover');
  		$block.slideUp(150);
  		$(document).unbind('mousemove',overControl);
  	}
  	var overControl = function(evt) {
  				var mouse = mouseXY(evt);
          var left = 18,//parseInt($block.css('left')),
              top = 136;//parseInt($block.css('top'));
          if ( mouse.x < left ||
               mouse.x > left + $block.width() || 
               mouse.y < top ||
               mouse.y > top + $block.height() )
            close($block);  
          //console.log(top,mouse.y,top + $block.height());
  	};
  });
  
  $('.bookmark').click(function() {
  	bookmarkpage();
  	return false;
 	})

  /*
	 * you_can_popup
	 */
 	var popups = new Array();
 	
 	$('.you_can_popup').each(function() {
 		// init
 		var $popup = $(this);
 		var $link = $popup.parent('li').find('>a');
 		var $ul = $link.parents('ul:eq(0)');    
 		$popup.find('a.close').text($link.text());
 		$popup = $popup.clone(false).appendTo(document.body);
    
    var $phone = $popup.find('input[name="phone"]');
    var $submit = $popup.find('.submit_ajax');
    var $form = $popup.find('form');
    $submit.submitable(function(XMLHttpRequest, textStatus){      
      eval("var data = " + XMLHttpRequest.responseText);    
      var $overlay = $('div.overlay_centered');
      $overlay.find('td').html(data.text + '<br /><br /><a href="#" class="close_form">Закрыть</a>');
      $overlay.find('a.close_form').click(function(){
        $overlay.remove();
        $close.trigger('click', ['notrack']);
        return false;
      });
      $(this).find('input[type!=hidden], textarea').val('').trigger('change');
      setTimeout(function(){
        $overlay.remove();
      }, 5000);
    }, function(){
      if ( $submit.hasClass('button_dark') )  {
        _gaq.push(['_trackEvent', $form.attr('name'), 'nofillphone']);
        alert('Пожалуйста, укажите телефон.');
        return false;        
      }
      _gaq.push(['_trackEvent', $form.attr('name'), 'send']);
      $(document.body)
        .append('<div class="overlay_centered"><table class="centered"><tr><td><h2>Подождите, идет отправка...</h2></td></tr></table></div>');
      $('div.overlay_centered')
        .css({
          left: $popup.css('left'),
          top:  $popup.css('top'),
          width:  $popup.width(),
          height: $popup.height() + 17
        });
    });    
    
    $phone.bind('change focus keyup',function() {
      if ( $.trim($(this).val()).length > 0 ) {
        $submit.removeClass('button_dark');
        $(this).parent().find('.pull').slideDown(200);
      } else {
        $submit.addClass('button_dark');
      }
    });

 		var $close = $popup.find('.close');
 		popups.push($close);
 		
 		var recalc = function() {
 			var pos = $link.offset(); 			
 			$popup
 				.css({
 					left: pos.left - 15 /* li padding */,
 					top: pos.top - 17 /* you_can_popup padding-top*/,
 					width: $ul.width()
 				})
 		} 
 		
 		// open
 		$link.click(function() {
      _gaq.push(['_trackEvent', $form.attr('name'), 'open']);
 			// close other popups
 			for ( var i = 0; i < popups.length; i++ )
 				popups[i].trigger('click', ['notrack']);
 			recalc();
 			$popup.show();
 			$(window).resize(recalc);
 			return false;
 		})
 		
 		//close
 		$close.click(function(evt, notrack) {
      if ( typeof notrack == 'undefined' )
        _gaq.push(['_trackEvent', $form.attr('name'), 'close']);
 			$popup.hide();
 			$(window).unbind('resize', recalc);
 			return false;
 		})
 	});
 

	/*
	 * fix ie6
	 */
	if ($.browser.msie && $.browser.version < 7) {
		$('.catalog .item a, .kit .item a, #gallery_slider .slide .name').each(function() {
					$(this).mouseover(function() {
								$(this).addClass('hover');
							}).mouseout(function() {
								$(this).removeClass('hover');
							})
				})
	}

  /*
	 * init gallery slider
	 */
  $('#gallery_slider').gallerySlider();

  /*
	 * init gallery swap
	 */
  $('.item_description .images').gallerySwap();

	/*
	 * Furnit selectings
	 */  
  $.fn.furnitMatching = function(settings) {
    settings = $.extend({
      isFull: false
    },settings)
    return this.each(function(){
      var $this = $(this);
      var $button = $(this).find('div.furnit_matching-button a:first')
      var $html = settings.isFull ? $('#furnit_matching_full') : $('#furnit_matching');
      var $form = $html.find('form');
      var $selectButton = $html.find('.choose');
      var $closeButton = $html.find('.close');
      var $bntReset = $html.find('.reset');
      var $checkboxes = $form.find('.block input');
      var $tip = $('<div id="furnit_matching_tip"><div>Выбрано <span class="furnit_matching_tip-loader">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span class="furnit_matching_tip-quantity"></span> предметов <a href="#" onclick="_gaq.push([\'_trackEvent\', \'' + $form.attr('name')+ '\', \'go\',\'context\']);">Показать</a><span class="furnit_matching_tip-corner furnit_matching_tip-corner-left"></span></div></div>"')
      var tipTimer = null;
      var tipHoverd = false;

      // settings
      var tipShowTime = 2000;

      var getSnapShot = function(id, value) {
        var snapshot = {};
        snapshot.changed_id = id;
        snapshot.changed_value = value;
        snapshot['idarr[]'] = [];
        $form.find('input[type=checkbox]:checked').each(function(){
         snapshot['idarr[]'].push($(this).val());
        });
        return snapshot;
      }

      var applyResponse = function(data) {
        var $li = null;
        var isDisabled = false;
        //console.log(data.arr);
        $checkboxes.each(function(){
          //console.log($(this).val(), $.inArray($(this).val(), data.arr));
          isDisabled = $.inArray($(this).val(), data.arr) == -1 ? false : true;
          $(this).attr('disabled', isDisabled );
          $li = $(this).parent('li');
          if ( isDisabled )
            $li.addClass('disabled');
          else
            $li.removeClass('disabled');
        });
      }

      // prevent auto closing after mouseover
      $tip.hover(function(){
        tipHoverd = true;
      }, function(){
        tipHoverd = false;
        if ( !tipTimer )
          $tip.hide();
      });

      var showTip = function($checkbox, data) {
        var $li = $checkbox.parent('li');
        var offset = $li.offset();
        var docWidth = $(document.body).width();
        var pos = {top: offset.top - 4};
        if ( 240 < offset.left ) {
          pos = $.extend(pos, {
            right: docWidth - offset.left + 6,
            left: 'auto'
          })
          $tip.find('span.furnit_matching_tip-corner').removeClass('furnit_matching_tip-corner-left')
        } else {
          pos = $.extend(pos, {
            left: offset.left + $li.width(),
            right: 'auto'
          })
          $tip.find('span.furnit_matching_tip-corner').addClass('furnit_matching_tip-corner-left')
        }
        // show loader if no data
        if ( typeof data == 'undefined' ) {
          $tip
            .hide()
            .find('span.furnit_matching_tip-loader').show().end()
            .find('span.furnit_matching_tip-quantity').hide().end()
            .find('a').hide().end()
            .css(pos)
            .show();
          clearTimeout(tipTimer);
        } else {
          $tip
            .find('span.furnit_matching_tip-loader').hide().end()
            .find('span.furnit_matching_tip-quantity').text(data.cnt).show().end()
            .find('a').attr('href', data.url).show().end()
            .css(pos)
            .show()
          tipTimer = setTimeout(function(){if ( !tipHoverd ) $tip.hide();tipTimer = null}, tipShowTime);
        }
      }

      // init
      if (!settings.isFull)
        $this.append($html);

      $tip.appendTo(document.body);

      $button.click(function(){
        if ( $button.hasClass('pressed') ) {
          $html.slideUp(function(){
            $button.removeClass('pressed');
          });
        } else {
          $html.slideDown(function(){
            $button.addClass('pressed');
          });
        }
        return false;
      });

      if (!settings.isFull) {
        $html.find('.close').click(function(){
          $button.trigger('click');
          return false;
        });
      } else {
        $html.find('.close').click(function(){
          $this.hide();
          return false;
        });
      }
      
      $bntReset.click(function() {
        $form.find('input[type=checkbox]:checked').removeAttr('checked');
        $selectButton
                .attr('href', "#")
                .text('Показать ' + 0 + ' предметов')
                .addClass('select');
        $closeButton.removeClass('button-half');     
        applyResponse({"cnt":0,"url":"#","arr":[]});
        return false;
      })

      $selectButton.click(function(){
        if ( $(this).hasClass('select') )
          return false;
      });

      $form.find('.block').each(function(){
        var $title = $(this).find('.block-title');
        var $content = $(this).find('.block-content');
        $title.click(function(){
          $title.toggleClass('block-title-hover');
          $content.slideToggle('fast');
          return false;
        });
      });

      $form.find('ul ul').parent('li').each(function(){
        var $input = $(this).find('>input');
        var $subinputs = $(this).find('ul input');
        $input.change(function(){
          if ( $input.attr('checked') ) {
            $subinputs.attr('checked', true).trigger('change', true);
          }
        })
      });

      $form.find('input')
      .click(function(){
         if($.browser.msie){
           $(this).trigger("change").blur();
           $(this).focus();
         }
      })
      .change(function(event, isCustom){
        var $checkbox = $(this);
        if ( typeof isCustom == 'undefined' || !isCustom )
          //$checkboxes.attr('disabled', true );
          showTip($checkbox);
          $.ajax({
            url: $form.attr('action'),
            data: getSnapShot($checkbox.attr('id'), $checkbox.attr('checked') ? 1 : 0 ),
            dataType: 'json',
            //type: 'post', //use GET because ajax do not send both GET and POST
            success: function(data){
              applyResponse(data);
              //$checkboxes.attr('disabled', false );
              $selectButton
                .attr('href', data.url)
                .text('Показать ' + data.cnt + ' предметов');
              if ( parseInt(data.cnt) > 0 ) {
                 $selectButton.removeClass('select');
                 $closeButton.addClass('button-half');
              } else {
                $selectButton.addClass('select');
                $closeButton.removeClass('button-half');
              }
              if ( parseInt(data.cnt) > 0 )
                showTip($checkbox, data);
              else
                $tip.hide()
            }
          });
      });

      /*var $block = null;
      var $blockContent = null;
      for ( var section in furnit_data ) {
        $block = $('<div class="block"><a class="block-title" href="#">' + furnit_data[section].title + '</a><div class="block-content"></div></div>');
        $blockContent = $block.find('.block-content');
        $block.find('.block-title').click(function(){
          $(this).toggleClass('block-title-hover');
          $blockContent.toggle();
          return false;
        });
        $block.appendTo($form);
      }*/
    })
  }
  
  $('.furnit_matching').furnitMatching();
  
  $('.furnit_selection').click(function(){
    var $html = $('#overlay');
    if ( $html.length < 1 )
      $html = $('<div id="overlay"><div class="overlay-content"></div></div>').appendTo(document.body);    
    var $htmlContent = $html.children('.overlay-content');
    
    $html.show();
        
    if ( $.browser.msie && $.browser.version < 7 ) {
      var wSize = getPageSize();
      $html.height(wSize[1]);
    }
    
    $('html, body').get(0).scrollTop = 0;
    if ( $('#furnit_matching_full').length < 1 ) {
      $html.addClass('overlay-loading');
      $.ajax({
        url: this.href,
        dataType: 'html',
        success: function(data, textStatus, jqXHR) {
          $html.removeClass('overlay-loading');
          $(data).appendTo($htmlContent);
          $html.furnitMatching({
            isFull: true
          });        
        }
      });
    }
    
    
    return false;
  });

  $('.jpop').jPop();

  /*
	 * Forms
	 */
  $('a.submit').submitable();

  /*
	 * 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
	 */
  $('.order, .book').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;
  })

  /*
	 * Refresh basket counter
	 */
  function refreshBasketCount() {
    var count = $('.basket>li').length;
    $('#basket_link').text('Вы отложили (' + ( count > 0 ? count : 'пусто' )+ ')')
  }

  /*
	 * Keep
	 */
  $('.keep').bind('click', function(){
    if ( $(this).hasClass('kept') ) return false;    
    var $image = $(this).parents('.item_description:first').find('.image img');
    var item = true;
    if ( $image.length < 1 ) {
      var $item_img = $(this).parent('.item-img');
      $image = $item_img.find('img:first');
      item = false;
    }
    if ( $image.length < 1 ) return false;
    $(this).addClass('kept');
    var $scrollable = $.browser.webkit ? $('body') : $('html');
    var currentScroll = Math.max($scrollable.get(0).scrollTop, $scrollable.get(0).scrollTop);    
    var increaseRate = 1.2;
    var id = $(this).attr('href').match(/id\=(\d+)/)[1];
    var scrollTo = function(targetScroll, callback) {      
			$scrollable.animate({
        scrollTop : targetScroll
				}, 200 + Math.abs(targetScroll - $('html').get(0).scrollTop)*0.5, 'easeOutQuad', callback);
    }
    scrollTo(0, function(){      
      var $proxy = $image.clone();
      var pageSize = getPageSize();
      var windowWidth = pageSize[2], windowHeight = pageSize[3];
      var basket_offset = $('#basket_link').offset();     
      var $image_pos = $image.offset();
      var $basket = $('.basket');
      $proxy.css({
        position: 'absolute',
        zIndex: 10,
        left: $image_pos.left,
        top: $image_pos.top
      }).appendTo(document.body);
      var proxy_width = $proxy.width() * increaseRate;
      var proxy_height = $proxy.height() * increaseRate;
      $proxy.animate({left: (windowWidth - proxy_width) / 2, top: (windowHeight - proxy_height) / 2, width: proxy_width, height: proxy_height}, 400, 'easeOutCubic');
      $proxy.animate({left: basket_offset.left + $('#basket_link').width() / 2, top: basket_offset.top, width: 0, height: 0}, 200, '', function(){
        var name = item ? $('h1:eq(0)').text() : $item_img.find('.name:first').text();
        var article = item ? $('.item_description .article .number:eq(0)').text() : $item_img.find('.article:first').text();        
        // add new item to the basket
        $proxy.remove();
        if ( $('#item_' + id).length == 0 ) {
          if ( $basket.length == 0 ) {
            var $basket_dropdown = $('<div class="dropmenu info_menu"><ul class="basket"></ul><a class="button book" href="/basket.html?action=view">Оформить заказ<span></span></a></div>').insertAfter($('#basket_link'));
            $basket = $basket_dropdown.find('.basket');
          }
          $basket.append('<li id="item_' + id + '"><a href="' + location.href + '">' + article + '<br />' + ( $('.item_description .image:eq(0)').attr('alt') || '' ) + '</a><span>' + name + '</span></li>');
          refreshBasketCount();
          //var $block = $('<div class="dropdown-container"><a href="' + $('#basket_link').attr('href') + '" class="dropdown-close">'+ $('#basket_link').html() +'</a></div>');
          //var $block_link = $block.find('.dropdown-close');
        }
        
        // show recently added item
        var $basketContent = $('#basket_link').parent('td').find('.dropmenu').clone();
        $('#basket_link').parent('td').find('.dropmenu').remove();
        var imageRatio = 74 / Math.min($image.width(), $image.height());
        $('#basket_link').parent('td').append('<div class="dropmenu info_menu"><ul class="basket"><li id="item_' + id + '"><a href="' + location.href + '" class="basket_image"><img src=' + $image.attr('src') + ' width="' + $image.width()*imageRatio + '" height="' + $image.height()*imageRatio + '"/></a><a href="' + location.href + '">' + article + '<br />' + ( $('.item_description .image:eq(0)').attr('alt') || '' ) + '</a><span>' + name + '</span></li></ul></div>');
        var menuO = $('#basket_link').dropdownMenuInit($('#basket_link'));
        $.fn.dropdownMenuOpen(menuO, true);
        setTimeout(function(){
          $.fn.dropdownMenuClose(menuO);
          scrollTo(currentScroll);
          $('#basket_link').parent('td').find('.dropmenu').remove();
          $basketContent.appendTo($('#basket_link').parent('td'));
        }, 450);
        //scroll back
      });
    });
    $.post($(this).attr('href'));
    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');
      }
    });

  });

  /*
	 * Pages
	 */
  $('#order-content').pages();

  /*
	 * Decor chackboxes
	 */
  $('#order-content .page-orderlist 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;
    })

  });
 

})})(jQuery);

(function($) {

  $.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);
    });
  };

})(jQuery);

/*
	 * Pages
	 */
(function($) {

  // realized 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;
      });

    });
  };

})(jQuery);

/**
 * form validator
 */
(function($) {

  $.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(){
        if ( isActive ) {
          if ( typeof callback != 'function' )
            $form.submit();
          else {
            if ( typeof callforward == 'function' ) {
              var result = callforward.call();
              if ( typeof result == 'undefined' )
                result = true;
              if (  result === false )                
                return false;
            }
            $.ajax({
              data: $form.serializeArray(),
              type: $form.attr('method'),
              url: $form.attr('action') + ( $form.attr('action').indexOf('?') >= 0 ? '&' : '?') + 'nobot=1',
              complete: function(XMLHttpRequest, textStatus){callback.call($form.get(0), XMLHttpRequest, textStatus)}
            })
          }
        }
        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;
  };

})(jQuery);

/**
 * pop up images
 */
(function($) {


  jQuery.fn.jPop = function() {
    return this.each(function(){
      $(this)
        .mouseover(function(event){
          $.jPop.showImg($(this).attr('src').substr($(this).attr('src').search('#') + 1), event);
        })
        .mouseout(function(event){
          $.jPop.hideImg(event);
        });
    })
  }

	jQuery.extend({
				jPop : {

					templateImg : ["<img class='imageZoom' />"],

					showImg : function(src, event) {
						var coords = mouseXY(event);
						var relX = 22;
						var relY = -22;
						$.jPop.target = $(event.target || event.srcElement);
						$.jPop.img = $($.jPop.templateImg.join(''));
						$.jPop.img.attr('src', '/img/ajax_small.gif').css({
									borderWidth : 0
								}).css({
									left : coords.x - relX + 'px',
									top : coords.y - relY + 'px'
								}).appendTo(document.body).show();
						var image = new Image();
						image.onload = function() {
							relX = -30;
							relY = 5;
							$.jPop.img.hide().attr({
										'src' : this.src,
										'width' : this.width,
										'height' : this.height
									}).css({
										left : coords.x - relX + 'px',
										top : coords.y - relY + 'px'
									}).css({
										borderWidth : 5
									}).show();
						};
						image.src = src;
						$.jPop.target.mousemove(function(event) {
									coords = mouseXY(event);
									$.jPop.img.css({
												left : coords.x - relX + 'px',
												top : coords.y - relY + 'px'
											});
								});
					},

					hideImg : function(event) {
						$.jPop.img.hide();
						$.jPop.img.remove();
						$.jPop.target.unbind('mousemove');
					}
				}
			})
  
})(jQuery);

/**
 *             Gallery swap
 */
(function($) {
  showHugeImage = function(src, $thumbList) {
    var settings = {
      overlayApperSpped: 200,
      panelApperSpead: 100,
      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">\
          <img src="/img/s.gif" alt="" class="image" style="z-index: 1;" />\
          <a href="#" id="huge_gallery_close">Вернуться к описанию предмета</a>\
          <a href="#" id="huge_gallery_prev"></a>\
          <a href="#" id="huge_gallery_next"></a>\
          <div id="huge_gallery_panel_wrapper"><div id="huge_gallery_panel">\
            <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 $prev = $html.find('#huge_gallery_control a.prev, #huge_gallery_prev');
    var $next = $html.find('#huge_gallery_control a.next, #huge_gallery_next');
    var $btnClose = $html.find('#huge_gallery_close');
    var $panel = $html.find('#huge_gallery_panel');
    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 = $wrapper.find('.image');
    var currentScrollTop = 0;
    var notIEWidnowWidthCorrection = 15;

    /*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]});
    }

    var updateMouseCoords = function(evt){
      cursor = mouseXY(evt);
    }

    var panel_show = function() {
      $panel.stop().animate({top: 0},  settings.panelApperSpead, settings.panelApperEasing);
    }

    var panel_hide = function() {
      $panel.stop().animate({top: 55}, settings.panelApperSpead, settings.panelApperEasing);
    }

    var close = function() {
      $html.fadeOut(settings.overlayApperSpped, function(){
        $html.remove();
        $(document.body)
          .css({
            overflow: 'auto',
            height: 'auto'
          });
        $('html, body').attr('scrollTop', currentScrollTop);
        _gaq.push(['_trackEvent', 'tovar', 'bigimgclose']);
      });
      $(window).unbind('resize', updatePageSizeInfo);
      $wrapper.unbind('mousemove', updateMouseCoords);
      return false;
    }

    var open = function() {
      updatePageSizeInfo();
      $(window).bind('resize', updatePageSizeInfo);
      $wrapper.bind('mousemove', updateMouseCoords);

      currentScrollTop = Math.max($('body').attr('scrollTop'), $('html').attr('scrollTop'));
      $('html, body').attr('scrollTop', 0);
      $(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).attr('data-href');
        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 ( imageSrc == src ) {          
          $thumbCurrent = $thumb.find('a');
          thumbClick($thumbCurrent);
        }
      });

      $html.fadeIn(settings.overlayApperSpped, function(){
        panel_show();
      });

    }

    var onLoad = function($thumb) {
      var $oldImage = $wrapper.find('.image');
      var $newImage = $('<img src="' + $thumb.attr('_href') + '" class="image" />');
      $oldImage.fadeOut();
      $newImage
        .css({
          top: (parseInt(pageSize[3]) - parseInt(preloadedImage.height)) / 2,
          left: (parseInt(pageSize[2]) - parseInt(preloadedImage.width)) / 2
        })
        .hide()
        .appendTo($wrapper);
      $newImage.bind("contextmenu mousedown dragstart",function(){
        return false;
      });
      clearInterval(timer);
      timer = setInterval(function(){
        if ( cursor == null ) return;
        var imageExceedHeight = parseInt(pageSize[3]) - 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();

    }

    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 )});
      }

      //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(showNext);
    $prev.click(showPrev);
    $btnClose.click(close);

    open();

  };
  
  
$.fn.hugeGallery = function(){
    var $thumbList = $(this);
    return this.each(function(){
      $(this).click(function(){
        showHugeImage($(this).attr('data-href'), $thumbList);
        return false;
      });
    })
  }

  $.fn.gallerySwap = function(settings) {
    return this.each(function(){
      settings = $.extend({
        image: '.image',
        thumbs: 'ul li a',
        swapSpeed: 500,
        swapEasing: 'easeInOutQuart'
      }, settings);

      var self = this;
      var $image = $(settings.image, this);
      var $thumbs = $(settings.thumbs, this);
      var preloadedImage = null;
      var $hugeImageList = $thumbs.filter("[data-href]");

      var $original_note = $image.append('<span class="show_original"><span class="show_original-text">Просмотреть исходное изображение</span><span class="show_original-icon"></span></span>').find('span.show_original');

      var onLoad = function($thumb) {
        $original_note.hide();
        $image.animate({height: preloadedImage.height}, settings.swapSpeed);
        swapThumb($thumb);
        swapImage($thumb);
      }

      var swapThumb = function($thumb, callBack) {
        var height = $thumb.height();
        $thumbs.each(function() {
          if (parseInt($(this).css('top')) < 0)
            $(this).animate({top: 0}, settings.swapSpeed, settings.swapEasing);
        });
        $thumb.animate({top: -height - 1/* to hide focus frame */}, settings.swapSpeed, settings.swapEasing, function() {
          if ( typeof callBack == 'function' )
            callBack.call(self);
        });
      }

      var swapImage = function($thumb) {
        var $oldImage = $image.find('a');
        var hugeSrc = $thumb.attr('data-href');
        var $newImage = $('<a href="#" style="z-index: 2; bottom: -' + preloadedImage.height + 'px;' + ( typeof hugeSrc != 'undefined' ? '' : ' cursor: default;' ) + '"><img src="' + preloadedImage.src + '" alt="' + ( $thumb.attr('alt') || '' ) + '" /></a>');
        $newImage.add($original_note).click(function(){
          if ( typeof hugeSrc != 'undefined' ) {
            _gaq.push(['_trackEvent', 'tovar', 'bigimg']);
            showHugeImage(hugeSrc, $hugeImageList);
          }
          return false;
        });
        //$newImage.lightBox();
        $oldImage.css('z-index',1);
        $newImage.appendTo($image);
    		$newImage.animate({bottom: 0}, settings.swapSpeed, settings.swapEasing);
        $oldImage.animate({bottom: -preloadedImage.height}, settings.swapSpeed, settings.swapEasing, function() {
          $oldImage.remove();
          if ( typeof hugeSrc != 'undefined' ) $original_note.show();
        });
      }

      $thumbs.click(function(){
        var $thumb = $(this);
        var $preloadScreen = $thumb.find('span');
        // abort onload event if image is already loading
        if ( preloadedImage != null )
          preloadedImage.onload = null;
        preloadedImage = new Image();
        preloadedImage.onload = function() {
          $preloadScreen.hide();
          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 )
          $preloadScreen.show();
        return false;
      })

      $image.each(function(){
        if ( $.browser.msie && $.browser.version < 7 )
          $(this).hover(function(){
            $(this).find('.show_original-text').show();
           $(this).find('.show_original-icon').hide();
          }, function(){
            $(this).find('.show_original-text').hide();
            $(this).find('.show_original-icon').show();
          });
      });
      //init
      $thumbs.eq(0).trigger('click');

    });
  }
})(jQuery);

/**
 *             Gallery slider
 */
(function($) {
  $.fn.gallerySlider = function(settings) {
    return this.each(function(){
      settings = $.extend({
        slide: '.slide',
        slideWidth: 600,
        animationSpeed: 200,
        animationEasing: ''
      }, settings);

      var $container = $(this);
      var $slides = $container.find(settings.slide);
      var slideWidthHidden = ( ( $container.width() - settings.slideWidth ) / ($slides.length - 1) );

      $(window).resize(function(){
        slideWidthHidden = ( ( $container.width() - settings.slideWidth ) / ($slides.length - 1) );
        var visibleWidth = 0;
        $slides.each(function(num){
          $(this).css({marginLeft: Math.round(slideWidthHidden * num + visibleWidth)});
          if ( $(this).hasClass('visible') )
            visibleWidth = settings.slideWidth - slideWidthHidden;
        });
      });

      var visibleWidth = 0;
      $slides.each(function(num){
        //init position
        var $slide = $(this);
        var $prevSlides = $slide.prevAll(settings.slide);
        var $nextSlides = $slide.nextAll(settings.slide);
        $slide.animate({marginLeft: Math.round(slideWidthHidden * num + visibleWidth)}, settings.animationSpeed, settings.animationEasing );
        if ( $slide.hasClass('visible') )
          visibleWidth = settings.slideWidth - slideWidthHidden;

        $slide.click(function(){
          if ( $slide.hasClass('visible') )
             return true;

          var $toMove = jQuery();

          if ( $prevSlides.filter('.visible').length > 0 ) {
              $toMove = $slide;
              $prevSlides.each(function(){
                if ( $(this).hasClass('visible') ) return false;
                $toMove = $toMove.add($(this));
              })
              $toMove.animate({marginLeft: '-=' + Math.round(settings.slideWidth - slideWidthHidden)}, settings.animationSpeed, settings.animationEasing );
          }

          if ( $nextSlides.filter('.visible').length > 0 ) {
              $nextSlides.each(function(){
                $toMove = $toMove.add($(this));
                if ( $(this).hasClass('visible') ) return false;
              })
              $toMove.animate({marginLeft: '+=' + Math.round(settings.slideWidth - slideWidthHidden)}, settings.animationSpeed, settings.animationEasing );
          }

          $slides.filter('.visible').removeClass('visible').addClass('hidden');
          $slide.removeClass('hidden').addClass('visible');

          return false;
        })
      });

      
    });
  }

})(jQuery);

/**
 *            Easing functions
 */
jQuery.extend(jQuery.easing, {
  easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
  easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
  easeOutQuint : function(x, t, b, c, d) {
    return c * ((t = t / d - 1) * t * t * t * t + 1) + b;
	},
  easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
  easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
  easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + 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;
	}
});

/**
 * 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;
}

/**
 * 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, xScroll, yScroll);
	return arrayPageSize;
};

/**
 * Add current page to bookmarks
 */
function bookmarkpage() 
{
	var title = document.title;
	var url = window.location.href;
	if (navigator.appName === "Microsoft Internet Explorer")
		window.external.AddFavorite(url, title);
	else if(window.opera && window.print) { // Opera Browser
		var elem = document.createElement('a');
		elem.setAttribute('href',url);
		elem.setAttribute('title',title);
		elem.setAttribute('rel','sidebar');
		elem.click();
	}
	else if (window.sidebar) { // Other Browsers wich support it
		window.sidebar.addPanel(title, url, "");
	}
}

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

