/*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 += '<div id="startagain"><a id="refresh-product-selector">Start Again</a></div>'

            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();
	
var ribbonText= new Array();
ribbonText['dial1'] = "Ban of virgin HCFCs to service RAC equipment. Make sure you're not breaking the law.";
ribbonText['dial2'] = "Restrictions on the use of recycled HCFC gas. Make sure you're compliant.";
ribbonText['dial3'] = "Rules for the use and supply of reclaimed HCFC gas. What are your options?";
ribbonText['dial4'] = "Evaluation of products to replace HCFCs using existing equipment by 2015. How will you maximise your uptime?";
ribbonText['dial5'] = "Evaluation of capital investment required to replace older equipment. How will you maximise energy efficiency and ensure value?";
ribbonText['dial6'] = 'Evaluation of capital investment using natural refrigerants. How will you safely manage and get the most out of new refrigerants?';
ribbonText['dial7'] = "Fourth generation refrigerants (HFOs). Do you need to prepare for what happens next?";

var ribbonColor = new Array();
ribbonColor['dial1'] = '#a92330';
ribbonColor['dial2'] = '#ee212c';
ribbonColor['dial3'] = '#f7941e';
ribbonColor['dial4'] = '#39b54a';
ribbonColor['dial5'] = '#8dc63f';
ribbonColor['dial6'] = '#b4d488';
ribbonColor['dial7'] = '#8ac3ea';




//START OF SCRIPT TO FREEZE THE PIPEWORK
	setInterval(function(start) {
		var curropacity = $('#opacity').val();
		if(curropacity < 1){
			var newopacity = parseFloat(curropacity)+0.01;
			$('#opacity').val(newopacity)
			var stylestr = 'opacity:'+newopacity+'; filter:alpha(opacity='+newopacity*100+')'
			$('#splashInner').attr('style', stylestr)
		}		
	}, 50);
	//END OF SCRIPT TO FREEZE THE PIPEWORK

//END OF SCRIPT TO FREEZE THE PIPEWORK






	
$('.dialOver').hover(function(){
$(this).addClass('active');
	var dialID = $(this).children('.dial').attr('id')
	$('#ribbonText').html(ribbonText[dialID]);
	rotateDial(true, dialID)
	//alert(ribbonText[$(this).attr('id')]);
	//alert(dialID);
	$("#ribbon").removeClass()
	$("#ribbon").addClass(dialID)
	if(typeof document.body.style.maxHeight === "undefined") {
	$("#ribbon").attr('style', 'background: '+ribbonColor[dialID]);
	}
	$("#ribbon").animate({ 
            width: "529px", 
            left: "430px"
        }, 200, 'linear', function() {
    $('#ribbonText').fadeIn();
  })
},
  function () {
    rotateDial(false, this)
	$("#ribbon").css('left', '1000px');
	$('#ribbonText').hide();
	$('.dialOver').removeClass('active');
	
  })


var test
function rotateDial(startstop, target) {
	if(startstop == true){
		test = setInterval(function() {
		var rot1 = $('#rot_'+target).val();
		var numLow = parseFloat(rot1)-5;
        var numHigh = parseFloat(rot1)+5;
        var adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;
        var numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
		var newrot1 = numRand;
		var rotstring = '-webkit-transform: rotate('+newrot1+'deg);	-moz-transform: rotate('+newrot1+'deg);	transform: rotate('+newrot1+'deg);'
		$('#'+target).attr('style', rotstring);
		$('#rot_'+target).val(newrot1)
	 }, 40)
	}
	if(startstop == false){
		clearInterval(test)
	}
}


/*if(typeof document.body.style.maxHeight === "undefined") {
        alert('ie6');
} else {
        alert('other');
}*/

$('#main table td a').hover(function(){
									// $(this).animate({ backgroundColor: "blue" }, 'slow');
$(this).parent('td').parent('tr').animate({ backgroundColor: "#eee" }, 500);
},function() {
    $(this).parent('td').parent('tr').animate({ backgroundColor: "#fff" }, 500);
});


/**** Track case study document clicks ****/
$('#main td.pdfimage a').click(function() {
	var pdfhref = $(this).attr('href');
		//if(typeof pageTracker !== 'undefined') {
			_gaq.push(['_trackEvent', 'Downloads', 'PDF', pdfhref]);
	//}
});


function goToByScroll(id){
     	$('html,body').animate({scrollTop: $('#anchor_legal').offset().top},'slow');
}
$('.vertical-navigation a').click(function() {
	//goToByScroll("legal");
	var theanchor = $(this).attr('href');
	$('html,body').animate({scrollTop: $(theanchor+"_anchor").offset().top},'slow');
	//alert(theanchor+"_anchor");
	return false;
});





});
