jQuery.noConflict();

jQuery(function(){
	new initGallery(jQuery('.gallery'),{
		list: 'ul',
		effect: 'fade',
		autoRotation: 7000,
		duration: 1000
	});
	jQuery('#wrapper').myPopup();
	initValidation();
	 /*clearFormFields({
		 clearInputs: true,
		 clearTextareas: true,
		 passwordFieldText: false,
		 addClassFocus: "focus",
		 filterClass: "default"
	 });*/
	/*if(!jQuery.cookie('lightbox-show')) initLightbox(); */
});

// init loadpage lightbox
function initLightbox(){
	var popup = jQuery('#loadpage');
	var _fader = jQuery('body > div.fader');
	if(!_fader) {
		_fader = jQuery('<div class="fader"></div>');
		jQuery('body').append(_fader);
		_fader.css({
			position: 'absolute',
			top: '0px',
			left: '0px',
			zIndex: 999,
			background: '#471d0a',
			opacity: 0.98
		});
	}
	if(popup.length) init(popup);
	function init(popup){
		var btnClose = popup.find('a.close');
		var w = jQuery('body').width();
		var _w = jQuery('#wrapper').width();
		if (_w > w) w =_w;
		var h = jQuery(window).height();
		var _offset = jQuery(window).scrollTop();
		
		var ret = _offset+(h/2) - popup.outerHeight(true)/2;
		if (ret < 0) ret = 0;
		var te = jQuery('#wrapper').outerHeight(true);
		if (jQuery(window).height() > te) te = jQuery(window).height();
		
		popup.css({top: ret, left: w/2 - popup.outerWidth(true)/2}).hide();
		_fader.css({width: w, height: te}).hide().fadeIn(300, function(){
			popup.fadeIn(300);
			initValidateLogin(popup);
		});
		
		jQuery(window).resize(function(){
			w = jQuery('body').width();
			_w = jQuery('#wrapper').width();
			if (_w > w) w =_w;
			popup.animate({
				left: w/2 - popup.outerWidth(true)/2
			}, {queue:false, duration: 300});
			_fader.css({
				width: w
			});
		});
		function closedPopup(){
			popup.fadeOut(300, function(){
				popup.css({left: '-9999px'}).show();
				jQuery(window).unbind('resize');
				_fader.hide();
			});
			jQuery.cookie('lightbox-show', true, {expires: 30});
		}
		btnClose.click(function(){
			closedPopup();
			return false;
		});
		_fader.click(function(){
			closedPopup();
			return false;
		});
	}
}

function initValidateLogin(popup){
	var _errorClass = 'validation-failed';
	var _regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var _regNum = /^[0-9]+$/;
	
	popup.find('form#form-validate').each(function(){
		var _form = jQuery(this);
		var pass = _form.find('#password');
		var conf = _form.find('#confirmation');
		function checkFields() {
			var _flag = false;
			_form.find('.'+_errorClass).removeClass(_errorClass);

			// fields validation
			_form.find('input.required-email').each(function(){
				if(!_regEmail.test(jQuery(this).val())) addError(jQuery(this));
			});
			_form.find('input.required').each(function(){
				if(!jQuery(this).val().length || jQuery(this).val() == jQuery(this).attr('alt')) addError(jQuery(this));
			});
			
			if(pass.val() != conf.val() || pass.val() == '' || conf.val() == ''){
				addError(pass);
				addError(conf);
			}

			// error class adding
			function addError(_obj) {
				_obj.parent().addClass(_errorClass);
				_flag=true;
			}
			return _flag;
		}
		
		// catch form submit event
		_form.submit(function(){
			if(checkFields()) {
				return false;
			}
			else{
				jQuery.cookie('lightbox-show', true, {expires: 30});
			}
		});
	});
}

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

// main gallery module
function initGallery(context, options){this.init(context, options)}
(function( $ ){
	initGallery.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(){},
		activeSlide: 0,
		
		init: function(context, options){
			for ( var i in options ) this[i] = options[i]; 
			this.holder = jQuery(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.ceil(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, this.list, this.active);
			
			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(jQuery(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(jQuery(e.currentTarget).attr('rel') == 'next') this.active++;
					else if(jQuery(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 );

jQuery.fn.myPopup = function(_options){
	// defaults options	
	var _options = jQuery.extend({
		duration: 700,
		linkOpenName: '.link-popup',
		linkCloseName: 'a.close, a.btn-close',
		divFader: 'fader',
		wrapper: 'body'
	},_options);

	return this.each(function(){
		var _hold = jQuery(this);
		var _speed = _options.duration;
		var _IE = jQuery.browser.msie;
		var links = _hold.find(_options.linkOpenName);
		var _fader = jQuery('<div class="'+_options.divFader+'"></div>');
		var _select = jQuery(_options.wrapper).find('select');
		var popup;
		jQuery('body').append(_fader);
		_fader.css({
			position: 'absolute',
			top: '0px',
			left: '0px',
			zIndex: 999,
			background: '#471d0a',
			opacity: 0.98
		});
		
		function init(_obj){
			popup = jQuery(_obj);
			var btnClose = popup.find(_options.linkCloseName);
			var submitBtn = popup.find('.link-submit');
			
			if (_IE) _select.css({visibility: 'hidden'});
			var w = jQuery('body').width();
			var _w = jQuery(_options.wrapper).width();
			if (_w > w) w =_w;
			var h = jQuery(window).height();
			var _offset = jQuery(window).scrollTop();
			
			var ret = _offset+(h/2) - popup.outerHeight(true)/2;
			if (ret < 0) ret = 0;
			var te = jQuery(_options.wrapper).height();
			if (jQuery(window).height() > te) te = jQuery(window).height();
			
			popup.css({
				top: ret,
				left: w/2 - popup.outerWidth(true)/2
			}).hide();
			_fader.css({
				width: w,
				height: te
			}).fadeIn(300, function(){
				popup.fadeIn(300);
			});
			jQuery(window).resize(function(){
				w = jQuery('body').width();
				_w = jQuery(_options.wrapper).width();
				if (_w > w) w =_w;
				popup.animate({
					left: w/2 - popup.outerWidth(true)/2
				}, {queue:false, duration: 300});
				_fader.css({
					width: w
				});
			});
			function closedPopup(opt1){
				popup.fadeOut(300, function(){
					popup.css({left: '-9999px'}).show();
					if (_IE) _select.css({visibility: 'visible'});
					submitBtn.unbind('click');
					jQuery(window).unbind('resize');
					if (opt1) _fader.hide();
					else {
						if (submitBtn.attr('href')) init(submitBtn.attr('href'));
						else init(submitBtn.attr('title'));
					}
				});
			}
			btnClose.click(function(){
				closedPopup(true);
				return false;
			});
			submitBtn.click(function(){
				closedPopup();
				return false;
			})
			_fader.click(function(){
				closedPopup(true);
				return false;
			});
		}
		links.click(function(){
			if (jQuery(this).attr('href')) init(jQuery(this).attr('href'));
			else init(jQuery(this).attr('title'));
			return false;
		});
	});
}

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

			// fields validation
			_form.find('input.required-email').each(function(){
				if(!_regEmail.test(jQuery(this).val())) addError(jQuery(this));
			});
			_form.find('input.required-num').each(function(){
				if(!_regNum.test(jQuery(this).val())) addError(jQuery(this));
			});
			_form.find('input.required, textarea.required').each(function(){
				if(!jQuery(this).val().length || jQuery(this).val() == jQuery(this).attr('alt')) addError(jQuery(this));
			});                        
                        
                        _form.find('input.required-phone').each(function(){
				if(!_regPhone.test(jQuery(this).val())) addError(jQuery(this));
			});
			
			_form.find('select.required-sel').each(function(){
				if (jQuery(this).val() == jQuery(this).attr('title')) {
					addError(jQuery(this));
				}
			});
                       
                                                _form.find('input.required-chk').each(function(){
				if(!jQuery(this).attr('checked')){
					addError(jQuery(this))
				}
			});

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

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


/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }
    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
