//page init
$(function () {
    initOpenClose();
    initClearInputs();
    initCustomForms();
    initGalleries();
});

// open-close init
function initOpenClose() {
    jQuery('div.slide-area').OpenClose({
        activeClass: 'active',
        opener: 'a.opener',
        slider: 'div.slide-section',
        effect: 'slide',
        animSpeed: 500
    });
}

// init clear inputs
function initClearInputs() {
    clearFormFields({
        clearInputs: true,
        clearTextareas: true,
        passwordFieldText: true,
        addClassFocus: "focus",
        filterClass: "default"
    });
}

// init carousel
function initGalleries() {
    $('.gallery').scrollGallery({
        autoRotation: true,
        switchTime: 5000,
        duration: 650
    });
    $('.slideshow').fadeGallery({
        autoRotation: true,
        switchTime: 5000,
        duration: 650
    });
}

// slideshow plugin
jQuery.fn.fadeGallery = function (_options) {
    var _options = jQuery.extend({
        slideElements: '.slides > li',
        pagerLinks: 'ul.switcher li',
        btnNext: 'a.next',
        btnPrev: 'a.prev',
        btnPlayPause: 'a.play-pause',
        btnPlay: 'a.play',
        btnPause: 'a.pause',
        pausedClass: 'paused',
        disabledClass: 'disabled',
        playClass: 'playing',
        activeClass: 'active',
        loadingClass: 'ajax-loading',
        loadedClass: 'slide-loaded',
        dynamicImageLoad: false,
        dynamicImageLoadAttr: 'alt',
        currentNum: false,
        allNum: false,
        startSlide: 0,
        noCircle: false,
        pauseOnHover: true,
        autoRotation: false,
        autoHeight: false,
        onBeforeFade: false,
        onAfterFade: false,
        onChange: false,
        disableWhileAnimating: false,
        switchTime: 3000,
        duration: 650,
        event: 'click'
    }, _options);

    return this.each(function () {
        // gallery options
        if (this.slideshowInit) return; else this.slideshowInit;
        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 _dynamicImageLoad = _options.dynamicImageLoad;
        var _dynamicImageLoadAttr = _options.dynamicImageLoadAttr;
        var _autoRotation = _options.autoRotation;
        var _activeClass = _options.activeClass;
        var _loadingClass = _options.loadingClass;
        var _loadedClass = _options.loadedClass;
        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;
        var _onBeforeFade = _options.onBeforeFade;
        var _onAfterFade = _options.onAfterFade;
        var _disableWhileAnimating = _options.disableWhileAnimating;

        // gallery init
        var _anim = false;
        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) {
                        if (_disableWhileAnimating && _anim) return;
                        _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;
            });
        }

        // dynamic image loading (swap from ATTRIBUTE)
        function loadSlide(slide) {
            if (!slide.hasClass(_loadingClass) && !slide.hasClass(_loadedClass)) {
                var images = slide.find(_dynamicImageLoad); // pass selector here
                var imagesCount = images.length;
                if (imagesCount) {
                    slide.addClass(_loadingClass);
                    images.each(function () {
                        var img = this;
                        img.onload = function () {
                            img.loaded = true;
                            img.onload = null;
                            setTimeout(reCalc, _duration);
                        };
                        img.setAttribute('src', img.getAttribute(_dynamicImageLoadAttr));
                        img.setAttribute(_dynamicImageLoadAttr, '');
                    }).css({ opacity: 0 });

                    function reCalc() {
                        var cnt = 0;
                        images.each(function () {
                            if (this.loaded) cnt++;
                        });
                        if (cnt == imagesCount) {
                            slide.removeClass(_loadingClass);
                            images.animate({ opacity: 1 }, { duration: _duration, complete: function () {
                                if (jQuery.browser.msie && jQuery.browser.version < 9) jQuery(this).css({ opacity: 'auto' });
                            }
                            });
                            slide.addClass(_loadedClass);
                        }
                    }
                }
            }
        }

        // gallery animation
        function prevSlide() {
            if (_disableWhileAnimating && _anim) return;
            _prevIndex = _currentIndex;
            if (_currentIndex > 0) _currentIndex--;
            else {
                if (_noCycle) return;
                else _currentIndex = _slideCount - 1;
            }
            switchSlide();
        }
        function nextSlide() {
            if (_disableWhileAnimating && _anim) return;
            _prevIndex = _currentIndex;
            if (_currentIndex < _slideCount - 1) _currentIndex++;
            else {
                if (_noCycle) return;
                else _currentIndex = 0;
            }
            switchSlide();
        }
        function refreshStatus() {
            if (_dynamicImageLoad) loadSlide(_slides.eq(_currentIndex));
            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, _slides, _prevIndex, _currentIndex);
            }
        }
        function switchSlide() {
            _anim = true;
            if (typeof _onBeforeFade === 'function') _onBeforeFade(_this, _slides, _prevIndex, _currentIndex);
            _slides.eq(_prevIndex).stop().animate({ opacity: 0 }, {
                duration: _duration,
                complete: function () {
                    _anim = false;
                    _slides.eq(_prevIndex).hide();
                }
            });
            _slides.eq(_currentIndex).css({ display: 'block', opacity: 0 }).stop().animate({ opacity: 1 }, {
                duration: _duration,
                complete: function () {
                    if (typeof _onAfterFade === 'function') _onAfterFade(_this, _slides, _prevIndex, _currentIndex);
                }
            });
            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) {
            _pagerLinks.hover(function () {
                _hover = true;
                if (_timer) clearTimeout(_timer);
            }, function () {
                _hover = false;
                autoSlide();
            });
            _this.hover(function () {
                _hover = true;
                if (_timer) clearTimeout(_timer);
            }, function () {
                _hover = false;
                autoSlide();
            });
        }
        refreshStatus();
        autoSlide();
    });
};
// scrolling gallery plugin
jQuery.fn.scrollGallery = function (_options) {
    var _options = jQuery.extend({
        sliderHolder: '>div',
        slider: '>ul',
        slides: '>li',
        pagerLinks: 'div.pager a',
        btnPrev: 'a.prev',
        btnNext: 'a.next',
        activeClass: 'active',
        disabledClass: 'disabled',
        generatePagination: 'div.pg-holder',
        curNum: 'em.scur-num',
        allNum: 'em.sall-num',
        circleSlide: true,
        pauseClass: 'gallery-paused',
        pauseButton: 'none',
        pauseOnHover: true,
        autoRotation: false,
        stopAfterClick: false,
        switchTime: 5000,
        duration: 650,
        easing: 'swing',
        event: 'click',
        splitCount: false,
        afterInit: false,
        vertical: false,
        step: false
    }, _options);

    return this.each(function () {
        // gallery options
        var _this = jQuery(this);
        var _sliderHolder = jQuery(_options.sliderHolder, _this);
        var _slider = jQuery(_options.slider, _sliderHolder);
        var _slides = jQuery(_options.slides, _slider);
        var _btnPrev = jQuery(_options.btnPrev, _this);
        var _btnNext = jQuery(_options.btnNext, _this);
        var _pagerLinks = jQuery(_options.pagerLinks, _this);
        var _generatePagination = jQuery(_options.generatePagination, _this);
        var _curNum = jQuery(_options.curNum, _this);
        var _allNum = jQuery(_options.allNum, _this);
        var _pauseButton = jQuery(_options.pauseButton, _this);
        var _pauseOnHover = _options.pauseOnHover;
        var _pauseClass = _options.pauseClass;
        var _autoRotation = _options.autoRotation;
        var _activeClass = _options.activeClass;
        var _disabledClass = _options.disabledClass;
        var _easing = _options.easing;
        var _duration = _options.duration;
        var _switchTime = _options.switchTime;
        var _controlEvent = _options.event;
        var _step = _options.step;
        var _vertical = _options.vertical;
        var _circleSlide = _options.circleSlide;
        var _stopAfterClick = _options.stopAfterClick;
        var _afterInit = _options.afterInit;
        var _splitCount = _options.splitCount;

        // gallery init
        if (!_slides.length) return;

        if (_splitCount) {
            var curStep = 0;
            var newSlide = $('<slide>').addClass('split-slide');
            _slides.each(function () {
                newSlide.append(this);
                curStep++;
                if (curStep > _splitCount - 1) {
                    curStep = 0;
                    _slider.append(newSlide);
                    newSlide = $('<slide>').addClass('split-slide');
                }
            });
            if (curStep) _slider.append(newSlide);
            _slides = _slider.children();
        }

        var _currentStep = 0;
        var _sumWidth = 0;
        var _sumHeight = 0;
        var _hover = false;
        var _stepWidth;
        var _stepHeight;
        var _stepCount;
        var _offset;
        var _timer;

        _slides.each(function () {
            _sumWidth += $(this).outerWidth(true);
            _sumHeight += $(this).outerHeight(true);
        });

        // calculate gallery offset
        function recalcOffsets() {
            if (_vertical) {
                if (_step) {
                    _stepHeight = _slides.eq(_currentStep).outerHeight(true);
                    _stepCount = Math.ceil((_sumHeight - _sliderHolder.height()) / _stepHeight) + 1;
                    _offset = -_stepHeight * _currentStep;
                } else {
                    _stepHeight = _sliderHolder.height();
                    _stepCount = Math.ceil(_sumHeight / _stepHeight);
                    _offset = -_stepHeight * _currentStep;
                    if (_offset < _stepHeight - _sumHeight) _offset = _stepHeight - _sumHeight;
                }
            } else {
                if (_step) {
                    _stepWidth = _slides.eq(_currentStep).outerWidth(true) * _step;
                    _stepCount = Math.ceil((_sumWidth - _sliderHolder.width()) / _stepWidth) + 1;
                    _offset = -_stepWidth * _currentStep;
                    if (_offset < _sliderHolder.width() - _sumWidth) _offset = _sliderHolder.width() - _sumWidth;
                } else {
                    _stepWidth = _sliderHolder.width();
                    _stepCount = Math.ceil(_sumWidth / _stepWidth);
                    _offset = -_stepWidth * _currentStep;
                    if (_offset < _stepWidth - _sumWidth) _offset = _stepWidth - _sumWidth;
                }
            }
        }

        // gallery control
        if (_btnPrev.length) {
            _btnPrev.bind(_controlEvent, function () {
                if (_stopAfterClick) stopAutoSlide();
                prevSlide();
                return false;
            });
        }
        if (_btnNext.length) {
            _btnNext.bind(_controlEvent, function () {
                if (_stopAfterClick) stopAutoSlide();
                nextSlide();
                return false;
            });
        }
        if (_generatePagination.length) {
            _generatePagination.empty();
            recalcOffsets();
            var _list = $('<ul />');
            for (var i = 0; i < _stepCount; i++) $('<li><a href="#">' + (i + 1) + '</a></li>').appendTo(_list);
            _list.appendTo(_generatePagination);
            _pagerLinks = _list.children();
        }
        if (_pagerLinks.length) {
            _pagerLinks.each(function (_ind) {
                jQuery(this).bind(_controlEvent, function () {
                    if (_currentStep != _ind) {
                        if (_stopAfterClick) stopAutoSlide();
                        _currentStep = _ind;
                        switchSlide();
                    }
                    return false;
                });
            });
        }

        // gallery animation
        function prevSlide() {
            recalcOffsets();
            if (_currentStep > 0) _currentStep--;
            else if (_circleSlide) _currentStep = _stepCount - 1;
            switchSlide();
        }
        function nextSlide() {
            recalcOffsets();
            if (_currentStep < _stepCount - 1) _currentStep++;
            else if (_circleSlide) _currentStep = 0;
            switchSlide();
        }
        function refreshStatus() {
            if (_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
            if (!_circleSlide) {
                _btnPrev.removeClass(_disabledClass);
                _btnNext.removeClass(_disabledClass);
                if (_currentStep == 0) _btnPrev.addClass(_disabledClass);
                if (_currentStep == _stepCount - 1) _btnNext.addClass(_disabledClass);
            }
            if (_curNum.length) _curNum.text(_currentStep + 1);
            if (_allNum.length) _allNum.text(_stepCount);
        }
        function switchSlide() {
            recalcOffsets();
            if (_vertical) _slider.animate({ marginTop: _offset }, { duration: _duration, queue: false, easing: _easing });
            else _slider.animate({ marginLeft: _offset }, { duration: _duration, queue: false, easing: _easing });
            refreshStatus();
            autoSlide();
        }

        // autoslide function
        function stopAutoSlide() {
            if (_timer) clearTimeout(_timer);
            _autoRotation = false;
        }
        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();
            });
        }
        recalcOffsets();
        refreshStatus();
        autoSlide();

        // pause buttton
        if (_pauseButton.length) {
            _pauseButton.click(function () {
                if (_this.hasClass(_pauseClass)) {
                    _this.removeClass(_pauseClass);
                    _autoRotation = true;
                    autoSlide();
                } else {
                    _this.addClass(_pauseClass);
                    stopAutoSlide();
                }
                return false;
            });
        }

        if (_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
    });
};
// open-close plugin
jQuery.fn.OpenClose = function (_options) {
    // default options
    var _options = jQuery.extend({
        activeClass: 'active',
        opener: '.opener',
        slider: '.slide',
        animSpeed: 400,
        animStart: false,
        animEnd: false,
        effect: 'fade',
        event: 'click'
    }, _options);

    return this.each(function () {
        // options
        var _holder = jQuery(this);
        var _slideSpeed = _options.animSpeed;
        var _activeClass = _options.activeClass;
        var _opener = jQuery(_options.opener, _holder);
        var _slider = jQuery(_options.slider, _holder);
        var _animStart = _options.animStart;
        var _animEnd = _options.animEnd;
        var _effect = _options.effect;
        var _event = _options.event;
        if (_slider.length) {
            _opener.bind(_event, function () {
                if (!_slider.is(':animated')) {
                    if (typeof _animStart === 'function') _animStart();
                    if (_holder.hasClass(_activeClass)) {
                        _slider[_effect == 'fade' ? 'fadeOut' : 'slideUp'](_slideSpeed, function () {
                            if (typeof _animEnd === 'function') _animEnd();
                        });
                        _holder.removeClass(_activeClass);
                    } else {
                        _holder.addClass(_activeClass);
                        _slider[_effect == 'fade' ? 'fadeIn' : 'slideDown'](_slideSpeed, function () {
                            if (typeof _animEnd === 'function') _animEnd();
                        });
                    }
                }
                return false;
            });
            if (_holder.hasClass(_activeClass)) _slider.show();
            else _slider.hide();
        }
    });
};
// clear inputs
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].title;
                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].title;
                    fakeInput.className = inputs[i].className;
                    fakeInput.fake = true;
                    inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
                    if (inputs[i].value == "") {
                        inputsSwap(inputs[i], null);
                    }
                    else {
                        fakeInput.style.display = "none";
                    }
                }
                if (inputs[i].value == "") {
                    inputs[i].value = inputs[i].valueHtml;
                }
            }
        }
    }
    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";
    }
}

// custom forms script
var maxVisibleOptions = 20;
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.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;
    }
}

