/**
 * SWM JavaScript core
 *
 * @author  Peter Dobetsberger <p.dobetsberger@edelweiss72.de>
 *
 * Conventions:
 * Variables in camelCase
 * Classes in PascalCase
 * Function/Methods in camelCase
 */

 
SWM = {};
/**
 * HtmlObject $(String htmlObjectId)
 * shortnotation for window.document.getElementById()
 */


// Helper für show/hide
SWM.findObj = function (n, d) { 
    var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
    if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=SWM.findObj(n,d.layers[i].document);
    if(!x && d.getElementById) x=d.getElementById(n); return x;
}


// Helper für show/hide 
SWM.changeProp = function (objName,x,theProp,theValue) { 
    var obj = SWM.findObj(objName);
    if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
    if (theValue == true || theValue == false)
    eval("obj."+theProp+"="+theValue);
    else eval("obj."+theProp+"='"+theValue+"'");
    }
}

// hide Layer 
SWM.hideLayer = function (setDiv) {
	  SWM.changeProp(setDiv,'','style.display','none','DIV');
}


// show Layer
SWM.showLayer = function (setDiv) {
	  SWM.changeProp(setDiv,'','style.display','block','DIV');
}

// showTab,showProduct
SWM.showBoxIsRunning = false;
// divname Divname
// nr      Nummer
// count   Anzahl
SWM.showBox = function (divname,nr,count) {
	if (SWM.showBoxIsRunning) {
		return;
	}
	SWM.showBoxIsRunning = true;
	
    for (i=1; i<=count; i++) {
        if (i == nr) {
			$('#' + divname + '_switch_' + i).addClass('active');
			$('#' + divname + '_' + i).show();
		} else {
			$('#' + divname + '_switch_' + i).removeClass('active');
			$('#' + divname + '_' + i).hide();
		}
    }
	SWM.showBoxIsRunning = false;
}

SWM.oldTeaser = 1;
/**
 * switchTeaser
 *
 * New version, taken over SWM mods at 03.08.10.
 */

SWM.teaserBgImages = new Array();
/**
 * teaserBGImages
 *
 * array with all bg image sources
 */

SWM.switchTeaser = function (showId,count) {
    
    for(i=1;i<=count;i++) {
        var divId='#teaser_'+i;
        $(divId).removeClass("topIndex");
        $(divId).removeClass("lowIndex");
        $(divId).addClass("zeroIndex");
        pagerId='#pager_'+i;
        $(pagerId).removeClass("active");
        $(pagerId).addClass("inactive");
    }

    pagerId='#pager_'+showId;
    $(pagerId).removeClass("inactive");
    $(pagerId).addClass("active");
    



    var showMe ='#teaser_'+showId;
    var hideMe ='#teaser_'+SWM.oldTeaser;
    
    $(showMe).removeClass("zeroIndex");
    $(hideMe).removeClass("zeroIndex");
    
    $(showMe).hide();
    $(showMe).addClass("topIndex");
    $(hideMe).addClass("lowIndex");  
    $(showMe).fadeIn(2000);
    
    // show and hide boxText
    $('#text_'+showId).fadeIn(2000);
    
    if (SWM.oldTeaser != showId){
        $('#text_'+ SWM.oldTeaser).fadeOut(2000);
    }

    var privateNavId='#privateNavActive';
    if ($('#text_'+showId).hasClass("boxTextDark")){
        $(privateNavId).addClass("boxTextDark");
    }else{
        $(privateNavId).removeClass("boxTextDark");
    }
    
    SWM.oldTeaser = showId;
}

/**
 * Homepage teaser loop class, loops thru all available teaser
 * by triggering pager links click events.
 *
 * @class      SWM.switchHpTeaserLoop
 * @namespace  SWM
 * @static
 */
SWM.switchHpTeaserLoop = {
    _links:           null,
    _intervall:       5000,
    _currPos:         0,
    _intervallHandle: null,
    /**
     * Initilaizes the hp teaser loop.
     *
     * @param  {String}   linkSelector  jQuery selector to get all links in teaser pager
     * @param  {String}   imgSelector   jQuery selector to get all background images, we need this to preload them
     * @param  {Integer}  intervall     Interval in ms for the teaser loop, wenn 0, soll kein Loop durchlaufen werden
     */
    initialize: function(linkSelector, imgSelector, intervall) {
        this._links = $(linkSelector);
        this._intervall = intervall;
        if (this._links.length > 0 && intervall != 0) {
            var that = this;
            that._intervallHandle = window.setInterval(function(){
                if (++that._currPos >= that._links.length) {
                    that._currPos = 0;
                }
                SWM.switchTeaser(that._currPos+1, that._links.length);
               // $(that._links[that._currPos]).click();
            }, that._intervall);
            textBoxId='#text_1';
            privateNavId='#privateNavActive';
            if ($(textBoxId).hasClass("boxTextDark")){
                $(privateNavId).addClass("boxTextDark");
            }else{
                $(privateNavId).removeClass("boxTextDark");
            }
        }
        $('#text_1').show();
        
        // jetzt erst weitere Hintergrundbilder schreiben, wegen Ladezeit
        $('.moduleImage .boxTeaser img').each(function(index, item){
            $(item).css('backgroundImage', 'url(' + SWM.teaserBgImages[index] + ')');
        });
    },
    /**
     * Stops the teaser loop.
     */
    stop: function() {
        if (this._intervallHandle !== null) {
            window.clearInterval(this._intervallHandle);
        }
    },
    /**
     * Preloads all images
     *
     * @param  {String}   imgSelector   jQuery selector to get all images, we need this to preload them
     * @private
     */
    _preloadImages: function (imgSelector) {
        $(imgSelector).each(function(pos, item){
            var imagesList = [];
            // extract background-image
            var img = $(item).css('background-image').match(/url\((.*)\)/);
            if (img !== 0 && img.length > 1) {
                img = img[1].replace(/"/g, "").replace(/'/g, "");
                var obj = new Image();
                obj.src = img;
                imagesList.push(obj.src);
            }
        });
    }
};



// wird für popup-Modul in easyred benötigt 
function openPopup(URL,popname,W,H,scroll,rezisable,X,Y) {
  	var URL,popname,W,H,scroll,rezisable,X,Y;
  	if (!popname) { popname='popup'; }
  	if (!W) { W=520; }
  	if (!H) { H=460; }
  	if (!scroll) { scroll=0; }
  	if (!rezisable) { rezisable=0; }
  	if (!X) { X=screen.width/2-(W/2); }
  	if (!Y) { Y=screen.height/2-(H/2)-20; }
  	properties = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars="+scroll+",resizable="+rezisable+",";
  	properties += "width="+W+",height="+H+",left="+X+",top="+Y;
  	popwin=window.open(URL,popname,properties);
  	popwin.focus();
}

// Löscht Textfeldinhalt onFocus und setzt originalen Inhalt / neuen Inhalt onblur
SWM.clearTextField = function (field) {
    if (field.defaultValue == field.value) field.value = '';
    else if (field.value == '') field.value = field.defaultValue;
}

// prüfen ob diese zbesser... InputFeld auf leer setzen
SWM.clearField = function(field, cssClass) {
    // addValue
    if ($(field).data("value")) {return;}
    $(field).data("value", $(field).val());
    $(field).val("");;
    if (cssClass){
        $(field).removeClass(cssClass);
    }
    // addFocus-Event
    $(field).focus(function(){
        //if ($(this).data("done")){return;}
        if ($(this).val() == $(field).data("value")) {
            $(this).val("");
            if (cssClass){
                $(this).removeClass(cssClass);
            }
            //$(this)
        }
    });
    // addBlur-Event
    $(field).blur(function(){
        if ($(this).val() == "") {
            $(this).val($(field).data("value"));
            if (cssClass){
                $(this).addClass(cssClass);
            }
        }
    });
    // nach Eingabe deaktivierung
    $(field).bind('keypress', function(e){
        $(this).data("done", true);
    });
}   


// Info Layer öffnen
/**
 * @deprecated
 */
SWM.showInfoLayer = function (layerId, newPos) {
	// layerID = ID des Layers zum Einbleden
	// newPos  = margin-top zur korrekten Positionierung des Layer
	var layerToFadeIn = "#" + layerId;
	var offset = $(layerToFadeIn).offset();
	var yPos = Math.round(offset.top);
                        
	$(layerToFadeIn).css("margin-top",newPos);
	$(layerToFadeIn).fadeIn(function() {						   
	});
}

// Info Layer schließen
/**
 * @deprecated
 */
SWM.closeInfoLayer = function(layerId) {
	var layerToFadeIn = "#" + layerId;
	$(layerToFadeIn).fadeOut(function() {
	});	
}

/**
 * Classs for toggle-list
 *
 * @param    {String}       listId - id-name from the ul-tag
 * @returns  {Object}       the API with public members
 */
SWM.ToggleList = function(listId) {
    var _root = "";
    var _speed = "slow"
    var _unique = false;


    // --------------------- private-area [methods] ------------------------- //


    /**
     * Constructor - hides all toggle-list-elements
     *
     * @param    {String}         listId - listId - id-name from the ul-tag
     */
    function __construct(listId) {
        if (!listId) {throw "Constructor-parameter must be a string";}

        _root = listId;
        $(_root + " a.jsToggle").removeClass("jsActive");
        $(_root + " .jsToggle:not(a.jsToggle)").hide(0);
        _open();
    }

    /**
     * Opens all toggle-elements witch has the class name "jsOpen"
     *
     * @returns  {void}
     */
    function _open() {
        var index = 0;
        $(_root + " a.jsToggle").each(function(){
            if ($(this).hasClass("jsOpen")) {
                $(this).addClass("jsActive");
                $(_root + " .jsToggle:not(a.jsToggle):eq("+index+")").show(0);
            }
            index++;
        });
    }


    /**
     * Close all list-points
     *
     * @returns  {void}
     */
    function _closeAll(currentIndex) {
        var index = 0;
        
        $(_root + " a.jsToggle").each(function() {
            if (index != currentIndex) {
                $(this).removeClass("jsActive");
                $(_root + " .jsToggle:not(a.jsToggle):eq("+index+")").hide(_speed);
            } else {
                if (!$.browser.msie){
                    $(this).toggleClass("jsActive");
                    $(_root + " .jsToggle:not(a.jsToggle):eq("+index+")").toggle(_speed, function() {
                        // Animation complete.
                        if ($(this).prev(0).hasClass("jsActive")){
                            var x = $(this).offset().top - 100; // 100 provides buffer in viewport
                            $('html,body').animate({scrollTop: x}, 500);
                        }
                    });
                }else{
                    if ($(this).hasClass('jsActive')){
                        $(_root + " .jsToggle:not(a.jsToggle):eq("+index+")").hide();
                    }else{
                        $(_root + " .jsToggle:not(a.jsToggle):eq("+index+")").show();

                            var x = $(this).offset().top - 130; // 100 provides buffer in viewport
                            $('html,body').animate({scrollTop: x}, 500);

                    }
                    $(this).toggleClass("jsActive");
                }
            }
            index++;
        });
    }


    /**
     * Opens toggle-list-elements by number
     *
     * @param    {Array}         listArray - numbers of the toggle-list-elements, witch sould be open
     * @returns  {void}
     */
    function _toggle(listArray) {
        for (var i=0; i<listArray.length; i++) {
            $(_root + " a.jsToggle:eq(" + (listArray[i]-1) + ")").toggleClass("jsActive");
            $(_root + " .jsToggle:not(a.jsToggle):eq(" + (listArray[i]-1) + ")").toggle(_speed);
        }
    }

    
    __construct(listId);

    // --------------------- public-area [API] ------------------------------ //
    return {


        /**
         * Opens a toggle-list-element
         *
         * @param    {HTMLObject|Array}         handlerObject - HTMLObjet from the event-handler object (this)
         *                                      or Array with numbers (indexes)
         * @returns  {void}
         */
        toggle: function(handlerObject) {
            // toggle multiple lists
            if (handlerObject.constructor == Array) {
                _toggle(handlerObject);
                return;
            }

            var index = $(_root + " a.jsToggle").index($(handlerObject));
            if (_unique) {
                _closeAll(index);
            } else {
                $(_root + " .jsToggle:not(a.jsToggle):eq("+index+")").toggle(_speed);
                $(_root + " a.jsToggle:eq(" + index + ")").toggleClass("jsActive");
            }
            
            return false;
        },


        /**
         * Speed for the toggle-animation
         *
         * @param    {Mixed}         speed - based on jQuery-speed-handling
         * @returns  {void}
         */
        setSpeed: function(speed) {
            _speed = speed;
        },


        /**
         * If "_unique" ist "true", all other list-points will closed, when one is open
         *
         * @param    {Boolean}         value - true or false
         * @returns  {void}
         */
        setUnique: function(value) {
            if (value.constructor != Boolean) {throw "parameter from setUnique must from typof boolean";}
            _unique = value;
        }
    }
}


/**
 * Minimalistic and simple infolayer handler class.
 *
 * @class      SWM.InfoLayer
 * @namespace  SWM
 * @static
 */
SWM.InfoLayer = {
    _counter:  1,
    _offset:   22,
    _template: '\
        <span class="boxInfoIcon"><img src="/dms/swm_common/img/icons/info.gif" width="12" height="12" alt="" /></span>\
        <div class="boxColCenter">\
        {HTML_TEXT}\
        </div>\
        <div class="boxCloseIcon">\
            <a href="javascript:void(0);" onclick="$(\'{LAYER_ID}\').fadeOut();"><img src="/dms/swm_common/img/icons/schliessen.gif" width="11" height="11" alt="" /></a>\
        </div>\
    ',

    initialize: function() {
        $('.globalInfoIconText').hide();
        // to do on fireing onclick event
        $('.globalInfoIcon').click(function(){
            $('.globalInfoIconText').hide();
            var context = $(this);

            if (context.attr('id').length === 0) {
                context.attr('id', 'jsInfoIcon_' + String(SWM.InfoLayer._counter++));
            }
            
            var infoLayer     = null;
            var infoLayerId   = context.attr('id') + '_layer';
            var initialAction = true;
            var inRightColumn = false;

            // detect, if infoicon is in left or right column
            if (context.parents('.divContentCenter').length > 0) {
                var column = $(context.parents('.divContentCenter')[0]);
                var className = 'jsGlobalInfoIconTextContentCenter';
            } else if (context.parents('.divContentRight').length > 0) {
                var column = $(context.parents('.divContentRight')[0]);
                var className = 'jsGlobalInfoIconTextContentRight';
                inRightColumn = true;
            } else {
                var column = context;
                var className = 'jsGlobalInfoIconTextContentCenter';
            }

            // get infolayer
            if ($('#' + infoLayerId).length > 0) {
                // infolayer already processed before
                initialAction = false;
                infoLayer     = $($('#' + infoLayerId)[0]);
            }  else {

                // initial processing, find infolayer
                if (context.nextAll('.globalInfoIconText').size() != 0) {
                    // text element is on the same level as infoicon
                    infoLayer = context.nextAll('.globalInfoIconText');
                } else if (context.parent().nextAll('.globalInfoIconText').size() != 0) {
                    // text element is on the same level as infoicon's parent
                    infoLayer = context.parent().nextAll('.globalInfoIconText');
                }
            }

            if (infoLayer !== null) {
                // get/set positions
                var colPos = column.offset();
                var pos    = context.offset();
                if(inRightColumn) // in der rechten Spalte wird der Info Layer zentriert positioniert
                {
                    //pos.top   -= SWM.InfoLayer._offset;
                    //pos.left   = colPos.left + SWM.InfoLayer._offset;
                    pos.top   -= SWM.InfoLayer._offset;
                    pos.left   = colPos.left + SWM.InfoLayer._offset -76;
                }
                else //ansonsten leigt das "i" des Icons über dem "i" des Layers
                {
                    pos.top= pos.top-15;
                    pos.left= pos.left-16;
                }
                
                if (initialAction == true) {
                    // initial processing of infolayer, prepare markup
                    infoLayer.attr('id', infoLayerId).addClass(className);
                    infoLayerId = '#' + infoLayerId;
                    // make new content, add it to body
                    var newHtml = SWM.InfoLayer._template.replace('{HTML_TEXT}', infoLayer.html());
                    newHtml = newHtml.replace('{LAYER_ID}', infoLayerId);
                    infoLayer.html(newHtml).appendTo($('body'));
                }
                // show layer
                infoLayer.css(pos).fadeIn();
            }
            return false;
        });
    }
}

$ = jQuery.noConflict();
$(document).ready(function() {
    // initialize all available infolayer
    SWM.InfoLayer.initialize();
});



/**
* Bäderkarte
*/
SWM.toggleMap = function (clickedElement){

	$('#map_all').hide();
	$('#map_sauna').hide();
	$('#map_fitness').hide();

	switch (clickedElement.value){
		case 'fitness': $('#map_fitness').show(); break;
		case 'sauna':   $('#map_sauna').show(); break;
		case 'all': 	$('#map_all').show(); break;
	
	}
}


/**
* Fly-out navigation für den IE6
*/
SWM.hoverNavi = function()
{
    if(navigator.userAgent.match("MSIE 6.0"))
    {
        $(".moduleTopMainNavigation ul li").mouseover(
        function()
        {
            $(this).find("ul").show();
        });
            
        $(".moduleTopMainNavigation ul li").mouseout(
        function()
        {
            $(this).find("ul").hide();
        });
    }
}

/**
* Script für die Bildergelalerie
*/
SWM.ImageGallery =  function(galleryElem){

    this._activators= galleryElem.find(".boxCol2 a");
    this._images=     galleryElem.find(".boxZoom li");
    this._next=       galleryElem.find(".boxNext span");
    this._prev=       galleryElem.find(".boxPrev span");
    this._rack=       galleryElem.find(".boxCol2");
    this._imagesPos=  0;
    this._rackPos=  0;
    this._rackWidth=  this._rack.find("ul").width();
    this._thumbWidth=  65;
    this._scrollRack= true;

    /*End: Construcor*/
    
    /**
    * Zeigt ein Bild in der Galerie an.
    * @param image (DOM Object or int) Es kann entweder das DOM-Objekt des Thumnails angezeigt übergeben werden oder
    * die Position des Bildes in der Reihenfolge
    */
    this.show = function(image)
    {
        var that = this;
        if (typeof(image) === 'object')
        {
            that._activators.each(function(pos, item)
            {
                if (item === image) 
                {
                    that._imagesPos = pos;
                }
            });
        } 
        else if(typeof(image) === "number")
        {
            that._imagesPos = image;
        }
        
        that._images.each(function(pos, item)
        {
            if (pos == that._imagesPos)
            {
                item.style.display = 'block';
                $(that._activators[pos]).addClass('active');
            }
            else 
            {
                item.style.display = 'none';
                $(that._activators[pos]).removeClass('active');
            }
        });
        
        if(that._imagesPos === 0)
        {
            that._prev.removeClass("active");
            that._next.addClass("active");
        }
        else if(that._imagesPos+1 === that._activators.length)
        {
            that._next.removeClass("active");
            that._prev.addClass("active");
        }
        else
        {
            that._prev.addClass("active");
            that._next.addClass("active");
        }
    }
    
    this.moveRack = function(direction)
    {
       var scrollRack = true;
       if(direction === "-") // zurück
       {
            if(!this._prev.get(0).className.match("active"))
            {
                return;
            }
            this._imagesPos--;
            if(this._imagesPos+2 === this._activators.length)
            {
                scrollRack = false;
            }
            else
            {
                this._next.addClass("active");
                this._rackPos = this._rackPos + this._thumbWidth;
                if(this._rackPos>-60)
                {
                    this._rackPos = 0;
                }
            }
            if(this._imagesPos === 0)
            {
                this._prev.removeClass("active");
            }
       }
       else // vor
       {
            if(!this._next.get(0).className.match("active"))
            {
                return;
            }
            if(this._imagesPos === 0)
            {
                scrollRack = false;
            }
            else
            {
                this._prev.addClass("active");
                
                var maxPos = (this._rackWidth-390)*-1;
                var nextPos = this._rackPos - this._thumbWidth;
                if(nextPos<maxPos)
                {
                   if(this._imagesPos+2 === this._activators.length)
                   {
                        this._next.removeClass("active");
                   }
                   scrollRack = false;
                }
                else
                {
                    this._rackPos = nextPos;
                }
            }
            
            this._imagesPos++;
       }
       if(scrollRack && this._scrollRack)
       {
        this._rack.animate({left: this._rackPos+'px'}, 200);
       }
       
       this.show(this._imagesPos);
    }
}

/**
* Funktion für die Flowplayer PLayliste
*/
 SWM.flowplayerPlay = function(li, player, src)
 {
     var lis = li.parentNode.getElementsByTagName('LI');
     for(n in lis) if(lis[n].className && li.parentNode == lis[n].parentNode) lis[n].className = lis[n].className.replace(/\bactive\b/, '');
     li.className += ' active';
     player.play(src); 
  }
  
  
/**
* Zeigt Infolayer "Seite versenden"
*/
SWM.SendPageLayer = 
{
    open:function(){
        jQuery('#layer_send').show();
    },
      
    close:function(elem){
        jQuery('#layer_send').hide();
    }
      
 
}
