$(function(){
	initTabs();
	hideFormText();
	initNavFix();
	initAcc();
	initGallery();
	pdfIcons();
});

// Prepend PDF links with PDF icons
function pdfIcons() {
	$("div#content a").each(function() {
		var regex = new RegExp("\.pdf$", "i");
		if (regex.exec($(this).attr("href"))) {
			var pdi = "/~ice/wp-content/themes/informationculturalexchange/images/pdficon_small.gif";
			
			if ( ! urlExists(pdi)) {
				pdi = "/wp-content/themes/informationculturalexchange/images/pdficon_small.gif";
			}
			
			$("<img class=\"pdf-icon\" src=\""+pdi+"\">").insertBefore($(this));
		}
	});
}

function urlExists(url) {
	var http = new XMLHttpRequest();
	http.open('HEAD', url, false);
	http.send();
	return http.status!=404;
}

// init gallery
function initGallery(){
	
	// hide gallery for now to stop content flash
	$(".project-gallery").css("visibility", "hidden");

	var g1 = $('.gallery').gallery({
		listOfSlides: '.frame > ul > li',
		switcher: '.switcher > ul > li',
		autoRotation: 5000
	});
	$('.gallery').mouseenter(function(){
		g1.stop();
	}).mouseleave(function(){
		g1.play();
	})
	// gallery on home page
	var gall = $('.project-gallery').gallery({
		infinite: true,
		listOfSlides: 'ul.switcher > li',
		autoRotation:7000,
		onStart: function(obj){
			var listItems = obj.list.parents('.project-gallery').find('.frame > ul');
			var items = obj.list.parents('.project-gallery').find('.frame > ul > li');
			listItems.append(items.clone(true));
			listItems.append(items.clone(true));
			obj.list.parents('.project-gallery').find('.frame > ul > li').removeClass('active');
			
			setTimeout(function(){
				$('.project-gallery').gallery({
					listOfSlides: '.frame > ul > li',
					switcher: 'ul.switcher > li',
					event:'mouseenter',
					effect: true,
					onStart: function(_this){
						_this.list.parent().children().removeClass('active');
					}
				});
			}, 500);
		}
	});
	$('.project-gallery .switcher-hold').mouseenter(function(){
		gall.stop();
	}).mouseleave(function(){
		gall.play();
	});

	setTimeout(function() {
		$(".project-gallery").css("visibility", "visible");
	}, 600);
}

// init accordion
function initAcc(){
	$('ul.accordion').uniAccordion({
		activeClass:'active',
		items:'> li',
		opener:'> a.tab',
		slider:'> div.content',
		animSpeed: 300,
		event:'click'
	});
}

// page init
function initNavFix() {
	new touchNav({
		navBlock: 'nav'
	});
}

//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];
			}
		}
	}
}

//tabs
function initTabs(){
	var sets = document.getElementsByTagName("ul");
	for (var i = 0; i < sets.length; i++)
	{
		if (sets[i].className.indexOf("tabset") != -1)
		{
			var tabs = [];
			var links = sets[i].getElementsByTagName("a");
			for (var j = 0; j < links.length; j++)
			{
				if (links[j].className.indexOf("tab") != -1)
				{
					tabs.push(links[j]);
					links[j].tabs = tabs;
					var c = document.getElementById(links[j].href.substr(links[j].href.indexOf("#") + 1));

					//reset all tabs on start
					if (c) if (links[j].className.indexOf("active") != -1) c.style.display = "block";
					else c.style.display = "none";

					links[j].onclick = function ()
					{
						var c = document.getElementById(this.href.substr(this.href.indexOf("#") + 1));
						if (c)
						{
							//reset all tabs before change
							for (var i = 0; i < this.tabs.length; i++)
							{
								var tab = document.getElementById(this.tabs[i].href.substr(this.tabs[i].href.indexOf("#") + 1));
								if (tab)
								{
									tab.style.display = "none";
								}
								this.tabs[i].className = this.tabs[i].className.replace("active", "");
							}
							this.className += " active";
							c.style.display = "block";
							return false;
						}
					}
				}
			}
		}
	}
}

// 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();

// 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);
		}
	}
}

// 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.index(accItems.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.filter('.'+o.activeClass);
				if(i != accItems.index(activeSlide)) {
					setActiveSlide(i);
				}
				return false;
			});
		});

		// element animations
		function setActiveSlide(setNum) {
			oldIndex = curIndex;
			curIndex = setNum;
			accItems.eq(oldIndex).removeClass(o.activeClass);
			accItems.eq(curIndex).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);
					accItems.eq(curNum).stop().animate(animProps,{duration:o.animSpeed,easing:o.easing,queue:false});
				}
			});
		}
		function repositionElements() {
			// recalculate dimensions
			accWidth = accordion.width();
			accOpenersWidth = 0;
			accItems.each(function(){
				accOpenerWidth = jQuery(this).data('opener').outerWidth(true);
				accOpenersWidth += accOpenerWidth;
			});
			accFreeWidth = accWidth - accOpenersWidth;

			// set styles
			accItems.each(function(i){
				jQuery(this).data('slider').css({width:accFreeWidth});
				animProps = {zIndex:i+1, width:accFreeWidth + accOpenerWidth};
				animProps[o.openerPosition] = i*accOpenerWidth + (i <= curIndex ? 0 : accFreeWidth)
				jQuery(this).css(animProps);
			});
		}

		repositionElements();
		jQuery(window).resize(repositionElements);
	});
}

// main gallery module
$.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: false,							//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(true));
			this.list.append(_el.clone(true));
			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) $this.switcher.removeClass('active').eq($this.active / $this.options.slideElement).addClass('active');
	},
	runTimer: function($this){
		if($this._t) clearInterval($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;
			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);
			if ($this.options.event === 'click') 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(){
		var _this = this;
		if (_this._t) clearInterval(_this._t);
	},
	play: function(){
		var _this = this;
		if (_this._t) clearInterval(_this._t);
		if (_this.options.autoRotation) _this.runTimer(_this);
	}
}
