//Page init scripts
jQuery(function(){
	initCustomForms();
	initCufon();
	initInputs();
	initPopup();
	initSlider();
	var wpcf7Radio = jQuery('.wpcf7-radio .wpcf7-list-item');
	wpcf7Radio.each(function(n){
			if(n == (wpcf7Radio.length - 1)){
				jQuery(this).addClass('last-child');
			}
		});
});

/* initCufon */
function initCufon() {
	Cufon.replace('.connect strong', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('.connect .info-block a', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('#header q', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('#header cite', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('#main h2', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('.section-holder h3', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('.btn-nominate', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('#main .block-text .banner strong', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('.btn-donate a', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('.btn-donate span', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('#header .block-carousel h2', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('#header .block-carousel h3', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('.form-dominate-main h2 span', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
	Cufon.replace('#main .online strong', { fontFamily: 'ALTEHAASGROTESK_BOLD', hover: true });
};

/* initPopup */
function initPopup(){
	new popupNV(jQuery('.open-popup'));
};
/* popup module */
(function( $ ){
	popupNV = function(){
		this.init.apply(this,arguments)
	}
	popupNV.prototype = {
		init: function(context, options){
			this.options = jQuery.extend({
				eventType: 'click',
				popupUrl: 'href',
				buttonClose: '.close, .btn-close, .link-close',
				animationSpeed: 350,
				overlayMarkup: '<div class="lightbox-overlay"><span></span></div>',
				hideOnClickOverlay: true,
				overlayColor: '#000',
				overlayOpacity: 0.8,
				afterOpen: function(){},
				afterClose: function(){},
				afterInit: function(){}
			}, options);
			if(!context) return;
			this.set = jQuery(context);
			this.elementInit();
			this.eventInit();
		},
		elementInit: function(){
			this.set.each(this.binder(function(i, elem){
				jQuery(elem).bind(this.options.eventType, this.binder(function(){
					this.load = true;
					this.popup = jQuery(jQuery(elem).attr(this.options.popupUrl).substr(jQuery(elem).attr(this.options.popupUrl).lastIndexOf('#')));
					this.openPopup(this.popup);
					return false;
				}));
			}, this))
			this.overlay = jQuery(this.options.overlayMarkup);
			this.overlay.css({
				width: '100%',
				height: '100%',
				position: 'absolute',
				left: 0,
				top: 0,
				display: 'none',
				backgroundColor: this.options.overlayColor,
				zIndex: 1001
			})
			this.overlay.appendTo(jQuery('body'));
			this.options.afterInit(this);
		},
		eventInit: function(){
			jQuery(window).bind('scroll resize', this.binder(function(){
				this.load = false;
				this.refreshPosition(this.popup)
				this.resizeOverlay();
			}));
			jQuery(this.options.buttonClose, this.popup).live('click', this.binder(function(){
				this.closePopup(this.popup);
				return false;
			}));
			this.overlay.bind('click', this.binder(function(){
				if(this.options.hideOnClickOverlay){
					this.closePopup(this.popup);
				};
				return false;
			}));
		},
		openPopup: function(popup){
			this.visible = true;
			if(popup){
				popup.css({
					opacity: 0,
					display: 'block'
				}).animate({
					opacity: 1
				}, { queue: false, duration: this.options.animationSpeed, complete: this.binder(function(){
					this.options.afterOpen(this);
				})});
				this.refreshPosition(popup);
				this.resizeOverlay();
				this.showOverlay();
				jQuery(window).data('activePopupNV', this);
			};
		},
		closePopup: function(popup){
			this.visible = false;
			if(popup){
				popup.animate({
					opacity: 0
				}, { queue: false, duration: this.options.animationSpeed, complete: this.binder(function(){
					popup.css({ top: -9999, left: -9999 });
					this.options.afterClose(this);
				})});
				jQuery(window).data('activePopupNV', null);
			};
			this.hideOverlay();
		},
		refreshPosition: function(popup){
			if(!this.visible) return;
			this.popupTop = this.popupLeft = 0;
			this.popupTop = jQuery(window).height() > popup.outerHeight() ? jQuery(window).scrollTop() + (jQuery(window).height() - popup.outerHeight())/2 : this.popupTop;
			this.popupLeft = jQuery(window).width() > popup.outerWidth() ? jQuery(window).scrollLeft() + (jQuery(window).width() - popup.outerWidth())/2 : this.popupLeft;
			if(this.load){
				popup.css({
					top: this.popupTop,
					left: this.popupLeft,
					zIndex: 1999
				});
			}else {
				popup.css({
					zIndex: 1999
				}).animate({
					top: this.popupTop,
					left: this.popupLeft
				}, { queue: false, duration: 100 });
			}
		},
		getMaxHeight: function(){
			if(!document.body) return 0;
			return Math.max(
				jQuery(window).height(),
				jQuery('body > div').height(),
				jQuery('body').height()
			)
		},
		getMaxWidht: function(){
			if(!document.body) return 0;
			return Math.max(
				jQuery(window).width(),
				jQuery('body > div').width(),
				jQuery('body').width()
			)
		},
		resizeOverlay: function(){
			if(!this.visible) return;
			this.overlay.css({ width: this.getMaxWidht(), height: this.getMaxHeight() });
		},
		showOverlay: function(){
			this.overlay.stop().css({ display: 'block', opacity: 0 }).animate({ opacity: this.options.overlayOpacity }, { queue: false, duration: this.options.animationSpeed });
		},
		hideOverlay: function(){
			this.overlay.stop().animate({ opacity: 0 }, { queue: false, duration: this.options.animationSpeed, complete: this.binder(function(){
				this.overlay.css({ display: 'none' });
			})});
		},
		binder: function(fn, scope, args){
			var newScope = scope || this;
			return function() {
				return fn.apply(newScope, args || arguments);
			}
		}
	}
})( jQuery );

/* initSlider */
function initSlider(){
	jQuery('.block-carousel').each(function(){
		var set = jQuery(this);
		if(this.load) return; else this.load = true;
		new SliderNV(set,{
			slider:'.carousel >ul',
			btnPrev:'a.prev',
			btnNext:'a.next',
			effect: false,
			autoRotation: true,
			switchTime:5000
		});
	});
};
/* slider module */
(function($){
	SliderNV = function(){
		this.init.apply(this,arguments)
	}
	SliderNV.prototype = {
		init: function(context, options){
			/* default options */
			this.options = jQuery.extend({
				sliderHolder: '>div',
				slider:'>ul',
				slides: '>li',
				pagerLinks:'div.pager a',
				generatePagination: false,
				generatePaginationMarkup: '<li><a href="#">&amp;nbsp;</a></li>',
				btnPrev:'a.btn-prev111',
				btnNext:'a.btn-next111',
				activeClass:'active',
				disabledClass:'disabled',
				circleSlide: true,
				effect: true, // true == slide effect & false == fade effect
				pauseClass:'gallery-paused',
				pauseOnHover:true,
				autoRotation:false,
				switchTime:5000,
				animSpeed:650,
				easing:'swing',
				pagerEvent: 'click',
				butttonEvent:'click',
				beforeInit: function(){},
				afterInit:function(){},
				beforeAnimation: function(){},
				afterAnimation: function(){},
				vertical:false,
				reverse: false,
				step: false,
				startElement: 0,
				autoHeight: false
			},options);
			if(!context) return;
			this.set = context;
			if(typeof this.options.beforeInit === 'function') this.options.beforeInit(this);
			this.elementInit();
			this.eventInit();
			this.startPosition(this.currentElement);
			if(typeof this.options.afterInit === 'function') this.options.afterInit(this);
			this.set.data('sliderNV', this);
		},
		elementInit: function(){
			this.sliderHolder = jQuery(this.options.sliderHolder, this.set);
			this.slider = jQuery(this.options.slider, this.set);
			this.slides = jQuery(this.options.slides, this.slider);
			this.reCalc();
			this.currentElement = this.prevElement = this.options.startElement || 0;
			this.pagination();
			this.stepCount = this.slides.length;
			this.autoSlide();
		},
		reCalc: function(){
			this.sumHeight = 0;
			this.sumWidth = 0;
			this.slides.each(jQuery.proxy(function(i, elem){
				this.sumHeight += jQuery(elem).outerHeight(true);
				this.sumWidth += jQuery(elem).outerWidth(true);
			},this));
		},
		eventInit: function(){
			this.set.find(this.options.btnPrev).unbind(this.options.butttonEvent).bind(this.options.butttonEvent, jQuery.proxy(function(){
				this.prev();
				return false;
			}, this));
			this.set.find(this.options.btnNext).unbind(this.options.butttonEvent).bind(this.options.butttonEvent, jQuery.proxy(function(){
				this.next();
				return false;
			}, this));
			if(this.options.pauseOnHover){
				this.set.bind('mouseenter', jQuery.proxy(function(){
					this.set.addClass(this.options.pauseClass);
					clearTimeout(this.autoTimer);
				}, this)).bind('mouseleave',jQuery.proxy(function(){
					this.set.removeClass(this.options.pauseClass);
					this.autoSlide();
				}, this));
			};
		},
		pagination: function(){
			if(this.options.generatePagination) {
				this.set.find(this.options.generatePagination).empty()
				this.slides.each(jQuery.proxy(function(){
					var temp = jQuery(this.options.generatePaginationMarkup);
					this.set.find(this.options.generatePagination).append(temp);
				},this));
			};
			this.pagerLinks = jQuery(this.options.pagerLinks, this.set);
			if(this.pagerLinks){
				this.pagerLinks.each(jQuery.proxy(function(idx, elem){
					jQuery(elem).unbind(this.options.pagerEvent).bind(this.options.pagerEvent, jQuery.proxy(function(){
						if(!jQuery(elem).hasClass(this.options.activeClass)){
							this.prevElement = this.currentElement;
							this.currentElement = idx;
							this.swichFunction(this.currentElement);
							this.set.data('sliderNV', this);
						};
						return false;
					},this));
				},this));
			};
		},
		prev: function(){
			this.prevElement = this.currentElement;
			if(this.currentElement > 0){
				this.currentElement--;
			}
			else if(this.options.circleSlide) {
				this.currentElement = this.stepCount-1;
			};
			this.swichFunction(this.currentElement);
		},
		next: function(){
			this.prevElement = this.currentElement;
			if(this.currentElement < this.stepCount-1){
				this.currentElement++;
			}
			else if(this.options.circleSlide) {
				this.currentElement = 0;
			};
			this.swichFunction(this.currentElement);
		},
		disableButton: function(){
			if(!this.options.circleSlide) {
				this.set.find(this.options.btnPrev).removeClass(this.options.disabledClass);
				this.set.find(this.options.btnNext).removeClass(this.options.disabledClass);
				if(this.currentElement == 0){
					this.set.find(this.options.btnPrev).addClass(this.options.disabledClass);
				}
				else if(this.currentElement == this.stepCount-1){
					this.set.find(this.options.btnNext).addClass(this.options.disabledClass);
				};
			};
		},
		recalcOffsets: function(curr){
			if(this.options.vertical) {
				/* slide vertical */
				if(this.options.step) {
					this.stepHeight = this.slides.eq(curr).outerHeight(true)*parseInt(this.options.step);
					this.stepCount = Math.ceil((this.sumHeight-this.sliderHolder.height())/this.stepHeight)+1;
					this.offset = -this.stepHeight*curr;
				} else {
					this.stepHeight = this.sliderHolder.height();
					this.stepCount = Math.ceil(this.sumHeight/this.stepHeight);
					this.offset = -this.stepHeight*curr;
					if(this.offset < this.stepHeight-this.sumHeight) this.offset = this.stepHeight-this.sumHeight;
				}
			}
			else {
				/* slide horizontal */
				if(this.options.step) {
					this.stepWidth = this.slides.eq(curr).outerWidth(true)*parseInt(this.options.step);
					this.stepCount = Math.ceil((this.sumWidth-this.sliderHolder.width())/this.stepWidth)+1;
					this.offset = -this.stepWidth*curr;
					if(this.offset < this.sliderHolder.width()-this.sumWidth) this.offset = this.sliderHolder.width()-this.sumWidth;
				} else {
					this.stepWidth = this.sliderHolder.width();
					this.stepCount = Math.ceil(this.sumWidth/this.stepWidth);
					this.offset = -this.stepWidth*curr;
					if(this.offset < this.stepWidth-this.sumWidth) this.offset = this.stepWidth-this.sumWidth;
				}
			};
		},
		swichFunction: function(curr){
			if(!this.options.effect){
				/* fade effect */
				if(typeof this.options.beforeAnimation ==='function') this.options.beforeAnimation(this);
				this.slides.filter(':visible').stop(false, true).fadeOut(this.options.animSpeed);
				this.slides.eq(curr).stop(false, true).fadeIn(this.options.animSpeed, jQuery.proxy(function(){
					if(typeof this.options.afterAnimation ==='function') this.options.afterAnimation(this);
					this.autoSlide();
					if(this.options.autoHeight) this.slider.css({ position: 'relative', height: this.slides.eq(this.currentElement).outerHeight(true) });
					this.set.data('sliderNV', this);
				},this));
			}
			else {
				/* slide effect */
				var marginType = {};
				this.recalcOffsets(curr);
				marginType[this.options.vertical ? 'marginTop' : 'marginLeft'] = this.offset;
				if(typeof this.options.beforeAnimation ==='function') this.options.beforeAnimation(this);
				this.slider.animate(
					marginType,
					{
						queue: false,
						duration: this.options.animSpeed,
						complete: jQuery.proxy(function(){
							if(typeof this.options.afterAnimation ==='function') this.options.afterAnimation(this);
							this.autoSlide();
							this.set.data('sliderNV', this);
						},this)
					}
				);
			};
			this.pagerLinks.removeClass(this.options.activeClass).eq(this.currentElement).addClass(this.options.activeClass);
			if(!this.options.circleSlide) this.disableButton();
			this.set.data('sliderNV', this);
		},
		startPosition: function(curr){
			if(this.options.effect) {
				var marginType = {};
				this.recalcOffsets(curr);
				marginType[this.options.vertical ? 'marginTop' : 'marginLeft'] = this.offset;
				this.slider.css(marginType);
				this.slider.css({ width: this.sumWidth });
			}
			else {
				this.slides.css({ position: 'absolute', top: 0, left: 0 });
				this.slider.css({ position: 'relative' });
				if(this.options.autoHeight) this.slider.css({ position: 'relative', height: this.slides.eq(this.currentElement).outerHeight(true) });
				this.slides.hide().eq(this.currentElement).show();
			};
			this.disableButton();
			this.pagerLinks.removeClass(this.options.activeClass).eq(this.currentElement).addClass(this.options.activeClass);
		},
		autoSlide: function(){
			if(this.options.autoRotation && !this.set.hasClass(this.options.pauseClass)){
				if(this.autoTimer) clearTimeout(this.autoTimer);
				this.autoTimer = setTimeout(jQuery.proxy(function(){
					if(this.options.reverse) {
						this.prev();
					}
					else {
						this.next();
					}
				},this), this.options.switchTime + this.options.animSpeed);
			}
		}
	};
})( jQuery );

// clear inputs on focus
function initInputs() {
	// replace options
	var opt = {
		clearInputs: true,
		clearTextareas: true,
		clearPasswords: true
	}
	// collect all items
	var inputs = [].concat(
		PlaceholderInput.convertToArray(document.getElementsByTagName('input')),
		PlaceholderInput.convertToArray(document.getElementsByTagName('textarea'))
	);
	// apply placeholder class on inputs
	for(var i = 0; i < inputs.length; i++) {
		if(inputs[i].className.indexOf('default') < 0) {
			var inputType = PlaceholderInput.getInputType(inputs[i]);
			if((opt.clearInputs && inputType === 'text') ||
				(opt.clearTextareas && inputType === 'textarea') || 
				(opt.clearPasswords && inputType === 'password')
			) {
				new PlaceholderInput({
					element:inputs[i],
					wrapWithElement:false,
					showUntilTyping:false,
					getParentByClass:false,
					placeholderAttr:'value'
				});
			}
		}
	}
}

// input type placeholder class
;(function(){
	PlaceholderInput = function() {
		this.options = {
			element:null,
			showUntilTyping:false,
			wrapWithElement:false,
			getParentByClass:false,
			placeholderAttr:'value',
			inputFocusClass:'focus',
			inputActiveClass:'text-active',
			parentFocusClass:'parent-focus',
			parentActiveClass:'parent-active',
			labelFocusClass:'label-focus',
			labelActiveClass:'label-active',
			fakeElementClass:'input-placeholder-text'
		}
		this.init.apply(this,arguments);
	}
	PlaceholderInput.convertToArray = function(collection) {
		var arr = [];
		for (var i = 0, ref = arr.length = collection.length; i < ref; i++) {
		 arr[i] = collection[i];
		}
		return arr;
	}
	PlaceholderInput.getInputType = function(input) {
		return (input.type ? input.type : input.tagName).toLowerCase();
	}
	PlaceholderInput.prototype = {
		init: function(opt) {
			this.setOptions(opt);
			if(this.element && this.element.PlaceholderInst) {
				this.element.PlaceholderInst.refreshClasses();
			} else {
				this.element.PlaceholderInst = this;
				if(this.elementType == 'text' || this.elementType == 'password' || this.elementType == 'textarea') {
					this.initElements();
					this.attachEvents();
					this.refreshClasses();
				}
			}
		},
		setOptions: function(opt) {
			for(var p in opt) {
				if(opt.hasOwnProperty(p)) {
					this.options[p] = opt[p];
				}
			}
			if(this.options.element) {
				this.element = this.options.element;
				this.elementType = PlaceholderInput.getInputType(this.element);
				this.wrapWithElement = (this.elementType === 'password' || this.options.showUntilTyping ? true : this.options.wrapWithElement);
				this.setOrigValue( this.options.placeholderAttr == 'value' ? this.element.defaultValue : this.element.getAttribute(this.options.placeholderAttr) );
			}
		},
		setOrigValue: function(value) {
			this.origValue = value;
		},
		initElements: function() {
			// create fake element if needed
			if(this.wrapWithElement) {
				this.element.value = '';
				this.element.removeAttribute(this.options.placeholderAttr);
				this.fakeElement = document.createElement('span');
				this.fakeElement.className = this.options.fakeElementClass;
				this.fakeElement.innerHTML += this.origValue;
				this.fakeElement.style.color = getStyle(this.element, 'color');
				this.fakeElement.style.position = 'absolute';
				this.element.parentNode.insertBefore(this.fakeElement, this.element);
			}
			// get input label
			if(this.element.id) {
				this.labels = document.getElementsByTagName('label');
				for(var i = 0; i < this.labels.length; i++) {
					if(this.labels[i].htmlFor === this.element.id) {
						this.labelFor = this.labels[i];
						break;
					}
				}
			}
			// get parent node (or parentNode by className)
			this.elementParent = this.element.parentNode;
			if(typeof this.options.parentByClass === 'string') {
				var el = this.element;
				while(el.parentNode) {
					if(hasClass(el.parentNode, this.options.parentByClass)) {
						this.elementParent = el.parentNode;
						break;
					} else {
						el = el.parentNode;
					}
				}
			}
		},
		attachEvents: function() {
			this.element.onfocus = bindScope(this.focusHandler, this);
			this.element.onblur = bindScope(this.blurHandler, this);
			if(this.options.showUntilTyping) {
				this.element.onkeydown = bindScope(this.typingHandler, this);
				this.element.onpaste = bindScope(this.typingHandler, this);
			}
			if(this.wrapWithElement) this.fakeElement.onclick = bindScope(this.focusSetter, this);
		},
		togglePlaceholderText: function(state) {
			if(this.wrapWithElement) {
				this.fakeElement.style.display = state ? '' : 'none';
			} else {
				this.element.value = state ? this.origValue : '';
			}
		},
		focusSetter: function() {
			this.element.focus();
		},
		focusHandler: function() {
			this.focused = true;
			if(!this.element.value.length || this.element.value === this.origValue) {
				if(!this.options.showUntilTyping) {
					this.togglePlaceholderText(false);
				}
			}
			this.refreshClasses();
		},
		blurHandler: function() {
			this.focused = false;
			if(!this.element.value.length || this.element.value === this.origValue) {
				this.togglePlaceholderText(true);
			}
			this.refreshClasses();
		},
		typingHandler: function() {
			setTimeout(bindScope(function(){
				if(this.element.value.length) {
					this.togglePlaceholderText(false);
					this.refreshClasses();
				}
			},this), 10);
		},
		refreshClasses: function() {
			this.textActive = this.focused || (this.element.value.length && this.element.value !== this.origValue);
			this.setStateClass(this.element, this.options.inputFocusClass,this.focused);
			this.setStateClass(this.elementParent, this.options.parentFocusClass,this.focused);
			this.setStateClass(this.labelFor, this.options.labelFocusClass,this.focused);
			this.setStateClass(this.element, this.options.inputActiveClass, this.textActive);
			this.setStateClass(this.elementParent, this.options.parentActiveClass, this.textActive);
			this.setStateClass(this.labelFor, this.options.labelActiveClass, this.textActive);
		},
		setStateClass: function(el,cls,state) {
			if(!el) return; else if(state) addClass(el,cls); else removeClass(el,cls);
		}
	}
	
	// utility functions
	function hasClass(el,cls) {
		return el.className ? el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')) : false;
	}
	function addClass(el,cls) {
		if (!hasClass(el,cls)) el.className += " "+cls;
	}
	function removeClass(el,cls) {
		if (hasClass(el,cls)) {el.className=el.className.replace(new RegExp('(\\s|^)'+cls+'(\\s|$)'),' ');}
	}
	function bindScope(f, scope) {
		return function() {return f.apply(scope, arguments)}
	}
	function getStyle(el, prop) {
		if (document.defaultView && document.defaultView.getComputedStyle) {
			return document.defaultView.getComputedStyle(el, null)[prop];
		} else if (el.currentStyle) {
			return el.currentStyle[prop];
		} else {
			return el.style[prop];
		}
	}
}());

// custom forms script
var maxVisibleOptions = 43;
var all_selects = false;
var active_select = null;
var selectText = "please select";

function initCustomForms() {
	getElements();
	separateElements();
	replaceRadios();
	replaceCheckboxes();
	replaceSelects();

	// hide drop when scrolling or resizing window
	if (window.addEventListener) {
		window.addEventListener("scroll", hideActiveSelectDrop, false);
		window.addEventListener("resize", hideActiveSelectDrop, false);
	}
	else if (window.attachEvent) {
		window.attachEvent("onscroll", hideActiveSelectDrop);
		window.attachEvent("onresize", hideActiveSelectDrop);
	}
}

function refreshCustomForms() {
	// remove prevously created elements
	if(window.inputs) {
		for(var i = 0; i < checkboxes.length; i++) {
			if(checkboxes[i].checked) {checkboxes[i]._ca.className = "checkboxAreaChecked";}
			else {checkboxes[i]._ca.className = "checkboxArea";}
		}
		for(var i = 0; i < radios.length; i++) {
			if(radios[i].checked) {radios[i]._ra.className = "radioAreaChecked";}
			else {radios[i]._ra.className = "radioArea";}
		}
		for(var i = 0; i < selects.length; i++) {
			var newText = document.createElement('div');
			if (selects[i].options[selects[i].selectedIndex].title.indexOf('image') != -1) {
				newText.innerHTML = '<img src="'+selects[i].options[selects[i].selectedIndex].title+'" alt="" />';
				newText.innerHTML += '<span>'+selects[i].options[selects[i].selectedIndex].text+'</span>';
			} else {
				newText.innerHTML = selects[i].options[selects[i].selectedIndex].text;
			}
			document.getElementById("mySelectText"+i).innerHTML = newText.innerHTML;
		}
	}
}

// getting all the required elements
function getElements() {
	// remove prevously created elements
	if(window.inputs) {
		for(var i = 0; i < inputs.length; i++) {
			inputs[i].className = inputs[i].className.replace('outtaHere','');
			if(inputs[i]._ca) inputs[i]._ca.parentNode.removeChild(inputs[i]._ca);
			else if(inputs[i]._ra) inputs[i]._ra.parentNode.removeChild(inputs[i]._ra);
		}
		for(i = 0; i < selects.length; i++) {
			selects[i].replaced = null;
			selects[i].className = selects[i].className.replace('outtaHere','');
			selects[i]._optionsDiv._parent.parentNode.removeChild(selects[i]._optionsDiv._parent);
			selects[i]._optionsDiv.parentNode.removeChild(selects[i]._optionsDiv);
		}
	}

	// reset state
	inputs = new Array();
	selects = new Array();
	labels = new Array();
	radios = new Array();
	radioLabels = new Array();
	checkboxes = new Array();
	checkboxLabels = new Array();
	for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
		if(document.forms[nf].className.indexOf("default") < 0) {
			for(var nfi = 0; nfi < document.forms[nf].getElementsByTagName("input").length; nfi++) {inputs.push(document.forms[nf].getElementsByTagName("input")[nfi]);}
			for(var nfl = 0; nfl < document.forms[nf].getElementsByTagName("label").length; nfl++) {labels.push(document.forms[nf].getElementsByTagName("label")[nfl]);}
			for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName("select").length; nfs++) {selects.push(document.forms[nf].getElementsByTagName("select")[nfs]);}
		}
	}
}

// separating all the elements in their respective arrays
function separateElements() {
	var r = 0; var c = 0; var t = 0; var rl = 0; var cl = 0; var tl = 0; var b = 0;
	for (var q = 0; q < inputs.length; q++) {
		if(inputs[q].type == "radio") {
			radios[r] = inputs[q]; ++r;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && labels[w].htmlFor == inputs[q].id)
				{
					radioLabels[rl] = labels[w];
					++rl;
				}
			}
		}
		if(inputs[q].type == "checkbox") {
			checkboxes[c] = inputs[q]; ++c;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && (labels[w].htmlFor == inputs[q].id))
				{
					checkboxLabels[cl] = labels[w];
					++cl;
				}
			}
		}
	}
}

//replacing radio buttons
function replaceRadios() {
	for (var q = 0; q < radios.length; q++) {
		radios[q].className += " outtaHere";
		var radioArea = document.createElement("div");
		if(radios[q].checked) {
			radioArea.className = "radioAreaChecked";
		}
		else
		{
			radioArea.className = "radioArea";
		}
		radioArea.id = "myRadio" + q;
		radios[q].parentNode.insertBefore(radioArea, radios[q]);
		radios[q]._ra = radioArea;

		radioArea.onclick = new Function('rechangeRadios('+q+')');
		if (radioLabels[q]) {
			if(radios[q].checked) {
				radioLabels[q].className += "radioAreaCheckedLabel";
			}
			radioLabels[q].onclick = new Function('rechangeRadios('+q+')');
		}
	}
	return true;
}

//checking radios
function checkRadios(who) {
	var what = radios[who]._ra;
	for(var q = 0; q < radios.length; q++) {
		if((radios[q]._ra.className == "radioAreaChecked") && (radios[q]._ra.nextSibling.name == radios[who].name))
		{
			radios[q]._ra.className = "radioArea";
		}
	}
	what.className = "radioAreaChecked";
}

//changing radios
function changeRadios(who) {
	if(radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name) {
				radios[q].checked = false;
			} 
			radios[who].checked = true; 
			checkRadios(who);
		}
	}
}

//rechanging radios
function rechangeRadios(who) {
	if(!radios[who].checked) {
		for(var q = 0; q < radios.length; q++) {
			if(radios[q].name == radios[who].name) {
				radios[q].checked = false; 
				if(radioLabels[q]) radioLabels[q].className = radioLabels[q].className.replace("radioAreaCheckedLabel","");
			}
		}
		radios[who].checked = true; 
		if(radioLabels[who] && radioLabels[who].className.indexOf("radioAreaCheckedLabel") < 0) {
			radioLabels[who].className += " radioAreaCheckedLabel";
		}
		checkRadios(who);
		
		if(window.$ && window.$.fn) {
			$(radios[who]).trigger('change');
		}
	}
}

//replacing checkboxes
function replaceCheckboxes() {
	for (var q = 0; q < checkboxes.length; q++) {
		checkboxes[q].className += " outtaHere";
		var checkboxArea = document.createElement("div");
		if(checkboxes[q].checked) {
			checkboxArea.className = "checkboxAreaChecked";
			if(checkboxLabels[q]) {
				checkboxLabels[q].className += " checkboxAreaCheckedLabel"
			}
		}
		else {
			checkboxArea.className = "checkboxArea";
		}
		checkboxArea.id = "myCheckbox" + q;
		checkboxes[q].parentNode.insertBefore(checkboxArea, checkboxes[q]);
		checkboxes[q]._ca = checkboxArea;
		checkboxArea.onclick = new Function('rechangeCheckboxes('+q+')');
		if (checkboxLabels[q]) {
			checkboxLabels[q].onclick = new Function('changeCheckboxes('+q+')');
		}
		checkboxes[q].onkeydown = checkEvent;
	}
	return true;
}

//checking checkboxes
function checkCheckboxes(who, action) {
	var what = checkboxes[who]._ca;
	if(action == true) {
		what.className = "checkboxAreaChecked";
		what.checked = true;
	}
	if(action == false) {
		what.className = "checkboxArea";
		what.checked = false;
	}
	if(checkboxLabels[who]) {
		if(checkboxes[who].checked) {
			if(checkboxLabels[who].className.indexOf("checkboxAreaCheckedLabel") < 0) {
				checkboxLabels[who].className += " checkboxAreaCheckedLabel";
			}
		} else {
			checkboxLabels[who].className = checkboxLabels[who].className.replace("checkboxAreaCheckedLabel", "");
		}
	}
	
}

//changing checkboxes
function changeCheckboxes(who) {
	setTimeout(function(){
		if(checkboxes[who].checked) {
			checkCheckboxes(who, true);
		} else {
			checkCheckboxes(who, false);
		}
	},10);
}

// rechanging checkboxes
function rechangeCheckboxes(who) {
	var tester = false;
	if(checkboxes[who].checked == true) {
		tester = false;
	}
	else {
		tester = true;
	}
	checkboxes[who].checked = tester;
	checkCheckboxes(who, tester);
	if(window.$ && window.$.fn) {
		$(checkboxes[who]).trigger('change');
	}
}

// check event
function checkEvent(e) {
	if (!e) var e = window.event;
	if(e.keyCode == 32) {for (var q = 0; q < checkboxes.length; q++) {if(this == checkboxes[q]) {changeCheckboxes(q);}}} //check if space is pressed
}

// replace selects
function replaceSelects() {
	for(var q = 0; q < selects.length; q++) {
		if (!selects[q].replaced && selects[q].offsetWidth) {
			selects[q]._number = q;
			//create and build div structure
			var selectArea = document.createElement("div");
			var left = document.createElement("span");
			left.className = "left";
			selectArea.appendChild(left);

			var disabled = document.createElement("span");
			disabled.className = "disabled";
			selectArea.appendChild(disabled);

			selects[q]._disabled = disabled;
			var center = document.createElement("span");
			var button = document.createElement("a");
			var text = document.createTextNode(selectText);
			center.id = "mySelectText"+q;

			var stWidth = selects[q].offsetWidth;
			selectArea.style.width = stWidth + "px";
			if (selects[q].parentNode.className.indexOf("type2") != -1){
				button.href = "javascript:showOptions("+q+",true)";
			} else {
				button.href = "javascript:showOptions("+q+",false)";
			}
			button.className = "selectButton";
			selectArea.className = "selectArea";
			selectArea.className += " " + selects[q].className;
			selectArea.id = "sarea"+q;
			center.className = "center";
			center.appendChild(text);
			selectArea.appendChild(center);
			selectArea.appendChild(button);

			//insert select div
			selects[q].parentNode.insertBefore(selectArea, selects[q]);
			//build & place options div

			var optionsDiv = document.createElement("div");
			var optionsList = document.createElement("ul");
			var optionsListHolder = document.createElement("div");
			
			optionsListHolder.className = "select-center";
			optionsListHolder.innerHTML =  "<div class='select-center-right'></div>";
			optionsDiv.innerHTML += "<div class='select-top'><div class='select-top-left'></div><div class='select-top-right'></div></div>";
			
			optionsListHolder.appendChild(optionsList);
			optionsDiv.appendChild(optionsListHolder);
			
			selects[q]._optionsDiv = optionsDiv;
			selects[q]._options = optionsList;

			optionsDiv.style.width = stWidth + "px";
			optionsDiv._parent = selectArea;

			optionsDiv.className = "optionsDivInvisible";
			optionsDiv.id = "optionsDiv"+q;

			if(selects[q].className.length) {
				optionsDiv.className += ' drop-'+selects[q].className;
			}

			populateSelectOptions(selects[q]);
			optionsDiv.innerHTML += "<div class='select-bottom'><div class='select-bottom-left'></div><div class='select-bottom-right'></div></div>";
			document.body.appendChild(optionsDiv);
			selects[q].replaced = true;
			
			// too many options
			if(selects[q].options.length > maxVisibleOptions) {
				optionsDiv.className += ' optionsDivScroll';
			}
			
			//hide the select field
			if(selects[q].className.indexOf('default') != -1) {
				selectArea.style.display = 'none';
			} else {
				selects[q].className += " outtaHere";
			}
		}
	}
	all_selects = true;
}

//collecting select options
function populateSelectOptions(me) {
	me._options.innerHTML = "";
	for(var w = 0; w < me.options.length; w++) {
		var optionHolder = document.createElement('li');
		var optionLink = document.createElement('a');
		var optionTxt;
		if (me.options[w].title.indexOf('image') != -1) {
			optionTxt = document.createElement('img');
			optionSpan = document.createElement('span');
			optionTxt.src = me.options[w].title;
			optionSpan = document.createTextNode(me.options[w].text);
		} else {
			optionTxt = document.createTextNode(me.options[w].text);
		}
		
		// hidden default option
		if(me.options[w].className.indexOf('default') != -1) {
			optionHolder.style.display = 'none'
		}
		
		optionLink.href = "javascript:showOptions("+me._number+"); selectMe('"+me.id+"',"+w+","+me._number+");";
		if (me.options[w].title.indexOf('image') != -1) {
			optionLink.appendChild(optionTxt);
			optionLink.appendChild(optionSpan);
		} else {
			optionLink.appendChild(optionTxt);
		}
		optionHolder.appendChild(optionLink);
		me._options.appendChild(optionHolder);
		//check for pre-selected items
		if(me.options[w].selected) {
			selectMe(me.id,w,me._number,true);
		}
	}
	if (me.disabled) {
		me._disabled.style.display = "block";
	} else {
		me._disabled.style.display = "none";
	}
}

//selecting me
function selectMe(selectFieldId,linkNo,selectNo,quiet) {
	selectField = selects[selectNo];
	for(var k = 0; k < selectField.options.length; k++) {
		if(k==linkNo) {
			selectField.options[k].selected = true;
		}
		else {
			selectField.options[k].selected = false;
		}
	}
	
	//show selected option
	textVar = document.getElementById("mySelectText"+selectNo);
	var newText;
	var optionSpan;
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		newText = document.createElement('img');
		newText.src = selectField.options[linkNo].title;
		optionSpan = document.createElement('span');
		optionSpan = document.createTextNode(selectField.options[linkNo].text);
	} else {
		newText = document.createTextNode(selectField.options[linkNo].text);
	}
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);
		textVar.appendChild(optionSpan);
	} else {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);
	}
	if (!quiet && all_selects) {
		if(typeof selectField.onchange === 'function') {
			selectField.onchange();
		}
		if(window.$ && window.$.fn) {
			$(selectField).trigger('change');
		}
	}
}

//showing options
function showOptions(g) {
	_elem = document.getElementById("optionsDiv"+g);
	var divArea = document.getElementById("sarea"+g);
	if (active_select && active_select != _elem) {
		active_select.className = active_select.className.replace('optionsDivVisible',' optionsDivInvisible');
		active_select.style.height = "auto";
	}
	if(_elem.className.indexOf("optionsDivInvisible") != -1) {
		_elem.style.left = "-9999px";
		_elem.style.width = divArea.offsetWidth + 'px';
		_elem.style.top = findPosY(divArea) + divArea.offsetHeight + 'px';
		_elem.className = _elem.className.replace('optionsDivInvisible','');
		_elem.className += " optionsDivVisible";
		/*if (_elem.offsetHeight > 200)
		{
			_elem.style.height = "200px";
		}*/
		_elem.style.left = findPosX(divArea) + 'px';
		
		active_select = _elem;
		if(_elem._parent.className.indexOf('selectAreaActive') < 0) {
			_elem._parent.className += ' selectAreaActive';
		}
		
		if(document.documentElement) {
			document.documentElement.onclick = hideSelectOptions;
		} else {
			window.onclick = hideSelectOptions;
		}
	}
	else if(_elem.className.indexOf("optionsDivVisible") != -1) {
		hideActiveSelectDrop();
	}
	
	// for mouseout
	/*_elem.timer = false;
	_elem.onmouseover = function() {
		if (this.timer) clearTimeout(this.timer);
	}
	_elem.onmouseout = function() {
		var _this = this;
		this.timer = setTimeout(function(){
			_this.style.height = "auto";
			_this.className = _this.className.replace('optionsDivVisible','');
			if (_elem.className.indexOf('optionsDivInvisible') == -1)
				_this.className += " optionsDivInvisible";
		},200);
	}*/
}

function hideActiveSelectDrop() {
	if(active_select) {
		active_select.style.height = "auto";
		active_select.className = active_select.className.replace('optionsDivVisible', '');
		active_select.className = active_select.className.replace('optionsDivInvisible', '');
		active_select._parent.className = active_select._parent.className.replace('selectAreaActive','')
		active_select.className += " optionsDivInvisible";
		active_select = false;
	}
}

function hideSelectOptions(e) {
	if(active_select) {
		if(!e) e = window.event;
		var _target = (e.target || e.srcElement);
		if(!isElementBefore(_target,'selectArea') && !isElementBefore(_target,'optionsDiv')) {
			hideActiveSelectDrop();
			if(document.documentElement) {
				document.documentElement.onclick = function(){};
			}
			else {
				window.onclick = null;
			}
		}
	}
}

function isElementBefore(_el,_class) {
	var _parent = _el;
	do {
		_parent = _parent.parentNode;
	}
	while(_parent && _parent.className != null && _parent.className.indexOf(_class) == -1)
	return _parent.className && _parent.className.indexOf(_class) != -1;
}

function findPosY(obj) {
	if (obj.getBoundingClientRect) {
		var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
		var clientTop = document.documentElement.clientTop || document.body.clientTop || 0;
		return Math.round(obj.getBoundingClientRect().top + scrollTop - clientTop);
	} else {
		var posTop = 0;
		while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
		return posTop;
	}
}

function findPosX(obj) {
	if (obj.getBoundingClientRect) {
		var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
		var clientLeft = document.documentElement.clientLeft || document.body.clientLeft || 0;
		return Math.round(obj.getBoundingClientRect().left + scrollLeft - clientLeft);
	} else {
		var posLeft = 0;
		while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
		return posLeft;
	}
};
