jQuery(function () {
    clearInputs();
    initGallery();
    initFadeDrop();
    initCustomForms();

});
$(document).ready(function () {

    $("a#lnkfeedback").fancybox({
        'width': 880,
        'height': 450,
        'margin': 0,
        'padding': 0,

        'transitionIn': 'none',
        'transitionOut': 'none',
        'titleShow': false,
        'scrolling': 'no'

    });
    $("a#lnkfeedbackHeader").fancybox({
        'width': 880,
        'height': 450,
        'margin': 0,
        'padding': 0,

        'transitionIn': 'none',
        'transitionOut': 'none',
        'titleShow': false,
        'scrolling': 'no'

    });
    $("a#lnkfeedbackImage").fancybox({
        'width': 880,
        'height': 450,
        'margin': 0,
        'padding': 0,

        'transitionIn': 'none',
        'transitionOut': 'none',
        'titleShow': false,
        'scrolling': 'no'

    });

    $("a#newsletter").fancybox({
        'width': 320,
        'height': 280,
        'margin': 0,
        'padding': 0,

        'transitionIn': 'none',
        'transitionOut': 'none',
        'titleShow': false,
        'scrolling': 'no'

    });

    $("a#embed").fancybox({
        frameWidth: 620,
        frameHeight: 400,
        overlayShow: true,
        overlayOpacity: 0.9,
        overlayColor: '#000',
        type: 'iframe'
    });

    /********* Fancybox for image gallery *********/
    function formatTitle(title, currentArray, currentIndex, currentOpts) {
        return '<div id="gallery-title">' + (title && title.length ? '<b>' + title + '</b>' : '') + 'Bilde ' + (currentIndex + 1) + ' av ' + currentArray.length + '</div>';
    }

    function fancyboxStart() { $('embed, object, select').css('visibility', 'hidden'); }
    function fancyboxEnd() { $('embed, object, select').css({ 'visibility': 'visible' }); }
    $("a.grouped_elements").fancybox({
        'onStart': fancyboxStart,
        'onClosed': fancyboxEnd,
        /* 'showCloseButton': false,*/
        'titlePosition': 'inside',
        'speedIn': 600,
        'speedOut': 200,
        'overlayOpacity': 0.7,
        'overlayColor': '#777',
        'titleFormat': formatTitle

    });
    /********* Fancybox for image gallery *********/
});

// init fade drop
function initFadeDrop() {
    var dur = 350; //ms
    //	var defColor = '#fff6c5';
    var rollColor = '#333333';
    var linkRollColor = '#f4f4f4';
    var activeClass = "hover"
    jQuery('#nav > li').each(function () {
        var hold = jQuery(this);
        var link = hold.find('>a');
        var drop = hold.find('>ul');
        hold.css({ backgroundColor: defColor });
        drop.css({ opacity: 0 }).hide();
        hold.mouseenter(function () {
            hold.addClass(activeClass).stop().animate({ backgroundColor: rollColor }, { duration: dur, queue: false });
            link.stop().animate({ color: linkRollColor }, { duration: dur, queue: false });
            drop.show().stop().animate({ opacity: 1 }, { duration: dur, queue: false });
        }).mouseleave(function () {
            link.stop().animate({ color: rollColor }, { duration: dur, queue: false });
            hold.stop().animate({ backgroundColor: defColor }, { duration: dur, queue: false });
            drop.show().stop().animate({ opacity: 0 }, { duration: dur, queue: false, complete: function () {
                hold.removeClass(activeClass);
                drop.hide();
            }
            })
        });
    });
};

// init gallery
function initGallery() {
    jQuery('ul.fade-gallery, ul.fade-gallery2, ul.fade-gallery3').fadeGallery({
        pauseOnHover: true,
        autoRotation: true,
        switchTime: 3000 //ms
    });
    jQuery('div.carousel').galleryCircle({
        switchTime: 3000 //ms
    });
};

// clear inputs
function clearInputs() {
    clearFormFields({
        clearInputs: true,
        clearTextareas: true,
        passwordFieldText: false,
        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.filterClass) o.filterClass = "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) == -1) {
                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) == -1) {
                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";
    }
}

// slideshow plugin
jQuery.fn.fadeGallery = function (_options) {
    var _options = jQuery.extend({
        slideElements: '>li',
        pagerGener: true,
        pagerHold: false,
        pagerLinks: 'ul.nav-list li',
        btnNext: 'a.btn-next',
        btnPrev: 'a.btn-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,
        caption: 'ul.caption > li',
        pauseOnHover: false,
        autoRotation: false,
        autoHeight: false,
        onChange: false,
        switchTime: 3000,
        duration: 800,
        event: 'click'
    }, _options);

    return this.each(function () {
        // gallery options
        var _this = jQuery(this);
        var _slides = jQuery(_options.slideElements, _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;
        var _pagerGener = _options.pagerGener;
        var _pagerHold = jQuery(_options.pagerHold, _this);
        var _caption = jQuery(_options.caption, _this);
        var _paging = '';
        if (_pagerGener) {
            for (var i = 0; i < _slides.length; i++) {
                _paging += '<li><a href="#">' + (i + 1) + '</a></li>';
            }
            _pagerHold.html('<ul>' + _paging + '</ul>');
        }
        var _pagerLinks = jQuery(_options.pagerLinks, _this);
        // 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();
        _caption.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);
            _caption.eq(_prevIndex).fadeOut();
            _caption.eq(_currentIndex).fadeIn();
            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();
    });
};





// gallery function
jQuery.fn.galleryCircle = function (_options) {
    // defaults options
    var _options = jQuery.extend({
        btPrev: 'a.link-prev',
        btNext: 'a.link-next',
        holderList: 'div.mask',
        scrollElParent: '>ul',
        scrollEl: '>li',
        numHolder: false,
        numCreate: false,
        step: 1,
        innerMargin: 0,
        curPage: false,
        onClick: null,
        easing: 'swing',
        switchTime: false,
        duration: 800
    }, _options);

    return this.each(function () {
        var _this = jQuery(this);
        var _next = jQuery(_options.btNext, _this).length ? jQuery(_options.btNext, _this) : false;
        var _prev = jQuery(_options.btPrev, _this).length ? jQuery(_options.btPrev, _this) : false;
        var _holderList = jQuery(_options.holderList, _this);
        var _scrollElParent = jQuery(_options.scrollElParent, _holderList);
        var _scrollEl = jQuery(_options.scrollEl, _scrollElParent);
        var _numHolder = false;
        if (_options.numHolder) _numHolder = jQuery(_options.numHolder, _this).length ? jQuery(_options.numHolder, _this) : false;
        var _step, _t = null;
        var _widthSum = 0;
        _scrollEl.each(function () { _widthSum += jQuery(this).outerWidth(true); })
        var _startPosition = _scrollEl.index(_scrollEl.filter('.active'));
        if (_startPosition == -1) _startPosition = 0;
        _scrollEl.removeClass('active');
        var _easing = _options.easing;

        if (!_options.step) _step = _holderList.innerWidth();
        var _margin = _widthSum;
        _scrollElParent.append(_scrollEl.clone(true));
        _scrollElParent.prepend(_scrollEl.clone(true));

        var _offsetStartPosition = 0;
        _offsetStartPosition = culcOffset(_startPosition);

        _scrollElParent.css('marginLeft', (-_margin + _options.innerMargin - _offsetStartPosition));

        //auto rotation
        if (_options.switchTime) {
            _t = setTimeout(function () {
                nextSlides();
            }, _options.switchTime);
        }

        //button next "click"
        if (_next) {
            _next.click(function () {
                if (!_scrollElParent.is(':animated')) {
                    if (jQuery.isFunction(_options.onClick)) _options.onClick.apply(_this);
                    nextSlides();
                }
                return false;
            });
        }

        //button prev "click"
        if (_prev) {
            _prev.click(function () {
                if (!_scrollElParent.is(':animated')) {
                    if (jQuery.isFunction(_options.onClick)) _options.onClick.apply(_this);
                    prevSlides();
                }
                return false;
            });
        }

        //curent position
        function getCurElIndex() {
            var _curMargin = parseInt(_scrollElParent.css('marginLeft')) + _widthSum - _options.innerMargin;
            for (i = 0; i < _scrollEl.length; i++) {
                if (_curMargin == 0) return i;
                if (_curMargin <= _options.innerMargin) _curMargin += _scrollEl.eq(i).innerWidth();
                else _curMargin -= _scrollEl.eq(i).innerWidth();
                if (_curMargin == _options.innerMargin) return i + 1;
            }
        }

        // offset of gallery if when activ element not first at start 
        function culcOffset(_ind) {
            var _tmpcounter = 0;
            var _pos = 0;
            while (_tmpcounter < _ind) {
                _pos += _scrollEl.eq(_tmpcounter).outerWidth(true);
                _tmpcounter++;
            };
            return _pos;
        }

        //go next slide
        function nextSlides() {
            if (_t) clearTimeout(_t);
            if (_options.step) {
                _curElIndex = getCurElIndex();
                _step = _scrollEl.eq(_curElIndex).innerWidth();
            };
            _margin = -parseInt(_scrollElParent.css('marginLeft'));
            _margin += _step;

            _scrollElParent.animate({ 'marginLeft': (-_margin + _options.innerMargin) }, { duration: _options.duration, easing: _easing, complete: function () {
                if (_margin >= _widthSum * 2) {
                    _margin = _widthSum + (_margin - _widthSum * 2);
                }
                _scrollElParent.css({ 'marginLeft': -_margin + _options.innerMargin });
                jQuery.fn.galleryCircle.numListActive(_numHolder, _scrollEl);

                //autoslide
                if (_options.switchTime) {
                    _t = setTimeout(function () {
                        nextSlides();
                    }, _options.switchTime)
                }
            }
            });
        }

        //go prev slide
        function prevSlides() {
            if (_t) clearTimeout(_t);
            if (_options.step) {
                _curElIndex = getCurElIndex();
                if (_curElIndex == 0) _curElIndex = _scrollEl.length;
                _step = _scrollEl.eq(_curElIndex - 1).innerWidth();
            };
            _margin = -parseInt(_scrollElParent.css('marginLeft'));
            _margin -= _step;
            _scrollElParent.animate({ 'marginLeft': (-_margin + _options.innerMargin) }, { duration: _options.duration, easing: _easing, complete: function () {
                if (_margin < _widthSum) {
                    _margin = _widthSum * 2 - (_widthSum - _margin);
                }
                _scrollElParent.css({ 'marginLeft': -_margin + _options.innerMargin });
                jQuery.fn.galleryCircle.numListActive(_numHolder, _scrollEl);

                //autoslide
                if (_options.switchTime) {
                    _t = setTimeout(function () {
                        nextSlides();
                    }, _options.switchTime)
                }
            }
            });
        }

        // Number list Create
        jQuery.fn.galleryCircle.numListCreate = function (_numHolder, _scrollEl) {
            var _numListElC = '';
            for (var i = 0; i < _scrollEl.length; i++) {
                _numListElC += '<li><a href="">' + (i + 1) + '</a></li>';
            }
            jQuery(_numHolder).html('<ul>' + _numListElC + '</ul>');
        };

        // Number list Activate
        jQuery.fn.galleryCircle.numListActive = function (_numHolder, _scrollEl) {
            _curElIndex = getCurElIndex();
            if (jQuery(_options.curPage, _this).length && _options.curPage) jQuery(_options.curPage, _this).text('Pagina ' + (getCurElIndex() + 1) + '/' + _scrollEl.length);
            if (_numHolder) {
                jQuery('a', _numHolder).removeClass('active');
                jQuery('a', _numHolder).eq(_curElIndex).addClass('active');
            }
        };

        //click on control elemens
        function numClick() {
            jQuery(_options.numHolder, _this).find('a').click(function () {
                if (_t) clearTimeout(_t);
                var _aList = jQuery(_options.numHolder, _this).find('a');
                var _index = _aList.index(jQuery(this));
                _margin = _widthSum + _index * _scrollEl.outerWidth(true);
                _scrollElParent.animate({ 'marginLeft': (-_margin + _options.innerMargin) }, { duration: _options.duration, easing: _easing, complete: function () {
                    if (_margin >= _widthSum * 2) {
                        _margin = _widthSum + (_margin - _widthSum * 2);
                    }
                    _scrollElParent.css({ 'marginLeft': -_margin + _options.innerMargin });
                    _aList.removeClass('active').eq(_index).addClass('active');

                    //autoslide
                    if (_options.switchTime) {
                        _t = setTimeout(function () {
                            nextSlides();
                        }, _options.switchTime)
                    }
                }
                });
                return false;
            });
        };

        // init creating num list
        if (_options.numCreate) jQuery.fn.galleryCircle.numListCreate(_numHolder, _scrollEl);

        // pagination first init (example Page 2/6)
        if (jQuery(_options.curPage, _this).length && _options.curPage) jQuery(_options.curPage, _this).text('Pagina ' + (getCurElIndex() + 1) + '/' + _scrollEl.length);

        // init activate num list item and init numClick()
        if (_options.numHolder) {
            jQuery.fn.galleryCircle.numListActive(_numHolder, _scrollEl);
            numClick();
        }
    });
}

// init custom forms
var _selectHeight = 34;
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 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() {
    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";
            if (radioLabels[q]) {
                radioLabels[q].className += "radioAreaCheckedLabel"
            }

        }
        else {
            radioArea.className = "radioArea";
        }
        radioArea.id = "myRadio" + q;

      //  if (radios[q].onclick != null)
       //     radioArea.setAttribute('onclick', 'Test()');
        radios[q].parentNode.insertBefore(radioArea, radios[q]);
        radios[q]._ra = radioArea;

       if ( radios[q].onclick != null)
           radioArea.onclick = new Function('rechangeRadios(' + q + '); radios[' + q + '].onclick();');
       else
           radioArea.onclick = new Function('rechangeRadios(' + q + ')');
       
   /*     $(radioArea).click(function () {
            rechangeRadios(q);
            if (radios[q].onclick != null) {
                radios[q].click();
            }
        });
        */
        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";
            if (radioLabels[q]) {
                radioLabels[q].className = radioLabels[q].className.replace("radioAreaCheckedLabel", "");
            }
        }
    }
    what.className = "radioAreaChecked";
    if (radioLabels[who])
        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) {
                if (radios[q].id != radios[who].id)
                    radios[q].checked = false;
                else {
                    radios[who].checked = true;
                    checkRadios(who);
                }


            }


        }
        /*   if (radios[q].checked == true) {
        var index = radios[q].outerHTML.indexOf('class=\"');
        radios[q].outerHTML = radios[q].outerHTML.substring(0, index) + " checked=\"true\" " + radios[q].outerHTML.substring(index);

        }*/

    }
}

//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 = checkboxArea.onclick2 = new Function('rechangeCheckboxes(' + q + ')');
        if (!checkboxes[q].disabled) {
            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 (checkboxLabels[who])
            checkboxLabels[who].className += " checkboxAreaCheckedLabel";
    }
    if (action == false) {
        what.className = "checkboxArea";
        what.checked = false;
        if (checkboxLabels[who])
            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);

    if (checkboxes[who].className.indexOf('brosjyre') == -1)
        __doPostBack('__Page', 'MyCustomArgument');
    else if (checkboxes[who].checked == true) {
        var index = checkboxes[who].outerHTML.indexOf('class=\"');
        checkboxes[who].outerHTML = checkboxes[who].outerHTML.substring(0, index) + " checked=\"true\" " + checkboxes[who].outerHTML.substring(index);

    }

}

//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;

            if (selects[q].className == "garageLength" || selects[q].className == "garageWidth")
                center.className = "center " + selects[q].className;
            else
                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 optionsListParent2 = document.createElement("div");
            optionsListParent2.className = "select-center-right";
            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(optionsListParent2);
            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;
            if (selectField.className.indexOf('garageWidth') > -1) {
                $("#ctl00_cphContent_hfWidth").val(selectField.options[k].text);
                $("#ctl00_cphContent_hfWidthFactor").val(selectField.options[k].value);
            }
            else if (selectField.className.indexOf('garageLength') > -1) {
                $("#ctl00_cphContent_hfLength").val(selectField.options[k].text);
                $("#ctl00_cphContent_hfLengthFactor").val(selectField.options[k].value);
            }
        }
        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;
}

/*!
* Color animation jQuery-plugin
* http://www.bitstorm.org/jquery/color-animation/
* Copyright 2011 Edwin Martin <edwin@bitstorm.org>
* Released under the MIT and GPL licenses.
*/
; (function (d) {
    function i() { var b = d("script:first"), a = b.css("color"), c = false; if (/^rgba/.test(a)) c = true; else try { c = a != b.css("color", "rgba(0, 0, 0, 0.5)").css("color"); b.css("color", a) } catch (e) { } return c } function g(b, a, c) { var e = "rgb" + (d.support.rgba ? "a" : "") + "(" + parseInt(b[0] + c * (a[0] - b[0]), 10) + "," + parseInt(b[1] + c * (a[1] - b[1]), 10) + "," + parseInt(b[2] + c * (a[2] - b[2]), 10); if (d.support.rgba) e += "," + (b && a ? parseFloat(b[3] + c * (a[3] - b[3])) : 1); e += ")"; return e } function f(b) {
        var a, c; if (a = /#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/.exec(b)) c =
[parseInt(a[1], 16), parseInt(a[2], 16), parseInt(a[3], 16), 1]; else if (a = /#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/.exec(b)) c = [parseInt(a[1], 16) * 17, parseInt(a[2], 16) * 17, parseInt(a[3], 16) * 17, 1]; else if (a = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b)) c = [parseInt(a[1]), parseInt(a[2]), parseInt(a[3]), 1]; else if (a = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([01\.]*)\s*\)/.exec(b)) c = [parseInt(a[1], 10), parseInt(a[2], 10), parseInt(a[3], 10), parseFloat(a[4])]; return c
    }
    d.extend(true, d, { support: { rgba: i()} }); var h = ["color", "backgroundColor", "borderBottomColor", "borderLeftColor", "borderRightColor", "borderTopColor", "outlineColor"]; d.each(h, function (b, a) { d.fx.step[a] = function (c) { if (!c.init) { c.a = f(d(c.elem).css(a)); c.end = f(c.end); c.init = true } c.elem.style[a] = g(c.a, c.end, c.pos) } }); d.fx.step.borderColor = function (b) { if (!b.init) b.end = f(b.end); var a = h.slice(2, 6); d.each(a, function (c, e) { b.init || (b[e] = { a: f(d(b.elem).css(e)) }); b.elem.style[e] = g(b[e].a, b.end, b.pos) }); b.init = true }
})(jQuery);

function initPopups() {
    initPopup({
        popupHolderTag: 'li',
        popupTag: 'div',
        popupHolderClass: 'ico-comment',
        popupClass: 'box-tips',
        linkOpenClass: 'open-tip',
        linkCloseClass: 'btn-close',
        openClass: 'active',
        openEvent: 'click'
    });
}
if (window.addEventListener)
    window.addEventListener("load", initPopups, false);
else if (window.attachEvent)
    window.attachEvent("onload", initPopups);

function initPopup(_popup) {
    if (!_popup.popupHolderTag) _popup.popupHolderTag = 'div';
    if (!_popup.popupTag) _popup.popupTag = 'div';
    if (!_popup.popupHolderClass) _popup.popupHolderClass = 'popup-holder';
    if (!_popup.popupClass) _popup.popupClass = 'popup';
    if (!_popup.linkOpenClass) _popup.linkOpenClass = 'open';
    if (!_popup.linkCloseClass) _popup.linkCloseClass = 'close';
    if (!_popup.openClass) _popup.openClass = 'active';
    if (!_popup.openEvent) _popup.openEvent = 'hover';

    var timer = [];
    var _popupHolderTag = document.getElementsByTagName(_popup.popupHolderTag);
    if (_popupHolderTag) {
        for (var i = 0; i < _popupHolderTag.length; i++) {
            if (_popupHolderTag[i].className.indexOf(_popup.popupHolderClass) != -1) {
                var _popupLink = _popupHolderTag[i].getElementsByTagName('a');
                for (var j = 0; j < _popupLink.length; j++) {
                    _popupLink[j].parent = _popupHolderTag[i];
                    if (_popupLink[j].className.indexOf(_popup.linkOpenClass) != -1) {
                        if (_popup.openEvent == 'click') {
                            _popupLink[j].onclick = function () {
                                if (this.parent.className.indexOf(_popup.openClass) != -1) {
                                    this.parent.className = this.parent.className.replace(_popup.openClass, '');
                                } else {
                                    this.parent.className += ' ' + _popup.openClass;
                                }
                                return false;
                            }
                        } else {
                            var _popupTag = _popupHolderTag[i].getElementsByTagName(_popup.popupTag);
                            for (var k = 0; k < _popupTag.length; k++) {
                                if (_popupTag[k].className.indexOf(_popup.popupClass) != -1) {
                                    _popupTag[k].parent = _popupHolderTag[i];
                                    _popupTag[k].onmouseover = function () {
                                        if (timer[j]) clearTimeout(timer[j]);
                                        if (this.parent.className.indexOf(_popup.openClass) == -1) {
                                            this.parent.className += ' ' + _popup.openClass;
                                        }
                                    }
                                    _popupTag[k].onmouseout = function () {
                                        var _this = this;
                                        timer[j] = setTimeout(function () {
                                            _this.parent.className = _this.parent.className.replace(_popup.openClass, '');
                                        }, 2);
                                    }
                                }
                            }
                            _popupLink[j].onmouseover = function () {
                                if (timer[j]) clearTimeout(timer[j]);
                                if (this.parent.className.indexOf(_popup.openClass) == -1) {
                                    this.parent.className += ' ' + _popup.openClass;
                                }
                            }
                            _popupLink[j].onmouseout = function () {
                                var _this = this;
                                timer[j] = setTimeout(function () {
                                    _this.parent.className = _this.parent.className.replace(_popup.openClass, '');
                                }, 2);
                            }
                        }
                    } else if (_popupLink[j].className.indexOf(_popup.linkCloseClass) != -1) {
                        _popupLink[j].onclick = function () {
                            if (this.parent.className.indexOf(_popup.openClass) != -1) {
                                this.parent.className = this.parent.className.replace(_popup.openClass, '');
                            } else {
                                this.parent.className += ' ' + _popup.openClass;
                            }
                            return false;
                        }
                    }
                }
            }
        }
    }
}

