// settings for mail gallery
var autoRotation = 3000;	// in ms (1000ms = 1s), "false" to disable auto rotation
var duration = 2000;			// "fade", in ms (1000ms = 1s)

// DOM ready
$(function(){
	initDrop();
	initGallery();
	clearInputs();
	initValidation();
});

// load content
$(window).load(function(){
	loadImage();
});

// init load images
function loadImage(){
	$('div.img-holder').each(function(){
		var hold = $(this);
		var imgs = hold.find('img');
		imgs.each(function(){
			$(this).attr('src', $(this).attr('alt'));
		});
		
	});
}

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

// init gallery
function initGallery(){
	// home page gallery
	new gallery('.gallery', {
		autoRotation: autoRotation,
		duration: duration,
		list: '.holder > ul',
		switcher: 'ul.switcher > li',
		effect: 'fade'
	});
	// portfolio "Icon Gallery with Tabs"
	$('.tab-content').each(function(){
		var _this = $(this);
		new gallery(_this, {
			list: '.projects-info > .holder > ul',
			switcher: '.projects-box ul.projects > li > a',
			effect: 'fade',
			onStart: function(obj){
				var switcher = obj.switcher.closest('.projects-box');
				var insideGallery = obj.list.children();

				new gallery(switcher, {
					list: 'ul.projects',
					prev: 'a.back',
					next: 'a.next',
					effect: 'slide',
					disableBtn: true,
					disabledChild: true
				});
				
				insideGallery.each(function(){
					new gallery($(this), {
						list: '.images-block ul',
						switcher: '.thumb-block > .thumb-hold > ul.thumb > li > a',
						effect: 'fade',
						onStart: function(obj){
							var hold = obj.switcher.closest('.thumb-block');
							new gallery(hold, {
								list: 'ul.thumb',
								prev: 'a.back',
								next: 'a.next',
								effect: 'slide',
								disableBtn: true,
								disabledChild: true,
								onStart: function(obj){
									initTabs();
								}
							});
						}
					});
				});
			}
		});
	});
	// portfolio "List Gallery"
	$('.menu-block').each(function(){
		var _this = $(this);
		new gallery(_this, {
			list: '.projects-item ul.g1',
			switcher: 'ul.menu > li',
			effect: 'fade',
			onStart: function(obj){
				var insideGallery = obj.list.children();

				insideGallery.each(function(){
					new gallery($(this), {
						list: '.images-block ul',
						switcher: '.thumb-block > .thumb-hold > ul.thumb > li > a',
						effect: 'fade',
						onStart: function(obj){
							var hold = obj.switcher.closest('.thumb-block');
							new gallery(hold, {
								list: 'ul.thumb',
								prev: 'a.back',
								next: 'a.next',
								effect: 'slide',
								disableBtn: true,
								disabledChild: true
							});
						}
					});
				});
			}
		});
	});
}

// slide drop
function initDrop(){
	var wait, _duration = 300;
	$('#nav li').each(function(){
		var li = $(this);
		var drop = li.find('> .drop, > .drop2');
		li.mouseenter(function(){
			$(this).addClass('hover');
			if(drop.length) drop.slideDown(_duration);
		}).mouseleave(function(){
			$(this).removeClass('hover');
			if(drop.length) {
				wait = true;
				drop.slideUp(_duration, function(){wait = false});
			}
		});
	});
}

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

// init validate form
function initValidation(){
	var _errorClass = 'incorrect';
	var _regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var _regPhone = /^[0-9\-\ \()]+$/;
	var _regNum = /^[0-9]+$/;
	
	$('form.validate').each(function(){
		var _form = $(this);
		function checkFields() {
			var _flag = false;
			_form.removeClass('haserror').find('.'+_errorClass).removeClass(_errorClass);

			// fields validation
			_form.find('input.required-email').each(function(){
				if(!_regEmail.test($(this).val())) addError($(this).parent());
			});
			_form.find('input.required-phone').each(function(){
				if(!_regPhone.test($(this).val())) addError($(this).parent());
			});
			_form.find('input.required-num').each(function(){
				if(!_regNum.test($(this).val())) addError($(this).parent());
			});
			_form.find('input.required').each(function(){
				if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this).parent());
			});
			if(_form.find('.check-section').find('input:checkbox:checked').length < 1){
				addError(_form.find('.check-section'));
			}

			// error class adding
			function addError(_obj) {
				_obj.addClass(_errorClass);
				_flag=true;
				_form.addClass('haserror')
			}
			return _flag;
		}

		// catch form submit event
		_form.submit(function(){
			if(checkFields()) {
				return false;
			}
		});
	});
}

// main gallery module
function gallery(context, options){this.init(context, options)}
(function( $ ){
	gallery.prototype = {
		autoRotation: false,
		duration: 700,
		disableBtn: false,
		disabledChild: false,
		list: 'ul.g1',
		switcher: false,
		prev: false,
		next: false,
		effect: false,
		event:'click',
		onStart: function(){},
		beforeChange: function(){},
		onChange: function(){},
		switcherClick: function(){},
		
		init: function(context, options){
			for ( var i in options ) this[i] = options[i]; 
			this.holder = $(context);
			if(this.holder == undefined) return;
			
			this.list = this.holder.find(this.list);
			this.animation = true, this.active = 0;
			this.prevActive = this.active, this.wait;
			this.count = this.list.children().length,
			this.w = this.list.children().eq(0).outerWidth(true);
			this.holdW = this.list.parent().width();
			this.visEl = Math.floor(this.holdW/this.w);
			
			if(this.count <= this.visEl) this.animation = false;
			
			if(this.effect == 'fade') this.list.children().css('opacity', 0).eq(this.active).css('opacity', 1).addClass('active');
			else if(this.effect == 'slide') this.list.css('marginLeft', -this.w*this.active);

			this.initControls(this);
			
			this.toggleState.listItem(this);
			if(this.switcher) this.toggleState.switchItem(this);
			
			this.onStart(this);
			
			if(this.autoRotation && this.animation) this.runTimer(this);
		},
		initControls: function(_this){
			if(_this.prev && _this.next){
				_this.prev = _this.holder.find(_this.prev).attr('rel', 'prev').click(function(e){
					_this.beforeChange(_this, e);
					_this.refreshState(e);
					return false;
				});
				_this.next = _this.holder.find(_this.next).attr('rel', 'next').click(function(e){
					_this.beforeChange(_this, e);
					_this.refreshState(e);
					return false;
				});
			}
			if(_this.switcher){
				_this.switcher = _this.holder.find(_this.switcher);
				_this.toggleState.switchItem(_this);
				_this.switcher.bind(_this.event, function(){
					var ind = _this.switcher.index($(this));
					_this.switcherClick(_this);
					_this.refreshState(ind);
					return false;
				});
			}
			if(this.disableBtn) this.disabledConrtol();
		},
		toggleState:{
			listItem: function(_this){
				_this.list.children().eq(_this.prevActive).removeClass('active');
				_this.list.children().eq(_this.active).addClass('active');
			},
			switchItem: function(_this){
				_this.switcher.eq(_this.prevActive).removeClass('active');
				_this.switcher.eq(_this.active).addClass('active');
			}
		},
		disabledConrtol: function(){
			if(this.active == 0) {
				if(this.disabledChild){
					this.prev.attr('rel', 'stop').children().addClass('disabled');
					this.next.attr('rel', 'next').children().removeClass('disabled');
				}
				else{
					this.prev.attr('rel', 'stop').parent().addClass('disabled');
					this.next.attr('rel', 'next').parent().removeClass('disabled');
				}
			}
			else if(this.active == this.count-1 || (this.visEl >= 2 && this.active + this.visEl == this.count)) {
				if(this.disabledChild){
					this.prev.attr('rel', 'prev').children().removeClass('disabled');
					this.next.attr('rel', 'stop').children().addClass('disabled');
				}
				else{
					this.prev.attr('rel', 'prev').parent().removeClass('disabled');
					this.next.attr('rel', 'stop').parent().addClass('disabled');
				}
				this.autoRotation = false;
			}
			else {
				if(this.disabledChild){
					this.prev.attr('rel', 'prev').children().removeClass('disabled');
					this.next.attr('rel', 'next').children().removeClass('disabled');
				}
				else{
					this.prev.attr('rel', 'prev').parent().removeClass('disabled');
					this.next.attr('rel', 'next').parent().removeClass('disabled');
				}
			}
		},
		runTimer: function(_this){
			_this.beforeChange(_this);
			this.wait = setTimeout(function(){_this.refreshState('next')}, this.autoRotation)
		},
		stop: function(){
			if(this.wait) clearTimeout(this.wait)
		},
		play: function(){
			if(this.wait) clearTimeout(this.wait);
			if(this.autoRotation) this.runTimer(this);
		},
		changeSlide:{
			fade:function(_this){
				_this.list.children().eq(_this.prevActive).animate({opacity:0}, {queue:false, duration:_this.duration});
				_this.list.children().eq(_this.active).animate({opacity:1}, {queue:false, duration:_this.duration, complete:function(){
					_this.play();
					_this.onChange(_this, _this.list, _this.active);
				}});
			},
			slide:function(_this){
				if(_this.active + _this.visEl > _this.count) _this.active = 0;
				_this.list.animate({marginLeft:-_this.w*_this.active}, {queue:false, duration:_this.duration, complete:function(){
					_this.play();
					_this.onChange(_this, _this.list, _this.active);
				}});
			}
		},
		refreshState: function(e){
			if(this.animation){
				this.prevActive = this.active;
				if(typeof e == 'string' && e == 'next') this.active++;
				else if(typeof e == 'number') this.active=e;
				else{
					if($(e.currentTarget).attr('rel') == 'next') this.active++;
					else if($(e.currentTarget).attr('rel') == 'prev') this.active--;
				}
				if(this.wait) clearTimeout(this.wait);
				if(this.active == this.count) this.active = 0;
				else if(this.active == -1) this.active=this.count - 1;
				
				this.toggleState.listItem(this);
				if(this.switcher) this.toggleState.switchItem(this);
				
				if(this.disableBtn) this.disabledConrtol();
				
				if(this.effect == 'fade') this.changeSlide.fade(this);
				else if(this.effect == 'slide') this.changeSlide.slide(this);
			}
		}	
	}
})( jQuery );

//init clear form fields
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";
	}
}
