/*check that the 'boc' namespace doesn't already exist*/
if(typeof boc === 'undefined') {
    boc = {};
}

boc.gas2010 = {

    applications: [],
    usages: [],
    
    init: function() {
        this.productSelectorInit();
        this.menuRoller();
        this.validateAskBarry();
		
		jQuery('a[href*=pdf], a[rel=external]').click(function() {
			window.open(this.href);
			return false;
		});

    },
    validateAskBarry: function() {
        if(jQuery('#ask-barry-contact-form').length === 0) {
            return;
        }

        jQuery('#ask-barry-contact-form').validate({
            rules: {
                message: {
                    required: true,
                    minlength: 3
                },
                email: {
                    required: true,
                    email: true
                }
            },
            errorPlacement: function(error, element) {
                error.insertAfter(element.parent());
            },
            success: function(label) {
                label.addClass('valid').text('Ok!');
            }
        });
    },
    productSelectorInit: function() {
        if(jQuery('#product-selector').length === 0) {
            return;
        }

        jQuery('#load-recommended-gases').empty();
        jQuery('#recommended-gases-heading').hide();
        
        var that = this;

        /*display a loading image*/
        jQuery('<img id="ajax-loader-image" src="./images/ajax_loader.gif" alt="" />').css({
            position: 'relative',
            margin: 'auto',
            display: 'block',
            top: '10px'
        }).insertBefore(jQuery('#recommended-gases-heading'));

        //storage

        jQuery.get('xml/product_selection.xml', function(data) {

            jQuery('#ajax-loader-image').remove();

            jQuery(data).find('entry').each(function() {
                var application = jQuery(this).find('application').text();
                if(!that.inArray(application, that.applications)) {
                    that.applications.push(application);
                }
            });
            var html = '<p><b>Q1. Application</b></p><p><select name="applications">';
            html += '<option value="#">Please select an option</option>';
            jQuery.each(that.applications, function(i, elm) {
                html += '<option value="' + elm + '">' + elm + '</option>';
            });
            html += '</select></p>';
            html += '<p><b>Q2. Temperature Range or Usage/System</b></p><p><select name="usages" disabled="disabled">';
            html += '<option value="#">Please select an option</option>';
            html += '</select></p>';
            html += '<p><b>Q3. Oil Change?</b></p><p><select name="oilchange" disabled="disabled">';
            html += '<option value="#">Please select an option</option>';
            html += '<option value="yes">Yes</option>';
            html += '<option value="no">No</option>';
            html += '</select></p>';
            html += '<p class="align-right"><a id="refresh-product-selector"><img id="refresh-image" src="images/table_refresh.png" alt="" />Start Again</a></p>'

            jQuery('#product-selector').html(html);

            jQuery('a#refresh-product-selector').click(function() {
                that.usages = [];
                that.applications = [];
                that.productSelectorInit();
                jQuery(this).unbind();
            });

            var html2 = '<option value="#">Please select an option</option>';
            
            var application = 0;

            jQuery('select[name=applications]').change(function() {
                jQuery(this).attr('disabled', 'disabled');
                application = this.options[this.selectedIndex].value;
                if(application !== '#') {
                    jQuery(data).find('entry').each(function() {
                        if(jQuery(this).find('application').text() === application) {
                            if(!that.inArray(jQuery(this).find('usage').text(), that.usages)) {
                                that.usages.push(jQuery(this).find('usage').text());
                            }
                        }
                    });
                    jQuery.each(that.usages, function(i, elm) {
                        html2 += '<option value="' + elm + '">' + elm + '</option>';
                    });
                    jQuery('select[name=usages]').html(html2);
                }
                jQuery('select[name=usages]').removeAttr('disabled');
            });

            var usage = 0;

            jQuery('select[name=usages]').change(function() {
                jQuery(this).attr('disabled', 'disabled');
                usage = this.options[this.selectedIndex].value;
                jQuery('select[name=oilchange]').removeAttr('disabled');
            });

            var oilchange = 0;

            jQuery('select[name=oilchange]').change(function() {
                oilchange = this.options[this.selectedIndex].value;
                if(oilchange !== '#') {
                    
                    jQuery(data).find('entry').each(function() {
                        if(
                            (jQuery(this).find('application').text().toLowerCase() === application.toLowerCase())
                            && (jQuery(this).find('usage').text().toLowerCase() === usage.toLowerCase())
                            && (jQuery(this).find('oilchange').text().toLowerCase() === oilchange.toLowerCase())
                        ) {
                            jQuery('#recommended-gases-heading').show();
                            var notes = [];
							jQuery(this).find('gases').find('gas').each(function() {
								var gasHTML = '<p class="gasHTMLToken"><a href="' + jQuery(this).find('link').text() + '">' + jQuery(this).find('name').text() + '';
								if(jQuery(this).find('notes').length > 0) {
									gasHTML += ' *';
									notes.push(jQuery(this).find('notes').text());
								}
								gasHTML += '</a></p>';
								jQuery('#load-recommended-gases').append(gasHTML);
							});
                            for(var i = 0, ii = notes.length; i < ii; i+=1) {
                                jQuery('#load-recommended-gases').append(
                                    jQuery('<p class="disclaimer-type-text"></p>').text('* ').append(notes[i])
                                );
                            }
                        }
                    });
					
					if(jQuery('#load-recommended-gases').find('.gasHTMLToken').length === 0) {
						jQuery('#recommended-gases-heading').show();
						jQuery('#load-recommended-gases').append(jQuery('<p></p>').text("No gases found. It is suggested that you try the same values with an oil change or try a different usage system."));
					}
					
                    jQuery('select[name=oilchange]').attr('disabled', 'disabled');
                }
            });
        });

    },

    menuRoller: function() {

        var navElm = jQuery('#nav-wrap'),
            navTop = navElm.offset().top;

        var conditional = false;
            
        jQuery(window).scroll(function() {
            if(navTop + navElm.outerHeight() > jQuery(window).height()) {
                conditional = (jQuery(window).scrollTop() > navElm.outerHeight());
            } else {
                conditional = true;
            }
            if(jQuery(window).scrollTop() > navTop && conditional) {
                navElm.stop();
                navElm.animate(
                    {
                        top: jQuery(window).scrollTop() - navTop
                    },
                    {
                        duration: 1000,
                        easing: 'easeOutQuint',
                        step: function() {
                            if(jQuery('#footer').offset().top <= navElm.offset().top + navElm.outerHeight()) {
                                navElm.stop();
                                navElm.animate({
                                    //the navElm height multiplier is arbitrary
                                    top: (jQuery('#footer').offset().top - 1.7*navElm.outerHeight()) + 'px'
                                }, 1000, 'easeOutQuint');
                            }
                        }
                    }
                );
            } else {
                navElm.stop();
                navElm.animate({
                    top: 0
                }, 1000, 'easeOutQuint');
            }
        });
        
    },

    /*a custom function to test if an element (needle) is in an array (haystack)*/
    inArray: function(needle, haystack) {
        for(var i = 0, l = haystack.length; i < l; i+=1) {
            if(needle === haystack[i]) {
                return true;
            }
        }
        return false;
    }
}

jQuery(document).ready(function() {
    boc.gas2010.init();
});