//Portions are Copyright (c) 2000-2005, Mobular Technologies&#174;, Inc.  All Rights Reserved.
//Mobular and Mobular Technologies are Registered Trademarks of Mobular
//Technologies, Inc.
//All rights reserved.  Unauthorized reproduction prohibited.
//http://www.mobular.com/
//
var onePageEnable = {
	_obj 			: "1pageImg",
	src 			: "images/1page.gif",
	alt 			: "Single Page View"
};

var onePageDisable = {
	_obj 			: "1pageImg",
	src 			: "images/1page_dis.gif",
	alt 			: ""
};

var twoPageEnable = {
	_obj 			: "2pageImg",
	src 			: "images/2page.gif",
	alt 			: "Two Page View"
};

var twoPageDisable = {
	_obj 			: "2pageImg",
	src 			: "images/2page_dis.gif",
	alt 			: ""
};

var zoomInEnable = {
	_obj 			: "zoomInImg",
	src 			: "images/zoom_in.gif",
	alt 			: "Zoom in"
};

var zoomInDisable = {
	_obj 			: "zoomInImg",
	src 			: "images/zoom_in_dis.gif",
	alt 			: ""
};

var zoomOutEnable = {
	_obj 			: "zoomOutImg",
	src 			: "images/zoom_out.gif",
	alt 			: "Zoom out"
};

var zoomOutDisable = {
	_obj 			: "zoomOutImg",
	src 			: "images/zoom_out_dis.gif",
	alt 			: ""
};

var firstEnable = {
	_obj 			: "first",
	src 			: "images/rewind.gif",
	alt 			: "First page"
};

var firstDisable = {
	_obj 			: "first",
	src 			: "images/rewind_dis.gif",
	alt 			: ""
};

var previousEnable = {
	_obj 			: "previous",
	src 			: "images/previous.gif",
	alt 			: "Previous page"
};

var previousDisable = {
	_obj 			: "previous",
	src 			: "images/previous_dis.gif",
	alt 			: ""
};

var nextEnable = {
	_obj 			: "next",
	src 			: "images/next.gif",
	alt 			: "Next page"
};

var nextDisable = {
	_obj 			: "next",
	src 			: "images/next_dis.gif",
	alt 			: ""
};

var lastEnable = {
	_obj 			: "last",
	src 			: "images/fastforw.gif",
	alt 			: "Last Page"
};

var lastDisable = {
	_obj 			: "last",
	src 			: "images/fastforw_dis.gif",
	alt 			: ""
};

var uiElements = {

	imgSettings : [
					"_obj",
					"src",
					"alt"
				  ],
	processImg: function(settings, alt_override) {

		var collection = uiElements.imgSettings;
		var _obj = settings[collection[0]];
		var obj = document.getElementById(_obj);
		if (obj) {
			for ( var n=1; n < collection.length; n++ ) {
				var setting = collection[n];
				try {
					var _setting = settings[setting];
					if (alt_override && setting == "alt") { _setting = alt_override; }
					obj.attributes[setting].value = _setting;
				} catch (e) { }
			}
		}
	},
	_disableAll: function() {
		// anything else is probably not in the book.
    	this.processImg(zoomInDisable);
	    this.processImg(zoomOutDisable);
	    this.processImg(firstDisable);
	    this.processImg(previousDisable);
	    this.processImg(nextDisable);
	    this.processImg(lastDisable);
	}
};

//set varible to be global on the dom
var any_useful_links = false;

// Event model listeners

function _addfix() {
	eengine.objects.pageAttachments = function(_tag) {
		var pgStatus = binder.kitData.current;
		var docs = binder.kitData.documents;
		var reExt = /\.(.+)$/i;

		var attachment = '';
		var _page = docs[pgStatus.doc].pages[pgStatus.page];
		
		for ( var a=0; a < _page.attachments.length; a++ ) {
			var _attach = _page.attachments[a];
			
			var reExt = /\.(.+)$/i;
			var re = reExt.exec(_attach);
			
			if ( (re != null) && (re.length>1 ) ) {
				var _ext = re[1];
				switch ( _ext.toLowerCase() ) {
				case 'xls':
					// requirement: XLS is only for single page type mode
					if ( pgStatus.layout == 0 ) {
						attachment += '\n <FONT SIZE="2" FACE="lucida,helvetica" color="'+eengine.nl_c+'"><b>'+eengine.erMsg[22]+'</b></font><BR><BR>';                                                          
						attachment += '\n <a href="'+_attach+'" target="ExcelWindow">';                                                            
						attachment += '\n '+eengine.iHtml( "images/selected.gif", 0, '' )+'</A><BR><BR>';
					}
					break;
				}
			}
		}                       
		var _lnk = document.getElementById(_tag);
		if ( _lnk ) {
			_lnk.innerHTML = attachment;
		}                                   
	}
}


function onEngineIdle() {
	
	_addfix();
	
	if ( document.getElementById('toc_placeholder') ) {
		var _div = document.getElementById('toc_placeholder');
		var _title = "[+] Click to Select";
		var _param = {
			buttonText: ''+_title,
			id: 'toc_placeholder',
			buttonTemplate: "<span class=\"dijit dijitReset dijitLeft dijitInline\" dojoAttachEvent=\"onmouseenter:_onMouse,onmouseleave:_onMouse,onmousedown:_onMouse,onclick:_onDropDownClick,onkeydown:_onDropDownKeydown,onblur:_onDropDownBlur,onkeypress:_onKey\" waiRole=\"presentation\"><div class='dijitReset dijitRight' waiRole=\"presentation\"><button title=\"Table of Contents dropdown button\" class=\"dijitReset dijitStretch dijitButtonNode dijitButtonContents\" type=\"${type}\"dojoAttachPoint=\"focusNode,titleNode\" waiRole=\"button\" waiState=\"haspopup-true,labelledby-${id}_label\"><div class=\"dijitReset dijitInline dijitButtonText\"  dojoAttachPoint=\"containerNode,popupStateNode\" waiRole=\"presentation\"id=\"${id}_label\">${label}</div></button></div></span>"
		};	
		new display.dropDownTOC.dropDownTOC(_param, _div);
	}
	
	/* If searchbox varible not supplied during build set default value */
	var srcbox = document.getElementById("query");
	if (srcbox.value == ""){
		srcbox.value = "Search Document(s)";
	}
	
	document.getElementById('active_page_count').innerHTML = "";


	
	/**
	 * Set all eBooks to start in layout 0 (single page mode) initially.
	 * 
	 *   (fixes bug in which g_startingLayout=0 that does work as expected)
	 */
	uiElements._disableAll();
	for (var x = 0; x < eengine.kitData.documents.length; x++) {
		eengine.kitData.documents[x].layout = 0;	
	}
	eengine.kitData.current.layout = 0;
	eengineConfig.buildSettings._startingLayout = "0";
	eengine.zoomLvl = 1;
 	//end single page layout stuff in this section
    
    
    enableLinks();
	recreateShowShow();

	//set customer logo link - link is stored in link.js file
	if(typeof CustomerHref != "undefined"){
		document.getElementById('CustomerHref').href = "http://" + CustomerHref;
	}

	// check for RSS and wipe out if not needed.
	try {
		if ( dijit.byId('rssObj').rssFeeds.length == 0 ) {
			document.getElementById('rssObj').style.display = "none";
		}
	} catch (e) {
		document.getElementById('rssObj').style.display = "none";
	}

	try {
		if ( (!any_useful_links) && ( _leaveOpen ) ) {
			any_useful_links = true;
		}
      } catch (e) {}
	
	_checkToCloseZone(window.any_useful_links);
	
	eengine.total_load                   = 1;
}
eengineConfig.subscribe( "onEngineIdle()", "eengine.postProcess.engineidle");

// this is a workaround until the full themes system can be implemented.
function injectStyle(widget, mySession) {
	if ( mySession.event == -900 ) {
		/* add stylesheet code here like so:
			var css = '.rssCrumbBaseMiddle { background-color: #CCC; }';
		*/
		var css = '';
		css += '.rssWidgetContainer { width:  150px; height: 350px;	}';

		// css strings may be entered
		if ( css != '' ) {
			//dojo.html.insertCssText(css);
		}
	}
}
eengineConfig.subscribe( "injectStyle", "rssCrumb" );

function onDisplayS2F() {
	uiElements._disableAll();
}
eengineConfig.subscribe( "onDisplayS2F()", "eengine.postProcess.s2fUI" );

function onDisplayS2D() {
	uiElements._disableAll();
}
eengineConfig.subscribe( "onDisplayS2D()", "eengine.postProcess.s2dUI" );

function onDisplayPrint() {
	uiElements._disableAll();
}
eengineConfig.subscribe( "onDisplayPrint()", "eengine.postProcess.displayprintUI" );

function onDisplayHelp() {
	uiElements._disableAll();
}
eengineConfig.subscribe( "onDisplayHelp()", "eengine.postProcess.helpUI" );

function onDisplayPage(widget, mySession){
	var action = mySession.event;

	if (action = 902) {
		var _page_count = binder.kitData.documents[binder.kitData.current.doc].pages.length;
		document.getElementById('active_page_count').innerHTML = "of " + _page_count;

		// adjust zoom first
		switch (eengine.zoomLvl) {
			case 1:
				uiElements.processImg(zoomInEnable);
				document.getElementById('_zoomInLink').style.display = "";

				uiElements.processImg(zoomOutDisable);
				document.getElementById('_zoomOutLink').style.display = "none";

				// enable / disable the one / two page buttons
				uiElements.processImg(onePageDisable);
				uiElements.processImg(twoPageEnable);
				break;
			case 2:
				uiElements.processImg(zoomInDisable);
				document.getElementById('_zoomInLink').style.display = "none";

				// swap zoom out for zoom in on ui
				uiElements.processImg(zoomOutEnable);
				document.getElementById('_zoomOutLink').style.display = "";
				break;
			default:
				// zoomLvl 0
				uiElements.processImg(zoomInDisable);
				document.getElementById('_zoomInLink').style.display = "";

				uiElements.processImg(zoomOutDisable);
				document.getElementById('_zoomOutLink').style.display = "none";

				// enable / disable the one / two page buttons
				uiElements.processImg(onePageEnable);
				uiElements.processImg(twoPageDisable);
				break;
		}

		if (isAtDocStart()) { 
			uiElements.processImg(firstDisable);
			uiElements.processImg(previousDisable);
			
			
			if (isAtDocEnd()){
				uiElements.processImg(lastDisable);
				uiElements.processImg(nextDisable);	
				
			}else{
				uiElements.processImg(lastEnable);
				uiElements.processImg(nextEnable);					
			}
			
		} else if (isAtDocEnd()) {
			uiElements.processImg(lastDisable);
			uiElements.processImg(nextDisable);	

			uiElements.processImg(firstEnable);
			uiElements.processImg(previousEnable);				
			
		} else {
			uiElements.processImg(firstEnable);
			uiElements.processImg(previousEnable);
			uiElements.processImg(nextEnable);	
			uiElements.processImg(lastEnable);
		}			
			
		
/*		
		if (isAtKitStart()) {
			uiElements.processImg(firstDisable);
			uiElements.processImg(previousDisable);
			uiElements.processImg(nextEnable);
			if (isLastDoc()) {
				uiElements.processImg(Disable)
			} else {
				_alt = "Next eBook - " + binder.kitData.documents[binder.kitData.current.doc+1].title;
				uiElements.processImg(nextDocEnable, _alt)
			}
		} else if (isAtKitEnd()) {
			uiElements.processImg(firstEnable);
			uiElements.processImg(previousEnable);
			uiElements.processImg(nextDisable);
			uiElements.processImg(nextDocDisable);
		} else if (isAtDocStart()) {
			_alt = "Previous eBook - " + binder.kitData.documents[binder.kitData.current.doc-1].title;
			uiElements.processImg(firstEnable, _alt);

			_alt = "Previous eBook - " + binder.kitData.documents[binder.kitData.current.doc-1].title + " (last page)";
			uiElements.processImg(previousEnable, _alt);

			uiElements.processImg(nextEnable);

			if (isLastDoc()) {
				uiElements.processImg(nextDocDisable)
			} else {
				_alt = "Next eBook - " + binder.kitData.documents[binder.kitData.current.doc+1].title;
				uiElements.processImg(nextDocEnable, _alt)
			}
		} else if (isAtDocEnd()) {
			uiElements.processImg(firstEnable);
			uiElements.processImg(previousEnable);

			_alt = "Next eBook - " + binder.kitData.documents[binder.kitData.current.doc+1].title;
			uiElements.processImg(nextEnable, _alt);

			if (isLastDoc()) {
				uiElements.processImg(nextDocDisable)
			} else {
				_alt = "Next eBook - " + binder.kitData.documents[binder.kitData.current.doc+1].title;
				uiElements.processImg(nextDocEnable, _alt)
			}
		} else {
			uiElements.processImg(firstEnable);
			uiElements.processImg(previousEnable);
			uiElements.processImg(nextEnable);
			if (isLastDoc()) {
				uiElements.processImg(nextDocDisable)
			} else {
				_alt = "Next eBook - " + binder.kitData.documents[binder.kitData.current.doc+1].title;
				uiElements.processImg(nextDocEnable, _alt)
			}
		}
*/
		//show next nav button if on cover and this is a single view only document
		//if (eengine.kitData.current.cover == 1 && eengine.kitData.documents.length == 1){
		if ((eengine.kitData.current.cover == 1) && (eengine.kitData.current.layout == 0) && (eengine.kitData.documents.length == 1)){
			uiElements.processImg(nextEnable);					
			uiElements.processImg(lastEnable);
		}
	}
}
eengineConfig.subscribe( "onDisplayPage", "display.book.book");

function onDislayCover() {

	var event = eengine.reporting.getLatest();
	var action = parseInt( event.action, 10 );
	if ( action == -95 ) {
		document.getElementById('active_page_count').innerHTML = "";
		uiElements._disableAll();

		// custom to make first doc have red NEW! marker
		for ( var d=1; d < binder.kitData.documents.length; d++ ) {
			try {
				var _a = document.getElementById('link_'+d);
				var _title = _a.innerHTML;
				if ( _title.indexOf("NEW!") != -1 ) {
					_title = _title.replace("NEW!", "<span style='color:red;font-weight:bold;'>NEW!</span>");
					_a.innerHTML = _title;
				}
			} catch (e) {}
		}
	}

}
eengineConfig.subscribe( "onDislayCover()", "eengine.postProcess.coverUI" );

function isAtDocStart() {
	var _current = eengine.kitData.current;
	if (_current.page == 0) {
		return true;
	} else {
		return false;
	}
}


function isAtDocEnd() {
	var _kit = eengine.kitData;
	var _current = _kit.current;
	if ((_current.layout == 1 && _current.page >= _kit.documents[_current.doc].pages.length - 1) || (_current.layout == 0 && _current.page == _kit.documents[_current.doc].pages.length - 1)) {
		return true;
	} else {
		return false;
	}
}

function isAtKitStart() {
	var _current = eengine.kitData.current;
	if (isAtDocStart() && _current.doc == 1) {
		return true;
	} else {
		return false;
	}
}

function isAtKitEnd() {
	var _kit = eengine.kitData;
	var _current = _kit.current;
	if (isAtDocEnd() && _current.doc == _kit.documents.length - 1) {
		return true;
	} else {
		return false;
	}
}

function isLastDoc() {
	var _doc = eengine.kitData.current.doc;
	if (_doc == eengine.kitData.documents.length - 1) {
		return true;
	} else {
		return false;
	}
}

function zoomIn() {
	// First part of the if statement is a work around, I should just be able to call eengine.getZoom(0) to
	// zoom out.  Once all zoom issues are worked out the getZoom calls should go directly into the eesearch.html
	// template file and the zoomIn and zoomOut functions can be deleted.
	if (binder.kitData.current.layout == 1) {
		eengine.switchLayout();
	} else if (binder.kitData.current.layout == 0) {
		eengine.getZoom(0);
	}
}

function zoomOut() {
	eengine.getZoom(1);
}

function goFirst() {
	var _doc = eengine.kitData.current.doc;
	if (!isAtDocStart()) {
		eengine.writePage(_doc, 0);
	}
}

function goPrevious() {
	if (!isAtDocStart()) {
		//fix for two page layout navigation when moving from toc - toc to page two then go previous
		var _current = eengine.kitData.current;
		if (_current.layout == 1 && _current.page == 1){
			eengine.writePage(_current.doc, 0);
		}else{
			eengine.writePage(-65536);
		}
	}
}

function goNext() {
	if (!isAtDocEnd()) {
		eengine.writePage(65536);
	}
}

function goLast() {
	var _doc = binder.kitData.current.doc;
	if (!isAtDocEnd()) {
		var _page = binder.kitData.documents[_doc].pages.length - 1;
		eengine.writePage(_doc, _page);
	}
}

function recreateShowShow() {
}

/**
 * Enable the sidebar links if they are set in links.js - a required file.  HTML div
 * sections are required to be pressent in the showglobal.html file.
 */
function enableLinks(){
    try{
        // Gather location, if 'location' bar is not there a blank  string is returned
        var finalVotingDate = new Date(2000,00,01);

        var t = new String(""+this.parent.location);

        // Check for '?'.   If present and the voting value pair is present, process it.
        if (t.indexOf("?") != -1 && t.indexOf("voting=") != -1) {
            t = t.substring(t.indexOf("?")+1);
            t = unescape(t);
            var _date = getFinalVotingDate(t);
            if (_date != "") {
                var _d = _date.split('-');
                finalVotingDate.setFullYear(_d[0]);
                finalVotingDate.setMonth(_d[1]-1);
                finalVotingDate.setDate(_d[2]);
                finalVotingDate.setDate(finalVotingDate.getDate() + 1);
            }
        }

        document.getElementById('useful_links').innerHTML = usefulLinksString;
        
		//use global varible any_useful_links
        any_useful_links = false;
        if (configureSegment('useful1') && ! any_useful_links) { any_useful_links = true; }
        if (configureSegment('useful2') && ! any_useful_links) { any_useful_links = true; }
        if (configureSegment('useful3') && ! any_useful_links) { any_useful_links = true; }
        if (configureSegment('useful4') && ! any_useful_links) { any_useful_links = true; }
        if (configureSegment('useful5') && ! any_useful_links) { any_useful_links = true; }
        if (configureSegment('useful6') && ! any_useful_links) { any_useful_links = true; }
        if (configureSegment('useful7') && ! any_useful_links) { any_useful_links = true; }
        if (configureSegment('useful8') && ! any_useful_links) { any_useful_links = true; }
        if (configureSegment('financials') && ! any_useful_links) { any_useful_links = true; }

        if (any_useful_links) {
          document.getElementById('useful_links_start').style.visibility = "visible";
          document.getElementById('useful_links_close').style.visibility = "visible";
        } else {
          document.getElementById('useful_links_start').innerHTML = "";
          document.getElementById('useful_links_close').innerHTML = "";
        }
    } catch (e) {}
    
}

function getFinalVotingDate(query_string) {

	var re = /[\?]*voting=(.+)[&]*/;
    var _prm = query_string.split('&');

	// remove any stray '?' items that would prevent parsing
	for ( var i=0; i < _prm.length; i++ ) {
		if ( _prm[i].indexOf("?") > 0 ) {
			_prm[i] = _prm[i].substring( _prm[i].indexOf("?")+1 );
		}
	}

	for ( var i=0; i < _prm.length; i++ ) {
		if ( _prm[i].match(re) ) {
			var voting_parameter = _prm[i].split('=');
			var voting_date = ( voting_ends != '' ? voting_ends : '<blank>' );
			var _voting_parm = false;
			try {
				_voting_parm = eval(voting_parameter[1].toLowerCase());
			} catch (e) { }

			if (voting_parameter.length > 1 && _voting_parm == true)
			{
				// Is voting enabled on the query string (e.g ?voting=true)...
				re = /(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])/;
				if (! voting_date.match(re) ) {
					alert('Invalid date defined in the links.js for voting_ends parameter (yyyy-mm-dd): ' + voting_date);
					return "";
				} else {
					return voting_date;
				}
			} else if (voting_parameter.length > 1 && voting_parameter[1].toLowerCase() != '') {
				// Is the links.js voting_ends date overridden on the query string...
				voting_date = voting_parameter[1];
				re = /(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])/;
				if (! voting_date.match(re) ) {
					return "";
				} else {
					return voting_date;
				}

			} else {
				return "";
			}
		}
	}

	return "";

}

function addQueryStringParameter(_parm, _str) {

	var re = eval("/[\?]*(" +  _parm + "=.+)[&]*/");
 	var t = new String(""+this.parent.location);
	var _prm = t.split('&');

	// remove any stray '?' items that would prevent parsing
	for ( var i=0; i < _prm.length; i++ ) {
		if ( _prm[i].indexOf("?") > 0 ) {
			_prm[i] = _prm[i].substring( _prm[i].indexOf("?")+1 );
		}
	}

	for ( var i=0; i < _prm.length; i++ ) {
		if ( _prm[i].match(re) ) {
			if (_str.indexOf("?") > 0) { _str += "&" + RegExp.$1 }
			else if (_str.indexOf("?") == -1) { _str += "?" + RegExp.$1 }
			return _str;
		}
	}

	return _str;
}

function _checkToCloseZone(any_useful_links) {
	if ( ( g_RSSWidget_rssFeeds.length == 0 ) && (! any_useful_links ) ) {
		// remove globalRCSpacer and globalRCContainer
		document.getElementById('globalRCSpacer').style.display = "none";
		document.getElementById('globalRCContainer').style.display = "none";
	}
}

function configureSegment (segment, dateConstraint) {

	var skipIt = false;
	if (dateConstraint) {
		var currentDate = new Date();
		if (currentDate < dateConstraint) { skipIt = false; } else { skipIt = true; }
	}

	try {
		var textDiv = segment + "_link_text";
		var textVariable = textDiv;
		var segmentLink = eval(segment + "_link");
		var segmentDiv = segment + "_segment";

		var textString = eval(textVariable);
		if (trim(segmentLink) != '' && ! skipIt) {

				var _content = document.getElementById(segmentDiv).innerHTML;

				var obj = /\n/ig;
				_content = _content.replace ( obj, "temporaryreplaceoflinefeeds" );

				obj = eval("/\\[\\[" + textVariable + "\\]\\]/ig");
				_content = _content.replace(obj, textString);

				obj = eval("/\\%5B\\%5B" + textVariable + "\\%5D\\%5D/ig");
				_content = _content.replace(obj, textString);

				obj = /\[\[click_text\]\]/ig;
				_content = _content.replace(obj, clickString);

				obj = /\%5B\%5Bclick_text\%5D\%5D/ig;
				_content = _content.replace(obj, clickString);

				obj = /temporaryreplaceoflinefeeds/ig;
				_content = _content.replace ( obj, "\n" );

				document.getElementById(segmentDiv).innerHTML = _content;
				document.getElementById(segmentDiv).style.visibility = "visible";

				return true;
		} else {
				document.getElementById("globalRC").removeChild(document.getElementById(segmentDiv));
				return false;
		}
	}
	catch (e) {
        return false;
	}
}

function fireLink(link) {

    var url = "";

	if (link.indexOf('http') != 0 && link.indexOf('_link') > 0) {
		try {
			url = eval(link);
			if (url.toLowerCase().indexOf('.xls') > 0 && url.toLowerCase().indexOf('http') == -1)
			{
				url = 'xls/' + url;
			}
		}
		catch (e) {
			alert('Invalid hyperlink: ' + link);
			return 0;
		}
	} else if (link.indexOf('http') == 0 || link.indexOf('mailto') == 0) {
		url = link;
	} else {
		alert('Invalid hyperlink: ' + link + "...Links must be valid http, https, or mailto qualified hyperlinks.");
		return 0;
	}

    if (url != '')
	{
		if (url.toLowerCase().indexOf('mailto:') == 0)
		{
			window.open(url);
		}
		else
		{
			// For CFS only, if the psac parameter is defined, grab it and send it back to Computershare on the
			// doClickThrough.
			url = addQueryStringParameter('psac', url);
			eengine.doClickThrough(url, 600, 800, 2);
		}
	}
}

function trim (strText) {
    // Get rid of leading spaces
    while (strText.substring (0, 1) == ' ')
        strText = strText.substring (1, strText.length);

    // Get rid of trailing spaces
    while (strText.substring (strText.length - 1, strText.length) == ' ')
        strText = strText.substring (0, strText.length - 1);

    return strText;
}
