$(function(){
	initDropDown();
	initNavFix();
	initRandomImage();
});

// random image init
function initRandomImage(){
	var holder = document.getElementById('random-image-list');
	var items = holder.getElementsByTagName('li');
	var index = Math.round(Math.random() * (items.length-1));
	holder.innerHTML = items[index].innerHTML;
}

// page init
function initNavFix() {
	if(!jQuery.browser.msie) new touchNav({navBlock: 'nav'});
}

// dropdown init
function initDropDown(){
	var _duration = 200;
	$('#nav li').each(function(){
		var _this = $(this);
		var drop = _this.find('ul');
		var box = $('<div>');

		if(_this.parent().is('#nav')){
			box.css({
				width: _this.find('> ul').width()+1,
				height: 0,
				'position': 'absolute',
				left:0,
				top:_this.height(),
				'overflow': 'hidden'
			});
			_this.data('drop', _this.find('> ul'));
			if(_this.find('> ul').length) {
				if(_this.find('> ul').offset().left+_this.find('> ul').width() > $('#nav').offset().left+$('#nav').width()){
					var l = ($('#nav').offset().left+$('#nav').width())-(_this.find('> ul').offset().left+_this.find('> ul').width());
					box.css('left', l-1);
				}
			}
			_this.find('> ul').data('h', _this.find('> ul').height()).css('top', -_this.find('> ul').data('h'))
			_this.find('> ul').data('first', true).wrap(box);
		}
		else{
			box.css({
				width: 0,
				height: _this.find('> ul').height(),
				'position': 'absolute',
				left:_this.width()+1,
				top:0,
				'overflow': 'hidden'
			});
			_this.data('drop', _this.find('> ul'));
			if(_this.find('> ul').length) {
				if(_this.find('> ul').offset().left+_this.find('> ul').width() > $('#nav').offset().left+$('#nav').width()){
					_this.data('right', true);
					var l = ($('#nav').offset().left+$('#nav').width())-(_this.find('> ul').offset().left+_this.find('> ul').width());
					box.css({
						left: 'auto',
						right: _this.find('> ul').width()-1
					});
					_this.find('> ul').data('w', _this.find('> ul').width()).css({
						left:'auto',
						right: -1
					});
				}
			}
			if(!_this.data('right')) _this.find('> ul').data('w', _this.find('> ul').width()).css('left', -_this.find('> ul').data('w'))
			_this.find('> ul').wrap(box);
		}
		if(drop.length) _this.addClass('has-drop-down').find('> a').addClass('has-drop-down-a');
		
		
		
		_this.mouseenter(function(){
			$(this).addClass('hover');
			if(drop.data('first')){
				_this.data('drop').parent().animate({height: _this.data('drop').data('h')}, {queue:false, duration: _duration});
				_this.data('drop').animate({top:0}, {queue:false, duration: _duration});
				_this.data('drop').find('li > div').css('overflow', 'hidden');
			}
			else{
				_this.data('drop').parents('li').find('> div').css('overflow', 'visible');
				_this.data('drop').parents('li').eq(0).find('> div').css('overflow', 'hidden');
				if(_this.data('right')){
					_this.data('drop').animate({right:0}, {queue:false, duration: _duration});
				}
				else{
					_this.data('drop').animate({left:0}, {queue:false, duration: _duration});
				}
				_this.data('drop').parent().animate({width: _this.data('drop').data('w')+1}, {queue:false, duration: _duration});
			}
		}).mouseleave(function(){
			$(this).removeClass('hover');
			if(drop.data('first')){
				_this.data('drop').parent().animate({height: 0}, {queue:false, duration: _duration, complete: function(){
					_this.data('drop').parents('li').find('> div').css('overflow', 'hidden');
				}});
				_this.data('drop').animate({top:-_this.data('drop').data('h')}, {queue:false, duration: _duration});
			}
			else{
				_this.data('drop').parent().css('overflow', 'hidden');
				_this.data('drop').parent().animate({width: 0}, {queue:false, duration: _duration});
				if(_this.data('right')){
					_this.data('drop').animate({right:-_this.data('drop').data('w')}, {queue:false, duration: _duration});
				}
				else{
					_this.data('drop').animate({left:-_this.data('drop').data('w')}, {queue:false, duration: _duration});
				}
			}
		});
		
	});
}

// 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);
		}
	}
}

// mobile browsers detect
browserPlatform = {
	platforms: [
		{ uaString:['BlackBerry','midp'], cssFile:'blackberry.css' }, // Blackberry <5
		{ 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.0.css' },	// Blackberry 6+
		{ 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();

/* IE6 Hover fix module */
var ieHover = {
	lazyMode: true,
	init: function(){
		this.setDefaults();
		return this;
	},
	setDefaults: function() {
		this.fixActive = /MSIE 6/.test(navigator.userAgent);
		if(this.fixActive) {
			this.hoverEvents = []; this.hoverQueue = [];
			this.activators = {
				onhover:{on:'onmouseenter', off:'onmouseleave'},
				onactive:{on:'onmousedown', off:'onmouseup'}
			}
			window.attachEvent('onload', this.bind(this.domReady,this));
			window.attachEvent('onunload', this.bind(this.unhookHoverEvents,this));
		}
	},
	domReady: function() {
		this.pageReady = true;
		if(this.lazyMode) {
			this.processStylesheets();
		}
		if(this.hoverQueue.length) {
			for(var i = 0; i < this.hoverQueue.length; i++) {
				this.doFix(this.hoverQueue[i].s,this.hoverQueue[i].c);
			}
		}
	},
	processStylesheets: function() {
		var sheets = document.styleSheets, len = sheets.length;
		for(var i = 0; i < len; i++) { this.parseStylesheet(sheets[i]); }
	},
	parseStylesheet: function(sheet) {
		if(sheet.imports) {
			try {
				var imports = sheet.imports, l = imports.length;
				for(var i=0; i<l; i++) this.parseStylesheet(sheet.imports[i]);
			} catch(e){}
		}
		try {
			var rules = (this.currentSheet = sheet).rules, l = rules.length;
			for(var j=0; j<l; j++) this.parseCSSRule(rules[j]);
		} catch(e){}
	},
	parseCSSRule: function(rule) {
		var select = rule.selectorText, style = rule.style.cssText;
		if(!/(^|\s)(([^a]([^ ]+)?)|(a([^#.][^ ]+)+)):(hover|active)/i.test(select) || !style) return;
		var pseudo = select.replace(/[^:]+:([a-z-]+).*/i, 'on$1');
		var newSelect = select.replace(/(\.([a-z0-9_-]+):[a-z]+)|(:[a-z]+)/gi, '.$2' + pseudo);
		var className = (/\.([a-z0-9_-]*on(hover|active))/i).exec(newSelect)[1];
		var affected = select.replace(/:(hover|active).*$/, '');
		var elements = this.parseSelector(affected);
		if(!elements.length) return;
		this.currentSheet.addRule(newSelect, style);
		for(var i=0; i < elements.length; i++) {
			this.addHoverElement(elements[i], className, this.activators[pseudo]);
		}
	},
	fix: function(selector, className) {
		if(this.fixActive) {
			if(this.pageReady) {
				this.doFix(selector,className)
			} else {
				this.hoverQueue.push({s:selector,c:className});
			}
		}
	},
	doFix: function(selector, className) {
		if(this.fixActive && typeof selector === 'string') {
			var elements = this.parseSelector(selector);
			for(var i=0; i < elements.length; i++) {
				this.addHoverElement(elements[i], className || 'hover', this.activators['onhover']);
			}
		}
	},
	addHoverElement: function(node, className, events) {
		if(!node.hovers) node.hovers = {};
		if(node.hovers[className]) return;
		node.hovers[className] = true;
		this.hookHoverEvent(node, events.on, function() { node.className += ' ' + className; });
		this.hookHoverEvent(node, events.off, function() { node.className = node.className.replace(new RegExp('\\s+'+className, 'g'),''); });
	},
	hookHoverEvent: function(node, type, handler) {
		node.attachEvent(type, handler);
		this.hoverEvents[this.hoverEvents.length] = {
			node:node, type:type, handler:handler
		};
	},
	unhookHoverEvents: function() {
		for(var e,i=0; i < this.hoverEvents.length; i++) {
			e = this.hoverEvents[i];
			e.node.detachEvent(e.type, e.handler);
		}
	},
	parseSelector: (function () {
		var g = /^([^#.>`]*)(#|\.|\>|\`)(.+)$/;
		function parseSelector(a, b) {
			var c = a.split(/\s*\,\s*/);
			var d = [];
			for (var i = 0; i < c.length; i++) {
				d = d.concat(doParse(c[i], b))
			};
			return d
		};
		function doParse(a, b, c) {
			a = a.replace(" ", "`");
			var d = a.match(g);
			var e, listNodes, listSubNodes, subselector, i, limit;
			var f = [];
			if (d == null) {
				d = [a, a]
			};
			if (d[1] == "") {
				d[1] = "*"
			};
			if (c == null) {
				c = "`"
			};
			if (b == null) {
				b = document
			};
			switch (d[2]) {
			case "#":
				subselector = d[3].match(g);
				if (subselector == null) {
					subselector = [null, d[3]]
				};
				e = document.getElementById(subselector[1]);
				if (e == null || (d[1] != "*" && !matchNodeNames(e, d[1]))) {
					return f
				};
				if (subselector.length == 2) {
					f.push(e);
					return f
				};
				return doParse(subselector[3], e, subselector[2]);
			case ".":
				if (c != ">") {
					listNodes = getElementsByTagName(b, d[1])
				} else {
					listNodes = b.childNodes
				};
				for (i = 0, limit = listNodes.length; i < limit; i++) {
					e = listNodes[i];
					if (e.nodeType != 1) {
						continue
					};
					subselector = d[3].match(g);
					if (subselector != null) {
						if (e.className == null || e.className.match("(\\s|^)" + subselector[1] + "(\\s|$)") == null) {
							continue
						};
						listSubNodes = doParse(subselector[3], e, subselector[2]);
						f = f.concat(listSubNodes)
					} else if (e.className != null && e.className.match("(\\s|^)" + d[3] + "(\\s|$)") != null) {
						f.push(e)
					}
				};
				return f;
			case ">":
				if (c != ">") {
					listNodes = getElementsByTagName(b, d[1])
				} else {
					listNodes = b.childNodes
				};
				for (i = 0, limit = listNodes.length; i < limit; i++) {
					e = listNodes[i];
					if (e.nodeType != 1) {
						continue
					};
					if (!matchNodeNames(e, d[1])) {
						continue
					};
					listSubNodes = doParse(d[3], e, ">");
					f = f.concat(listSubNodes)
				};
				return f;
			case "`":
				listNodes = getElementsByTagName(b, d[1]);
				for (i = 0, limit = listNodes.length; i < limit; i++) {
					e = listNodes[i];
					listSubNodes = doParse(d[3], e, "`");
					f = f.concat(listSubNodes)
				};
				return f;
			default:
				if (c != ">") {
					listNodes = getElementsByTagName(b, d[1])
				} else {
					listNodes = b.childNodes
				};
				for (i = 0, limit = listNodes.length; i < limit; i++) {
					e = listNodes[i];
					if (e.nodeType != 1) {
						continue
					};
					if (!matchNodeNames(e, d[1])) {
						continue
					};
					f.push(e)
				};
				return f
			}
		};
		function getElementsByTagName(a, b) {
			if (b == "*" && a.all != null) {
				return a.all
			};
			return a.getElementsByTagName(b)
		};
		function matchNodeNames(a, b) {
			if (b == "*") {
				return true
			};
			return a.nodeName.toLowerCase().replace("html:", "") == b.toLowerCase()
		};
		return parseSelector
	}()),
	bind: function(fn, scope, args) {
		return function() {
			return fn.apply(scope, args || arguments);
		}
	}
}.init();
