// page init
$(function(){
	initCufon();
	initCountdown();
	initOpenClose();
	initAccordion();
	initCustomForms();
	initLayout();
	initFormValidation();
})

// form validation
function initFormValidation() {
	var _errorClass = 'error';
	var _regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	$('form.nieuwsbrief-form').each(function(){
		var _form = $(this);
		function checkFields() {
			var _flag = false;
			_form.find('.'+_errorClass).removeClass(_errorClass);

			// fields validation
			_form.find('input.required-email').each(function(){
				if(!_regEmail.test($(this).val())) addError($(this));
			});
			_form.find('input.required, textarea.required').each(function(){
				if(!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this));
			});

			// error class adding
			function addError(_obj) {
				_obj.parents('div.row').addClass(_errorClass);
				_flag=true;
			}
			return _flag;
		}

		// catch form submit event
		_form.submit(function(){
			if(checkFields()) {
				return false;
			}
		});
	});
}

// cufon init
function initCufon() {
	Cufon.replace('.footer-holder ul li a', { fontFamily: 'blair', hover: true});
	Cufon.replace('.txt-baner h2', { fontFamily: 'helvetica-roman-medium'});
	Cufon.replace('.menu-content h2', { fontFamily: 'blair-medium'});
	Cufon.replace('.txt-baner a', { fontFamily: 'helvetica-roman-medium', hover: true});
	Cufon.replace('.menu-nav a', { fontFamily: 'blair', hover: true});
	Cufon.replace('.menu-info h3', { fontFamily: 'blair'});
	Cufon.replace('.title h2', { fontFamily: 'blair'});
	Cufon.replace('.ttl', { fontFamily: 'blair'});
	Cufon.replace('.form-box h3', { fontFamily: 'blair'});
	Cufon.replace('.pagination span', { fontFamily: 'blair'});
	Cufon.replace('.contact-box h3', { fontFamily: 'blair'});
	Cufon.replace('.gallery-info ul li h3', { fontFamily: 'blair'});
	Cufon.replace('.accordion .opener', { fontFamily: 'blair', hover: true});
	Cufon.replace('.contact-box ul li', { fontFamily: 'blair', hover: true});
	Cufon.replace('.review-box h3', { fontFamily: 'blair'});
	Cufon.replace('.txt-box h3', { fontFamily: 'blair'});
	Cufon.replace('.client-list h3', { fontFamily: 'blair'});
	Cufon.replace('.blockqoute-txt', { fontFamily: 'helvetica-ext-o'});
	Cufon.replace('.menu-holder blockquote q', { fontFamily: 'helvetica-ext-o'});
	Cufon.replace('.menu-holder blockquote a', { fontFamily: 'blair-medium', hover: true});
	Cufon.replace('.menu-holder blockquote span', { fontFamily: 'blair'});
	Cufon.replace('.counter span', { fontFamily: 'blair'});
	Cufon.replace('.counter em', { fontFamily: 'helvetica-th'});
	Cufon.replace('.friend-holder .friend-info h3 a', { fontFamily: 'blair', hover: true});
}

// background rotation code
function initBackgroundRotation() {
	// options
	var _animSpeed = 900;
	var _scrollSpeed = 800;
	var _switchTime = 6000;
	var _activeClass = 'active';
	var _backgroundAutoSwitch = true;
	var _disableAutoRotationIfGallery = false;
	var _autoslideflag = true;

	// init
	var _bgHolder = $('body > div.bg:eq(0)');
	var _bgImages = $('ul.backgrounds img').clone();
	var _bgCount = _bgImages.length;
	var _firstSlide = _bgHolder.find('>div:eq(0)').attr('rel',0);
	var _lastSrc = _firstSlide.find('img').attr('src');
	var _currentIndex = 0;
	var _oldIndex = 0;
	var _oldSlide;
	var _newSlide;
	var _timer;

	if(!_bgImages.length) return;
	else $('ul.backgrounds').remove();

	// animation
	function numBackground(_newInd) {
		if(_newInd != _currentIndex && _newInd <= _bgCount-1) {
			_oldIndex = _currentIndex;
			_currentIndex = _newInd;
			switchBackground();
		}
	}
	function prevBackground() {
		_oldIndex = _currentIndex;
		if(_currentIndex > 0) _currentIndex--;
		else _currentIndex = _bgCount-1;
		switchBackground();
	}
	function nextBackground() {
		_oldIndex = _currentIndex;
		if(_currentIndex < _bgCount-1) _currentIndex++;
		else _currentIndex = 0;
		switchBackground();
	}
	function autoChangeBackground() {
		if(_backgroundAutoSwitch) {
			if(_timer) clearTimeout(_timer);
			if(_autoslideflag) 
			_timer = setTimeout(nextBackground, _switchTime);
		}
	}
	function loadSlide(_ind) {
		if(!_bgHolder.children().filter('[rel='+(_ind)+']').length) {
			var _cloneSlide = _firstSlide.clone();
			_cloneSlide.attr('rel',_ind).hide().find('img').removeAttr('src').attr('src',_bgImages.eq(_ind).attr('alt'));
			_cloneSlide.appendTo(_bgHolder);
			fixLayout();
		}
		_oldSlide = _bgHolder.children().filter('[rel='+_oldIndex+']');
		_newSlide = _bgHolder.children().filter('[rel='+_ind+']');
		autoChangeBackground();
	}
	function switchBackground() {
		loadSlide(_currentIndex);
		_oldSlide.fadeOut(_animSpeed);
		_newSlide.fadeIn(_animSpeed);
		_lastSrc = _newSlide.find('img').attr('src');
		$('body').trigger('backgroundchanged');
	}

	// scrolling gallery
	var _backgroundControlGalleries = $('div.gallery-holder').parent();
	if(_backgroundControlGalleries.length) {
		if(_disableAutoRotationIfGallery) _backgroundAutoSwitch = false;
		_backgroundControlGalleries.each(function(){
			// gallery options & init
			var _holder = $(this);
			var _slidesHolder = _holder.find('div.gallery-holder');
			var _btnLeft = _slidesHolder.find('a.btn-prev');
			var _btnRight = _slidesHolder.find('a.btn-next');
			var _paginationHolder = _holder.find('div.pagination');
			var _paginationLinks = _holder.find('div.gallery-holder li');
			var _paginationText = _paginationHolder.find('>span');
			var _bgPrev = _paginationHolder.find('a.prev')
			var _bgNext = _paginationHolder.find('a.next')
			var _slider = _slidesHolder.find('>ul');
			var _slides = _slider.children();
			var _slidesCount = _slides.length;
			var _stepWidth = _slidesHolder.width();
			var _currentStep = 0;
			var _sumWidth = _slidesCount*_slides.eq(0).outerWidth(true);
			var _stepCount = Math.ceil(_sumWidth / _stepWidth);
			var _maxOffset = _stepWidth-_sumWidth;
			var _offset;

			// pagination
			function updatePagination() {
				_paginationText.html((_currentIndex+1)+'/'+_bgCount);
				Cufon.replace('.pagination span', { fontFamily: 'blair'});
			}
			_bgPrev.click(function(){
				prevBackground();
				return false;
			})
			_bgNext.click(function(){
				nextBackground();
				return false;
			})
			_paginationLinks.each(function(_ind){
				$(this).click(function(){
				_autoslideflag = false;
					numBackground(_ind);
					return false;
				})
			})

			// gallery control
			_btnLeft.click(function(){
				prevSlide();
				return false;
			});
			_btnRight.click(function(){
				nextSlide();
				return false;
			});

			// gallery animation
			function prevSlide() {
				if(_currentStep > 0) _currentStep--;
				else _currentStep = _stepCount-1;
				switchSlide();
			}
			function nextSlide() {
				if(_currentStep < _stepCount-1) _currentStep++;
				else _currentStep = 0;
				switchSlide();
			}
			function switchSlide() {
				_offset = -_currentStep*_stepWidth;
				if(_offset < _maxOffset) {_offset = _maxOffset; _currentStep = _stepCount-1;}
				_slider.animate({marginLeft:-_currentStep*_stepWidth},{duration:_scrollSpeed, queue:false});
			}

			// event on background change
			$('body').bind('backgroundchanged',function(){
				updatePagination();
			})
		})
	}

	// fire event end start autoslide
	$('body').bind('backgroundchanged',function(){
		$('body').find('input.bg-src').val(_lastSrc);
	});
	$('body').trigger('backgroundchanged');
	autoChangeBackground();
}

// function
function fixLayout() {
	// fix layout
	var _bg = $('body > div.bg');
	var _bgHolder = _bg.find('> div');
	var _imgs = _bgHolder.find('img');
	var _cells = _bgHolder.find('td');
	var _timer;
	var _aspectRatio = parseFloat(document.body.bgAspectRatio);

	// if IE6
	if(typeof document.body.style.maxHeight === "undefined") {
		_imgs.css({width:'50%',height:'auto'});
		var _sizeImage = _imgs.filter(':visible').eq(0);
		if(_sizeImage.height() < _bg.height()) {
			_imgs.css({height:'50%'});
			_imgs.css({width:_aspectRatio*_sizeImage.height()});
		}
	} else {
		_cells.css({height:'100%'})
		_cells.css({height:_bgHolder.height()});
	}
}

// layout fix function
function initStretchedBackground() {
	// fix layout
	var _imgWidth, _imgHeight, _imgRatio;
	var _imgSample = $('body > div.bg img').get(0);
	if(!_imgSample) return;
	if(_imgSample.complete) {
		_imgWidth = _imgSample.width;
		_imgHeight = _imgSample.height;
		_imgRatio = _imgWidth/_imgHeight;
	} else {
		_imgSample.onload = function() {
			_imgWidth = _imgSample.width;
			_imgHeight = _imgSample.height;
			_imgRatio = _imgWidth/_imgHeight;
			document.body.bgAspectRatio = _imgRatio;
			fixLayout();
			_imgSample.onload = null;
		}
	}
	document.body.bgAspectRatio = _imgRatio;
	fixLayout();
	$(window).resize(fixLayout);
}

// page layout animation
function initLayout() {
	var _delay = 600;
	var _slideSpeed = 1000;
	var _easing = 'easeInOutExpo';
	var _wrapper = $('#wrapper');
	var _footer = $('#footer');
	var _footerOffset = parseInt(_footer.css('marginTop'));
	var _dropNoHide = _footer.find('div.nohidebox').show();

	// layout animation on page load
	var _pageMinWidth = 1000;
	_wrapper.css({'overflow':'hidden', minWidth:1000});
	function ff() {
		var _wrapH = $('#wrap').outerHeight(true);
		var _windowH = $(window).height();
		var _windowW = $(window).width();

		if(_windowH < _wrapH+_footer.height() || _windowW < _pageMinWidth) {
			_wrapper.css({height:_wrapH+_footer.height()});
			if(_wrapper.height() < $(document).height()) _wrapper.css({height:$(document).height()});
			$('body').css({overflow:'visible'});
			$('html').css({overflow:'auto'});
		} else {
			_wrapper.css({height:_windowH});
			$('body').css({overflow:'hidden'});
			$('html').css({overflow:'hidden'});
		}
		$('.bg ').css({height:'auto'}).css({height:$(document).height(),width:$(document).width()});
	}
	$(window).resize(ff);
	ff();

	// refresh on window load
	$(window).load(function(){
		// dropdown function
		$('ul.footer-nav > li').each(function(){
			var _item = $(this);
			var _dropMenu = $('#'+_item.find('a').attr('rel'));
			if(_dropMenu.length) _dropMenu.css({marginBottom:-_dropMenu.outerHeight()}).show();
		});
	})

	// dropdown function
	var _dropActive = 'active';
	var _dropItems = $('ul.footer-nav > li');
	_dropItems.each(function(){
		var _item = $(this);
		var _dropMenu = $('#'+_item.find('a').attr('rel'));

		function toggleDrop(state) {
			if(state) {
				// hide active drops
				if(_dropNoHide.length) _dropNoHide.animate({marginBottom:-_dropNoHide.outerHeight()},{duration:_slideSpeed, easing:_easing, queue:false});
				_dropItems.not(_item).removeClass(_dropActive).each(function(){
					var _item = $(this);
					var _dropMenu = $('#'+_item.find('a').attr('rel'));
					_dropMenu.animate({marginBottom:-_dropMenu.outerHeight()},{duration:_slideSpeed, easing:_easing, queue:false});
				});

				// show selected drop
				_item.addClass(_dropActive);
				_dropMenu.animate({marginBottom:0},{duration:_slideSpeed, easing:_easing, queue:false});
			} else {
				_dropItems.removeClass(_dropActive);
				if(_dropNoHide.length) _dropNoHide.animate({marginBottom:0},{duration:_slideSpeed, easing:_easing, queue:false});
				_dropMenu.animate({marginBottom:-_dropMenu.outerHeight()},{duration:_slideSpeed, easing:_easing, queue:false});
			}
			try {Cufon.refresh('.footer-holder ul li a')} catch(e){}
		}
		if(_dropMenu.length) {
			_dropMenu.css({marginBottom:-_dropMenu.outerHeight()}).show();

			// connect content column with menu
			var _active = 'active';
			var _slideBlock = jQuery('div.content-column > div.slide-block');
			var _slideOpener = _slideBlock.find('> div.title a.open-close');

			_item.click(function(){
				// collapse content if menu clicked
				if(_slideBlock.length && _slideBlock.hasClass(_active)) _slideOpener.trigger('click');

				// toggle menu
				if(parseInt(_dropMenu.css('marginBottom'))) toggleDrop(true);
				else toggleDrop(false);
				return false;
			});
		}
	});
	if(_dropNoHide.length) {
		var _gTimer;
		function toggleNoHide(state) {
			if(_gTimer) clearTimeout(_gTimer);
			_gTimer = setTimeout(function(){
				if(state) {
					_dropNoHide.animate({marginBottom:0},{duration:_slideSpeed, easing:_easing, queue:false});
				} else {
					_dropNoHide.animate({marginBottom:-_dropNoHide.outerHeight()},{duration:_slideSpeed, easing:_easing, queue:false});
				}
			},_delay*2)
		}
	}

	// dropdown menus
	$('ul.ad-options > li').each(function(){
		var _animSpeed = 300;
		var _opener = $(this);
		var _hoverClass = 'hover';
		var _drop = _opener.find('>ul').show();

		if(_drop.length) {
			var _dropHeight = _drop.outerHeight();
			var _wrap = $('<div />');
			_wrap.css({
				zIndex: 400,
				position: 'absolute',
				overflow: 'hidden',
				height: _dropHeight,
				width: _drop.outerWidth(),
				left: parseInt(_drop.css('left')),
				bottom: parseInt(_drop.css('bottom'))
			})
			_wrap.appendTo(_opener).hide();
			_drop.appendTo(_wrap).css({bottom:0, marginBottom:-_dropHeight});
			_opener.hover(function(){
				_opener.addClass(_hoverClass);
				_wrap.show();
				_drop.stop().animate({marginBottom:0},{duration:_animSpeed});
				setTimeout(function(){Cufon.refresh('.footer-holder ul li a')},50);
			},function(){
				_opener.removeClass(_hoverClass);
				_drop.stop().animate({marginBottom:-_dropHeight},{duration:_animSpeed,complete:function(){
					_wrap.hide();
				}});
				setTimeout(function(){Cufon.refresh('.footer-holder ul li a')},50);
			})
			
		}
	})

	// fix stretched background
	initBackgroundRotation();	
	initStretchedBackground();
}

// coundown init
function initCountdown() {
	var _refreshRate = 10000;
	$('div.counter').each(function(){
		var _holder = $(this);

		var _srcDate = parseInt(_holder.find('input.src-value').val());
		var _days = _holder.find('span.days');
		var _hours = _holder.find('span.hours');
		var _minutes = _holder.find('span.minutes');

		function refreshCufon() {
			Cufon.replace('.counter span', { fontFamily: 'blair'})
			Cufon.replace('.counter em', { fontFamily: 'helvetica-th'})
		}
		function parseDate(date) {
			var _days = Math.floor(date / (1000*60*60*24));
			var _hours = Math.floor((date-_days*(1000*60*60*24)) / (1000*60*60))
			var _minutes = Math.floor((date-_days*(1000*60*60*24)-_hours*(1000*60*60)) / (1000*60))
			return {d:_days,h:_hours,m:_minutes};
		}
		function countDown() {
			var date = parseDate(_srcDate);
			_days.html(date.d);
			_hours.html(date.h);
			_minutes.html(date.m);
			refreshCufon();
			_srcDate-=_refreshRate;
		}
		countDown();
		setInterval(countDown,_refreshRate);
	})
}

// open-close blocks
function initOpenClose(){
	var _slideSpeed = 500;
	var _activeClass = 'active';
	$('div.slide-block').each(function(){
		var _holder = $(this);
		var _opener = _holder.find('a.open-close');
		var _slider = _holder.find('div.block');
		_opener.click(function(){
			if(_holder.hasClass(_activeClass)) {
				_slider.slideUp(_slideSpeed,function(){
					_holder.removeClass(_activeClass);
				});
			} else {
				_holder.addClass(_activeClass);
				_slider.slideDown(_slideSpeed);
			}
			return false;
		});
		if(_holder.hasClass(_activeClass)) _slider.show();
		else _slider.hide();
	});
}

// accordion init
function initAccordion() {
	var _activeClass = 'active';
	var _slideSpeed = 500;

	$('ul.accordion').each(function(){
		var _accordion = $(this);
		var _items = _accordion.find('li:has(div)');
		_items.each(function(){
			var _holder = $(this);
			var _opener = _holder.find('>a');
			var _slider = _holder.find('>div');

			// wrap to div with no paddings
			var _wrap = $('<div>').css({position:'relative',overflow:'hidden',zoom:1,padding:0});
			_slider.wrap(_wrap);
			_slider = _holder.find('>div');

			_opener.click(function(){
				var _levelItems = _holder.parent().children(':has(div)').not(_holder);

				if(_holder.hasClass(_activeClass)) {
					_slider.slideUp(_slideSpeed,function(){
						_holder.removeClass(_activeClass);
					});
				} else {
					_holder.addClass(_activeClass);
					_slider.slideDown(_slideSpeed);

					// collapse others
					_levelItems.find('>div:visible').slideUp(_slideSpeed,function(){
						_levelItems.removeClass(_activeClass);
					})
				}
				return false;
			});

			if(_holder.hasClass(_activeClass)) _slider.show();
			else _slider.hide();
		});
	});
}

// custom forms script
var _selectHeight = 22;
var _forms = document.getElementsByTagName('form');
var inputs = new Array();
var selects = new Array();
var labels = new Array();
var radios = new Array();
var radioLabels = new Array();
var checkboxes = new Array();
var checkboxLabels = new Array();
var buttons = new Array();
var selects = new Array();
var all_selects = false;
var active_select = null;
var agt = navigator.userAgent.toLowerCase();
var selectText = "please select";
var IN_CFORMS = true;

function initCustomForms() {
	if(!document.getElementById) {return false;}
	getElements();
	separateElements();
	replaceRadios();
	replaceCheckboxes();
	replaceSelects();

	var _selects = document.getElementsByTagName('select');
	var _SelctClassName = [];
	if (_selects) {
		for (var i = 0; i < _selects.length; i++) {
			if (_selects[i].className != '' && _selects[i].className != 'outtaHere')
				_SelctClassName[i] = ' drop-'+_selects[i].className;
		}
		for (var i = 0; i < _SelctClassName.length; i++) {
			var _selectDrop = document.getElementById('optionsDiv'+i);
			if (_selectDrop) {
				if (_SelctClassName[i])
					_selectDrop.className += _SelctClassName[i];
			}
		}
	}
}


// getting all the required elements
function getElements() {
	for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
		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;
				}
			}
		}
		if((inputs[q].type == "submit") || (inputs[q].type == "button")) {
			buttons[b] = inputs[q]; ++b;
		}
	}
}

//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])
		{
			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;
			}
			radios[who].checked = true;
			checkRadios(who);
		}
	}
}

//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";
		}
		else {
			checkboxArea.className = "checkboxArea";
		}
		checkboxArea.id = "myCheckbox" + q;
		checkboxes[q].parentNode.insertBefore(checkboxArea, checkboxes[q]);
		checkboxes[q]._ca = checkboxArea;
		checkboxArea.onclick = checkboxArea.onclick2 = 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;
	}
}

//changing checkboxes
function changeCheckboxes(who) {
	if(checkboxes[who].checked) {
		checkCheckboxes(who, false);
	}
	else {
		checkCheckboxes(who, true);
	}
}

//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);
}

//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
}


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);

		//hide the select field
		selects[q].className += " outtaHere";
		//insert select div
		selects[q].parentNode.insertBefore(selectArea, selects[q]);
		//build & place options div

		var optionsDiv = document.createElement("div");

		var optionsList = document.createElement("ul");
		optionsDiv.innerHTML += "<div class='select-top'><div></div></div>";
		optionsDiv.appendChild(optionsList);

		selects[q]._options = optionsList;

		optionsDiv.style.width = stWidth + "px";
		optionsDiv._parent = selectArea;

		optionsDiv.className = "optionsDivInvisible";
		optionsDiv.id = "optionsDiv"+q;


		populateSelectOptions(selects[q]);
		optionsDiv.innerHTML += "<div class='select-bottom'><div class='select-bottom-left'></div><div class='select-bottom-right'></div></div>";
		document.getElementsByTagName("body")[0].appendChild(optionsDiv);
		selects[q].replaced = true;
		}
	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);
		}

		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);
		}
	}
	if (me.disabled) {
		me._disabled.style.display = "block";
	}
	else {
		me._disabled.style.display = "none";
	}
}

//selecting me
function selectMe(selectFieldId,linkNo,selectNo) {
	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 (selectField.onchange && all_selects)
		{
			eval(selectField.onchange());
		}
}
//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.top = findPosY(divArea) + _selectHeight + '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(document.documentElement)
			{
				document.documentElement.onclick = hideSelectOptions;
			}
			else
			{
				window.onclick = hideSelectOptions;
			}
		}
		else if(_elem.className.indexOf("optionsDivVisible") != -1) {
			_elem.style.height = "auto";
			_elem.className = _elem.className.replace('optionsDivVisible','');
			_elem.className += " optionsDivInvisible";
		}

		// 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 hideSelectOptions(e)
{
	if(active_select)
	{
		if(!e) e = window.event;
		var _target = (e.target || e.srcElement);
		if(isElementBefore(_target,'selectArea') == 0 && isElementBefore(_target,'optionsDiv') == 0)
		{
			active_select.className = active_select.className.replace('optionsDivVisible', '');
			active_select.className = active_select.className.replace('optionsDivInvisible', '');
			active_select.className += " optionsDivInvisible";
			active_select = false;

			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)

	if(_parent.className && _parent.className.indexOf(_class) != -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}

}

function findPosY(obj) {
	var posTop = 0;
	while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
	return posTop;
}
function findPosX(obj) {
	var posLeft = 0;
	while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
	return posLeft;
}

/* jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ */
jQuery.easing.jswing=jQuery.easing.swing;jQuery.extend(jQuery.easing,{def:"easeOutQuad",swing:function(e,f,a,h,g){return jQuery.easing[jQuery.easing.def](e,f,a,h,g)},easeInQuad:function(e,f,a,h,g){return h*(f/=g)*f+a},easeOutQuad:function(e,f,a,h,g){return -h*(f/=g)*(f-2)+a},easeInOutQuad:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f+a}return -h/2*((--f)*(f-2)-1)+a},easeInCubic:function(e,f,a,h,g){return h*(f/=g)*f*f+a},easeOutCubic:function(e,f,a,h,g){return h*((f=f/g-1)*f*f+1)+a},easeInOutCubic:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f+a}return h/2*((f-=2)*f*f+2)+a},easeInQuart:function(e,f,a,h,g){return h*(f/=g)*f*f*f+a},easeOutQuart:function(e,f,a,h,g){return -h*((f=f/g-1)*f*f*f-1)+a},easeInOutQuart:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f+a}return -h/2*((f-=2)*f*f*f-2)+a},easeInQuint:function(e,f,a,h,g){return h*(f/=g)*f*f*f*f+a},easeOutQuint:function(e,f,a,h,g){return h*((f=f/g-1)*f*f*f*f+1)+a},easeInOutQuint:function(e,f,a,h,g){if((f/=g/2)<1){return h/2*f*f*f*f*f+a}return h/2*((f-=2)*f*f*f*f+2)+a},easeInSine:function(e,f,a,h,g){return -h*Math.cos(f/g*(Math.PI/2))+h+a},easeOutSine:function(e,f,a,h,g){return h*Math.sin(f/g*(Math.PI/2))+a},easeInOutSine:function(e,f,a,h,g){return -h/2*(Math.cos(Math.PI*f/g)-1)+a},easeInExpo:function(e,f,a,h,g){return(f==0)?a:h*Math.pow(2,10*(f/g-1))+a},easeOutExpo:function(e,f,a,h,g){return(f==g)?a+h:h*(-Math.pow(2,-10*f/g)+1)+a},easeInOutExpo:function(e,f,a,h,g){if(f==0){return a}if(f==g){return a+h}if((f/=g/2)<1){return h/2*Math.pow(2,10*(f-1))+a}return h/2*(-Math.pow(2,-10*--f)+2)+a},easeInCirc:function(e,f,a,h,g){return -h*(Math.sqrt(1-(f/=g)*f)-1)+a},easeOutCirc:function(e,f,a,h,g){return h*Math.sqrt(1-(f=f/g-1)*f)+a},easeInOutCirc:function(e,f,a,h,g){if((f/=g/2)<1){return -h/2*(Math.sqrt(1-f*f)-1)+a}return h/2*(Math.sqrt(1-(f-=2)*f)+1)+a},easeInElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return -(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e},easeOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k)==1){return e+l}if(!j){j=k*0.3}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}return g*Math.pow(2,-10*h)*Math.sin((h*k-i)*(2*Math.PI)/j)+l+e},easeInOutElastic:function(f,h,e,l,k){var i=1.70158;var j=0;var g=l;if(h==0){return e}if((h/=k/2)==2){return e+l}if(!j){j=k*(0.3*1.5)}if(g<Math.abs(l)){g=l;var i=j/4}else{var i=j/(2*Math.PI)*Math.asin(l/g)}if(h<1){return -0.5*(g*Math.pow(2,10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j))+e}return g*Math.pow(2,-10*(h-=1))*Math.sin((h*k-i)*(2*Math.PI)/j)*0.5+l+e},easeInBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*(f/=h)*f*((g+1)*f-g)+a},easeOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}return i*((f=f/h-1)*f*((g+1)*f+g)+1)+a},easeInOutBack:function(e,f,a,i,h,g){if(g==undefined){g=1.70158}if((f/=h/2)<1){return i/2*(f*f*(((g*=(1.525))+1)*f-g))+a}return i/2*((f-=2)*f*(((g*=(1.525))+1)*f+g)+2)+a},easeInBounce:function(e,f,a,h,g){return h-jQuery.easing.easeOutBounce(e,g-f,0,h,g)+a},easeOutBounce:function(e,f,a,h,g){if((f/=g)<(1/2.75)){return h*(7.5625*f*f)+a}else{if(f<(2/2.75)){return h*(7.5625*(f-=(1.5/2.75))*f+0.75)+a}else{if(f<(2.5/2.75)){return h*(7.5625*(f-=(2.25/2.75))*f+0.9375)+a}else{return h*(7.5625*(f-=(2.625/2.75))*f+0.984375)+a}}}},easeInOutBounce:function(e,f,a,h,g){if(f<g/2){return jQuery.easing.easeInBounce(e,f*2,0,h,g)*0.5+a}return jQuery.easing.easeOutBounce(e,f*2-g,0,h,g)*0.5+h*0.5+a}});
