// page init
jQuery(function(){
  clearInputs();
  initLightbox();
  initOpenClose();
  initGalleries();
  initValidation();
  initEffects();
  initAjaxTabs();
});

// clear inputs
function clearInputs(){
  clearFormFields({
    clearInputs: true,
    clearTextareas: true,
    passwordFieldText: false,
    addClassFocus: false,
    filterClass: "default"
  });
};

// galleries init
function initGalleries(){
  jQuery('div.bottom-gallery').fadeGallery({
    duration:(jQuery.browser.msie && jQuery.browser.version < 9) ? 0 : 800 //ms
  });
  jQuery('#tj_container').gridnav({
    rows  : 1,
    type  : {
            mode    : 'seqfade',   // use def | fade | seqfade | updown | sequpdown | showhide | disperse | rows
            speed    : 500,      // for fade, seqfade, updown, sequpdown, showhide, disperse, rows
      easing    : '',      // for fade, seqfade, updown, sequpdown, showhide, disperse, rows  
            factor    : 100,      // for seqfade, sequpdown, rows
            reverse    : ''      // for sequpdown

    }
  });
};

// effects init
function initEffects(){
  var dur = 600; //ms
  var openedClass = 'home-opened';
  var hold = $('body');
  var slide = hold.find('div.header-cover');
  var menu = hold.find('div.main-menu');
  var opener = slide.find('.logo > a');
  var links = hold.find('a.redirect');
  var main = hold.find('#main');
  var h = menu.outerHeight()-14;
  var winLocaction = window.location;
  links.click(function(){
    animRedirect($(this).attr('href'));
    return false;
  });
  opener.click(function(){
    var href = opener.attr('href');
    if (hold.hasClass('home-page')) {
      // open-close on homepage
      if (hold.hasClass(openedClass)) {
        hold.removeClass(openedClass);
        slide.animate({top:0},{duration: dur, queue: false});
      } else {
        hold.addClass(openedClass);
        slide.animate({top:-h},{duration: dur, queue: false});
      }
    } else {
      slide.animate({top:0},{duration: dur, queue: false});
      main.animate({opacity:0},{duration: dur, queue: false,complete:function(){
        window.location = href;
      }});
    }
    return false;
  });
  function animRedirect(url){
    slide.animate({top:-h},{duration: dur, queue: false});
    main.animate({opacity:0},{duration: dur, queue: false,complete:function(){
      window.location = url;
    }});
  };
};

function initValidation(){
  if($('form.validate').length){
    $('form.validate').each(function(){
      var form = $(this);
      var completeList = form.find('ul.complete-list');
      var submit = form.find('input:submit').hide();
      completeList.children().each(function(){
        $(this).attr('checkblock', $(this).attr('title')).removeAttr('title').removeClass('complete');
      });
      form.find('input.required').each(function(){
        $(this).focus(function(){
          completeList.children().filter('[checkblock='+$(this).attr('id')+']').removeClass('complete');
        }).blur(function(){
          if($(this).val() != ''){
            completeList.children().filter('[checkblock='+$(this).attr('id')+']').addClass('complete');
          }
          else{
            completeList.children().filter('[checkblock='+$(this).attr('id')+']').removeClass('complete');
          }
          checkForm();
        });
      });
      
      function checkForm(){
        if(completeList.children().filter(':not(.complete)').length == 0){submit.show()}
      }
    });
  }
}

// lightbox init
function initLightbox(){
  jQuery('a[rel="fancybox"]').fancybox({
    padding:15,
    margin:100,
    centerOnScroll:true,
    overlayColor:'#000',
    overlayOpacity:0.8,
    showNavArrows:false,
    titlePosition:'over',
    titleFormat:function(title, currentArray, currentIndex, currentOpts){
			 return '<div class="popup-title"><div class="popup-nav"><a class="btn-prev" href="javascript:;" onclick="jQuery.fancybox.prev();">prev</a><a class="btn-next" href="javascript:;" onclick="jQuery.fancybox.next();">Close</a><a class="close" href="javascript:;" onclick="jQuery.fancybox.close();">Close</a></div><div class="description">'+(title && title.length ? '<p>' + title + '</p>' : '' ) + '</div></div>';
		}
	});
	jQuery('a.open-popup').fancybox({
		padding:1,
		margin:10,
		width:1024,
		height:805,
		autoScale:false,
		centerOnScroll:true,
		overlayColor:'#000',
		overlayOpacity:0.8,
		onComplete:function(){
			setTimeout(function(){
				jQuery('#fancybox-wrap').addClass('popup-style2');
				jQuery(window).trigger('resize')
			},5)
		},
		onClosed:function(){
			jQuery('#fancybox-wrap').removeClass('popup-style2');
		}
	});
	jQuery('a.open-image').fancybox({
		padding:1,
		margin:10,
		autoScale:true,
		centerOnScroll:true,
		overlayColor:'#000',
		overlayOpacity:0.8,
		onComplete:function(){
			setTimeout(function(){
				jQuery('#fancybox-wrap').addClass('popup-style2');
			},5)
		},
		onClosed:function(){
			jQuery('#fancybox-wrap').removeClass('popup-style2');
    }
  });
};

// open-close init
function initOpenClose(){
  var dur = 500; //ms
  var opacity = 0.7;
  var activeClass = 'gallery-active';
  var hold = jQuery('body');
  var wrap = hold.find('#wrapper');
  var footer = hold.find('#footer');
  var opener = jQuery('#footer li:not(.shop) > a, div.bottom-gallery a.close, a.opener');
  var slide = hold.find('div.slide-box');
  var h = slide.outerHeight();
  var fader = jQuery('<div id="fader" />')
  if (!hold.hasClass(activeClass)) slide.css({bottom:-h});
  fader.appendTo(hold);
  fader.css({
    width:initW(),
    height:initH(),
    opacity:0
  }).hide();
  opener.click(function(){
    move($(this).attr('href'));
    return false;
  });
  fader.click(function(){
    move();
    return false;
  });
  function move(obj){
    if (!hold.hasClass(activeClass)) {
      hold.addClass(activeClass);
      fader.show().stop().animate({opacity:opacity},{duration: dur, queue: false})
      slide.filter(obj).stop().animate({bottom:0},{duration: dur, queue: false})
    } else {
      fader.stop().animate({opacity:0},{duration: dur, queue: false,complete:function(){
        hold.removeClass(activeClass);
        fader.hide();
      }})
      slide.stop().animate({bottom:-h},{duration: dur, queue: false})
    }
  };
  jQuery(window).resize(function(){
    fader.css({
      height:initH(),
      width:initW()
    });
  })
  function initH(){return wrap.outerHeight() > jQuery(window).height() ? wrap.outerHeight() : jQuery(window).height();}
  function initW(){return wrap.outerWidth() > jQuery(window).width() ? wrap.outerWidth() : jQuery(window).width();}
};

// ajax tabs init
function initAjaxTabs(){
	jQuery('div.ajax-tabs').ajaxTabs({
		afterFirstLoad:function(holder){
			setTimeout(function(){
				initCarousel();
				initLightbox();
			},100);
		}
	});
};

// carousel init
function initCarousel(){
	$('div.links-gallery').each(function(){
		if(this.init) return; else this.init = true;
		var _wraper = $(this),
			_holder = $('div.window', _wraper),
			_mover = $('> ul', _holder),
			_slide = $('> li', _mover),
			_prev = $('a.prev', _wraper),
			_next = $('a.next', _wraper),
			_length = _slide.length-1;
		
		var _duration = 500,
			_loadDuration = 4000,
			_current = 0,
			_margin = 0,
			_step = [], _stepSum = 0;
			
		_step[0] = 0;
		_slide.each(function(i){
			_stepSum += $(this).outerWidth(true);
			_step[i+1] = _stepSum;
		});
		if (_stepSum > _holder.innerWidth()) {
			_prev.show();
			_next.show();
		}
		var _maxMargin = _step[_slide.length] - _holder.innerWidth();
		
		_next.click(function(){
			if ($(this).hasClass('back')) {
				$(this).removeClass('back');
				_current = 0;
			} else _current++;
			if (_current > _length) _current = 0;
			_margin = _step[_current];
			if (_margin > _maxMargin) {
				_margin = _maxMargin;
				_next.addClass('back');
			}
			_mover.animate({'marginLeft': -_margin}, {duration:_duration, queue:false});
			return false;
		});
		_prev.click(function(){
			_current--;
			if (_current < 0) _current = _length;
			if (_margin == _maxMargin) {
				for (var i=_length; i > 0; i--) {
					if (_step[i] < _maxMargin) {
						_current = i;
						break;
					}
				}
			}
			_margin = _step[_current];
			if (_margin > _maxMargin) {
				_margin = _maxMargin;
				_next.addClass('back');
			}
			_mover.animate({'marginLeft': -_margin}, {duration:_duration, queue:false});
			return false;
		});
	});
}
// ajax tabs plugin
$.fn.ajaxTabs = function(options){
	var options = $.extend({
		tabset:'ul.ajax-tabset',
		tabsHolder:'div.ajax-content',
		afterFirstLoad:null,
		fadeSpeed:false
	},options);

	return this.each(function(){
		var holder = $(this);
		var tabset = $(options.tabset, holder);
		var tabsHolder = $(options.tabsHolder,holder);
		var decor = $('div.tag-box', holder);
		var links = $('a',tabset);
		var hrefArray = [];
		var tabArray = [];
		var firstLoad = [];
		var active = 0;
		var ajaxInAction = false;
		links.each(function(i){
			hrefArray[i] = $(this).attr('href');
			firstLoad[i] = true;
			if ($(this).hasClass('active')) active = i;
		});

		links.each(function(i){
			$(this).click(function(){
				if (i != active && !ajaxInAction) loadTab(i);
				return false;
			});
		});
		
		loadTab(active);
		
		function loadTab(ind) {
			if (typeof tabArray[ind] != 'undefined') {
				showTab(ind);
			} else {
				ajaxInAction = true;
				$.ajax({
					url: hrefArray[ind],
					dataType:'text',
					error:function(){
						alert('ajax error');
					},
					success:function(msg){
						ajaxInAction = false;
						tabArray[ind] = $(msg).appendTo(tabsHolder).hide();
						showTab(ind);
					}
				});
				
			}
		}
		
		function showTab(ind){
			tabArray[active].css({display:'none'});
			links.eq(active).removeClass('active');
			links.eq(ind).addClass('active');
			if (options.fadeSpeed) {
				tabArray[ind].fadeIn(options.fadeSpeed,function(){
					if (typeof options.afterFirstLoad == 'function' && firstLoad[ind]) {
						options.afterFirstLoad(tabArray[ind]);
						firstLoad[ind] = false;
					}
				});
			} else {
				tabArray[ind].show();
				if (typeof options.afterFirstLoad == 'function' && firstLoad[ind]) {
					options.afterFirstLoad(tabArray[ind]);
					firstLoad[ind] = false;
				}
			}
			active = ind;
		}
	});
};

// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
  var _options = jQuery.extend({
    slideElements:'div.window > div.slide',
    pagerGener: false,
    pagerHold: false,
    pagerLinks:'ul.nav-list li',
    btnNext:'a.next',
    btnPrev:'a.prev',
    btnPlayPause:'a.play-pause',
    btnPlay:'a.play',
    btnPause:'a.pause',
    pausedClass:'paused',
    disabledClass: 'disabled',
    playClass:'playing',
    activeClass:'active',
    currentNum:false,
    allNum:false,
    startSlide:null,
    noCircle:false,
    caption:'ul.caption > li',
    pauseOnHover:false,
    autoRotation:false,
    autoHeight:false,
    onChange:false,
    switchTime:3000,
    duration:650,
    event:'click'
  },_options);

  return this.each(function(){
    // gallery options
    var _this = jQuery(this);
    var _slides = jQuery(_options.slideElements, _this);
    var _btnPrev = jQuery(_options.btnPrev, _this);
    var _btnNext = jQuery(_options.btnNext, _this);
    var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
    var _btnPause = jQuery(_options.btnPause, _this);
    var _btnPlay = jQuery(_options.btnPlay, _this);
    var _pauseOnHover = _options.pauseOnHover;
    var _autoRotation = _options.autoRotation;
    var _activeClass = _options.activeClass;
    var _disabledClass = _options.disabledClass;
    var _pausedClass = _options.pausedClass;
    var _playClass = _options.playClass;
    var _autoHeight = _options.autoHeight;
    var _duration = _options.duration;
    var _switchTime = _options.switchTime;
    var _controlEvent = _options.event;
    var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
    var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
    var _startSlide = _options.startSlide;
    var _noCycle = _options.noCircle;
    var _onChange = _options.onChange;
    var _pagerGener = _options.pagerGener;
    var _pagerHold = jQuery(_options.pagerHold,_this);
    var _caption = jQuery(_options.caption,_this);
    var _paging = '';
    if(_pagerGener){
      for(var i=0; i< _slides.length; i++){
        _paging += '<li><a href="#">'+(i+1)+'</a></li>';
      }
      _pagerHold.html('<ul>'+_paging+'</ul>');
    }
    var _pagerLinks = jQuery(_options.pagerLinks, _this);
    // gallery init
    var _hover = false;
    var _prevIndex = 0;
    var _currentIndex = 0;
    var _slideCount = _slides.length;
    var _timer;
    if(_slideCount < 2) return;

    _prevIndex = _slides.index(_slides.filter('.'+_activeClass));
    if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
    else _currentIndex = _prevIndex;
    if(_startSlide != null) {
      if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
      else _prevIndex = _currentIndex = parseInt(_startSlide);
    }
    _slides.hide().eq(_currentIndex).show();
    _caption.hide().eq(_currentIndex).show();
    if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
    else _this.removeClass(_playClass).addClass(_pausedClass);

    // gallery control
    if(_btnPrev.length) {
      _btnPrev.bind(_controlEvent,function(){
        prevSlide();
        return false;
      });
    }
    if(_btnNext.length) {
      _btnNext.bind(_controlEvent,function(){
        nextSlide();
        return false;
      });
    }
    if(_pagerLinks.length) {
      _pagerLinks.each(function(_ind){
        jQuery(this).bind(_controlEvent,function(){
          if(_currentIndex != _ind) {
            _prevIndex = _currentIndex;
            _currentIndex = _ind;
            switchSlide();
          }
          return false;
        });
      });
    }

    // play pause section
    if(_btnPlayPause.length) {
      _btnPlayPause.bind(_controlEvent,function(){
        if(_this.hasClass(_pausedClass)) {
          _this.removeClass(_pausedClass).addClass(_playClass);
          _autoRotation = true;
          autoSlide();
        } else {
          _autoRotation = false;
          if(_timer) clearTimeout(_timer);
          _this.removeClass(_playClass).addClass(_pausedClass);
        }
        return false;
      });
    }
    if(_btnPlay.length) {
      _btnPlay.bind(_controlEvent,function(){
        _this.removeClass(_pausedClass).addClass(_playClass);
        _autoRotation = true;
        autoSlide();
        return false;
      });
    }
    if(_btnPause.length) {
      _btnPause.bind(_controlEvent,function(){
        _autoRotation = false;
        if(_timer) clearTimeout(_timer);
        _this.removeClass(_playClass).addClass(_pausedClass);
        return false;
      });
    }
    // gallery animation
    function prevSlide() {
      _prevIndex = _currentIndex;
      if(_currentIndex > 0) _currentIndex--;
      else {
        if(_noCycle) return;
        else _currentIndex = _slideCount-1;
      }
      switchSlide();
    }
    function nextSlide() {
      _prevIndex = _currentIndex;
      if(_currentIndex < _slideCount-1) _currentIndex++;
      else {
        if(_noCycle) return;
        else _currentIndex = 0;
      }
      switchSlide();
    }
    function refreshStatus() {
      if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
      if(_currentNum) _currentNum.text(_currentIndex+1);
      if(_allNum) _allNum.text(_slideCount);
      _slides.eq(_prevIndex).removeClass(_activeClass);
      _slides.eq(_currentIndex).addClass(_activeClass);
      if(_noCycle) {
        if(_btnPrev.length) {
          if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
          else _btnPrev.removeClass(_disabledClass);
        }
        if(_btnNext.length) {
          if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
          else _btnNext.removeClass(_disabledClass);
        }
      }
      if(typeof _onChange === 'function') {
        _onChange(_this, _currentIndex);
      }
    }
    function switchSlide() {
      _slides.eq(_prevIndex).stop().animate({opacity:0},{duration: _duration, queue: false,complete:function(){
        jQuery(this).css({display:'none'});
      }})
      _slides.eq(_currentIndex).stop().css({display:'block',opacity:0}).animate({opacity:1},{duration: _duration, queue: false,complete:function(){
        jQuery(this).css({opacity:''});
      }})
      _caption.eq(_prevIndex).fadeOut();
      _caption.eq(_currentIndex).fadeIn();
      if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
      refreshStatus();
      autoSlide();
    }

    // autoslide function
    function autoSlide() {
      if(!_autoRotation || _hover) return;
      if(_timer) clearTimeout(_timer);
      _timer = setTimeout(nextSlide,_switchTime+_duration);
    }
    if(_pauseOnHover) {
      _this.hover(function(){
        _hover = true;
        if(_timer) clearTimeout(_timer);
      },function(){
        _hover = false;
        autoSlide();
      });
    }
    refreshStatus();
    autoSlide();
  });
};

// clear inputs plugin
function clearFormFields(o){
  if (o.clearInputs == null) o.clearInputs = true;
  if (o.clearTextareas == null) o.clearTextareas = true;
  if (o.passwordFieldText == null) o.passwordFieldText = false;
  if (o.addClassFocus == null) o.addClassFocus = false;
  if (!o.filterClass) o.filterClass = "default";
  if(o.clearInputs) {
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++ ) {
      if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass) == -1) {
        inputs[i].valueHtml = inputs[i].value;
        inputs[i].onfocus = function ()  {
          if(this.valueHtml == this.value) this.value = "";
          if(this.fake) {
            inputsSwap(this, this.previousSibling);
            this.previousSibling.focus();
          }
          if(o.addClassFocus && !this.fake) {
            this.className += " " + o.addClassFocus;
            this.parentNode.className += " parent-" + o.addClassFocus;
          }
        }
        inputs[i].onblur = function () {
          if(this.value == "") {
            this.value = this.valueHtml;
            if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
          }
          if(o.addClassFocus) {
            this.className = this.className.replace(o.addClassFocus, "");
            this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
          }
        }
        if(o.passwordFieldText && inputs[i].type == "password") {
          var fakeInput = document.createElement("input");
          fakeInput.type = "text";
          fakeInput.value = inputs[i].value;
          fakeInput.className = inputs[i].className;
          fakeInput.fake = true;
          inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
          inputsSwap(inputs[i], null);
        }
      }
    }
  }
  if(o.clearTextareas) {
    var textareas = document.getElementsByTagName("textarea");
    for(var i=0; i<textareas.length; i++) {
      if(textareas[i].className.indexOf(o.filterClass) == -1) {
        textareas[i].valueHtml = textareas[i].value;
        textareas[i].onfocus = function() {
          if(this.value == this.valueHtml) this.value = "";
          if(o.addClassFocus) {
            this.className += " " + o.addClassFocus;
            this.parentNode.className += " parent-" + o.addClassFocus;
          }
        }
        textareas[i].onblur = function() {
          if(this.value == "") this.value = this.valueHtml;
          if(o.addClassFocus) {
            this.className = this.className.replace(o.addClassFocus, "");
            this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
          }
        }
      }
    }
  }
  function inputsSwap(el, el2) {
    if(el) el.style.display = "none";
    if(el2) el2.style.display = "inline";
  }
};

/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 * 
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 *
 * Version: 1.3.4 (11/11/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function(B){var L,T,Q,M,d,m,J,A,O,z,C=0,H={},j=[],e=0,G={},y=[],f=null,o=new Image(),i=/\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,k=/[^\.]\.(swf)\s*$/i,p,N=1,h=0,t="",b,c,P=false,s=B.extend(B("<div/>")[0],{prop:0}),S=B.browser.msie&&B.browser.version<7&&!window.XMLHttpRequest,r=function(){T.hide();o.onerror=o.onload=null;if(f){f.abort()}L.empty()},x=function(){if(false===H.onError(j,C,H)){T.hide();P=false;return}H.titleShow=false;H.width="auto";H.height="auto";L.html('<p id="fancybox-error">The requested content cannot be loaded.<br />Please try again later.</p>');n()},w=function(){var Z=j[C],W,Y,ab,aa,V,X;r();H=B.extend({},B.fn.fancybox.defaults,(typeof B(Z).data("fancybox")=="undefined"?H:B(Z).data("fancybox")));X=H.onStart(j,C,H);if(X===false){P=false;return}else{if(typeof X=="object"){H=B.extend(H,X)}}ab=H.title||(Z.nodeName?B(Z).attr("title"):Z.title)||"";if(Z.nodeName&&!H.orig){H.orig=B(Z).children("img:first").length?B(Z).children("img:first"):B(Z)}if(ab===""&&H.orig&&H.titleFromAlt){ab=H.orig.attr("alt")}W=H.href||(Z.nodeName?B(Z).attr("href"):Z.href)||null;if((/^(?:javascript)/i).test(W)||W=="#"){W=null}if(H.type){Y=H.type;if(!W){W=H.content}}else{if(H.content){Y="html"}else{if(W){if(W.match(i)){Y="image"}else{if(W.match(k)){Y="swf"}else{if(B(Z).hasClass("iframe")){Y="iframe"}else{if(W.indexOf("#")===0){Y="inline"}else{Y="ajax"}}}}}}}if(!Y){x();return}if(Y=="inline"){Z=W.substr(W.indexOf("#"));Y=B(Z).length>0?"inline":"ajax"}H.type=Y;H.href=W;H.title=ab;if(H.autoDimensions){if(H.type=="html"||H.type=="inline"||H.type=="ajax"){H.width="auto";H.height="auto"}else{H.autoDimensions=false}}if(H.modal){H.overlayShow=true;H.hideOnOverlayClick=false;H.hideOnContentClick=false;H.enableEscapeButton=false;H.showCloseButton=false}H.padding=parseInt(H.padding,10);H.margin=parseInt(H.margin,10);L.css("padding",(H.padding+H.margin));B(".fancybox-inline-tmp").unbind("fancybox-cancel").bind("fancybox-change",function(){B(this).replaceWith(m.children())});switch(Y){case"html":L.html(H.content);n();break;case"inline":if(B(Z).parent().is("#fancybox-content")===true){P=false;return}B('<div class="fancybox-inline-tmp" />').hide().insertBefore(B(Z)).bind("fancybox-cleanup",function(){B(this).replaceWith(m.children())}).bind("fancybox-cancel",function(){B(this).replaceWith(L.children())});B(Z).appendTo(L);n();break;case"image":P=false;B.fancybox.showActivity();o=new Image();o.onerror=function(){x()};o.onload=function(){P=true;o.onerror=o.onload=null;F()};o.src=W;break;case"swf":H.scrolling="no";aa='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+H.width+'" height="'+H.height+'"><param name="movie" value="'+W+'"></param>';V="";B.each(H.swf,function(ac,ad){aa+='<param name="'+ac+'" value="'+ad+'"></param>';V+=" "+ac+'="'+ad+'"'});aa+='<embed src="'+W+'" type="application/x-shockwave-flash" width="'+H.width+'" height="'+H.height+'"'+V+"></embed></object>";L.html(aa);n();break;case"ajax":P=false;B.fancybox.showActivity();H.ajax.win=H.ajax.success;f=B.ajax(B.extend({},H.ajax,{url:W,data:H.ajax.data||{},dataType:"text",error:function(ac,ae,ad){if(ac.status>0){x()}},success:function(ad,af,ac){var ae=typeof ac=="object"?ac:f;if(ae.status==200||ae.status===0){if(typeof H.ajax.win=="function"){X=H.ajax.win(W,ad,af,ac);if(X===false){T.hide();return}else{if(typeof X=="string"||typeof X=="object"){ad=X}}}L.html(ad);n()}}}));break;case"iframe":E();break}},n=function(){var V=H.width,W=H.height;if(V.toString().indexOf("%")>-1){V=parseInt((B(window).width()-(H.margin*2))*parseFloat(V)/100,10)+"px"}else{V=V=="auto"?"auto":V+"px"}if(W.toString().indexOf("%")>-1){W=parseInt((B(window).height()-(H.margin*2))*parseFloat(W)/100,10)+"px"}else{W=W=="auto"?"auto":W+"px"}L.wrapInner('<div style="width:'+V+";height:"+W+";overflow: "+(H.scrolling=="auto"?"auto":(H.scrolling=="yes"?"scroll":"hidden"))+';position:relative;"></div>');H.width=L.width();H.height=L.height();E()},F=function(){H.width=o.width;H.height=o.height;B("<img />").attr({id:"fancybox-img",src:o.src,alt:H.title}).appendTo(L);E()},E=function(){var W,V;T.hide();if(M.is(":visible")&&false===G.onCleanup(y,e,G)){B.event.trigger("fancybox-cancel");P=false;return}P=true;B(m.add(Q)).unbind();B(window).unbind("resize.fb scroll.fb");B(document).unbind("keydown.fb");if(M.is(":visible")&&G.titlePosition!=="outside"){M.css("height",M.height())}y=j;e=C;G=H;if(G.overlayShow){Q.css({"background-color":G.overlayColor,opacity:G.overlayOpacity,cursor:G.hideOnOverlayClick?"pointer":"auto",height:B(document).height()});if(!Q.is(":visible")){if(S){B("select:not(#fancybox-tmp select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"})}Q.show()}}else{Q.hide()}c=R();l();if(M.is(":visible")){B(J.add(O).add(z)).hide();W=M.position(),b={top:W.top,left:W.left,width:M.width(),height:M.height()};V=(b.width==c.width&&b.height==c.height);m.fadeTo(G.changeFade,0.3,function(){var X=function(){m.html(L.contents()).fadeTo(G.changeFade,1,v)};B.event.trigger("fancybox-change");m.empty().removeAttr("filter").css({"border-width":G.padding,width:c.width-G.padding*2,height:H.autoDimensions?"auto":c.height-h-G.padding*2});if(V){X()}else{s.prop=0;B(s).animate({prop:1},{duration:G.changeSpeed,easing:G.easingChange,step:U,complete:X})}});return}M.removeAttr("style");m.css("border-width",G.padding);if(G.transitionIn=="elastic"){b=I();m.html(L.contents());M.show();if(G.opacity){c.opacity=0}s.prop=0;B(s).animate({prop:1},{duration:G.speedIn,easing:G.easingIn,step:U,complete:v});return}if(G.titlePosition=="inside"&&h>0){A.show()}m.css({width:c.width-G.padding*2,height:H.autoDimensions?"auto":c.height-h-G.padding*2}).html(L.contents());M.css(c).fadeIn(G.transitionIn=="none"?0:G.speedIn,v)},D=function(V){if(V&&V.length){if(G.titlePosition=="float"){return'<table id="fancybox-title-float-wrap" cellpadding="0" cellspacing="0"><tr><td id="fancybox-title-float-left"></td><td id="fancybox-title-float-main">'+V+'</td><td id="fancybox-title-float-right"></td></tr></table>'}return'<div id="fancybox-title-'+G.titlePosition+'">'+V+"</div>"}return false},l=function(){t=G.title||"";h=0;A.empty().removeAttr("style").removeClass();if(G.titleShow===false){A.hide();return}t=B.isFunction(G.titleFormat)?G.titleFormat(t,y,e,G):D(t);if(!t||t===""){A.hide();return}A.addClass("fancybox-title-"+G.titlePosition).html(t).appendTo("body").show();switch(G.titlePosition){case"inside":A.css({width:c.width-(G.padding*2),marginLeft:G.padding,marginRight:G.padding});h=A.outerHeight(true);A.appendTo(d);c.height+=h;break;case"over":A.css({marginLeft:G.padding,width:c.width-(G.padding*2),bottom:G.padding}).appendTo(d);break;case"float":A.css("left",parseInt((A.width()-c.width-40)/2,10)*-1).appendTo(M);break;default:A.css({width:c.width-(G.padding*2),paddingLeft:G.padding,paddingRight:G.padding}).appendTo(M);break}A.hide()},g=function(){if(G.enableEscapeButton||G.enableKeyboardNav){B(document).bind("keydown.fb",function(V){if(V.keyCode==27&&G.enableEscapeButton){V.preventDefault();B.fancybox.close()}else{if((V.keyCode==37||V.keyCode==39)&&G.enableKeyboardNav&&V.target.tagName!=="INPUT"&&V.target.tagName!=="TEXTAREA"&&V.target.tagName!=="SELECT"){V.preventDefault();B.fancybox[V.keyCode==37?"prev":"next"]()}}})}if(!G.showNavArrows){O.hide();z.hide();return}if((G.cyclic&&y.length>1)||e!==0){O.show()}if((G.cyclic&&y.length>1)||e!=(y.length-1)){z.show()}},v=function(){if(!B.support.opacity){m.get(0).style.removeAttribute("filter");M.get(0).style.removeAttribute("filter")}if(H.autoDimensions){m.css("height","auto")}M.css("height","auto");if(t&&t.length){A.show()}if(G.showCloseButton){J.show()}g();if(G.hideOnContentClick){m.bind("click",B.fancybox.close)}if(G.hideOnOverlayClick){Q.bind("click",B.fancybox.close)}B(window).bind("resize.fb",B.fancybox.resize);if(G.centerOnScroll){B(window).bind("scroll.fb",B.fancybox.center)}if(G.type=="iframe"){B('<iframe id="fancybox-frame" name="fancybox-frame'+new Date().getTime()+'" frameborder="0" hspace="0" '+(B.browser.msie?'allowtransparency="true""':"")+' scrolling="'+H.scrolling+'" src="'+G.href+'"></iframe>').appendTo(m)}M.show();P=false;B.fancybox.center();G.onComplete(y,e,G);K()},K=function(){var V,W;if((y.length-1)>e){V=y[e+1].href;if(typeof V!=="undefined"&&V.match(i)){W=new Image();W.src=V}}if(e>0){V=y[e-1].href;if(typeof V!=="undefined"&&V.match(i)){W=new Image();W.src=V}}},U=function(W){var V={width:parseInt(b.width+(c.width-b.width)*W,10),height:parseInt(b.height+(c.height-b.height)*W,10),top:parseInt(b.top+(c.top-b.top)*W,10),left:parseInt(b.left+(c.left-b.left)*W,10)};if(typeof c.opacity!=="undefined"){V.opacity=W<0.5?0.5:W}M.css(V);m.css({width:V.width-G.padding*2,height:V.height-(h*W)-G.padding*2})},u=function(){return[B(window).width()-(G.margin*2),B(window).height()-(G.margin*2),B(document).scrollLeft()+G.margin,B(document).scrollTop()+G.margin]},R=function(){var V=u(),Z={},W=G.autoScale,X=G.padding*2,Y;if(G.width.toString().indexOf("%")>-1){Z.width=parseInt((V[0]*parseFloat(G.width))/100,10)}else{Z.width=G.width+X}if(G.height.toString().indexOf("%")>-1){Z.height=parseInt((V[1]*parseFloat(G.height))/100,10)}else{Z.height=G.height+X}if(W&&(Z.width>V[0]||Z.height>V[1])){if(H.type=="image"||H.type=="swf"){Y=(G.width)/(G.height);if((Z.width)>V[0]){Z.width=V[0];Z.height=parseInt(((Z.width-X)/Y)+X,10)}if((Z.height)>V[1]){Z.height=V[1];Z.width=parseInt(((Z.height-X)*Y)+X,10)}}else{Z.width=Math.min(Z.width,V[0]);Z.height=Math.min(Z.height,V[1])}}Z.top=parseInt(Math.max(V[3]-20,V[3]+((V[1]-Z.height-40)*0.5)),10);Z.left=parseInt(Math.max(V[2]-20,V[2]+((V[0]-Z.width-40)*0.5)),10);return Z},q=function(V){var W=V.offset();W.top+=parseInt(V.css("paddingTop"),10)||0;W.left+=parseInt(V.css("paddingLeft"),10)||0;W.top+=parseInt(V.css("border-top-width"),10)||0;W.left+=parseInt(V.css("border-left-width"),10)||0;W.width=V.width();W.height=V.height();return W},I=function(){var Y=H.orig?B(H.orig):false,X={},W,V;if(Y&&Y.length){W=q(Y);X={width:W.width+(G.padding*2),height:W.height+(G.padding*2),top:W.top-G.padding-20,left:W.left-G.padding-20}}else{V=u();X={width:G.padding*2,height:G.padding*2,top:parseInt(V[3]+V[1]*0.5,10),left:parseInt(V[2]+V[0]*0.5,10)}}return X},a=function(){if(!T.is(":visible")){clearInterval(p);return}B("div",T).css("top",(N*-40)+"px");N=(N+1)%12};B.fn.fancybox=function(V){if(!B(this).length){return this}B(this).data("fancybox",B.extend({},V,(B.metadata?B(this).metadata():{}))).unbind("click.fb").bind("click.fb",function(X){X.preventDefault();if(P){return}P=true;B(this).blur();j=[];C=0;var W=B(this).attr("rel")||"";if(!W||W==""||W==="nofollow"){j.push(this)}else{j=B("a[rel="+W+"], area[rel="+W+"]");C=j.index(this)}w();return});return this};B.fancybox=function(Y){var X;if(P){return}P=true;X=typeof arguments[1]!=="undefined"?arguments[1]:{};j=[];C=parseInt(X.index,10)||0;if(B.isArray(Y)){for(var W=0,V=Y.length;W<V;W++){if(typeof Y[W]=="object"){B(Y[W]).data("fancybox",B.extend({},X,Y[W]))}else{Y[W]=B({}).data("fancybox",B.extend({content:Y[W]},X))}}j=jQuery.merge(j,Y)}else{if(typeof Y=="object"){B(Y).data("fancybox",B.extend({},X,Y))}else{Y=B({}).data("fancybox",B.extend({content:Y},X))}j.push(Y)}if(C>j.length||C<0){C=0}w()};B.fancybox.showActivity=function(){clearInterval(p);T.show();p=setInterval(a,66)};B.fancybox.hideActivity=function(){T.hide()};B.fancybox.next=function(){return B.fancybox.pos(e+1)};B.fancybox.prev=function(){return B.fancybox.pos(e-1)};B.fancybox.pos=function(V){if(P){return}V=parseInt(V);j=y;if(V>-1&&V<y.length){C=V;w()}else{if(G.cyclic&&y.length>1){C=V>=y.length?0:y.length-1;w()}}return};B.fancybox.cancel=function(){if(P){return}P=true;B.event.trigger("fancybox-cancel");r();H.onCancel(j,C,H);P=false};B.fancybox.close=function(){if(P||M.is(":hidden")){return}P=true;if(G&&false===G.onCleanup(y,e,G)){P=false;return}r();B(J.add(O).add(z)).hide();B(m.add(Q)).unbind();B(window).unbind("resize.fb scroll.fb");B(document).unbind("keydown.fb");if(G.type==="iframe"){m.find("iframe").attr("src",S&&/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")}if(G.titlePosition!=="inside"){A.empty()}M.stop();function V(){Q.fadeOut("fast");A.empty().hide();M.hide();B.event.trigger("fancybox-cleanup");m.empty();G.onClosed(y,e,G);y=H=[];e=C=0;G=H={};P=false}if(G.transitionOut=="elastic"){b=I();var W=M.position();c={top:W.top,left:W.left,width:M.width(),height:M.height()};if(G.opacity){c.opacity=1}A.empty().hide();s.prop=1;B(s).animate({prop:0},{duration:G.speedOut,easing:G.easingOut,step:U,complete:V})}else{M.fadeOut(G.transitionOut=="none"?0:G.speedOut,V)}};B.fancybox.resize=function(){if(Q.is(":visible")){Q.css("height",B(document).height())}B.fancybox.center(true)};B.fancybox.center=function(){var V,W;if(P){return}W=arguments[0]===true?1:0;V=u();if(!W&&(M.width()>V[0]||M.height()>V[1])){return}M.stop().animate({top:parseInt(Math.max(V[3]-20,V[3]+((V[1]-m.height()-40)*0.5)-G.padding)),left:parseInt(Math.max(V[2]-20,V[2]+((V[0]-m.width()-40)*0.5)-G.padding))},typeof arguments[0]=="number"?arguments[0]:200)};B.fancybox.init=function(){if(B("#fancybox-wrap").length){return}B("body").append(L=B('<div id="fancybox-tmp"></div>'),T=B('<div id="fancybox-loading"><div></div></div>'),Q=B('<div id="fancybox-overlay"></div>'),M=B('<div id="fancybox-wrap"></div>'));d=B('<div id="fancybox-outer"></div>').append('<div class="fancybox-bg" id="fancybox-bg-n"></div><div class="fancybox-bg" id="fancybox-bg-ne"></div><div class="fancybox-bg" id="fancybox-bg-e"></div><div class="fancybox-bg" id="fancybox-bg-se"></div><div class="fancybox-bg" id="fancybox-bg-s"></div><div class="fancybox-bg" id="fancybox-bg-sw"></div><div class="fancybox-bg" id="fancybox-bg-w"></div><div class="fancybox-bg" id="fancybox-bg-nw"></div>').appendTo(M);d.append(m=B('<div id="fancybox-content"></div>'),J=B('<a id="fancybox-close"></a>'),A=B('<div id="fancybox-title"></div>'),O=B('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),z=B('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>'));J.click(B.fancybox.close);T.click(B.fancybox.cancel);O.click(function(V){V.preventDefault();B.fancybox.prev()});z.click(function(V){V.preventDefault();B.fancybox.next()});if(B.fn.mousewheel){M.bind("mousewheel.fb",function(V,W){if(P){V.preventDefault()}else{if(B(V.target).get(0).clientHeight==0||B(V.target).get(0).scrollHeight===B(V.target).get(0).clientHeight){V.preventDefault();B.fancybox[W>0?"prev":"next"]()}}})}if(!B.support.opacity){M.addClass("fancybox-ie")}if(S){T.addClass("fancybox-ie6");M.addClass("fancybox-ie6");B('<iframe id="fancybox-hide-sel-frame" src="'+(/^https/i.test(window.location.href||"")?"javascript:void(false)":"about:blank")+'" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(d)}};B.fn.fancybox.defaults={padding:10,margin:40,opacity:false,modal:false,cyclic:false,scrolling:"auto",width:560,height:340,autoScale:true,autoDimensions:true,centerOnScroll:false,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:true,hideOnContentClick:false,overlayShow:true,overlayOpacity:0.7,overlayColor:"#777",titleShow:true,titlePosition:"float",titleFormat:null,titleFromAlt:false,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",easingIn:"swing",easingOut:"swing",showCloseButton:true,showNavArrows:true,enableEscapeButton:true,enableKeyboardNav:true,onStart:function(){},onCancel:function(){},onComplete:function(){},onCleanup:function(){},onClosed:function(){},onError:function(){}};B(document).ready(function(){B.fancybox.init()})})(jQuery);

(function($) {
  jQuery.fn.reverse = Array.prototype.reverse;
  
  var config  = {},
    // auxiliar functions
    aux    = {
      setup        : function( $wrapper, $items, opts ) {
        
        // set the wrappers position to relative
        $wrapper.css('position', 'relative');
        
        // save the items position
        aux.saveInitialPosition( $items );
        
        // set the items to absolute and assign top & left
        $items.each(function(i) {
          var $item   = $(this);
          
          $item.css({
            position  : 'absolute',
            left    : $item.data('left'),
            top      : $item.data('top')
          });
        });
        
          // check how many items we have per row
        var rowCount   = Math.floor( $wrapper.width() / $items.width() ),
          // number of items to show is rowCount * n rows
          shown    = rowCount * opts.rows,
          // total number of rows
          totalRows  = Math.ceil( $items.length / rowCount );
        
        // save this values for later
        config.totalRows  = totalRows;
        config.rowCount   = rowCount;
        config.shownItems  = shown;
        
        // show n rowns
        $wrapper.children(':gt(' + (shown - 1) + ')').hide();
        
        // assign row classes to the items
        $items.each(function(i) {
          var $item   = $(this),
            row    = Math.ceil( (i + 1) / rowCount );
          
          $item.addClass('tj_row_' + row);    
        });
        
        nav.setup( $wrapper, $items, opts );
        
      },
      saveInitialPosition  : function( $items ) {
        $items.each(function(i) {
          var $item   = $(this);
          
          $item.data({
            left    : $item.position().left + 'px',
            top      : $item.position().top + 'px'
          });                  
        });
      }
    },
    // navigation types
    nav    = {
      setup      : function( $wrapper, $items, opts ) {
        nav[opts.type.mode].setup( $wrapper, $items, opts );
      },
      def        : {
        setup    : function( $wrapper, $items, opts ) {
          $items.each(function(i) {
            var $item   = $(this),
              row    = Math.ceil( (i + 1) / config.rowCount ),
              t,
              f = row % opts.rows;
          
            if( f === 1 ) {
              t = '0px';    
            } else if( f === 0 ) {
              t = (opts.rows - 1) * $items.height()  + 'px'; 
            } else {
              t = (f - 1) * $items.height() + 'px';
            }
            
            $item.css({ top  : t });
          });  
        },
        pagination  : function( $wrapper, dir, opts ) {
          if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 
            ( dir === -1 && config.currentRow - opts.rows <= 0 )
          ) {
            $wrapper.data( 'anim', false );
            return false;
          }
          
          var currentRows  = '', nextRows = '';
          
          for( var i = 0; i < opts.rows; ++i ) {
            currentRows += '.tj_row_' + (config.currentRow + i) + ',';
            
            (dir === 1)
              ? nextRows  += '.tj_row_' + (config.currentRow + opts.rows + i) + ','
              : nextRows  += '.tj_row_' + (config.currentRow - 1 - i) + ',';
          }
          
          $wrapper.children(currentRows).hide();
          $wrapper.children(nextRows).show();
          
          (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
          
          $wrapper.data( 'anim', false );
        }
      },
      fade      : {
        setup    : function( $wrapper, $items, opts ) {
          // same like def mode
          nav['def'].setup( $wrapper, $items, opts );
        },
        pagination  : function( $wrapper, dir, opts ) {
          if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) ||
            ( dir === -1 && config.currentRow - opts.rows <= 0 )
          ) {
            $wrapper.data( 'anim', false );
            return false;
          }
          
          var currentRows  = '', nextRows = '';
          
          for( var i = 0; i < opts.rows; ++i ) {
            currentRows += '.tj_row_' + (config.currentRow + i) + ',';
            
            (dir === 1)
              ? nextRows  += '.tj_row_' + (config.currentRow + opts.rows + i) + ','
              : nextRows  += '.tj_row_' + (config.currentRow - 1 - i) + ',';
          }
          
          $wrapper.children(currentRows).fadeOut( opts.type.speed, opts.type.easing );
          
          var $nextRowElements= $wrapper.children(nextRows),

            totalNextRows  = $nextRowElements.length,
            cnt        = 0;
            
          $nextRowElements.fadeIn( opts.type.speed, opts.type.easing, function() {
            ++cnt;
            if( cnt === totalNextRows ) {
              $wrapper.data( 'anim', false );
            }  
          });
          
          (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
        }
      },
      seqfade      : {
        setup    : function( $wrapper, $items, opts ) {
          // same like def mode
          nav['def'].setup( $wrapper, $items, opts );
        },
        pagination  : function( $wrapper, dir, opts ) {
          if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 
            ( dir === -1 && config.currentRow - opts.rows <= 0 )
          ) {
            $wrapper.data( 'anim', false );
            return false;
          }
          
          var currentRows  = '', nextRows = '';
          for( var i = 0; i < opts.rows; ++i ) {
            currentRows += '.tj_row_' + (config.currentRow + i) + ',';
            
            (dir === 1)
            ? nextRows  += '.tj_row_' + (config.currentRow + opts.rows + i) + ','
            : nextRows  += '.tj_row_' + (config.currentRow - 1 - i) + ',';
          }
          
          var seq_t  = opts.type.factor;
          
          var $currentRowElements;
          ( dir === 1 )
            ? $currentRowElements = $wrapper.children(currentRows)
            : $currentRowElements = $wrapper.children(currentRows).reverse();
            
          $currentRowElements.each(function(i) {
            var $el = $(this);
            setTimeout(function() {
              $el.fadeOut( opts.type.speed, opts.type.easing )
            }, seq_t + i * seq_t);
          });
          
          var $nextRowElements;
          ( dir === 1 )
            ? $nextRowElements = $wrapper.children(nextRows)
            : $nextRowElements = $wrapper.children(nextRows).reverse();
          
          var total_elems  = $nextRowElements.length,
            cnt      = 0;
          
          $nextRowElements.each(function(i) {
            var $el = $(this);
            setTimeout(function() {
              $el.fadeIn( opts.type.speed, opts.type.easing, function() {
                ++cnt;
                if( cnt === total_elems ) { 
                  $wrapper.data( 'anim', false );
                }  
              })
            }, (seq_t * 2) + i * seq_t);
          });
          
          (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
        }
      },
      updown      : {
        setup    : function( $wrapper, $items, opts ) {
          $wrapper.children(':gt(' + (config.shownItems - 1) + ')').css('opacity', 0);
          
          $items.each(function(i) {
            var $item   = $(this),
              row    = Math.ceil( (i + 1) / config.rowCount ),
              t    = $item.position().top,
              f = row % opts.rows;
            
            if( row > opts.rows ) {
              t = (opts.rows * $items.height());    
            }
            
            $item.css({ top  : t + 'px'});
          });
        },
        pagination  : function( $wrapper, dir, opts ) {
          if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 
            ( dir === -1 && config.currentRow - 1 <= 0 )
          ) {
            $wrapper.data( 'anim', false );
            return false;
          }
          
          var movingRows  = '';
          
          for( var i = 0; i <= opts.rows; ++i ) {
            ( dir === 1 )
              ? movingRows += '.tj_row_' + (config.currentRow + i) + ','
              : movingRows += '.tj_row_' + (config.currentRow + (i - 1)) + ',';
          }
          
          var $elements;
          
          ( dir === 1 )
            ? $elements = $wrapper.children(movingRows)
            : $elements = $wrapper.children(movingRows).reverse();
          
          var total_elems  = $elements.length,
            cnt      = 0;
          
          $elements.each(function(i) {
            var $el     = $(this),
              row      = $el.attr('class'),
              animParam  = {},
              
              currentRow  = config.currentRow;
            
            // if first row fade out
            // if last row fade in
            // for all the rows move them up / down
            if( dir === 1 ) {
              if(  row === 'tj_row_' + (currentRow) ) {
                animParam.opacity  = 0;
              }
              else if( row === 'tj_row_' + (currentRow + opts.rows) ) {
                animParam.opacity  = 1;
              }
            }
            else {
              if(  row === 'tj_row_' + (currentRow - 1) ) {
                animParam.opacity  = 1;
              }
              else if( row === 'tj_row_' + (currentRow + opts.rows - 1) ) {
                animParam.opacity  = 0;
              }
            }
            
            $el.show();
            
            (dir === 1)
              ? animParam.top = $el.position().top - $el.height() + 'px'
              : animParam.top = $el.position().top + $el.height() + 'px'
            
            $el.stop().animate(animParam, opts.type.speed, opts.type.easing, function() {
              if( parseInt( animParam.top ) < 0 || parseInt( animParam.top ) > $el.height() * (opts.rows - 1) )
                $el.hide();
              
              ++cnt;
              if( cnt === total_elems ) {
                $wrapper.data( 'anim', false );
              }  
            });
          });
          
          (dir === 1) ? config.currentRow += 1 : config.currentRow -= 1;
        }
      },
      sequpdown    : {
        setup     : function( $wrapper, $items, opts ) {
          // same like updown mode
          nav['updown'].setup( $wrapper, $items, opts );
        },
        pagination  : function( $wrapper, dir, opts ) {
          if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 
            ( dir === -1 && config.currentRow - 1 <= 0 )  
          ) {
            $wrapper.data( 'anim', false );
            return false;
          }
          
          var movingRows  = '';
          
          for( var i = 0; i <= opts.rows; ++i ) {
            ( dir === 1 )
              ? movingRows += '.tj_row_' + (config.currentRow + i) + ','
              : movingRows += '.tj_row_' + (config.currentRow + (i - 1)) + ',';
          }
          
          var seq_t  = opts.type.factor,
            $elements;
          
          var dircond  = 1;
          if( opts.type.reverse ) dircond = -1;
          ( dir === dircond )
            ? $elements = $wrapper.children(movingRows)
            : $elements = $wrapper.children(movingRows).reverse();
          
          var total_elems  = $elements.length,
            cnt      = 0;
          
          $elements.each(function(i) {
            var $el     = $(this),
              row      = $el.attr('class'),
              animParam  = {},
              
              currentRow  = config.currentRow;
              
            setTimeout(function() {
              // if first row fade out
              // if last row fade in
              // for all the rows move them up / down
              if( dir === 1 ) {
                if(  row === 'tj_row_' + (currentRow) ) {
                  animParam.opacity  = 0;
                }
                else if( row === 'tj_row_' + (currentRow + opts.rows) ) {
                  animParam.opacity  = 1;
                }
              }
              else {
                if(  row === 'tj_row_' + (currentRow - 1) ) {
                  animParam.opacity  = 1;
                }
                else if( row === 'tj_row_' + (currentRow + opts.rows - 1) ) {
                  animParam.opacity  = 0;
                }
              }
              
              $el.show();
              
              (dir === 1)
                ? animParam.top = $el.position().top - $el.height() + 'px'
                : animParam.top = $el.position().top + $el.height() + 'px'
              
              $el.stop().animate(animParam, opts.type.speed, opts.type.easing, function() {
                if( parseInt( animParam.top ) < 0 || parseInt( animParam.top ) > $el.height() * (opts.rows - 1) )
                  $el.hide();
                  
                ++cnt;
                if( cnt === total_elems ) { 
                  $wrapper.data( 'anim', false );
                }  
              });  
            }, seq_t + i * seq_t);
          });
          
          (dir === 1) ? config.currentRow += 1 : config.currentRow -= 1;
        }
      },
      showhide    : {
        setup     : function( $wrapper, $items, opts ) {
          $items.each(function(i) {
            var $item   = $(this),
              row    = Math.ceil( (i + 1) / config.rowCount ),
              t,
              f = row % opts.rows;
            
            if( f === 1 ) {
              t = '0px';    
            } else if( f === 0 ) {
              t = (opts.rows - 1) * $items.height()  + 'px'; 
            } else {
              t = (f - 1) * $items.height() + 'px';
            }
            
            $item.css({ top  : t });
          });    
        },
        pagination  : function( $wrapper, dir, opts ) {
          if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 
            ( dir === -1 && config.currentRow - opts.rows <= 0 )
          ) {
            $wrapper.data( 'anim', false );
            return false;
          }
          
          var currentRows  = '', nextRows = '';
          
          for( var i = 0; i < opts.rows; ++i ) {
            currentRows += '.tj_row_' + (config.currentRow + i) + ',';
            
            (dir === 1)
              ? nextRows  += '.tj_row_' + (config.currentRow + opts.rows + i) + ','
              : nextRows  += '.tj_row_' + (config.currentRow - 1 - i) + ',';
          }
          
          $wrapper.children(currentRows).hide( opts.type.speed, opts.type.easing );
          
          var $nextRowElements= $wrapper.children(nextRows),
            totalNextRows  = $nextRowElements.length,
            cnt        = 0;
            
          $nextRowElements.show( opts.type.speed, opts.type.easing, function() {
            ++cnt;
            if( cnt === totalNextRows ) {
              $wrapper.data( 'anim', false );
            }  
          });
          
          (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
        }
      },
      disperse    : {
        setup     : function( $wrapper, $items, opts ) {
          $items.each(function(i) {
            var $item   = $(this),
              row    = Math.ceil( (i + 1) / config.rowCount ),
              t,
              f = row % opts.rows;
          
            if( f === 1 ) {
              t = '0px';    
            } else if( f === 0 ) {
              t = (opts.rows - 1) * $items.height()  + 'px'; 
            } else {
              t = (f - 1) * $items.height() + 'px';
            }
            
            $item.css({ top  : t }).data('top', t);
          });
        },
        pagination  : function( $wrapper, dir, opts ) {
          if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 
            ( dir === -1 && config.currentRow - opts.rows <= 0 )
          ) {
            $wrapper.data( 'anim', false );
            return false;
          }
          
          var currentRows  = '', nextRows = '';
          for( var i = 0; i < opts.rows; ++i ) {
            currentRows += '.tj_row_' + (config.currentRow + i) + ',';
            
            (dir === 1)
              ? nextRows  += '.tj_row_' + (config.currentRow + opts.rows + i) + ','
              : nextRows  += '.tj_row_' + (config.currentRow - 1 - i) + ',';
          }
          
          $wrapper.children(currentRows).each(function(i) {
            var $el = $(this);
            $el.stop().animate({
              left  : $el.position().left + Math.floor( Math.random() * 101 ) - 50 + 'px',
              top    : $el.position().top + Math.floor( Math.random() * 101 ) - 50 + 'px',
              opacity  : 0
            }, opts.type.speed, opts.type.easing, function() {
              $el.css({
                left  : $el.data('left'),
                top    : $el.data('top')
              }).hide();
            });
          });
          
          var $nextRowElements  = $wrapper.children(nextRows);
            total_elems      = $nextRowElements.length,
            cnt          = 0;
          
          $nextRowElements.each(function(i) {
            var $el = $(this);
            
            $el.css({
              left  : parseInt($el.data('left')) + Math.floor( Math.random() * 301 ) - 150 + 'px',  
              top    : parseInt($el.data('top')) + Math.floor( Math.random() * 301 ) - 150 + 'px',
              opacity  : 0
            })
            .show()
            .animate({
              left  : $el.data('left'),
              top    : $el.data('top'),
              opacity  : 1
            }, opts.type.speed, opts.type.easing, function() {
              ++cnt;
              if( cnt === total_elems ) { 
                $wrapper.data( 'anim', false );
              }
            });
          });
          
          (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
        }
      },
      rows      : {
        setup     : function( $wrapper, $items, opts ) {
          // same like def mode
          nav['def'].setup( $wrapper, $items, opts );
        },
        pagination  : function( $wrapper, dir, opts ) {
          if( ( dir === 1 && config.currentRow + opts.rows > config.totalRows ) || 
            ( dir === -1 && config.currentRow - opts.rows <= 0 )
          ) {
            $wrapper.data( 'anim', false );
            return false;
          }
          
          var currentRows  = '', nextRows = '';
          for( var i = 0; i < opts.rows; ++i ) {
            currentRows += '.tj_row_' + (config.currentRow + i) + ',';
            
            (dir === 1)
              ? nextRows  += '.tj_row_' + (config.currentRow + opts.rows + i) + ','
              : nextRows  += '.tj_row_' + (config.currentRow - 1 - i) + ',';
          }
          
          $wrapper.children(currentRows).each(function(i) {
            var $el   = $(this),
              rownmb  = $el.attr('class').match(/tj_row_(\d+)/)[1],
              diff;
              
            if( rownmb%2 === 0 ) {
              diff = opts.type.factor;
            }
            else {
              diff = -opts.type.factor;
            }
            
            $el.stop().animate({
              left  : $el.position().left + diff + 'px',
              opacity  : 0
            }, opts.type.speed, opts.type.easing, function() {
              $el.css({
                left  : $el.data('left')
              }).hide();
            });
          });
          
          var $nextRowElements  = $wrapper.children(nextRows);
            total_elems      = $nextRowElements.length,
            cnt          = 0;
          
          $nextRowElements.each(function(i) {
            var $el = $(this),
              rownmb  = $el.attr('class').match(/tj_row_(\d+)/)[1],
              diff;
            
            if( rownmb%2 === 0 ) {
              diff = opts.type.factor;
            }
            else {
              diff = -opts.type.factor;
            }
            
            $el.css({
              left  : parseInt($el.data('left')) + diff + 'px',
              opacity  : 0
            })
            .show()
            .animate({
              left  : $el.data('left'),
              opacity  : 1
            }, opts.type.speed, opts.type.easing, function() {
              ++cnt;
              if( cnt === total_elems ) { 
                $wrapper.data( 'anim', false );
              }
            });
          });
          
          (dir === 1) ? config.currentRow += opts.rows : config.currentRow -= opts.rows;
        }
      }
    },
    methods = {
      init   : function( options ) {
        
        if( this.length ) {
          
          var settings = {
            rows  : 2,
            navL  : '#tj_prev',
            navR  : '#tj_next',
            type  : {
              mode    : 'def',     // use def | fade | seqfade | updown | sequpdown | showhide | disperse | rows
              speed    : 500,      // for fade, seqfade, updown, sequpdown, showhide, disperse, rows
              easing    : 'jswing',    // for fade, seqfade, updown, sequpdown, showhide, disperse, rows  
              factor    : 50,      // for seqfade, sequpdown, rows
              reverse    : false      // for sequpdown
            }
          };
          
          return this.each(function() {
            
            // if options exist, lets merge them with our default settings
            if ( options ) {
              $.extend( settings, options );
            }
            
            var $el       = $(this).css( 'visibility', 'hidden' ),
              // the ul
              $wrapper    = $el.find('ul.tj_gallery'),
              // the items
              $thumbs      = $wrapper.children('li'),
              total      = $thumbs.length,
              // the navigation elements
              $p_nav      = $(settings.navL),
              $n_nav      = $(settings.navR);
            
            // save current row for later (first visible row)
            config.currentRow  = 1;
            
            // flag to control animation progress
            $wrapper.data( 'anim', false );
            
            // preload thumbs
            var loaded = 0;
            $thumbs.find('img').each( function(i) {
              var $img   = $(this);
              $('<img/>').load( function() {
                ++loaded;
                if( loaded === total ) {
                  
                  // setup
                  aux.setup( $wrapper, $thumbs, settings );

                  $el.css( 'visibility', 'visible' );
                  
                  // navigation events
                  if( $p_nav.length ) {
                    $p_nav.bind('click.gridnav', function( e ) {
                      if( $wrapper.data( 'anim' ) ) return false;
                      $wrapper.data( 'anim', true );
                      nav[settings.type.mode].pagination( $wrapper, -1, settings );
                      return false;
                    });
                  }
                  if( $n_nav.length ) {
                    $n_nav.bind('click.gridnav', function( e ) {
                      if( $wrapper.data( 'anim' ) ) return false;
                      $wrapper.data( 'anim', true );
                      nav[settings.type.mode].pagination( $wrapper, 1, settings );
                      return false;
                    });
                  }
                  /*
                  adds events to the mouse
                  */
                  $el.bind('mousewheel.gridnav', function(e, delta) {
                    if(delta > 0) {
                      if( $wrapper.data( 'anim' ) ) return false;
                      $wrapper.data( 'anim', true );
                      nav[settings.type.mode].pagination( $wrapper, -1, settings );
                    }  
                    else {
                      if( $wrapper.data( 'anim' ) ) return false;
                      $wrapper.data( 'anim', true );
                      nav[settings.type.mode].pagination( $wrapper, 1, settings );
                    }  
                    return false;
                  });
                  
                }
              }).attr( 'src', $img.attr('src') );
            });
            
          });
        }
      }
    };
  
  $.fn.gridnav = function(method) {
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.gridnav' );
    }
  };
})(jQuery); 

