/* Global Variables */
var tablesInited = false;

//NOTE: this initCalls collection should not be added to. Use global.js.
var initCalls = new Array();
//initCalls.push(" NavigationEvents()");
initCalls.push(" ColumnH6Fix()");
initCalls.push(" IEPopupMarginFix()");
initCalls.push(" FlashInit()");
initCalls.push(" InitFeatures()");
initCalls.push(" tableSpacingFix()");
initCalls.push(" collapseExpandableList()"); //ecom-1955
//Note: this approach should not be used rather use the jQuery .ready event to add onload events - idurham 18/11/09 
function runInitFunctions() { // perform onLoad actions
	for(var i=0, len=initCalls.length; i<len; i++ ) {
		eval(initCalls [i]);
	}
};
$j(document).ready(function () {
	runInitFunctions();
	//jQuery(".scrollableTable").scrollableTable();
});
function tableSpacingFix(){
	var tables = $j("table:not([cellspacing])");
	for(var i=0, len=tables.length;i<len;i++){
		tables[i].cellSpacing=0;
	}
}
//TODO: Review what these functions achive and see if the problems that they are intended to fix
//      can't be fixed in CSS, or at very least refactored to be more efficient
function InitFeatures() {
	var divs = document.getElementsByTagName("div");
	if (divs) {
		for (var i=0, len=divs.length;i<len;i++) {
			if (divs[i].className.indexOf("feature") > -1) {
				FixFeature(divs[i]);
			}
		}
	}
}
//TODO: Review what these functions achieve and see if the problems that they are intended to fix
//      can't be fixed in CSS, or at very least refactored to be more efficient
function FixFeature(feature) {
	var imgs = feature.getElementsByTagName("img");
	var done = false;
	for (var i=0, len=imgs.length;i<len;i++) {
		if (imgs[i].className == "offscreen") {
			var div = feature.getElementsByTagName("div")[1].getElementsByTagName("div")[0];
			div.style.marginLeft = (imgs[i].width) + "px";
			imgs[i].style.display = "none";
			feature.style.position = "static";
			done = true;
		}
	}
	if (!done) {
		feature.style.position = "static";
	}
}
//TODO: Review what these functions achieve and see if the problems that they are intended to fix
//      can't be fixed in CSS, or at very least refactored to be more efficient
function IEPopupMarginFix() {
	var innerPop = document.getElementById("innerPop");
	if (innerPop && document.all) {
		innerPop.style.width = (document.getElementsByTagName("body")[0].offsetWidth - 50) + "px";
	}
}
//TODO: Review what these functions achieve and see if the problems that they are intended to fix
//      can't be fixed in CSS, or at very least refactored to be more efficient
function ColumnH6Fix() {
	var objs = document.getElementsByTagName('div');
	for (var j=0, len = objs.length;j<len;j++) {
		var obj = objs[j];
		var s = obj.className;
		if (s.indexOf('columnType') > -1) {
			if (obj.childNodes) {
				var child;
				for (var i=0;i<obj.childNodes.length;i++) {
					s = "" + obj.childNodes[i].tagName;
					if (s != 'undefined') {
						child = obj.childNodes[i];
						break;
					}
				}
				if (child) {
					s = child.className + "";
					if (child.tagName.toLowerCase() == "h6") {
						if (s.indexOf("firstHeading") == -1) {
							child.className = s + " firstHeading";
						}
					} else if (s.indexOf("h6") != -1) {
						if (s.indexOf("firstHeading") == -1) {
							child.className = s + " firstHeading";
						}
					}
				}
			}
		}
	}
}
//TODO: The tov and tou functions should be replaced by css classes that perform the same action using the
//      :hover psudo class. This requires many pages to be changed but this could be done using a staged 
//      approach doing a page or 2 at a time to reduce the risk.
function tov(obj) {
	obj.style.top = '-20px';
}
function tou(obj) {
	obj.style.top = '0px';
}
//TODO: Remove this function and all references to it and replace with the .parent(tagName) function from jQuery
function getParentByTagName(el, tagName) {
	if (el.tagName.toLowerCase() == tagName) {
		return el;
	} else if (el.parentNode) {
		while (el.parentNode) {
			var tag = el.tagName.toLowerCase();
			if (tag == tagName) {
				break;
			} else {
				el = el.parentNode;
			}
		}
	}
	return el;
}
function displayRememberMeDisclaimer() {
    var options = {
        type:"ajax", 
        url:"/home/overlay-disclaimer.jhtml", 
        modal: true,
        width: 800,
        height: 571 //This height is needed for IE6
        };
    $j.displayOverlay(options);
}
function acceptRememberMeDisclaimer(event) {
    event.preventDefault();
    var url = "/home/ajax/accept_guest_disclaimer.ajax";
    var button = $j(this);
    button.attr("disabled", true);
    button.parent().addClass("disabled");
    $j.getJSON(url, null, function(response){
            if(response.success) {
                $j.removeOverlay();
            } else {
                alert("Sorry an error has occurred with your request");
                button.attr("disabled", false);
                button.parent().removeClass("disabled");
            }
        });
}
function openSitemap(el) {
	NewWindow(el.href, "sitemap", 250, 405);
}
function NewWindow(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	var winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl;
	if(scroll == "no"){
		winprops += ', scrollbars=no';
	} else {
		winprops += ', scrollbars=yes';
	}
	if (myname == '') {
		myname = '_blank';
	}
	var win = window.open(mypage, myname, winprops);
	if(win){
		if (parseInt(navigator.appVersion) >= 4) { 
			win.window.focus();
		}
	}
}
function showLayer(id) {
	if(document.getElementById("layer1")){
		var layers = new Array("");
		var layer = "layer1";
		var count = 1;
		var vert = false;
		if (document.getElementById(layer).className.indexOf("vertTabbed") > -1) {
			vert = true;
		}
		while (document.getElementById(layer)) {
			layers.push(layer);
			count++;
			layer = "layer" + count;
		}
		for (var i=1, len=layers.length; i<len; i++) {
			var obj = document.getElementById(layers[i]);
			if (layers.length > 2) {
				var tabs = obj.getElementsByTagName("div")[0].getElementsByTagName("img");
				for (var j=0, size=tabs.length; j<size; j++) {
					if (j+1 == i) {
						if (vert) {
							tabs[j].parentNode.className = "sel";
						} else {
							tabs[j].className = "sel";
						}
					}
				}
			}
			obj.style.display = "none";
		}
		obj = document.getElementById(layers[id]);
		obj.style.display = "block";
		if (vert) {
			var divs = obj.getElementsByTagName("div");
			if (divs[0].offsetHeight == 0) {
				divs[0].style.height = divs[0].getElementsByTagName("img").length * 42 + "px";
			}
			if (divs[1].offsetHeight > divs[0].offsetHeight) {
				divs[0].style.height = divs[1].offsetHeight + "px";
			} else {
				divs[1].style.height = divs[0].offsetHeight + "px";
			}
		}
	}
};
function FlashInit() {
	var minFlashVersion = 6;
	var o=["object"], j, k;
	for(j=0, len=o.length; j<len; j++){
		var e=document.getElementsByTagName(o[j]);
		for(k=0, size=e.length; k<size; k++){
			var ele = e[k];
			if(ele.outerHTML){
				if(!ele.getAttribute("data")||ele.getAttribute("data")==""){
					ele.outerHTML=ele.outerHTML;
				} else {
					var tempStr = ele.getAttribute("data");
					ele.removeAttribute("data");
					ele.outerHTML=ele.outerHTML;
					ele.setAttribute("data", tempStr);
				}
			}
		}
	}
	var htmlContent = document.getElementById("htmlContent");
	var flashContent = document.getElementById("flashContent");
	if (htmlContent && flashContent) {
		if (flashinstalled == 2 && flashversion >= minFlashVersion) {
			flashContent.style.display = "block";
		} else {
			htmlContent.style.display = "block";
		}
	} else {
		if (htmlContent){
			htmlContent.style.display = "block";
		}
	}
}
function EventApplication() {
	var dl = document.getElementsByTagName("dl");
	if (dl.length > 0) {
		var event = document.getElementById("headingColumn").getElementsByTagName("img")[0].getAttribute("alt");
		var html = "<dl><dt>Event</dt><dd>" + event + "</dd>";
		var dlChild = dl[0].childNodes;
		var len = dlChild.length;
		var dtCount = 0;
		for (var i=0;i<len;i++) {
			var tagName = dlChild[i].tagName;
			if (tagName) {
				tagName = tagName.toLowerCase();
				if (tagName == "dt") {
					dtCount++;
					if (dtCount > 2) {
                        break;
                    }
					html += "<dt>" + dlChild[i].innerHTML + "</dt>";
				} else if (tagName == "dd") {
					html += "<dd>" + dlChild[i].innerHTML + "</dd>";
				}
			}
		}
		html += "</dl>";
		document.location.href = "/press/events/registration.jhtml?event=" + event + "&top=" + html;
	}
}
function initScrollableTable(){
	var divs = $$(".scrollableTable");
	for(var i=0, len=divs.length; i<len; i++){
        var tableId = "scrollingHeader" + (i+1);
		var scrollableTable = divs[i];
		var scrollableDiv = scrollableTable.down("div");
		var table = scrollableDiv.down("table");
		var caption = table.down("caption");
		var captionContent = "";
		if(caption) {
			captionContent = "<caption>" + caption.innerHTML + "</caption>";
		}
        var colGroup = table.down("colgroup");
		var colGroupContent = "";
		if(colGroup) {
			colGroupContent = "<colgroup>" + colGroup.innerHTML + "</colgroup>";
		}
		var thead = table.down("thead");
        var theadContent = "<thead>" + thead.innerHTML + "</thead>";
		scrollableTable.down().innerHTML = "<table>" + captionContent + colGroupContent + theadContent + "</table>";
		var headerTable = scrollableTable.down("table");
		headerTable.setAttribute("cellpadding",0);
		headerTable.setAttribute("cellspacing",0);
        headerTable.setAttribute("id",tableId);
		if(table.getAttribute("className")) {
			headerTable.setAttribute("className",table.getAttribute("className"));
		} else {
			headerTable.setAttribute("class",table.getAttribute("class"));
		}
		headerTable.style.width = table.getWidth() + "px";
		var trs = thead.getElementsByTagName("tr");
		var ths = trs[trs.length-1].getElementsByTagName("th");
		var headerTrs = headerTable.getElementsByTagName("tr");
		var headerThs = headerTrs[headerTrs.length-1].getElementsByTagName("th");
		var offset = "-" + headerThs[0].offsetHeight + "px";

		table.parentNode.style.zIndex = "10";
		table.style.zIndex = "10";
		headerTable.parentNode.style.zIndex = "20";
		headerTable.style.zIndex = "20";
		headerTable.parentNode.style.position = "absolute";
		for(var j=0, length=headerThs.length; j<length; j++) {
            var cell = Element.extend(ths[j]);
            //Need to minus the amount of padding that has been applied ie reduce width by 6
            var newWidth = cell.getWidth() - 6;
            var newHeaderCell = Element.extend(headerThs[j]);
			newHeaderCell.setStyle({width: newWidth + "px"});
		}
	}
	tablesInited = true;
}
function scrollIt(){
	if(!tablesInited) {
		return;
	}
	var pageTop = 0;
	if(document.documentElement && document.documentElement.scrollTop){
		pageTop = document.documentElement.scrollTop;
	} else {
		if (document.all){
			pageTop=document.body.scrollTop;
		} else if (document.getElementById){
			pageTop=window.pageYOffset;
		}
	}
	var divs = $j(".scrollableTable");
	divs.each(function( iter ) {
		var container = $j(this);
		var tableTop = container.offset().top;
		var headerTableContainer = container.children("span");
		if(tableTop < pageTop){
			headerTableContainer.css("top", pageTop + "px");
		} else{
			headerTableContainer.css("top", "");
		}
		var footer = container.children(".scrollableFooter").eq(0);
		if(footer.length > 0) {
			var windowHeight = $j(window).height();
			footer.css("top", "");
			var headerTableHeight = headerTableContainer.height();
			var headerTableTop = headerTableContainer.offset().top;
			var footerHeight = footer.height();
			var footerTop = footer.offset().top;
			if( footerTop > ( pageTop + windowHeight - footerHeight) && 
			    ( pageTop + windowHeight - footerHeight) > ( headerTableTop + headerTableHeight)) 
			{
				var topCss = (pageTop + windowHeight - footerHeight - footerTop);
				footer.css("top", topCss + "px");
			}
		}
	});
}
function changeWTTags() {
    var options = $$(".container input[type='radio']");
	if(options[0].checked) {
		dcsMultiTrack('WT.seg_2', 'investor');
	} else {
		dcsMultiTrack('WT.seg_2', 'intermediary');
	}
    WT_pauseSubmit(options[0]);
}
function changeWTTagsCa() {
    var investor = $("investor");
	if(investor.checked) {
		dcsMultiTrack('WT.seg_2', 'investor');
	} else {
		dcsMultiTrack('WT.seg_2', 'intermediary');
	}
    WT_pauseSubmit(investor);
}
function WT_pauseSubmit( element ) {
    window.setTimeout("WT_sendTheForm('"+element.form.name+"')", 1000);
}
function WT_sendTheForm(formName) {
    var regex = /^#.*/;
    if(!formName.match(regex)) { //If form id doesn't have the hash at front then add it
        formName = "#" + formName;
    }
	$j(formName).submit();
}
/**
 *  Cross browser method for adding a single option to an existing select element
 *  
 *  @param {Object}  selectElement - reference to the select DOM element
 *  @param {String}  option        - Text that will display as an option in the selectbox
 *  @param {String}  value         - Value that will be assigned to the option. 
 *                                   [Optional] - Defaults to same as option if not supplied
 *  @param {Boolean} selected      - Set to 'true' if want new option to be the default selected option
 *                                   [Optional] - Defaults to 'false' if not supplied
 */
function eCOM_Util_addNewSelectOption(selectElement, option, value, selected){
    value = value || option; //if no value passed in then default the value to be the same as the option
    selected = selected || false;
    var newOption = null;
    if(selectElement) {
        var options = selectElement.options;
        var len = options.length;
        newOption = new Option(option, value, selected, false);
        options[len] = newOption;
    }
    return newOption;
}
//ecom-1955
function collapseExpandableList(){
    if($j(".expand-heading").length > 0) {
    	var materialColection = new eCOM_collapsibleList("expand-heading");
    	materialColection.collapseAll();
    }
}


