/*************************************************
 functions.js - Global Javascript Functions
 Walbusch.de
 Version: 1.0
 Generated: 10.02.2010
 *************************************************/

jQuery(document).ready(function() {

    // MHK:START
    /*** send form by link***/
    jQuery(".next_step").bind("click", function () {
        jQuery(this).parents("form").submit();
    });

    /*** change input value on focus ***/
    jQuery('.default').each(function() {
        var default_value = this.value;
        jQuery(this).focus(function() {
            if(this.value == default_value) {
                this.value = '';
            }
        });
        jQuery(this).blur(function() {
            if(this.value == '') {
                this.value = default_value;
            }
        });
    });
    // MHK:END

    /*** initialize autotab function***/

    jQuery('#directOrderBox\\:productCode1').autotab({ target: 'directOrderBox\\:productCode2', format: 'numeric' });
    jQuery('#directOrderBox\\:productCode2').autotab({target: 'directOrderBox\\:productCode3', format: 'numeric', previous: 'directOrderBox\\:productCode1'});
    jQuery('#directOrderBox\\:productCode3').autotab({target: 'directOrderBox\\:productSize', format: 'numeric', previous: 'directOrderBox\\:productCode2'});
    jQuery('#directOrderBox\\:productSize').autotab({previous: 'directOrderBox\\:productCode3', format: 'numeric'});

    jQuery('#productCode1').autotab({target: 'productCode2', format: 'numeric'});
    jQuery('#productCode2').autotab({target: 'productCode3', format: 'numeric', previous: 'productCode1'});
    jQuery('#productCode3').autotab({target: 'productSize', format: 'numeric', previous: 'productCode2'});
    jQuery('#productSize').autotab({previous: 'productCode3', format: 'numeric'});

    jQuery('#birthDay').autotab({target: 'birthMonth', format: 'numeric'});
    jQuery('#birthMonth').autotab({target: 'birthYear', format: 'numeric', previous: 'birthDay'});
    jQuery('#birthYear').autotab({previous: 'birthMonth', format: 'numeric'});

    jQuery('#orderGiftVoucherForm\\:birthDay2').autotab({target: 'orderGiftVoucherForm\\:birthMonth2', format: 'numeric'});
    jQuery('#orderGiftVoucherForm\\:birthMonth2').autotab({target: 'orderGiftVoucherForm\\:birthYear2', format: 'numeric', previous: 'orderGiftVoucherForm\\:birthDay2'});
    jQuery('#orderGiftVoucherForm\\:birthYear2').autotab({previous: 'orderGiftVoucherForm\\:birthMonth2', format: 'numeric'});

    jQuery('#voucherForm\\:code1').autotab({target: 'voucherForm\\:code2', format: 'numeric'});
    jQuery('#voucherForm\\:code2').autotab({target: 'voucherForm\\:code3', format: 'numeric', previous: 'voucherForm\\:code1'});
    jQuery('#voucherForm\\:code3').autotab({previous: 'voucherForm\\:code2', format: 'numeric'});

    jQuery('#cartForm\\:voucherInputForm\\:code1').autotab({target: 'cartForm\\:voucherInputForm\\:code2', format: 'numeric'});
    jQuery('#cartForm\\:voucherInputForm\\:code2').autotab({target: 'cartForm\\:voucherInputForm\\:code3', format: 'numeric', previous: 'cartForm\\:voucherInputForm\\:code1'});
    jQuery('#cartForm\\:voucherInputForm\\:code3').autotab({previous: 'cartForm\\:voucherInputForm\\:code2', format: 'numeric'});

    jQuery('#loginPart1').autotab({target: 'loginPart2', format: 'numeric'});
    jQuery('#loginPart2').autotab({format: 'numeric', previous: 'loginPart1'});


    jQuery('#validUntilDay').autotab({target: 'validUntilMonth', format: 'numeric'});
    jQuery('#validUntilMonth').autotab({target: 'validUntilYear', format: 'numeric', previous: 'validUntilDay'});
    jQuery('#validUntilYear').autotab({previous: 'validUntilMonth', format: 'numeric'});
    //    jQuery('#login_email').autotab({target:'password', format:'all'});
    //    jQuery("#password").autotab({target:'password', format:'all'})



    /*** disable deliveryAddress form ***/
    jQuery("#deliveryADD").bind("click", function () {
        if (jQuery("#deliveryADD").is(":checked")){
            var imageDisabled = jQuery(".checkmandatory").attr("src");
            jQuery("#formitems").removeClass("disable");
            jQuery("fieldset[id='formitems'] :input").removeAttr("readonly");//.removeAttr("disabled");
            jQuery(".checkmandatory").removeAttr("src", imageDisabled);
            jQuery(".checkmandatory").attr("src", imageDisabled.replace("_de",""));

        } else {
            var imageDisabled = jQuery(".checkmandatory").attr("src");
            jQuery("#formitems").addClass("disable");
            jQuery("fieldset[id='formitems'] :input").attr("readonly", "readonly");//.attr("disabled", "true");
            jQuery(".checkmandatory").attr("src", imageDisabled.replace("mandatory","mandatory_de"));
        };
    });

    /*** disable deliveryAddress, change link text ***/
    jQuery("#sendToDeliveryAddress").bind("click", function() {
        if (jQuery("#sendToDeliveryAddress").is(":checked")) {
            jQuery("#deliveryAddressSelection").removeClass("disabled");
            jQuery("#billingAddressLink").text("Rechnungsadresse");
        } else {
            if (!jQuery("#deliveryAddressSelection").hasClass("disabled")) {
                jQuery("#deliveryAddressSelection").addClass("disabled");
            }
            jQuery("#billingAddressLink").text("Rechnungs- und Lieferadresse");
        }
    });

    /*** Count Quantity ***/
    jQuery(".updown_btn_up").bind("click", function () {
        var inputField, startVal, plus, calc, maxValue;
        inputField = jQuery(this).parent().prev();
        startVal = inputField.val();
        plus = 1;
        maxValue = 9;
        if (startVal < maxValue) {
            calc = Number(startVal)+Number(plus);
            inputField.val(calc);
        }
    });
    jQuery(".updown_btn_down").bind("click", function () {
        var inputField, startVal, plus, calc;
        inputField = jQuery(this).parent().prev();
        startVal = inputField.val();
        plus = 1;
        if(startVal != 1) {
            calc = Number(startVal)-Number(plus);
            inputField.val(calc);
        };
    });

    /*** Switch Product Image ***/
    jQuery("#ColorPicker ul li a").bind("click", function () {
        var imgpath;
        imgpath = jQuery(this).attr("rel");
        jQuery(this).parent().addClass("active");
        jQuery("#productIMG").html("\<img src=\"images/"+ imgpath +"\" alt=\"Produktbild\" />");
        jQuery("#ColorPicker ul li").removeClass("active");
        jQuery("a[rel='" + imgpath + "']").parent().addClass("active")
    });

    /** initialize tooltips **/

    if(!isIPadAgent){
        jQuery(".tooltip").jTooltip({position:'top'});
        jQuery(".jTooltipLeft").jTooltip({position:'left'});
        jQuery(".jTooltipRightTop").jTooltip({position:'rightTop'});
        jQuery(".jTooltipLeftTop").jTooltip({position:'leftTop'});
    }



    //--- init toggling of active menu item ----------------------------------------------------------------------------
    jQuery(".mainnavigation li.active > a, .newCustomerNav li.active > a").one('click', function(){
        jQuery(this).find("~ ul").toggle();
        jQuery(this).parent().toggleClass("active");
        return false;
    });

    /*** change plz input field length: 7 default , 4 for 'ch' / 'at' , 5 for 'de' *******/
    jQuery(".select_country").change(
            function(e) {
                var n = 7;
                if (e.target.value == "de") {
                    n = 5;
                }
                else if (e.target.value == "ch" || e.target.value == "at") {
                    n = 4;
                }
                jQuery(".input_postal_code").val(jQuery(".input_postal_code").val().substring(0,n)).attr("maxLength", n)
            }
            );

    var aLinkHeight = 16;

    var closedContentHeight = 145;

    /** initialize automatic expandable product description, cropped to 130px height **/
    //    var aContainerHeight = jQuery('.fixedHeightContainer').height();
    var sellingPointsHeight = jQuery('.sellingPointsPanel').height();
    sellingPointsHeight = jQuery('.sellingPointsPanel').text().length == 0 ? -15 : sellingPointsHeight;
    var descriptionTextHeight = jQuery('.productDescriptionContent').height();
    var materialDescriptionHeight = jQuery('.materialDescriptionPanel').height();
    var fullContentHeight = descriptionTextHeight + sellingPointsHeight + materialDescriptionHeight;
    var shortDescriptionTextHeight = closedContentHeight - sellingPointsHeight - materialDescriptionHeight;

    if (fullContentHeight > closedContentHeight){
        jQuery('.productDescriptionPanel')
                .css("height", shortDescriptionTextHeight )
                .css("overflow", "hidden");
        jQuery('.productDescriptionContent .moreLink')
                .css("position", "relative")
                .css("top", (0 - descriptionTextHeight - aLinkHeight  + shortDescriptionTextHeight))
                .bind('click', function(){
            var container = jQuery(this).parents().map(function () {if (jQuery(this).hasClass("productDescriptionPanel")) return this;});
            container.find('.moreLink').hide();
            container.animate({height : descriptionTextHeight + aLinkHeight},function(){
                container.find('.lessLink').show();
            });
        })
                .show();
        jQuery('.productDescriptionContent .lessLink')
                .bind('click', function(){
            var container = jQuery(this).parents().map(function () {if (jQuery(this).hasClass("productDescriptionPanel")) return this;});
            container.find('.lessLink').hide();
            container.animate({height : closedContentHeight - sellingPointsHeight - materialDescriptionHeight}, function(){
                container.find('.moreLink').show();
            });
        })
                .show();
    } else {
        jQuery('.fixedHeightContainer').css("height", 193 );
    }

    jQuery('#infoBox').css("visibility", "visible");

    /** initialize automatic expandable product description, cropped to 130px height **/
    var aMaxContainerHeight = jQuery('.maxHeightContainer').height();
    var aMaxTextHeight = jQuery('.maxHeightPanel').height();
    if (aMaxTextHeight <= aMaxContainerHeight){
        jQuery('.maxHeightContainer').css("height", "auto");
    }else{
        jQuery('.maxHeightPanel .moreLink')
                .css("top", (aMaxContainerHeight - aMaxTextHeight - aLinkHeight))
                .css("position", "relative")
                .bind('click', function(){
            var container = jQuery(this).parents().map(function () {if (jQuery(this).hasClass("maxHeightContainer")) return this;});
            container.find('.moreLink').hide();
            container.animate({height : aMaxTextHeight + aLinkHeight},function(){
                container.find('.lessLink').show();
            });
        })
                .show();
        jQuery('.maxHeightPanel .lessLink')
                .bind('click', function(){
            var container = jQuery(this).parents().map(function () {if (jQuery(this).hasClass("maxHeightContainer")) return this;});
            container.find('.lessLink').hide();
            container.animate({height : aMaxContainerHeight}, function(){
                container.find('.moreLink').show();
            });
        })
                .show();
    }

    //---- LIMITED TEXTAREA -------------------------------
    jQuery('textarea.limited300').keyup(function(){
        var max = 300;
        var text = jQuery(this).val();
        if(text.length > max){
            jQuery(this).val(text.substr(0, max));
        }
    });

    //--- TOGGLE LINK ---------------------------------------
    jQuery(".toggleLink img").toggle(
            function(){
                jQuery(this).attr("src", "images/bt_minus.gif").nextAll(".toggleLinkContent").show();
            },
            function(){
                jQuery(this).attr("src", "images/bt_plus.gif").nextAll(".toggleLinkContent").hide();
            }
            );

    //--- SIMPLE TABS ----------------------------------------
    jQuery('.tabContainer .tabHeaderLabel').bind('click', function(){
        var node = this;

        var aContainer = jQuery(this).parents().map(function () {
            if (jQuery(this).hasClass("tabContainer")) return this;
        });
        var id =  node.parentNode.id;
        aContainer.find('.tabHeaderActive').removeClass('tabHeaderActive').addClass('tabHeaderInactive');
        aContainer.find('#' + id).removeClass('tabHeaderInactive').addClass('tabHeaderActive');
        aContainer.find('.tabContentActive').removeClass('tabContentActive').addClass('tabContentInactive');
        aContainer.find('#' + id + 'Content').removeClass('tabContentInactive').addClass('tabContentActive');
    });

    //------------------------------------------------------------------------------------------------------------------
    //--- MHK: START ---------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------------------------
    //Init Bueste
    BustView.init();

    jQuery('#mhk-bust-forward').bind('click', function(){
        BustView.goNext();
        return false;
    });

    jQuery('#mhk-bust-back').bind('click', function(){
        BustView.goPrev();
        return false;
    });

    jQuery('#mhk-bust-control ul a').bind('click', function(){
        BustView.pick( jQuery(this) );
        return false;
    });

    //Init Tab navigation
    jQuery('.mhk-tab-navigation li a').live('click',function () {
        jQuery('.mhk-tab-details').not('.mhk-tab-disabled').addClass('hide').hide().filter(this.hash).removeClass('hide').show();
        jQuery('.mhk-tab-navigation li').not('.mhk-tab-disabled').removeClass('mhk-tab-active');
        jQuery(this).parent().addClass('mhk-tab-active');

        // switch right col content
        if(jQuery(this).hasClass('mhk-special-1')){
            jQuery('.mhk-right-col-cont').hide();
            jQuery('.mhk-right-col .mhk-special-1').removeClass('hide').show();
        }

        if(jQuery(this).hasClass('mhk-special-2')){
            jQuery('.mhk-right-col-cont').hide();
            jQuery('.mhk-right-col .mhk-special-2').removeClass('hide').show();
            // set focus on first empty input box, if relevant
            if(jQuery(".mhk-measurement-list .mhk-input-container input:text"))
                setTimeout("MhkPrevNextNavigation.setFocusOnFirtsEmptyTextField()", 500);
        }
        return false;
    });

    //Step-1 Material Chooser Select
    jQuery("select[id$='mhk-material-chooser']").bind('change', function(){
        $value = jQuery(this).val();
        jQuery('.itemsContainer').each(function(){
            jQuery(this).hide();
        });
        jQuery('#mhk-material-container-'+$value).show();
    });

    // onclick on Material - Radio Button
    jQuery('.itemsContainer .mhk-radio:checked').parents('.item').addClass('itemSelected');
    jQuery('.itemsContainer .mhk-radio').bind('click', function(){
        jQuery(this).closest('fieldset').find('.item').removeClass('itemSelected');
        jQuery(this).closest('.item').addClass('itemSelected');

        jQuery(this).closest('fieldset').find('.itemsContainer .mhk-radio').each(function(){
            jQuery(this).removeAttr('checked');
        });

        jQuery(this).attr('checked', true);

    });

    //onclick on Material Image
    jQuery('.itemsContainer .material-image').bind('click', function(){
        if(jQuery(this).parents('li > div').hasClass('itemSelected')){
            jQuery(this).parent().siblings('.mhk-hidden-link').trigger('click');
        }else{
            //do nothing
        }
        jQuery(this).parent().siblings('input').trigger('click');
    });


    //Step-4 Input on focus show measurement info
    jQuery('.mhk-special-inputs input').focus(function (){
        jQuery('.mhk-special-inputs input').removeClass('mhk-highlight');
        jQuery(this).addClass('mhk-highlight');
        liClass = jQuery(this).closest('li').attr('class');
        jQuery('.mhk-measurement-info li').hide();
        jQuery('.mhk-measurement-info li.'+liClass).show();
    });

    //Weiter-Button
    jQuery('#mhk-continue-button,#mhk-next-top').bind('click', function(){
        MhkPrevNextNavigation.goToNext();
        return false;
    });
    //Zurueck-Button
    jQuery('#mhk-prev-top').bind('click', function(){
        MhkPrevNextNavigation.goToPrev();
        return false;
    });

    // MHK: END
});


// MHK: START
var BustView = {
    init: function(){
        this.getList().each(function(){
            jQuery(this).addClass('mhk-bust-inactive');
        });

        this.getActive().attr('class', 'mhk-bust-active');
    },

    goPrev: function(){
        var $list = this.getList();
        var $controls = jQuery('#mhk-bust-control a');
        var prev = ( ( $controls.length - 2 ) + ( this.getActiveIndex() - 1 ) ) % ( $controls.length - 2 ) ;
        var $view = $list.eq( prev );

        $list.attr('class', 'mhk-bust-inactive');
        $view.attr('class', 'mhk-bust-active');

        $controls.removeClass('mhk-control-active');
        $controls.eq( prev + 1 ).addClass('mhk-control-active');
    },

    goNext: function(){
        var $list = this.getList();
        var $controls = jQuery('#mhk-bust-control a');
        var next = ( this.getActiveIndex() + 1 ) % ( $controls.length - 2 ) ;
        var $view = $list.eq( next );

        $list.attr('class', 'mhk-bust-inactive');
        $view.attr('class', 'mhk-bust-active');

        $controls.removeClass('mhk-control-active');
        $controls.eq( this.getActiveIndex() + 1 ).addClass('mhk-control-active');
    },

    pick: function( me ){
        var idx = jQuery( me ).parents('ul').find('a').index( me )
        var $list = this.getList();
        var $view = this.getList().eq( idx );

        $list.attr('class', 'mhk-bust-inactive');
        $view.attr('class', 'mhk-bust-active');

        me.parents('ul').find('a').removeClass('mhk-control-active');
        me.addClass('mhk-control-active');
    },

    getList: function(){
        return(jQuery('#bust-container li'));
    },

    getListLength: function(){
        return(this.getList().length);
    },

    getActive: function(){
        return(jQuery('.mhk-bust-active'));
    },

    getActiveIndex: function(){
        return(this.getList().index(this.getActive()));
    }
};

//weiter-button
var MhkPrevNextNavigation = {

    getTabsList: function(){
        return(jQuery('.mhk-tab-navigation li').not('.mhk-tab-disabled'));
    },

    getActiveTab: function(){
        return(jQuery('.mhk-tab-active').not('.mhk-tab-disabled'));
    },

    getFirstTab: function(){
        return(jQuery('.mhk-tab-navigation li:first-child').not('.mhk-tab-disabled'));
    },

    getLastTab: function(){
        return(jQuery('.mhk-tab-navigation li:last').not('.mhk-tab-disabled'));
    },

    getActiveTabIndex: function(){
        return(this.getTabsList().index(this.getActiveTab()));
    },

    goToNext: function() {
        if ('.mhk-tab-container') {
            if (jQuery('#ProcessBarFrameExt .pstepAc').hasClass('pstep5Item')) {
                // this is the last step ('Ãœberblick') in the process, so do nothing
            } else {
                if (this.getActiveTabIndex() == this.getTabsList().index(this.getLastTab()) || jQuery('.enable-standard-selects').attr('checked')  || jQuery('.hide-standard-selects').attr('checked')) {
                    //if this is last tab, go to next page
                    window.location.href = jQuery('#ProcessBarFrameExt .pstepAc').next('div').find('a').attr('href');
                } else {
                    //go to the next tab
                    this.getActiveTab().next('li').find('a').trigger('click');
                }
            }
        }
    },

    goToPrev: function() {
        if ('.mhk-tab-container') {
            if (jQuery('#ProcessBarFrameExt .pstepAc').hasClass('pstep1Item')) {
                // this is the first step ('Stoff') in the process, so do nothing
            } else {
                if (this.getActiveTabIndex() == this.getTabsList().index(this.getFirstTab())) {
                    //if this is the first tab, go to previous page
                    window.location.href = jQuery('#ProcessBarFrameExt .pstepAc').prev('div').find('a').attr('href') + '?tabindex=last';
                } else {
                    //or to the previous tab
                    this.getActiveTab().prev('li').find('a').trigger('click');
                }
            }

        }
    },
    setFocusOnFirtsEmptyTextField : function(){
        jQuery(".mhk-measurement-list .mhk-input-container input:text[value='']:first").focus();
    }
};
//MHK: END

$.noConflict();

