// Cufon
if (typeof(Cufon) !== 'undefined')
{
	Cufon.replace('.post h1, .post h2, .post h3, #head-nav li a, .post p, #foot-nav li');

	$(function(){
		// rtl cufon hack
		if ($('html').attr('dir') === 'rtl') // todo: select by attr dir value rtl -> find cufon -> foreach results... 
		{
			var cache = {};
			$('cufon').each(function(){
				var self	= $(this),
					container = self.parent(),

					ltr_str	= container.text(),
					rtl_str	= ltr_str.split('').reverse().join(''),

					// http://www.i18nguy.com/temp/rtl.html
					// http://www.regularexpressions.info/unicode.html#block
					// match (non) Arabic, Hebrew
					regex = RegExp(/[^\u0600-\u06FF\u0590-\u05FF]+/g),
					no_rtl_str = ltr_str.match(regex),
					rv_ltr_str = rtl_str.match(regex);

				if (ltr_str in cache) return;

				cache[ltr_str] = rtl_str; // todo: change cache .. container context

				if ((no_rtl_str && rv_ltr_str) && (no_rtl_str.length == rv_ltr_str.length))
				{
					for (i = 0; i < no_rtl_str.length; i++)
					{
						rtl_str = rtl_str.replace(rv_ltr_str[i], '<bdo dir="ltr">' + no_rtl_str[i] + '</bdo>');
					}
				}

				if (ltr_str !== rtl_str)
				{

					container.html(rtl_str);

					Cufon.refresh();

					$('> cufon', container).each(function(){
						var canvas = $('canvas', this);
						canvas.css({
							left	: canvas.css('right'),
							right	: canvas.css('left')
						});
					});					
				}
			});
		}
	});
}



(function($) {
	$.fn.gallery = function(options) { return new Gallery(this.get(0), options); };

	function Gallery(context, options) { this.init(context, options); };

	Gallery.prototype = {
		options:{},
		init: function (context, options){
			this.options = $.extend({
				infinite: false,								
				duration: 700,									
				slideElement: 1,								
				autoRotation: false,							
				effect: false,									
				listOfSlides: 'ul > li',						
				switcher: false,								
				disableBtn: false,								
				nextBtn: 'a.link-next, a.btn-next, a.next',		
				prevBtn: 'a.link-prev, a.btn-prev, a.prev',		
				circle: true,									
				direction: false,								
				event: 'click',									
				IE: false,										
				autoHeight: false								
			}, options || {});
			var _el = $(context).find(this.options.listOfSlides);
			if (this.options.effect) this.list = _el;
			else this.list = _el.parent();
			this.switcher = $(context).find(this.options.switcher);
			this.nextBtn = $(context).find(this.options.nextBtn);
			this.prevBtn = $(context).find(this.options.prevBtn);
			this.count = _el.index(_el.filter(':last'));
		
			if (this.options.switcher) this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
			else this.active = _el.index(_el.filter('.active:eq(0)'));
			if (this.active < 0) this.active = 0;
			this.last = this.active;
		
			this.woh = _el.outerWidth(true);
			if (!this.options.direction) this.installDirections(this.list.parent().width());
			else {
				this.woh = _el.outerHeight(true);
				this.installDirections(this.list.parent().height());
			}
		
			if (!this.options.effect) {
				this.rew = this.count - this.wrapHolderW + 1;
				if (!this.options.direction) this.anim = '{marginLeft: -(this.woh * this.active)}';
				else this.anim = '{marginTop: -(this.woh * this.active)}';
				eval('this.list.css('+this.anim+')');
			}
			else {
				this.rew = this.count;
				this.list.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
				this.switcher.removeClass('active').eq(this.active).addClass('active');
				if(this.options.autoHeight) this.list.parent().css({height: this.list.eq(this.active).outerHeight()});
			}
			this.flag = true;
			if (this.options.infinite){
				this.count++;
				this.active += this.count;
				this.list.append(_el.clone());
				this.list.append(_el.clone());
				eval('this.list.css('+this.anim+')');
			}
		
			this.initEvent(this, this.nextBtn, true);
			this.initEvent(this, this.prevBtn, false);
			if (this.options.disableBtn) this.initDisableBtn();
			if (this.options.autoRotation) this.runTimer(this);
			if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
		},
		initDisableBtn: function(){
			this.prevBtn.removeClass('prev-'+this.options.disableBtn);
			this.nextBtn.removeClass('next-'+this.options.disableBtn);
			if (this.active == 0 || this.count+1 == this.wrapHolderW) this.prevBtn.addClass('prev-'+this.options.disableBtn);
			if (this.active == 0 && this.count == 1 || this.count+1 <= this.wrapHolderW) this.nextBtn.addClass('next-'+this.options.disableBtn);
			if (this.active == this.rew) this.nextBtn.addClass('next-'+this.options.disableBtn);
		},
		installDirections: function(temp){
			this.wrapHolderW = Math.ceil(temp / this.woh);
			if (((this.wrapHolderW - 1) * this.woh + this.woh / 2) > temp) this.wrapHolderW--;
		},
		fadeElement: function(){
			if ($.browser.msie && this.options.IE){
				this.list.eq(this.last).css({opacity:0});
				this.list.removeClass('active').eq(this.active).addClass('active').css({opacity:'auto'});
			}
			else{
				this.list.eq(this.last).animate({opacity:0}, {queue:false, duration: this.options.duration});
				this.list.removeClass('active').eq(this.active).addClass('active').animate({
					opacity:1
				}, {queue:false, duration: this.options.duration, complete: function(){
					$(this).css('opacity','auto');
				}});
			}
			if(this.options.autoHeight) this.list.parent().animate({height: this.list.eq(this.active).outerHeight()}, {queue:false, duration: this.options.duration});
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			this.last = this.active;
		},
		scrollElement: function($this){
			if (!$this.options.infinite) eval('$this.list.animate('+$this.anim+', {queue:false, duration: $this.options.duration});');
			else eval('$this.list.animate('+$this.anim+', $this.options.duration, function(){ $this.flag = true });');
			if ($this.options.switcher) $this.switcher.removeClass('active').eq($this.active / $this.options.slideElement).addClass('active');
		},
		runTimer: function($this){
			if($this._t) clearTimeout($this._t);
			$this._t = setInterval(function(){
				if ($this.options.infinite) $this.flag = false;
				$this.toPrepare($this, true);
			}, this.options.autoRotation);
		},
		initEventSwitcher: function($this, el){
			el.bind($this.options.event, function(){
				$this.active = $this.switcher.index($(this)) * $this.options.slideElement;
				if($this._t) clearTimeout($this._t);
				if ($this.options.disableBtn) $this.initDisableBtn();
				if (!$this.options.effect) $this.scrollElement($this);
				else $this.fadeElement();
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		initEvent: function($this, addEventEl, dir){
			addEventEl.bind($this.options.event, function(){
				if ($this.flag){
					if ($this.options.infinite) $this.flag = false;
					if($this._t) clearTimeout($this._t);
					$this.toPrepare($this, dir);
					if ($this.options.autoRotation) $this.runTimer($this);
				}
				return false;
			});
		},
		toPrepare: function($this, side){
			if (!$this.options.infinite){
				if (($this.active == $this.rew) && $this.options.circle && side) $this.active = -$this.options.slideElement;
				if (($this.active == 0) && $this.options.circle && !side) $this.active = $this.rew + $this.options.slideElement;
				for (var i = 0; i < $this.options.slideElement; i++){
					if (side) { if ($this.active + 1 <= $this.rew) $this.active++; }
					else { if ($this.active - 1 >= 0) $this.active--; }
				};
			}
			else{
				if ($this.active >= $this.count + $this.count && side) $this.active -= $this.count;
				if ($this.active <= $this.count-1 && !side) $this.active += $this.count;
				eval('$this.list.css('+$this.anim+')');
				if (side) $this.active += $this.options.slideElement;
				else $this.active -= $this.options.slideElement;
			}
			if (this.options.disableBtn) this.initDisableBtn();
			if (!$this.options.effect) $this.scrollElement($this);
			else $this.fadeElement();
		},
		stop: function(){
			if (this._t) clearTimeout(this._t);
		},
		play: function(){
			if (this._t) clearTimeout(this._t);
			if (this.options.autoRotation) this.runTimer(this);
		}
	}
}(jQuery));

$.fn.hoverClass = function(c) {
	return this.each(function(){
		$(this).hover( 
			function() { $(this).addClass(c);  },
			function() { $(this).removeClass(c); }
		);
	});
};



$(function($){

	
	// slide gallery
	$('div.gallery').gallery({
		slideElement: 1,
		duration: 700,
		listOfSlides: 'div > ul > li'
	});
	
	$("a.lightbox").fancybox({
		padding: 0,
		margin: 0,
		autoScale: false,
		overlayColor: '#000',
		titleShow: false,
		overlayShow: false,
		showNavArrows: false,
		onComplete: function(){
			var winW = $(window).width();
			var winH = $(window).height();
			if (winW < $('body').width()) winW = $('body').width();
			if (winH < $('body').height()) winH = $('body').height();
			var startW = $('#fancybox-img').outerWidth();
			var cof = winW / startW;
			var w = $('#fancybox-img').outerWidth();
			var h = $('#fancybox-img').outerHeight();
			var _time;
			
			$('#fancybox-content').css({height: winH, width: winW});
			$('#fancybox-img').css({height: h*cof, width: w*cof});
			$('#fancybox-wrap').css({height: winH, width: winW, visibility: 'visible', margin: 0});
			
			var raz = h*cof-winH;
			var now = winH/raz;
			
			$('#fancybox-wrap').mousemove(function(e){
				if (raz > 0) $('#fancybox-img').css({marginTop:-e.pageY/now});
			});
			
			$(window).resize(function(){
				$('#fancybox-img').css({marginTop: 0});
				if(_time) clearTimeout(_time);
				winW = $(window).width();
				winH = $(window).height();
				if (winW < $('body').width()) winW = $('body').width();
				if (winH < $('body').height()) winH = $('body').height();
				cof = winW / startW;
				
				$('#fancybox-wrap').css({height: winH, width: winW});
				$('#fancybox-content').css({height: winH, width: winW});
				$('#fancybox-img').css({height: h*cof, width: w*cof});
				
				_time = setTimeout(function(){
					winW = $(window).width();
					winH = $(window).height();
					if (winW < $('body').width()) winW = $('body').width();
					if (winH < $('body').height()) winH = $('body').height();
					cof = winW / startW;
					
					raz = h*cof-winH;
					now = winH/raz;
					$('#fancybox-wrap').css({height: winH, width: winW});
					$('#fancybox-content').css({height: winH, width: winW});
					$('#fancybox-img').css({height: h*cof, width: w*cof});
				}, 100);
			});
		}
	});


	// if bgImg is defined set the BG image
	if(typeof bgImg != 'undefined') {
		$("#bg").attr("src", bgImg);	
	// otherwise remove the <img>
	} else { 
		$('#bg').remove();		
	}
	
     var theWindow        = $(window),
     $bg              = $("#bg"),
     aspectRatio      = $bg.width() / $bg.height();

    function resizeBg() {

            if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
                $bg
                    .removeClass()
                    .addClass('bgheight');
            } else {
                $bg
                    .removeClass()
                    .addClass('bgwidth');
            }

    }

    theWindow.resize(function() {
            resizeBg();
    }).trigger("resize");

	
});

jQuery.fn.nudge = function(params) {
	//set default parameters
	params = jQuery.extend({
		amount: 15,				//amount of pixels to pad / marginize
		duration: 300,			//amount of milliseconds to take
		property: 'padding', 	//the property to animate (could also use margin)
		direction: 'left',		//direction to animate (could also use right)
		toCallback: function() {},	//function to execute when MO animation completes
		fromCallback: function() {}	//function to execute when MOut animation completes
	}, params);
	//For every element meant to nudge...
	this.each(function() {
		//variables
		var jQueryt = jQuery(this);
		var jQueryp = params;
		var dir = jQueryp.direction;
		var prop = jQueryp.property + dir.substring(0,1).toUpperCase() + dir.substring(1,dir.length);
		var initialValue = jQueryt.css(prop);
		/* fx */
		var go = {};
		go[prop] = parseInt(jQueryp.amount) + parseInt(initialValue);
		var bk = {};
		bk[prop] = initialValue;
		
		//Proceed to nudge on hover
		jQueryt.hover(function() {
			jQueryt.stop().animate(go, jQueryp.duration, '', jQueryp.toCallback);
		}, function() {
			jQueryt.stop().animate(bk, jQueryp.duration, '', jQueryp.fromCallback);
		});
	});
	return this;
};
