$(function () {
    initCastomForms();
    initTabs();
    initPage();
    initSlideShow();
    initValidation();
    itemsForm();
    initGallery();
    initLightbox();
//    $(".btn-search").click(function (event) {
//        event.preventDefault();
//        alert("Coming soon!");
//    });

});

function initLightbox(){
	a = [];
	$('a.open-popup').each(function(i){
		a[i] = $(this).pvlightbox({
			closer:'.shopping,.close'
		}); 
	});
}

//init gallery
function initGallery(){
	var speed = 1000;
	var activeClass = 'selected';
	jQuery('.slideshow').each(function(){
		var hold = jQuery(this);
		var slider = hold.find('.slider-holder');
		var slideHolder = slider.find('> ul');
		var slide = slideHolder.find('> li');
		var btnNext = hold.find('a.next');
		var btnPrev = hold.find('a.prev');
		var switcher = hold.find('.switcher li');
		var caption = hold.find('.slideshow2');
		var captionSlider = caption.find('ul.slider');
		var prevIndex, currentIndex = 0, offset, animating;
		var slideW = slider.outerWidth();
		var slideW2 = caption.outerWidth();
		
		switcher.removeClass(activeClass).eq(currentIndex).addClass(activeClass);
		
		function prevSlide(){
			prevIndex = currentIndex;
			if(currentIndex > 0) currentIndex--;
			else {
				animating = false;
				return;
			}
			switchSlide();
		}
		
		function nextSlide() {
			prevIndex = currentIndex;
			if(currentIndex < slide.length-1) currentIndex++;
			else {
				animating = false;
				return;
			}
			switchSlide();
		}
		
		function switchSlideNum(n) {
			if (n == currentIndex) {
				animating = false;
				return;
			}
			prevIndex = currentIndex;
			if (n < currentIndex) {direction = 0;}
			else {direction = 1;}
			currentIndex=n;
			switchSlide();
		}
		
		function switchSlide(){
			offset = slideW * currentIndex;
			offset2 = slideW2 * currentIndex;
			slideHolder.stop().animate({marginLeft: - offset},{duration: speed, complete: function(){animating = false;}});
			captionSlider.stop().animate({marginLeft: - offset2},{duration: speed, complete: function(){animating = false;}});
			switcher.removeClass(activeClass).eq(currentIndex).addClass(activeClass);
		}
		
		btnPrev.click(function(){
			if(!animating){
				animating = true;
				prevSlide();
			}
			return false;
		});
		btnNext.click(function(){
			if(!animating){
				animating = true;
				nextSlide();
			}
			return false;
		});
		switcher.each(function(i){
			jQuery(this).click(function(){
				if(!animating){
					animating = true;
					switchSlideNum(i);
				}
				return false;
			});
		});
	});
}

function initValidation(){
	var _errorClass = 'error';
	var _regEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var _regPhone = /^[0-9\-\ \()]+$/;

	$('form.validate').each(function () {
	    var _form = $(this);
	    var _checkField1 = _form.find('.required-check');
	    var _item = _form.find('.required-check > li');
	    _item.click(function () {
	        _checkField1.removeClass('error-chk');
	    })
	    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-phone').each(function () {
	            if (!_regPhone.test($(this).val())) addError($(this));
	        });
	        _form.find('input.required').each(function () {
	            if (!$(this).val().length || $(this).val() == $(this).attr('alt')) addError($(this));
	        });
	        _form.find('textarea.required').each(function () {
	            if (!$(this).val().length || $(this).val() == $(this).attr('alt')) {
	                $(this).parent().addClass(_errorClass + '-area');
	                _flag = true;
	            };
	        });
	        var _checkField = _form.find('.required-check');
	        if (_checkField.length) {
	            var _input = _checkField.find('input:checkbox');
	            var _flag2 = false;
	            _input.each(function () {
	                if ($(this).is(':checked')) {
	                    _flag2 = true;
	                }
	            });
	            if (!_flag2) {
	                _checkField.addClass('error-chk');
	                _flag = true;
	            }
	        }
	        _form.find('input.required-chek').each(function () {
	            if (!$(this).is(':checked')) {
	                $(this).parent().find('label').addClass('error-chk');
	                _flag = true;
	            }
	        });
	        // error class adding
	        function addError(_obj) {
	            _obj.addClass(_errorClass);
	            _flag = true;
	        }
	        return _flag;
	    }
	    // catch form submit event
	    _form.submit(function () {
	        if (checkFields()) {
	            return false;
	        } else {
	            jQuery.ajax({
	                url: _form.attr('action'),
	                data: _form.serialize(),
	                type: 'POST',
	                success: changeTab,
	                error: function () {
	                    alert('ERROR!')
	                }
	            });
	            return false;
	        }
	    });
	});
}

function itemsForm(){
	var _form = $('.items-form');
	_form.submit(function(){
		jQuery.ajax({
			url: _form.attr('action'),
			data: _form.serialize(),
			type: 'POST',
			success: changeTab,
			error: function(){
				alert('ERROR!')
			}
		});
		return false;
	})
}

function changeTab(){
	var _list = $('.heading-tabs .tabset');
	var _links = _list.find('.tab');
	var _index = _list.find('.active').parent().index()+1;
	_list.find('li').eq(_index).find('.tab').trigger('click');
}

// slideshow init
function initSlideShow() {
	jQuery('div.gallery').fadeGallery({
		slideElements:'ul.images > li',
		pagerLinks:'div.pager a',
		btnNext:'a.next',
		btnPrev:'a.prev',
		btnPlayPause:'a.play-pause',
		pausedClass:'paused',
		playClass:'playing',
		activeClass:'active',
		pauseOnHover:true,
		autoRotation:false,
		autoHeight:false,
		switchTime:3000,
		duration:500,
		event:'click'
	});
}

// slideshow plugin
jQuery.fn.fadeGallery = function(_options){
	var _options = jQuery.extend({
		slideElements:'div.slideset > div',
		pagerLinks:'div.pager a',
		btnNext:'a.next',
		btnPrev:'a.prev',
		btnPlayPause:'a.play-pause',
		btnPlay:'a.play',
		btnPause:'a.pause',
		pausedClass:'paused',
		disabledClass: 'disabled',
		playClass:'playing',
		activeClass:'active',
		currentNum:false,
		allNum:false,
		startSlide:null,
		noCircle:false,
		pauseOnHover:true,
		autoRotation:false,
		autoHeight:false,
		onChange:false,
		switchTime:3000,
		duration:650,
		event:'click'
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _slides = jQuery(_options.slideElements, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _btnPlayPause = jQuery(_options.btnPlayPause, _this);
		var _btnPause = jQuery(_options.btnPause, _this);
		var _btnPlay = jQuery(_options.btnPlay, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledClass = _options.disabledClass;
		var _pausedClass = _options.pausedClass;
		var _playClass = _options.playClass;
		var _autoHeight = _options.autoHeight;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _currentNum = (_options.currentNum ? jQuery(_options.currentNum, _this) : false);
		var _allNum = (_options.allNum ? jQuery(_options.allNum, _this) : false);
		var _startSlide = _options.startSlide;
		var _noCycle = _options.noCircle;
		var _onChange = _options.onChange;

		// gallery init
		var _hover = false;
		var _prevIndex = 0;
		var _currentIndex = 0;
		var _slideCount = _slides.length;
		var _timer;
		if(_slideCount < 2) return;

		_prevIndex = _slides.index(_slides.filter('.'+_activeClass));
		if(_prevIndex < 0) _prevIndex = _currentIndex = 0;
		else _currentIndex = _prevIndex;
		if(_startSlide != null) {
			if(_startSlide == 'random') _prevIndex = _currentIndex = Math.floor(Math.random()*_slideCount);
			else _prevIndex = _currentIndex = parseInt(_startSlide);
		}
		_slides.hide().eq(_currentIndex).show();
		if(_autoRotation) _this.removeClass(_pausedClass).addClass(_playClass);
		else _this.removeClass(_playClass).addClass(_pausedClass);

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				nextSlide();
				return false;
			});
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentIndex != _ind) {
						_prevIndex = _currentIndex;
						_currentIndex = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// play pause section
		if(_btnPlayPause.length) {
			_btnPlayPause.bind(_controlEvent,function(){
				if(_this.hasClass(_pausedClass)) {
					_this.removeClass(_pausedClass).addClass(_playClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_autoRotation = false;
					if(_timer) clearTimeout(_timer);
					_this.removeClass(_playClass).addClass(_pausedClass);
				}
				return false;
			});
		}
		if(_btnPlay.length) {
			_btnPlay.bind(_controlEvent,function(){
				_this.removeClass(_pausedClass).addClass(_playClass);
				_autoRotation = true;
				autoSlide();
				return false;
			});
		}
		if(_btnPause.length) {
			_btnPause.bind(_controlEvent,function(){
				_autoRotation = false;
				if(_timer) clearTimeout(_timer);
				_this.removeClass(_playClass).addClass(_pausedClass);
				return false;
			});
		}

		// gallery animation
		function prevSlide() {
			_prevIndex = _currentIndex;
			if(_currentIndex > 0) _currentIndex--;
			else {
				if(_noCycle) return;
				else _currentIndex = _slideCount-1;
			}
			switchSlide();
		}
		function nextSlide() {
			_prevIndex = _currentIndex;
			if(_currentIndex < _slideCount-1) _currentIndex++;
			else {
				if(_noCycle) return;
				else _currentIndex = 0;
			}
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentIndex).addClass(_activeClass);
			if(_currentNum) _currentNum.text(_currentIndex+1);
			if(_allNum) _allNum.text(_slideCount);
			_slides.eq(_prevIndex).removeClass(_activeClass);
			_slides.eq(_currentIndex).addClass(_activeClass);
			if(_noCycle) {
				if(_btnPrev.length) {
					if(_currentIndex == 0) _btnPrev.addClass(_disabledClass);
					else _btnPrev.removeClass(_disabledClass);
				}
				if(_btnNext.length) {
					if(_currentIndex == _slideCount-1) _btnNext.addClass(_disabledClass);
					else _btnNext.removeClass(_disabledClass);
				}
			}
			if(typeof _onChange === 'function') {
				_onChange(_this, _currentIndex);
			}
		}
		function switchSlide() {
			_slides.eq(_prevIndex).fadeOut(_duration);
			_slides.eq(_currentIndex).fadeIn(_duration);
			if(_autoHeight) _slides.eq(_currentIndex).parent().animate({height:_slides.eq(_currentIndex).outerHeight(true)},{duration:_duration,queue:false});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function autoSlide() {
			if(!_autoRotation || _hover) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		refreshStatus();
		autoSlide();
	});
}

function initTabs() {
	$('ul.tabset,ul.links').each(function(){
		var _list = $(this);
		var _links = _list.find('a.tab');
		var _back = $('.tab-content .back');
		_links.each(function(i) {
			var _link = $(this);
			var _href = _link.attr('href');
			var _tab = $(_href);

			if(_link.hasClass('active')) _tab.show();
			else _tab.hide();
			_link.click(function(){
				_links.filter('.active').each(function(){
					$($(this).removeClass('active').attr('href')).hide();
				});
				_link.addClass('active');
				_tab.show();
				return false;
			});
		});
		_back.click(function(){
			_list.find('li').eq(_list.find('.active').parent().index()-1).find('.tab').trigger('click')
			return false;
		});
	});
}
$.fn.pvlightbox = function(options){return new pvlightbox($(this).eq(0),options)}
function pvlightbox(link, options) {this.init(link,options)}
pvlightbox.prototype = {
	init:function(link,options){
		var el = this;
		//options
		el.options = $.extend({
			fadeSpeed:400,
			closer:'a.close-btn',
			scroll:false,
			wrapper:'#wrapper',
			IE:true,
			zIndex:1000
		},options);	
		//popup & default css styles
		if ($.browser.msie && el.options.IE) el.popup = $(link.attr('href')).css({visibility:'hidden'})
		else el.popup = $(link.attr('href')).css({opacity:0,visibility:'hidden'});
		if (el.options.zIndex) el.popup.css({zIndex : el.options.zIndex});
		el.closer = $(el.popup.find(el.options.closer));
		el.popup.visible = false;
		pvlightbox.prototype.activePopup = false;
		if (!pvlightbox.prototype.firstRun) {
			pvlightbox.prototype.firstRun = 'done'
			if ($.browser.msie && $.browser.version < 7) pvlightbox.prototype.selects = $('select',document);
			//create fader
			if (!$('#fader').length) {
				$('body').append('<div id="fader"></div>');
				pvlightbox.prototype.fader = $('#fader');
				pvlightbox.prototype.fader.css({position:'absolute',top:0,left:0,background:'#000',opacity:0,display:'none'});	
				if (el.options.zIndex) pvlightbox.prototype.fader.css({zIndex : el.options.zIndex-1});
			}
			//fader click event
			pvlightbox.prototype.fader.click(function(){
				if (pvlightbox.prototype.activePopup == false) el.hideFader()
				else pvlightbox.prototype.activePopup.hidePopup(function(){el.hideFader()});
				return false;
			});
			//esc event
			$(document).keydown(function (e) {
				if (e.keyCode == 27) {
					if (pvlightbox.prototype.activePopup == false) el.hideFader()
					else pvlightbox.prototype.activePopup.hidePopup(function(){el.hideFader()});
					return false;
				}
			});
			//minWidth
			pvlightbox.prototype.minWidth = $('body').css('min-width');
			if (pvlightbox.prototype.minWidth == '0px' || typeof(pvlightbox.prototype.minWidth) == 'undefined') {
				if (el.options.wrapper) {
					pvlightbox.prototype.wrapper = $(el.options.wrapper);
					pvlightbox.prototype.minWidth = $(el.options.wrapper).outerWidth();
				}
			}
			pvlightbox.prototype.minWidth = parseInt(pvlightbox.prototype.minWidth);
		}
		if ($.browser.msie && $.browser.version < 7) {
			el.popupSelects = $('select',el.popup);
			pvlightbox.prototype.selects = pvlightbox.prototype.selects.not(el.popupSelects);
		}
		//open event
		link.click(function(){
			if (pvlightbox.prototype.activePopup == el) {return false;}
			if (pvlightbox.prototype.activePopup) {
				pvlightbox.prototype.activePopup.hidePopup(function(){
					el.showPopup()
					el.positioning(true);
				});
			} else {
				el.showFader(function(){el.showPopup()});
				el.positioning(true);
			} 
			return false;
		});
		//close event
		el.closer.click(function(){
			el.hidePopup(function(){el.hideFader()});
			return false;
		});
		//resize event
		$(window).resize(function(){
			if (el.popup.visible) el.positioning(false);
		});
		if (el.options.scroll) {
			$(window).scroll(function(){
				el.positioning(true);
			});
		}
	},
	showPopup:function(){
		var el = this;
		el.popup.visible = true;
		pvlightbox.prototype.activePopup = el;
		if ($.browser.msie && el.options.IE) el.popup.css({visibility:'visible'})
		else el.popup.stop().css({'visibility':'visible'}).animate({opacity:1},el.options.fadeSpeed)
	},
	hidePopup:function(callback){
		var el = this;
		if ($.browser.msie && el.options.IE) {
			el.popup.css({left:'-9999px',top:'-9999px',visibility:'hidden'});
			el.popup.visible = false;
			pvlightbox.prototype.activePopup = false;
			if ($.isFunction(callback)) callback();
		} else {
			el.popup.stop().animate({opacity:0},el.options.fadeSpeed,function(){
				el.popup.css({left:'-9999px',top:'-9999px',visibility:'hidden'});
				el.popup.visible = false;
				pvlightbox.prototype.activePopup = false;
				if ($.isFunction(callback)) callback();
			});
		}
	},
	showFader:function(callback){
		var el = this;
		el.fader.stop().css({display:'block'}).animate({opacity:0.73},el.options.fadeSpeed,function(){
			if ($.isFunction(callback)) callback();
		});
		if ($.browser.msie && $.browser.version < 7) pvlightbox.prototype.selects.css({'visibility': 'hidden'});
	},
	hideFader:function(){
		var el = this;
		el.fader.stop().animate({opacity:0},el.options.fadeSpeed,function(){
			el.fader.css({display:'none'});
			if ($.browser.msie && $.browser.version < 7) pvlightbox.prototype.selects.css({'visibility': 'visible'});
		});
	},
	positioning:function(openFlag){
		var el = this;
		//x offset
		var windowW = $(window).width();
		var popupW = el.popup.outerWidth();
		if (windowW < pvlightbox.prototype.minWidth) {
			el.popup.css({left:pvlightbox.prototype.minWidth/2-popupW/2})
			el.fader.css({width:pvlightbox.prototype.minWidth});
		} else {
			 el.popup.css({left:windowW/2-popupW/2});
			 el.fader.css({width:windowW})
		}
		//y offset
		var docH = $(document).height();
		var popupH = el.popup.outerHeight();
		if (openFlag) {
			var windowH = $(window).height();
			var popupH = el.popup.outerHeight();
			if (popupH < windowH) el.popup.css({top:windowH/2-popupH/2+$(window).scrollTop()});
			else if ($(window).scrollTop()+popupH > docH){
				el.popup.css({top:docH-popupH});
			} else {
				el.popup.css({top:$(window).scrollTop()});
			}
		}
		el.fader.css({height:docH});
	}
}

// custom forms 

var _selectHeight = 23;

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 selectText = "please select";

function is_mac() {
	if (navigator.appVersion.indexOf("Safari") != -1)
	{
		if(!window.getComputedStyle)
		{
			return true;
		}
	}
	
	return false;
}

function initCastomForms() {
	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() {
	var _frms = document.getElementsByTagName("form");
	for (var nf = 0; nf < _frms.length; nf++) {
		if(_frms[nf].className.indexOf("default") == -1) {
			var a = document.forms[nf].getElementsByTagName("input");
			for(var nfi = 0; nfi < a.length; nfi++) {
				inputs.push(a[nfi]);
			}
			var b = document.forms[nf].getElementsByTagName("label");
			for(var nfl = 0; nfl < b.length; nfl++) {
				labels.push(b[nfl]);
			}
			var c = document.forms[nf].getElementsByTagName("select");
			for(var nfs = 0; nfs < c.length; nfs++) {
				selects.push(c[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";
			radioLabels[q].className += "radioAreaCheckedLabel"
		}
		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";
			radioLabels[q].className = radioLabels[q].className.replace("radioAreaCheckedLabel", "");
		}
	}
	what.className = "radioAreaChecked";
	radioLabels[who].className += " radioAreaCheckedLabel";
}

//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";
			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 = 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;
		checkboxLabels[who].className += " checkboxAreaCheckedLabel";
	}
	if(action == false) {
		what.className = "checkboxArea";
		what.checked = false;
		checkboxLabels[who].className = checkboxLabels[who].className.replace("checkboxAreaCheckedLabel", "");
	}
}

//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].className.indexOf("default") == -1)
	{
		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 optionsListParent = document.createElement("div");
		optionsListParent.className = "select-center";
		var optionsList = document.createElement("ul");
		optionsDiv.innerHTML += "<div class='select-top'><div class='select-top-left'></div><div class='select-top-right'></div></div>";
		optionsListParent.appendChild(optionsList);
		optionsDiv.appendChild(optionsListParent);
		
		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++) {
		if(me.options[w].title.indexOf("title") == -1) {
			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);
			}
		}
		else 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";
			_active.className = _active.className.replace('selectAreaActive','');
		}
		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';
			divArea.className += ' selectAreaActive';
			_active = divArea;
			
			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";
			divArea.className = divArea.className.replace('selectAreaActive','');
		}
		
		// 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);
		}*/
}
_active = false;
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.className = _active.className.replace('selectAreaActive','');
			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;
}


function initPage()
{
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
}
function clearFormFields(o)
{
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filter) o.filter = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text" || inputs[i].type == "password") && inputs[i].className.indexOf(o.filterClass)) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass)) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}


// hover for IE6
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 u=k(){9 g=/^([^#.>`]*)(#|\\.|\\>|\\`)(.+)$/;k u(a,b){9 c=a.J(/\\s*\\,\\s*/);9 d=[];n(9 i=0;i<c.l;i++){d=d.v(o(c[i],b))};6 d};k o(a,b,c){a=a.z(" ","`");9 d=a.r(g);9 e,5,m,7,i,h;9 f=[];4(d==8){d=[a,a]};4(d[1]==""){d[1]="*"};4(c==8){c="`"};4(b==8){b=E};K(d[2]){w"#":7=d[3].r(g);4(7==8){7=[8,d[3]]};e=E.L(7[1]);4(e==8||(d[1]!="*"&&!x(e,d[1]))){6 f};4(7.l==2){f.A(e);6 f};6 o(7[3],e,7[2]);w".":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};7=d[3].r(g);4(7!=8){4(e.j==8||e.j.r("(\\\\s|^)"+7[1]+"(\\\\s|$)")==8){q};m=o(7[3],e,7[2]);f=f.v(m)}y 4(e.j!=8&&e.j.r("(\\\\s|^)"+d[3]+"(\\\\s|$)")!=8){f.A(e)}};6 f;w">":4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};m=o(d[3],e,">");f=f.v(m)};6 f;w"`":5=p(b,d[1]);n(i=0,h=5.l;i<h;i++){e=5[i];m=o(d[3],e,"`");f=f.v(m)};6 f;M:4(c!=">"){5=p(b,d[1])}y{5=b.B};n(i=0,h=5.l;i<h;i++){e=5[i];4(e.C!=1){q};4(!x(e,d[1])){q};f.A(e)};6 f}};k p(a,b){4(b=="*"&&a.F!=8){6 a.F};6 a.p(b)};k x(a,b){4(b=="*"){6 N};6 a.O.G().z("P:","")==b.G()};6 u}();k Q(a,b){9 c=u(a);n(9 i=0;i<c.l;i++){c[i].R=k(){4(t.j.H(b)==-1){t.j+=" "+b}};c[i].S=k(){4(t.j.H(b)!=-1){t.j=t.j.z(b,"")}}}}4(D.I&&!D.T){D.I("U",V)}',58,58,'||||if|listNodes|return|subselector|null|var||||||||limit||className|function|length|listSubNodes|for|doParse|getElementsByTagName|continue|match||this|parseSelector|concat|case|matchNodeNames|else|replace|push|childNodes|nodeType|window|document|all|toLowerCase|indexOf|attachEvent|split|switch|getElementById|default|true|nodeName|html|hoverForIE6|onmouseover|onmouseout|opera|onload|ieHover'.split('|'),0,{}))
/*parametrs [selector, hover_class]*/
function ieHover() {
	hoverForIE6("#nav li, .topiclist li, .size input.submit", "hover");
}
