var SNSmisc = {
    showCategoryWidgetText : function(wrapper, trigger, target, shorttext, initheight, autoheight){
        var oldHeight = wrapper.getHeight() - trigger.getHeight();
        //alert(oldHeight);
        var oldText = target.innerHTML;
        var newText = shorttext
        $(target).update(newText);
        if(!initheight || initheight == undefined) {
            var initheight = wrapper.getHeight();
        }
        wrapper.setStyle({
            height : initheight + 'px'
        });
        trigger.observe('mouseover', function(event) {                            
            $(target).update(oldText);
            var height = oldHeight;
            if(oldHeight < initheight){
                oldHeight = initheight;
            }
            wrapper.setStyle({height:height + 'px'});
            if(autoheight){
                wrapper.setStyle({height:'auto'});
            }
            
            trigger.hide();
            /*new Effect.Tween(
                wrapper,
                initheight, 
                oldHeight,
                {
                    duration : 0.1,
                    afterFinish : function() {
                        trigger.hide();
                    },
                    queue: { position: 'end', scope: 'popuout' + wrapper.id}
                },
                function(value){
                    
                }
            );*/
            event.stopPropagation();
        });

        wrapper.observe('mouseout', function(event) {
            //We could probably replace the following with Event.element(event), but oh well.
            var event = (event) ? event : window.event;
            var mouse_over_element;
            //What the mouse is currently over...
            //So let's check to see what the mouse is now over, and assign it to mouse_over_element...
            if(event.toElement) {
                mouse_over_element = event.toElement;
            } else if(event.relatedTarget) {
                mouse_over_element = event.relatedTarget;
            }
            //In the event that the mouse is over something outside the DOM (like an alert window)...
            if(mouse_over_element == null) {
                return;
            }
            //Now we just make sure that what the mouse is currently over is NOT a descendant of
            //the dropdown, and that the target is not the current mouse_over_element (I can't
            //remember which case this covers, but it's important)
            if(!mouse_over_element.descendantOf(wrapper) && wrapper != mouse_over_element) {              
                wrapper.setStyle({height:initheight + 'px'});
                $(target).update(newText);
                trigger.show();
                /*new Effect.Tween(
                    $(wrapper),
                    oldHeight,
                    initheight,
                    {                    
                        duration : 0.5,
                        queue: { position: 'end', scope: 'popuout' + wrapper.id},
                        afterFinish : function() {
                            target.update(newText);
                            trigger.show();
                        }
                    },
                    'height'
                    
                );*/
            }

        });
    },
    infoboxTimeout: null,
    initInfobox:function(trigger, container){
        //var position = Position.cumulativeOffset(trigger);
        //var leftOffset = 13;
        //var topOffset = 0;
        //console.log(position);
        //container.setStyle({top: (position[1] + topOffset) + 'px', left: (position[0] + leftOffset) + 'px'});
        trigger.observe('mouseover', function(event){
            event.stopPropagation();
            //console.log(event.target);                   
            container.show();                     
                    
        })
        trigger.observe('mouseout', function(event){
            event.stopPropagation();
            var from = $(event.target);
            var to = $(event.relatedTarget);
            //console.log(from);
            //console.log(to);
            
            //for overedgemouse movement
            SNSmisc.infoboxTimeout = window.setTimeout(function(){                
                container.hide();
                   
            }, 1000);
                                  
        });   
        
        //for overedgemouse movement
        container.observe('mouseover', function(event){
            if(SNSmisc.infoboxTimeout != null){
                window.clearInterval(SNSmisc.infoboxTimeout);
            }
            
        });     
        container.observe('mouseout', function(event){
            event.stopPropagation();
            var from = $(event.target);
            var to = $(event.relatedTarget);
            //console.log(from);
            //console.log(to);
            if(!to.descendantOf(container) && to != container){
                container.hide();
                event.stopPropagation();
            }                           
        });
    },
     
    toggleAGB:function(firstid, secondid){
        var first = $(firstid);
        var second = $(secondid);
        
        first.observe('click', function(event){
          
          if(first.checked){
              second.checked = true;
          }
          else{
              second.checked = false;
          }
        });
        
        second.observe('click', function(event){
         if(second.checked){
              first.checked = true;
          }
          else{
              first.checked = false;
          }
        });
    },
    getCookie:function(c_name){
        var i,x,y,ARRcookies = document.cookie.split(";");
        for (i=0;i<ARRcookies.length;i++) {
            x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
            x = x.replace(/^\s+|\s+$/g,"");
            if (x==c_name) {
                return unescape(y);
            }
        }
    },
    
    setCookie:function(c_name, value, path, exdays){
        var exdate=new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()) + ((path==null) ? "" : "; path=" + path);
        document.cookie=c_name + "=" + c_value;
    },    
    
     initSeoBar:function(hoverselector, tooltipclass, contents, emptystring){
        var lis = $$(hoverselector);
        for(var i = 0;i < lis.length; i++){
            var el = lis[i];
            var container = el.down(tooltipclass);
            if(contents[i] != emptystring){
                container.innerHTML = contents[i];
                el.observe('mouseover', function(event){
                    //console.log(event.target);
                    var tooltip = $(event.target).down(tooltipclass);
     
                    if(tooltip != undefined){
                        tooltip.show();
                    }   
                    
                })
                el.observe('mouseout', function(event){
                    //console.log(event.target);
                    var tooltip = $(event.target).down(tooltipclass);
                //console.log(tooltip);
                    if(tooltip != undefined){
                        tooltip.hide();
                    }                    
                });
           }
        }
        //console.log(lis);
    },
    
    
    showMore: function(original, target, trigger, wrapper, mouseoutclass){
             
        
        var oldHeight = wrapper.getHeight();
        
        wrapper.setStyle({height:'auto'});
        trigger.hide();
        original.hide();
        target.show();
        
        wrapper.observe('mouseout', function(event){
            var from = $(event.target);
            var to = $(event.relatedTarget);
            //console.log(to.descendantOf(wrapper));
            
            
            if(from.hasClassName(mouseoutclass) && !to.descendantOf(wrapper)){
                wrapper.setStyle({height:oldHeight});
                trigger.show();
                original.show();
                target.hide();
                event.stopPropagation();
            }
        })
    },
    
    getUrlparam: function(param) {
       var search = window.location.search.substring(1);
       if(search.indexOf('&') > -1) {
          var params = search.split('&');
          for(var i = 0; i < params.length; i++) {
              var key_value = params[i].split('=');
              if(key_value[0] == param) return key_value[1];
          }
       } else {
          var params = search.split('=');
          if(params[0] == param) return params[1];
       }
       return false;
    },

    removeShipping:function (){
        $('billing:use_for_shipping').setValue(1);
        $('billing:use_for_shipping_no').checked = false;
        $('shippingremovewrapper').hide();
    },

    addShipping:function (){
        $('billing:use_for_shipping').setValue(1);
        $('billing:use_for_shipping_no').checked = false;
        $('shippingremovewrapper').show();
        $('fade_delivery_adress').show();
    },
    
    /*add to cart*/
    addToCart: function(url){
        var form = $('product_addtocart_form');
        form.request({
            onLoading:snslightbox.showLoader(),
            onComplete:function(response){
                snslightbox.hideLoader();                
                var data = response.responseText.evalJSON();
                if(data.success == true){
                    snslightbox.setContent(data.successHtml);
                    snslightbox.addClass('addtocartsuccess');
                    $('header-cart-wrap').update(data.update_section.headerCart);
                    //$('footer-cart-wrap').update(data.update_section.footerCart);        
                    //console.log(data);
                    var js; 
                    var firstscript = document.getElementsByTagName('script')[0];
                    var scripturl = url + '/event/basket?itemids='+data.sku+'&quantities=' + data.qty;
                    //alert(scripturl);
                    
                    if(document.getElementById('comnosjs')) {  
                        document.getElementById('comnosjs').src = scripturl;
                    }else{                  
                        js = document.createElement('script');
                        js.id = 'comnosjs';
                        js.src = scripturl;
                        js.type = "text/javascript";
                        firstscript.parentNode.insertBefore(js, firstscript);
                    }
                    
                    // Affilinet Retargeting Tracking
                    /*if(document.getElementById('productAffilinetScript')) {
                        $('productAffilinetScript').remove();  //remove it to get changes                      
                    }
                    if(document.getElementById('productAffilinetScript1')) {
                        $('productAffilinetScript1').remove(); //remove it to get changes
                    }

                    js = document.createElement('script');
                    js.id = 'productAffilinetScript1';
                    js.type = "text/javascript";
                    js.innerHTML = 'var type = "AddToCart";var site = "4712";var product_id = '+data.id+';var product_price = '+data.price+';var currency = "EUR";var product_quantity = '+data.qty+';';
                    firstscript.parentNode.insertBefore(js, firstscript);
                    
                    js = document.createElement('script');
                    js.id = 'productAffilinetScript';
                    js.src = 'http://partners.webmasterplan.com/art/JS/param.aspx';
                    js.type = "text/javascript";
                    firstscript.parentNode.insertBefore(js, firstscript); */
                   
                    var rts_Tx = Math.random(); rts_Tx = rts_Tx * 100000000000000000;
                    //declare and assign variables

                    var type = "AddToCart";

                    var site = "4712";

                    var product_id =  data.id ; //sample assignment to another jvascript variable

                    var product_price = data.price;

                    var currency = "EUR";

                    var product_quantity = data.qty;

                    //compose Querystring parameters

                    var rts_para = "type=" + type + "&site=" + site +"&product_id=" + product_id + "&product_price=" + product_price + "&currency=" + currency;

                    //set protocol

                    try { 
                        rts_Protx = (("https:" == document.location.protocol) ? "https" : "http"); 
                    }
                    catch (err) { 
                        rts_Protx = "https"; 
                    }

                    //create div and iframe to call affilinet

                    var d = document.createElement("div");

                    var s = d.style; 
                    s.position="absolute";
                    s.left=0;
                    s.top=0;
                    s.width="0px"; 
                    s.height="0.px";

                    d.setAttribute("style", "left: 0px; top: 0px; width: 0px; height: 0px; position: absolute;");

                    d.setAttribute("id", "ppx_div_" + rts_Tx , 0);

                    var f = document.createElement("iframe");

                    with (f){
                        setAttribute("id", "ppx_ifr_" + rts_Tx, 0);
                        setAttribute("name", "ppx_ifr_" + rts_Tx, 0);
                        setAttribute("src", rts_Protx + "://partners.webmasterplan.com/art/JS/param.aspx?" + rts_para + "&rtspin=true", 0);
                        setAttribute("allowtransparency","true",0);
                        setAttribute("framespacing","0",0);
                        setAttribute("frameborder","no",0);
                        setAttribute("scrolling","no",0);
                        setAttribute("width","1",0);
                        setAttribute("height","1",0);

                    }

                    d.appendChild(f);

                    document.getElementsByTagName("body")[0].appendChild(d);
                                       
                }
                if(data.error){
                    snslightbox.setContent(data.errorHtml);
                    snslightbox.addClass('addtocarterror');   
                }
                snslightbox.show(); 
            }
        });
    },
    /*addToCart: function(){
        var form = $('product_addtocart_form');
        form.request({
            onLoading:snslightbox.showLoader(),
            onComplete:function(response){
                snslightbox.hideLoader();                
                var data = response.responseText.evalJSON();
                if(data.success == true){
                    snslightbox.setContent(data.successHtml);
                    snslightbox.addClass('addtocartsuccess');
                    $('header-cart-wrap').update(data.update_section.headerCart);
                    //$('footer-cart-wrap').update(data.update_section.footerCart);                    
                }
                if(data.error){
                    snslightbox.setContent(data.errorHtml);
                    snslightbox.addClass('addtocarterror');   
                }
                snslightbox.show(); 
            }
        });
    },*/
    
    openSendafriendPopup: function(url , productid){
        var url= url;
          
          if(typeof ASSOC_PRODUCT != "undefined" && ASSOC_PRODUCT != ''){
              url = url + 'associd/' + ASSOC_PRODUCT + '/';
          }
          
          url = url + 'id/' + productid;
                
          popWin( url, 'sendafriendpopup', 'width=510, scrollbars=yes');
    },
    
    showNewsletter: function(url, title, params) {
        popWin( url, title, params);
    }, 
    
    togglePackagePopup: function(){
            $('package-popup').toggle()
    },
    
    EMail:   function (s){
        var a = false;
        var res = false;
        if(typeof(RegExp) == 'function'){
          var b = new RegExp('abc');
          if(b.test('abc') == true){a = true;}
        } 
        
        if(a == true){
          reg = new RegExp('^([a-zA-Z0-9\-\.\_]+)'+
                          '(\@)([a-zA-Z0-9\-\.]+)'+
                          '(\.)([a-zA-Z]{2,4})$');
          res = (reg.test(s));
        }else{
          res = (s.search('@') >= 1 &&
               s.lastIndexOf('.') > s.search('@') &&
                   s.lastIndexOf('.') >= s.length-5)
        }
        return(res);        
    },
    
    //Passwortstärke ermitteln
   
    contains: function(strText, strPattern){
        for (i = 0; i < strText.length; i++) {
            if (strPattern.indexOf(strText.charAt(i)) > -1){
                return true;
            }
        }
        return false;
    },
    
    actPowerClassName : 'power-0',
    
    checkPass : function(strPass, strId, strTextId, aTexts){
        var nCrackrate = 1000; // Anzahl möglicher Versuche das Passwort zu Knacken pro Sekunde
        var nTreshholddays = 365 * 10; // Schwellwert, ab wann das Passwort als Sicher gilt
        var nSteps = 10; // Anzahl der Schritte, die im CSS angehangen werden
       
        nCombinationCount = 0;
        
        strToCheck = "0123456789"; // Überprüfen ob Ziffern vormmen
        if (this.contains(strPass, strToCheck)){
            nCombinationCount += strToCheck.length;
        }
        strToCheck = "abcdefghijklmnopqrstuvwxyz"; // Überprüfen ob kleine Buchstaben vorkommen
        if (this.contains(strPass, strToCheck)){
            nCombinationCount += strToCheck.length;
        }
        strToCheck = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // Überprüfen ob grosse Buchstaben vorkommen
        if (this.contains(strPass, strToCheck)){
            nCombinationCount += strToCheck.length;
        }
        strToCheck = ",;:-_=+\|//?^&!.@$Â£#*()%~<>{}[]";// Überprüfen ob Sonderzeichen vorkommen
        if (this.contains(strPass, strToCheck)){
            nCombinationCount += strToCheck.length;
        }        
        var nDays = ((Math.pow(nCombinationCount, strPass.length) / nCrackrate) / 2) / 86400; // Wieviele Tage benÃ¶tigt man?
        var nStrongness = Math.round(nDays / nTreshholddays * 100); // Stärke errechnen
        if (nStrongness < (strPass.length * 5)){
            nStrongness += strPass.length * 5; // Zeichenlänge für Stärke berücksichtigen
        }
        if (nStrongness > 100){
            nStrongness = 100; // Max 100% zulassen
        }
        nStrongness = Math.round(nStrongness / (100 / nSteps)); // Max Schritte
        oId = $(strId);
        oId.removeClassName(this.actPowerClassName)
        oId.addClassName('power' + "-" + nStrongness);
        this.actPowerClassName = 'power' + "-" + nStrongness;
        
        otId = $(strTextId);
        
        if (aTexts) {
            nKey = Math.round((aTexts.length - 1) / nSteps * nStrongness);
            otId.update(aTexts[nKey]);
        }
    }, 
    trim: function(string){
      // Erst führende, dann Abschließende Whitespaces entfernen
      // und das Ergebnis dieser Operationen zurückliefern
      return string.replace (/^\s+/, '').replace (/\s+$/, '');
    }          
}

SNSlangswitch = Class.create({
    expanded : false,
    initialize : function(triggerid, containerid, closedimgsrc, openedimgsrc){
        this.expanded = false;
        this.trigger = $(triggerid);
        this.container = $(containerid);
        //this.closedimg = closedimgsrc;
        //this.openedimg = openedimgsrc;
        
        //the whole container as Trigger event
        this.trigerparent = this.trigger.up();
        
        //init observers
        this.trigerparent.observe('click', this.updateLangSwitsch.bind(this));
        this.container.observe('mouseout', this.mouseout.bind(this));
        
//      this.trigerparent.observe('mouseout', this.mouseout.bind(this));
        this.container.observe('mouseover', this.mouseover.bind(this));
        
        //timeout for resolving event bubbling effects
        this.timer = null;
    },
    
    
    mouseover: function(){
        if(this.timer !== null){
          clearTimeout(this.timer);
          this.timer = null;    
        }
    },
    
    mouseout: function(event){
//      console.log(event);
        if(this.expanded){
            this.timer = setTimeout(this.hideLangSwitch.bind(this), 0);
            
        }
        event.stop();
    },
    
    
    hideLangSwitch: function(){
        this.container.hide();
        this.expanded = false;
        //this.trigger.src = this.closedimg;      
    },
    
    showLangSwitch: function(){
        this.container.show();
        this.expanded = true;
        //this.trigger.src = this.openedimg;
    },
    
    updateLangSwitsch: function(){
        if(this.expanded){
            this.hideLangSwitch();
        }
        else{
            this.showLangSwitch();
        }
    }
});
