var _autoSlideDuration = 8000;

// page init
var _timer = false;
jQuery(document).ready(function(){
	ajaxLink();
	sliderForContent($('div.loadContent div.inform-holder, div.our-promo'));
	simpleTab($('div.loadContent'));
	simpleTab($('#content'));
	// promo button fade
	_promoLinks = $('div.promo-list li a');
	_promoLinks.each(function(){
		var _link = $(this), _duration = 1000;
		_link.mouseenter(function(){
			if (!_link.parent().hasClass('active'))
				_link.animate({'opacity':0.80},{duration:_duration,queue:false});
		}).mouseleave(function(){
			if (!_link.parent().hasClass('active'))
				_link.animate({'opacity':1},{duration:_duration,queue:false});
		}).bind('clearFx', function(){
			_link.animate({'opacity':1},{duration:_duration,queue:false});
		}).bind('addFx', function(){
			_link.animate({'opacity':0.80},{duration:_duration,queue:false});
		});
	});
	_promoLinks.parent().filter('.active').children().trigger('addFx');
});
jQuery(window).load(function(){
	sampleSmoothHover();
	setHeight();
	mainSlider($('.hslider, .vslider'));
});

function simpleTab(_content) {
	$('.tabset',_content).each(function(i, tabset){
		var _tabLinks = $('a',tabset), _active;
		if (!_tabLinks.parent().hasClass('active')) _tabLinks.eq(0).parent().addClass('active');
		_tabLinks.each(function(j, link){
			var _id = $('.'+link.href.substr(link.href.indexOf('#')+1), _content);
			if ($(link).parent().hasClass('active')){_id.show();_active = _id;}
			else _id.hide();
			
			$(link).click(function(){
				if (!$(this).parent().hasClass('active')) {
					_tabLinks.parent().removeClass('active');
					$(link).parent().addClass('active');
					_active.fadeOut(150, function(){
						_id.fadeIn(250);
						$('div.loadContent div.inform-holder:visible').trigger('resizeInit');
						_active = _id;
					});
				}
				return false;
			})
		});
	});
}

function setHeight(){
	var _holder = $('#promo'),
		_aside = $('div.aside', _holder),
		_inform = $('div.inform',_holder),
		_vs = $('.vslider .holder', _aside);
	
	if (_inform.innerHeight() >= _aside.innerHeight()) {
		_vs.height(_vs.height() + _holder.innerHeight() - _aside.innerHeight());
	} else {
		_vs.height(_vs.height() - (_holder.innerHeight()-_inform.height()));
	}
	
}

function mainSlider(_objs){
	_objs.each(function(){
		var _wraper = $(this),
			_holder = $('> div', _wraper),
			_mover = $('> ul', _holder),
			_slide = $('> li', _mover),
			_length = _slide.length-1;
			
		var _vert = $('a.top', _wraper).length;
			
		var _prev, _next;
			
		if (_vert) {
			_prev  = $('a.top', _wraper);
			_next  = $('a.bottom', _wraper);
		} else {
			_prev  = $('a.prev', _wraper);
			_next  = $('a.next', _wraper);
		}
		
		var _duration = 500,
			_loadDuration = 4000,
			_current = 0,
			_margin = 0,
			_step = [], _stepSum = 0;
			
		_step[0] = 0;
		var _inW, _maxMargin;
		function heightThis(){
			_slide.each(function(i){
				_stepSum += (_vert) ? $(this).outerHeight(true) : $(this).outerWidth(true);
				_step[i+1] = _stepSum;
			});
			_inW = (_vert) ? _holder.innerHeight()-13 : _holder.innerWidth();
			_maxMargin = _step[_slide.length] - _inW;
			_stepSum = 0;
		}
		heightThis();
		setTimeout(heightThis, 100);
		
		
		function resizeWindow(){
			_inW = (_vert) ? _holder.innerHeight()-13 : _holder.innerWidth();
			_maxMargin = _step[_slide.length] - _inW;
			if (_margin + _holder.innerWidth() >  _step[_slide.length]) {
				_margin = _maxMargin;
				_current = _length;
				_mover.animate({'marginLeft': -_margin}, {duration:_duration, queue:false});
			}
		}
		
		$(window).resize(resizeWindow);
		
		_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');
			}
			if (_vert)
				_mover.animate({'marginTop': -_margin}, {duration:_duration, queue:false});
			else
				_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');
			}
			if (_vert)
				_mover.animate({'marginTop': -_margin}, {duration:_duration, queue:false});
			else
				_mover.animate({'marginLeft': -_margin}, {duration:_duration, queue:false});
			return false;
		});
	});
}

function sliderForContent(_objs){
	_objs.each(function() {
		var _obj = $(this);
		var _slideEl = _obj.find('.slide'),
			_parent = _slideEl.parent(),
			_switcher = _obj.find('div.switcher li a, div.switcher2 li a'),
			_prev = _obj.find('div.switcher a.prev, div.switcher2 a.prev'),
			_next = _obj.find('div.switcher a.next, div.switcher2 a.next'),
			_li = _switcher.parent(), _li2 = false,
			_playBtn = _obj.find('a.play');
			
		var _current = 0, _oldSlide,
			_width = _parent.outerWidth(),
			_length = _slideEl.length - 1,
			_duration = 600,
			_easing = 'easeInExpo';
			
			
		if (_switcher.parent().hasClass('active')) _current = _switcher.parent().index(_switcher.parent().filter('.active'));
		_li.removeClass('active').eq(_current).addClass('active');
			
		if (_obj.hasClass('autoslide')) {
			var _cls = '';
			_slideEl.each(function(i,_el){
				_cls += '.'+$(_el).attr('id')+', ';
			});
			if ($(_cls).length) {
				var _switcher2 = $(_cls),
					_li2 = _switcher2.parent();
				_li2.removeClass('active').eq(_current).addClass('active');
				var _mainLink = _li2.parents('div.why').find('a.ajax-link');
				_switcher2.click(function(){
					if (!_mainLink.parent().hasClass('active')) {
						_li2.removeClass('oldActive');
						$(this).parent().addClass('oldActive');
						_mainLink.trigger('click');
					}
					if (_timer && _obj.hasClass('autoslide') && _obj.is(':visible') && !_playBtn.hasClass('pause')) {
						clearTimeout(_timer);
						_timer = setTimeout(nextSlide, _autoSlideDuration);
					}
					if (!$(this).parent().hasClass('active')) {
						_oldSlide = _current;
						_current = _switcher2.index(this);
						slideThis();
					}
					return false;
				});
			}
			_timer = setInterval(nextSlide, _autoSlideDuration);
			_obj.bind('initAutoslide', function(){
				if (_obj.hasClass('autoslide')) {
					_li2.filter('.oldActive').addClass('active');
					_li2.removeClass('oldActive');
					_timer = setTimeout(nextSlide, _autoSlideDuration);
				}
			}).bind('stopAutoslide', function(){
				_li2.removeClass('oldActive').filter('.active').addClass('oldActive');
				_li2.removeClass('active');
				_playBtn.removeClass('pause');
				if (_timer) clearTimeout(_timer);
			}).bind('pause', function(){
				if (_timer) clearTimeout(_timer);
			}).bind('play', function(){
				_timer = setTimeout(nextSlide, _autoSlideDuration);
			});
			_playBtn.click(function(){
				if ($(this).hasClass('pause')) {
					$(this).removeClass('pause');
					_obj.trigger('play');
				} else {
					$(this).addClass('pause');
					_obj.trigger('pause');
				}
				return false;
			});
		}
		
		addClassItem(_li.eq(_current));
		
		setStyle();
		function setStyle(){
			_slideEl.css({'left':'-100%', 'width':'100%'});
			_slideEl.eq(_current).css({'left':0});
		}
		
		$(window).resize(setStyle);
		
		function slideThis(){
			if (_li2) _li2.removeClass('active').eq(_current).addClass('active');
			_li.removeClass('active').eq(_current).addClass('active');
			var _width = _slideEl.parent().outerWidth();
			if (_oldSlide < _current) {
				_slideEl.eq(_oldSlide).animate({left:-_width},{duration:_duration,queue:false,easing:_easing});
				_slideEl.eq(_current).css('left',_width).animate({left:0},{duration:_duration,queue:false,easing:_easing});
			} else {
				_slideEl.eq(_oldSlide).animate({left:_width},{duration:_duration,queue:false,easing:_easing});
				_slideEl.eq(_current).css('left',-_width).animate({left:0},{duration:_duration,queue:false,easing:_easing});
			}
		}
		
		function nextSlide(){
			if (_timer && _obj.hasClass('autoslide') && _obj.is(':visible') && !_playBtn.hasClass('pause')) {
				clearTimeout(_timer);
				_timer = setTimeout(nextSlide, _autoSlideDuration);
			}
			_oldSlide = _current;
			_current++;
			if (_current > _length) _current = 0;
			slideThis();
			return false;
		}
		
		_next.click(nextSlide);
		_prev.click(function(){
			if (_timer && _obj.hasClass('autoslide') && _obj.is(':visible') && !_playBtn.hasClass('pause')) {
				clearTimeout(_timer);
				_timer = setTimeout(nextSlide, _autoSlideDuration);
			}
			_oldSlide = _current;
			_current--;
			if (_current < 0) _current = _length;
			slideThis();
			return false;
		});
		_switcher.click(function(){
			if (_timer && _obj.hasClass('autoslide') && _obj.is(':visible') && !_playBtn.hasClass('pause')) {
				clearTimeout(_timer);
				_timer = setTimeout(nextSlide, _autoSlideDuration);
			}
			if (!$(this).parent().hasClass('active')) {
				_oldSlide = _current;
				_current = _switcher.index(this);
				slideThis();
			}
			return false;
		});
	});
}

function addClassItem(_li){
	_li.removeAttr('class').addClass('active');
	var _prevLi = _li.prevAll();
	var _nextLi = _li.nextAll();
	var i=0, j=0;
	_prevLi.removeAttr('class');
	_nextLi.removeAttr('class');
	_prevLi.each(function(){
		$(this).addClass('item-'+(i++));
	});
	_nextLi.each(function(){
		$(this).addClass('item-'+(j++));
	});
}

function ajaxLink() {
	var _ajaxLinks = $('div.promo-list a, div.vslider ul a, div.hslider ul a, a.ajax-link');
	var _contentHolder = $('#ajax-holder');
	var _load = $('.load').hide();
	var _current = 0;
	if (!_ajaxLinks.parent().filter('.active').length) _contentHolder.empty();
	
	_ajaxLinks.each(function(i){
		var _link = $(this);
		if (_link.parent().hasClass('active')) {
			_contentHolder.children('div').attr('rel',_link.attr('href')).addClass('loadContent');
			_current = i;
			_link.trigger('addFx');
		}
		_link.click(function(){
			if (!_link.parent().hasClass('active')) {
				loadPage(_link);
				_current = i;
			}
			return false;
		});
	});
	
	function loadPage(link){
		_ajaxLinks.parent().removeClass('active');
		link.parent().addClass('active');
		_ajaxLinks.not(link).trigger('clearFx');
		var _url = link.attr('href');
		var _loadTab = _contentHolder.find('[rel="'+_url+'"]');
		
		if (!_loadTab.length) {
			var _sender = $.ajax({url:_url});
			_load.show().css('opacity',0).fadeTo(350, 0.9, function(){
				_sender.success(function(_msg){
					var _content = $(_msg).addClass('loadContent').hide().attr('rel',_url);
					_contentHolder.append(_content);
					var _oldHolder = _contentHolder.find('.loadContent:visible');
					_oldHolder.hide().trigger('stopAutoslide');
					$(_content).show()
					sliderForContent($('div.inform-holder', _content));
					if (_content.hasClass('our-promo'))
						sliderForContent(_content);
					simpleTab(_content);
					_load.fadeOut(200);
				});
			});
		} else {
			var _oldHolder = _contentHolder.find('.loadContent:visible');
			_oldHolder.fadeOut(150, function(){
				_loadTab.css('opacity',1).fadeIn(200);
				_loadTab.trigger('initAutoslide');
			}).trigger('stopAutoslide');
		}
	}
}

function sampleSmoothHover() {
	var delay = 100;
	var animSpeed = 300;
	$('.vslider li a, .hslider li a').each(function(){
		var item = $(this);
		var image = item.find('img');
		var gray = image.clone().appendTo(item).grayscale();
		var t;

		image.addClass('fly').hide();
		if (image.closest('li').hasClass('active')) image.show();
		
		if ($(this).parents('.vslider').length) {
			image.css({
				left:(item.width() - image.width())/2
			});
		} else image.css({left:0});

		item.mouseenter(function(){
			if ($(this).parent().hasClass('active')) return false;
			if(t) clearTimeout(t);
			t = setTimeout(function(){
				image.fadeIn(animSpeed);
			},delay)
		}).mouseleave(function(){
			if ($(this).parent().hasClass('active')) return false;
			if(t) clearTimeout(t);
			t = setTimeout(function(){
				image.fadeOut(animSpeed);
			},delay)
		}).bind('clearFx', function(){
			image.fadeOut(animSpeed);
		}).bind('addFx', function(){
			image.fadeIn(animSpeed);
		});
	});
}

// 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;
			$(image).css('opacity',0.6);
			var _temp = _options.temp;
			if($.browser.msie && $.browser.version < 9) {
				image.style.filter = 'gray'
			} else {
				image.src = grayscale(image);
			}
		});
	}
})(jQuery);

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright В© 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});
