jQuery(function(){
	clearInputs();
	initGallery();
	initLightbox();
	initSlideBox();
	initFadePopup();
	initTabs();
});

// init gallery
function initGallery(){
	jQuery('div.carousel').fadeGallery({
		pauseOnHover:true,
		autoRotation:true,
		switchTime:5000 //ms
	});
};

// init lightbox
function initLightbox(){
	jQuery('a.with-popup').each(function(){
		jQuery(this).modalPopup();
	})
};

// init slide box
function initSlideBox(){
	var dur = '200';
	var activeClass = 'active';
	var hold = jQuery('li.style-it');
	var slide = hold.find('div.c').show();
	var w = slide.width();
	if(!hold.hasClass(activeClass)) hold.css({marginLeft:-w});
	hold.hover(function(){
		hold.addClass(activeClass);
		hold.stop().animate({marginLeft:0},{duration:dur,queue:false});
	},function(){
		hold.removeClass(activeClass);
		hold.stop().animate({marginLeft:-w},{duration:dur,queue:false});
	});
};

// init fade popup
function initFadePopup(){
	var dur = '300';
	var activeClass = 'active';
	var hold = jQuery('div.find-togos');
	var popup = hold.find('div.find-popup');
	popup.css({opacity:0}).hide();
	hold.hover(function(){
		hold.addClass(activeClass);
		popup.show().stop().animate({opacity:1},{duration: dur, queue: false,complete:function(){
			popup.css({opacity:''});
		}});
	},function(){
		hold.removeClass(activeClass);
		popup.show().stop().animate({opacity:0},{duration: dur, queue: false,complete:function(){
			popup.hide();
		}})
	});
};

// init tabs
function initTabs() {
	jQuery('ul.tabset').each(function(){
		var _list = jQuery(this);
		var _links = _list.find('a.tab');
		_links.each(function() {
			var _link = jQuery(this);
			var _href = _link.attr('href');
			var _tab = jQuery(_href);
			if(_link.hasClass('active')) _tab.show();
			else _tab.hide();
			_link.click(function(){
				_links.filter('.active').each(function(){
					jQuery(jQuery(this).removeClass('active').attr('href')).hide();
				});
				_link.addClass('active');
				_tab.show();
				return false;
			});
		});
	});
}

// clear inputs
function clearInputs(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: false,
		addClassFocus: "focus",
		filterClass: "default"
	});
}
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.filter) o.filter = "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)) {
				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)) {
				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";
	}
};

// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
	var _options = jQuery.extend({
		slideElements:'div.frame > ul > li',
		pagerGener: true,
		pagerHold: 'div.switcher',
		pagerLinks:'div.switcher a',
		btnNext:'a.link-next',
		btnPrev:'a.link-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:true,
		autoRotation:false,
		autoHeight:true,
		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).fadeOut(_duration);
			_slides.eq(_currentIndex).fadeIn(_duration);
			_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();
	});
};

//lightbox plugin
jQuery.fn.modalPopup = function(options){return new modalPopup(jQuery(this).eq(0),options)}
function modalPopup(link, options) {this.init(link,options)}
modalPopup.prototype = {
	init:function(link,options){
		var el = this;
		//options
		el.options = jQuery.extend({
			fadeSpeed:400,
			closer:'a.btn-close',
			scroll:true,
			wrapper:'body',
			IE:true,
			zIndex:999
		},options);	
		//popup & default css styles
		if (jQuery.browser.msie && el.options.IE) el.popup = jQuery(link.attr('href')).css({visibility:'hidden'})
		else el.popup = jQuery(link.attr('href')).css({opacity:0,visibility:'hidden'});
		if (el.options.zIndex) el.popup.css({zIndex : el.options.zIndex});
		el.closer = jQuery(el.popup.find(el.options.closer));
		el.popup.visible = false;
		modalPopup.prototype.activePopup = false;
		if (!modalPopup.prototype.firstRun) {
			modalPopup.prototype.firstRun = 'done';
			if (jQuery.browser.msie && jQuery.browser.version < 7) modalPopup.prototype.selects = jQuery('select');
			//create fader
			if (!jQuery('#fader').length) jQuery('body').append('<div id="fader"></div>');
			modalPopup.prototype.fader = jQuery('#fader');
			modalPopup.prototype.fader.css({position:'absolute',top:0,left:0,background:'#000',opacity:0,display:'none'});	
			if (el.options.zIndex) modalPopup.prototype.fader.css({zIndex : el.options.zIndex-1});
			modalPopup.prototype.wrapper = jQuery(el.options.wrapper);
			//fader click event
			modalPopup.prototype.fader.click(function(){
				if (modalPopup.prototype.activePopup == false) el.hideFader()
				else modalPopup.prototype.activePopup.hidePopup(function(){el.hideFader()});
				return false;
			});
			//esc event
			jQuery(document).keydown(function (e) {
				if (e.keyCode == 27) {
					if (modalPopup.prototype.activePopup == false) el.hideFader()
					else modalPopup.prototype.activePopup.hidePopup(function(){el.hideFader()});
					return false;
				}
			});
		}
		
		el.wrapper = modalPopup.prototype.wrapper;
		
		if (jQuery.browser.msie && jQuery.browser.version < 7) {
			el.popupSelects = jQuery('select',el.popup);
			modalPopup.prototype.selects = modalPopup.prototype.selects.not(el.popupSelects);
		}
		
		//open event
		link.click(function(){
			el.show();
			return false;
		});
		//close event
		el.closer.click(function(){
			el.close();
			return false;
		});
		//resize event
		jQuery(window).resize(function(){
			if (el.popup.visible) el.positioning(false);
		});
		if (el.options.scroll) {
			jQuery(window).scroll(function(){
				el.positioning(true);
			});
		}
	},
	
	close:function(){
		var el = this;
		el.hidePopup(function(){el.hideFader()});
	},
	
	show:function(){
		var el = this;
		if (modalPopup.prototype.activePopup == el) {return false;}
		if (modalPopup.prototype.activePopup) {
			modalPopup.prototype.activePopup.hidePopup(function(){
				el.showPopup()
				el.positioning(true);
			});
		} else {
			el.showFader(function(){el.showPopup()});
			el.positioning(true);
		} 
	},
	
	showPopup:function(){
		var el = this;
		el.popup.visible = true;
		modalPopup.prototype.activePopup = el;
		if (jQuery.browser.msie && el.options.IE) el.popup.css({visibility:'visible'})
		else el.popup.stop().css({'visibility':'visible'}).animate({opacity:1},el.options.fadeSpeed)
	},
	hidePopup:function(callback){
		var el = this;
		if (jQuery.browser.msie && el.options.IE) {
			el.popup.css({left:'-9999px',top:'-9999px',visibility:'hidden'});
			el.popup.visible = false;
			modalPopup.prototype.activePopup = false;
			if (jQuery.isFunction(callback)) callback();
		} else {
			el.popup.stop().animate({opacity:0},el.options.fadeSpeed,function(){
				el.popup.css({left:'-9999px',top:'-9999px',visibility:'hidden'});
				el.popup.visible = false;
				modalPopup.prototype.activePopup = false;
				if (jQuery.isFunction(callback)) callback();
			});
		}
	},
	showFader:function(callback){
		var el = this;
		el.fader.stop().css({display:'block'}).animate({opacity:0.5},el.options.fadeSpeed,function(){
			if (jQuery.isFunction(callback)) callback();
		});
		if (jQuery.browser.msie && jQuery.browser.version < 7) modalPopup.prototype.selects.css({'visibility': 'hidden'});
	},
	hideFader:function(){
		var el = this;
		el.fader.stop().animate({opacity:0},el.options.fadeSpeed,function(){
			el.fader.css({display:'none'});
			if (jQuery.browser.msie && jQuery.browser.version < 7) modalPopup.prototype.selects.css({'visibility': 'visible'});
		});
	},
	positioning:function(openFlag){
		var el = this;
		//x offset
		var windowW = jQuery(window).width();
		var popupW = el.popup.outerWidth();
		var wrapperW = el.wrapper.outerWidth();
		
		if (windowW < wrapperW) {
			el.popup.css({left:wrapperW/2-popupW/2})
			el.fader.css({width:wrapperW});
		} else {
			 el.popup.css({left:windowW/2-popupW/2});
			 el.fader.css({width:windowW})
		}
		//y offset
		var docH;
		var windowH = jQuery(window).height();
		var wrapperH = el.wrapper.outerHeight();
		if (windowH < wrapperH) docH = wrapperH
		else docH = windowH;
		
		var popupH = el.popup.outerHeight();
		if (openFlag) {
			var popupH = el.popup.outerHeight();
			if (popupH < windowH) el.popup.css({top:windowH/2-popupH/2+jQuery(window).scrollTop()});
			else if (jQuery(window).scrollTop()+popupH > docH){
				el.popup.css({top:docH-popupH});
			} else {
				el.popup.css({top:jQuery(window).scrollTop()});
			}
		}
		el.fader.css({height:docH});
	}
};
