jQuery.noConflict();
// init page
jQuery(window).load(function(){
	hoverAnimate();
	initCarousel();
	initFadeText();
	initGallery();
	initImageHover();
	initLazyLoad();
});

//init lazy loading
function initLazyLoad(){
	jQuery('img.lazy').lazyload({
		effect:'fadeIn',
		speed:'slow',
		container:jQuery('.gallery')
	});
	/*jQuery('img.lazy').asynchImageLoader({
		timeout:2000,
		effect:'fadeIn',
		speed:2000
	});*/
}

function initGrayscaleImage(_this){
	var _thisX = _this.position().left,
		_grayed = _this.clone().appendTo(_this.parent()).grayscale().css({opacity: 0, position:'absolute', top:0, left:_thisX});
		_duration = 400;
	_grayed.stop().animate({opacity:1}, _duration * 2, "linear", function(){ _this.css('opacity', '1'); });
	_grayed.mouseenter(function(){
		_grayed.stop().animate({opacity:0}, _duration);
	});
	_grayed.mouseleave(function(){
		_grayed.stop().animate({opacity:1}, _duration);
	});
}

//init carousel
function initCarousel(){
	jQuery('.container').scrollGallery({
		btnPrev:'a.prev',
		btnNext:'a.next',
		circleSlide:false,
		duration:650
	});
}

//init image hover
function initImageHover(){
	jQuery('.partners-holder a img').each(function(){
		var _this = jQuery(this);
		var _duration = 400;
		_this.mouseenter(function(){
			_this.stop().animate({opacity:1}, _duration);
		});
		_this.mouseleave(function(){
			_this.stop().animate({opacity:.3}, _duration);
		});
		/*var _this = jQuery(this),
			_thisX = _this.position().left,
			_grayed = _this.clone().appendTo(_this.parent()).grayscale().css({opacity: 0, position:'absolute', top:0, left:_thisX});
			_duration = 400;
		_grayed.stop().animate({opacity:1}, _duration * 2, "linear", function(){ _this.css('opacity', '1'); });
		_grayed.mouseenter(function(){
			_grayed.stop().animate({opacity:0}, _duration);
		});
		_grayed.mouseleave(function(){
			_grayed.stop().animate({opacity:1}, _duration);
		});*/
	});
};

// text tabs code
function initFadeText(){
	var animSpeed = 300;
	var activeClass = 'active';
	var boxes = jQuery('.discription');
	var elementActive = boxes.find('li.'+activeClass);
	var curHeigth = elementActive.height();
	boxes.css({height: curHeigth});

	jQuery('.nav-fade a, .gallery a').each(function(){
		var curLink = jQuery(this);
		var rel = curLink.attr('rel');
		var currentBox = jQuery(rel).hide().css({opacity:0});
		curLink.hover(function(){
			//if(!currentBox.hasClass(activeClass)){
				elementActive.removeClass(activeClass).animate({opacity : 0},{duration:animSpeed});
				currentBox.addClass(activeClass).css({opacity:0}).stop().show().animate({opacity : 1},{duration:animSpeed});
				curHeigth = currentBox.height();
				boxes.css({height: curHeigth});
			//}
		}, function(){
			currentBox.stop().show().animate({opacity : 0},{
				duration:animSpeed,
				complete:function(){
					currentBox.removeClass(activeClass).removeAttr('style').hide();
				}
			});
		});
		
		curLink.parents('ul').eq(0).mouseleave(function(){
			elementActive.stop().show().addClass(activeClass).animate({opacity : 1},{duration:animSpeed});
			curHeigth = elementActive.height();
			boxes.css({height: curHeigth});
			if(curHeigth == null) boxes.css({height: ''});
		});
	});

	elementActive.show().css({opacity:1});
}

// ajax posts gallery
function initGallery() {
	var animSpeed = 600;
	var showSpeed = 300;
	var loadingClass = 'ajax-loading';
	var disabledClass = 'btn-disabled';
	
	jQuery('.alt-gallery').each(function(){
		var gallery = jQuery(this);
		var ajaxBusy = false;
		var hold = gallery.find('.post-holder');
		var btnPrev = gallery.find('.prev');
		var btnNext = gallery.find('.next');
		var slideWidth = hold.width();
		var currentSlide = hold.children();
		var nextSlide;
		var direction;

		// init gallery
		currentSlide.css({position:'absolute',width:slideWidth});
		hold.css({height:currentSlide.height()})

		// event handlers
		btnPrev.click(function(){
			if(!ajaxBusy && !isEmptyLink(this)) {
				switchSlide(this.href, 1);
			}
			return false;
		});
		btnNext.click(function(){
			if(!ajaxBusy && !isEmptyLink(this)) {
				switchSlide(this.href, -1);
			}
			return false;
		});

		function isEmptyLink(obj) {
			return jQuery(obj).attr('href') == '#';
		}
		function refreshState() {
			if(isEmptyLink(btnPrev)) btnPrev.addClass(disabledClass); else btnPrev.removeClass(disabledClass);
			if(isEmptyLink(btnNext)) btnNext.addClass(disabledClass); else btnNext.removeClass(disabledClass);
		}
		function parseSlideData(obj) {
			var prevURL = obj.find('a.prev').attr('href');
			var nextURL = obj.find('a.next').attr('href');
			btnPrev.attr('href',prevURL || '#');
			btnNext.attr('href',nextURL || '#');
			refreshState();
		}
		function switchSlide(href, direction) {
			ajaxBusy = true;
			gallery.addClass(loadingClass);
			nextSlide = jQuery('<div class="post single-post">');
			currentSlide.animate({marginLeft:direction*slideWidth},{duration:animSpeed,complete:function(){
				currentSlide.remove();
				currentSlide = nextSlide;
				nextSlide.css({position:'absolute',display:'none'}).appendTo(hold);
				jQuery.ajax({
					url:href,
					type:'POST',
					data:'ajax=true',
					dataType:'text',
					success:function(msg) {
						nextSlide.html(msg);
						parseSlideData(nextSlide);
						nextSlide.fadeIn(showSpeed);
						hold.animate({height:nextSlide.height()},{duration:showSpeed});
						gallery.removeClass(loadingClass);
						ajaxBusy = false;
					},
					error:function(){
						alert('AJAX Error');
						gallery.removeClass(loadingClass);
						ajaxBusy = false;
					}
				});
			}});
		}
		refreshState();
	});
}

//animate hover
function hoverAnimate(){
	var animEl = jQuery('#main-nav li');
	var speed = 400;
	var desc = jQuery('.discription li');
	animEl.each(function(){
		var el = jQuery(this);
		var link = el.find('a');
		var span = jQuery('<span />');
		span.appendTo(el);
		if(!el.hasClass('active')){
			el.hover(function(){	
				jQuery(this).addClass('hover');
				span.stop().css({opacity:0}).animate({opacity:1}, speed);
			}, function(){
				span.stop().animate({opacity : 0}, {
					duration: speed,
					complete: function(){
						el.removeClass('hover');
						jQuery(this).removeAttr('style');
					}
				});
			});	
		}
	});
}

// scrolling gallery dynamic ajax load plugin
jQuery.fn.scrollGallery = function(_options){
	var _options = jQuery.extend({
		sliderHolder: '>div',
		slider:'>ul',
		slides: '>li',
		pagerLinks:'div.pager a',
		btnPrev:'a.link-prev',
		btnNext:'a.link-next',
		activeClass:'active',
		disabledClass:'disabled',
		generatePagination:'div.pg-holder',
		curNum:'em.scur-num',
		allNum:'em.sall-num',
		circleSlide:true,
		pauseClass:'gallery-paused',
		pauseButton:'none',
		loadingClass:'loading',
		pauseOnHover:true,
		autoRotation:false,
		stopAfterClick:false,
		switchTime:5000,
		duration:650,
		easing:'swing',
		event:'click',
		splitCount:false,
		afterInit:false,
		vertical:false,
		ajaxLoad:false,
		step:false
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _sliderHolder = jQuery(_options.sliderHolder, _this);
		var _slider = jQuery(_options.slider, _sliderHolder);
		var _slides = jQuery(_options.slides, _slider);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _generatePagination = jQuery(_options.generatePagination, _this);
		var _curNum = jQuery(_options.curNum, _this);
		var _allNum = jQuery(_options.allNum, _this);
		var _pauseButton = jQuery(_options.pauseButton, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _pauseClass = _options.pauseClass;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledClass = _options.disabledClass;
		var _easing = _options.easing;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _step = _options.step;
		var _vertical = _options.vertical;
		var _circleSlide = _options.circleSlide;
		var _stopAfterClick = _options.stopAfterClick;
		var _afterInit = _options.afterInit;
		var _splitCount = _options.splitCount;
		var _ajaxLoad = _options.ajaxLoad;
		var _loadingClass = _options.loadingClass;

		// gallery init
		if(!_slides.length) return;

		if(_splitCount) {
			var curStep = 0;
			var newSlide = jQuery('<slide>').addClass('split-slide');
			_slides.each(function(){
				newSlide.append(this);
				curStep++;
				if(curStep > _splitCount-1) {
					curStep = 0;
					_slider.append(newSlide);
					newSlide = jQuery('<slide>').addClass('split-slide');
				}
			});
			if(curStep) _slider.append(newSlide);
			_slides = _slider.children();
		}

		var _currentStep = 0;
		var _sumWidth = 0;
		var _sumHeight = 0;
		var _hover = false;
		var _stepWidth;
		var _stepHeight;
		var _stepCount;
		var _offset;
		var _timer;

		_slides.each(function(){
			_sumWidth+=jQuery(this).outerWidth(true);
			_sumHeight+=jQuery(this).outerHeight(true);
		});

		// calculate gallery offset
		function recalcOffsets() {
			if(_vertical) {
				if(_step) {
					_stepHeight = _slides.eq(_currentStep).outerHeight(true);
					_stepCount = Math.ceil((_sumHeight-_sliderHolder.height())/_stepHeight)+1;
					_offset = -_stepHeight*_currentStep;
				} else {
					_stepHeight = _sliderHolder.height();
					_stepCount = Math.ceil(_sumHeight/_stepHeight);
					_offset = -_stepHeight*_currentStep;
					if(_offset < _stepHeight-_sumHeight) _offset = _stepHeight-_sumHeight;
				}
			} else {
				if(_step) {
					_stepWidth = _slides.eq(_currentStep).outerWidth(true)*_step;
					_stepCount = Math.ceil((_sumWidth-_sliderHolder.outerWidth())/_stepWidth)+1;
					_offset = -_stepWidth*_currentStep;
					if(_offset < _sliderHolder.outerWidth()-_sumWidth) _offset = _sliderHolder.outerWidth()-_sumWidth;
				} else {
					_stepWidth = _sliderHolder.outerWidth();
					_stepCount = Math.ceil(_sumWidth/_stepWidth);
					_offset = -_stepWidth*_currentStep;
					if(_offset < _stepWidth-_sumWidth) _offset = _stepWidth-_sumWidth;
				}
			}
		}

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				nextSlide();
				return false;
			});
		}
		if(_generatePagination.length) {
			_generatePagination.empty();
			recalcOffsets();
			var _list = jQuery('<ul />');
			for(var i=0; i<_stepCount; i++) jQuery('<li><a href="#">'+(i+1)+'</a></li>').appendTo(_list);
			_list.appendTo(_generatePagination);
			_pagerLinks = _list.children();
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentStep != _ind) {
						if(_stopAfterClick) stopAutoSlide();
						_currentStep = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// gallery animation
		function prevSlide() {
			recalcOffsets();
			if(_currentStep > 0) _currentStep--;
			else if(_circleSlide) _currentStep = _stepCount-1;
			switchSlide();
		}
		function nextSlide() {
			recalcOffsets();
			if(_currentStep < _stepCount-1) _currentStep++;
			else if(_circleSlide) _currentStep = 0;
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
			if(!_circleSlide) {
				_btnPrev.removeClass(_disabledClass);
				_btnNext.removeClass(_disabledClass);
				if(_currentStep == 0) _btnPrev.addClass(_disabledClass);
				if(_currentStep == _stepCount-1) _btnNext.addClass(_disabledClass);
			}
			if(_curNum.length) _curNum.text(_currentStep+1);
			if(_allNum.length) _allNum.text(_stepCount);
		}
		function dynamicLoad(){
			var _path = _slides.eq(_currentStep).attr('rel'),
				_place = _slides.eq(_currentStep);
			_place.addClass(_loadingClass);
			jQuery.ajax({
				url:_path,
				type:'get',
				success:function(msg){
					_place.html(msg);
					_place.removeClass(_loadingClass);
				},
				error:function(){
					alert("AJAX Error!");
					_place.removeClass(_loadingClass);
				}
			});
		}
		function switchSlide() {
			if(_ajaxLoad && _slides.eq(_currentStep).html() == ''){dynamicLoad();}
			recalcOffsets();
			if(_vertical) _slider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
			else _slider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
			refreshStatus();
			autoSlide();
		}
		if(_ajaxLoad && _slides.eq(_currentStep).html() == ''){dynamicLoad();}
		// autoslide function
		function stopAutoSlide() {
			if(_timer) clearTimeout(_timer);
			_autoRotation = false;
		}
		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();
			});
		}
		recalcOffsets();
		refreshStatus();
		autoSlide();

		// pause buttton
		if(_pauseButton.length) {
			_pauseButton.click(function(){
				if(_this.hasClass(_pauseClass)) {
					_this.removeClass(_pauseClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_this.addClass(_pauseClass);
					stopAutoSlide();
				}
				return false;
			});
		}

		if(_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
	});
}

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

;(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery); 

// grayscale plugin
(function($){
	function grayscale(image, bPlaceImage) {
		var myCanvas=document.createElement("canvas");
		var myCanvasContext=myCanvas.getContext("2d");
		var imgWidth=image.width;
		var imgHeight=image.height;
		myCanvas.width= imgWidth;
		myCanvas.height=imgHeight;
		myCanvasContext.drawImage(image,0,0);
		var imageData=myCanvasContext.getImageData(0,0, imgWidth, imgHeight);
		for (i=0; i<imageData.height; i++) {
			for (j=0; j<imageData.width; j++) {
				var index=(i*4)*imageData.width+(j*4);
				var red=imageData.data[index];
				var green=imageData.data[index+1];
				var blue=imageData.data[index+2];
				var alpha=imageData.data[index+3];
				var average=(red+green+blue)/3;
				imageData.data[index]=average;
				imageData.data[index+1]=average;
				imageData.data[index+2]=average;
				imageData.data[index+3]=alpha;
			}
		}
		myCanvasContext.putImageData(imageData,0,0,0,0, imageData.width, imageData.height);

		if (bPlaceImage) {
			var myDiv=document.createElement("div");
			myDiv.appendChild(myCanvas);
			image.parentNode.appendChild(myCanvas);//, image);
		}
		return myCanvas.toDataURL();
	}

	jQuery.fn.grayscale = function(_options){
		var _options = jQuery.extend({
			temp:1
		},_options);
		return this.each(function(){
			// options
			var image = this;
			var _temp = _options.temp;
			if($.browser.msie && $.browser.version < 9) {
				image.style.filter = 'gray'
			} else {
				image.src = grayscale(image);
			}
		});
	}
})(jQuery);
