// jQuery extensions
jQuery.preloadImages = function() {
	for (var i = 0; i < arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
}

jQuery.fn.reverse = [].reverse;

MilwaukeeTool = window.MilwaukeeTool || {};

MilwaukeeTool.Common = function() {
    function _init_navigation() {
        $('#navigation > ul > li > a').hover(
        // over

			function() {

			    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
			        var ieversion_over = new Number(RegExp.$1) // capture x.x portion and store as a number
			        if (ieversion_over < 7) {
			            HideDropdowns();
			        }
			    }
			    $(this).css('background-position', '0 -33px');

			    // does the nav item have a sub menu?
			    var menu = $(this).parent().find('.subnav:first');
			    if (menu.length) {
			        $(menu).css('display', 'block');
			        MilwaukeeTool.Common.toggle_conflicts_subnav('hide');
			    }
			},
        // out
			function() {

			    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
			        var ieversion_over = new Number(RegExp.$1) // capture x.x portion and store as a number
			        if (ieversion_over < 7) {
			            ShowDropdowns();
			        }
			    }

			    if (!$(this).hasClass('nav-current')) {
			        $(this).css('background-position', '0 0');
			    }

			    // does the nav item have a sub menu?
			    var menu = $(this).parent().find('.subnav:first');
			    if (menu.length) {
			        $(menu).css('display', 'none');
			        MilwaukeeTool.Common.toggle_conflicts_subnav('show');
			    }
			}
		);

        $('.subnav').hover(
        // over
			function() {
			    $(this).css('display', 'block');
			    // update the hover state of the parent/top-level nav item
			    $(this).parent().find('a:first').css('background-position', '0 -33px');
			    MilwaukeeTool.Common.toggle_conflicts_subnav('hide');
			},
        // out
			function() {
			    $(this).css('display', 'none');
			    // update the hover state of the parent/top-level nav item
			    if (!$(this).hasClass('nav-current')) {
			        $(this).parent().find('a:first').css('background-position', '0 0');
			    }
			    MilwaukeeTool.Common.toggle_conflicts_subnav('show');
			}
		);

        // set up subnav lists
        $('.subnav h4 a').toggle(
        // over
			function() {
			    // if next sibling is a ul
			    var next_sibling = $(this).parent().next('ul');

			    if (next_sibling.length > 0) {
			        // legacy code for hover action
			        // remove hover state from all h4's
			        //$(this).parents('.subnav:first').find('h4').removeClass('subnav-selected');

			        // hide all other ul's
			        //$(this).parents('.subnav:first').find('ul').css('display', 'none');

			        // add hover state to heading
			        $(this).parent().addClass('subnav-selected');

			        // show the ul
			        $(next_sibling).css('display', 'block');
			    } else {
			        // if no ul to toggle, just send the user along to the default href (if present)
			        if ($(this).attr('href') != '') {
			            document.location = $(this).attr('href');
			        }
			    }
			},
        // out
			function() {
			    // if next sibling is a ul
			    var next_sibling = $(this).parent().next('ul');

			    if (next_sibling.length > 0) {
			        // add hover state to heading
			        $(this).parent().removeClass('subnav-selected');

			        // show the ul
			        $(next_sibling).css('display', 'none');

			        return false;
			    }
			}
		);
    }

    function _init_search() {
        $('#search-form .text:first').focus(function() {
            this.value = (this.value == 'Search') ? '' : this.value;
        });

        $('#search-form .text:first').blur(function() {
            this.value = (this.value == '') ? 'Search' : this.value;
        });
    }

    function _init_dropshadows() {
        $('.page-title').dropShadow({ left: -16, top: -12, blur: 8 });
    }

    function _init_tertiary_navigation() {
        $('.tertiary-select-heading a').click(function() {
            var container = $(this).parents('.tertiary-select:first');
            var items = $(container).find('.tertiary-select-items:first');

            if ($(items).css('display') == 'block') {
                $(items).css('display', 'none');
            } else {
                $(items).css('display', 'block');
            }

            return false;
        });

        $('.tertiary-select-items').hover(
			function() {
			    $(this).css('display', 'block');
			},
			function() {
			    $(this).css('display', 'none');
			}
		);
    }

    function _init_locale_selector() {
        $('#locale-selector-link').click(function() {
            // get visibility of selector box
            var current_state = $('#locale-selector').css('display');

            if (current_state == 'none') {
                $(this).find('img:first').attr('src', '/images/locale-select-hover.png');
                $('#locale-selector').css('display', 'block');
            } else {
                $(this).find('img:first').attr('src', '/images/locale-select.png');
                $('#locale-selector').css('display', 'none');
            }

            return false;
        });

        $('#locale-selector').mouseover(function() {
            $(this).css('display', 'block');
            $('#locale-selector-link img:first').attr('src', '/images/locale-select-hover.png');
        });

        $('#locale-selector').mouseout(function() {
            $(this).css('display', 'none');
            $('#locale-selector-link img:first').attr('src', '/images/locale-select.png');
        });
    }

    function _init_hdc_footer_form() {
        $('.footer-hdc-signup-email:first').focus(function() {
            this.value = (this.value == 'Email') ? '' : this.value;
        });
        $('.footer-hdc-signup-email:first').blur(function() {
            this.value = (this.value == '') ? 'Email' : this.value;
        });

        $('.footer-hdc-signup-firstname:first').focus(function() {
            this.value = (this.value == 'First Name') ? '' : this.value;
        });
        $('.footer-hdc-signup-firstname:first').blur(function() {
            this.value = (this.value == '') ? 'First Name' : this.value;
        });

        $('.footer-hdc-signup-zip:first').focus(function() {
            this.value = (this.value == 'Zip/Postal Code') ? '' : this.value;
        });
        $('.footer-hdc-signup-zip:first').blur(function() {
            this.value = (this.value == '') ? 'Zip/Postal Code' : this.value;
        });

        $('#hdc-footer-form a.button').click(
        function(e) {
            var emailRegEx = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
            var ok = emailRegEx.test($('#hdc-footer-form input.footer-hdc-signup-email')[0].value);
            if (!ok) {
                $('#hdc-footer-form .footer-hdc-signup-email:first').addClass('error');
            }
            else {
                $('#hdc-footer-form .footer-hdc-signup-email:first').removeClass('error');
            }

            if (jQuery.trim($('#hdc-footer-form .footer-hdc-signup-firstname')[0].value) == '' || jQuery.trim($('#hdc-footer-form .footer-hdc-signup-firstname')[0].value) == 'First Name') {
                ok = false;
                $('#hdc-footer-form .footer-hdc-signup-firstname:first').addClass('error');
            }
            else {
                $('#hdc-footer-form .footer-hdc-signup-firstname:first').removeClass('error');
            }

            if (jQuery.trim($('#hdc-footer-form .footer-hdc-signup-zip')[0].value) == '' || jQuery.trim($('#hdc-footer-form .footer-hdc-signup-zip')[0].value) == 'Zip/Postal Code') {
                ok = false;
                $('#hdc-footer-form .footer-hdc-signup-zip:first').addClass('error');
            }
            else {
                $('#hdc-footer-form .footer-hdc-signup-zip:first').removeClass('error');
            }

            if (!ok) {
                e.preventDefault();
                alert('Please fill in all required fields.');
            }
            else {
                cmCreateRegistrationTag($('.footer-hdc-signup-email')[0].value, $('.footer-hdc-signup-email')[0].value, null, null, $('#hdc-footer-form .footer-hdc-signup-zip')[0].value);
                cmCreateConversionEventTag("Partial Registration", "2", "Heavy Duty Club Registration", "25");
            }
        });
    }

    function _init_share_modal_form() {
        $('.share-modal-window a.submit').click(
        function(e) {

            var ok = true;

            // make sure all required fields are filled
            $('.share-modal-window .required').each(function() {
                if (this.value == '') {
                    ok = false;
                    $(this).addClass('error');
                } else {
                    $(this).removeClass('error');
                }
            });

            // make sure all email fields are valid
            var emailRegEx = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
            $('.share-modal-window .email').each(function() {
                if (!emailRegEx.test(this.value)) {
                    ok = false;
                    $(this).addClass('error');
                } else {
                    $(this).removeClass('error');
                }
            });

            if (!ok) {
                e.preventDefault();
                alert('Please fill in all required fields.');
            }
            else {
                cmCreatePageElementTag(document.title, "Share");
                cmCreateConversionEventTag("Share", "2", "Share Page", "15");
            }
        });
    }

    function _init_share_print_buttons() {
        $('#share-print .share-button').click(function() {
            cmCreateConversionEventTag("Share", "1", "Share Page", "5");
        });

        $('#share-print .print-button').click(function() {
            cmCreatePageElementTag(document.title, "Print Page");
        });
    }

    function _init_buy_local_buttons() {
        $(function() {
            $('a.buy-now').click(function() {
                cmCreatePageElementTag($(this).attr("sku"), "Buy Local");
            });

        });
    }

    return {
        toggle_conflicts_subnav: function(action) {
            // only take action if ie 6 or below
            if (jQuery.browser.msie && jQuery.browser.version <= 6) {
                var display = (action == 'show') ? 'visible' : 'hidden';

                if ($('#category-select').length > 0) {
                    $('#category-select').css('visibility', display);
                }

                if ($('.subcategory-banner .subcategory-feature-image .new').length > 0) {
                    $('.subcategory-banner .subcategory-feature-image .new').css('visibility', display);
                }

                $('.badge-new').css('visibility', display);
            }
        },

        debug: function(msg) {
            if ($('#debug').length > 0) {
                var cur_html = $('#debug').html();
                $('#debug').html(msg + '<br />' + cur_html);
            }
        },

        init: function() {
            _init_navigation();
            _init_search();
            _init_dropshadows();
            _init_tertiary_navigation();
            _init_locale_selector();
            _init_hdc_footer_form();
            _init_share_modal_form();
            _init_share_print_buttons();
            _init_buy_local_buttons();
        }
    }
} ();

$(document).ready(function() {
	MilwaukeeTool.Common.init();
});

function HideDropdowns() {
    // hide all dropdowns on the page

    // looping through all forms on the page
    for (f = 0; f < document.forms.length; f++) {
        var elements = document.forms[f].elements;
        // looping through all elements on certain form
        for (e = 0; e < elements.length; e++) {
            if (elements[e].type == "select-one") {
                elements[e].style.display = 'none';
            }
        }
    }
}

function ShowDropdowns() {
    // hide all dropdowns on the page
    for (f = 0; f < document.forms.length; f++) {
        var elements = document.forms[f].elements;
        for (e = 0; e < elements.length; e++) {
            if (elements[e].type == "select-one") {
                elements[e].style.display = 'block';
            }
        }
    }
}


KeyListener = {
    init: function() {
        $('#shell').bind('keypress', function(e) {
            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
            var target = e.target.tagName.toLowerCase();
            if (key === 13 && target === 'input') {
                e.preventDefault();
                var parentFieldset = $(e.target).parents('fieldset');
                var submitbutton = $(parentFieldset).find('a.button');
                if (submitbutton.length > 0) {
                    submitbutton.trigger('click');
                }
            }
        });
    }
};
$(document).ready(function() {    
    KeyListener.init()
});
