jQuery.noConflict();
// init page
jQuery(function() {
	initNavFix();
	hideFormText();
	initGallery();
	initDrop();
});

jQuery(window).load(function() {
	initAutoScalingNav({
		menuId: "nav", 
		tag: "strong", 
		spacing: 3, 
		sideClasses: true
	});
})

function initAutoScalingNav(o) {
	if (!o.menuId) o.menuId = "nav";
	if (!o.tag) o.tag = "a";
	if (!o.spacing) o.spacing = 0;
	if (!o.constant) o.constant = 0;
	if (!o.minPaddings) o.minPaddings = 0;
	if (!o.liHovering) o.liHovering = false;
	if (!o.sideClasses) o.sideClasses = false;
	if (!o.equalLinks) o.equalLinks = false;
	if (!o.flexible) o.flexible = false;
	var nav = document.getElementById(o.menuId);
	if(nav) {
		nav.className += " scaling-active";
		var lis = nav.getElementsByTagName("li");
		var asFl = [];
		var lisFl = [];
		var width = 0;
		for (var i=0, j=0; i<lis.length; i++) {
			if(lis[i].parentNode == nav) {
				var t = lis[i].getElementsByTagName(o.tag).item(0);
				asFl.push(t);
				asFl[j++].width = t.offsetWidth;
				lisFl.push(lis[i]);
				if(width < t.offsetWidth) width = t.offsetWidth;
			}
			if(o.liHovering) {
				lis[i].onmouseover = function() {
					this.className += " hover";
				}
				lis[i].onmouseout = function() {
					this.className = this.className.replace("hover", "");
				}
			}
		}
		var menuWidth = nav.clientWidth - asFl.length*o.spacing - o.constant;
		if(o.equalLinks && width * asFl.length < menuWidth) {
			for (var i=0; i<asFl.length; i++) {
				asFl[i].width = width;
			}
		}
		width = getItemsWidth(asFl);
		if(width < menuWidth) {
			var version = navigator.userAgent.toLowerCase();
			for (var i=0; getItemsWidth(asFl) < menuWidth; i++) {
				asFl[i].width++;
				if(!o.flexible) {
					asFl[i].style.width = asFl[i].width + "px";
				}
				if(i >= asFl.length-1) i=-1;
			}
			if(o.flexible) {
				for (var i=0; i<asFl.length; i++) {
					width = (asFl[i].width - o.spacing - o.constant/asFl.length)/menuWidth*100;
					if(i != asFl.length-1) {
						lisFl[i].style.width = width + "%";
					}
					else {
						if(navigator.appName.indexOf("Microsoft Internet Explorer") == -1 || version.indexOf("msie 8") != -1 || version.indexOf("msie 9") != -1)
							lisFl[i].style.width = width + "%";
					}
				}
			}
		}
		else if(o.minPaddings > 0) {
			for (var i=0; i<asFl.length; i++) {
				asFl[i].style.paddingLeft = o.minPaddings + "px";
				asFl[i].style.paddingRight = o.minPaddings + "px";
			}
		}
		if(o.sideClasses) {
			lisFl[0].className += " first-child";
			lisFl[0].getElementsByTagName(o.tag).item(0).className += " first-child-a";
			lisFl[lisFl.length-1].className += " last-child";
			lisFl[lisFl.length-1].getElementsByTagName(o.tag).item(0).className += " last-child-a";
		}
		nav.className += " scaling-ready";
	}
	function getItemsWidth(a) {
		var w = 0;
		for(var q=0; q<a.length; q++) {
			w += a[q].width;
		}
		return w;
	}
}

function initNavFix() {
	new touchNav({
		navBlock: 'nav' // String id or DOM-object
	});
}

// navigation accesibility module
function touchNav(opt) {
	this.options = {
		hoverClass: 'hover',
		menuItems: 'li',
		menuOpener: 'a',
		menuDrop: 'ul',
		navBlock: null
	}
	for(var p in opt) {
		if(opt.hasOwnProperty(p)) {
			this.options[p] = opt[p];
		}
	}
	this.init();
}
touchNav.prototype = {
	init: function() {
		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);
	},
	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() {
		// attach event handlers
		this.preventCurrentClick = true;
		for(var i = 0; i < this.menuItems.length; i++) {
			this.bind(function(i){
				var item = this.menuItems[i];
				// only for touch input devices
				if(this.isTouchDevice && this.getDrop(item)) {
					this.addHandler(this.getOpener(item), 'click', this.bind(this.clickHandler));
					this.addHandler(this.getOpener(item), 'touchstart', this.bind(function(){
						this.currentItem = item;
						this.currentLink = this.getOpener(item);
						this.pressHandler.apply(this, arguments);
					}));
				}
				// for desktop computers and touch devices
				this.addHandler(item, 'mouseover', this.bind(function(){
					this.currentItem = item;
					this.mouseoverHandler();
				}));
				this.addHandler(item, 'mouseout', this.bind(function(){
					this.currentItem = item;
					this.mouseoutHandler();
				}));
			})(i);
		}
		// hide dropdowns when clicking outside navigation
		if(this.isTouchDevice) {
			this.addHandler(document, 'touchstart', this.bind(this.clickOutsideHandler));
		}
	},
	mouseoverHandler: function() {
		this.addClass(this.currentItem, this.options.hoverClass);
	},
	mouseoutHandler: function() {
		this.removeClass(this.currentItem, this.options.hoverClass);
	},
	hideActiveDropdown: function() {
		for(var i = 0; i < this.menuItems.length; i++) {
			this.removeClass(this.menuItems[i], this.options.hoverClass);
		}
		this.activeParent = null;
	},
	pressHandler: function(e) {
		// hide previous drop (if active)
		if(this.currentItem != this.activeParent && !this.isParent(this.activeParent, this.currentLink)) {
			this.hideActiveDropdown();
		}
		// handle current drop
		this.activeParent = this.currentItem;
		if(this.hasClass(this.currentItem, this.options.hoverClass)) {
			this.preventCurrentClick = false;
		} else {
			this.preventEvent(e);
			this.preventCurrentClick = true;
			this.addClass(this.currentItem, this.options.hoverClass);
		}
	},
	clickHandler: function(e) {
		// prevent first click on link
		if(this.preventCurrentClick) {
			this.preventEvent(e);
		}
	},
	clickOutsideHandler: function(event) {
		var e = event.changedTouches ? event.changedTouches[0] : event;
		if(this.activeParent && !this.isParent(this.menu, e.target)) {
			this.hideActiveDropdown();
		}
	},
	preventEvent: function(e) {
		if(!e) e = window.event;
		if(e.preventDefault) e.preventDefault();
		e.returnValue = false;
	},
	isParent: function(parent, child) {
		while(child.parentNode) {
			if(child.parentNode == parent) {
				return true;
			}
			child = child.parentNode;
		}
		return false;
	},
	isTouchDevice: (function() {
		try {
			document.createEvent("TouchEvent");
			return true;
		} catch (e) {
			return false;
		}
	}()),
	addHandler: function(object, event, handler) {
		if (object.addEventListener) object.addEventListener(event, handler, false);
		else if (object.attachEvent) object.attachEvent('on' + event, handler);
	},
	removeHandler: function(object, event, handler) {
		if (object.removeEventListener) object.removeEventListener(event, handler, false);
		else if (object.detachEvent) 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){
		var newScope = scope || this;
		return function() {
			return func.apply(newScope, arguments);
		}
	}
}

//clear inputs
function hideFormText() {
	var _inputs = document.getElementsByTagName('input');
	var _txt = document.getElementsByTagName('textarea');
	var _value = [];
	
	if (_inputs) {
		for(var i=0; i<_inputs.length; i++) {
			if (_inputs[i].type == 'text' || _inputs[i].type == 'password') {
				
				_inputs[i].index = i;
				_value[i] = _inputs[i].value;
				
				_inputs[i].onfocus = function(){
					if (this.value == _value[this.index])
						this.value = '';
				}
				_inputs[i].onblur = function(){
					if (this.value == '')
						this.value = _value[this.index];
				}
			}
		}
	}
	if (_txt) {
		for(var i=0; i<_txt.length; i++) {
			_txt[i].index = i;
			_value['txt'+i] = _txt[i].value;
			
			_txt[i].onfocus = function(){
				if (this.value == _value['txt'+this.index])
					this.value = '';
			}
			_txt[i].onblur = function(){
				if (this.value == '')
					this.value = _value['txt'+this.index];
			}
		}
	}
}

// initGallery
function initGallery() {
	jQuery('.promo-gallery').each(function(){
		var holder = jQuery(this);
		var frame = jQuery('> .frame', this);
		var activeState = 'active';
		var swichTime = 7000;
		var animSpeed = 700;
		var btnPrev = holder.find('a.link-prev');
		var btnNext = holder.find('a.link-next');
		var captions = jQuery('.captions .caption', holder);
		var slides = jQuery('.images .image', holder);
		var length = slides.length;
		var currentItem = 0;
		var prevItem = currentItem;
		var timer;
		var flagAnimation = false;
		var autoRotation = true;
		var direction = 0;
		var step = slides.eq(currentItem).outerWidth();
		var over = false;
		
		slides.css({
			position: 'absolute',
			top: 0,
			left: step
		});
		captions.hide();
		slides.eq(currentItem).css({
			left: 0
		});
		captions.eq(currentItem).show();
		
		btnNext.click(function(){
			nextSlide();
			return false;
		});
		
		btnPrev.click(function(){
			prevSlide();
			return false;
		});
		
		function prevSlide() {
			if(!flagAnimation) {
				prevItem = currentItem;
				if(currentItem > 0) currentItem--;
				else currentItem = length - 1;
				direction = 1;
				switchItem();
			}
		}
		
		function nextSlide(){
			if(!flagAnimation) {
				prevItem = currentItem;
				if(currentItem < length - 1) currentItem++;
				else currentItem = 0;
				direction = -1;
				switchItem();
			}
		}
		
		function switchItem(){
			flagAnimation = true;
			var _left = direction ? -step : step;
			var prevLeft = direction ? step : -step;
			slides.eq(prevItem).removeClass(activeState).animate({left: direction*step}, {duration: animSpeed});
			captions.eq(prevItem).fadeOut(animSpeed);
			slides.eq(currentItem).addClass(activeState).css({left: -direction*step}).animate({left: 0}, {duration: animSpeed,complete: function(){
				flagAnimation = false;
			}});
			captions.eq(currentItem).fadeIn(animSpeed);
			autorotation();
		}
		
		function autorotation() {
			if(!autoRotation || over) return;
			if(timer) clearTimeout(timer);
			timer = setTimeout(nextSlide, swichTime);
		}
		
		autorotation();
		
		frame.mouseenter(function() {
			over = true;
			if(timer) clearTimeout(timer);
		}).mouseleave(function() {
			over = false;
			autorotation();
		});
	});
}

// initDrop
function initDrop() {
	jQuery('#nav li:has(>ul)').each(function() {
		var li = jQuery(this),
			drop = jQuery('> ul', this);
		
		drop.css({
			display: 'none',
			opacity: 0
		});
		
		li.mouseenter(function() {
			drop.stop().css({
				display: 'block'
			}).animate({
				opacity: 1
			}, {
				queue: false
			});
		}).mouseleave(function() {
			drop.animate({
				opacity: 0
			}, {
				queue: false,
				complete: function() {
					drop.hide();
				}
			});
		});
	});
}

// mobile browsers detect
browserPlatform = {
	platforms: [
		{ uaString:['symbian','midp'], cssFile:'symbian.css' }, // Symbian phones
		{ uaString:['opera','mobi'], cssFile:'opera.css' }, // Opera Mobile
		{ uaString:['msie','ppc'], cssFile:'ieppc.css' }, // IE Mobile <6
		{ uaString:'iemobile', cssFile:'iemobile.css' }, // IE Mobile 6+
		{ uaString:'webos', cssFile:'webos.css' }, // Palm WebOS
		{ uaString:'Android', cssFile:'android.css' }, // Android
		{ uaString:['BlackBerry','/6.0','mobi'], cssFile:'blackberry6.css' },	// Blackberry 6
		{ uaString:['BlackBerry','/7.0','mobi'], cssFile:'blackberry7.css' },	// Blackberry 7+
		{ uaString:'ipad', cssFile:'ipad.css', miscHead:'<meta name="viewport" content="width=device-width" />' }, // iPad
		{ uaString:['safari','mobi'], cssFile:'safari.css', miscHead:'<meta name="viewport" content="width=device-width" />' } // iPhone and other webkit browsers
	],
	options: {
		cssPath:'css/',
		mobileCSS:'allmobile.css'
	},
	init:function(){
		this.checkMobile();
		this.parsePlatforms();
		return this;
	},
	checkMobile: function() {
		if(this.uaMatch('mobi') || this.uaMatch('midp') || this.uaMatch('ppc') || this.uaMatch('webos')) {
			this.attachStyles({cssFile:this.options.mobileCSS});
		}
	},
	parsePlatforms: function() {
		for(var i = 0; i < this.platforms.length; i++) {
			if(typeof this.platforms[i].uaString === 'string') {
				if(this.uaMatch(this.platforms[i].uaString)) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			} else {
				for(var j = 0, allMatch = true; j < this.platforms[i].uaString.length; j++) {
					if(!this.uaMatch(this.platforms[i].uaString[j])) {
						allMatch = false;
					}
				}
				if(allMatch) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			}
		}
	},
	attachStyles: function(platform) {
		var head = document.getElementsByTagName('head')[0], fragment;
		var cssText = '<link rel="stylesheet" href="' + this.options.cssPath + platform.cssFile + '" type="text/css"/>';
		var miscText = platform.miscHead;
		if(platform.cssFile) {
			if(document.body) {
				fragment = document.createElement('div');
				fragment.innerHTML = cssText;
				head.appendChild(fragment.childNodes[0]);
			} else {
				document.write(cssText);
			}
		}
		if(platform.miscHead) {
			if(document.body) {
				fragment = document.createElement('div');
				fragment.innerHTML = miscText;
				head.appendChild(fragment.childNodes[0]);
			} else {
				document.write(miscText);
			}
		}
	},
	uaMatch:function(str) {
		if(!this.ua) {
			this.ua = navigator.userAgent.toLowerCase();
		}
		return this.ua.indexOf(str.toLowerCase()) != -1;
	}
}.init();
