// page init
jQuery(function(){
	clearInputs();
	initDropDown();
	initMenu();
	$('.gallery').gallery({
		listOfSlides: '.holder ul > li',
		switcher: 'ul.switcher > li',
		infinite: true
	});
	// horAcc();
	$('ul.accordion').uniAccordion({
		activeClass:'selected',
		items:'> li',
		opener:'> a.opener',
		slider:'> div.slide',
		animSpeed: 300,
		event:'click'
	});
	initAutoScalingNav({
		menuId: "nav",
		sideClasses: true,
		spacing:1,
		minPaddings: 10
	});
});

function horAcc(){
	var activeClass = 'selected';
	$('ul.accordion').each(function(){
		var list = $(this);
		var link = list.find('a.opener');
		var box = list.find('div.slide');
		var active = 0;

		list.children().each(function(){
			$(this).find('div.slide').show();
			$(this).data('w', $(this).find('div.slide').outerWidth(true)-5)
			$(this).find('div.slide').css({
				width:0,
				display:'none'
			});
		});
		
		link.eq(active).addClass(activeClass);
		box.eq(active).css({
			width: box.eq(active).parent().data('w'),
			display:'block'
		});
		
		link.click(function(){
			var ind = link.index($(this));
			var _this = $(this);
			box.eq(ind).show().animate({width:link.parent().data('w')}, {queue:false, duration:700, complete: function(){
				link.removeClass(activeClass);
				_this.addClass(activeClass);
			}});
			box.eq(active).animate({width:0}, {queue:false, duration:700, complete: function(){
				$(this).hide();
				active = ind;
			}});
			return false;
		});

	});
}

// clear inputs
function clearInputs(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: false,
		addClassFocus: "focus",
		filterClass: "default"
	});
};

// clear inputs plugin
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";
	}
};

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;
	}
}

/* sidebar navigation */
var _id = 'menuOLD';
var _innerEl = 'ul';
var _className = 'opened';
var _hide = false;

var _menu;
var _nodes;
function initMenu() {
	_menu = document.getElementById(_id);
	if (_menu){
		_nodes = _menu.getElementsByTagName('a');
		for (var i=0; i<_nodes.length; i++) {
			if (_nodes[i].parentNode.getElementsByTagName(_innerEl)[0]) {
				_nodes[i].onclick = function () {
					if(this.parentNode.className.indexOf(_className) !=-1) {
						this.parentNode.className = this.parentNode.className.replace(_className, "");
					} else {
						if (_hide) hideLevels(this);
						this.parentNode.className += ' '+_className;
					}
					return false;
				}
			}
		}
	}
}
function hideLevels(_this){
	var _lis = _menu.getElementsByTagName('li');
	for (var i=0; i<_lis.length; i++) {
		var _f = false;
		var _a = _lis[i].getElementsByTagName('a');
		for (var j=0; j<_a.length; j++) {
			if (_a[j] == _this) _f = true;
		}
		if (!_f) _lis[i].className = _lis[i].className.replace(_className, "");
	}
}
function initDropDown()
{
	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].onmouseover = function()	{
				this.className += " hover";
			}
			lis[i].onmouseout = function() {
				this.className = this.className.replace(" hover", "");
			}
		}
	}
}


// 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();

// main gallery module
(function($) {
	$.fn.gallery = function(options) { return new Gallery(this.get(0), options); };
	
	function Gallery(context, options) { this.init(context, options); };
	
	Gallery.prototype = {
		options:{},
		init: function (context, options){
			this.options = $.extend({
				infinite: false,								//true = infinite gallery
				duration: 700,									//duration of effect it 1000 = 1sec
				slideElement: 1,								//number of elements for a slide
				autoRotation: 7000,							//false = option is disabled; 1000 = 1sec
				effect: false,									//false = slide; true = fade
				listOfSlides: 'ul > li',						//elements galleries
				switcher: false,								//false = option is disabled; 'ul > li' = elements switcher
				disableBtn: false,								//false = option is disabled; 'hidden' = class adds an buttons "prev" and "next"
				nextBtn: 'a.link-next, a.btn-next, a.next',		//button "next"
				prevBtn: 'a.link-prev, a.btn-prev, a.prev',		//button "prev"
				circle: true,									//true = cyclic gallery; false = not cyclic gallery
				direction: false,								//false = horizontal; true = vertical
				event: 'click',									//event for the buttons and switcher
				IE: false,										//forced off effect it "fade" in IE
				autoHeight: false,								//auto height on fade
				easing: 'swing',
				onStart: function(){},
				onChange: function(){}
			}, options || {});
			var _el = $(context).find(this.options.listOfSlides);
			this.holder = $(context);
			if (this.options.effect) this.list = _el;
			else this.list = _el.parent();
			this.switcher = $(context).find(this.options.switcher);
			this.nextBtn = $(context).find(this.options.nextBtn);
			this.prevBtn = $(context).find(this.options.prevBtn);
			this.count = _el.index(_el.filter(':last'));
			
			if (this.options.switcher) this.active = this.switcher.index(this.switcher.filter('.active:eq(0)'));
			else this.active = _el.index(_el.filter('.active:eq(0)'));
			if (this.active < 0) this.active = 0;
			this.last = this.active;
			
			this.woh = _el.outerWidth(true);
			this.options.onStart(this);
			if (!this.options.direction) this.installDirections(this.list.parent().width());
			else {
				this.woh = _el.outerHeight(true);
				this.installDirections(this.list.parent().height());
			}
			
			if (!this.options.effect) {
				this.rew = this.count - this.wrapHolderW + 1;
				this.list.css({position: 'relative'}).css(this.dirAnimate());
			}
			else {
				this.rew = this.count;
				this.list.css({opacity: 0}).removeClass('active').eq(this.active).addClass('active').css({opacity: 1}).css('opacity', 'auto');
				this.switcher.removeClass('active').eq(this.active).addClass('active');
				if(this.options.autoHeight) this.list.parent().css({height: this.list.eq(this.active).outerHeight()});
			}
			this.flag = true;
			if (this.options.infinite){
				this.count++;
				this.active += this.count;
				this.list.append(_el.clone());
				this.list.append(_el.clone());
				this.list.css(this.dirAnimate());
			}
			
			this.initEvent(this, this.nextBtn, true);
			this.initEvent(this, this.prevBtn, false);
			if (this.options.disableBtn) this.initDisableBtn();
			if (this.options.autoRotation) this.runTimer(this);
			if (this.options.switcher) this.initEventSwitcher(this, this.switcher);
		},
		dirAnimate: function(){
			if (!this.options.direction) return {left: -(this.woh * this.active)};
			else return {top: -(this.woh * this.active)};
		},
		initDisableBtn: function(){
			this.prevBtn.removeClass('prev-'+this.options.disableBtn);
			this.nextBtn.removeClass('next-'+this.options.disableBtn);
			if (this.active == 0 || this.count+1 == this.wrapHolderW) this.prevBtn.addClass('prev-'+this.options.disableBtn);
			if (this.active == 0 && this.count+1 == 1 || this.count+1 <= this.wrapHolderW) this.nextBtn.addClass('next-'+this.options.disableBtn);
			if (this.active == this.rew) this.nextBtn.addClass('next-'+this.options.disableBtn);
		},
		installDirections: function(temp){
			this.wrapHolderW = Math.ceil(temp / this.woh);
			if (((this.wrapHolderW - 1) * this.woh + this.woh / 2) > temp) this.wrapHolderW--;
		},
		fadeElement: function(){
			if ($.browser.msie && this.options.IE){
				this.list.eq(this.last).css({opacity:0});
				this.list.removeClass('active').eq(this.active).addClass('active').css({opacity:'auto'});
			}
			else{
				this.list.eq(this.last).animate({opacity:0}, {queue:false, easing: this.options.easing, duration: this.options.duration});
				this.list.removeClass('active').eq(this.active).addClass('active').animate({
					opacity:1
				}, {queue:false, duration: this.options.duration, complete: function(){
					$(this).css('opacity','auto');
				}});
			}
			if(this.options.autoHeight) this.list.parent().animate({height: this.list.eq(this.active).outerHeight()}, {queue:false, duration: this.options.duration});
			if (this.options.switcher) this.switcher.removeClass('active').eq(this.active).addClass('active');
			this.last = this.active;
		},
		scrollElement: function($this){
			if (!$this.options.infinite) $this.list.stop().animate($this.dirAnimate(), {queue:false, easing: $this.options.easing, duration: $this.options.duration, complete:function(){ $this.options.onChange($this) }});
			else $this.list.stop().animate($this.dirAnimate(), $this.options.duration, $this.options.easing, function(){ $this.flag = true;$this.options.onChange($this); });
			if ($this.options.switcher) {
				if(($this.active / $this.options.slideElement) - $this.count == $this.count) var act = 0;
				else var act = ($this.active / $this.options.slideElement) - $this.count;
				$this.switcher.removeClass('active').eq(act).addClass('active');
			}
		},
		runTimer: function($this){
			if($this._t) clearTimeout($this._t);
			$this._t = setInterval(function(){
				if ($this.options.infinite) $this.flag = false;
				$this.toPrepare($this, true);
			}, this.options.autoRotation);
		},
		initEventSwitcher: function($this, el){
			el.bind($this.options.event, function(){
				$this.active = $this.switcher.index($(this)) * $this.options.slideElement + $this.count;
				if($this._t) clearTimeout($this._t);
				if ($this.options.disableBtn) $this.initDisableBtn();
				if (!$this.options.effect) $this.scrollElement($this);
				else $this.fadeElement();
				if ($this.options.autoRotation) $this.runTimer($this);
				return false;
			});
		},
		initEvent: function($this, addEventEl, dir){
			addEventEl.bind($this.options.event, function(){
				if ($this.flag){
					if ($this.options.infinite) $this.flag = false;
					if($this._t) clearTimeout($this._t);
					$this.toPrepare($this, dir);
					if ($this.options.autoRotation) $this.runTimer($this);
				}
				return false;
			});
		},
		toPrepare: function($this, side){
			if (!$this.options.infinite){
				if (($this.active == $this.rew) && $this.options.circle && side) $this.active = -$this.options.slideElement;
				if (($this.active == 0) && $this.options.circle && !side) $this.active = $this.rew + $this.options.slideElement;
				for (var i = 0; i < $this.options.slideElement; i++){
					if (side) { if ($this.active + 1 <= $this.rew) $this.active++; }
					else { if ($this.active - 1 >= 0) $this.active--; }
				};
			}
			else{
				if ($this.active >= $this.count + $this.count && side) $this.active -= $this.count;
				if ($this.active <= $this.count-1 && !side) $this.active += $this.count;
				$this.list.css($this.dirAnimate());
				if (side) $this.active += $this.options.slideElement;
				else $this.active -= $this.options.slideElement;
			}
			if (this.options.disableBtn) this.initDisableBtn();
			if (!$this.options.effect) $this.scrollElement($this);
			else $this.fadeElement();
		},
		stop: function(){
			if (this._t) clearTimeout(this._t);
		},
		play: function(){
			if (this._t) clearTimeout(this._t);
			if (this.options.autoRotation) this.runTimer(this);
		}
	}
}(jQuery));

// horizontal accordion plugin
jQuery.fn.uniAccordion = function(o){
	// default options
	var o = jQuery.extend({
		activeClass:'active',
		opener:'>.opener',
		slider:'>.slide',
		items:'>*',
		easing:'linear',
		animSpeed: 500,
		openerPosition: 'left', // right
		event:'click'
	},o);

	return this.each(function(){
		// options
		var accordion = jQuery(this), animProps,
			accItems = jQuery(o.items, accordion);

		// revert slides order
		if(!accItems.length) return;
		if(o.openerPosition == 'right') {
			var itemsParent = accItems.eq(0).parent();
			accItems.each(function(ind){
				accItems.eq(accItems.length - 1 - ind).appendTo(itemsParent);
			});
			accItems = jQuery(o.items, accordion);
		} else if(o.openerPosition !== 'left') {
			o.openerPosition = 'left'
		}

		// plugin variables
		accordion.css({position:'relative',overflow:'hidden'});
		var accWidth = 0,
			accOpenerWidth = 0,
			accOpenersWidth = 0,
			accFreeWidth = 0,
			oldIndex = 0,
			curIndex = accItems.find('a.opener').index(accItems.find('a.opener').filter('.'+o.activeClass));
		if(curIndex < 0) curIndex = 0;
		


		// event handlers
		accItems.each(function(i){
			var item = jQuery(this).css({display:'block',position:'absolute'});
			item.data('opener',jQuery(o.opener, this));
			item.data('slider',jQuery(o.slider, this));
			item.data('opener').bind(o.event, function(){
				var activeSlide = accItems.find('a.opener').filter('.'+o.activeClass);
				if(i != accItems.find('a.opener').index(activeSlide)) {
					setActiveSlide(i);
				}
				return false;
			});
		});

		// element animations
		function setActiveSlide(setNum) {
			oldIndex = curIndex;
			curIndex = setNum;
			accItems.eq(oldIndex).find('a.opener').removeClass(o.activeClass);
			accItems.eq(curIndex).find('a.opener').addClass(o.activeClass)
			accItems.each(function(curNum){
				if(curNum > Math.min(oldIndex,curIndex) && curNum <= Math.max(oldIndex,curIndex)) {
					animProps = {};
					animProps[o.openerPosition] = curNum*accOpenerWidth + (curNum <= curIndex ? 0 : accFreeWidth-0);
					accItems.eq(curNum).stop().animate(animProps,{duration:o.animSpeed,easing:o.easing,queue:false});
				}
			});
		}
		function repositionElements() {
			// recalculate dimensions
			accWidth = accordion.outerWidth(true);
			accOpenersWidth = 0;
			accItems.each(function(){
				accOpenerWidth = jQuery(this).data('opener').width();
				accOpenersWidth += accOpenerWidth;
			});
			accFreeWidth = accWidth - accOpenersWidth+0;

			// set styles
			accItems.each(function(i){
				jQuery(this).data('slider').css({width:accFreeWidth-30});
				animProps = {zIndex:i+1, width:accFreeWidth + accOpenerWidth - 0};
				animProps[o.openerPosition] = i*accOpenerWidth + (i <= curIndex ? 0 : accFreeWidth-0)
				jQuery(this).css(animProps);
			});
		}

		repositionElements();
		accItems.eq(curIndex).find('a.opener').addClass(o.activeClass)
		// jQuery(window).resize(repositionElements);
	});
}
