/* ---------------------------------------------------------------------
Global JavaScript & jQuery

Target Browsers: All
Authors: Josh Anderson
------------------------------------------------------------------------ */

var NERD = NERD || {};

$(function() {

    // Initialize!
    NERD.HasJS.init();
    NERD.ExternalLinks.init();
    NERD.AutoReplace.init();
    NERD.TouchDevices.init();
    NERD.MegaNav.init();
    NERD.HeroRotator.init();
    NERD.ImageRotator.init();
    NERD.RegisterForm.init();
    NERD.UIDialog.init();
    // NERD.FilterAccordion.init();
    NERD.TabContainer.init();
    //NERD.SupplierFields.init();
    //NERD.ResumeUploadForm.init();
    NERD.PriceListForm.init();
    NERD.FormSubmissions.init();
    NERD.PriceListAddendums.init();
    NERD.LangDropdown.init();
    NERD.Tooltips.init();
    NERD.Community.init();
    NERD.EqualHeight.init();
    NERD.Flowplayer.init();

});

/* ---------------------------------------------------------------------
HasJS
Author: Nerdery Boilerplate

Replaces "no-js" class with "has-js" on the body if JavaScript
is present. This allows you to style both the JavaScript enhanced
and non JavaScript experiences. 
------------------------------------------------------------------------ */

NERD.HasJS = {
    init: function() {
        $('body').removeClass('no-js');
        $('body').addClass('has-js');
    }
};

/* ---------------------------------------------------------------------
ExternalLinks
Author: Nerdery Boilerplate

Launches links with a rel="external" in a new window
------------------------------------------------------------------------ */

NERD.ExternalLinks = {
    init: function() {
        var self = this;
        $('a[rel=external]').attr('target', '_blank');
        self.structureExternal();
    },
    structureExternal: function() {
        var self = this;
        if ($('.structure-external').length) {
            var container = $('.structure-external');
            container.find('a').each(function() {
                var me = $(this);
                me.attr('target', '_blank');
            });
        }
        // Make the "Order Literature" link an external link
        $('#our-company-mega-nav-21336 a').attr('target', '_blank');
        if ($('#nav-sub-21336').length) {
            var me = $('#nav-sub-21336 a');
            me.attr('target', '_blank');
        }
        if ($('#nav-sub-344').length) {
            var me = $('#nav-sub-344 a');
            me.attr('target', '_blank');
        }
        // Make the "Merchandise Store" link an external link
        $('#our-company-mega-nav-21300 a').attr('target', '_blank');
        if ($('#nav-sub-21300').length) {
            var me = $('#nav-sub-21300 a');
            me.attr('target', '_blank');
        }
        if ($('#nav-sub-345').length) {
            var me = $('#nav-sub-345 a');
            me.attr('target', '_blank');
        }
    }
};

/* ---------------------------------------------------------------------
AutoReplace
Author: Nerdery Boilerplate

Mimics HTML5 placeholder behavior

Additionally, adds and removes 'placeholder-text' class, used as a styling
hook for when placeholder text is visible or not visible

Additionally, prevents forms from being
submitted if the default text remains in input field - which we may 
or may not want to leave in place, depending on usage in site
------------------------------------------------------------------------ */
NERD.AutoReplace = {
    $fields: undefined,

    init: function() {
        var $fields = $('[placeholder]');

        if ($fields.length !== 0) {
            var self = this;
            self.$fields = $fields.addClass('placeholder-text');
            self.bind();
        }
    },

    bind: function() {
        var self = this;

        self.$fields.each(
            function() {
                var me = $(this);
                var defaultText = me.attr('placeholder');
                me.attr('placeholder', '').val(defaultText);

                me.focus(
                    function() {
                        if (me.val() === defaultText) {
                            me.val('').removeClass('placeholder-text');
                        } 
                    }
                );

                me.blur(
                    function() {
                        if (me.val() === '') {
                            me.val(defaultText).addClass('placeholder-text');
                        }
                    }
                );

                me.parents('form').submit(
                    function() {
                        if (me.is('.required') && (me.val() === defaultText || me.val() === "")) {
                            return false;
                        }
                    }
                );
            }
        );
    }
};

/* ---------------------------------------------------------------------
Touch Devices
Author: Josh Anderson

If it's a touch device, add a class to the header.
------------------------------------------------------------------------ */

NERD.TouchDevices = {
    
    init: function() {
        
        var TouchDevice = 'ontouchstart' in document.documentElement;
        
        if (TouchDevice == true) {
            $('body').addClass('touch-device');
        }
        
    }
    
}

/* ---------------------------------------------------------------------
Mega Nav
Author: Josh Anderson

Hide and show the mega navigation in the header
------------------------------------------------------------------------ */

NERD.MegaNav = {
    
    init: function() {
        var self = this;
        var nav = $('.mega-nav');
        nav.css('left', '-9999px');
        
        // Get the menu height
        var menuHeight = $('.main-nav').height();
        
        // Set all of the menu items equal to the tallest one
        $('.primary').css('height', (menuHeight-16));
        
        // Sett all of the list items in the mega-nav equal to the tallest one
        $('.mega-nav').children('.column-group').each(function() {
            var me = $(this);
            var height = me.height();
            me.children('.column').css('height', height);
        });
        
        // Special Treatment for touch devices
        if ($('body').hasClass('touch-device') == true) {
            self.bindTouch(menuHeight);
        } else {
            self.bindNormal(menuHeight);
        }
        
    },
    
    bindNormal: function(menuHeight) {
        
        var self = this;
        var trigger = $('.primary').parent();
        var parentLI = $('.mega-nav');
        
        trigger.hover(
            function() {
                var me = $(this);
                me.find('.mega-nav').css({left: 0, top: menuHeight});
                me.children('a').addClass('hovered');
            },
            function() {
                var me = $(this);
                me.find('.mega-nav').css('left', '-9999px');
                me.children('a').removeClass('hovered');
            }
        );
        
        parentLI.hover(
            function() {
                var me = $(this);
                me.parent().addClass('hovered');
            },
            function() {
                var me = $(this);
                me.parent().removeClass('hovered');
            }
        );
        
    },
    
    bindTouch: function(menuHeight) {
        
        var self = this;
        var trigger = $('.primary');
        var parentLI = $('.mega-nav');
        
        trigger.click(function(e) {
                
            var me = $(this);
            
            // First click opens the dropdown menu
            if (me.hasClass('hovered') == false) {
            
                e.preventDefault();

                // Hide any open mega menus
                $('.main-nav').find('.mega-nav').css('left', '-9999px');
                $('.main-nav').find('.primary').removeClass('hovered');
                
                // Open the correct mega menu
                me.parent().find('.mega-nav').css({left: 0, top: menuHeight});
                me.parent().children('a').addClass('hovered');
                
                setTimeout(function() {
                    $('body').addClass('open-menu');
                }, 100);
                
            } else {
                
                // Let the link go to the page
                return true;
            
            }
        
        });
        
        // Close the menu if the user clicks outside of it
        $('body.open-menu').live('click', function(e) {
            
            if ($(e.target).closest('.main-nav-wrapper').length == 0) {
            
                // Hide any open mega menus
                $('.main-nav').find('.mega-nav').css('left', '-9999px');
                $('.main-nav').find('.primary').removeClass('hovered');

                $('body').removeClass('open-menu');
            
            }
            
        });
        
    }
    
};

/* ---------------------------------------------------------------------
Hero Image Rotator
Author: Josh Anderson

Count all of the images, build a small dotted nav and rotate through them
------------------------------------------------------------------------ */

NERD.HeroRotator = {
    
    total: undefined,
    state: undefined,
    
    init: function() {
        // Only run if the rotator exists and there is more than one image
        if ($('.rotator.hero').length) {
            var self = this;

            var rotator = $('.rotator.hero');
            var totalSlides = rotator.find('li').length;
            
            if (totalSlides == "0") {
                rotator.hide();
            }
            
            if (totalSlides > "1") {
                
                var imageHeight = "250";
                rotator.find('.slides').height(255);

                //Create the nav dots
                rotator.find('.slides').after('<ol class="rotator-nav"></ol>');
                rotator.find('.slides li').each(function(i) {
                    var me = $(this);

                    var number = i+1;

                    me.css({position: 'absolute', marginBottom: '5px'});

                    me.addClass('slide-' + number);
                    rotator.find('.rotator-nav').append('<li><a href="#" class="icon" rel="' + number + '">Slide ' + number + '</a></li>');
                });
                
                //Make sure the text fits in the grey description box
                var maxHeight = imageHeight-22;

                rotator.find('.overflow').each(function() {
                    var me = $(this);
                    var height = me.height();

                    if (height > maxHeight) {
                        var parentWidth = me.parent().width();
                        var accomodatingWidth = parentWidth+((height-maxHeight)*3);

                        me.parent().width(accomodatingWidth);
                    }
                });

                //Hide the slides
                rotator.find('.slides li').hide();

                //Set the first slide to active
                rotator.find('.slide-1').show();
                rotator.find('.rotator-nav li a').eq(0).addClass('active');

                self.bind(totalSlides);
                self.play(totalSlides);

            }
        }
    },
    
    bind: function(totalSlides) {
        var self = this;
        
        // Pause the slideshow on hover
        $('.slides').hover(
            function() {
                self.pause();
            },
            function() {
                self.play(totalSlides);
            }
        );
        
        $('.rotator-nav a').click(function(e) {
            var me = $(this);
            e.preventDefault();
            
            // Pause the slideshow and assuming the user is taking control if a specific image is selected.
            self.pause();
            
            if (me.hasClass('active') == false) {
                var image = me.attr('rel');
                $('.rotator.hero .rotator-nav li a').removeClass('active');
                me.addClass('active');
                self.specific(image);
            }
        });
    },
    
    play: function(totalSlides) {
        var self = this;
        
        self.state = window.setInterval(function() {
            
            var current = parseInt($('.rotator.hero .slides').find('li:visible').attr('class').replace('slide-', ''));
            
            // Set the next image to be displayed
            if (current == totalSlides) {
                var next = '1';
            } else {
                var next = current+1;
            }
            
            $('.rotator.hero .rotator-nav li a').removeClass('active');
            $('.rotator.hero .rotator-nav li a').eq(next-1).addClass('active');
            
            var image = next;
            
            self.specific(image);
        }, 4000);
    },
    
    pause: function() {
        var self = this;
        clearInterval(self.state);
    },
    
    specific: function(image) {
        var self = this;
        
        $('.rotator.hero .slides li').fadeOut(400);
        $('.rotator.hero .slides .slide-' + image).fadeIn(400);
    }
    
}

/* ---------------------------------------------------------------------
Image Rotator
Author: Josh Anderson

Count all of the images, build a small dotted nav and rotate through them
------------------------------------------------------------------------ */

NERD.ImageRotator = {
    
    total: undefined,
    state: undefined,
    liHeight: undefined,
    
    init: function() {
        // Only run if the rotator exists and there is more than one image
        if ($('.rotator.sidebar').length) {
            var self = this;

            var rotator = $('.rotator.sidebar');
            var totalSlides = rotator.find('li').length;
            
            if (totalSlides > "1") {
                
                //Find tallest li
                self.liHeight = 0;
                rotator.find('.slides li').each(function() {
                    var newLI = $(this);
                    
                    if (newLI.height() > self.liHeight) {
                       self.liHeight = newLI.height();
                    }
                });
                
                rotator.find('.slides').height(self.liHeight+5);

                //Create the nav dots
                rotator.find('.slides').after('<div class="rotator-group"><ol class="rotator-nav"></ol></div>');
                rotator.find('li').each(function(i) {
                    var me = $(this);

                    var number = i+1;

                    me.css({position: 'absolute', marginBottom: '5px'});

                    me.addClass('slide-' + number);
                    $('.rotator.sidebar').find('.rotator-nav').append('<li><a href="#" class="icon" rel="' + number + '">Slide ' + number + '</a></li>');
                });

                //Hide the slides
                rotator.find('.slides li').hide();

                //Set the first slide to active
                rotator.find('.slide-1').show();
                rotator.find('.rotator-group li a').eq(0).addClass('active');

                self.bind(totalSlides);
                self.play(totalSlides);
            }
        }
    },
    
    bind: function(totalSlides) {
        var self = this;
        
        // Pause the slideshow on hover
        $('.slides').hover(
            function() {
                self.pause();
            },
            function() {
                self.play(totalSlides);
            }
        );
        
        $('.rotator-nav a').click(function(e) {
            var me = $(this);
            e.preventDefault();
            
            // Pause the slideshow and assuming the user is taking control if a specific image is selected.
            self.pause();
            
            if (me.hasClass('active') == false) {
                var image = me.attr('rel');
                $('.rotator.sidebar .rotator-nav li a').removeClass('active');
                me.addClass('active');
                self.specific(image);
            }
        });
    },
    
    play: function(totalSlides) {
        var self = this;
        
        self.state = window.setInterval(function() {
            var current = parseInt($('.rotator.sidebar .slides').find('li:visible').attr('class').replace('slide-', ''));
            
            // Set the next image to be displayed
            if (current == totalSlides) {
                var next = '1';
            } else {
                var next = current+1;
            }
            
            $('.rotator.sidebar .rotator-nav li a').removeClass('active');
            $('.rotator.sidebar .rotator-nav li a').eq(next-1).addClass('active');
            
            var image = next;
            
            self.specific(image);
        }, 6000);
    },
    
    pause: function() {
        var self = this;
        clearInterval(self.state);
    },
    
    specific: function(image) {
        var self = this;
        
        $('.rotator.sidebar .slides li').fadeOut(400);
        $('.rotator.sidebar .slides .slide-' + image).fadeIn(400);
    }
    
}

/* ---------------------------------------------------------------------
Register Form
Author: Josh Anderson

Handles the registration form
------------------------------------------------------------------------ */

NERD.RegisterForm = {
    
    country: undefined,
    state: undefined,

    init: function() {
    
        if ($('#member_form').length) {
            var self = this;
            // Hide the job role "other" field
            if ($('#member_job_role').val() != 'other') {
                $('div.other_job_role').hide();
                $('div.other_job_role').parent().css('height', '58px');
            }
            // Create an error container but leave it hidden to populate later
            $('#member_form').before('<ul class="form_error" style="display: none;"></ul>')
            //$('#contact_inquiry').ketchup();
            self.bind();
        }

    },

    bind: function() {
    
        var self = this;

        // Display the "Other job role" field if "Other" is select
        $('#member_job_role').live('change', function() {
            var me = $(this);
            if (me.val() == 'other') {
                $('div.other_job_role').show();
                $('#member_job_role_other').addClass('required_field');
            } else {
                $('div.other_job_role').hide();
                $('#member_job_role_other').removeClass('required_field');
                $('li.member_job_role_other').remove();
                self.removeError();
            }
        });

        // Confirm emails match
        $('#email').blur(function() {
            
            var me = $(this);
            var Placeholder = me.hasClass('placeholder-text');
            var OriginalEmail = $('#username').val();

            if (Placeholder == false) {
                // If email is not the default value.
                if ($(this).val() != OriginalEmail || OriginalEmail == "") {
                    // Check to see if there is already an alert about this
                    if ($('li.email_match').length == 0 && $('li.email_validity').length == 0) {
                        $('ul.form_error').append('<li class="email_match">'+ lang.emails_do_not_match +'</li>');
                        $('ul.form_error').slideDown();
                    }
                } else {
                    $('li.email_match').remove();
                    self.removeError();
                }   
            } else {
                $('li.email_match').remove();
                self.removeError();
            }
            
        });

        // Validate the email address
        $('#username').blur(function() {
    
            var me = $(this);
            var Placeholder = me.hasClass('placeholder-text');
            
            if (Placeholder == false) {
                var emailReg = /^['_a-z0-9-]+(\.['_a-z0-9-]+)*(\+['_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$/;
                if (!emailReg.test($(this).val())) {
                   $('ul.form_error').append('<li class="email_validity">'+ lang.enter_valid_email +'</li>');
                   $('ul.form_error').slideDown();
                } else {
                   $('li.email_validity').remove();
                self.removeError();
                }
            } else {
                $('li.email_validity').remove();
                self.removeError();
            }
            
        });

        // Confirm passwords match
        $('#password').blur(function() {
            var confirm_pass = $('#password_confirm').val();
            // If passwords match.
            if ($(this).val() != confirm_pass && confirm_pass != '') {
                // Check to see if there is already an alert about this
                if ($('li.password_match').length == 0) {
                    $('ul.form_error').append('<li class="password_match">'+ lang.passwords_do_not_match +'</li>');
                    $('ul.form_error').slideDown();
                    $('#password').parent().addClass('password_error_field');
                    $('#password_confirm').parent().addClass('password_error_field');
                }
            } else {
                $('li.password_match').remove();
                $('#password').parent().removeClass('password_error_field');
                $('#password_confirm').parent().removeClass('password_error_field');
                self.removeError();
            }
        });

        $('#password_confirm').blur(function() {
            var orig_pass = $('#password').val();
            // If passwords match.
            if ($(this).val() != orig_pass) {
                // Check to see if there is already an alert about this
                if ($('.form_error').is(':visible') == false) {
                    $('ul.form_error').append('<li class="password_match">'+ lang.passwords_do_not_match +'</li>');
                    $('ul.form_error').slideDown();
                    $('#password').parent().addClass('password_error_field');
                    $('#password_confirm').parent().addClass('password_error_field');
                }
            } else {
                $('li.password_match').remove();
                $('#password').parent().removeClass('password_error_field');
                $('#password_confirm').parent().removeClass('password_error_field');
                self.removeError();
            }
        });

        // Validate the password itself
        $('#password').blur(function() {
            // If password length is less than 8.
            if ($(this).val().length < "8") {
                // Check to see if there is already an alert about this
                if ($('.form_error').is(':visible') == false && $('#password').val() != "") {
                    $('ul.form_error').append('<li class="password_length">'+ lang.password_min_length +'</li>');
                    $('ul.form_error').slideDown();
                    $('#password').parent().addClass('password_error_field');
                }
            } else {
                $('li.password_length').remove();
                $('#password').parent().removeClass('password_error_field');
                self.removeError();
            }
            // Check password for uppercase, lowercase and numeric characters.
            if ($(this).val().match(/[a-z]/) && $(this).val().match(/[A-Z]/) && $(this).val().match(/\d+/)) {
                $('li.password_case').remove();
                $('#password').parent().removeClass('password_error_field');
                self.removeError();
            } else {
                // Check to see if there is already an alert about this
                if ($('.form_error').is(':visible') == false && $('#password').val() != "") {
                    $('ul.form_error').append('<li class="password_case">'+ lang.password_requirements +'</li>');
                    $('ul.form_error').slideDown();
                    $('#password').parent().addClass('password_error_field');
                }
            }
        });
        // Make sure the required fields are filled out.
        $('.required_field').blur(function() {
            var me = $(this);
            var attrId = me.attr('name');
            // Check for entry.
            if (me.val().match(/[\s]*/) != "") {
                if ($('li.' + attrId).length == 0) {
                    var labelField = me.prev('label').text();
                    $('ul.form_error').append('<li class="' + attrId + '">'+ lang.field_is_required.replace('%s', labelField).replace('*', '') +'.</li>');
                    $('ul.form_error').slideDown();
                    me.parent().addClass('error_field');
                }
            } else {
                me.parent().removeClass('error_field');
                $('li.' + attrId).remove();
                self.removeError();
            }
        });

        // Country and state dropdown - Get it right away and whenever it changes.
        self.country = $('#member_company_country').val();
        self.state = $('#member_company_state').attr('value');
        self.stateOptions();
        $('#member_company_country').live('change', function() {
            self.country = $(this).val();
            self.stateOptions();
        });

        // Opt-in checkbox
        var currentOptIn = $('#member_opt_in').attr('value');
        if (currentOptIn == "Yes") {
            $('#opt-in').attr('checked', 'checked');
        }
        $('#opt-in').live('click', function() {
           var me = $(this);
           if (me.attr('checked') == true) {
               $('#member_opt_in').attr('value', 'Yes');
           } else {
               $('#member_opt_in').attr('value', 'No');
           }
        });

        // Literature checkbox
        var currentValue = $('#member_literature_t_c').attr('value');
        if (currentValue == "Yes") {
            $('#literature_t_d').attr('checked', 'checked');
        }
        $('#literature_t_d').live('click', function() {
           var me = $(this);
           if (me.attr('checked') == true) {
               $('#member_literature_t_d').attr('value', 'Yes');
           } else {
               $('#member_literature_t_d').attr('value', 'No');
           }
        });

        // CAD checkbox
        var currentValue = $('#member_cad_t_c').attr('value');
        if (currentValue == "Yes") {
            $('#literature_t_d').attr('checked', 'checked');
        }
        $('#cad_t_d').live('click', function() {
           var me = $(this);
           if (me.attr('checked') == true) {
               $('#member_cad_t_d').attr('value', 'Yes');
           } else {
               $('#member_cad_t_d').attr('value', 'No');
           }
        });

        // Business interests
        $('.business_interest_container').show();
        $('#member_ques_business_interest').hide();

        // Get the inital values and check the correct boxes (for the edit page)
        $('input.business_interest').each(function() {
            var me = $(this);
            var inputValue = me.attr('value');
            var currentClass = me.attr('class').replace('business_interest', '').replace(' ', '');
            var inputTextArea = $('#member_ques_business_interest').text();
            if (inputTextArea.indexOf(inputValue) != "-1") {
                me.attr('checked', 'checked');
            }
        });

        // Track what the users checks and unchecks and add it to the textarea
        $('.business_interest').live('click', function() {
           var me = $(this);
           var meValue = me.attr('value');
           if (me.attr('checked') == 'checked') {
               var currentText = $('#member_ques_business_interest').text();
               $('#member_ques_business_interest').text(currentText + meValue + ' \n');
           } else {
               var newText = $('#member_ques_business_interest').text().replace(meValue + ' \n' , '');
               $('#member_ques_business_interest').text(newText);
           }
        });

        // Software interests
        $('.software_interest_container').show();
        $('#member_ques_software_interest').hide();

        // Get the inital values and check the correct boxes (for the edit page)
        $('input.software_interest').each(function() {
            var me = $(this);
            var inputValue = me.attr('value');
            var currentClass = me.attr('class').replace('software_interest', '').replace(' ', '');
            var inputTextArea = $('#member_ques_software_interest').text();
            if (inputTextArea.indexOf(inputValue) != "-1") {
                me.attr('checked', 'checked');
            }
        });

        // Track what the users checks and unchecks and add it to the textarea
        $('.software_interest').live('click', function() {
           var me = $(this);
           var meValue = me.attr('value');
           if (me.attr('checked') == 'checked') {
                  var currentText = $('#member_ques_software_interest').text();
                  $('#member_ques_software_interest').text(currentText + meValue + ' \n');
              } else {
                  var newText = $('#member_ques_software_interest').text().replace(meValue + ' \n' , '');
                  $('#member_ques_software_interest').text(newText);
              }
        });

        // On submit - prevent the form from submitting if there are errors - Step 1
        $('form.step_1 input.submit').click(function(e) {
            $('form.step_1').find('.required_field').each(function() {
                var me = $(this);
                var Placeholder = me.hasClass('placeholder-text');
                
                // Check for any required fields that are blank.
                if (me.val().match(/[\s]*/) != "" || Placeholder == true) {
    
                    e.preventDefault();
    
                    me.parent().addClass('error_field_submit');
                    if ($('li.missing_fields').length == 0) {
                        $('ul.form_error').append('<li class="missing_fields">'+ lang.required_fields_are_empty +'</li>');
                        $('ul.form_error').slideDown();
                        setTimeout(function() {
                            $('.error_field_submit').removeClass('error_field_submit');
                            $('li.missing_fields').remove();
                            self.removeError();
                        }, 3400);
                    }
                }
                
            });
            if ($('.form_error').attr('style') == "display: block;") {
                e.preventDefault();
            }
            if ($('.error_field_submit').length) {
                e.preventDefault();
            }

            if ($('#member_prefix').val() == "Select:" || $('#member_job_role').val() == "Select:") {
                e.preventDefault();
                if ($('.missing_fields').length == 0) {
                    $('ul.form_error').append('<li class="missing_fields">'+ lang.required_fields_are_empty +'</li>');
                    $('ul.form_error').slideDown();
                    setTimeout(function() {
                        $('.error_field_submit').removeClass('error_field_submit');
                        $('li.missing_fields').remove();
                        self.removeError();
                    }, 3400);
                }
            };

        });

        // On submit - prevent the form from submitting if there are errors - Step 2
        $('form.step_2 input.submit').click(function(e) {
            $('form.step_2 .required_field').each(function() {
                var me = $(this);
                var defaultVal = $(this)[0].defaultValue;
                // Check for any required fields that are blank.
                if (me.val().match(/[\s]*/) != "" || defaultVal == me.val()) {
                    me.parent().addClass('error_field_submit');
                    if ($('li.missing_fields').length == 0) {
                        $('ul.form_error').append('<li class="missing_fields">'+ lang.required_fields_are_empty +'</li>');
                        $('ul.form_error').slideDown();
                        setTimeout(function() {
                            $('.error_field_submit').removeClass('error_field_submit');
                            $('li.missing_fields').remove();
                            self.removeError();
                        }, 3400);
                    }
                }
            });
            if ($('.error_field_submit').length) {
                e.preventDefault();
            }
        });

        // On submit - prevent the form from submitting if there are errors - Step 3
        $('form.step_3 input.submit').click(function(e) {
            $('form.step_3 .required_field').each(function() {
                var me = $(this);
                var defaultVal = $(this)[0].defaultValue;
                // Check for any required fields that are blank.
                if (me.val().match(/[\s]*/) != "" || defaultVal == me.val()) {
                    me.parent().addClass('error_field_submit');
                    if ($('li.missing_fields').length == 0) {
                        $('ul.form_error').append('<li class="missing_fields">'+ lang.required_fields_are_empty +'</li>');
                        $('ul.form_error').slideDown();
                        setTimeout(function() {
                            $('.error_field_submit').removeClass('error_field_submit');
                            $('li.missing_fields').remove();
                            self.removeError();
                        }, 3400);
                    }
                }
            });
            if ($('.error_field_submit').length) {
                e.preventDefault();
            }
        });
    },

    removeError: function() {
        if ($('ul.form_error').children().length == 0) {
            $('ul.form_error').slideUp();
        }
    },

    stateOptions: function() {
        var self = this;
        if (self.country == 'United States' || self.country == 'Canada') {
            var oldSelector = $('input#member_company_state');
            if ($(oldSelector).length) {
                $(oldSelector).after('<select class="thicksel" id="member_company_state" name="member_company_state"></select>');
                $(oldSelector).remove();
            }
            if (self.country == 'United States') {
                $('#member_company_state option').remove();
                var stateValues = {1 : 'Alabama', 2 : 'Alaska', 3 : 'Arizona', 4 : 'Arkansas', 5 : 'California', 6 : 'Colorado', 7 : 'Connecticut', 8 : 'Delaware', 9 : 'Florida', 10 : 'Georgia', 11 : 'Hawaii', 12 : 'Idaho', 13 : 'Illinois', 14 : 'Indiana', 15 : 'Iowa', 16 : 'Kansas', 17 : 'Kentucky', 18 : 'Louisiana', 19 : 'Maine', 20 : 'Maryland', 21 : 'Massachusetts', 22 : 'Michigan', 23 : 'Minnesota', 24 : 'Mississippi', 25 : 'Missouri', 26 : 'Montana', 27 : 'Nebraska', 28 : 'Nevada', 29 : 'New Hampshire', 30 : 'New Jersey', 31 : 'New Mexico', 32 : 'New York', 33 : 'North Carolina', 34 : 'North Dakota', 35 : 'Ohio', 36 : 'Oklahoma', 37 : 'Oregon', 38 : 'Pennsylvania', 39 : 'Rhode Island', 40 : 'South Carolina', 41 : 'South Dakota', 42 : 'Tennessee', 43 : 'Texas', 44 : 'Utah', 45 : 'Vermont', 46 : 'Virginia', 47 : 'Washington', 48 : 'West Virginia', 49 : 'Wisconsin', 50 : 'Wyoming'};
                $.each(stateValues, function(key, value) {
                    $('#member_company_state').append('<option value="' + value + '" class="' + value + '">' + value + '</option>');
                })
            } else if (self.country == 'Canada') {
                $('#member_company_state option').remove();
                var stateValues = {1 : 'Alberta', 2 : 'British Columbia', 3 : 'Manitoba', 4 : 'New Brunswick', 5 : 'Newfoundland', 6 : 'Northwest Territories', 7 : 'Nova Scotia', 8 : 'Nunavut', 9 : 'Ontario', 10 : 'Prince Edward Island', 11 : 'Quebec', 12 : 'Saskatchewan', 13 : 'Yukon'};
                $.each(stateValues, function(key, value) {
                    $('#member_company_state').append('<option value="' + value + '" class="' + value + '">' + value + '</option>');
                })
            }
            if (self.state.length > 0) {
                $('#member_company_state option.' + 'WI').attr('selected', 'selected');
            }
        } else {
            var oldSelector = $('select#member_company_state');
            if ($(oldSelector).length) {
                $(oldSelector).after('<input class="text thick state" type="text" id="member_company_state" name="member_company_state" value="'+ lang.state +'" />');
                $(oldSelector).remove();
            }
        };
    }
}

/* ---------------------------------------------------------------------
UI Dialog
Author: Josh Anderson

Handles the Modals all over the site.
To use, simply put the class "ajax_modal" on a link.
The page you are linking to must have the class "ajax_container" surrounding the content you wish to display.
------------------------------------------------------------------------ */

NERD.UIDialog = {
    init: function() {
        if ($('.ajax_modal').length) {
            var self = this;
            $('.ajax_modal').live("click", function() {
                var url = $(this).attr('href');
                self.openModal(url);
                return false;
            });
        }
    },
    openModal: function(url) {
        var self = this;
        if (!$('div.modal_container').length) {
            $('body').append('<div class="modal_container"></div>');
        }
        $('div.modal_container').dialog({
            autoOpen: true,
            width: 780,
            height: 'auto',
            position: 'top',
            modal: true,
            resizable: false,
            closeOnEscape: true,
            draggable: false,
            open: function() {
                $(this).html('<div class="loading_modal"></div>');
                var link = url;
                $('.modal_container').load(link + ' .ajax_container', function() {
                    NERD.LocationMap.init();
                    NERD.EqualHeight.init();
                    $('.cancel_modal').click(function(e) {
                        e.preventDefault();
                        $('div.modal_container').dialog('close');
                    });
                    $('.close_modal').click(function() {
                        $('div.modal_container').dialog('close');
                    });
                });
            },
            close: function() {

            }
        });
    }
}

/* ---------------------------------------------------------------------
Filter Accordion
Author: Josh Anderson

Show and hide facet filters on the site
------------------------------------------------------------------------ */

NERD.FilterAccordion = {
    
    init: function() {
        
        if ($('.filter-accordion').length) {
            var self = this;
            
            $('.filter-accordion .facet_filters').hide();
            $('.filter-accordion .widget-heading .section-heading').addClass('trigger').removeClass('down');
            
            self.bind();
        }
        
    },
    
    bind: function() {
        
        var self = this;
        
        $('.filter-accordion .widget-heading .section-heading').toggle(
            function() {
                var me = $(this);
                me.closest('.widget-heading').next('.facet_filters').slideDown(200);
                me.addClass('down');
            },
            function() {
                var me = $(this);
                me.closest('.widget-heading').next('.facet_filters').slideUp(200);
                me.removeClass('down');
            }
        );
        
    }
    
}

/* ---------------------------------------------------------------------
Tab Container
Author: Josh Anderson

Create the tabs. Handle the show/hide of the tab content.
------------------------------------------------------------------------ */

NERD.TabContainer = {
    
    init: function() {
        
        if ($('.mason-tabs').length) {
            var self = this;
            
            var container = $('.mason-tabs');
            
            container.addClass("tab-container");
            
            container.append("<div class='tabs'> \
                <div class='tab tab-0'>" + lang.overview + "</div> \
                <div class='tab tab-1'>" + lang.requirements + "</div> \
                <div class='tab tab-2'>" + lang.become_a_supplier + "</div> \
                <div class='tab tab-3'>" + lang.submit_documents + "</div> \
                </div>");
            
            var tabCount = container.find('.tab').length;
            
            $('.mason').each(function(i) {
                var me = $(this);
                var html = me.html();
                $('.tabs').parent().append('<div class="tab-content tab-content-' + i + '">' + html + '</div>');
            });
            
            $('.mason').remove();
        }
        
        if ($('.tab-container').length) {
            var self = this;
            
            if ($('.tabs').length == "0") {
                $('.tab-container').prepend('<div class="tabs"></div>');

                $('.tab-container .tab-content').each(function(i) {
                    var me = $(this);
                    var tabText = me.prev('.module-heading').text();
                    me.prev('.module-heading').addClass('hidden');
                    me.addClass('tab-content-' + i);
                    $('.tabs').append('<div class="tab tab-' + i + '">' + tabText + '</div>');
                });
            }
            
            //Hide all tabs
            $('.tab-content').hide();
            
            if ($('.form_error').length) {
                //Show supplier form tab
                $('.tab-container .tab-content').eq(3).show();
                $('.tabs .tab').eq(3).addClass('active');
            } else {
                //Show first tab
                $('.tab-container .tab-content').eq(0).show();
                $('.tabs .tab').eq(0).addClass('active');
            }
            
            self.tabSizing();
            self.bind();
        }
        
    },
    
    tabSizing: function() {
        var self = this;
        
        var containerWidth = $('.tabs').width();
        var numberOfTabs = $('.tabs .tab').length;
        
        // Calculate the tab width
        var tabWidth = (containerWidth/numberOfTabs)-10;
        
        $('.tabs .tab').width(tabWidth);
    },
    
    bind: function() {
        
        $('.tab').click(function() {
            var me = $(this);
            
            if (me.hasClass('active') == false) {
                var tabContent = me.attr('class').replace('tab ', '').replace('tab-', 'tab-content-');
            
                // Hide all tabs
                $('.tab-content').hide();
                $('.tabs .tab').removeClass('active');
            
                // Show the content
                $('.' + tabContent).show();
                me.addClass('active');
            }   
        });
        
    }
    
}

/* ---------------------------------------------------------------------
Supplier Fields
Author: Josh Anderson

SupplierFields handles the "Add another document" link and adds more fields for them to use. A max of 5.
If js is disabled they just see 5 file upload fields.
------------------------------------------------------------------------ */

NERD.SupplierFields = {
    
    init: function() {
        
        if ($('#supplier-submissions_proform').length) {
            var self = this;

            $('.proform').find('.column-group').each(function(i) {
                i = i+1;
                $(this).addClass('row-number' + i);
            });
            
            $('.proform').find('.column-group').each(function(i) {
                if (i >= "4") {
                    var FieldHTML = $('.row-number' + i + ' .column.half').html();
                    $('.row-number' + i + ' .column').addClass('first');
                    $('.row-number' + i + ' .column').after('<div class="column half">' + FieldHTML + '</div>');
                    $('.row-number' + i + ' .first').empty().attr('style', 'width: 321px; height: 60px;');
                }
            });
            
            $('.file-input').each(function(i) {
                i = i+1;
                $(this).addClass('file-input' + i);
            });
            
            $('.file-input').hide();
            $('.file-input1').show();
            $('.file-input2').show();
            $('.file-input3').parent().append('<a class="add-file-input">Add another document</a>');
            
            self.bind();
        }
        
    },
    
    bind: function() {
        var self = this;
        
        // Link to add more file fields
        $('.add-file-input').live('click', function() {
            
            var currentNumber = parseInt($(this).parent().find('.file-input').attr('class').replace(' ', '').replace('file-inputfile-input', ''));
            var currentField = $('.file-input' + currentNumber);
            var nextField = $('.file-input' + parseInt(currentNumber+1));
            
            $('.add-file-input').remove();
            if (nextField.attr('class') != 'fileinput fileinput5') {
                nextField.after('<a class="add-file-input">Add another document</a>');
            }
            
            currentField.show();
            
        });
    }
    
}

/* ---------------------------------------------------------------------
Resume Upload Form
Author: Josh Anderson

Hides the Resume Upload form on page load for users with js.
Then displays the form when they click the "apply for this position" button.
Also adds a print button for users.
------------------------------------------------------------------------ */

NERD.ResumeUploadForm = {
    
    container: undefined,
    state: undefined,
    country: undefined,
    
    init: function() {
        if ($('.resume-upload').length) {
            var self = this;
            if ($('.print_this_container').length) {
                $('.print_this_container').append('<a href="#">Print This</a><a href="#"><div class="icon print">Print Icon</div></a>');
            }
            self.container = $('.resume-upload');
            for (i=2;i<6;i++) {
                $('label.attach_resume_' + i).remove();
            }
            $('.form .column-group').each(function(i) {
                i = i+1;
                $(this).addClass('rownumber' + i);
            });
            $('.fileinput').each(function(i) {
                i = i+1;
                $(this).addClass('fileinput' + i);
                var fieldHTML = $(this).parent().html();
                if (i!=1) {
                    $('.fileinput' + (i-1)).after(fieldHTML);
                }
            });
            for (i=4;i<8;i++) {
                $('.rownumber' + i).remove();
            }
            $('.fileinput').hide();
            $('.fileinput1').show();
            $('.fileinput5').after('<a class="add-file-input">Add another document</a>');
            self.bind();
        }
    },
    
    bind: function() {
        var self = this;
        // Link to add more file fields
        $('.add-file-input').click(function(e) {
            e.preventDefault();
            $('.fileinput').each(function() {
                var me = $(this);
                if (me.is(':hidden')) {
                    me.show();
                    if (me.hasClass('fileinput5')) {
                        $('.add-file-input').hide();
                    }
                    return false;
                }
            });
        });
        $('.print_this_container a').click(function() {
            window.print();
            return false;
        });
        // Country and state dropdown - Get it right away and whenever it changes.
        self.country = $('#country_select').val();
        self.state = $('#state_select').attr('value');
        self.stateOptions();
        $('#country_select').live('change', function() {
            self.country = $(this).val();
            self.stateOptions();
        });
    },
    
    stateOptions: function() {
        var self = this;
        if (self.country == 'United States' || self.country == 'Canada') {
            var oldSelector = $('input#state_select');
            if ($(oldSelector).length) {
                $(oldSelector).after('<select class="thicksel" id="state_select" name="state_select"></select>');
                $(oldSelector).remove();
            }
            if (self.country == 'United States') {
                $('#state_select option').remove();
                var stateValues = {1 : 'Alabama', 2 : 'Alaska', 3 : 'Arizona', 4 : 'Arkansas', 5 : 'California', 6 : 'Colorado', 7 : 'Connecticut', 8 : 'Delaware', 9 : 'Florida', 10 : 'Georgia', 11 : 'Hawaii', 12 : 'Idaho', 13 : 'Illinois', 14 : 'Indiana', 15 : 'Iowa', 16 : 'Kansas', 17 : 'Kentucky', 18 : 'Louisiana', 19 : 'Maine', 20 : 'Maryland', 21 : 'Massachusetts', 22 : 'Michigan', 23 : 'Minnesota', 24 : 'Mississippi', 25 : 'Missouri', 26 : 'Montana', 27 : 'Nebraska', 28 : 'Nevada', 29 : 'New Hampshire', 30 : 'New Jersey', 31 : 'New Mexico', 32 : 'New York', 33 : 'North Carolina', 34 : 'North Dakota', 35 : 'Ohio', 36 : 'Oklahoma', 37 : 'Oregon', 38 : 'Pennsylvania', 39 : 'Rhode Island', 40 : 'South Carolina', 41 : 'South Dakota', 42 : 'Tennessee', 43 : 'Texas', 44 : 'Utah', 45 : 'Vermont', 46 : 'Virginia', 47 : 'Washington', 48 : 'West Virginia', 49 : 'Wisconsin', 50 : 'Wyoming'};
                $.each(stateValues, function(key, value) {
                    $('#state_select').append('<option value="' + value + '" class="' + value + '">' + value + '</option>');
                })
            } else if (self.country == 'Canada') {
                $('#state_select option').remove();
                var stateValues = {1 : 'Alberta', 2 : 'British Columbia', 3 : 'Manitoba', 4 : 'New Brunswick', 5 : 'Newfoundland', 6 : 'Northwest Territories', 7 : 'Nova Scotia', 8 : 'Nunavut', 9 : 'Ontario', 10 : 'Prince Edward Island', 11 : 'Quebec', 12 : 'Saskatchewan', 13 : 'Yukon'};
                $.each(stateValues, function(key, value) {
                    $('#state_select').append('<option value="' + value + '" class="' + value + '">' + value + '</option>');
                })
            }
            if (self.state.length > 0) {
                $('#state_select option.' + 'WI').attr('selected', 'selected');
            }
        } else {
            var oldSelector = $('select#state_select');
            if ($(oldSelector).length) {
                $(oldSelector).after('<input class="text thick state" type="text" id="state_select" name="state_select" value="" />');
                $(oldSelector).remove();
            }
        };
    }
    
}

NERD.PriceListForm = {
    init: function() {
        if ($('.price-list-options').length) {
            var self = this;
            var container = $('.price-list-options');
            container.before('<select class="price-list-option-js"></select>');
            container.find('li').each(function() {
                var me = $(this);
                me.price_title = me.text();
                me.price_class = me.attr('class');
                $('.price-list-option-js').append('<option class="' + me.price_class + '">' + me.price_title + '</option>');
            });
            $('.price-list-option-js').prepend('<option selected="selected"></option>');
            container.remove();
            $('.price-list-option-text').remove();
            $('#price_list_region').hide();
            self.bind();
        }
    },
    bind: function() {
        var self = this;
        var selectList = $('.price-list-option-js');
        $(selectList).live('change', function() {
            var me = $(this);
            $('#price_list_region').val(me.val());
        });
    }
}


/* ---------------------------------------------------------------------
Form Submissions
Author: Josh Anderson

Hides and shows the forms on the form submission page
------------------------------------------------------------------------ */

NERD.FormSubmissions = {
    
    button: undefined,
    
    init: function() {
        if ($('.form-information-table').length) {
            
            var self = this;
            
            $('.result-list .column.description').append('<p><span class="form-submit-details arrow down">View Submission Details</span></p>');
            $('.form-information-table').wrap('<div class="form-information-details" />');
            self.button = $('.form-submit-details');
            self.list = $('.form-information-details');
            self.list.each(function() {
                var me = $(this);
                var height = me.height();
                var width = me.width();
                me.css('height', height);
                me.css('width', width);
                me.attr('style', 'display: none; height: ' + height + 'px; width: 650px;');
            });
            
            self.bind();
            
        }
    },
    
    bind: function() {
        var self = this;
        self.button.toggle(
            function() {
                var list = $(this).parent().parent().parent().next('.form-information-details');
                list.slideDown();
            },
            function() {
                var list = $(this).parent().parent().parent().next('.form-information-details');
                list.slideUp();
            }
        );
    }

}

/* ---------------------------------------------------------------------
Price List Addendums
Author: Josh Anderson

Hides and shows the forms on the form submission page
------------------------------------------------------------------------ */

NERD.PriceListAddendums = {
    
    button: undefined,
    
    init: function() {
        if ($('.price-list-addendum').length) {
            
            var self = this;
            
            $('.price-list-addendum').parent().find('.column.description').append('<p><span class="form-submit-details arrow down">' + lang.view_price_list_addendum + '</span></p>');
            $('.price-list-addendum').wrap('<div class="addendum-information-table" />');
            self.button = $('.form-submit-details');
            self.list = $('.addendum-information-table');
            self.list.each(function() {
                var me = $(this);
                var height = me.height();
                var width = me.width();
                me.css('height', height);
                me.css('width', width);
                me.attr('style', 'display: none; height: ' + height + 'px; width: 680px;');
            });
            
            self.bind();
            
        }
    },
    
    bind: function() {
        var self = this;
        self.button.toggle(
            function() {
                var list = $(this).parent().parent().parent().next('.addendum-information-table');
                list.slideDown();
            },
            function() {
                var list = $(this).parent().parent().parent().next('.addendum-information-table');
                list.slideUp();
            }
        );
    }

}

/* ---------------------------------------------------------------------
Lang Dropdown
Author: Josh Anderson

Handle other languages for the downloads section.
------------------------------------------------------------------------ */

NERD.LangDropdown = {
    
    init: function() {
        if (('.download-lang-list').length) {
            var self = this;
            
            $('.other-languages').removeClass('active');
            $('.other-languages span').addClass('arrow').addClass('down');
            $('.download-lang-list').hide();
            
            self.bind();
        }
    },
    
    bind: function() {
        
        $('.other-languages').toggle(
            function() {
                var me = $(this);
                me.addClass('active');
                me.next('.download-lang-list').slideDown(400);
            },
            function() {
                var me = $(this);
                me.next('.download-lang-list').slideUp(400);
                setTimeout(function() {
                    me.removeClass('active');
                }, 400);
            }
        );
        
    }
    
}

NERD.LocationMap = {
    init: function() {
        var locationMap = $('.location-map');
        if(locationMap.length !== 0) {
            var self = this;
            self.locationMap = locationMap;
            self.region = self.locationMap.find('.regions li a');
            self.map = self.locationMap.find('.map');
            
            self.region.hover(function() {
                self.over($(this));
            }, function() {
                self.off($(this));
            });
        }
    },
    
    over: function(trigger) {
        var self = this;
        var fadeDur = 300;
        
        if(trigger.hasClass('r1a') || trigger.hasClass('r1b')) {
            var mapPos = 1;
        } else if(trigger.hasClass('r2')) {
            var mapPos = 2;
        } else if(trigger.hasClass('r3')) {
            var mapPos = 3;
        } else if(trigger.hasClass('r4')) {
            var mapPos = 4;
        } else if(trigger.hasClass('r5a') || trigger.hasClass('r5b')) {
            var mapPos = 5;
        } else if(trigger.hasClass('r6')) {
            var mapPos = 6;
        } else if(trigger.hasClass('r7')) {
            var mapPos = 7;
        } else if(trigger.hasClass('r8')) {
            var mapPos = 8;
        } else if(trigger.hasClass('r9')) {
            var mapPos = 9;
        } else if(trigger.hasClass('r10')) {
            var mapPos = 10;
        } else if(trigger.hasClass('r11')) {
            var mapPos = 11;
        }
        
        mapPos = '0px -'+(mapPos * 350)+'px';                
        self.map
            .stop(true, true)
            .fadeOut(0)
            .css({'background-position': mapPos})
            .fadeIn(fadeDur)
        ;
    },
    
    off: function(trigger) {
        var self = this;
        self.map
            .stop(true, true)
            .fadeOut(0)
            .css({'background-position': '0 0'})
            .fadeIn(fadeDur)
        ;
    }
}

/* ---------------------------------------------------------------------
ToolTips

Handles the tooltips on the events calendar.
------------------------------------------------------------------------ */

NERD.Tooltips = {
    $markup: $('<span class="tooltip png_bg"><span class="close-tool-tip"></span><span class="wrapper png_bg"><span class="wrapper-inner png_bg"></span></span></span>'),
    $hoverDate: undefined,
    init: function() {
        if ($('.calendar_date').length) {
            var self = this;
            self.$hoverDate = $('.event .info');
            $('.calendar_widget').hide();
            self.bind();
        }
    },
    bind: function() {
        var self = this;
        self.$hoverDate.click(
            function(event) {
                event.stopPropagation();
                var me = $(this).parent();
                var date = me.attr('class').replace(' ', '').replace('calendar_date', '').replace('calendar_date_', '').replace('event', '').replace('hover', '');
                var html = $('.sidebar_widget_' + date + ' .main').html();
                var infoWidth = me.find('.info').width();
                
                // In case being called for a second time, remove existing tooltips
                $('.tooltip-container').remove();
                
                me.append('<div class="tooltip-container"></div>');
                
                var $tip = self.$markup.clone();
                
                me.find('.tooltip-container').append($tip);
                $tip.find('.wrapper-inner').append(html);
                $tip.css(
                    {
                        'left': infoWidth,
                        'top' : Math.floor(-(($tip.height()/2)+14))
                    }
                );
                $('.close-tool-tip').click(function() {
                    $('.tooltip-container').remove();
                });
                $('html').click(function() {
                    $('.tooltip-container').remove();
                });
            }
        );
    }
}

// Add classes to the youtube blocks

NERD.Community = {
    init: function() {
        if ($('.youtube-block').length) {
            var self = this;
            $('.youtube-item').each(function(i) {
                var me = $(this);
                me.removeClass('youtube-item');
                if (i == 0) {
                    me.addClass('featured');
                } else {
                    me.addClass('block-0' + i);
                }
            });
        }
    }
}

// Set all profile grey boxes to an equal height.

NERD.EqualHeight = {
    init: function() {
        if ($('.equal-height').length) {
            var self = this;
            var container = $('.equal-height');
            var height = container.height()-40;
            
            container.find('div.form').height(height);
        }
    }
}

NERD.Flowplayer = {
    
    init: function() {
        
        //Flowplayer Call
        if($('#player').length) {
            flowplayer("player", {
                src: root_url + "assets/media/flash/flowplayer-3.2.7-0.swf",
                wmode: "opaque"
                }, {
                // change the default controlbar's style preferences
                plugins: {
                    controls: {
                        backgroundColor: '#000',
                        progressColor: '#FFFFFF',
                        bufferColor: '#CCCCCC',
                        durationColor: '#CCCCCC',
                        volumeColor: '#FFFFFF',
                        backgroundGradient: 'medium'
                    }
                }
            }).ipad();
        }
    
        if($('.testimonial_player').length) {
            flowplayer(".testimonial_player", root_url + "assets/media/flash/flowplayer-3.2.7-0.swf", {
                clip: {
                    autoPlay: false
                },
                plugins: {
                    controls: {
                       all: false
                   }
                }
            }).ipad();
        }
        
    }
    
}

/**
 * Victaulic Solr Search
 *
 * @author      Brian Litzinger
 * @link        http://nerdery.com
 *
 * Initialized only on the search/results page. When clicking on a category/facet
 * in the left sidebar, it saves the value to the saved_filters object, which
 * is then passed to the Ajax request and sends those saved_filters to the
 * search/results_listing file. It contains an EE plugin that sends the requested
 * filters to Solr itself, then returns the results to the page.
 *
 */
 
var FacetSearch = {
    
    init: function(results_template, filters, ajax) {
        var self = this;
        
        // get collections for our clickable items
        self.current_filters = $('#current_facet_filters');
        self.facet_filters = $('.facet_filters');
        self.facet_headings = $('.filters .widget-heading');
        self.remove_all = $('#remove_all_filters');
        self.sort = $('#sort');
        // self.arrange = $('#arrange');

        if (self.sort.length) {
            var me = $(this);
            $('.heading-form').show();
        }
        
        $('.heading-select').click(function() {
            $('#sort').show();
        });

        // create object to save selections to, preset to filters if it's sent to init()
        self.saved_filters = (typeof filters == 'object') ? filters : {};

        // How fast do we want our filters to fade in/out?
        self.fade_speed = (ajax === true) ? 0 : 'fast';

        // Get the template/uri to hit in the ajax response
        self.results_template = results_template;

        // kick it off
        self.bind();
        
        if(self.saved_filters)
        {
            for(key in self.saved_filters)
            {
                // Turn our string into a usable array
                if(Object.prototype.toString.call(self.saved_filters[key]) === "[object Array]")
                {
                    var value = self.saved_filters[key][0].split(',');
                }
                else
                {
                    var value = self.saved_filters[key].split(',');
                }

                // Re-create our key values as arrays, not just strings
                self.saved_filters[key] = [];

                for(i = 0; i < value.length; i++)
                {
                    self.saved_filters[key].push(value[i]);
                }
            }

            self.onload();
        }

        $('#remove_all_filters').hide();
    },

    onload: function()
    {
        var self = this;

        setTimeout({
            run: function() {

                for(key in self.saved_filters)
                {
                    values = self.saved_filters[key];

                    // Loop over each possible ID and find the filter matching the
                    // facet and ID and move them to the current filters list
                    for(i = 0; i < values.length; i++)
                    {
                        var ele = self.facet_filters.find('#'+ key +'_'+ values[i]);

                        ele.addClass('cloned').fadeOut(self.fade_speed, function(){
                            var clone = $(this).clone();
                            self.hide_empty();
                            clone.appendTo(self.current_filters.closest('ul')).fadeIn(self.fade_speed);
                        });
                    }
                }
                
                // Update the list
                self.accordian(true);
            }
        }.run, 1000);
    },

    bind: function() {
        var self = this;
        var rels = [],
            facet_groups = [];

        self.current_filters.find('li.facet').live('click', function(e){
            self.remove_filter($(this), true);
            e.preventDefault();
        });

        self.facet_filters.find('li.facet').live('click', function(e){
            self.add_filter($(this), true);
            e.preventDefault();
        });

        self.remove_all.live('click', function(e){
            self.remove_all_filters(true);
            e.preventDefault();
        });

        // For sorting ASC/DESC or by Title, UL needs #sort
        self.sort.find('a').live('click', function(e){
            var field = self.get_data($(this), 'field');
            var value = self.get_data($(this), 'value');

            var href = window.location.href;
            var qry_keys = parseUri(href).queryKey;

            if(qry_keys.order_by && qry_keys.order)
            {
                href = href.replace(/order_by=(\w+)/, 'order_by='+ field);
                href = href.replace(/order=(\w+)/, 'order='+ value);
            }
            else
            {
                href = href.indexOf('?') != -1 ? href + '&' : href + '?';
                href = href + 'order_by='+ field + '&order='+ value;
            }

            window.location = href;

            $('#sort').hide();

            e.preventDefault();
        });

        // Find all filter groups that are duplicates or go by the same rel value,
        // e.g product sizing for inches and metric
        self.facet_filters.each(function(i){
            rel = $(this).attr('rel');

            if(self.facet_filters.filter('[rel='+ rel +']').length > 1 && $.inArray(rel, rels) == -1)
            {
                // Add class so we know this is a group of measurements
                $(this).addClass('group');
                
                rels.push(rel);
            }
        });
        
        if(rels.length > 0)
        {
            var keys = {
                productKFactorImperial:  'psi',
                productKFactorSi:        'kPa',
                productSizeRangeInches:  'in',
                productSizeRangeMetric:  'mm',
                productOrificeInches:    'in',
                productOrificeMetric:    'mm'
            };

            // Go through each of our found duplicates, and append all their child LIs to the first dupe,
            // then remove all the rest of the dupes. This is to toggle units of measurements.
            for(i = 0; i < rels.length; i++)
            {
                original = self.facet_filters.filter('[rel='+ rels[i] +']:eq(0)');
                main_rel = original.find('li:eq(0)').attr('rel');
                
                dupes = self.facet_filters.filter('[rel='+ rels[i] +']:gt(0)');
                original.append(dupes.find('li'));

                dupes.prev('div').remove();
                dupes.remove();

                original.find('li').not('[data-facet='+ main_rel +']').hide();
                inactive_rel = original.find('li').not('[data-facet='+ main_rel +']').attr('rel');

                var toggle = '<div class="widget-toggle">\
                                <a class="active" rel="'+ main_rel +'" href="#">'+ keys[main_rel] +'</a>\
                                <span class="toggle-separator">|</span>\
                                <a class="" rel="'+ inactive_rel +'" href="#">'+ keys[inactive_rel] +'</a>\
                            </div>';

                // original.before(toggle);
                var widget_heading = original.prev('div.widget-heading').append(toggle);
                
                $(widget_heading).find('a').click(function(e){

                    var link = $(this);
                    var link_rel = link.attr('rel');
                    var sibling = link.siblings('a');
                    // var block_list = link.closest('div.block_list');
                    var block_list = link.closest('div.widget-heading').next('ul.facet_filters');
                    var items = block_list.find('li');
                    
                    if(link.hasClass('active'))
                    {
                        link.removeClass('active');
                        sibling.addClass('active');

                        items.not('[data-facet='+ link_rel +']').not('.cloned').show();
                        items.filter('[data-facet='+ link_rel +']').hide();
                    }

                    if(!link.hasClass('active'))
                    {
                        link.addClass('active');
                        sibling.removeClass('active');

                        items.not('[data-facet='+ link_rel +']').hide();
                        items.filter('[data-facet='+ link_rel +']').not('.cloned').show();
                    }
                    
                    e.preventDefault();
                });
            }
        }
    },

    show_empty: function()
    {
        if(this.current_filters.find('li.facet').length == 0)
        {
            this.accordian(true);
            this.current_filters.find('div.info').fadeIn('fast');
            this.current_filters.closest('.widget').removeClass('block_list').find('div.info').show();
            $('#remove_all_filters').hide();
        }
    },

    hide_empty: function()
    {   
        $('.filters.toggle_list').find('div.info').hide();
        $('#remove_all_filters').show();
    },

    add_filter: function(ele, search) {
        var self = this;

        var id = self.get_data(ele, 'id');
        var facet = self.get_data(ele, 'facet');
        var facet_group = self.get_data(ele, 'facet-group');

        // Make sure our facet exists in the saved_filters obj
        // and is an array before pushing the ID to it.
        if(typeof(self.saved_filters[facet]) == 'undefined')
        {
            self.saved_filters[facet] = [];
        }

        // Add add the selected ID to it's facet array
        self.saved_filters[facet].push(id);

        clone = ele.addClass('cloned').clone();
        clone.appendTo(self.current_filters.closest('ul')).fadeIn(self.fade_speed, function(){
            self.hide_empty();
            self.accordian(true);
        });
        
        // ele.addClass('cloned').fadeOut(self.fade_speed, function(){
        //     clone = ele.clone();
        //     clone.appendTo(self.current_filters.closest('ul')).fadeIn(self.fade_speed, function(){
        //         self.hide_empty();
        //         self.accordian(true);
        //     });
        // });
        
        if(search) self.search();
    },

    remove_filter: function(ele, search) {
        var self = this;

        var id = self.get_data(ele, 'id');
        var facet = self.get_data(ele, 'facet');
        var facet_group = self.get_data(ele, 'facet-group');

        if(self.saved_filters[facet].length > 0)
        {
            for (i = 0; i < self.saved_filters[facet].length; i++)
            {
                if (self.saved_filters[facet][i] == id)
                {
                    self.saved_filters[facet].splice(i, 1);
                }
            }
        }

        ele.fadeOut(self.fade_speed, function(){
            ele.remove();
            $('#'+ facet +'_'+ id).removeClass('cloned').fadeIn(self.fade_speed, function(){
                self.show_empty();
                if(search) self.accordian(true);
            });
        });

        if(search) self.search();
    },

    remove_all_filters: function(search) {
        var self = this;

        self.current_filters.find('li').not('.empty').each(function(){
            self.remove_filter($(this), false);
        });

        if(search) self.search();
    },

    search: function()
    {
        var self = this;

        results = $('#solr_results');

        if(results[0].tagName == 'UL')
        {
            results.addClass('loading_ajax').html('<li></li>');
        }
        else
        {
            results.addClass('loading_ajax').html('');
        }

        data_array = [];
        
        // Create a URI string that EE won't barf on.
        // facet=123,456,789
        for (var facet in self.saved_filters)
        {
            if(self.saved_filters[facet].length > 0)
            {
                data_array.push(facet +'='+ self.saved_filters[facet].join(','));
            }
        }

        var href = window.location.href;
        var qry_keys = parseUri(href).queryKey;

        if(qry_keys.order_by && qry_keys.order)
        {
            data_array.push('order_by='+ qry_keys.order_by);
            data_array.push('order='+ qry_keys.order);
        }

        data_str = data_array.length > 0 ? '?'+ data_array.join('&') : '';
        
        // See if we have a date pair in the URI. All EE's dates are /yyyy/mm/
        var date_regex = /(\d{4})\/(\d{2})/g; 
        
        // If so, add it to the new URI
        if(date_regex.test(href)) 
        {
            var matches = href.match(date_regex);
            data_str = '/'+ matches[0] + data_str
        }

        $('.paginator_num').hide();

        // Add a slight delay so the user can see whats going on (ajax spinner, 
        // filter moving in/out of the selected filters box)
        setTimeout({
            run: function() {
                // $('#content').load(root_url + self.results_template + data_str +' #content_inner', function(response, status, xhr){
                //     if(status == 'error')
                //     {
                //         $('#solr_results').html('<p>There was an error with your request.</p>');
                //     }
                //     else
                //     {
                //         self.init(self.results_template, self.saved_filters, true);
                //     }
                // });
                // return false;
                // console.log(site_url + self.results_template + data_str);
                window.location = site_url + self.results_template + data_str;
            }
        }.run, 250);
        
        return false;
    },

    /*
        This is called in init, and whenever a facet is added to or removed
        from the current_facets list. It keeps the more/less button visible
        or hidden when needed, and also keeps the "5 more..." text up-to-date.
        When an item is given the class of "cloned" it means it has been
        cloned and added to the current_facets list. The accordian does not
        affect any items of this class, they're essentially invisible to the
        accordian.
    */
    accordian: function(updating)
    {
        var self = this;
        
        self.facet_filters.each(function(){

            var ul = $(this);
            var cloned = $(this).find('li.facet').filter('.cloned');
            var normal = $(this).find('li.facet').not('.cloned');
            var all = $(this).find('li.facet');
            
            // console.log('cloned');
            // console.log(cloned);
            // console.log('normal');
            // console.log(normal);
            // console.log('all');
            // console.log(all);
            
            var li = updating ? normal : all;

            var display_limit = self.get_data(ul, 'list-display-limit');
            var diff = 0;

            // Only count those that are visible, some are hidden in bind()
            var count = $(li).filter(':visible').length;

            ul.closest('div').show();
            
            // in the event that one of the cloned filters is in a list with 1 sibling
            // of another measurement, show that sibling and change the measurement toggle.
            if(ul.hasClass('group') && count > 0 && cloned.length > 0 && normal.length > 0)
            {
                normal.show();
                
                active = ul.closest('div').find('.widget-toggle a').filter('.active');
                ul.closest('div').find('.widget-toggle a').not('.active').addClass('active');
                active.removeClass('active');
            }
            // otherwise hide the entire container, no facets to show
            else if(count == 0)
            {
                //ul.closest('div').hide();
            }
            else
            {
                if(count <= display_limit)
                {
                    if(ul.find('li.more_less').length == 1 && !updating)
                    {
                        ul.find('li.more_less').hide();

                        // Make sure all LIs are visible at this point b/c we just removed their only
                        // control to make them visible.
                        li.fadeIn();
                    }
                }
                else if(count > display_limit)
                {
                    diff = count - display_limit;

                    if(ul.find('li.more_less').length == 1)
                    {
                        view = ul.find('li.more_less').show();

                        if(view.hasClass('more'))
                        {
                            view.children('a').text(diff +' '+ lang.view_more);
                        }
                    }
                    else
                    {
                        view = $('<li class="more_less more"><a href="#">'+ diff +' '+ lang.view_more +'</a></li>');
                        view.appendTo(ul);
                    }

                    /*
                        In the event that no cloned items are available, show some.
                        This happened during dev when the display_limit was set to 1, if
                        that single item was clicked, it would be hidden and moved to the
                        current_filters list, then the rest of the filters would still be
                        hidden and the more/less button would have to be clicked to show
                        more options. This way it always keeps the minimum of display_limit
                        visible in each facet list.
                    */
                    if(li.filter(':visible').length == 0)
                    {
                        li.filter(':lt('+ display_limit +'):not(.cloned)').show();
                    }
                    else
                    {
                        // Hide anything beyond our display limit
                        li.filter(':gt('+ (display_limit - 1) +'):not(.cloned)').addClass('extra').hide();
                    }
                    
                    // Show or hide sibling LIs depending on current visibility or classes
                    view.unbind('click').click(function(e)
                    {
                        var me = $(this);
                        
                        if(me.hasClass('more') == true)
                        {
                            e.preventDefault();
                            filtered_li = li.filter('.extra:not(.cloned)');

                            me.addClass('less').removeClass('more').children('a').text(lang.view_less);
                            filtered_li.filter(':hidden').slideDown();
                        }
                        else
                        {
                            e.preventDefault();
                            filtered_li = li.filter('.extra:not(.cloned)');

                            me.addClass('more').removeClass('less').children('a').text(diff +' '+ lang.view_more);
                            filtered_li.filter(':visible').slideUp();
                        }
                    });
                    
                    if(updating && view.hasClass('less')) view.click();
                }
            }
            
            // if(self.facet_filters.filter(':visible').length == 0)
            if($('.filter-accordion .widget-heading').length == 0)
            {
                $('#refine_search, .filter-accordion').hide();
            }

            if (li.length == 0) 
            {
                ul.prev('.widget-heading').hide();
            }
            else
            {
                $('.filter-accordion .facet_filters').hide();
                $('.filter-accordion .widget-heading .section-heading').addClass('trigger').removeClass('down');

                $('.filter-accordion .widget-heading .section-heading').toggle(
                    function() {
                        $(this).closest('.widget-heading').next('.facet_filters').slideDown(200);
                        $(this).addClass('down');
                    },
                    function() {
                        $(this).closest('.widget-heading').next('.facet_filters').slideUp(200);
                        $(this).removeClass('down');
                    }
                );
            }
            
            
        });
    },

    get_data: function(ele, key)
    {
        var self = this;
        // make sure we get our data attribute no matter what version of jQuery we have
        return $(ele).data(key) || $(ele).attr('data-'+ key) || false;
    }
}

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
    var o   = parseUri.options,
        m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
        uri = {},
        i   = 14;

    while (i--) uri[o.key[i]] = m[i] || "";

    uri[o.q.name] = {};
    uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
    });

    return uri;
};

parseUri.options = {
    strictMode: false,
    key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
    q:   {
        name:   "queryKey",
        parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
        strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
        loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};


// https://github.com/carhartl/jquery-cookie
(function($) {
    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)) {
            options = $.extend({}, options);

            if (value === null || value === undefined) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || {};
        var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

        var pairs = document.cookie.split('; ');
        for (var i = 0, pair; pair = pairs[i] && pairs[i].split('='); i++) {
            if (decode(pair[0]) === key) return decode(pair[1] || ''); // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, thus pair[1] may be undefined
        }
        return null;
    };
})(jQuery);


