//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);			
	}
};

// Event model listeners

function onEngineIdle() {
	
	//configure right hand sidebar
	_rhs();
	
	if ( document.getElementById('toc_placeholder') ) {
		var _div = document.getElementById('toc_placeholder');
		var _title = eengine.kitData.description; 
		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 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);	
	}
	
	document.getElementById('active_page_count').innerHTML = "";
	dijit.byId('tocDDbutton').containerNode.innerHTML = '[+] Click to select'; 
	 			
	uiElements._disableAll();	
	
	// at this point, check the buildSettings. If _startingLayout is 0, then check for 'display_mode_control_viewmode' and hide it.
	// NOTE: if it is desired that a user viewing single page mode can return to two page mode.. comment this block out.
/*	if ( eengineConfig.buildSettings._startingLayout == "0" ) {
		try {
			document.getElementById('display_mode_control_viewmode').style.display = "none";
			document.getElementById('display_mode_control_viewmodeLabel').style.display = "none";
		} catch (e) {}		
	}
*/
	recreateShowShow();  
	
	// Display the Voting / Segment 5?
	var currentDate = new Date();
	
	var url = "";
	try { url = eval('voting_link'); } catch (e) { }
	var cover_voting_segment = document.getElementById('cover_voting_segment');
	if (cover_voting_segment && currentDate < finalVotingDate && url != "") {
		cover_voting_segment.style.visibility = "visible";
	} else if (cover_voting_segment) {
		cover_voting_segment.innerHTML = "";
		cover_voting_segment.style.visibility = "hidden";
	}
	
	// Display the Notice of Annual Meeting / Segment 6?
	var cover_notice_segment = document.getElementById('cover_notice_segment');
	if (cover_notice_segment && currentDate < finalVotingDate) {
		cover_notice_segment.style.visibility = "visible";
	} else if (cover_notice_segment) {
		cover_notice_segment.innerHTML = "";
		cover_notice_segment.style.visibility = "hidden";
	}
	
	// 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";		
	}
	
	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 onDisplaySearch(){
	eengine.kitData.current.layout = 0;
	eengineConfig.buildSettings._startingLayout = "0";
	eengine.zoomLvl = 1;	
}
eengineConfig.subscribe("onDisplaySearch()", "eengine.postProcess.search");

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 = eengine.kitData.documents[eengine.kitData.current.doc].pages.length
		document.getElementById('active_page_count').innerHTML = "of " + _page_count;	

		//clean out the "Page" text displayed in PageStatus that is stored with the Documents array
		var doc = eengine.kitData.documents[eengine.kitData.current.doc];
		for(var _page = 0; _page < doc.pages.length; _page++){
			if (typeof doc.pages[_page].title !== "undefined"){
				doc.pages[_page].title = doc.pages[_page].title.replace("Page ", "");
			}
		}
		
		// check to see if we turn on the 'return to search' link
		try {
			if ( eengine.dbSearch._results.length > 0) {
				document.getElementById('redisplaySearch').style.visibility = "visible";
			}			
		} catch (e) {}		
		
		// 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) 						
		}		
	}
}
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();
		
		// Display the Voting / Segment 5?
		var currentDate = new Date();
		
		var url = "";
		try { url = eval('voting_link'); } catch (e) { }
		var cover_voting_segment = document.getElementById('cover_voting_segment');
		if (cover_voting_segment && currentDate < finalVotingDate && url != "") {
			cover_voting_segment.style.visibility = "visible";
		} else if (cover_voting_segment) {
			cover_voting_segment.innerHTML = "";
			cover_voting_segment.style.visibility = "hidden";
		}
		
		// Display the Notice of Annual Meeting / Segment 6?
		var cover_notice_segment = document.getElementById('cover_notice_segment');
		if (cover_notice_segment && currentDate < finalVotingDate) {
			cover_notice_segment.style.visibility = "visible";
		} else if (cover_notice_segment) {
			cover_notice_segment.innerHTML = "";
			cover_notice_segment.style.visibility = "hidden";
		}		
	}
}  
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 (eengine.kitData.current.layout == 1) {
		eengine.switchLayout();
	} else if (eengine.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 = eengine.kitData.current.doc;
	if (!isAtDocEnd()) {
		var _page = eengine.kitData.documents[_doc].pages.length - 1;		
		eengine.writePage(_doc, _page);
	}

}


function recreateShowShow() {
}

function _rhs() {
  
document.getElementById('useful_links').innerHTML = usefulLinksString;
configureSegment('voting', finalVotingDate);
configureSegment('shareholding', finalVotingDate);
//configureSegment('future_delivery', finalVotingDate, true);
configureSegment('request_materials', finalVotingDate);
configureSegment('phone_voting', finalVotingDate);

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 = "";
}  

}

function _checkToCloseZone(any_useful_links) {
	var t = new String(""+this.parent.location);
	if (t.indexOf("?") != -1 && t.indexOf("voting=") != -1) {
		any_useful_links = true;
	}	
	
	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, cont) {
	if (!cont) {
		cont = false;
	}
	
	var skipIt = false;
	if (dateConstraint) {
		var currentDate = new Date();
		if (currentDate < dateConstraint) { skipIt = false; } else { skipIt = true; }
	}
	if ( ( skipIt ) && ( cont ) ) {
		skipIt = false;
	}	
  
	try {
		var textDiv = segment + "_link_text";
		var textVariable = textDiv;		
		var segmentLink = '';
		try {
			segmentLink = eval(segment + "_link");
		} catch (e) {}
		 
		var segmentNumber = '';
		try {
			segmentNumber = eval(segment + "_number");
		} catch (e){}
		if ( trim(segmentNumber) == '' ) {
			switch (segment) {
				case "request_materials":
					segmentNumber = "555-5554";
					break;
				case "phone_voting":
					segmentNumber = "555-5555";
					break;
			}			
		}
		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 if ( (trim(segmentNumber) != '' ) && ! skipIt ) {
				if ( trim(textString) == '' ) {
					switch (segment) {
						case "request_materials":
							textString = "Request Printed Materials";
							break;
						case "phone_voting":
							textString = "Phone Voting";
							break;
					}
				}
				
				document.getElementById(textVariable).innerHTML = textString;
				document.getElementById(segment + "_number").innerHTML = segmentNumber;

				// ensure number is there for entries with a number				
				document.getElementById(segmentDiv).style.visibility = "visible";
				
				return true;		
		} else {
				document.getElementById("globalRC").removeChild(document.getElementById(segmentDiv));
				return false;
		}
	}
	catch (e) {
	}
}

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
		{
			try {
				url = unescape(url);
			} catch (e) { /* stub don't wory about it. */ }
			
			// 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;
}

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;
}
