
//init page
$(function(){
	initXmlGallery();
	initNavFix();
	initDropDown();
	initClearInputs();
	initOpenDrop();
})
//init gallery
function initXmlGallery(){
	// gallery options
	var _activeClass = 'active';
	var _autoSlide = true;
	var _switchTime = 7000;
	var _fadeSpeed = 500;
	
	// xml gallery init
	$('div.xml-gallery').each(function(_groupIndex){
		var _holder = $(this);
		var _xmlSource = _holder.attr('title');
		_holder.removeAttr('title');
		var gallery = _holder.find('.gallery-holder');

//throw "XML is: " + _xmlSource;
		
		// ajax XML request
		gallery.empty();
		$.ajax({
			url: _xmlSource,
			dataType: ($.browser.msie) ? 'text' : 'xml',
			success: function(xmlData){
				var _galleryData;
				if (typeof xmlData == 'string') {
					_galleryData = new ActiveXObject('Microsoft.XMLDOM');
					_galleryData.async = false;
					_galleryData.loadXML(xmlData);
				} else {
					_galleryData = xmlData;
				}

				//generate gallery from XML
				$(_galleryData).find('item').each(function(){
					var _item = $(this);
					var _source = $(this).find('source').text();
					var _id = $(this).find('id').text();
					var _title = $(this).find('title').text();
					var _link = $(this).find('link').text();

//throw "Link is: " + _link;

					var _order = $(this).find('order').text();
					var _target = $(this).find('target').text();

					var img = new Image();
					img.src = _source;
					gallery.append('<a href="'+_link+'" target="'+_target+'"><img src="'+_source+'"  alt="'+_title+'" /></a>');
				});

				gallery.each(function(){
					var _this = $(this);
					var _list = $('> a', _this);

					var _a = _list.index(_list.filter('.active:eq(0)'));
					if(_a == -1) _a = 0;
					_list.removeClass('active').css({'opacity': 0, display:'none'}).eq(_a).addClass('active').css('opacity', 1).css({'opacity': 'auto', display:'block'});

					var _t;
					if (_switchTime){
						_t = setTimeout(function(){
							if(_a < _list.length - 1) changeEl(_a + 1);
							else changeEl(0);
						}, _switchTime);
					}
					function changeEl(_ind){
						if(_t) clearTimeout(_t);
						if(_ind != _a){
							_list.eq(_a).removeClass('active').css({display:'block'}).animate({opacity: 0}, {queue:false, duration:_fadeSpeed, complete: function(){
								$(this).hide();
								_list.eq(_ind).addClass('active').css({opacity:0,display:'block'}).animate({opacity: 1}, {queue:false, duration:_fadeSpeed, complete: function(){
									_a = _ind;
									if (_switchTime){
										_t = setTimeout(function(){
											if(_a < _list.length - 1) changeEl(_a + 1);
											else changeEl(0);
										}, _switchTime);
									}
								}});
							}});
						}
					}
					var prevIndex = 0;
					var btnNext = _holder.find('a.next');
					btnNext.click(function(){
						prevIndex = _a;
						_a++;
						if(_a > _list.length-1){
							_a = 0;
						}
						switchSlide();
						return false;
					});
					var btnPrev = _holder.find('a.prev');
					btnPrev.click(function(){
						prevIndex = _a;
						_a--;
						if(_a < 0){
							_a = _list.length-1;
						}
						switchSlide();
						return false;
					});
					function switchSlide(){
						_list.eq(prevIndex).removeClass('active').css({display:'block'}).animate({opacity: 0}, {queue:false, duration:_fadeSpeed, complete: function(){
							$(this).hide();
							_list.eq(_a).addClass('active').css({opacity:0,display:'block'}).animate({opacity: 1}, {queue:false, duration:_fadeSpeed, complete: function(){
							}});
						}});
					}
				});
			},
			error: function() {
				alert('AJAX Error!');
			}
		});
	});
}
// page init
function initNavFix() {
	new touchNav({
		navBlock: 'menu'
	});
}
//init clear inputs
function initClearInputs(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: false,
		addClassFocus: "focus",
		filterClass: "default"
	});
}

// navigation accesibility module
function touchNav(options) {
	this.options = {
		mobileReg: /(ipad|iphone|ipod|android|blackberry|iemobile)/gi,
		hoverClass: 'hover',
		followLink: false,
		menuItems: 'li',
		menuOpener: 'a',
		menuDrop: 'div',
		navBlock: null
	}
	for(var p in options) {
		this.options[p] = options[p];
	}
	this.init();
}
touchNav.prototype = {
	init: function() {
		this.isMobile = (this.options.mobileReg).test(navigator.userAgent);
		if(typeof this.options.navBlock === 'string') {
			this.menu = document.getElementById(this.options.navBlock);
		} else if(typeof this.options.navBlock === 'object') {
			this.menu = this.options.navBlock;
		}
		if(this.menu) {
			this.getElements();
			this.addEvents();
		}
	},
	getElements: function() {
		this.menuItems = this.menu.getElementsByTagName(this.options.menuItems);
	},
	hideActiveDropdown: function() {
		if(this.activeParent) {
			for(var i = 0; i < this.menuItems.length; i++) {
				this.removeClass(this.menuItems[i], this.options.hoverClass);
			}
			this.activeParent = null;
		}
	},
	getOpener: function(obj) {
		for(var i = 0; i < obj.childNodes.length; i++) {
			if(obj.childNodes[i].tagName && obj.childNodes[i].tagName.toLowerCase() == this.options.menuOpener.toLowerCase()) {
				return obj.childNodes[i];
			}
		}
		return false;
	},
	getDrop: function(obj) {
		for(var i = 0; i < obj.childNodes.length; i++) {
			if(obj.childNodes[i].tagName && obj.childNodes[i].tagName.toLowerCase() == this.options.menuDrop.toLowerCase()) {
				return obj.childNodes[i];
			}
		}
		return false;
	},
	addEvents: function() {
		// mobile event handlers
		if(this.isMobile) {
			for(var i = 0; i < this.menuItems.length; i++) {
				this.menuItems[i].touchNav = this;
				if(this.getDrop(this.menuItems[i])) {
					this.addHandler(this.getOpener(this.menuItems[i]), 'click', this.bind(this.clickHandler,this.menuItems[i]));
				}
			}
			this.addHandler(document.body, 'click', this.bind(this.outsideHandler, this));
			this.addHandler(document.body, 'touchstart', this.bind(this.outsideHandler, this));
		}
		// desktop event handlers
		else {
			for(var i = 0; i < this.menuItems.length; i++) {
				this.menuItems[i].touchNav = this;
				this.addHandler(this.menuItems[i], 'mouseover', this.mouseoverHandler);
				this.addHandler(this.menuItems[i], 'mouseout', this.mouseoutHandler);
			}
		}
	},
	outsideHandler: function(e) {
		var childFlag = false;
		if(this.activeParent) {
			this.outsideTarget = e.target || e.currentTarget || e.srcElement;
			while (this.outsideTarget.parentNode) {
				if(this.activeParent == this.outsideTarget) {
					childFlag = true;
					break;
				}
				this.outsideTarget = this.outsideTarget.parentNode;
			}
			if(!childFlag) {
				this.hideActiveDropdown();
			}
		}
	},
	mouseoverHandler: function() {
		this.touchNav.addClass(this, this.touchNav.options.hoverClass);
	},
	mouseoutHandler: function() {
		this.touchNav.removeClass(this, this.touchNav.options.hoverClass);
	},
	clickHandler: function(e) {
		// get current dropdown
		var tNav = this.touchNav;
		tNav.currentElement = e.currentTarget || e.srcElement;
		tNav.currentParent = tNav.currentElement.parentNode;

		// hide previous drop (if exists)
		if(tNav.activeParent && !tNav.isParent(tNav.activeParent, tNav.currentParent) && tNav.currentParent != tNav.activeParent) {
			tNav.hideActiveDropdown();
		}

		// handle current drop
		if(tNav.hasClass(tNav.currentParent, tNav.options.hoverClass)) {
			tNav.removeClass(tNav.currentParent, tNav.options.hoverClass);
			if(tNav.options.followLink) {
				window.location.href = tNav.currentElement.href;
			}
		} else {
			tNav.addClass(tNav.currentParent, tNav.options.hoverClass);
			tNav.activeParent = tNav.currentParent;
			return tNav.preventEvent(e);
		}
	},
	preventEvent: function(e) {
		if(!e) e = window.event;
		if(e.preventDefault) e.preventDefault();
		if(e.stopPropagation) e.stopPropagation();
		e.cancelBubble = true;
		return false;
	},
	isParent: function(parent, child) {
		while(child.parentNode) {
			if(child.parentNode == parent) {
				return true;
			}
			child = child.parentNode;
		}
		return false;
	},
	addHandler: function(object, event, handler) {
		if (typeof object.addEventListener != 'undefined') object.addEventListener(event, this.bind(handler,object), false);
		else if (typeof object.attachEvent != 'undefined') object.attachEvent('on' + event, this.bind(handler,object));
	},
	removeHandler: function(object, event, handler) {
		if (typeof object.removeEventListener != 'undefined') object.removeEventListener(event, handler, false);
		else if (typeof object.detachEvent != 'undefined') object.detachEvent('on' + event, handler);
	},
	hasClass: function(obj,cname) {
		return (obj.className ? obj.className.match(new RegExp('(\\s|^)'+cname+'(\\s|$)')) : false);
	},
	addClass: function(obj,cname) {
		if (!this.hasClass(obj,cname)) obj.className += " "+cname;
	},
	removeClass: function(obj,cname) {
		if (this.hasClass(obj,cname)) obj.className=obj.className.replace(new RegExp('(\\s|^)'+cname+'(\\s|$)'),' ');
	},
	bind: function(func, scope){
		return function() {
			return func.apply(scope, arguments);
		}
	}
}
//init drop state
function initDropDown(){
	var t;
	var nav = document.getElementById("menu");
	if(nav) {
		var lis = nav.getElementsByTagName("li");
		for (var i=0; i<lis.length; i++) {
			if(lis[i].getElementsByTagName("ul").length > 0) {
				lis[i].className += " has-drop-down"
				lis[i].getElementsByTagName("a")[0].className += " has-drop-down-a"
			}
			lis[i].onmouseenter = function()	{
				this.className += " hover";
			}
			lis[i].onmouseleave = function() {
				
				this.className = this.className.replace(" hover", "");
			}
		}
	}
}
//clear inputs
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";
	}
}
//init open drop
function initOpenDrop(){
	var holder = $('ul#menu');
	if(holder.length){
		var items = holder.children();
		items.each(function(){
			var item = $(this);
			var drop = item.find('>ul');
			if(drop.length){
				item.hover(function(){
					drop.css('left',0);
				},function(){
					drop.css('left','-9999px');
				});
			}
		});
	}
}

