//======================== Generic load event function. Allows numerous function to be loaded on the same page without breaking anything 
function addLoadEvent(func) {
  var oldonload = window.onload;             
  if (typeof window.onload != 'function') {	   
    window.onload = func;					
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();									
    }
  }
}


//======================== W3C compliant Popup script
function popupLauncher()
{
  if( document && document.body && document.getElementById && document.getElementsByTagName ) //check to see if browser understands the methods
   {
     var alinks = document.getElementsByTagName('A'); // get all the links

     for( i=0; i < alinks.length; i++ ) // store then all one by one
     {
      if( alinks[i].rel == "external" ) // check each one to see if it has the rel attribute set to external
       {
         try
         {
          alinks[i].target = "_blank";  // if it does open new window
         }
         catch(e)
          {}
       }
     }
   }
}

//======================== search form (used to clear and reset all input fields)
function resetFields(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {// get all the element tags within a form
    var element = whichform.elements[i];
    if (element.type == "submit") continue;       // check if element is a submit button
    if (element.type == "radio") continue;
    if (element.type == "reset") continue;
    if (!element.defaultValue) continue;			// check if element doesn't have some default text and stop if it doesn't
    element.onfocus = function() {					// function for if element is in focus
    if (this.value == this.defaultValue) {		// check if the elements text is the default when page was loaded
      this.value = "";								// if it is delete it
     }
    }
    element.onblur = function() {					// function for if element this element no-longer in focus
      if (this.value == "") {						// check if the elements text is empty
        this.value = this.defaultValue;			// if the elements text is empty put the default value back
      }
    }
  }
}
//======================== Function used by the reset form function. Allows the reset form function to be used for all input fields, not matter how many there are
function prepareForms() {
  for (var i=0; i<document.forms.length; i++) {   // get all the forms
    var thisform = document.forms[i];
    resetFields(thisform);							// apply reset form function to all the forms
  }
}

//======================= Function to show a flash
function showFlash(url) {
	$.fancybox({
		//"orig"			: $(this),
		"padding"			: 0,
		"href"				: url,
		"overlayOpacity"	: 0.8,
		"hideOnContentClick": true,
		"transitionIn"		: "fade",
		"transitionOut"		: "fade",
		"type"				: "swf",
		"swf"				: {
			"wmode"				: "transparent",
			"allowfullscreen"	: "true"
		}

	});

}

//======================== Function to check is javascript is activated. If it is the class js-active is assigned to html tag
	var newclassname = 'js-active'; 				// define class 
	var ob = document.getElementsByTagName('HTML');// get the html tag 
	if (ob.length > 0){
	  ob = ob[0];									// check if there is already a class applied to html tag
	  if (ob.className == ''){
	      ob.className = newclassname;				// if there isn't then add class
	  } else {
	     ob.className += ' ' + newclassname;		// if there is a class already present add class js-active after it
	  }
	}
	
$(document).ready(function() {
	$("a.fancyFlash").fancybox({
		//"orig"			: $(this),
		"padding"			: 0,
		"overlayOpacity"	: 0.8,
		"hideOnContentClick": true,
		"transitionIn"		: "fade",
		"transitionOut"		: "fade",
		"type"				: "swf",
		"swf"				: {
			"wmode"				: "transparent",
			"allowfullscreen"	: "true"
		}

	});
});

// -------- main-nav prevent jump on hover
$(document).ready(function(){
	var navlinks = $("ul#main-nav li a"); 							// get all the links
		for (var i = 0; i < navlinks.length; i++) {
		var linkwidth = $(navlinks[i]).width(); 					// get there width
		var newlinkwidth = linkwidth + 10; 							// add 10 pixels to the width value
		 if($.browser.msie && parseInt($.browser.version) == 6) { 	// see if browser is IE6
			$(navlinks[i]).css("width", newlinkwidth);				// if IE6 add 10px to width attribute of link
		  }else{
			$(navlinks[i]).css("min-width", newlinkwidth); 		// if any other browser add 10px to min-width attribute of link
		  }
	}
});

// -------- create custom animation for sliders (used by the col-3 blocks slider function beneath)
   jQuery.fn.slideFadeToggle = function(speed, easing, callback) { //
   return this.animate({height: 'toggle', opacity: 'toggle'}, speed, easing, callback); 
   };


// -------- col-3 blocks sliders (adds and removes the class open which controls the how the arrows are displayed and executes the slideFadeToggle animation)
$(document).ready(function(){
	$("#col-3 .block h4, #col-2 .block h4").click(function () {  // get all the h4s and add click event listener
	$(this).next().slideFadeToggle('normal'); 					   // execute slideFadeToggle animation
	$(this).toggleClass("open"); 								   // reverse present state by adding or removing class open
	return false;												   // stop page jumping to the top when clicked
	});
});

// -------- check col-3 blocks (If JS is active function checks the current state of the nested content within the sliders when the page is first loaded and hides the required content)
$(document).ready(function(){ 											
	$("#col-3 .block h4, #col-2 .block h4").next().css("display","none"); // get all the next sibling of h4 and hide them
	var openH4 =  $("#col-3 h4.open");									   // get all these sibling if it has the class name open
		for (var i = 0; i < openH4.length; i++) {
		$(openH4[i]).next().css("display","block");					   // show all these siblings
		}
});

// -------- sector lable slider (function to show and hide the subnav main sectors)
$(document).ready(function(){
	var sLable = $("#col-1 .lable");														// get li tag with the class lable and cache it
	
    $(sLable).each(function(i) {
        var menuSubItems = $(this).parent().parent().children().not(":nth-child(1)");
        if ($(this).parent().hasClass("open")) {
            menuSubItems.show();
            $(this).toggle(
                function () {																	// toggle this off and on
                    menuSubItems.hide();
                    $(this).removeClass("open");
                    $(this).parent().removeClass("open");
                },
                function () {
                    menuSubItems.show();
                    $(this).addClass("opensoft");
                    $(this).parent().addClass("open");
                }
            );
        } else {
            menuSubItems.hide();
            $(this).toggle(																	
                function () {
                   menuSubItems.show();
                    $(this).addClass("opensoft");
                    $(this).parent().addClass("open");
                },
                function () {
                    menuSubItems.hide();
                    $(this).removeClass("open");
                    $(this).parent().removeClass("open");
                }
            );
        }
    });
});

//hide sectors which are not suppposed to be open
$(document).ready(function() {
    $("#col-1 ul.sector > li").each(function(i) {
        if(!$(this).hasClass("open")) {
            $(this).children("ul").hide();
        }
    });
});

// -------- progressive enhancement extra's to make ff2
$(document).ready(function(){ 
	if($.browser.mozilla && $.browser.version.substr(0,3)<="1.8") { 	// see if browser is FF3 or less
		$(".item a .arrow2").css("display","-moz-inline-box") // remove bottom border of submenu li
	}
});

// -------- progressive enhancement extra's to make IE6 behave like a real browser
$(document).ready(function(){ 
	if($.browser.msie && parseInt($.browser.version) == 6) { 	// see if browser is IE6
		$("#sub-nav ul ul li:last-child").css("border-bottom","none"); // remove bottom border of submenu li
		$(":submit").hover(
			  function () {
				$(this).addClass("hover"); 	// adds hover class on mouseOver
			  }, 
			  function () {
				$(this).removeClass("hover");	// removes hover class on mouseOut
			  }
		);
		$(":submit").click(
			  function () {
				$(this).addClass("click"); 	// adds click class on mouseDown
			  }
		);
		$("h5 + p").css("margin-top","-1em");
		$(".events #content-divider + .item").css("margin-top","2.3em");
	}
});

$(document).ready(function(){ 
	if($.browser.msie) { 	// see if browser is IE
		$("#sub-nav ul ul li:last-child").css("border-bottom","none"); // remove bottom border of submenu li
		$("#col-2 .block h4 a").focus(
			function(){
				 $(this).blur();
			}
		); // remove factive styling
	}
});

// -------- progressive enhancement forms
$(document).ready(function(){
	var inputFile = $("input.file_1");
	if (inputFile.length > 0) {
		var possibleLanguages = new Array("en", "de", "es", "it", "cn", "nl");
		var bodyClassName = document.getElementsByTagName("body")[0].className;
		var bodyClassNames = bodyClassName.split(" ");
		for(i=0;i<bodyClassNames.length;i++) {
			if (jQuery.inArray(bodyClassNames[i], possibleLanguages) !== -1) {
				var lang = bodyClassNames[i];
				break;
			}
		}
		var lang = (lang == "" || lang == undefined) ? "en" : lang;
		
		
		inputFile.filestyle({ 			
			image: "/img/file-input-"+lang+".png", // path needs to be relative to the host html document
			imageheight : 23,
			imagewidth : 108,
			width : 250
		});
		$("input.file_1 + div").addClass("file-submit");
	}
});

// -------- print this page
$(document).ready(function(){
    $("#print-this-page").click(function (e) {
        window.print();
    });

	$("a.print").click(function(e){
	 	window.print();
	});
	
    // ------ removes the right border from the last li element in the content footer
    $('div#content-footer ul:first-child li:last-child').css('border-right', 'none');
});

// -------- value chain mouseOut solution to red links
$(document).ready(function(){ 
	var eChainLinks = $("#valuechain ul .subnav li a");
	if (eChainLinks) {
		$(eChainLinks).mouseout(
			function(){
			 $(this).css("color","#163b68");
			 $(this).find("span").css("background-position","0 0px");
		}).mouseover(
			function(){
			 $(this).css("color","#163b68");
			 $(this).find("span").css("background-position","0 -63px");
		}).mousedown(
			function(){
			 $(this).css("color","#f92b31");
			 $(this).find("span").css("background-position","0 -84px");
		}).mouseup(
			function(){
			 $(this).css("color","#163b68");
			 $(this).find("span").css("background-position","0 -63px");
		});
	}
});


//======================== IE6 antiflicker (stops the ie flicker on background images
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

addLoadEvent(prepareForms);
addLoadEvent(popupLauncher);
