var hoverTimer;

var thalia={
    timer:null,
    sfEls:null,//Array for 1st level nav elements
    folderRows:null, // Array of folder rows
    currentFolder:null, // currently active folder Object
    newFolder:null,    // last clicked Folder

/**************************************************************************************************
** Initialize Scripts - is this a browser that understands DOM?
**************************************************************************************************/
    scriptInit:function() {
        if (!document.getElementById) {
            return false;
        }else{
            return true;
        }
    },

/************************************************************************************************
** Set up Event Listener - the script that allows us to use the addEvent call below
*************************************************************************************************/

    addEvent:function(elm, evType, fn, useCapture) {
        if ( fn == undefined ) {
            return true;
        }
        if (elm.addEventListener) {
            elm.addEventListener(evType, fn, useCapture);
            return true;
        } else if (elm.attachEvent) {
            var r = elm.attachEvent('on' + evType, fn);
            return r;
        } else {
            elm['on' + evType] = fn;
        }
    },

/***********************************************************************************************
** helper functions:
** $: get object
** getElementsByClass: does what the function name says
** log: logging for ie and firefox
** changeClass: add, remove, swap, check classes for an object
************************************************************************************************/

    $:function() {
        var elements = new Array();
        for (var i = 0; i < arguments.length; i++) {
            var element = arguments[i];
            if (typeof element == 'string'){
                if(document.getElementById(element)){
                    element = document.getElementById(element);
                }
            }
            if (arguments.length == 1){
                if (typeof element == 'object'){
                    return element;
                }else{
                    return false;
                }
            }
            if (typeof element == 'object'){
                elements.push(element);
            }
        }
        return elements;
    },

    getElementsByClass:function(searchClass,node,tag) {
        var classElements = new Array();
        if ( node == null )
            node = document;
        if ( tag == null )
            tag = '*';
        var els = node.getElementsByTagName(tag);
        var elsLen = els.length;

        var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
        for (i = 0, j = 0; i < elsLen; i++) {
            if ( pattern.test(els[i].className) ) {
                classElements[j] = els[i];
                j++;
            }
        }
        return classElements;
    },
    log:function(string){
        if (typeof(console)=="undefined"){
            alert(string);
        }else{
            console.log(string);
        }
    },

/*****************************************************************************************
** This function takes four parameters:
** a defines the action you want the function to perform.
** O the object in question.
** c1 the name of the first class
** c2 the name of the second class
**
** Possible actions are:
** swap replaces class c1 with class c2 in object o.
** add adds class c1 to the object o.
** remove removes class c1 from the object o.
** check tests if class c1 is already applied to object o and returns true or false.
******************************************************************************************/

    changeClass:function(a,o,c1,c2){
        switch(a){
            case 'swap':
                o.className=!thalia.changeClass('check',o,c1)?o.className.replace(c2,c1) : o.className.replace(c1,c2);
            break;
            case 'add':
                if (!thalia.changeClass('check',o,c1)){o.className+=o.className ? ' ' + c1 : c1;}
            break;
            case 'remove':
                var rep=o.className.match(' ' + c1) ? ' ' + c1 : c1;
                o.className = o.className.replace(rep,'');
            break;
            case 'check':
                return new RegExp('\\b' + c1 + '\\b').test(o.className)
            break;
            case 'checkPart':
                return new RegExp(c1).test(o.className)
            break;
        }
    },

    checkRegExp:function(ex,text){
        return new RegExp(ex).test(text)
    },

    parseInputReplaceFields:function(){
        thalia.allReplaceFields = thalia.getElementsByClass('replaceDefaultText',null,'INPUT');
        for (var i=0;i<thalia.allReplaceFields.length;i++){
            thalia.allReplaceFields[i].onfocus = function(){
                if (this.value == this.title){
                    this.value = "";
                }
            }
            thalia.allReplaceFields[i].onblur = function(){
                if (this.value == ""){
                    this.value = this.title
                }
            }
        }
    },

    toggleLayer:function(obj){
        thalia.log("obj.opened: " + obj.opened);
        if (obj.opened){
            thalia.changeClass('swap',obj,'layerClosed','layerOpened');
            thalia.changeClass('remove',obj.toggleLayer,'toggleOpen');
            thalia.changeClass('add',obj.toggleLayer,'toggleClosed')
        }else{
            thalia.changeClass('swap',obj,'layerOpened','layerClosed');
            thalia.changeClass('remove',obj.toggleLayer,'toggleClosed');
            thalia.changeClass('add',obj.toggleLayer,'toggleOpen')
        }
    },

    navHover:function() {
        $("#nav li.liLevel1").each(function() {
            $(this)
            .bind("mouseenter", function(){
                var elem = $(this);
                /*hoverTimer = setTimeout(function() {addHoverClass(elem, " navHover");}, 300);*/
                hoverTimer = setTimeout(function() {addHoverClass(elem, " navHover");}, 1);
            })
            .bind("mouseleave", function(){
                clearTimeout(hoverTimer);
                $(this).removeClass("navHover");
            });
        });

    },
/***********************************************************************************
** navigation functions
** clearNav:         hide all subnav items but the one with the parameter id
** changeNavItem:     hide all first-level nav items and then show the one selected (id)
** closeNav:         hide a certain subnav item (id)
** changeMoodImg:    change mood image
***********************************************************************************/
    clearNav:function(id){
        for (var i=0; i<thalia.navEls.length; i++) {
            //console.log("i: " + i + " | id: "+ id);
            if (thalia.activeNav != i+1){
                thalia.navEls[i].className=thalia.navEls[i].className.replace(new RegExp(" navHover\\b"), "");
                var tempObj = thalia.$('navImg_'+(i+1));
                if (tempObj) {
                    thalia.$('navImg_'+(i+1)).src = tempObj.src.replace(new RegExp("_a"), "_i");
                }
            }
        }
    },
    changeNavItem:function(id){
        var aktItem = thalia.$('navImg_'+id);
        for (var i=1; i<thalia.navEls.length+1; i++) {
            var tempObj = thalia.$('navImg_'+(i));
            //console.log("tempObj: " + tempObj);
            if (i!=id){
                thalia.$('navImg_'+(i)).src = tempObj.src.replace(new RegExp("_a"), "_i");
            }
        }
        aktItem.src = aktItem.src.replace(new RegExp("_i"), "_a");
    },
    closeNav:function(id){
        //console.log("in ID: " + id);
        /*clearInterval(thalia.timer);*/
        var obj = thalia.navEls[id];
        obj.className=obj.className.replace(new RegExp(" navHover\\b"), "");
    },

    changeMoodImg:function(id){
        var moodImgObj = thalia.$('moodImg');
        //moodImgObj.src = thalia.moodImgPath+'moodbild_'+id + '.jpg';
        moodImgObj.src = thalia.moodPics[id].src;
    },
    preloadMoodImages:function(){
        for (var i=0; i<thalia.navEls.length; i++) {
            thalia.moodPics[i] = new Image();
            thalia.moodPics[i].src = thalia.moodImgPath+'moodbild_'+i + '.jpg';
        }
    },

    getPos:function (el){
        if (el){
            for (var lx=0, ly=0; el!=null;lx+=el.offsetLeft,ly+=el.offsetTop,el=el.offsetParent);
            return new Array(lx, ly);
        }
        return false;
    },
    initNav:function(){
        /*
        $("#nav li.liLevel1").each(function(i) {
            var tempId = i;
            if ($(this).hasClass("liActive")) thalia.activeNav= i+1;
            $(this)
            .bind("mouseenter", function(){
                thalia.clearNav();
                var elem = $(this);
                hoverTimer = setTimeout(function() {addHoverClass(elem, " navHover");}, 300);
                var tempObj = thalia.$('navImg_'+(tempId+1));
                if (tempObj) {
                    tempObj.src = tempObj.src.replace(new RegExp("_i"), "_a");
                }
            })
            .bind("mouseleave", function(){
                clearTimeout(hoverTimer);
                thalia.closeNav(tempId);
                thalia.clearNav();
            });
        });
        */
        thalia.navEls = thalia.getElementsByClass('liLevel1');
        for (var i=0; i<thalia.navEls.length; i++) {
            thalia.navEls[i].tempId = i;
            if(thalia.navEls[i].className.indexOf('liActive')>-1) thalia.activeNav= i+1;
            thalia.navEls[i].onmouseover=function() {
                thalia.clearNav();
                this.className+=" navHover";
                var tempObj = thalia.$('navImg_'+(this.tempId+1));
                if (tempObj) {
                    tempObj.src = tempObj.src.replace(new RegExp("_i"), "_a");
                }
            }
            thalia.navEls[i].onmouseout=function() {
                thalia.closeNav(this.tempId);
                thalia.clearNav();
            }
        }
    },
    initLeftNav:function(){
        thalia.imgLinks = thalia.getElementsByClass('imgLink');
        for(var j=0;j<thalia.imgLinks.length;j++){
            thalia.imgLinks[j].tempId = j;
            if(thalia.imgLinks[j].className.indexOf('activeLeftNav')>-1) thalia.activeLeftNav= j+1;
            thalia.imgLinks[j].onmouseover = function(){
                if (this.tempId+1 != thalia.activeLeftNav){
                    var tempObj = this.childNodes[0];
                    tempObj.src = tempObj.src.replace(new RegExp("_inactive"), "_active");
                }
            }
            thalia.imgLinks[j].onmouseout = function(){
                if (this.tempId+1 != thalia.activeLeftNav){
                    var tempObj = this.childNodes[0];
                    tempObj.src = tempObj.src.replace(new RegExp("_active"), "_inactive");
                }
            }
        }
    },

    initFaq:function(){
        thalia.faqContainer = thalia.$('faqList');
        thalia.faqDT = thalia.faqContainer.getElementsByTagName('DT');
        thalia.faqDD = thalia.faqContainer.getElementsByTagName('DD');
        for (var i=0;i<thalia.faqDT.length;i++){
            thalia.faqDT[i].tempId = i;
            thalia.faqDT[i].onclick=function(){
                thalia.faqDD[this.tempId].className = (thalia.faqDD[this.tempId].className == 'hideDD')?'showDD':'hideDD';
                return false;
            }
            thalia.faqDT[i].onmouseover=function(){
                this.className += (this.className == 'mouseoverDD')?' mouseoutDD':' mouseoverDD';
            }
            thalia.faqDT[i].onmouseout=function(){
                this.className -= (this.className == 'mouseoverDD')?' mouseoutDD':' mouseoverDD';
            }
        }
    },
    countInput:function(){
        /*
         * This counter has been disabled. In The template grusskarte.cjheckout.darstellung.tile.html
         * an own counter has been integrated
         */
        /*
        var elems = thalia.getElementsByClass('countInput');
        for (var i=0;i<elems.length;i++){
            elems[i].tempId = i;
            var classes = elems[i].className.split(' ');
            for (var j=0;j<classes.length;j++){
                if(thalia.checkRegExp('count_', classes[j])){
                    elems[i].countClass = classes[j];
                }
            }
            elems[i].countAmount = (elems[i].countClass.split('_')[1]>0)?elems[i].countClass.split('_')[1]:1000;
            elems[i].onkeydown = function(){
                var str = this.value;
                if (str.length > this.countAmount) str = str.substring(0, this.countAmount);
                this.value = str;
            }
        }
        */
    },

/***********************************************************************************
** find select boxes to be replaced by dhtml versions for ie:
** option text can be longer than select box width (standard in other browsers like Firefox)
***********************************************************************************/
    parseDropdowns:function(){
        var dropdownImage='pics/dropdownArrow.gif'; //path to arrow image
        var dropdownOffsetY=2; //offset of drop down menu vertically from default location (in px)
        var dropdownIndex=100;
        if (dropdownImage!="")    dropdownImage='<img class="downimage" src="'+dropdownImage+'" title="Bitte wählen Sie" />';
        thalia.selectBoxes = thalia.getElementsByClass('dhtmlSelect');
        for (var i=0;i<thalia.selectBoxes.length;i++){
            var selectid = thalia.selectBoxes[i].id;
            var selectBoxParent = thalia.selectBoxes[i].parentNode;
            var dropdown = '<div id="dhtml_'+selectid+'" class="dhtmlselect">'+thalia.selectBoxes[i].title+" "+dropdownImage+'<div class="dropdown">';
            for (var j=0; j<thalia.selectBoxes[i].options.length; j++){
                dropdown += '<a href="'+thalia.selectBoxes[i].options[j].value+'">'+thalia.selectBoxes[i].options[j].text+'</a>';
            }
            dropdown += '</div></div>';
            thalia.selectBoxes[i].style.display="none";
            selectBoxParent.innerHTML += dropdown;
            var dhtmlDropdown=thalia.$("dhtml_"+selectid);
            dhtmlDropdown.style.zIndex=dropdownIndex;
            dropdownIndex--;
            dhtmlDropdown.getElementsByTagName("div")[0].style.top=dhtmlDropdown.offsetHeight-dropdownOffsetY+"px";
            dhtmlDropdown.getElementsByTagName("img")[0].style.left=dhtmlDropdown.offsetWidth-1+"px";
            dhtmlDropdown.onmouseover=function(){
                this.getElementsByTagName("div")[0].style.display="block";
            }
            dhtmlDropdown.onmouseout=function(){
                this.getElementsByTagName("div")[0].style.display="none";
            }
        }
    },
    getURLParam:function(strParamName){
        var strReturn = "";
        var strHref = window.location.href;
        if ( strHref.indexOf("?") > -1 ){
            var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
            var aQueryString = strQueryString.split("&");
            for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
                if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
                    var aParam = aQueryString[iParam].split("=");
                    var aParams = aParam[1].split(",");
                    //var aParams = (aParam[1].split(",").length >1)? aParams : aParams[0];
                    //strReturn = (aParams.length>1) ? aParams : aParams[0];
                    strReturn = aParams;
                    break;
                }
            }
        }
        return strReturn;
    },

/**************************************************************************
**    main init function
** add functions you want to execute on load
***************************************************************************/

    init:function(){
        if(thalia.scriptInit){
            //if(startBereich != undefined) thalia.receiveGetString();
            //if(thalia.$('folderNav')) thalia.initFolderNav();
            //thalia.initNav();
            thalia.initLeftNav();
            thalia.parseInputReplaceFields();
            if(thalia.$('faqList')) thalia.initFaq();
            thalia.countInput();
            //thalia.navHover();
            initMainNav();
        }
    }
}
thalia.addEvent(window, 'load', thalia.init, false);

/**************************************************************************
**    function for top layer navigation
***************************************************************************/

function addHoverClass(elem, cssClass) {
    $(elem).addClass(cssClass);
    //elem.className += cssClass;
}

/**************************************************************************
**    function for Main Navigation
***************************************************************************/

function initMainNav(){

    $('.overlay').hide();

    preLoadNavImgs();
    checkActive();

    function preLoadNavImgs(){

    }

    function checkActive(){
        if($('#nav li').hasClass('liActive')){
            var navImg = $('.liActive').css('background-image');
            navImg = navImg.replace(/_mo/,"");
            navImg = navImg.replace(/.gif/,"_mo.gif");
            $('.liActive').css('background-image',navImg);
            $('.liActive').find('.overlay').show();
        }
    }

    function setActive(element){
    	//console.log("setActive: " + element);
        var navImg = $(element).css('background-image');
        navImg = navImg.replace(/_mo/,"");
        navImg = navImg.replace(/.gif/,"_mo.gif");
        $(element).css('background-image',navImg);
        $(element).css('z-index','100');
        $(element).find('.overlay').show();
    }
    function setInActive(element){
    	//console.log("setInActive: " + $(element).css('background-image'));
        var navImg = $(element).css('background-image');
        if (navImg != undefined){
        	navImg = navImg.replace(/_mo.gif/,".gif");
        	navImg = navImg.replace(/_mo/,"");
        	$(element).css('background-image',navImg);
        	$(element).css('z-index','10');
        	$(element).find('.overlay').hide();
        }
    }

    $('#contentNavigation #nav .liLevel1').mouseenter(function(){
    	clearTimeout(this.hoverTimerOut);
    	  /*if ($('#nav li').hasClass('liActive')){
            setInActive('.liActive');
        }
        if ($('#nav li').hasClass('liLevel1')){
            setActive(this);
            $('#breadcrumb').css('border-top','1px solid #ffffff');
        }*/
        var elem = $(this);
        hoverTimer = setTimeout(function() {
        	//clearTimeout(hoverTimerOut);
        	addHoverClass(elem, "navHover");
        	if (elem.hasClass('liActive') === false){
        		setInActive('#nav li.liActive');
        		setActive(elem);
        		
        	}
        	$('#breadcrumb').css('border-top','1px solid #ffffff');
        }, 300);
        
      
    });

    $('#contentNavigation #nav .liLevel1').mouseleave(function(){
    	clearTimeout(hoverTimer);
    	var elem = $(this);
    	if (elem.hasClass('navHover')){
    	this.hoverTimerOut = setTimeout(function() {
    		elem.removeClass("navHover");
        	setInActive(elem);
        	if ($('#nav li').hasClass('liActive')){
                setActive('.liActive');
            }
        	$('#breadcrumb').css('border-top','1px solid #B9B9B7');
        }, 300);
       }
    	
        /*if ($('#nav li').hasClass('liLevel1')){
            setInActive(this);
            $('#breadcrumb').css('border-top','1px solid #B9B9B7');
        }*/
        /*if ($('#nav li').hasClass('liActive')){
            setActive('.liActive');
        }*/
        //clearTimeout(hoverTimer);
        //$(this).removeClass("navHover");
    });


}
