﻿// JScript File

/*
 * 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;
	}
}
 
/*
 * 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');
			}
		}
		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);
	}
}

/*
 * 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");
    });

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
/*
 * 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 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);
			});
		}
		
	},
	show: function(li) {
		$(li).addClass('hover');
		this.iframeFix(li);
	},
	hide: function(li) {
		$(li).removeClass('hover');
		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';
		}
	}
}


//Extension detection, icon placement, and icon alternate text
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('wmv') != -1) {
          x[i].setAttribute("title", "Windows Media Video");
        } else if (x[i].className.indexOf('realAudio') != -1) {
          x[i].setAttribute("title", "Real Audio");
        } else if (x[i].className.indexOf('rss') != -1) {
          x[i].setAttribute("title", "RSS Feed");
        } else if (x[i].className.indexOf('catchCode') != -1) {
          x[i].onkeypress = gaCatchCode;
          x[i].onclick = gaCatchCode;
        } else if (isAssetDoc(x[i])) { // Set file extensions in isAssetDoc() below
          var fileExt = getFileExt(x[i]);
          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 isAssetDoc(obj) {
  var types = new Array("pdf", "doc", "xls", "ppt");
  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;
  return url.substr(url.lastIndexOf(".")+1);
}
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 clearSearchText(obj) {
  if(obj.value == "Search Annual Report")
  {
    obj.value = "";
  }
}

function restoreSearchText(obj) {
  if(obj.value == "") {
    obj.value = "Search Annual Report";
  }
}

// Flash Deep Linking
function track( param ) {
	// code here for call to tracking analytics
}
function track( param )	{
	// code here for call to tracking analytics
}
	// grab root url for use in email page form
var url = location.href;
var urlArr = url.split('#',1);
var rooturl = urlArr[0];
	//alert(rooturl);

//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.apply(this, a);
}

var tb_container;
var tb_content;
//The thickbox callback function
function tb_callback(caption, url, imageGroup) {
    // Add wrappers
        var TB_window = $('#TB_window')[0];
        tb_container = document.createElement('div');
        tb_container.id = "TB_wrapper";
        var imgContainer = document.createElement('div');
        imgContainer.id = "TB_popupImg";
        tb_container.appendChild(imgContainer);
        var contentPad = document.createElement('div');
        contentPad.id = "TB_contentPad";
        tb_container.appendChild(contentPad);
        tb_content = document.createElement('div');
        tb_content.id = "TB_content";
        contentPad.appendChild(tb_content);
        if (TB_window.childNodes != null) {
	        while(TB_window.childNodes.length > 0) {
    	        tb_content.appendChild(TB_window.childNodes[0]);
            }
        }
        TB_window.appendChild(tb_container);
}

// Hack thickbox to have a callback for tb_position (called when contents are ready to show)
tb_position2 = tb_position;

window.tb_position = function() {
//overflow
    if ($("#TB_closeWindowButton").length > 0) {
        $("#TB_closeWindowButton").unbind("click").click(function() {
            tb_remove();
            return (false);
        });
    }

    $("#TB_ajaxContent").css("overflow", "hidden");
    if ($("#TB_ImageOff").length > 0) {
        $("#TB_closeWindow").hide();
        $("#TB_ImageOff").unbind("click").click(function() {
            return (false);
        });
        $("#TB_Image").removeAttr("width").removeAttr("height");
    }

	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() {
    // Undo the border we added to the thickbox
    var TB_window = $('#TB_window')[0];
    if (tb_content.childNodes != null) {
	    while(tb_content.childNodes.length > 0) {
    	    TB_window.appendChild(tb_content.childNodes[0]);
        }
    }
    TB_window.removeChild(tb_container);
    
	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");

	// 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) {
		tbTabEls[tbTabEls.length == 1 ? 0 : 1].focus();
	}
}

function tb_unrestrictTabOrder() {
    $(document).unbind("keydown");
    $(document).unbind("keypress");
}

addLoadEvent(GetAnchors);

// table row and column hover test by GM
$(function(){
    if ($('.rowColumnHover').tableHover != undefined) {
        $('.rowColumnHover').tableHover({spanCols: false, headCols: true, allowFoot: false, ignoreCols: [1], rowClass: 'rowHover', colClass: 'colHover', cellClass: 'hoverCell'}); 
    }
})


//**************************************************************************************************************//
// Main drawer behavior, affects all 'accordion' drawers throughout site (but not 'promo' drawers on Home page).
function rAccordin() {
	this.initialize();
}
rAccordin.prototype = {
	initialize: function() {

        
        // open and close drawers on mouseclick
        $('div.accordion> h3').click(function() {
            $(this).next('div').slideToggle('fast', function () {
                $(this).toggleClass('printOnly').show().css("display","");
            });
            // Close other drawers
            /*$(this).next('div').siblings('div').slideUp('fast', function () {
                $(this).addClass('printOnly').show().css("display","");
            }); */
            $(this).toggleClass("open");
            $(this).toggleClass("closed");
        });
    }
}



addLoadEvent(function() {
    new rAccordin();
});

//**************************************************************************************************************//
// AR homepage banner behavior.

function dynamicContentHeader(contentDisplayItems, navItems, thumbnailSelection) {
	this.contentItems = [];
	this.currentContent = null;
	this.cycleIntervalId;
	this.timeoutIntervalId;
	this.mouseActivityTimer = 0;
	this.cycleDelay = 9;
	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", 500);

	this.thumbnailSelection = thumbnailSelection;
	thumbnailSelection.css("z-index", 100).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(){
		this2.onItemClick();
	});
}

dynamicHeaderItem.prototype = {
	select: function(previousContent, instant) {
		if (previousContent) {
			previousContent.deselect();
		}

		var duration = instant ? 10 : 1000;
		$(this.navItem).removeClass("navItemUnselected");
		$(this.navItem).addClass("navItemSelected");
		$(this.contentItem).css("z-index", 100).fadeIn(duration, function() {
			if (previousContent && previousContent.contentItem != this) {
				$(previousContent.contentItem).fadeOut(0);
			}
		});
	},

	deselect: function() {
		$(this.navItem).addClass("navItemUnselected");
		$(this.navItem).removeClass("navItemSelected");
		$(this.contentItem).css("z-index", 1);
	},

	onItemClick: function() {
		this.engine.showContent(this, true);
		this.engine.stopCycle();
	}
}

///////////////////////////////////////////////////////////////////////////
// AR Home Banner ready items

$(document).ready(function(){
    if ($("#arHomeDisplayArea").length > 0) {
    	mainHeader = new dynamicContentHeader(
		    $("#arHomeDisplayArea .displayItem"),
		    $("#arHomeNavArea .navItem"),
		    $("#arHomeNavArea .thumbnailSelection")
	    );

        // Add shadow border to banner
    	$(".shadowBorder").each(function(i){
		    $(this).prepend(
	    		'<div class="shadow">' +
				    '<div class="shadow01"></div>' +
				    '<div class="shadow21"></div>' +
				    '<div class="shadow10"></div>' +
			    	'<div class="shadow12"></div>' +
		    		'<div class="shadow00"></div>' +
	    			'<div class="shadow02"></div>' +
    				'<div class="shadow20"></div>' +
				    '<div class="shadow22"></div>' +
			    '</div>'
		    );
        });
	}
});
