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) ) || ((formData.zipcode_abc != '') && (formData.zipcode_abc.search(/^[A-Za-z]{2}$/) < 0  ))) { 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();    
    }
        
}



var formular = {
    
    classNameByError: "error",
    isSkinning: false,
    obj: null,
    element: new Array(),
    
    init: function(id){
        this.element = new Array();
        this.obj = jQuery('#'+id).get(0);
    },
    init: function(id, isSkinning){
        this.isSkinning = isSkinning;
        this.element = new Array();
        this.obj = jQuery('#'+id).get(0);
    },
    
    addElement: function(id, type, mandatory){
        
        var pattern = null;
        type = (type.substr(0,1) == "/") ? eval(type) : type;
        var typeOfType = typeof type;
        if ((typeOfType.toLowerCase() == "object") || (typeOfType.toLowerCase() == "function")){
            pattern = type;
            type = 'pattern';
        }
    
        var elm = new formElement(id, type, mandatory, pattern);
        if (elm) this.element[this.element.length] = elm;
    },
        
    validateForm: function(){
        var valid = true;
        if (this.element != null)
          for(var i=0; i < this.element.length; i++){
            if (this.element[i].checkElement() == false) valid = false;
          }
        return valid;
    }
} //formular

function formElement(id, type, mandatory, pattern){
    this.id = id;
    this.type = ((type == 'pattern') && (pattern == null)) ? 'string' : type;
    this.obj = (this.type != "radio") ? this.obj = jQuery('#'+id).get(0) : this.obj = true;
    this.pattern = pattern;    
    this.mandatory = mandatory;
    switch(this.type){
        case "radio" :
        case "checkbox" :
            this.mark_obj = jQuery("#mark_" + this.id).get(0) ? jQuery("#mark_" + this.id).get(0) : null;
            break;
        default :
            this.mark_obj = this.obj;
            break;
    }
    
    this.checkElement = function(){
        var valid = true;
        if (this.mandatory == false) return true;
        else {
            switch(this.type){
                case "string" :
                case "text" :
                    valid = this.checkTextElement();
                    break;
                case "radio":
                    valid = this.checkRadioElement();
                    break;
                case "email":
                    valid = this.checkEmailElement();
                    break;
                case "checkbox":
                    valid = this.checkCheckboxElement();
                    break;
                case "textarea":
                    valid = this.checkTextareaElement();
                    break;
                case "select":
                    valid = this.checkSelectElement();
                    break;
                case "pattern":
                    valid = this.checkPatternElement();
                    break;
                 default:
                    valid = false;
                    break;
            }
            return valid;
        }
    };
    this.checkTextElement = function(){
        if (this.obj.value != "") {
            this.clearLabelElement();
            return true;
        }
        else {
            this.markLabelElement();
            return false;
        }
    };
    this.checkRadioElement = function(){
        var valid = false;
        for (var i=0; i< formular.obj.elements.length; i++){
            if (formular.obj.elements[i].name == this.id) {
                if (formular.obj.elements[i].checked == true) {
                    this.clearLabelElement();
                    valid = true;
                }
            }
        }
        if (valid == false) this.markLabelElement();
        return valid;
    };
    this.checkEmailElement = function(){
        if (!(this.obj.value.search(/[@.]/) >= 0) || !(this.obj.value.search(/.+@..+\...+/) >= 0) || !(this.obj.value.length >= 8)) {
            this.markLabelElement();
            return false;
        } else {
            this.clearLabelElement();
            return true;
        }
        
    };
    this.checkCheckboxElement = function(){
        if (this.obj.checked != false) {
            this.clearLabelElement();
            return true;
        }
        else {
            this.markLabelElement();
            return false;
        }
    };
    this.checkTextareaElement = function(){
        if (this.obj.value != "") {
            this.clearLabelElement();
            return true;
        }
        else {
            this.markLabelElement();
            return false;
        }
    };
    this.checkSelectElement = function(){
        if (this.obj.value != "") {
            this.clearLabelElement();
            return true;
        }
        else {
            this.markLabelElement();
            return false;
        }
    };
    this.checkPatternElement = function(){
        if (!this.pattern.test(this.obj.value)){
            this.markLabelElement();
            return false;
        } else {
            this.clearLabelElement();
            return true;
        }
        
    };
    this.markLabelElement = function(){
        if (!formular.isSkinning) jQuery(this.mark_obj).addClass(formular.classNameByError);
        else {
            switch(this.type){
                case "string" :
                case "text" :
                case "email":
                case "pattern":
                    jQuery(this.mark_obj).parents('.jqTransformInputWrapper').addClass(formular.classNameByError);
                    break;
                case "textarea":
                    jQuery(this.mark_obj).parents('.jqTransformTextarea').addClass(formular.classNameByError);
                    break;
                case "select":
                    jQuery(this.mark_obj).parents('.jqTransformSelectWrapper').addClass(formular.classNameByError);
                    break;
                case "radio":
                case "checkbox":
                    jQuery(this.mark_obj).addClass(formular.classNameByError);
                    break;
            }            
        }
    };
    this.clearLabelElement = function(){
        if (!formular.isSkinning) jQuery(this.mark_obj).removeClass(formular.classNameByError);
        else {
            switch(this.type){
                case "string" :
                case "text" :
                case "email":
                case "pattern":
                    jQuery(this.mark_obj).parents('.jqTransformInputWrapper').removeClass(formular.classNameByError);
                    break;
                case "textarea":
                    jQuery(this.mark_obj).parents('.jqTransformTextarea').removeClass(formular.classNameByError);
                    break;
                case "select":
                    jQuery(this.mark_obj).parents('.jqTransformSelectWrapper').removeClass(formular.classNameByError);
                    break;
                case "radio":
                case "checkbox":
                    jQuery(this.mark_obj).removeClass(formular.classNameByError);
                    break;
            }
        }               
    };
    if (this.obj) return this;
    else return false;
}

function validateForm(){
    return formular.validateForm();
}
/* ------------------------------------------------------------------------
    Class: prettyPhoto
    Use: Lightbox clone for jQuery
    Author: Stephane Caron (http://www.no-margin-for-errors.com)
    Version: 2.5.6
------------------------------------------------------------------------- */
(function($) {
    $.prettyPhoto = {version: '2.5.6'};
    
    $.fn.prettyPhoto = function(settings) {
        settings = jQuery.extend({
            animationSpeed: 'normal', /* fast/slow/normal */
            opacity: 0.80, /* Value between 0 and 1 */
            showTitle: true, /* true/false */
            allowresize: true, /* true/false */
            default_width: 500,
            default_height: 344,
            counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
            theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
            hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
            wmode: 'opaque', /* Set the flash wmode attribute */
            autoplay: true, /* Automatically start videos: True/False */
            modal: false, /* If set to true, only the close button will close the window */
            changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
            callback: function(){}, /* Called when prettyPhoto is closed */
            markup: '<div class="pp_pic_holder"> \
                        <div class="pp_top"> \
                            <div class="pp_left"></div> \
                            <div class="pp_middle"></div> \
                            <div class="pp_right"></div> \
                        </div> \
                        <div class="pp_content_container"> \
                            <div class="pp_left"> \
                            <div class="pp_right"> \
                                <div class="pp_content"> \
                                    <div class="pp_loaderIcon"></div> \
                                    <div class="pp_fade"> \
                                        <a href="#" class="pp_expand" title="Expand the image">Expand</a> \
                                        <div class="pp_hoverContainer"> \
                                            <a class="pp_next" href="#">next</a> \
                                            <a class="pp_previous" href="#">previous</a> \
                                        </div> \
                                        <div id="pp_full_res"></div> \
                                        <div class="pp_details clearfix"> \
                                            <a class="pp_close" href="#">Close</a> \
                                            <p class="pp_description pb0 lh14"></p> \
                                            <div class="pp_nav"> \
                                                <a href="#" class="pp_arrow_previous">Previous</a> \
                                                <p class="currentTextHolder">0/0</p> \
                                                <a href="#" class="pp_arrow_next">Next</a> \
                                            </div> \
                                        </div> \
                                    </div> \
                                </div> \
                            </div> \
                            </div> \
                        </div> \
                        <div class="pp_bottom"> \
                            <div class="pp_left"></div> \
                            <div class="pp_middle"></div> \
                            <div class="pp_right"></div> \
                        </div> \
                    </div> \
                    <div class="pp_overlay"></div> \
                    <div class="ppt"></div>',
            image_markup: '<img id="fullResImage" src="" />',
            flash_markup: '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="{width}" height="{height}"><param name="wmode" value="{wmode}" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="{path}" /><embed src="{path}" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="{width}" height="{height}" wmode="{wmode}"></embed></object>',
            quicktime_markup: '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="{height}" width="{width}"><param name="src" value="{path}"><param name="autoplay" value="{autoplay}"><param name="type" value="video/quicktime"><embed src="{path}" height="{height}" width="{width}" autoplay="{autoplay}" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>',
            iframe_markup: '<iframe class="pb0 lh14" src ="{path}" width="{width}" height="{height}" frameborder="no"></iframe>',
            inline_markup: '<div class="pp_inline clearfix">{content}</div>'
        }, settings);
        
        // Fallback to a supported theme for IE6
        if($.browser.msie && parseInt($.browser.version) == 6){
            settings.theme = "light_square";
        }
        
        if($('.pp_overlay').size()==0) _buildOverlay(); // If the overlay is not there, inject it!
        
        // Global variables accessible only by prettyPhoto
        var doresize = true, percentBased = false, correctSizes,
        
        // Cached selectors
        $pp_pic_holder, $ppt, $pp_overlay,
        
        // prettyPhoto container specific
        pp_contentHeight, pp_contentWidth, pp_containerHeight, pp_containerWidth,
        
        // Window size
        windowHeight = $(window).height(), windowWidth = $(window).width(),
    
        //Gallery specific
        setPosition = 0,
        // Global elements
        scrollPos = _getScroll();
    
        // Window/Keyboard events
        $(window).scroll(function(){ scrollPos = _getScroll(); _centerOverlay(); _resizeOverlay(); });
        $(window).resize(function(){ _centerOverlay(); _resizeOverlay(); });
        $(document).keydown(function(e){
            if($pp_pic_holder.is(':visible'))
            switch(e.keyCode){
                case 37:
                    $.prettyPhoto.changePage('previous');
                    break;
                case 39:
                    $.prettyPhoto.changePage('next');
                    break;
                case 27:
                    if(!settings.modal)
                    $.prettyPhoto.close();
                    break;
            };
        });
    
        // Bind the code to each links
        $(this).each(function(){
            $(this).bind('click',function(){
                _self = this; // Fix scoping
                // Find out if the picture is part of a set
                theRel = $(this).attr('rel');
                galleryRegExp = /\[(?:.*)\]/;
                theGallery = galleryRegExp.exec(theRel);
                
                // Build the gallery array
                var images = new Array(), titles = new Array(), descriptions = new Array();
                if(theGallery){
                    $('a[rel*="'+theGallery+'"]').each(function(i){
                        if($(this)[0] === $(_self)[0]) setPosition = i; // Get the position in the set
                        images.push($(this).attr('href'));
                        titles.push($(this).find('img').attr('alt'));
                        descriptions.push($(this).attr('title'));
                    });
                }else{
                    images = $(this).attr('href');
                    titles = ($(this).find('img').attr('alt')) ?  $(this).find('img').attr('alt') : '';
                    descriptions = ($(this).attr('title')) ?  $(this).attr('title') : '';
                }
                $.prettyPhoto.open(images,titles,descriptions);
                return false;
            });
        });
    
        
        /**
        * Opens the prettyPhoto modal box.
        * @param image {String,Array} Full path to the image to be open, can also be an array containing full images paths.
        * @param title {String,Array} The title to be displayed with the picture, can also be an array containing all the titles.
        * @param description {String,Array} The description to be displayed with the picture, can also be an array containing all the descriptions.
        */
        $.prettyPhoto.open = function(gallery_images,gallery_titles,gallery_descriptions) {
            // To fix the bug with IE select boxes
            if($.browser.msie && $.browser.version == 6){
                $('select').css('visibility','hidden');
            };
            
            if(settings.hideflash) $('object,embed').css('visibility','hidden'); // Hide the flash
            
            // Convert everything to an array in the case it's a single item
            images = $.makeArray(gallery_images);
            titles = $.makeArray(gallery_titles);
            descriptions = $.makeArray(gallery_descriptions);
            image_set = ($(images).size() > 0) ?  true : false; // Find out if it's a set
            // Hide the next/previous links if on first or last images.
            _checkPosition($(images).size());
            $('.pp_loaderIcon').show(); // Do I need to explain?
        
            // Fade the content in
            $pp_overlay.show().fadeTo(settings.animationSpeed,settings.opacity);
            // Display the current position
            $pp_pic_holder.find('.currentTextHolder').text((setPosition+1) + settings.counter_separator_label + $(images).size());
            // Set the description
            if(descriptions[setPosition]){
                $pp_pic_holder.find('.pp_description').show().html(unescape(descriptions[setPosition]));
            }else{
                $pp_pic_holder.find('.pp_description').hide().text('');
            };
            // Set the title
            if(titles[setPosition] && settings.showTitle){
                hasTitle = true;
                $ppt.html(unescape(titles[setPosition]));
            }else{
                hasTitle = false;
            };
            
            // Get the dimensions
            movie_width = ( parseFloat(grab_param('width',images[setPosition])) ) ? grab_param('width',images[setPosition]) : settings.default_width.toString();
            movie_height = ( parseFloat(grab_param('height',images[setPosition])) ) ? grab_param('height',images[setPosition]) : settings.default_height.toString();
            
            // If the size is % based, calculate according to window dimensions
            if(movie_width.indexOf('%') != -1 || movie_height.indexOf('%') != -1){
                movie_height = parseFloat(($(window).height() * parseFloat(movie_height) / 100) - 100);
                movie_width = parseFloat(($(window).width() * parseFloat(movie_width) / 100) - 100);
                percentBased = true;
            }
            
            // Fade the holder
            $pp_pic_holder.fadeIn(function(){
                imgPreloader = "";
                // Inject the proper content
                switch(_getFileType(images[setPosition])){
                    case 'image':
                        // Set the new image
                        imgPreloader = new Image();
                        // Preload the neighbour images
                        nextImage = new Image();
                        if(image_set && setPosition > $(images).size()) nextImage.src = images[setPosition + 1];
                        prevImage = new Image();
                        if(image_set && images[setPosition - 1]) prevImage.src = images[setPosition - 1];
                        $pp_pic_holder.find('#pp_full_res')[0].innerHTML = settings.image_markup;
                        $pp_pic_holder.find('#fullResImage').attr('src',images[setPosition]);
                        imgPreloader.onload = function(){
                            // Fit item to viewport
                            correctSizes = _fitToViewport(imgPreloader.width,imgPreloader.height);
                            _showContent();
                        };
                        imgPreloader.onerror = function(){
                            alert('Image cannot be loaded. Make sure the path is correct and image exist.');
                            $.prettyPhoto.close();
                        };
                    
                        imgPreloader.src = images[setPosition];
                    break;
                
                    case 'youtube':
                        correctSizes = _fitToViewport(movie_width,movie_height); // Fit item to viewport
                        movie = 'http://www.youtube.com/v/'+grab_param('v',images[setPosition]);
                        if(settings.autoplay) movie += "&autoplay=1";
                    
                        toInject = settings.flash_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,movie);
                    break;
                
                    case 'vimeo':
                        correctSizes = _fitToViewport(movie_width,movie_height); // Fit item to viewport
                    
                        movie_id = images[setPosition];
                        movie = 'http://vimeo.com/moogaloop.swf?clip_id='+ movie_id.replace('http://vimeo.com/','');
                        if(settings.autoplay) movie += "&autoplay=1";
                
                        toInject = settings.flash_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,movie);
                    break;
                
                    case 'quicktime':
                        correctSizes = _fitToViewport(movie_width,movie_height); // Fit item to viewport
                        correctSizes['height']+=15; correctSizes['contentHeight']+=15; correctSizes['containerHeight']+=15; // Add space for the control bar
                
                        toInject = settings.quicktime_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,images[setPosition]).replace(/{autoplay}/g,settings.autoplay);
                    break;
                
                    case 'flash':
                        correctSizes = _fitToViewport(movie_width,movie_height); // Fit item to viewport
                    
                        flash_vars = images[setPosition];
                        flash_vars = flash_vars.substring(images[setPosition].indexOf('flashvars') + 10,images[setPosition].length);
                        filename = images[setPosition];
                        filename = filename.substring(0,filename.indexOf('?'));
                    
                        toInject =  settings.flash_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,filename+'?'+flash_vars);
                    break;
                
                    case 'iframe':
                        correctSizes = _fitToViewport(parseInt(movie_width),parseInt(movie_height)+10); // Fit item to viewport
                
                        frame_url = images[setPosition];
                        frame_url = frame_url.substr(0,frame_url.indexOf('iframe')-1);
                
                        toInject = settings.iframe_markup.replace(/{width}/g,correctSizes['width']).replace(/{height}/g,correctSizes['height']).replace(/{path}/g,frame_url);
                        settings.allowresize = false;
                    break;
                
                    case 'inline':
                        // to get the item height clone it, apply default width, wrap it in the prettyPhoto containers , then delete
                        myClone = $(images[setPosition]).clone().css({'width':settings.default_width}).wrapInner('<div id="pp_full_res"><div class="pp_inline clearfix"></div></div>').appendTo($('body'));
                        correctSizes = _fitToViewport($(myClone).width(),$(myClone).height());
                        $(myClone).remove();
                        toInject = settings.inline_markup.replace(/{content}/g,$(images[setPosition]).html());
                    break;
                };
                if(!imgPreloader){
                    $pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject;
                
                    // Show content
                    _showContent();
                };
            });
        };
        
        /**
        * Change page in the prettyPhoto modal box
        * @param direction {String} Direction of the paging, previous or next.
        */
        $.prettyPhoto.changePage = function(direction){
            if(direction == 'previous') {
                setPosition--;
                if (setPosition < 0){
                    setPosition = 0;
                    return;
                };
            }else{
                if($('.pp_arrow_next').is('.disabled')) return;
                setPosition++;
            };
            // Allow the resizing of the images
            if(!doresize) doresize = true;
            _hideContent(function(){$.prettyPhoto.open(images,titles,descriptions)});
            $('a.pp_expand,a.pp_contract').fadeOut(settings.animationSpeed);
        };
        
        /**
        * Closes the prettyPhoto modal box.
        */
        $.prettyPhoto.close = function(){
            $pp_pic_holder.find('object,embed').css('visibility','hidden');
            
            $('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animationSpeed);
            
            $pp_overlay.fadeOut(settings.animationSpeed, function(){
                $('#pp_full_res').html(''); // Kill the opened content
                
                $pp_pic_holder.attr('style','').find('div:not(.pp_hoverContainer)').attr('style',''); // Reset the width and everything that has been set.
                _centerOverlay(); // Center it
            
                // To fix the bug with IE select boxes
                if($.browser.msie && $.browser.version == 6){
                    $('select').css('visibility','visible');
                };
                
                // Show the flash
                if(settings.hideflash) $('object,embed').css('visibility','visible');
                
                setPosition = 0;
                settings.callback();
            });
            doresize = true;
        };
    
        /**
        * Set the proper sizes on the containers and animate the content in.
        */
        _showContent = function(){
            $('.pp_loaderIcon').hide();
            // Calculate the opened top position of the pic holder
            projectedTop = scrollPos['scrollTop'] + ((windowHeight/2) - (correctSizes['containerHeight']/2));
            if(projectedTop < 0) projectedTop = 0 + $ppt.height();
            // Resize the content holder
            $pp_pic_holder.find('.pp_content').animate({'height':correctSizes['contentHeight']+15},settings.animationSpeed);
            
            // Resize picture the holder
            $pp_pic_holder.animate({
                'top': projectedTop,
                'left': (windowWidth/2) - (correctSizes['containerWidth']/2),
                'width': correctSizes['containerWidth']
            },settings.animationSpeed,function(){
                $pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(correctSizes['height']).width(correctSizes['width']);
                // Fade the new image
                $pp_pic_holder.find('.pp_fade').fadeIn(settings.animationSpeed);
                // Show the nav
                if(image_set && _getFileType(images[setPosition])=="image") { $pp_pic_holder.find('.pp_hoverContainer').show(); }else{ $pp_pic_holder.find('.pp_hoverContainer').hide(); }
                // Show the title
                if(settings.showTitle && hasTitle){
                    $ppt.css({
                        'top' : $pp_pic_holder.offset().top - 25,
                        'left' : $pp_pic_holder.offset().left + 20,
                        'display' : 'none'
                    });
                    $ppt.fadeIn(settings.animationSpeed);
                };
            
                // Fade the resizing link if the image is resized
                if(correctSizes['resized']) $('a.pp_expand,a.pp_contract').fadeIn(settings.animationSpeed);
                
                // Callback!
                settings.changepicturecallback();
            });
        };
        
        /**
        * Hide the content...DUH!
        */
        function _hideContent(callback){
            // Fade out the current picture
            $pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');
            $pp_pic_holder.find('.pp_fade').fadeOut(settings.animationSpeed,function(){
                $('.pp_loaderIcon').show();
                
                if(callback) callback();
            });
            
            // Hide the title
            $ppt.fadeOut(settings.animationSpeed);
        }
    
        /**
        * Check the item position in the gallery array, hide or show the navigation links
        * @param setCount {integer} The total number of items in the set
        */
        function _checkPosition(setCount){
            // If at the end, hide the next link
            if(setPosition == setCount-1) {
                $pp_pic_holder.find('a.pp_next').css('visibility','hidden');
                $pp_pic_holder.find('a.pp_arrow_next').addClass('disabled').unbind('click');
            }else{ 
                $pp_pic_holder.find('a.pp_next').css('visibility','visible');
                $pp_pic_holder.find('a.pp_arrow_next.disabled').removeClass('disabled').bind('click',function(){
                    $.prettyPhoto.changePage('next');
                    return false;
                });
            };
        
            // If at the beginning, hide the previous link
            if(setPosition == 0) {
                $pp_pic_holder.find('a.pp_previous').css('visibility','hidden');
                $pp_pic_holder.find('a.pp_arrow_previous').addClass('disabled').unbind('click');
            }else{
                $pp_pic_holder.find('a.pp_previous').css('visibility','visible');
                $pp_pic_holder.find('a.pp_arrow_previous.disabled').removeClass('disabled').bind('click',function(){
                    $.prettyPhoto.changePage('previous');
                    return false;
                });
            };
            
            // Hide the bottom nav if it's not a set.
            if(setCount > 1) {
                $('.pp_nav').show();
            }else{
                $('.pp_nav').hide();
            }
        };
    
        /**
        * Resize the item dimensions if it's bigger than the viewport
        * @param width {integer} Width of the item to be opened
        * @param height {integer} Height of the item to be opened
        * @return An array containin the "fitted" dimensions
        */
        function _fitToViewport(width,height){
            hasBeenResized = false;
            _getDimensions(width,height);
            
            // Define them in case there's no resize needed
            imageWidth = width;
            imageHeight = height;
            if( ((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allowresize && !percentBased) {
                hasBeenResized = true;
                notFitting = true;
            
                while (notFitting){
                    if((pp_containerWidth > windowWidth)){
                        imageWidth = (windowWidth - 200);
                        imageHeight = (height/width) * imageWidth;
                    }else if((pp_containerHeight > windowHeight)){
                        imageHeight = (windowHeight - 200);
                        imageWidth = (width/height) * imageHeight;
                    }else{
                        notFitting = false;
                    };
                    pp_containerHeight = imageHeight;
                    pp_containerWidth = imageWidth;
                };
            
                _getDimensions(imageWidth,imageHeight);
            };
            return {
                width:Math.floor(imageWidth),
                height:Math.floor(imageHeight),
                containerHeight:Math.floor(pp_containerHeight),
                containerWidth:Math.floor(pp_containerWidth) + 40,
                contentHeight:Math.floor(pp_contentHeight),
                contentWidth:Math.floor(pp_contentWidth),
                resized:hasBeenResized
            };
        };
        
        /**
        * Get the containers dimensions according to the item size
        * @param width {integer} Width of the item to be opened
        * @param height {integer} Height of the item to be opened
        */
        function _getDimensions(width,height){
            width = parseFloat(width);
            height = parseFloat(height);
            
            // Get the details height, to do so, I need to clone it since it's invisible
            $pp_details = $pp_pic_holder.find('.pp_details');
            $pp_details.width(width);
            detailsHeight = parseFloat($pp_details.css('marginTop')) + parseFloat($pp_details.css('marginBottom'));
            $pp_details = $pp_details.clone().appendTo($('body')).css({
                'position':'absolute',
                'top':-10000
            });
            detailsHeight += $pp_details.height();
            detailsHeight = (detailsHeight <= 34) ? 36 : detailsHeight; // Min-height for the details
            if($.browser.msie && $.browser.version==7) detailsHeight+=8;
            $pp_details.remove();
            
            // Get the container size, to resize the holder to the right dimensions
            pp_contentHeight = height + detailsHeight;
            pp_contentWidth = width;
            pp_containerHeight = pp_contentHeight + $ppt.height() + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height();
            pp_containerWidth = width;
        }
    
        function _getFileType(itemSrc){ 
            if (itemSrc.match(/youtube\.com\/watch/i)) {
                return 'youtube';
            }else if (itemSrc.match(/vimeo\.com/i)) {
                return 'vimeo';
            }else if(itemSrc.indexOf('.mov') != -1){ 
                return 'quicktime';
            }else if(itemSrc.indexOf('.swf') != -1){
                return 'flash';
            }else if(itemSrc.indexOf('iframe') != -1){
                return 'iframe'
            }else if(itemSrc.substr(0,1) == '#'){
                return 'inline';
            }else{
                return 'image';
            };
        };
    
        function _centerOverlay(){
            if(doresize) {
                titleHeight = $ppt.height();
                contentHeight = $pp_pic_holder.height();
                contentwidth = $pp_pic_holder.width();
                
                projectedTop = (windowHeight/2) + scrollPos['scrollTop'] - ((contentHeight+titleHeight)/2);
                
                $pp_pic_holder.css({
                    'top': projectedTop,
                    'left': (windowWidth/2) + scrollPos['scrollLeft'] - (contentwidth/2)
                });
                
                $ppt.css({
                    'top' : projectedTop - titleHeight,
                    'left': (windowWidth/2) + scrollPos['scrollLeft'] - (contentwidth/2) + 20
                });
            };
        };
    
        function _getScroll(){
            if (self.pageYOffset) {
                return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset};
            } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
                return {scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft};
            } else if (document.body) {// all other Explorers
                return {scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft};
            };
        };
    
        function _resizeOverlay() {
            windowHeight = $(window).height();
            windowWidth = $(window).width();
            
            $pp_overlay.css({
                'height':$(document).height()
            });
        };
    
        function _buildOverlay(){
            // Inject the markup
            $('body').append(settings.markup);
            
            // Set my global selectors
            $pp_pic_holder = $('.pp_pic_holder');
            $ppt = $('.ppt');
            $pp_overlay = $('div.pp_overlay');
            
            $pp_pic_holder.attr('class','pp_pic_holder ' + settings.theme); // Set the proper theme
            
            $pp_overlay
                .css({
                    'opacity':0,
                    'height':$(document).height()
                    })
                .bind('click',function(){
                    if(!settings.modal)
                    $.prettyPhoto.close();
                });
            $('a.pp_close').bind('click',function(){ $.prettyPhoto.close(); return false; });
            $('a.pp_expand').bind('click',function(){
                $this = $(this); // Fix scoping
                
                // Expand the image
                if($this.hasClass('pp_expand')){
                    $this.removeClass('pp_expand').addClass('pp_contract');
                    doresize = false;
                }else{
                    $this.removeClass('pp_contract').addClass('pp_expand');
                    doresize = true;
                };
            
                _hideContent(function(){ $.prettyPhoto.open(images,titles,descriptions) });
                
                $pp_pic_holder.find('.pp_fade').fadeOut(settings.animationSpeed);
        
                return false;
            });
        
            $pp_pic_holder.find('.pp_previous, .pp_arrow_previous').bind('click',function(){
                $.prettyPhoto.changePage('previous');
                return false;
            });
        
            $pp_pic_holder.find('.pp_next, .pp_arrow_next').bind('click',function(){
                $.prettyPhoto.changePage('next');
                return false;
            });
        };
        
        _centerOverlay(); // Center it
    };
    
    function grab_param(name,url){
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( url );
      if( results == null )
        return "";
      else
        return results[1];
    }
})(jQuery);
