/* Function to addEventListener to onload
 * @param func - a function which should be executed once the page has loaded
 * http://simon.incutio.com/archive/2004/05/26/addLoadEvent
 * it will work even if something has previously been assigned to window.onload
 * without using addLoadEvent itself. 
 */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

/*
 * Function to clear a text field
 * @param thefield
 *     the field to clear
 */
function cleartext(thefield) {
	if (thefield.defaultValue == thefield.value) {
		thefield.value = "";
	}
}

function GetAnchors() {
  if (document.getElementById) {
    var elements = new Array('a', 'area');
    for (var j=0; j < elements.length; j++) {
      var x = document.getElementsByTagName(elements[j]);
      for (var i=0;i<x.length;i++) {
        if (x[i].className.indexOf('newWindow') != -1) {
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].setAttribute("title", "New Window");
        } else if (x[i].className.indexOf('popup') != -1) {
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].setAttribute("title", "Pop-up Window");
        } else if (x[i].className.indexOf('download') != -1) {
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].setAttribute("title", "Download");
        } else if (x[i].className.indexOf('downReportRR') != -1) {
          x[i].setAttribute("title", "Download Report");
        } else if (x[i].className.indexOf('html') != -1) {
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].setAttribute("title", "Download");
        } else if (x[i].className.indexOf('podcast') != -1) {
          x[i].setAttribute("title", "Podcast");
        } else if (x[i].className.indexOf('rss') != -1) {
          x[i].setAttribute("title", "RSS Feed");
        } else if (x[i].className.indexOf('external') != -1) {
          x[i].setAttribute("title", "Link to External Site");
        } else if (x[i].className.indexOf('reqPrintRR') != -1) {
          x[i].setAttribute("title", "Request Printed Copy");
        } else if (x[i].className.indexOf('reqPrint') != -1) {
          x[i].setAttribute("title", "Request Printed Copy");
        } else if (x[i].className.indexOf('wmv') != -1) {
					//for Ivestor section only
          x[i].setAttribute("title", "Listen to the webcast in Windows Media Player");
        } else if (x[i].className.indexOf('realAudio') != -1) {
					//for Ivestor section only
          x[i].setAttribute("title", "Listen to the webcast in Real Audio");
        } else if (isAssetDoc(x[i])) { // make sure all file extensions you wish to set custom title for are in isAssetDoc() below
          var fileExt = getFileExt(x[i]);
          x[i].onkeypress = openNewWindow;
          x[i].onclick = openNewWindow;
          x[i].className=fileExt
         switch(fileExt) {
          case "doc":
            x[i].setAttribute("title", "Word document");
            break 
          case "ppt":
            x[i].setAttribute("title", "PowerPoint File");
            break            
           case "xls":
            x[i].setAttribute("title", "Excel File");
            break 
           default:
            x[i].setAttribute("title", fileExt.toUpperCase()+" file");
          }
        }
      }
    }
  }
}

function openNewWindow(e) {
    if (e == undefined || e.keyCode != 9) {
        if (isAssetDoc(this)) {
            var url = this.href;
            var parentHost = window.location.protocol + "//" + window.location.host;
            if (url.substring(0, parentHost.length) == parentHost) {
                url = url.substr(parentHost.length);
            } else if (url.substring(0, 23) == "http://www.eglobalatm.com/") {
                url = url.substr(22);
            }
        }
        var features = '';
        var start;
        var end;
        var width;
        var height;
        var thisurl = this.href ? this.href : "";
        width = parseInt(getValueFromClass(this, 'w')) > 0 ? getValueFromClass(this, 'w') : '';
        height = parseInt(getValueFromClass(this, 'h')) > 0 ? getValueFromClass(this, 'h') : '';
        if (height.length > 0 || width.length > 0) {
            features += height.length > 0 ? 'height=' + height + ',' : '';
            features += width.length > 0 ? 'width=' + width + ',' : '';
        }
        features += getFeatures(this);

        if (features.length > 0) {
            if (features.substr(features.length - 1, 1) == ",")
                features = features.substr(0, features.length - 1);
            window.open(this.href, '_new', features);
        } else {
            window.open(this.href);
        }
        return false;
    }
    return true;
}

function getValueFromClass(obj, attrib) {
  if (obj.className.indexOf(" "+attrib) != -1) {
    start = obj.className.indexOf(" "+attrib) + 1
    end = obj.className.indexOf(" ", start);
    end = (end == -1) ? obj.className.length - start : end - start;
    var aLength = attrib.length;
    return obj.className.substr(start+aLength, end-aLength);
  } else {
    return "";
  }
}

function isAssetDoc(obj) {
  var types = new Array("pdf", "doc", "xls", "ppt", "cvxn");
  var fileExt = getFileExt(obj);
  
  for(i=0; i<types.length;i++) {
    if (types[i] == fileExt) {
      return true;
    }
  }
  return false;
}

function getFileExt(obj) {
    var url = obj.href;
    var ext = url.substr(url.lastIndexOf(".") + 1);

    if (ext == "cvxn") {
        ext = url.substr(url.lastIndexOf(".") - 3, 3);
    }

    return ext;
}

function getFeatures(obj) {
  var features = "";
  if (obj.className.indexOf(" scroll") != -1) {
    features += "scrollbars=yes,";
  }
  return features;
}

// grab root url for use in email page form
var url = location.href;
var urlArr = url.split('#',1);
var rooturl = urlArr[0];
	//alert(rooturl);

/*
 * rClearText
 * Clears an input box if text is equal to default text onfocus. Adds default back on blur if input box is empty
 */
function rClearText(el) {
	this.initialize(el);
}
rClearText.prototype = {
	initialize: function(el) {
		$(el).focus(function() {
			if (el[0].value == el[0].defaultValue) { // Text hasn't been changed yet
				el[0].value = '';
			}
		});
		$(el).blur(function() {
			if (el[0].value == '') { // Text hasn't been changed yet
				el[0].value = el[0].defaultValue;
			}
		});
	}
}
function rClearTextFocus(el) {
	if (el.value == el.defaultValue) { // Text hasn't been changed yet
		el.value = '';
	}
}

function rClearTextBlur(el) {
	if (el.value == '') { // Text hasn't been changed yet
		el.value = el.defaultValue;
	}
}
 
/*
 * rDropDown
 * Adds class of 'hover' to LI onmouseover. Removes class onmouseout. Adds iFrame fix for IE
 */
function rDropDown() {
	this.initialize();
}
rDropDown.prototype = {
	open: false,
	timeout: false,
	openLi: null,
	initialize: function() {
	    var userAgent = navigator.userAgent.toLowerCase()
        if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1)
            $("#TopNav > ul").addClass('macFF');
            
		var lis = $("#TopNav > ul > li");
		for (var i=0; i<lis.length; i++) {
			$(lis[i]).bind('mouseover', {parentThis: this, li:lis[i]}, function(params) {
				params.data.parentThis.show(params.data.li);
			});
			$(lis[i]).bind('mouseout', {parentThis: this, li:lis[i]}, function(params) {
				params.data2 = params.data;
				params.data.parentThis.timeout = setTimeout(function() {
					params.data = params.data2;
					params.data.parentThis.hide(params.data.li);
				}, 1);
			});
			$(lis[i]).bind('click', {parentThis: this, li:lis[i]}, function(params) {
			    $(params.data.li).find("a").blur();
			    params.data.parentThis.hide(params.data.li);
			});
		}
	},
	show: function(li) {
		if (this.openLi && this.openLi != li) {
			this.hide(this.openLi);
		}
		if(this.timeout){
			clearTimeout(this.timeout);
			this.timeout = false;
		}
		if(this.open){
			return;
		}
		if ($(li).hasClass('hasSub')) {
			$(li).addClass('hoverSub');
		}
		else {
			$(li).addClass('hover');
		}
		this.openLi = li;
		this.open = true;
		this.iframeFix(li);
	},
	hide: function(li) {
		if(!this.open){
			return;
		}
		$(li).removeClass('hover');
		$(li).removeClass('hoverSub');
		this.open = false;
		if (this.iframe) {
			this.iframe.style.display = "none";
		}
	},
	iframeFix: function(li) {
		if(!document.all) {
			//return;
		}
		
		var subnav = $('div.subnav', li)[0];
		if (subnav) {
			if (!this.iframe) {
				this.iframe = document.createElement('iframe');
				this.iframe.style.position = 'absolute';
				this.iframe.frameBorder = 0;
				this.iframe.style.filter = 'alpha(opacity=0)';
				this.iframe.style.zIndex = -1;
				document.body.appendChild(this.iframe);
			}
			this.iframe.style.display = "block";
			this.iframe.style.top = $(subnav).offset().top + 'px';
			this.iframe.style.left = $(subnav).offset().left + 'px';
			this.iframe.style.width = $(subnav).width() + 'px';
			this.iframe.style.height = $(subnav).height() + 'px';
		}
	}
}

/*
 * ajaxForm
 * Handles AJAX for form submission. Returns a taconite XML string.
 */
function ajaxForm(frm) {
	$.ajax({
		type: "POST",
		url: frm.action,
		data: $(frm).serialize()
	});
}

/*
 * validateForm
 * Validates form for thickboxes
 */
function validateForm(frm) {
	var errors = new Array();
	
	for (var i=0; i<frm.elements.length; i++) {
		$(frm.elements[i].parentNode.parentNode).removeClass('error');
		if ($(frm.elements[i]).is('.req')) {
			// Not empty
			if(frm.elements[i].value.match(/^\s*$/)) {
				errors.push(frm.elements[i].name + ' cannot be empty');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
			// publication not chosen on printed copy request form	
			if(frm.elements[i].value.match("Select From List")) {
				errors.push(frm.elements[i].name + ' cannot be "Select From List"');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
			// country not chosen on printed copy request form	
			if(frm.elements[i].value.match("Select a Country")) {
				errors.push(frm.elements[i].name + ' cannot be "Select a Country"');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
		}
		else if ($(frm.elements[i]).is('.email')) {
			// Valid email
			if(frm.elements[i].value.match(/^\s*$/)) {
				// Not empty
				errors.push(frm.elements[i].name + ' cannot be empty');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
			else if(!frm.elements[i].value.match(/^[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)*\@[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)+$/)) {
				// Valid email
				errors.push(frm.elements[i].name + ' is not a valid email');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
		}
		else if ($(frm.elements[i]).is('.email2')) {
			// email2 matches email
			if(frm.elements[i].value != $('.email', frm)[0].value) {
				errors.push('Email addresses do not match');
				$(frm.elements[i].parentNode.parentNode).addClass('error');
			}
		}
	}
	if (errors.length > 0) {
		var errorMsg = '<h3>Important Message: Before you can continue there are a few errors to correct ...</h3>';
		errorMsg += '<ul>';
		for (var i=0; i<errors.length; i++) {
			errorMsg += '<li>'+ errors[i] + '</li>';
		}
		errorMsg += '</ul>';
		$('.errorBox', frm)[0].innerHTML = errorMsg;
		$('.errorBox', frm).show();
		
	}
	else {
		ajaxForm(frm);
	}
}

//hack thickbox to have a callback
tb_show2 = tb_show;
window.tb_show = function() {
	var a = arguments;
	tb_show2.apply(this, a);
	//setTimeout('tb_callback()', 100);
	tb_callback();
}
//The thickbox callback function
function tb_callback() {
	// Add wrappers
	var TB_window = $('#TB_window')[0];
	var container = document.createElement('div');
	container.id = "TB_wrapper";
	var imgContainer = document.createElement('div');
	imgContainer.id = "TB_popupImg";
	container.appendChild(imgContainer);
	var contentPad = document.createElement('div');
	contentPad.id = "TB_contentPad";
	container.appendChild(contentPad);
	var content = document.createElement('div');
	content.id = "TB_content";
	contentPad.appendChild(content);
	while(TB_window.childNodes.length > 0) {
		content.appendChild(TB_window.childNodes[0]);
	}
	TB_window.appendChild(container);
	
	// Remove text nodes from TB_closeAjaxWindow
	var TB_closeAjaxWindow = $('#TB_closeAjaxWindow')[0];
	for (var i=0; i<TB_closeAjaxWindow.childNodes.length; i++) {
		if (TB_closeAjaxWindow.childNodes[i].nodeType == '3') {
			TB_closeAjaxWindow.removeChild(TB_closeAjaxWindow.childNodes[i]);
		}
	}
}

// Hack thickbox to have a callback for tb_position (called when contents are ready to show)
tb_position2 = tb_position;
window.tb_position = function() {
    if ($("#TB_closeWindowButton").length > 0) {
        $("#TB_closeWindowButton").unbind("click").click(function() {
            tb_remove();
            return (false);
        });
    }
	var a = arguments;
	tb_position2.apply(this, a);
	setTimeout(tb_restrictTabOrder, 100);
	// tb_restrictTabOrder();
}

// Hack thickbox to have a callback for tb_showIframe (called when iframe contents are ready to show)
tb_showIframe2 = tb_showIframe;
window.tb_showIframe = function() {
	var a = arguments;
	tb_showIframe2.apply(this, a);
	setTimeout(tb_restrictTabOrder, 100);
	// tb_restrictTabOrder();
}

// Hack thickbox to have a callback for tb_remove
tb_remove2 = tb_remove;
window.tb_remove = function() {
	var a = arguments;
	tb_remove2.apply(this, a);
	tb_unrestrictTabOrder();
}

var tbTabEls = [];
var tbTabLock = false; // Prevents overlapping calls while tab key is held down
function tb_restrictTabOrder() {
	// Find elements within TB_content that should be tabbable
	tbTabEls = $("#TB_content").find("a:visible,:input:enabled:visible");
	
	// Prevent tab block from within plug-ins, since this takes focus away from the SWF immediately.
	$("#TB_content").find("object,embed").keydown(function(e) {
	    e.stopPropagation();
        e.preventDefault();
	});

	// Handle keydown event
	$(document).unbind("keydown").keydown(function(e) {
		switch(e.keyCode) {
			case 9: // Tab
				if (!tbTabLock) {
					tbTabLock = true;
					currentTabIndex = tbTabEls.index(e.target);
					if (currentTabIndex == -1) {
					    currentTabIndex = 0;
					}
					tbTabIndex = (currentTabIndex + (e.shiftKey ? -1 : 1) + tbTabEls.length) % tbTabEls.length;
					setTimeout(function(){
						tbTabEls[tbTabIndex].focus();
						tbTabLock = false
					}, 10);
				}
				return false;
			case 32: // Space (block space on anchor tag to prevent scrolling in BG)
				if ($(e.target).attr("href")) {
					return false;
				}
		}
		return true;
	});

	// Disable keypress for tab to prevent double-firing when tab key is held down
	$(document).unbind("keypress").keypress(function(e) {
		if (e.keyCode == 9) {
			return false;
		}
	});
	
    if (tbTabEls.length > 0) {
        setTimeout(function() {
	        tbTabEls[tbTabEls.length == 1 ? 0 : 1].focus();
	    },
	    500);
	}
}

function tb_unrestrictTabOrder() {
    $(document).unbind("keydown");
    $(document).unbind("keypress");
}

/*
 * onLoad functions
 * Initializes our functions on page load
 */
$(document).ready(function() {
    new rClearText($("#Search input"));
    new rDropDown();
    // add .last class to last LI item within Breadcrumb
    $("div#Breadcrumb ul li:last-child").addClass("last");

    // add enter key event to search text box in search container
    $("#Search input[@id$=search]").keydown(function(e) {
        if (e.keyCode == 10 || e.keyCode == 13) {
            $("#Search input:image").click();
            return false;
        }
    });

    // add enter key event to search text box in content container
    $("#Content input[@id$=SearchTerms]").keydown(function(e) {
        if (e.keyCode == 10 || e.keyCode == 13) {
            $("#Content input[@id$=Search]").click();
            return false;
        }
    });


    // send search queries directly to search page
    $("#Search input:image").click(function() {
        var searchVal = $("#Search input[@id$=search]").val();
        var appPath = (location.pathname.indexOf("/ChevronWebSite") >= 0) ? "/ChevronWebSite" : window.location.protocol + "//" + window.location.host;
        searchVal = escape(searchVal);
        window.location.href = appPath + "/search/?k=" + searchVal + "&text=" + searchVal.toLowerCase() + "&Header=FromHeader&ct=All%20Types";
        return false;
    }).keypress(function(e) {
        if (e.keyCode != 9) {
            $(this).click();
        }
    });

    // global search page functionality
    if ($("#Content select[@id$=ContentType], #Content select[@id$=Month], #Content select[@id$=Year]").length >= 5) {
        // disable month/year
        $("#Content select[@id$=ContentType]").bind("change", function() {
            if (this.selectedIndex != 0) {
                $("#Content fieldset>div:eq(2), #Content fieldset>div:eq(3)").show();
            } else {
                $("#Content fieldset>div:eq(2), #Content fieldset>div:eq(3)").hide();
            }
        }).trigger("change");
    }
});

// Popup window
function openPopup( e ) {
    document.getElementById( e ).style.visibility      = 'visible';
};

function closePopup( e ) {
    document.getElementById( e ).style.visibility      = 'hidden';
};

addLoadEvent(GetAnchors);

//**************************************************************************************************************//
// CR homepage banner behavior.

function dynamicContentHeader(contentDisplayItems, navItems, thumbnailSelection) {
	this.contentItems = [];
	this.currentContent = null;
	this.cycleIntervalId;
	this.timeoutIntervalId;
	this.mouseActivityTimer = 0;
	this.cycleDelay = 5;
	this.cycleRestartTimeout = 60;

	for (var i=0; i < contentDisplayItems.length; i++) {
		this.contentItems.push(new dynamicHeaderItem(contentDisplayItems[i], navItems[i], i, this));
	}

	contentDisplayItems.css("z-index", 1);
	navItems.css("z-index", 7);

	this.thumbnailSelection = thumbnailSelection;
	thumbnailSelection.css("z-index", 8).remove();

	var engine = this;
	this.scopedResetMouseActivityTimer = function() { engine.resetMouseActivityTimer() };
	this.scopedNextContentItem = function() { engine.nextContentItem() };
	this.scopedCheckMouseActivityTimer = function() { engine.checkMouseActivityTimer() };

	this.startCycle();
	this.showContentAt(0);
}

dynamicContentHeader.prototype = {

	nextContentItem: function() {
		this.showContentAt((this.currentContent.index + 1) % this.contentItems.length);
	},

	showContentAt: function(i) {
		this.showContent(this.contentItems[i]);
	},

	showContent: function(contentItem, instant) {
		var previousContent = this.currentContent;
		this.currentContent = contentItem;
		contentItem.select(previousContent, instant);
		$(this.currentContent.navItem).prepend(this.thumbnailSelection);
	},

	resetMouseActivityTimer: function() {
		this.mouseActivityTimer = 0;
	},
	
	checkMouseActivityTimer: function() {
		this.mouseActivityTimer++;
		if (this.mouseActivityTimer == this.cycleRestartTimeout) {
			this.startCycle();
		}
	},

	startCycle: function(startNow) {
		$(document).unbind("mousemove", this.scopedResetMouseActivityTimer);
		clearInterval(this.timeoutIntervalId);
		clearInterval(this.cycleIntervalId);
		this.cycleIntervalId = setInterval( this.scopedNextContentItem, 1000 * this.cycleDelay);
		if (startNow == true) {
			this.nextContentItem();
		}
	},
	
	stopCycle: function() {
		this.mouseActivityTimer = 0;
		$(document).bind("mousemove", this.scopedResetMouseActivityTimer);
		clearInterval(this.cycleIntervalId);
		clearInterval(this.timeoutIntervalId);
		this.timeoutIntervalId = setInterval( this.scopedCheckMouseActivityTimer, 1000);
	}
}

///////////////////////////////////////////////////////////////////////////
//

function dynamicHeaderItem(contentItem, navItem, index, engine) {
	this.index = index;
	this.navItem = navItem;
	this.contentItem = contentItem;
	this.engine = engine;
	var this2 = this;
	$(this.navItem).children("a").attr("href", "#");
	$(this.navItem).click(function(e){
		this2.onItemClick();
		e.stopPropagation();
        e.preventDefault();
	});
}

dynamicHeaderItem.prototype = {
	select: function(previousContent, instant) {
		if (previousContent) {
			previousContent.deselect();
		}

		var duration = instant ? 10 : 1000;
		$(this.navItem).filter(".navItemUnselected").removeClass("navItemUnselected");
		$(this.navItem).addClass("navItemSelected");
		$(this.contentItem).css("z-index", 9).fadeIn(duration, function() {
			if (previousContent && previousContent.contentItem != this) {
				$(previousContent.contentItem).fadeOut(0);
			}
		});
	},

	deselect: function() {
		$(this.navItem).addClass("navItemUnselected");
		$(this.navItem).filter(".navItemSelected").removeClass("navItemSelected");
		$(this.contentItem).css("z-index", 1);
	},

	onItemClick: function() {
		this.engine.showContent(this, true);
		this.engine.stopCycle();
	}
}

///////////////////////////////////////////////////////////////////////////
// AR/CR Home Banner ready items

$(document).ready(function() {
    var sectionPrefixes = ["arHome", "crHome", "nextHome"];
    var i = 0;
    while (i < sectionPrefixes.length) {
        var sectionIdPrefix = "#" + sectionPrefixes[i];
        if ($(sectionIdPrefix + "DisplayArea").length > 0) {
            mainHeader = new dynamicContentHeader(
		        $(sectionIdPrefix + "DisplayArea .displayItem"),
		        $(sectionIdPrefix + "NavArea .navItem"),
		        $(sectionIdPrefix + "NavArea .thumbnailSelection")
	        );
            break;
        }
        i++;
    }
});


// framebuster scripts
var sThisURL = unescape(window.location.pathname);

function doFramesBuster() {
    if (top.location.href.indexOf('.chevron.com') == -1 && top.location != self.location)
        breakFrames();
}

function breakFrames() {
    top.location.replace(sThisURL);
}    

$(document).ready(function(){
    doFramesBuster()
});

var addthis_config = {
    services_exclude: 'print, email'
};

