PopUp = function(autoapply){
    this.types = [];
    this.defaults = {
        width:470,
        height:465,
        top:0,
        left:0,
        location:false,
        resizable:false,
        scrollbars:false,
        status:false,
        toolbar:false,
        menubar:false,
        center:true,
        title:""
    }
    this.addType({
        name:"standard",
        location:false,
        resizable:false,
        scrollbars:true,
        status:false,
        toolbar:false,
        menubar:false
    });
    if(autoapply) this.apply();
}
o = PopUp.prototype;
o.apply = function(){
    var links = document.getElementsByTagName("a");
    if(!links) return;
    for(var i=0;i<links.length;i++){
        var l = links[i];
        if(l.className.indexOf("popup") > -1){
            this.attachBehavior(l,this.getType(l));
        }
    }
}
o.addType = function(type){
    for(var prop in this.defaults){
        if(type[prop] == undefined) type[prop] = this.defaults[prop];
    }
    this.types[type.name] = type;
}
o.getType = function(l){
    for(var type in this.types){
        if(l.className.indexOf(type) > -1) return type;
    }
    return "standard";
}
o.attachBehavior = function(l,type){
    var t = this.types[type];
    l.title = t.title;
    l.popupProperties = {
        type: type,
        ref: this
    };
    l.onclick = function(){
        this.popupProperties.ref.open(this.href,this.popupProperties.type);
        return false;
    }
}
o.booleanToWord = function(bool){
    if(bool) return "yes";
    return "no";
}
o.getTopLeftCentered = function(typeObj){
    var t = typeObj;
    var r = {left:t.left, top:t.top};
    var sh = screen.availHeight-20;
    var sw = screen.availWidth-10;
    if(!sh || !sw) return r;
    r.left = (sw/2)-(t.width/2);
    r.top = (sh/2)-(t.height/2);
    return r;
}
o.getParamsOfType = function(typeObj){
    var t = typeObj;
    var c = this.booleanToWord;
    if(t.center){
        var tc = this.getTopLeftCentered(typeObj);
        t.left = tc.left;
        t.top = tc.top;
    }
    var p = "width="+t.width;
    p+=",height="+t.height;
    p+=",left="+t.left;
    p+=",top="+t.top;
    p+=",location="+c(t.location);
    p+=",resizable="+c(t.resizable);
    p+=",scrollbars="+c(t.scrollbars);
    p+=",status="+c(t.status);
    p+=",toolbar="+c(t.toolbar);
    p+=",menubar="+c(t.menubar);
    return p;
}
o.open = function(url,type){
    if(!type) type = "standard";
    var t = this.types[type];
    var p = this.getParamsOfType(t);
    var w = window.open(url,t.name,p);
    if(w) w.focus();
    return false;
}
$(document).ready(function() {
    
    popup = new PopUp();
    popup.apply();
    
    $(function(){
        $('form').jqTransform({imgPath:'jqtransformplugin/img/'});
    });
    
    $("#lng ul li:last-child").addClass("last");
    $("#sidebar ul li:last-child").addClass("last");
    
    $(".bucket").hover(function() {
        $(this).find(".bucket-subline").addClass("over");
    }, function() {
        $(this).find(".bucket-subline").removeClass("over");
    });
    $(".buckets div:last-child").addClass("last");
    
    $("#footer li").hover(function() {
        $(this).addClass("over");
    }, function() {
        $(this).removeClass("over");
    });
    
    $(".tabContainer div:first").addClass("current");
     $("ul.tabNav li:first").addClass("current");
    $('ul.tabNav a').click(function() {
        var curChildIndex = $(this).parent().prevAll().length + 1;
        $(this).parent().parent().children('.current').removeClass('current');
        $(this).parent().addClass('current');
        
        $(this).parent().parent().next('.tabContainer').children('.current').slideUp('normal',function() {
            $(this).removeClass('current');
            $(this).parent().children('div:nth-child('+curChildIndex+')').slideDown('normal',function() {
                $(this).addClass('current');
            });
        });
        return false;                                
    });
});


/* Whish list */

var lightwindow = {
    
    options: {
        overlayId: 'overlay',
        lightwindowId: 'lightwindow',
        lightwindowTopDelta: 270
    },
    
    objOverlay: null,
    objLightwindow: null,
    
    show: function(){
        
        this.objOverlay = jQuery('#'+this.options.overlayId).get(0);
        this.objLightwindow = jQuery('#'+this.options.lightwindowId).get(0);
        if ((this.objOverlay != null) && (this.objLightwindow != null)) {
        
            //Position
            this.setElementsPosition();
            
            //Events
            jQuery(window).bind('resize', function(){ 
                lightwindow.setElementsPosition();
            });
            
        }
        
    },
    
    setElementsPosition: function(){
        
        lightwindow.objLightwindow.style.display = 'none';
        lightwindow.objOverlay.style.display = 'none';
        
          var arrayPageSize = lightwindow.getPageSize();
          var arrayPageScroll = lightwindow.getPageScroll();
        //Overlay
        lightwindow.objOverlay.style.display = 'block';
        lightwindow.objOverlay.style.height = (arrayPageSize[1] + 'px');
        lightwindow.objOverlay.style.width = (arrayPageSize[0] + 'px');
        
        //Lightwindow
        lightwindow.objLightwindow.style.display = 'block';
        
        var lightwindowTop = arrayPageScroll[1] + ((arrayPageSize[3] - lightwindow.options.lightwindowTopDelta - lightwindow.objLightwindow.offsetHeight) / 2);
        lightwindowTop = (lightwindowTop < 0) ? 0 : lightwindowTop;
        
        var lightwindowLeft = ((arrayPageSize[0] - lightwindow.objLightwindow.offsetWidth) / 2);
        
        lightwindow.objLightwindow.style.top = (lightwindowTop < 0) ? "0px" : lightwindowTop + "px";
        lightwindow.objLightwindow.style.left = (lightwindowLeft < 0) ? "0px" : lightwindowLeft + "px";
    },
    
    hide: function(){
        jQuery(window).unbind('resize');
        jQuery('#'+this.options.overlayId).hide();
        jQuery('#'+this.options.lightwindowId).hide();
    },
    
    getPageScroll: function(){
    
        var yScroll;
    
        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop){     // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
        } else if (document.body) {// all other Explorers
            yScroll = document.body.scrollTop;
        }
    
        var arrayPageScroll = new Array('',yScroll) 
        return arrayPageScroll;
    },
    
    
    getPageSize: function(){
        
        var xScroll, yScroll;
        
        if (window.innerHeight && window.scrollMaxY) {    
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }
        
        var windowWidth, windowHeight;
        if (self.innerHeight) {    // all except Explorer
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }    
        
        // for small pages with total height less then height of the viewport
        var pageHeight = null;
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else { 
            pageHeight = yScroll;
        }
    
        // for small pages with total width less then width of the viewport
        var pageWidth = null;
        if(xScroll < windowWidth){    
            pageWidth = windowWidth;
        } else {
            //Firefox - minus Scrollbalken, wenn Y-Scrolling vorhanden ist
            if (window.innerHeight && window.scrollMaxY) {    
              if (yScroll > windowHeight) xScroll = xScroll - 16;
            }        
            pageWidth = xScroll; 
        }
    
        var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight); 
        return arrayPageSize;
    }
    
};


var wishList = {
    
    serverAppURL: '/xchg/nl/wishlist-webservice.xml',
    wishlistPageURL: '/xchg/nl/hs.xsl/1153.html',
    redirectPageURL: '/xchg/nl/hs.xsl/index.html',
    mandatoryFieldText: 'mandatory field',
    zipCodeFormatFalseText: 'zipcode false',
    productLimit: 10,
    confirmationMessage: {
        0: 'Data has been sent',
        1: 'The product has been added to the wishlist',
        2: 'Send error',
        3: 'Data error',
        4: 'Wish list is empty',
        5: 'Form submit error',
        6: 'Error: product limit'
    },
    
    itemLabel: {
        windowHeadlinePopupAddToWishList: 'Add to wish list',
        windowHeadlinePopupCustomerData: 'Customer data',
        windowHeadlinePopupConditions: 'Conditions',
        windowHeadlinePopupErrorMessage: 'Error',
        buttonJoinParty: 'Join a party',
        buttonAddToWishList: 'Add to wish list',
        confirmationWishListAnchorLabel: 'View your Wishlist'
    },
    
    productData: {
            pid: null,
            name: null,
            price: null,
            imageURL: null,
            fileName: null
    },
    
    buttonJoinPartyEnabled: true,
    buttonAddToWhishListEnabled: true,
    ajaxError: false,
    mainWindowHeadline: '',
    submitAllowed: false,
    
    showPopupForm: function(){
    
        //Init form items
        jQuery('#lightwindow .buttonsPanel').show();
        jQuery('#lightwindow .productDetails').show();
        this.enablePopupFormButtons();
        jQuery('#lightwindow .contactForm').hide();
        jQuery('#lightwindow .confirmationMessage').hide();
        
        //Light window
        lightwindow.show();
    },
    
    initPopupForm: function(productData){
        
        this.productData = jQuery.extend(this.productData, productData);
        
        //transfer lightwindow elements in body
        jQuery('#overlay').appendTo('body');
        jQuery('#lightwindow').appendTo('body');
        
        //Wish list icon - Anchor URL
        jQuery('#wishlistInfo a').attr('href', this.wishlistPageURL);
        
        //Close button
        jQuery('#lightwindow .closeButton a').bind('click', function(){ 
            wishList.closePopupForm();
        });
        
        //Window headline
        jQuery('#lightwindow .head h1').html(this.itemLabel.windowHeadlinePopupAddToWishList);
        
        //Button "Join a party"
        jQuery('#lightwindow #joinParty').html(this.itemLabel.buttonJoinParty);
        jQuery('#lightwindow #joinParty').bind('click', function(){
            if (wishList.buttonJoinPartyEnabled == true) wishList.showPopupFormContact();
        });
        
        //Button "Add to whish list"
        jQuery('#lightwindow #addToWhishList').html(this.itemLabel.buttonAddToWishList);
        jQuery('#lightwindow #addToWhishList').bind('click', function(){
            
            if (wishList.buttonAddToWhishListEnabled == true) {
            
                wishList.disablePopupFormButtons();
                wishList.hidePopupFormContact();
                
                //product limit test
                wishList.ajaxError = true;
                jQuery.get(wishList.serverAppURL, { mode: 'list'} , function(xml){
                    wishList.ajaxError = false;
                    var items = wishList.getNodes(xml, 'item');
                    
                    var productQuantity = 0;
                    for(var i=0;i<items.length;i++){
                        if (items[i].getAttribute('id') == wishList.productData.pid) {
                            productQuantity = wishList.getNodeValue(items[i],'quantity');
                        }
                    }
                    
                    if (productQuantity < wishList.productLimit) {
                    
                        //AJAX-Request
                        wishList.ajaxError = true;
                        jQuery.get(wishList.serverAppURL, { mode: 'add', 
                                                            pid: wishList.productData.pid,
                                                            fileName: wishList.productData.fileName
                                                                                          }, function(xml){
                            wishList.ajaxError = false;
                            
                            //answer behandeln
                            var responsePid = wishList.getAttributeValueFromNode(xml, 'item', 'id');
                            
                            if (responsePid != wishList.productData.pid){ //data error 
                                wishList.showConfirmationMessage(wishList.confirmationMessage[3], 0);
                            } else {
                                wishList.showConfirmationMessage(wishList.confirmationMessage[1]+'<br/><a href="'+wishList.wishlistPageURL+'">'+wishList.itemLabel.confirmationWishListAnchorLabel+'</a>', 0);
                            }
                            
                            //refresh wish list icon
                            wishList.getWishListLenght();
                        });
                    
                    
                    } else {
                        wishList.showConfirmationMessage(wishList.confirmationMessage[6], 0);
                    }
                    
                });
                
                
                //if send error - in 30 sec. hide window
                window.setTimeout(function(){
                    if (wishList.ajaxError == true) wishList.showConfirmationMessage(wishList.confirmationMessage[2], 0);
                }, 30000);
                
              
            }
        });
        
        //Send-Button: Form "Join a party"
        jQuery('#lightwindow #sendButton').bind('click', function(){
            wishList.sendJoinPartyForm();
        });
        
        //Window headline save
        this.mainWindowHeadline = jQuery('#lightwindow .head h1').html();
        
    },
    
    showConfirmationMessage: function(message, duration){
        jQuery('#lightwindow .confirmationMessage span').html(message);
        jQuery('#lightwindow .confirmationMessage').slideDown("fast");
        
        if ((parseInt(duration)!=0) && (duration!=null)) {
            window.setTimeout("wishList.closePopupForm()", parseInt(duration));
        }
    },
    
    closePopupForm: function(){
        jQuery('#lightwindow .contactForm').hide();
        window.setTimeout(function(){ lightwindow.hide(); jQuery('#lightwindow .head h1').html(wishList.mainWindowHeadline); },100); 
    },
    
    showPopupFormContact: function(){
        
        jQuery('#lightwindow .buttonsPanel').slideUp("fast", function(){});        
        jQuery('#lightwindow .productDetails').slideUp("fast", function(){});
        
        jQuery('#lightwindow .contactForm .wrapper').hide();
        jQuery('#lightwindow .contactForm').slideDown("fast", function(){
            jQuery('#lightwindow .contactForm .wrapper').show();
        });
    },
    
    hidePopupFormContact: function(){
        jQuery('#lightwindow .contactForm .wrapper').hide();
        jQuery('#lightwindow .contactForm').slideUp("fast", function(){
            jQuery('#lightwindow .contactForm .wrapper').show();
        });
    },
    disablePopupFormButtons: function(){
        jQuery('#lightwindow #joinParty').addClass('disable');
        jQuery('#lightwindow #addToWhishList').addClass('disable');
        
        wishList.buttonJoinPartyEnabled = false;
        wishList.buttonAddToWhishListEnabled = false;
    },
    enablePopupFormButtons: function(){
        jQuery('#lightwindow #joinParty').removeClass('disable');
        jQuery('#lightwindow #addToWhishList').removeClass('disable');
        
        wishList.buttonJoinPartyEnabled = true;
        wishList.buttonAddToWhishListEnabled = true;
    },
    isJoinPartyFormValid: function(formData){
        
        var valid = true;
        if (formData.lastname == '') { valid = false; this.markField('lastname')} else this.clearField('lastname');
        
        if ((formData.zipcode == '') || (formData.zipcode_abc == ''))  { valid = false; this.markField('zipcode');} 
        else if ((formData.zipcode != '') && ( (!parseInt(formData.zipcode)) || (parseInt(formData.zipcode) < 1000) || (parseInt(formData.zipcode) > 9999) )) { valid = false; jQuery('#zipcode_error').html('&nbsp;'+this.zipCodeFormatFalseText);} else this.clearField('zipcode');
        
        if (formData.telephone == '') { valid = false; this.markField('telephone')} else this.clearField('telephone');
        if (!(formData.email.search(/[@.]/) >= 0) || !(formData.email.search(/.+@..+\...+/) >= 0) || !(formData.email.length >= 8)) { valid = false; this.markField('email')} else this.clearField('email');
        if (!(formData.email_repeat.search(/[@.]/) >= 0) || !(formData.email_repeat.search(/.+@..+\...+/) >= 0) || !(formData.email_repeat.length >= 8) || (formData.email != formData.email_repeat)) { valid = false; this.markField('email_repeat')} else this.clearField('email_repeat');
        
        return valid;
    },
    
    sendJoinPartyForm: function(){
    
       var formData = this.getFormData('joinPartyForm');
       
       if (this.isJoinPartyFormValid(formData) == true){
       
          this.disablePopupFormButtons();
          this.hidePopupFormContact();
       
          //Send data per AJAX
          wishList.ajaxError = true;
          jQuery.get(wishList.serverAppURL, { mode: 'customerDataJoinPartyForm', 
                                              lastname: formData.lastname, 
                                              zipcode: formData.zipcode, 
                                              zipcode_abc: formData.zipcode_abc, 
                                              telephone: formData.telephone, 
                                              email: formData.email, 
                                              ever_visit_party: formData.ever_visit_party,
                                              gender: formData.gender,
                                              age_category: formData.age_category,
                                              flagNewsletter: formData.flagNewsletter
                                                                                        }, function(xml){
              wishList.ajaxError = false;
              
              if (wishList.getNode(xml, 'item') != null) { //submit form - OK
              
                  //Show message
                  wishList.showConfirmationMessage(wishList.confirmationMessage[0], 0);
                  
              } else { //submit form - Fehler
                  
                  //Show message
                  wishList.showConfirmationMessage(wishList.confirmationMessage[5], 0);
                  
              }
          });             
           
          //if send error - in 30 sec. hide window
          window.setTimeout(function(){
              if (wishList.ajaxError == true)  wishList.showConfirmationMessage(wishList.confirmationMessage[2], 0);
          }, 30000);
                
       } 
    },
    
    getFormData: function(formName){
        
        var data = new Array();
        if(document.forms[formName]) {
           for(var i=0; i<document.forms[formName].elements.length;i++){
               if ((document.forms[formName].elements[i].type.toLowerCase() == 'text') || (document.forms[formName].elements[i].type.toLowerCase() == 'textarea')  ) {
                   data[document.forms[formName].elements[i].name] = document.forms[formName].elements[i].value;
               } else if (document.forms[formName].elements[i].type.toLowerCase() == 'checkbox') {
                   data[document.forms[formName].elements[i].name] = document.forms[formName].elements[i].checked;
               } else if (document.forms[formName].elements[i].type.toLowerCase() == 'radio') {
                   if (typeof(data[document.forms[formName].elements[i].name]) == 'undefined') data[document.forms[formName].elements[i].name] = '';
                   if (document.forms[formName].elements[i].checked) data[document.forms[formName].elements[i].name] = document.forms[formName].elements[i].value;
               }
           }
        }
        return data;
    },
    
    markField: function(fieldId){
        jQuery('#'+fieldId + '_error').html('&nbsp;'+this.mandatoryFieldText);
    },
    
    clearField: function(fieldId){
        jQuery('#'+fieldId + '_error').html('&nbsp;*');
    },
    
    
    getWishListLenght: function(){
        
        jQuery('#wishlistInfo').hide();
        
        //AJAX-Request
        wishList.ajaxError = true;
        jQuery.get(wishList.serverAppURL, { mode: 'getLength' }, function(xml){
            wishList.ajaxError = false;
            var wishListLength = wishList.getNodeValue(xml, 'wishListLength');
            if (!(wishListLength == null) && (wishListLength != 0)) {
                jQuery('#wishlistInfo').show();
                jQuery('#wishlistInfo a').html(wishListLength);
            } else {
                jQuery('#wishlistInfo').hide();
            }
        });        
        
    },
    
    submitWishListForm: function(){
        
        if (wishList.submitAllowed == true) { //show customer data window
        
            var valid = true;
            
            if (!document.wishListForm.agb.checked) {
                valid = false;
                jQuery('#agbContainer').addClass('error');
            } else jQuery('#agbContainer').removeClass('error');
            
            if (!document.wishListForm.visit.checked) {
                valid = false;
                jQuery('#visitContainer').addClass('error');
            } else jQuery('#visitContainer').removeClass('error');
            
            
            
            if (valid)  {
                
                //init lightwindow items
                jQuery('#lightwindow .contactForm').show();
                jQuery('#lightwindow .confirmationMessage').hide();
                jQuery('#lightwindow #sendButton').show();
                
                //Conditions text
                jQuery('#lightwindow #conditionsTextContainer').hide();
                
                //Error message
                jQuery('#lightwindow #errorMessageContainer').hide();
                
                //show lightwindow
                lightwindow.show();
                
                return false;            
            }
            else {
                return false;
            }
            
            
        } else { //show error messsage window
            this.showErrorMessageWindow();
            return false;
        }
        
    },
    
    
    updateProductQuantity: function(pid){
    
        wishList.ajaxError = true;
        jQuery.get(wishList.serverAppURL, { mode: 'update', pid: pid, quantity: wishList.getProductQuantity(pid)}, function(xml){
            wishList.ajaxError = false;
            
            //Product data
            var productNode = wishList.getNode(xml, 'item');
            var responsePid = wishList.getAttributeValueFromNode(xml, 'item', 'id'); 
            jQuery('#prod_' + responsePid + '_price').html(wishList.getNodeValue(productNode, 'price') + ' &euro;');
            
            //Total data
            jQuery('#subtotal').html(wishList.getNodeValue(xml, 'subtotal') + ' &euro;');
            jQuery('#deliveryFee').html(wishList.getNodeValue(xml, 'deliveryFee') + ' &euro;');
            jQuery('#total').html(wishList.getNodeValue(xml, 'total') + ' &euro;');
            
            wishList.submitAllowed = ( wishList.getNodeValue(xml, 'submitAllowed').toLowerCase() == 'true' ) ? true : false;
            
        });             
    
    },
    
    deleteProduct: function(pid){
    
        wishList.ajaxError = true;
        jQuery.get(wishList.serverAppURL, { mode: 'delete', pid: pid }, function(xml){
            wishList.ajaxError = false;
            
            //Delete product html
            var responsePid = wishList.getAttributeValueFromNode(xml, 'item', 'id');
            var responseWishListLength = wishList.getNodeValue(xml, 'wishListLength'); 
            
            if ((responseWishListLength == 0) || (responseWishListLength == "")) { //wish list is empty
                jQuery('#prod_' + responsePid).hide(); 
                jQuery('#prod_' + responsePid).html('&nbsp;');
                jQuery('#infoPanel_01').hide();
                jQuery('#infoPanel_02').html(wishList.confirmationMessage[4]);
                jQuery('#infoPanel_03').html('&nbsp;');
            } else {
            
                jQuery('#prod_' + responsePid).hide(); 
                jQuery('#prod_' + responsePid).html('&nbsp;');
                
                //Total data
                if (wishList.getNodeValue(xml, 'subtotal') != null) jQuery('#subtotal').html(wishList.getNodeValue(xml, 'subtotal') + ' &euro;');
                if (wishList.getNodeValue(xml, 'deliveryFee') != null) jQuery('#deliveryFee').html(wishList.getNodeValue(xml, 'deliveryFee') + ' &euro;');
                if (wishList.getNodeValue(xml, 'total') != null) jQuery('#total').html(wishList.getNodeValue(xml, 'total') + ' &euro;');
                
                wishList.submitAllowed = ( wishList.getNodeValue(xml, 'submitAllowed').toLowerCase() == 'true' ) ? true : false;
                
            }//wish list is NOT empty 
            
            //refresh wish list icon
            wishList.getWishListLenght();
            
        });             
    
    },
    
    getProductQuantity: function(pid){
    
        var objSelect = jQuery('#prod_'+pid+'_quantity').get(0);
        if (objSelect) {
            return objSelect.options[objSelect.selectedIndex].text;
        } else return null;
    },
    
    initCustomerContactDataForm: function(){
        //transfer lightwindow elements in body
        jQuery('#overlay').appendTo('body');
        jQuery('#lightwindow').appendTo('body');
        
        //Close button
        jQuery('#lightwindow .closeButton a').bind('click', function(){ 
            wishList.closePopupForm();
        });
        //Window headline
        jQuery('#lightwindow .head h1').html(this.itemLabel.windowHeadlinePopupCustomerData);
        
        //Send-Button: Form "Customer contact data"
        jQuery('#lightwindow #sendButton').bind('click', function(){
            wishList.sendCustomerDataContactForm();
        });
        
        //Close button bottom (Conditions window)
        jQuery('#lightwindow #conditionsTextContainer .sendButton').bind('click', function(){
            wishList.closePopupForm();
        });
        
        //Close button bottom (Error message window)
        jQuery('#lightwindow #errorMessageContainer .sendButton').bind('click', function(){
            wishList.closePopupForm();
        });
        
        //Window headline save
        this.mainWindowHeadline = jQuery('#lightwindow .head h1').html();
    },
    
    sendCustomerDataContactForm: function(){
       var formData = this.getFormData('customerDataContactForm');
       
       if (this.isJoinPartyFormValid(formData) == true){
       
          jQuery('#lightwindow #sendButton').hide();
       
          //Send data per AJAX
          wishList.ajaxError = true;
          jQuery.get(wishList.serverAppURL, { mode: 'customerDataContactForm', 
                                              lastname: formData.lastname, 
                                              zipcode: formData.zipcode, 
                                              zipcode_abc: formData.zipcode_abc, 
                                              telephone: formData.telephone, 
                                              email: formData.email, 
                                              ever_visit_party: formData.ever_visit_party,
                                              gender: formData.gender,
                                              age_category: formData.age_category,
                                              flagNewsletter: formData.flagNewsletter                                              
                                                                                        }, function(xml){
              wishList.ajaxError = false;
              
              if (wishList.getNode(xml, 'item') != null) { //submit form - OK
              
                  //Show message
                  wishList.showConfirmationMessage(wishList.confirmationMessage[0], 0);
                  
                  //Close button
                  jQuery('#lightwindow .closeButton a').bind('click', function(){ 
                      //Weiterleitung -> home page
                      window.setTimeout(function(){window.location.href = wishList.redirectPageURL}, 500);
                  });
                  
              
              } else { //submit form - Fehler
                  
                  //Show message
                  wishList.showConfirmationMessage(wishList.confirmationMessage[5], 0);
                  
              }
              
          });             
           
          //if send error - in 30 sec. hide window
          window.setTimeout(function(){
              if (wishList.ajaxError == true) wishList.showConfirmationMessage(wishList.confirmationMessage[2], 0);
          }, 30000);
       } 
    },
    
    getNodeValue: function(scope, node){ 
      if ( (scope != null) && (scope.getElementsByTagName(node).length != 0 ) ) {
              if (scope.getElementsByTagName(node)[0].firstChild == null) return '';
              else return scope.getElementsByTagName(node)[0].firstChild.nodeValue;
          }
      else return null;
    },
    getAttributeValueFromNode: function(scope, node, attribute){
      if ( (scope != null) && (scope.getElementsByTagName(node).length != 0 ) )
          return scope.getElementsByTagName(node)[0].getAttribute(attribute);
      else return null;
    },
    
    getNode: function(scope, node){
      if ( (scope != null) && (scope.getElementsByTagName(node).length != 0 ) )
          return scope.getElementsByTagName(node)[0];
      else return null;    
    },
    
    getNodes: function(scope, node){
      if ( (scope != null) && (scope.getElementsByTagName(node).length != 0 ) )
          return scope.getElementsByTagName(node);
      else return new Array();    
    },
    
    showConditions: function(){
        //init lightwindow items
        jQuery('#lightwindow .contactForm').hide();
        jQuery('#lightwindow .confirmationMessage').hide();
        jQuery('#lightwindow #sendButton').hide();
        jQuery('#lightwindow #errorMessageContainer').hide();
        
        //Conditions panel items
        jQuery('#lightwindow #conditionsTextContainer').show();
        jQuery('#lightwindow #conditionsTextContainer .sendButton').show();
       
        //Window headline
        jQuery('#lightwindow .head h1').html(this.itemLabel.windowHeadlinePopupConditions);
        
        //show lightwindow
        lightwindow.show();
        
    },
    
    showErrorMessageWindow: function(){
    
        //init lightwindow items
        jQuery('#lightwindow .contactForm').hide();
        jQuery('#lightwindow .confirmationMessage').hide();
        jQuery('#lightwindow #sendButton').hide();
        jQuery('#lightwindow #conditionsTextContainer').hide();
        
        //Conditions panel items
        jQuery('#lightwindow #errorMessageContainer').show();
        jQuery('#lightwindow #errorMessageContainer .sendButton').show();
       
        //Window headline
        jQuery('#lightwindow .head h1').html(this.itemLabel.windowHeadlinePopupErrorMessage);
        
        //show lightwindow
        lightwindow.show();
    
    }
    
};

var distMap = {
    
    serverAppURL: '/xchg/nl/dealer-locator.xml',
    
    c: {
        gmContainerId: 'gmap',
        mapZoom: 8,
        mapZoomDetail: 15,
        countryName: 'Nederland',

        markType: {
          0: {icon: '/xbcr/nl/default-marker.png'},
          1: {icon: '/xbcr/nl/green-marker.png'},
          2: {icon: '/xbcr/nl/blue-marker.png'},
          3: {icon: '/xbcr/nl/red-marker.png'}
        },

        infoTableId: {
             distributor: 'gmapInfoTableDistributor',
             customer: 'gmapInfoTableCustomer',
             dealer: 'gmapInfoTableDealer'
        }
    },
    
    message: {
        0: 'The position of the customer cannot be found.'
    },
    
    obj: null,
    geocoder: null,
    disributerNumber: null,
    customerZipcode: null,              
    dealers: new Array(),
                  
    init: function(config){
        
        this.c = jQuery.extend(this.c, config);
        this.disributerNumber = this.getUrlParameterByName('ds');
        this.customerZipcode = this.getUrlParameterByName('customerzip');
        
        if ((this.disributerNumber!=null) && (this.customerZipcode!=null)) {
        
          var mapObject = jQuery('#'+this.c.gmContainerId).get(0);
          
          var isGMap2 = (typeof(GBrowserIsCompatible) != "undefined") ? true : false;
          
          if ((isGMap2) && (GBrowserIsCompatible()) && (mapObject) ){
              
              distMap.obj = new GMap2(mapObject);
              distMap.obj.setMapType(G_NORMAL_MAP);
              distMap.addControl();
              
              distMap.geocoder = new GClientGeocoder();
              
              distMap.showDistributorEDealerMarks();
              distMap.showCustomerMark();
  
          }
        
        }
        
    },
    
    addControl: function(){
    
      distMap.obj.removeMapType(G_HYBRID_MAP);
      distMap.obj.addMapType(G_PHYSICAL_MAP);
      distMap.obj.addControl(new GSmallMapControl());
      distMap.obj.addControl(new GMapTypeControl());
    },
    
    showDistributorEDealerMarks: function(){
    
        jQuery.get(this.serverAppURL, { ds: this.disributerNumber} , function(xml){
            
            
            //E-Dealer
            var dealers = distMap.getNodes(xml,'eDealer'); 
            
            for(var i=0;i<dealers.length;i++){
            
                distMap.tmp = dealers[i];
                 
                var dealer = {
                    firstname:  distMap.getNodeValue(dealers[i], 'firstname'),
                    middlename: distMap.getNodeValue(dealers[i], 'middlename'),
                    lastname:   distMap.getNodeValue(dealers[i], 'lastname'),
                    street:     distMap.getNodeValue(dealers[i], 'street'),
                    housenum:   distMap.getNodeValue(dealers[i], 'housenum'),
                    houseext:   distMap.getNodeValue(dealers[i], 'houseext'),
                    zipcode:    distMap.getNodeValue(dealers[i], 'zipcode'),
                    city:       distMap.getNodeValue(dealers[i], 'city'),
                    dealnum:    distMap.getNodeValue(dealers[i], 'dealnum'),
                    distnum:    distMap.getNodeValue(dealers[i], 'distnum'),
                    lat:        distMap.getNodeValue(dealers[i], 'lat'),
                    lng:        distMap.getNodeValue(dealers[i], 'lng'),
                    infoWindowHtml: '',
                    marker: null
                };
                
                
                dealer.infoWindowHtml = '<div class="infoWindowContent" style="height: 100px;">'+
                                     '<b>E-Dealer</b><br/>'+
                                     'Number: ' + dealer.dealnum + '<br/>' +
                                     dealer.firstname + ' '+ dealer.middlename + ' '+ dealer.lastname + '<br/>' +
                                     dealer.street + ' ' + dealer.housenum + ' ' + dealer.houseext + '<br/>'+
                                     dealer.zipcode + ' ' + dealer.city + '<br/>'+
                                     distMap.c.countryName +'<br/>'+
                                     '</div>';
                
                dealer.marker = distMap.showMarker(1, dealer.lat, dealer.lng, dealer.infoWindowHtml);
                
                distMap.dealers[i] = dealer;
                
                //Dealer - InfoTable - Line
                var anchorId = 'dealerLink'+dealer.dealnum;
                jQuery('#'+distMap.c.infoTableId.dealer + ' table').append(
                  '<tr>' +
                      '<td>'+dealer.dealnum+'</td>' +
                      '<td>' + dealer.firstname + ' ' + dealer.middlename + ' ' +dealer.lastname +'</td>' +
                      '<td><a id="'+anchorId+'" href="javascript: void(0)">'+ dealer.street + ' ' + dealer.housenum + ' ' + dealer.houseext + ', ' + dealer.zipcode + ' ' + dealer.city + ', ' + distMap.c.countryName +'</a></td>' +
                  '</tr>'
                );
                
                distMap.initLinkToMarker(anchorId, distMap.dealers[i].marker, distMap.dealers[i].infoWindowHtml);
                
            }//for
            
            //Distributor
            var distNode = distMap.getNode(xml,'distributor'); 
            
            var ds = {
                id:         distMap.getAttributeValueFromNode(xml, 'distributor', 'id'),
                name:       distMap.getNodeValue(distNode, 'distname'),
                number:     distMap.getNodeValue(distNode, 'distnum'),
                street:     distMap.getNodeValue(distNode, 'street'),
                zipcode:    distMap.getNodeValue(distNode, 'zipcode'),
                city:       distMap.getNodeValue(distNode, 'city'),
                lat:        distMap.getNodeValue(distNode, 'lat'),
                lng:        distMap.getNodeValue(distNode, 'lng'),
                infoWindowHtml: ''
            };
            
            ds.infoWindowHtml =  '<div class="infoWindowContent" style="height: 80px;">'+
                                 '<b>Distributor</b><br/>'+
                                 ds.name + '<br/>'+
                                 ds.street + '<br/>'+
                                 ds.zipcode + ' ' + ds.city +'<br/>'+
                                 distMap.c.countryName +'<br/>'+
                                 '</div>';
            
            var distMarker = distMap.showMarker(3, ds.lat, ds.lng, ds.infoWindowHtml);
            distMap.obj.setCenter(new GLatLng(ds.lat, ds.lng), distMap.c.mapZoom);
            //Distributor - InfoTable
            var anchorId = 'distLink'+ds.number;
            jQuery('#'+distMap.c.infoTableId.distributor + ' table').append(
              '<tr><td>'+ds.number+'</td><td>'+ds.name+'</td><td><a id="'+anchorId+'" href="javascript: void(0)">'+ ds.street + ', ' + ds.zipcode + ' ' + ds.city + ', ' + distMap.c.countryName +'</a></td></tr>'
            );

            distMap.initLinkToMarker(anchorId, distMarker, ds.infoWindowHtml);
            
        });
    
    },
    
    
    initLinkToMarker: function(anchorId, marker, infoWindowHtml){
      jQuery('#'+anchorId).bind('click', function(){
          var point = marker.getLatLng();
          distMap.obj.setCenter(new GLatLng(point.lat(), point.lng()), distMap.c.mapZoomDetail);
          marker.openInfoWindowHtml(infoWindowHtml, {maxWidth: 220});
      });
    },
    
    
    showCustomerMark: function(){
    
      distMap.geocoder.getLatLng(distMap.customerZipcode+' '+distMap.c.countryName+', Europa', function(point) {
      
        if (point) {
        
          var infoWindowHtml = '<div class="infoWindowContent">'+
                               '<b>Customer</b><br/>'+
                               distMap.customerZipcode + '<br/>' + distMap.c.countryName + '<br/>'+
                               '</div>';
                               
          var customerMarker = distMap.showMarker(2, point.lat(), point.lng(), infoWindowHtml);
          
          
          //Customer - InfoTable
          var anchorId = 'customerLink';
          jQuery('#'+distMap.c.infoTableId.customer + ' table').append(
            '<tr><td><a id="'+anchorId+'" href="javascript: void(0)">'+ distMap.customerZipcode +'</a></td></tr>'
          );
          distMap.initLinkToMarker(anchorId, customerMarker, infoWindowHtml);
          
        } else {
          jQuery('#'+distMap.c.infoTableId.customer + ' table').append(
            '<tr><td>' + distMap.message[0] + ' (Zipcode: ' + distMap.customerZipcode + ')' +'</td></tr>'
          );
        }
        
      });
    
    },
    
    showMarker: function(type, lat, lng, infoWindowContent){
      
       var myHtml = infoWindowContent;
      
       //Marker icon object
       var PointIcon= new GIcon(G_DEFAULT_ICON);
       switch (type){
            case 1:
            case 2:
            case 3:
              PointIcon.image = distMap.c.markType[type].icon;  
            break;
            default:
              PointIcon.image = distMap.c.markType[0].icon;  
            break;
       }
       PointIcon.iconSize = new GSize(20, 34);
       
       //Marker
       var marker = new GMarker(new GLatLng(lat,lng),{draggable: false ,icon: PointIcon});
       distMap.obj.addOverlay(marker);
       
       //Info window
       GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(myHtml, {maxWidth: 220});
       });       
       
       return marker;
        
    },
    
    getUrlParameterByName: function(name){
        var params = window.location.search;
        if( params != "") {
            params = params.substr(1,params.length-1);
            var arr_params = params.split('&');
            for (var i=0; i<arr_params.length; i++){
                var param = arr_params[i].split('=');
                if (param[0].toLowerCase() == name.toLowerCase()) return param[1];
            }
            return null;
        } else return null;
    },
    
    getNodeValue: function(scope, node){ 
      if ( (scope != null) && (scope.getElementsByTagName(node).length != 0 ) ) {
              if (scope.getElementsByTagName(node)[0].firstChild == null) return '';
              else return scope.getElementsByTagName(node)[0].firstChild.nodeValue;
          }
      else return null;
    },

    getAttributeValueFromNode: function(scope, node, attribute){
      if ( (scope != null) && (scope.getElementsByTagName(node).length != 0 ) )
          return scope.getElementsByTagName(node)[0].getAttribute(attribute);
      else return null;
    },
    
    getNode: function(scope, node){
      if ( (scope != null) && (scope.getElementsByTagName(node).length != 0 ) )
          return scope.getElementsByTagName(node)[0];
      else return null;    
    },
    
    getNodes: function(scope, node){
      if ( (scope != null) && (scope.getElementsByTagName(node).length != 0 ) )
          return scope.getElementsByTagName(node);
      else return new Array();    
    }
        
}