/***** TII Global Browser Sniffing Variables *****/

var tii_isopera = typeof window.opera != 'undefined';

var tii_isie = typeof document.all != 'undefined'

   	&& !tii_isopera && navigator.vendor != 'KDE';

/***** TII Global Functions *****/

/***** ^^^ TII Global Functions Placed in >TII>Shared>JavaScript>TII LIB - JavaScript Event Listeners ^^^ *****/
/* Adds a function for the window load event */
function tii_callFunctionOnWindowLoad (functionToCall)
{
  if (typeof window.addEventListener != 'undefined')
  {
    window.addEventListener ('load', functionToCall, false);
  }
  else if (typeof document.addEventListener != 'undefined')
  {
    document.addEventListener ('load', functionToCall, false);
  }
  else if (typeof window.attachEvent != 'undefined')
  {
    window.attachEvent ('onload', functionToCall);
  }
  else
  {
    var oldFunctionToCall = window.onload;
    if (typeof window.onload != 'function')
    {
      window.onload = functionToCall;
    }
    else
    {
      window.onload = function ()
      {
        oldFunctionToCall ();
        functionToCall ();
      };
    }
  }
}

/* Calls functionToCall as soon as the targetElement is loaded, even if the document hasn't completely loaded yet. 
   Place the parameter list for functionToCall in order after tii_callFunctionOnElementLoad (targetId, functionToCall),
   e.g., tii_callFunctionOnElementLoad (targetId, functionToCall, parameter1, parameter 2, parameter 3, ...) */  
function tii_callFunctionOnElementLoad (targetId, functionToCall)
{
	var myArguments = arguments;
	tii_callFunctionOnWindowLoad (function ()
		{
			window.loaded = true;
		});
	var targetElement = document.getElementById (targetId);
	if (targetElement == null && !window.loaded)
	{
		var pollingInterval = setInterval (function ()
			{
				if (window.loaded)
				{
					clearInterval (pollingInterval);
				}
				targetElement = document.getElementById (targetId);
				if (targetElement != null)
				{
					clearInterval (pollingInterval);
					var argumentsTemp = new Array ();
					var argumentsTempLength = myArguments.length - 2;
					for (var i = 0; i < argumentsTempLength; i++)
					{
						argumentsTemp [i] = myArguments [i + 2];
					}		
					functionToCall.apply (this, argumentsTemp);
				}
			}, 10);
	}
}

/* Attaches an event handling function to the targetElement as soon as the targetElement is loaded
   (even if the document hasn't completely loaded yet). */  
function tii_addEventHandlerOnElementLoad (targetId, eventType, functionToCall, bubbleEventUpDOMTree)
{
	tii_callFunctionOnWindowLoad (function ()
		{
			window.loaded = true;
		});
	var targetElement = document.getElementById (targetId);
	if (targetElement == null && !window.loaded)
	{
		var pollingInterval = setInterval (function ()
			{
				if (window.loaded)
				{
					clearInterval (pollingInterval);
				}
				targetElement = document.getElementById (targetId);
				if (targetElement != null)
				{
					clearInterval (pollingInterval);
					tii_addEventHandler (targetElement, eventType, functionToCall, bubbleEventUpDOMTree);
				}
			}, 10);
	}
}

/* Attaches an event handling function to the targetElement. */
function tii_addEventHandler (targetElement, eventType, functionToCall, bubbleEventUpDOMTree)
{
  if (!targetElement)
  {
	  window.status = 'Warning: Tried to attach event to null object';
	  return false;
  }
  if (typeof targetElement.addEventListener != 'undefined')
  {
    targetElement.addEventListener (eventType, functionToCall, bubbleEventUpDOMTree);
  }
  else if (typeof targetElement.attachEvent != 'undefined')
  {
    targetElement.attachEvent ('on' + eventType, functionToCall);
  }
  else
  {
    eventType = 'on' + eventType;
    if (typeof targetElement [eventType] == 'function')
    {
      var oldListener = targetElement [eventType];
      targetElement [eventType] = function ()
      {
        oldListener ();
        return functionToCall ();
      }
    }
    else
    {
      targetElement [eventType] = functionToCall;
    }
  }

  return true;
}


function TiiAdFactorySetParam(key, value) {
	if (typeof(value) == "object") {
		this.params[key] = value;
	} else {
		if (value.toString() != "") {
			this.params[key] = value;
		}
	}
}

function TiiAd(factory, width, height, tileNumber) {
	this.tileNumber		= tileNumber;
	this.width		= width;
	this.height		= height;
	this.params		= new Array();

	// Methods
	this.setParam		= TiiAdFactorySetParam;
	this.setMagicNumber	= TiiAdSetMagicNumber;
	this.setPosition	= TiiAdSetPosition;
	this.setZone		= TiiAdSetZone;
	this.write		= TiiAdWrite;

	// Private Methods
	this._formatParams	= TiiAd_formatParams;
	this._getAdParams	= TiiAd_getAdParams;
	this._getAdTag		= TiiAd_getAdTag;
	this._getAdUrl		= TiiAd_getAdUrl;
	this._getImageUrl	= TiiAd_getImageUrl;
	this._getClickUrl	= TiiAd_getClickUrl;
	this._getDebugHtml	= TiiAd_getDebugHtml;
	this._getSecureAdTag	= TiiAd_getSecureAdTag;
	
	// Copy factory settings
	this.randomNumber	= factory.randomNumber;
	this.adServer		= factory.adServer;
	this.tileNumber		= factory.tileCounter;
	this.zone		= factory.zone;
	this.sitename		= factory.sitename;
	this.config		= factory.config;
}

function TiiAdSetMagicNumber(mn) {
	this.setParam("mn", mn);
}

function TiiAdSetPosition(pos) {
	this.setParam("pos", pos);
}

function TiiAdSetZone(zone) {
	this.zone = zone;
}

function TiiAdWrite() {
	if (TiiAdsIsDebugMode()) {
		document.write(this._getDebugHtml() + "<br/>");
	}
	
	document.write(this._getAdTag());
}

function TiiAd_formatParams() {
	var adParams = "";
	for (var key in this.params) {
		var value = this.params[key];
		
		if (typeof(value) == "function") {
			continue;
		}

		if (typeof(value) == "string" || typeof(value) == "number") {
			adParams += ";" + key + "=" + escape(value).toLowerCase();
		} else {
			for (var i = 0; i < value.length; i++) {
				if (value[i] != "") {
					adParams += ";" + key + "=" + escape(value[i]).toLowerCase();
				}
			}
		}
	}
	
	return adParams;
}

function TiiAd_getAdParams() {
	var adParams	= this._formatParams();
	var tileParam	= ";tile=" + this.tileNumber;

	var secureParam = "";
	if (TiiAd_isSecure()) {
		secureParam = ";sec=1";
	}

	var puParam = "";
	if (!this.config.popups) {
		puParam = ";pu=0";
	}

	var ordParam	= ";ord=" + this.randomNumber;
	var rhost	= document.referrer.split("/")[2];
	var rhostParam	= "";
	if (typeof(rhost) != "undefined") rhostParam	= ";rhost=" + rhost;
	var pageParam	= ";pgurl=" + escape(document.location);
	
	return this.sitename + "/" + this.zone.toLowerCase() + adParams + pageParam + rhostParam + tileParam + puParam + secureParam + ordParam + "?";
}

function TiiAd_getAdTag() {
	var adTag;
	if (TiiAd_isSecure()) {
		adTag = this._getSecureAdTag();		
	} else {
		adTag = '<scr' + 'ipt type="text/javascript" src="' + this._getAdUrl() + '"></scr' + 'ipt>';
	}
	
	return adTag;
}

function TiiAd_getSecureAdTag() {
	return '<a href="' + this._getClickUrl() + '" target="_blank"><img src="' + this._getImageUrl() + '" width="' + this.width + '" height="' + this.height + '" border="0" /></a>';
}

function TiiAd_getAdUrl() {
	return this.adServer + "adj/" + this._getAdParams();
}

function TiiAd_getImageUrl() {
	return this.adServer + "ad/" + this._getAdParams();
}

function TiiAd_getClickUrl() {
	return this.adServer + "jump/" + this._getAdParams();
}

function TiiAd_getDebugHtml() {
	var output = '<input style="font-family: courier new; font-size: small; width:' + this.width + 'px; margin: 0; padding: 0" value="' + this._getAdUrl() + '"/>';

	return output;
}

// Support Functions

function TiiAdsIsDebugMode() {
	return window.location.search.indexOf("debugads") >= 0;
}


function TiiAd_isSecure() {
	return (document.location.protocol == "https:");
}

/* Attaching event handlers to elements */
var clickToggle = true; 
tii_addEventHandlerOnElementLoad ('bubbleLink', 'mouseover', function (event){displayBubble(event);}, false);
tii_addEventHandlerOnElementLoad ('bubbleLink', 'mouseout', function (event){hideBubble(event);}, false);
tii_addEventHandlerOnElementLoad ('bubbleLink', 'keypress' , function (event){displayBubble(event);}, false); 
tii_addEventHandlerOnElementLoad ('bubbleLink', 'blur', function (event){hideBubble(event);}, false);

/* Thought Bubble for The Ag */
function displayBubble(event){
	
	bubLink = document.getElementById('bubbleLink');
	bub = document.getElementById('bubble');
	var bubPos = new Array(2);
	bubPos = findPos(bubLink);

	/*  Check for IE */
	if (tii_isie) 
	{
		bub.style.left = (parseInt(bubPos[0]) - 162).toString() + 'px';
		bub.style.top = (parseInt(bubPos[1]) +  25).toString() + 'px';	
	}
	else
	{
		bub.style.left = (parseInt(bubPos[0]) - 176).toString() + 'px';
		bub.style.top = (parseInt(bubPos[1]) +  26).toString() + 'px';	
	}
	
	/* Display the bubble */
	bub.style.display = 'block';
	clickToggle = false;
}

/* Hides the bubble */
function hideBubble(event){
/*	alert ('test');*/
	var bub = document.getElementById('bubble');	
	bub.style.display = 'none';
	clickToggle = true;
}

/* Finds the position of an element on the page */
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

/* Begin Main story module */
var currPic=0;
var timer1, timer2;
var paused = true;
var opacity = 100;
var msDivs = new Array(5);
var msButtons = new Array(5); 
var msWrap;
var button;
var position;
var currPosition;

function initPageComponents() {
 /*  Used to load all components on the page */
 msDivs[0] = document.getElementById('mainStory1');
 msDivs[1] = document.getElementById('mainStory2');
 msDivs[2] = document.getElementById('mainStory3');
 msDivs[3] = document.getElementById('mainStory4');
 msDivs[4] = document.getElementById('mainStory5');
 msButtons[0] = document.getElementById('a1'); 
 msButtons[1] = document.getElementById('a2');
 msButtons[2] = document.getElementById('a3');
 msButtons[3] = document.getElementById('a4');
 msButtons[4] = document.getElementById('a5'); 
 msWrap = document.getElementById('mainStoryWrap');
 initPausePlayEvents();
 var breakingNews = document.getElementById('breakingNewsImg'); 
 if (breakingNews == null)
 {
  paused = false; 
  timer1=setTimeout('timedStory()',5000);
 }
   doImageSwap();
}

function initPausePlayEvents() {
 /* add Event Handlers for the Photo Module */
 if (!document.getElementById || !document.getElementsByTagName) {
  return true;
 }
 /* checks for Javascript operability  */ 

 /*  get all the links in the photo module  */
 var topStories = document.getElementById('topStories');
 var links = topStories.getElementsByTagName('a');

 for (i=0;i < links.length; i++) {
  if (links.item(i).id.substring(0,1) == 'a'){  
   //filter the links for those that have a class name beginnig with 'a'
   //add the doNumber event handler for the number links
   links.item(i).href='javascript:void(0)';
   tii_addEventHandler (links [i], 'click', function (event)
   {
    doNumber (event);
   }, false);
  }
 }
 
 var playLink = document.getElementById('playLink');
  
 //add the doButton event handler for the play pause button 
 tii_addEventHandler ( playLink , 'click', function (event)
 {
  doButton (event);
 }, false);
}

/* helper function to deal specifically with images and the cross-browser differences in opacity handling */
function fader(opac) {
 if (msWrap.style.MozOpacity!=null) {  
  /* Mozilla's pre-CSS3 proprietary rule */ 
  msWrap.style.MozOpacity = (opac/100) - .001;
 } else if (msWrap.style.opac!=null) {
  /* CSS3 compatible */
  msWrap.style.opacity = (opac/100) - .001;
 } else if (msWrap.style.filter!=null) {
  /* IE's proprietary filter */ 
 if (opac==100){
  msWrap.style.filter = "none;";
 } else {
            msWrap.style.filter = "alpha(opacity="+opac+");";
        }
 }
}

function change(num, step) {
 /*fadeOut*/
 if (step == 1) {
  opacity -= 10;
  if (opacity > 0) {
   fader(opacity);
   timer2=setTimeout('change(' + num + ', 1)',50);
  }
  else { 
   change(num, 2);
  }
 }
 /*change picture*/
 else if (step == 2) {
  currPic = num;
  msDivs[0].style.display = (num == 0 ? "block" : "none"); 
  msDivs[1].style.display = (num == 1 ? "block" : "none"); 
  msDivs[2].style.display = (num == 2 ? "block" : "none");
  msDivs[3].style.display = (num == 3 ? "block" : "none");
  msDivs[4].style.display = (num == 4 ? "block" : "none"); 
  msButtons[0].className = (num == 0 ? "on" : "off");
  msButtons[1].className = (num == 1 ? "on" : "off");
  msButtons[2].className = (num == 2 ? "on" : "off"); 
  msButtons[3].className = (num == 3 ? "on" : "off");
  msButtons[4].className = (num == 4 ? "on" : "off");
  change(num, 3);
 }
 /*fadeIn*/
 else if (step == 3) { 
  opacity += 10;
  if (opacity <= 100) {
   fader(opacity);
   timer2=setTimeout('change(' + num + ', 3)',50);
  }
 }
}

/* change picture, wait 5 seconds, repeat */
function timedStory() 
{
 if (currPic<4)
 {
     currPic++;
     change(currPic, 1);
     timer1=setTimeout('timedStory()',5000);
 }
 else
 {
    currPic=0;
    change(currPic, 1);
     timer1=setTimeout('timedStory()',5000);
     currPic++;

 }
}
/* executed when the play pause button is selected */
function doButton(event) {
 paused = !paused;
 doImageSwap();
 if (paused) {
  /* stop the image loop */
  clearTimeout(timer1);
 }
 else { 
  /* restart the image loop */
  timedStory();
 }
}  


/*executed when a number link is selected */
function doNumber (event) {
 var eventSource = typeof event.target != 'undefined' ? event.target : window.event.srcElement;
 /*  get the number portion of the class name of the event source */ 
 currPic = eventSource.id.substring(1,2) - 1;
 paused = true;
 doImageSwap();
 clearTimeout(timer1);
 clearTimeout(timer2);
 change(currPic, 1);

} 

/* swap the play pause button image */
function doImageSwap() {
		 var button = document.getElementById('playLink'); 
		 if (!tii_isie){
		  var imageFile = paused ? "images/btn_play.gif" : "images/btn_pause.gif";
		  button.style.background= "url("+imageFile+") 0px 0px no-repeat"; 	
		 }else{
		  /*  Use an image sprite to deplete the image flickering in IE */
		  button.style.backgroundImage= "url(/images/btn_playpause.gif)";
		  position = paused ? "-16 px" : "0 px";  /* c h a nge the image source */
		  try {
			  document.execCommand('BackgroundImageCache', false, true);
			} catch(e) {}
				
			  /* if paused and play is not displayed */
			  if (paused == true && currPosition != "-16 px"){
				  button.style.backgroundPositionY=position;
			  }
			  /* if playing and paused is not displayed */
			  if (paused != true && currPosition != "0 px"){
				  button.style.backgroundPositionY=position;			  
			 }  
		 currPosition = position;
		 }
}  
/* End Main story module */

/* Initialization and Unobtrusive Javascript Calls */
tii_callFunctionOnElementLoad('playLink', initPageComponents);
