// page init
jQuery(function(){
	clearInputs();
	initSlideshow();
});

// clear inputs
function clearInputs(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: false,
		addClassFocus: "focus",
		filterClass: "default"
	});
};

// slideshow init
function initSlideshow(){
	jQuery('div.gallery').slideshow({
		autoPlay: true, // [true or false]
		effect:'slideX',//fade, slideX, slideY,
		switchTime: 7000, // [1000 - 1sec]
		animSpeed:700 // [1000 - 1sec]
	});
}

// font resize script
fontResize = {
	options: {
		maxStep:1.15,
		defaultFS: 1.2,
		resizeStep: 0.1,
		resizeHolder: 'body',
		cookieName: 'fontResizeCookie'
	},
	init: function() {
		this.domReady(function(){
			this.setDefaultScaling();
			this.addDefaultHandlers();
		});
		return this;
	},
	addDefaultHandlers: function() {
		this.addHandler('increase','inc');
		this.addHandler('decrease','dec');
		this.addHandler('reset');
	},
	setDefaultScaling: function() {
		if(this.options.resizeHolder == 'html') { this.resizeHolder = document.documentElement; }
		else { this.resizeHolder = document.body; }
		var cSize = this.getCookie(this.options.cookieName);
		if(cSize) {
			this.fSize = parseFloat(cSize,10)
		} else {
			this.fSize = this.options.defaultFS;
		}
		this.changeSize();
	},
	changeSize: function(direction) {
		if(typeof direction !== 'undefined') {
			if(direction == 1) {
				this.fSize += this.options.resizeStep;
				if (this.fSize > this.options.defaultFS * this.options.maxStep) this.fSize = this.options.defaultFS * this.options.maxStep;
			} else if(direction == -1) {
				this.fSize -= this.options.resizeStep;
				if (this.fSize < this.options.defaultFS / this.options.maxStep) this.fSize = this.options.defaultFS / this.options.maxStep;
			} else {
				this.fSize = this.options.defaultFS;
			}
		}
		this.resizeHolder.style.fontSize = this.fSize + 'em';
		this.updateCookie(this.fSize.toFixed(2));
		return false;
	},
	addHandler: function(obj, type) {
		if(typeof obj === 'string') { obj = document.getElementById(obj); }
		if(typeof obj !== 'undefined') {
			switch (type) {
				case 'inc':
					obj.onclick = this.bind(this.changeSize,this, [1]);
					break;
				case 'dec':
					obj.onclick = this.bind(this.changeSize,this, [-1]);
					break;
				default:
					obj.onclick = this.bind(this.changeSize,this, [0]);
			}
		}
	},
	domReady: function(fn) {
		var scope = this, calledFlag;
		(function(){
			if (document.addEventListener) {
				document.addEventListener('DOMContentLoaded', function(){
					if(!calledFlag) { calledFlag = true; fn.call(scope); }
				}, false)
			}
			if (!document.readyState || document.readyState.indexOf('in') != -1) {
				setTimeout(arguments.callee, 9);
			} else {
				if(!calledFlag) { calledFlag = true; fn.call(scope); }
			}
		}());
	},
	updateCookie: function(scaleLevel) {
		this.setCookie(this.options.cookieName,scaleLevel);
	},
	getCookie: function(name) {
		var matches = document.cookie.match(new RegExp("(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"));
		return matches ? decodeURIComponent(matches[1]) : undefined;
	},
	setCookie: function(name, value) {
		var exp = new Date();
		exp.setTime(exp.getTime()+(30*24*60*60*1000));
		document.cookie = name + '=' + value + ';' +'expires=' + exp.toGMTString() + ';' +'path=/';
	},
	bind: function(fn, scope, args){
		return function() {
			return fn.apply(scope, args || arguments);
		}
	}
}.init();

//create jQuery plugin
jQuery.fn.slideshow = function(options){return new slideshow(this, options);}

//constructor
function slideshow(obj, options){this.init(obj,options)}

//prototype
slideshow.prototype = {
	init:function(obj, options) {
		this.options = jQuery.extend({
			slides:'div.gallery-holder > ul >li',
			nextBtn:'a.next',
			prevBtn:'a.prev',
			pagingHolder:'div.switcher ul',
			pagingTag:'li',
			createPaging:false,
			autoPlay:false,
			autoHeight:false,
			dynamicLoad:false,
			imgAttr:'alt',
			effect:'slideX',//fade, slideX, slideY,
			startSlide:false,
			switchTime:5000,
			animSpeed:700
		},options);
		
		this.mainHolder = jQuery(obj);
		this.slides = jQuery(this.options.slides,this.mainHolder);		
		this.nextBtn = jQuery(this.options.nextBtn,this.mainHolder);
		this.prevBtn = jQuery(this.options.prevBtn,this.mainHolder);
		this.dynamicLoad = this.options.dynamicLoad;
		this.imgAttr = this.options.imgAttr;
		this.animSpeed = this.options.animSpeed;
		this.switchTime = this.options.switchTime;
		this.effect = this.options.effect;
		this.autoPlay = this.options.autoPlay;
		this.autoHeight = this.options.autoHeight;
		this.previous = -1;
		this.loadingFrame = 1;
		this.busy = false;
		this.direction = 1;
		this.timer;
		this.pagingArray = new Array;
		this.loadArray = new Array;
		this.preloader = new Array;
		this.slidesParent = this.slides.eq(0).parent();
		this.slideW = this.slidesParent.width();
		this.slideH = this.slidesParent.height();
		
		(function(){
			if (this.options.startSlide) this.current = this.options.startSlide
			else {
				var active = -1;
				for(var i = 0; i< this.slides.length-1; i++) {
					if (this.slides.eq(i).hasClass('active')) {
						active = i;
						break;						
					}
				}
				if (active != -1) this.current = active;
				else this.current = 0;
			}
		}).apply(this);
		
		this.initPaging();
		this.setStyles();
		this.bindEvents();
		this.showSlide();
	},
	
	initPaging:function(){
		var obj = this;
		this.pagingHolder = jQuery(this.options.pagingHolder,this.mainHolder);
		
		if (this.options.createPaging) {
			this.pagingHolder.each(function(i){
				var _this = jQuery(this);
				_this.empty();
				var list = jQuery('<ul>');
				for (var i = 0; i < obj.slides.length; i++) jQuery('<li><a href="#">' + (i + 1) + '</a></li>').appendTo(list);
				_this.append(list);
			});
		}
		
		this.paging = jQuery(this.options.pagingTag, this.pagingHolder);
		var ratio = Math.ceil(this.paging.length / this.slides.length);
		for (var i = 0; i < ratio; i++) {
			this.pagingArray.push(this.paging.slice(i*this.slides.length, (i*this.slides.length)+this.slides.length));
		}
	},
	
	setStyles:function(){
		//loader
		if (this.dynamicLoad) {
			this.loader = jQuery('<div class="loader">');
			this.loaderDiv = jQuery('<div>').appendTo(this.loader)
			this.loader.append(this.loaderDiv).appendTo(this.slidesParent);
		}
		// auto height
		if (this.autoHeight) {
			this.slides.eq(this.current).parent().css({height:this.slides.eq(this.current).outerHeight(true)});
		}
		//slides
		if (this.effect == 'fade') {
			this.slides.css({display:'none'});
			this.slides.eq(this.current).css({display:'block'});
		} else if (this.effect == 'slideX'){
			this.slides.css({display: 'none',left:-this.slideW});
			this.slides.eq(this.current).css({display:'block',left:0});
		} else if (this.effect == 'slideY'){
			this.slides.css({display:'none',top:-this.slideH});
			this.slides.eq(this.current).css({display:'block',top:0});
		}
	},
	
	bindEvents:function(){
		var obj = this;
		this.nextBtn.bind('click',function(){
			if (!obj.busy) obj.nextSlide();
			return false;
		});
		
		this.prevBtn.bind('click',function(){
			if (!obj.busy) obj.prevSlide();
			return false;
		});
		
		for (var i = 0; i < this.pagingArray.length; i++) {
			this.pagingArray[i].each(function(i){
				jQuery(this).bind('click',function(){
					if (i != obj.current && !obj.busy) {
						obj.previous = obj.current;
						obj.current = i;
						if (obj.previous > i) obj.direction = -1
						else obj.direction = 1;
						obj.showSlide();
					}
/*					return false;*/
				});
			});
		}
		
		if (this.dynamicLoad) this.loader.bind('click',function(){
			obj.abortLoading();
		});
	},
	
	nextSlide:function(){
		this.previous = this.current;
		if (this.current < this.slides.length-1) this.current++
		else this.current = 0;
		this.direction = 1;
		this.showSlide();
	},
	
	prevSlide:function(){
		this.previous = this.current;
		if (this.current > 0) this.current--
		else this.current = this.slides.length-1;
		this.direction = -1;
		this.showSlide();
	},
	
	showSlide:function(){
		var obj = this;
		var _current = this.current;
		this.busy = true;
		clearTimeout(this.timer);
		
		if (typeof this.loadArray[_current] != 'undefined' || !this.dynamicLoad) {
			//slide already loaded
			this.switchSlide();
		
		} else {
			//slide not loaded
			this.showLoading();
			var images = jQuery(this.dynamicLoad,this.slides.eq(this.current));
			if (images.length) {
				var counter = 0;
				images.each(function(){
					var preloader = new Image;
					obj.preloader.push(preloader);
					var img = jQuery(this);
					preloader.onload = function(){
						counter++;
						checkImages();
					}
					preloader.onerror = function(){
						//ignore errors
						counter++;
						checkImages();
					}
					preloader.src = img.attr(obj.imgAttr);
				});
				
				function checkImages(){
					if (counter == images.length) {
						images.each(function(){
							var img = jQuery(this);
							img.attr('src',img.attr(obj.imgAttr));
						});
						successLoad();
					}
				}
				
			} else successLoad();
		}
		
		function successLoad(){
			obj.loadArray[_current] = 1;
			obj.hideLoading();
			obj.switchSlide();
		}
	},
	
	switchSlide:function(){
		var obj = this;
		
		if (this.previous != -1) {
			var nextSlide = this.slides.eq(this.current);
			var prevSlide = this.slides.eq(this.previous);
			
			if (this.autoHeight) this.slides.eq(this.current).parent().stop().animate({height:this.slides.eq(this.current).outerHeight(true)},this.animSpeed);
			if (this.effect == 'fade') {
				nextSlide.stop().css({display:'block',opacity:0}).animate({opacity:1},this.animSpeed,function(){
					jQuery(this).css({opacity:'auto'});
				});
				prevSlide.stop().animate({opacity:0},this.animSpeed,callback);
			} else if (this.effect == 'slideX'){
				nextSlide.stop().css({display:'block',left:this.slideW*this.direction}).animate({left:0},this.animSpeed);
				prevSlide.stop().animate({left:-this.slideW*this.direction},this.animSpeed+10,callback);
			} else if (this.effect == 'slideY'){
				nextSlide.stop().css({display:'block',top:this.slideH*this.direction}).animate({top:0},this.animSpeed);
				prevSlide.stop().animate({top:-this.slideH*this.direction},this.animSpeed+10,callback);
			}
		} else {
			if (this.autoPlay) this.startAutoPlay();
			this.busy = false;
		}
		
		this.refreshStatus();
		
		function callback(){
			prevSlide.css({display:'none'});
			if (obj.autoPlay) obj.startAutoPlay();
			obj.busy = false;
		}
	},
	
	refreshStatus:function(){
		for (var i = 0; i < this.pagingArray.length;i++) {
			this.pagingArray[i].eq(this.previous).removeClass('active');
			this.pagingArray[i].eq(this.current).addClass('active');
		}
		this.slides.eq(this.previous).removeClass('active');
		this.slides.eq(this.current).addClass('active');
	},
	
	showLoading:function(){
		var obj = this;
		this.loader.show();
		clearInterval(this.loadingTimer);
		obj.loadingTimer = setInterval(animateLoading, 66);
		
		function animateLoading(){
			obj.loaderDiv.css('top', obj.loadingFrame * -40);
			obj.loadingFrame = (obj.loadingFrame + 1) % 12;
		}
	},
	
	hideLoading:function(){
		this.loader.hide();
		clearInterval(this.loadingTimer);
	},
	
	abortLoading:function(){
		this.busy = false;
		this.hideLoading();
		this.current = this.previous;
		for (var i = 0; i < this.preloader.length; i++) {
			this.preloader[i].onload = null;
			this.preloader[i].onerror = null;
		}
		if (this.autoPlay) this.startAutoPlay();
	},
	
	startAutoPlay:function(){
		var obj = this;
		clearTimeout(obj.timer);
		obj.timer = setTimeout(function(){
			obj.nextSlide();
		},obj.switchTime);
	}
};

// 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";
	}
}
