
/* start lightbox global variables */
var lightBox;
var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;
/* end lightbox global variables */

if ((document.location.href.indexOf('/boxing/events/') > -1 || document.location.href.indexOf('/mma/events/') > -1)) {
	Event.observe(window, 'load', function(){ 
		IPUI.requires('common.base.demandlet');
		IPUI.requires('utils.url');
		IPUI.demandlet.load();
		IPUI.requires('utils.validate');
		if ($('main-nav')) {
			var dd = new DropDownMenu($$('#main-nav div.dropper'), $$('#main-nav')[0]);
		};
	});

} else {
	document.observe('dom:loaded', function(){
		IPUI.requires('common.base.demandlet');
		IPUI.requires('utils.url');
		IPUI.demandlet.load();
		IPUI.requires('utils.validate');
		if ($('main-nav')) {
			var dd = new DropDownMenu($$('#main-nav div.dropper'), $$('#main-nav')[0]);
		};
	});
	
}




/* *************************************************************
 this function sets constants for sport object id 
 the values as noted below should be edited only if related Object instance IDs have been changed
************************************************************** */ 

function getIdConstant(idName) {
	var constantIDobj = {}	
	constantIDobj =  {
		// the following values can be updated if Object Instance IDs have changed on Dev or Prod
		SportIdInfl_prod	: '3044',
		SportIdInfl_dev		: '6762',
		SportIdMma_prod		: '588',
		SportIdMma_dev		: '588',
		SportIdBoxing_prod	: '548',
		SportIdBoxing_dev	: '548'
		}
	
	if (window.location.href.indexOf('dev.sports.sho.com') > -1  || window.location.href.indexOf('192.168.72.7') > -1) {
        var keyNameAppend = '_dev';
	} else if ( window.location.href.indexOf('sports.sho.com') > -1 ){
		var keyNameAppend = '_prod';
	} else {
		var keyNameAppend = '_prod';
	}
	var objectID;
	switch (idName) {
		case 'mma':
			objectID = constantIDobj['SportIdMma' + keyNameAppend];			
			break;
		case 'boxing':
		    objectID = constantIDobj['SportIdBoxing' + keyNameAppend];
			break;
		case 'football':
			objectID = constantIDobj['SportIdInfl' + keyNameAppend];
			break;
	}
	return objectID
}

//Useful functions
function noCache(){return Math.random(0, 1000)+'='+Math.random(0,1000);};
function uniqueId(){return Math.random(0, 1000);};
function findPosY(obj) {
	var posTop = 0;
	while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
	return posTop;
};
function findPosX(obj) {
	var posLeft = 0;
	while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
	return posLeft;
};

//Get URL Parameters
function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
};


/*
 * xreader.js - by Chris Lam
 * another way to read text from xml data.
 * 
 */
var xreader = function (tag) {
	var ELEMENT_NODE = 1, ATTRIBUTE_NODE = 2, TEXT_NODE = 3, CDATA = 4;
	var _nodes, _map;
	
   	var _route = function (dest) {
		var r = [];
		while (dest.nodeName != _map.nodeName) {
			r.push(dest.nodeName);
			dest = dest.parentNode;
		}
		return r.reverse();
	};
	var _compare = function (r1, r2) {
		return r1.join('') == r2.join('');
	};
	var _find = function (target) {
		return _map.getElementsByTagName(target);
	};
	var _isElement = function (node) {
		return node.nodeType == ELEMENT_NODE;
	};
	var _load = function (node) {
		if (!_map) {
			_map = _isElement(node)?node:node.documentElement;
			_resetMap = _map;
		} else {
			_map = _isElement(node)?node:node.documentElement;
		}
	};
	var _reset = function () {
		_map = _resetMap;
	};
	if (tag) {
		_load(tag);
	}
	return {
		load: function (node) {
			if(node != null && typeof(node) != 'undefined')		_load(node);
			return this;
       	},
		reset: function () {
			_reset();
			return this;
		},
       	get: function (path) {
			
			var trip = path.split('.');
			var destination = trip[0]?trip[trip.length-1]:trip[1];
			var dests = _find(destination);
			this.clear();
			for (var i = 0; i < dests.length; ++i) {
				if (!trip[0]) {
					_nodes.push(dests[i]);
				
			    } else {
						var route = _route(dests[i]);
						if (_compare(trip, route)) {
							 _nodes.push(dests[i]);
						}
				}
			}
			return this;
       	},
       	text: function () {
			var tmp = [];
			for (var i = 0; i < _nodes.length; ++i) {
				var children = _nodes[i].childNodes;
				for (var j = 0; j < children.length; j++) {
					if (children[j] != null) {
						var child = children[j];
						tmp[i] =[CDATA,TEXT_NODE] .include(child.nodeType) ? child.nodeValue : null;
					}
					else {
						tmp[i] = null;
					}
				}
			}
			return tmp;
       	},
		nodes: function () {
			return _nodes.clone();
		},
       	clear: function () {
       		_nodes = [];
       	},
		checkNull:function(node){
			if(node.firstChild == null)return true
			if(node.firstChild.nodeValue == '' || typeof(node.firstChild.nodeValue) == 'undefined')return true;
			return false;
		}
	};
};


/*
 * requests.js - by Chris Lam
 * Takes a list of requests in hash data format,
 * and returns a hash of all reponses as a parameter in the 
 * supplied callback function. The returned hash uses the 
 * same keys listed in the original hash
 * 
 * Example: var uris = { 'data': '/ajax/data.xml', 'data1': '/ajax/data1.xml', ... };
 * requests(uris, callback);
 * 
 */
var requests = function (uris, params) {
	var timer, done = 0, cache = {}, keys = $H(uris).keys();
	var check = function () {
		if (done == keys.length) {
			clearInterval(timer); 
			params && params.callback(cache);
		}
	};
	keys.each(function (key) {
		new Ajax.Request(uris[key], {
			method: (params && params.method) || 'post',
			paramters: (params && params.parameters) || '',
			onSuccess: function (resp) { cache[key] = resp;	}, 
			onComplete: function (resp) { ++done; }
		});
	});
	timer = setInterval(check, 10);
};

/* popup window */
function newWindow(wURL,wName,wWidth,wHeight,wScroll,wResizable,wCentered){
	var settings = 'height='+wHeight+',width='+wWidth+'scrollbars='+wScroll+',resizable='+wResizable;
		if(wCentered==true){
			lPosition	= (screen.width) ? (screen.width-wWidth)/2 : 0;
			tPosition	= (screen.height) ? (screen.height-wHeight)/2 : 0;	
			settings	+= ',left=' + lPosition + ',top=' + tPosition;
		}
		var nWindow	= window.open(wURL,wName,settings);
		nWindow.focus();
	};

/* stylize radio and check boxes */
function fancyCheckBoxes() {
    var d = document;
	var safari = (navigator.userAgent.toLowerCase().indexOf('safari') != -1) ? true : false;
	var gebtn = function(parEl,child) { return parEl.getElementsByTagName(child); };
	
    if(!d.getElementById || !d.createTextNode) return;
    var ls = gebtn(d,'label');
    for (var i = 0; i < ls.length; i++) {
        var l = ls[i];
        if (l.className.indexOf('label_') == -1) continue;
        var inp = gebtn(l,'input')[0];
        if (l.className == 'label_check') {
            l.className = (safari && inp.checked == true || inp.checked) ? 'label_check c_on' : 'label_check c_off';
            l.onclick = check_it;
        };
        if (l.className == 'label_radio') {
            l.className = (safari && inp.checked == true || inp.checked) ? 'label_radio r_on' : 'label_radio r_off';
            l.onclick = turn_radio;
        };
    };
};
var check_it = function() {

var d = document;
var safari = (navigator.userAgent.toLowerCase().indexOf('safari') != -1) ? true : false;
var gebtn = function(parEl,child) { return parEl.getElementsByTagName(child); };
    var inp = gebtn(this,'input')[0];
    if (this.className == 'label_check c_off' || (!safari && inp.checked)) {
        this.className = 'label_check c_on';
        if (safari) inp.checked = true;
    } else {
        this.className = 'label_check c_off';
        if (safari) inp.checked = false;
    };
};
var turn_radio = function() {

var d = document;
var safari = (navigator.userAgent.toLowerCase().indexOf('safari') != -1) ? true : false;

var gebtn = function(parEl,child) { return parEl.getElementsByTagName(child); };
    var inp = gebtn(this,'input')[0];
    if (this.className == 'label_radio r_off' || inp.checked) {
        var ls = gebtn(this.parentNode,'label');
        for (var i = 0; i < ls.length; i++) {
            var l = ls[i];
            if (l.className.indexOf('label_radio') == -1)  continue;
            l.className = 'label_radio r_off';
        };
		this.getElementsByTagName('input')[0].checked=true;
        this.className = 'label_radio r_on';
        if (safari) inp.checked = true;
	} else {
        this.className = 'label_radio r_off';
        if (safari) inp.checked = false;
	};
	return false;
	
};

/*  JS for Styled Select Drop Downs
#############################################################
Name: Niceforms
Version: 1.0
Author: Lucian Slatineanu
URL: http://www.badboy.ro/

Feel free to use and modify but please provide credits.
#############################################################*/

//Global Variables
//var niceforms = document.getElementsByClassName('niceform'); 

/*
var inputs = new Array(); 
var labels = new Array(); 
var radios = new Array(); 
var radioLabels = new Array(); 
var checkboxes = new Array(); 
var checkboxLabels = new Array(); 
var texts = new Array(); 
var textareas = new Array(); 
*/ 

var theId = null;

var selects = new Array(); 
// commenting out default selected display
// var selectText = "please select"; 
var agt = navigator.userAgent.toLowerCase(); 
this.ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1)); 
var hovers = new Array(); var buttons = new Array(); 
var isMac = new RegExp('(^|)'+'Apple'+'(|$)');

//Theme Variables - edit these to match your theme
var selectRightSideWidth = 38;
var selectLeftSideWidth = 11;
var selectAreaHeight = 25;
var selectAreaOptionsOverlap = 2;
var imagesPath = "/media/global/";

//Initialization function - if you have any other 'onload' functions, add them here
function niceForms(demandletId, selectedText) {
	if(!document.getElementById) {return false;}
	replaceSelects(demandletId, selectedText);
}

//getting all the required elements
function getElements(demandletId) {
	var re = new RegExp('(^| )'+'niceform'+'( |$)');
	for (var nf = 0; nf < document.getElementsByClassName('niceform').length; nf++) {
		if (re.test(document.getElementsByClassName('niceform')[nf].className)) {
		/*
		for(var nfi = 0; nfi < document.forms[nf].getElementsByTagName('input').length; nfi++) {inputs.push(document.forms[nf].getElementsByTagName('input')[nfi]);}
		for(var nfl = 0; nfl < document.forms[nf].getElementsByTagName('label').length; nfl++) {labels.push(document.forms[nf].getElementsByTagName('label')[nfl]);}
		for(var nft = 0; nft < document.forms[nf].getElementsByTagName('textarea').length; nft++) {textareas.push(document.forms[nf].getElementsByTagName('textarea')[nft]);}
		*/
			for (var nfs = 0; nfs < document.getElementsByClassName('niceform')[nf].getElementsByTagName('select').length; nfs++) {
				selects.push(document.getElementById(demandletId).getElementsByClassName('niceform')[nf].getElementsByTagName('select')[nfs]);
			}
		}
	}
}

function replaceSelects(demandletId, selectedText) {
	var divId = parseInt(demandletId.split('_')[1]);
	
	// for(var q = 0; q < selects.length; q++) {
    	//create and build div structure
		var selectArea = document.createElement('div');
		var left = document.createElement('div');
		var right = document.createElement('div');
		var center = document.createElement('div');
		var button = document.createElement('a');
		// setting default selected Text with passed string or default below
		var firstText = (selectedText) ? selectedText : 'Please Select';
		var text = document.createTextNode(firstText);
		center.setAttribute('id','mySelectText'+divId)
		var selectWidth = parseInt($('mySelect'+demandletId).className.replace(/width_/g, ""));
		center.style.width = selectWidth - 10 + 'px';
		selectArea.style.width = selectWidth + selectRightSideWidth + selectLeftSideWidth + 'px';
		button.style.width = selectWidth + selectRightSideWidth + selectLeftSideWidth + 'px';
		button.style.marginLeft = - selectWidth - selectLeftSideWidth + 'px';
		button.href = "javascript:showOptions("+divId+")";
		button.className = "selectButton"; //class used to check for mouseover
		selectArea.className = "selectArea";
		selectArea.id = "sarea"+divId;
		left.className = "left";
		right.className = "right";
		center.className = "center";
		right.appendChild(button);
		center.appendChild(text);
		selectArea.appendChild(left);
		selectArea.appendChild(right);
		selectArea.appendChild(center);
		//hide the select field
        $('mySelect'+demandletId).style.display='none'; 
 
        //insert select div
		//selects[q].parentNode.insertBefore(selectArea, selects[q]);
		
		$('mySelect'+demandletId).parentNode.appendChild(selectArea);
				
		//build & place options div
		var optionsDiv = document.createElement('div');
		
		//hide the first div
		optionsDiv.style.width = selectWidth + 1 + 'px';
		optionsDiv.className = "optionsDivInvisible";
		
		optionsDiv.id = "optionsDiv"+divId;
		optionsDiv.setAttribute('id',"optionsDiv"+divId);		
		
		//optionsDiv.style.left = findPosX(selectArea) + 'px'; commented out because offset was incorrect
		optionsDiv.style.top = findPosY(selectArea) + selectAreaHeight - selectAreaOptionsOverlap + 'px';
		//get select's options and add to options div
		//selects[q].id = 'mySelect'+q.toString();
				
		for(var w = 0; w < $('mySelect'+demandletId).options.length; w++) {
			var optionHolder = document.createElement('p');
			var optionLink = document.createElement('a');
			var optionTxt = document.createTextNode($('mySelect'+demandletId).options[w].text);
			var text = $('mySelect'+demandletId).options[w].text;
	
			if ((w == 0) || (text.toLowerCase() == 'boxing') || (text.toLowerCase() == 'mixed martial arts')) {
				optionLink.href = "javascript:showOptions(" + divId + ");";
				//optionLink.href = "javascript:selectMe(" + divId + ","+demandletId+")";
			}else {
				optionLink.href = "javascript:window.location.href='" + $('mySelect'+demandletId).options[w].id + "'";
			}
			optionLink.appendChild(optionTxt);
			optionHolder.appendChild(optionLink);
			optionsDiv.appendChild(optionHolder);
			
			
			//check for pre-selected items
		
		   /*
			if($('mySelect'+demandletId).options[w].selected) {
			selectMe($('mySelect'+demandletId),w,divId);
			 }
			*/
		//}
		//divId++;
		//insert options div
		$(demandletId).appendChild(optionsDiv);
	}
}
function showOptions(g) {
		var elem = document.getElementById("optionsDiv"+g);
		var selectArea = $('sarea'+g);
				
		if(elem.className=="optionsDivInvisible") {
			elem.className = "optionsDivVisible";
		}else if(elem.className=="optionsDivVisible") {
			elem.className = "optionsDivInvisible";
		}
		elem.onmousemove = function(){
			this.className = 'optionsDivVisible';
		}
		elem.onmouseover = function(){
			this.className = 'optionsDivVisible';
		}
		elem.onmouseout = function(){
			this.className = 'optionsDivInvisible';
		}
		selectArea.onmouseout = function(){
			elem.className = 'optionsDivInvisible';
		};
		
		//Adjusting the height of the optionsDiv
		if(selectArea != null && elem != null){
			elem.style.top = findPosY(selectArea) + selectAreaHeight - selectAreaOptionsOverlap + 'px';		
		}
}
function hideOptions(e) { //hiding the options on mouseout
	
	if (!e) var e = window.event;
	var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
	if(((reltg.nodeName != 'A') && (reltg.nodeName != 'DIV')) || ((reltg.nodeName == 'A') && (reltg.className=="selectButton") && (reltg.nodeName != 'DIV'))) {this.className = "optionsDivInvisible";};			
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function selectMe(selectFieldId,linkNo,selectNo) {
	//feed selected option to the actual select field
	selectField = selectFieldId;
	//selectField = $('mySelect'+selectFieldId);
	for(var k = 0; k < $(selectField).options.length; k++) {
		if(k==linkNo) 
		{selectField.options[k].selected = "selected";}
		else {selectField.options[k].selected = "";}
	}
	
	//show selected option
	textVar = $("mySelectText"+selectNo);
	// IPUI.console({type: 'info', msg: (textVar)});

	var newText = document.createTextNode(selectField.options[linkNo].text);
	textVar.replaceChild(newText, textVar.childNodes[0]);

	
}
function selectEvent(e) {
	if (!e) var e = window.event;
	var thecode = e.keyCode;
	switch(thecode){
		case 40: //down
			
			var fieldId = this.parentNode.parentNode.id.replace(/sarea/g, "");
			var linkNo = 0;
			for(var q = 0; q < selects[fieldId].options.length; q++) {if(selects[fieldId].options[q].selected) {linkNo = q;}}
			++linkNo;
			if(linkNo >= selects[fieldId].options.length) {linkNo = 0;}
			selectMe(selects[fieldId].id, linkNo, fieldId);
			break;
		case 38: //up
			
			var fieldId = this.parentNode.parentNode.id.replace(/sarea/g, "");
			var linkNo = 0;
			for(var q = 0; q < selects[fieldId].options.length; q++) {if(selects[fieldId].options[q].selected) {linkNo = q;}}
			--linkNo;
			if(linkNo < 0) {linkNo = selects[fieldId].options.length - 1;}
			selectMe(selects[fieldId].id, linkNo, fieldId);
			break;
		default:
			break;
	}
}


// copied from ip_form.xml
	var dfltValue   = '**NO VALUE**';
	var dfltChars   = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.?-()[]+=_-;:/#@$%&!,*<>\"\'\n\r ';
	var dfltMethod  = 'POST';
	function checkForm(object){var response=true;for(var i=0;i<object.elements.length;i++){if(checkFormElement(object.elements[i])==false){response=false;break;}}return response;};
	
	function checkFormElement(elementObj,options) {
		this.options = {};
		Object.extend(this.options, options || {});
		var response = true;
		if(elementObj.attributes['id']) {
			theO		= $(elementObj);
			oType		= theO.type;
	        oName  		= theO.getAttribute('id');
			if(!elementObj.getAttribute('name')) {
				theO.setAttribute('name',oName);
			}
	        oValue 		= $F(theO);
			if(this.options.required=='true') {
				oReqd=true;
			}
			else {
				(theO.attributes["required"]) ? oReqd=true : oReqd=false;
			}
		   	(theO.attributes["alert"]) ? oAlert=theO.attributes['alert'].value : oAlert ='';
			(theO.attributes["highlight"]) ? oHighlight=theO.attributes['highlight'].value : oHighlight='';
	       	(theO.attributes["chars"]) ? oChars=theO.attributes['chars'].value : oChars=dfltChars;
	        (theO.attributes["editor"]) ? oEditor=true : oEditor=false;
	        (theO.attributes["parent"]) ? oParent=theO.attributes['parent'].value : oParent='';
			(theO.attributes["minLen"]) ? oMin=theO.attributes['minLen'].value : oMin=1;
	        (theO.attributes["maxLen"]) ? oMax=theO.attributes['maxLen'].value : oMax=500;
			if(oReqd==true||(document.getElementById(oParent)&&oParent!=''&&$(oParent).checked==true)||oAlert!='') {
	        	if(oEditor==true) {
					var tmpValue = getEditor(oName);
					if(tmpValue.length<oMin || tmpValue.length>oMax) {
						response=false;
						if(oHighlight!='') theO.className = oHighlight;
						if(oAlert!='') alert(oAlert);
					}
	        	}
				else if(oType.indexOf('select-single')>-1 && oValue=="") {
					response=false;
					if(oHighlight!='') {
						theO.addClassName(oHighlight);
					}
					if(oAlert!='') alert(oAlert);
				}
				else if(oType.indexOf('select-multiple')>-1) {
					if(oValue=='') {
						response=false;
						if(oHighlight!='') {
							theO.addClassName(oHighlight);
						}
						if(oAlert!='') alert(oAlert);
					}
					else {
						if(oValue.indexOf(',')>-1 && oMin>1) {}
					}
				}
	        	else {
		            if(oName.toLowerCase().indexOf('email')>-1) { 
		                if(isValidEmail(oValue)==false) {
		                	response=false;
							if(oHighlight!='') theO.addClassName(oHighlight);
							if(oAlert!='') alert(oAlert);
		                }
		             } 
		             else if(validate(oValue,oChars)==false||oValue.length<oMin||oValue.length>oMax) {
		             	response=false;
						if(oHighlight!='') {
							theO.addClassName(oHighlight);
						}
						if(oAlert!='') alert(oAlert);
		             }
		     	}
	        }
		}	
		return response;
	};

	function isValidEmail(string){if(string.length<1)return false;if(string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/)!=-1){return true;}else{return false;}};
	function validate(strVl,strChrs){if(!strVl) return false;if(strVl==dfltValue)return false;if(strVl.length<1)return false;if(!strChrs) strChrs=dfltChars;for(i=0;i<strVl.length;i++){if(strChrs.indexOf(strVl.charAt(i))==-1)return false;}return true;};	
	
// submit a question form
function submitQuestion(formObj,responseElem){
		if(!formObj) return false;
		var params = formObj.serialize(true);
		params.nc=noCache();
		//params.type='submitQuestionINFL';
		params.fromEmail='noreply@sports.sho.com';
		params.toEmail='questions@showtime.net, jkaminsky@ipartners.com';
		params.subject='Someone has submitted a question for Inside The NFL';
		if(checkForm(formObj)){		
			new Ajax.Request(
				'/ajax/sendEmail.jsp',{
				parameters: params,
				onComplete: function(xml){
					Element.hide(formObj);
					if(!xml.responseXML){
							responseElem.innerHTML = responseElem.innerHTML.replace('<!--response-->','Sorry there was a problem with your request. Please try again later.');
						} else responseElem.innerHTML = responseElem.innerHTML.replace('<!--response-->','<strong>Thank You.</strong><br />Your question has been successfully submitted.');
					Element.show(responseElem);
					}
				}
			);
		}
	};
	
// submit a question form
function submitQuestionWarren(formObj,responseElem){
		if(!formObj) return false;
		var params = formObj.serialize(true);
		params.nc=noCache();
		//params.type='submitQuestionINFL';
		params.fromEmail='noreply@sports.sho.com';
		params.toEmail='questions@showtime.net, jkaminsky@ipartners.com';
		params.subject='Someone has submitted a question for Warren Sapp';
		if(checkForm(formObj)){		
			new Ajax.Request(
				'/ajax/sendEmail.jsp',{
				parameters: params,
				onComplete: function(xml){
					Element.hide(formObj);
					if(!xml.responseXML){
							responseElem.innerHTML = responseElem.innerHTML.replace('<!--response-->','Sorry there was a problem with your request. Please try again later.');
						} else responseElem.innerHTML = responseElem.innerHTML.replace('<!--response-->','<strong>Thank You.</strong><br />Your question has been successfully submitted.');
					Element.show(responseElem);
					}
				}
			);
		}
	};

/*  Control.Scroller, version 1.1
 *  Copyright (c) 2008, Glenn Nilsson <glenn.nilsson@gmail.com>
 *
 *  Control.Scroller is distributed under the terms of an Creative Commons
 *  Attribution license. In short words, you can use this however you like
 *  as long as you give me and the code credit. Read more at:
 *  <http://creativecommons.org/licenses/by/2.5/>
 *
 *  Requirements: Prototype framework <http://prototype.conio.net/> and
 *  slider.js from <http://wiki.script.aculo.us/scriptaculous/show/Slider>
 *
 *  For details, see: <http://wailqill.com/projects/scroller/>
 *
 *--------------------------------------------------------------------------*/
Control.Scroller = Class.create();
Control.Scroller.scrollers = [];
Control.Scroller.prototype = {
	initialize: function(scrollcontent, handle, track, options) {
		this.id = "scroller"
		this.scrollcontent = $(scrollcontent);
		this.handle = $(handle);
		this.track = $(track);
		
		this.currentValue = 0;

		/* Slider-options */
		this.options = Object.extend({
			axis: 'vertical',
			onChange: function(value)  {
				self.updateView(value);
			},
			onSlide: function(value)  {
				self.updateView(value);
			}
		}, options);
		var self = this;
		/* Scroller-options */
		this.options = Object.extend({
			scrollOnHover: false,
			visibleHeight: this.isVertical() ? 235 : this.scrollcontent.offsetHeight,
			visibleWidth: this.isVertical() ? this.scrollcontent.offsetWidth : 280,
			delta: 20,
			autoHide: true,
			interval: 100
		}, this.options);
		
		this.maxValue = this.isVertical() ?
				this.scrollcontent.offsetHeight - this.options.visibleHeight - this.handle.offsetHeight :
				this.scrollcontent.offsetWidth - this.options.visibleWidth - this.handle.offsetWidth;
		this.options.range = $R(0, this.maxValue);

		this.buttons = {
			up: $(this.options.up),
			down: $(this.options.down)
		};

    // Ensure that the scroller is needed.
    //var children = $A(this.scrollcontent.childNodes);
		//var wrapper = this.scrollcontent.insert({top:new Element("div", { "class": "scroller-scrollcontent-wrapper" })});
		//children.each(function(child) {
		//  wrapper.insert(child);
		//});
    if ((this.isVertical() && this.scrollcontent.offsetHeight <= this.options.visibleHeight) || (!this.isVertical() && this.scrollcontent.offsetWidth <= this.options.visibleWidth)) {
		  if (this.options.autoHide)
		    [this.track, this.handle, this.buttons.up, this.buttons.down].invoke("hide");
		  return;
		}
		
		this.scrollcontent.style.height = this.options.visibleHeight+"px";
		
		this.eventMouseAction = this.buttonAction.bindAsEventListener(this);
   		$H(this.buttons).values().each(function(button) {
			if (self.options.scrollOnHover) {
				Event.observe(button, "mouseover", self.eventMouseAction);
				Event.observe(button, "mouseout", self.eventMouseAction);
			} else {
				Event.observe(button, "mousedown", self.eventMouseAction);
				Event.observe(button, "mouseup", self.eventMouseAction);
			}
		});
		this.slider = new Control.Slider(this.handle, this.track, this.options);
	},
	isVertical: function() {
		return this.options.axis == 'vertical';
	},
	buttonAction: function(e) {
		this.multiplier = Event.element(e) == this.buttons.up ? -1 : 1;
		switch (e.type) {
			case "mouseover":
			case "mousedown":
				this.scroll();
				var self = this;
				this.timer = setInterval(function() { self.scroll() }, self.options.interval);
				break;
			case "mouseout":
			case "mouseup":
				clearTimeout(this.timer)
				break;
		}
	},
	scroll: function() {
		this.slider.setValue(this.currentValue + this.options.delta * this.multiplier, 0);
	},
	updateView: function(value) {
		this.currentValue = value;
		if (this.options.axis == "vertical") {
			this.scrollcontent.style.marginTop = (-this.currentValue) + "px";
			this.scrollcontent.style.height = (this.options.visibleHeight+this.currentValue)+"px";
			this.scrollcontent.style.clip = 'rect('+value+'px '+this.options.visibleWidth+'px '+(this.options.visibleHeight+this.currentValue)+'px 0px)';
		} else {
			this.scrollcontent.style.marginLeft = (-this.currentValue) + "px";
			this.scrollcontent.style.clip = 'rect(0 '+(this.options.visibleHeight+this.currentValue)+'px '+this.options.visibleHeight+'px '+value+'px)';
		}
		(this.options.onScroll || Prototype.emptyFunction)(value, this);
	}
};

/*
 * @Class: DropDownMenu
 * 
 * @Description: A dropdown navigation menu with sliding animation.
 * 
 * @Usage: var dd = new DropDownMenu(list of dropdown elements, overall parent element with CSS class parameters);
 *	
 * @Methods: no public methods
 * 
 */

DropDownMenu = Class.create();
DropDownMenu.prototype = {

	dropDownDisabledCheck: function(){
		if(window['dropDownMenusDisabled']==true){
			this.springloaderDelay = 1;
			this.downDelay = 1;
			this.upDelay = 1;
			this.hoverOutDelay = 1;
		} else {
			this.downDelay = 570;
			this.upDelay = 450;
			this.springloaderDelay = 200;
			this.hoverOutDelay = 250;
		}
	},

	initialize: function(droppers,dropcontainer){
		// TODO make these parametric from dropcontainer's CSS class
		this.downDelay = 570;
		this.upDelay = 450;
		this.springloaderDelay = 200;
		this.hoverOutDelay = 250;
		this.dropDownDisabledCheck();
		
		// classname can be something like "dropper [otherstyle otherstyle otherstyle] INT INT INT .."
		this.dropperWidths = droppers.map(function(item){
			return item.classNames().toString().split(" ").select(function(token){
				return parseInt(token) > -1;
			})[0];
		});

		// calculate horizontal offset locations of each dropdown
		this.dropperOffsets = this.dropperWidths.inject([0],function(acc,item){
			acc.push(acc[acc.length - 1] + parseInt(item));
			return acc;
		});

		// fetch header height from the container's CSS class names
		var headerHeight = dropcontainer.classNames().toString().split(" ").select(function(token){
			return parseInt(token) > -1;
		})[0];

		this.iframesEnabled = false;
		this.droppers = droppers;
		this.dropperiFrames = [];
		this.hoverStates = [];
		this.states = [];
		this.visibilityInitialized = [];
		// there exists a "next action" for every given dropdown. This way we can queue the next state
		// that a dropdown wants to go to if a dropdown is too busy animating while we interrupt it
		// with another target state.
		this.nextAction = [];
		
		//	next actions are baskets in which a waiting action can drop in a closure to be executed after the current action
		for(var i=0;i<this.droppers.length;i++) { this.nextAction[i] = null; }

		//	we need to do some things to hide droppers
		for(var i=0;i<this.droppers.length;i++) { this.visibilityInitialized[i] = false; }

		//	states: closed, opening, open, closing, closed
		for(var i=0;i<this.droppers.length;i++) { this.states[i] = "closed"; }
		
		//	hover states: in, out
		for(var i=0;i<this.droppers.length;i++) { this.hoverStates[i] = "out"; }

		for(var i=0;i<this.droppers.length;i++){
			var dropper = this.droppers[i];

			//dropper.setStyle({'zIndex':800});

			var lis = dropper.getElementsBySelector('li');
			var hasItems = lis.length > 0;

			if(hasItems && this.iframesEnabled){

				var zfixIFrame = new Element("iframe",{
					'id':'floatMessageIFrame',
					'src':'javascr'+'ipt:\'<ht'+'ml></ht'+'ml>\''
				});
				zfixIFrame.frameBorder=0;
				zfixIFrame.setStyle({
					'backgroundColor':'#2e2e2e', // #2e2e2e
					'zIndex':795,
					'position':'absolute'
					// 'height':'0px'
				});

				var ul = $(lis[0].parentNode);
				ul.setStyle({
					'zIndex':805
				});

				zfixIFrame = dropper.appendChild(zfixIFrame);
				this.dropperiFrames[i] = zfixIFrame;
				// console.debug(this.dropperiFrames[i]);
			}

			//
			// Make two re-useable, cloneable handlers that fire when the mouse leaves or enters
			// either the dropper or the heading for each dropdown menu.
			//
			var mouseout = (function(dropdownDiv,dropperIndex,dropperHasItems){
				return function(ev){
					this.hoverStates[dropperIndex] = "out";
					setTimeout(function(){
						// if still hovering outside... go ahead and slide back up
						if(this.hoverStates[dropperIndex]=="out"){
							if(this.states[dropperIndex]=="open"){
								this.applyHoverClasses(dropdownDiv,"over","out");	// wrapper div
								this.applyHoverClasses(dropdownDiv.previous(),"over","out"); // heading
								this.doSlideUp(dropdownDiv,dropperIndex,dropperHasItems);
							} else if (this.states[dropperIndex]=="closing"){
								// reject mouse-out, already closing
							} else {
								// reject mouse-out, but queue up the next action
								// fill nextAction basket with a close action
								this.nextAction[dropperIndex] = function(){
									if(this.hoverStates[dropperIndex]=='out' && this.states[dropperIndex]=="open"){
										this.applyHoverClasses(dropdownDiv,"over","out");	// wrapper div
										this.applyHoverClasses(dropdownDiv.previous(),"over","out"); // heading
										this.doSlideUp(dropdownDiv,dropperIndex,dropperHasItems);
									}
								}.bind(this);
							}
						} else if (this.hoverStates[dropperIndex]=="in"){
							// reject a mouse-out, we're still hovering.
						}
					}.bind(this),this.hoverOutDelay);
				}.bind(this);
			}.bind(this))(dropper,i,hasItems);

			var mouseover = (function(dropdownDiv,dropperIndex,dropperHasItems){
				var dropperHasBeenInitialized = false;
				return function(ev){
					
					if(!dropperHasBeenInitialized){
						//
						// Set styles and calculate dropper heights on-demand
						//
						dropdownDiv.getElementsBySelector("ul").each(function(item){
							item.setStyle({'position':'absolute'});
						});

						if(dropperHasItems){
							var lis = dropdownDiv.getElementsBySelector("li");
							var totalHeight = 0;			
							for(var l=0;l<lis.length;l++){
								totalHeight += lis[l].getHeight();
							}
							dropdownDiv.setStyle({
								'position':'absolute',
								'top':headerHeight+"px",
								'left':this.dropperOffsets[dropperIndex]+"px",
								'width':this.dropperWidths[dropperIndex]+"px",
								'height':(totalHeight+5)+"px"
							});
							this.initializeDropperDisplay(dropdownDiv);
						}
						dropperHasBeenInitialized = true;
					}

					this.hoverStates[dropperIndex] = "in";
					// moused in over ev.target
					if(this.states[dropperIndex]=="closed"){
						setTimeout(function(){
							// Timed Springloader function: if we're still hovering over THIS menu, go ahead and fly out.
							if(this.hoverStates[dropperIndex]=="in"){
								this.applyHoverClasses(dropdownDiv,"out","over");	// wrapper div
								this.applyHoverClasses(dropdownDiv.previous(),"out","over");	// heading
								this.doSlideDown(dropdownDiv,dropperIndex,dropperHasItems);
							}
						}.bind(this),this.springloaderDelay);
					} else if (this.states[dropperIndex]=="closing"){
						//
						// moused in while already closing
						// queue up an opening nextAction IF we are the heading portion, not the dropper itself
						//
						if(ev.target!=dropdownDiv){
							// queue up next action to open up this dropdown
							this.nextAction[dropperIndex] = function(){
								if(this.hoverStates[dropperIndex]=='in' && this.states[dropperIndex]=="closed"){
									this.applyHoverClasses(dropdownDiv,"out","over");	// wrapper div
									this.applyHoverClasses(dropdownDiv.previous(),"out","over");	// heading
									this.doSlideDown(dropdownDiv,dropperIndex,dropperHasItems);
								}
							}.bind(this);
						} else {
							// reject mouse-in: ev.target was not the dropdowndiv, it was some other element
						}
					} else {
						// reject this mouse-in: not closed
					}
				}.bind(this);
			}.bind(this))(dropper,i,hasItems);

			Event.observe(dropper,'mouseover',mouseover);
			Event.observe(dropper.previous(),'mouseover',mouseover);
			// 
			Event.observe(dropper.previous(),'mouseout',mouseout);
			Event.observe(dropper,'mouseout',mouseout);
		}
	},
	
	// remove "removedClass" from the element
	// add "addedClass" to the element
	applyHoverClasses: function(element,removedClass,addedClass){
		element.removeClassName(removedClass);
		element.addClassName(addedClass);
	},

	initializeDropperDisplay: function(dropper){
		var ul = dropper.getElementsBySelector('ul')[0];
		var iframe = dropper.getElementsBySelector('iframe')[0];
		var ulHeight = ul.getHeight();
		ul.setStyle({'top':'-'+ulHeight+'px'});
		if(iframe){
			iframe.setStyle({'top':'-'+ulHeight+'px'});
			iframe.setStyle({'height':ulHeight+'px'});
		}
		dropper.setStyle({'height':'0px'});
	},
	
	// animate a given dropper sliding up
	doSlideUp: function(dropper,dropperIndex,dropperHasItems){
		this.dropDownDisabledCheck();
		if(!dropperHasItems || window['dropDownMenusDisabled']==true){ // if there are no items, don't waste time or CPU on transitions
			this.states[dropperIndex] = "closed";
			this.checkForNextAction(dropperIndex);
		} else {
			var iframe;
			if(this.iframesEnabled==true){
				iframe = dropper.getElementsBySelector("iframe")[0];
			}
			var ul = dropper.getElementsBySelector("ul")[0];
			var ulHeight = ul.getHeight();
			if(iframe && this.iframesEnabled==true){
				new Effect.Parallel([
					new Effect.Move(iframe,{
						'sync':true,
						'x':0,'y':-ulHeight,
						'mode':'absolute',
						'duration':this.upDelay/1000,
						'transition':Effect.Transitions.EaseFromTo
					}),
					new Effect.Move(ul,{
						'sync':true,
						'x':0,'y':-ulHeight,
						'mode':'absolute',
						'duration':this.upDelay/1000,
						'transition':Effect.Transitions.EaseFromTo,
						'beforeStart':function(effect){
							this.states[dropperIndex] = "closing";				
						}.bind(this),
						'afterFinish':function(effect){
							dropper.setStyle({'height':'0px'});
							this.states[dropperIndex] = "closed";
							this.checkForNextAction(dropperIndex);
						}.bind(this)
					})
				],{
					'duration':this.upDelay/1000				
				});
			} else {
				new Effect.Move(ul,{
					'x':0,'y':-ulHeight,
					'mode':'absolute',
					'duration':this.upDelay/1000,
					'transition':Effect.Transitions.EaseFromTo,
					'beforeStart':function(effect){
						this.states[dropperIndex] = "closing";				
					}.bind(this),
					'afterFinish':function(effect){
						dropper.setStyle({'height':'0px'});
						this.states[dropperIndex] = "closed";
						this.checkForNextAction(dropperIndex);
					}.bind(this)
				});
			}
		}
	},

	// animate a given dropper sliding down and out.
	doSlideDown: function(dropper,dropperIndex,dropperHasItems){
		this.dropDownDisabledCheck();
		if(!dropperHasItems || window['dropDownMenusDisabled']==true){ // if there are no items, don't waste time or CPU on transitions
			this.states[dropperIndex] = "open";
			this.checkForNextAction(dropperIndex);			
		} else {
			var iframe;
			if(this.iframesEnabled==true){
				iframe = dropper.getElementsBySelector("iframe")[0];
			}
			var ul = dropper.getElementsBySelector("ul")[0];
			var ulHeight = ul.getHeight();
			if(iframe && this.iframesEnabled==true){
				new Effect.Parallel([
					new Effect.Move(iframe,{
						'sync':true,
						'x':0,'y':0,
						'mode':'absolute',
						'transition':Effect.Transitions.EaseFromTo,
						'duration':this.downDelay/1000
					}),
					new Effect.Move(ul,{
						'sync':true,
						'x':0,'y':0,
						'mode':'absolute',
						'transition':Effect.Transitions.EaseFromTo,
						'duration':this.downDelay/1000,
						'beforeStart':function(effect){
							dropper.setStyle({'height':ulHeight+'px'});
							this.states[dropperIndex] = "opening";
							if(this.visibilityInitialized[dropperIndex]==false){
								this.visibilityInitialized[dropperIndex]=true;
								dropper.setStyle({'visibility':'visible'});
							}
						}.bind(this),
						'afterFinish':function(effect){
							this.states[dropperIndex] = "open";
							this.checkForNextAction(dropperIndex);
						}.bind(this)
					})
				],{
					'duration':this.downDelay/1000
				});
			} else {
				new Effect.Move(ul,{
					'x':0,'y':0,
					'mode':'absolute',
					'duration':this.downDelay/1000,
					'transition':Effect.Transitions.EaseFromTo,
					'beforeStart':function(effect){
						dropper.setStyle({'height':ulHeight+'px'});
						this.states[dropperIndex] = "opening";
						if(this.visibilityInitialized[dropperIndex]==false){
							this.visibilityInitialized[dropperIndex]=true;
							dropper.setStyle({'visibility':'visible'});
						}
					}.bind(this),
					'afterFinish':function(effect){
						this.states[dropperIndex] = "open";
						this.checkForNextAction(dropperIndex);
					}.bind(this)
				});
			}
		}
	},
	
	// check if a next action exists for a given dropdown menu (id'd by dropperIndex) and if so, execute it, then clear it.
	checkForNextAction: function(dropperIndex){
		if(this.nextAction[dropperIndex]!=null && typeof(this.nextAction[dropperIndex])=='function'){
			// perform the next action by calling it, then remove it from the next action basket
			this.nextAction[dropperIndex]();
			this.nextAction[dropperIndex] = false;
		} else {
			// no next action to do 
		}
	}
};

/*
transitions.js

Based on Easing Equations v2.0
(c) 2003 Robert Penner, all rights reserved. 
This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html

Adapted for Scriptaculous by Ken Snyder (kendsnyder ~at~ gmail ~dot~ com) June 2006
*/

/*
Overshooting Transitions
*/
// Elastic (adapted from "EaseOutElastic")
Effect.Transitions.Elastic = function(pos) {
	return -1*Math.pow(4,-8*pos) * Math.sin((pos*6-1)*(2*Math.PI)/2) + 1;
};
// SwingFromTo (adapted from "BackEaseInOut")
Effect.Transitions.SwingFromTo = function(pos) {
	var s = 1.70158;
	if ((pos/=0.5) < 1) return 0.5*(pos*pos*(((s*=(1.525))+1)*pos - s));
	return 0.5*((pos-=2)*pos*(((s*=(1.525))+1)*pos + s) + 2);
};
// SwingFrom (adapted from "BackEaseIn")
Effect.Transitions.SwingFrom = function(pos) {
	var s = 1.70158;
	return pos*pos*((s+1)*pos - s);
};
// SwingTo (adapted from "BackEaseOut")
Effect.Transitions.SwingTo = function(pos) {
	var s = 1.70158;
	return (pos-=1)*pos*((s+1)*pos + s) + 1;
};

/*
Bouncing Transitions
*/
// Bounce (adapted from "EaseOutBounce")
Effect.Transitions.Bounce = function(pos) {
	if (pos < (1/2.75)) {
		return (7.5625*pos*pos);
	} else if (pos < (2/2.75)) {
		return (7.5625*(pos-=(1.5/2.75))*pos + .75);
	} else if (pos < (2.5/2.75)) {
		return (7.5625*(pos-=(2.25/2.75))*pos + .9375);
	} else {
		return (7.5625*(pos-=(2.625/2.75))*pos + .984375);
	}
};
// BouncePast (new creation based on "EaseOutBounce")
Effect.Transitions.BouncePast = function(pos) {
	if (pos < (1/2.75)) {
		return (7.5625*pos*pos);
	} else if (pos < (2/2.75)) {
		return 2 - (7.5625*(pos-=(1.5/2.75))*pos + .75);
	} else if (pos < (2.5/2.75)) {
		return 2 - (7.5625*(pos-=(2.25/2.75))*pos + .9375);
	} else {
		return 2 - (7.5625*(pos-=(2.625/2.75))*pos + .984375);
	}
};

/*
Gradual Transitions
*/
// EaseFromTo (adapted from "Quart.EaseInOut")
Effect.Transitions.EaseFromTo = function(pos) {
	if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,4);
	return -0.5 * ((pos-=2)*Math.pow(pos,3) - 2);    
};
// EaseFrom (adapted from "Quart.EaseIn")
Effect.Transitions.EaseFrom = function(pos) {
	return Math.pow(pos,4);
};
// EaseTo (adapted from "Quart.EaseOut")
Effect.Transitions.EaseTo = function(pos) {
	return Math.pow(pos,0.25);
};

// disabled for change to all static pages
/*
function headerLinks() {
	var header = $('header');
	var li = new Element('a', { href: 'http://www.sho.com/site/order/nfloffer.do?source=acq_shocom_infl', target: 'blank' }).update("Order Showtime");
	header.getElementsByTagName('li')[5].update(li);
};
*/
/*
 *   Start LightBox for ReminderPopups
 */

	/*
	Created By: Chris Campbell
	Website: http://particletree.com
	Date: 2/1/2006
	Inspired by the lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
	*/	
	//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/
	

	
	function getBrowserInfo() {
		if (checkIt('konqueror')) {
			browser = "Konqueror";
			OS = "Linux";
		}
		else if (checkIt('safari')) browser 	= "Safari";
		else if (checkIt('omniweb')) browser 	= "OmniWeb";
		else if (checkIt('opera')) browser 		= "Opera";
		else if (checkIt('webtv')) browser 		= "WebTV";
		else if (checkIt('icab')) browser 		= "iCab";
		else if (checkIt('msie')) browser 		= "Internet Explorer";
		else if (!checkIt('compatible')) { 
			browser = "Netscape Navigator";
			version = detect.charAt(8);
		}
		else browser = "An unknown browser";
	
		if (!version) version = detect.charAt(place + thestring.length);
	
		if (!OS) {
			if (checkIt('linux')) OS 		= "Linux";
			else if (checkIt('x11')) OS 	= "Unix";
			else if (checkIt('mac')) OS 	= "Mac";
			else if (checkIt('win')) OS 	= "Windows";
			else OS 						= "an unknown operating system";
		}
	};
	
	function checkIt(string) {
		place = detect.indexOf(string) + 1;
		thestring = string;
		return place;
	};
	
	/*-----------------------------------------------------------------------------------------------*/
	Event.unloadCache = Prototype.emptyFunction 
	Event.observe(window, 'load', initialize, false);
	Event.observe(window, 'load', getBrowserInfo, false);
	Event.observe(window, 'unload', Event.unloadCache, false);
	
	var lightbox = Class.create();
	
	lightbox.prototype = {
		yPos : 0,
		xPos : 0,
		
		
		initialize: function(ctrl, params) {
		
			if (ctrl) {			
				//console.info(ctrl);
				this.content = ctrl.href;
				this.params = {};
				this.elem = ctrl;
				this.activateRef = this.activate.bindAsEventListener(this);
				if (ctrl.lbEvtQueue == undefined) {
					ctrl.lbEvtQueue = [this.activateRef];
				} else {
					ctrl.lbEvtQueue.push(this.activateRef);
				}
				if (ctrl.onclick) {	this.oldonclick = ctrl.onclick;	}
				Object.extend(this.params, params || {});
				Event.observe(ctrl, 'click', this.activateRef, false);
				ctrl.onclick = function(){return false;};
			}
			// Inert code
			//else function(){return false;}
	},
		
		// Turn everything on - mainly the IE fixes
		activate: function(event) {
			if (browser == 'Internet Explorer'&& navigator.appVersion.substr(22,3) == "6.0") {
				this.getScroll();
				this.prepareIE('100%', 'hidden');
				this.prepareIE('100%', 'hidden');
				this.setScroll(0,0);
				this.hideSelects('hidden');
			}
			this.displayLightbox("block");
		},
		
		// Ie requires height to 100% and overflow hidden or else you can scroll down past the lightbox
		prepareIE: function(height, overflow) {
			bod = document.getElementsByTagName('body')[0];
			bod.style.height = height;
			bod.style.overflow = overflow;
			htm = document.getElementsByTagName('html')[0];
			htm.style.height = height;
			htm.style.overflow = overflow; 
		},
		
		// In IE, select elements hover on top of the lightbox
		hideSelects: function(visibility) {
			selects = document.getElementsByTagName('select');
			for(i = 0; i < selects.length; i++) {
				selects[i].style.visibility = visibility;
			}
		},
		
		// Taken from lightbox implementation found at http://www.huddletogether.com/projects/lightbox/
		getScroll: function() {
			if (self.pageYOffset) {
				this.yPos = self.pageYOffset;
			} else if (document.documentElement && document.documentElement.scrollTop){
				this.yPos = document.documentElement.scrollTop; 
			} else if (document.body) {
				this.yPos = document.body.scrollTop;
			}
		},
		
		setScroll: function(x, y) {
			window.scrollTo(x, y); 
		},
		
		displayLightbox: function(display) {
			$('overlay').style.display = display;
			if (!this.params.nodisplay || display == 'none') {
				if (display == 'none') {
					$('lightbox').style.top = null;
					$('lightbox').style.left = null;
					$('lightbox').style.width = null;
					$('lightbox').style.height = null;
				}
				$('lightbox').style.display = display;
			}
			if (this.params.nodisplay && display == 'block') {
				centerElem($('lightbox'));
				$('lightbox').style.display = 'block'; 
			}
			if (!this.params.noOverlayClick && display != 'none') {
				$('overlay').className = 'lbAction';
				$('overlay').rel = 'deactivate';
			}
			if (this.params.noOverlayClick) {
				$('overlay').className = '';
				$('overlay').rel = null;
				$('overlay').onclick = null;
			}
			if (display != 'none' && !this.params.noAjax) {
				this.loadInfo();
			}		
		},
		
		// Begin Ajax request based off of the href of the clicked linked
		loadInfo: function() {
			var myAjax = new Ajax.Request( this.content,
	        	{method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)});
		},
		
		// Display Ajax response and Close Button
		processInfo: function(response) {
			if (this.params.nodisplay) $('lightbox').style.display = 'none';
			if ($('lbContent')) Element.remove($('lbContent'));
			info = "<div id='lbContent'>"+response.responseText+"</div>";
			if (screen.height <= 600) {
				var tmp = document.createElement('div');
				tmp.innerHTML = info;
				var close = $(tmp).getElementsByClassName('close')[0];
				close.next().addClassName('win800x600');
				
				//DEV HERE
				$('lightbox').style.left = '50%';
				info = tmp.innerHTML;
			}
			new Insertion.Before($('lbLoadMessage'), info);
			$('lightbox').className = "done";
			if (this.params.oncomplete) { this.params.oncomplete(); }
			this.actions();			
		},
		
		// Search through new links within the lightbox, and attach click event
		actions: function() {
			lbActions = $$('.lbAction');
			for(i = 0; i < lbActions.length; i++) {
				if (lbActions[i].id == 'overlay') {
					lbActions[i].onclick = this[lbActions[i].rel].bindAsEventListener(this);
				} else {
					Event.observe(lbActions[i], 'mousedown', this[lbActions[i].rel].bindAsEventListener(this), false);
					lbActions[i].onclick = function(){return false;};
					//alert('hit');
				}
			}
	
		},
		
		// Example of creating your own functionality once lightbox is initiated
		insert: function(e) {
		   var link = Event.element(e).parentNode;
		   Element.remove($('lbContent'));
		 
		   var myAjax = new Ajax.Request(
				  link.href,
				  {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
		   );
		 
		},
		
		// Example of creating your own functionality once lightbox is initiated
		deactivate: function(e) {
			//alert('deactivate hit');
			if ($('lbContent')) Element.remove($('lbContent'));
			if (browser == "Internet Explorer" && navigator.appVersion.substr(22,3) == "6.0"){
				this.setScroll(0,this.yPos);
				this.prepareIE("auto", "auto");
				this.hideSelects("visible");
			}
			this.displayLightbox("none");
			$('lightbox').className = 'loading';
		},
		
		removeListener: function (restoreOld) {
			Event.stopObserving(this.elem, 'click', this.activateRef, false);
			if (restoreOld && this.oldonclick) {
				this.elem.onclick = this.oldonclick;
			}
		},
		
		flush: function () {
			while (this.elem.lbEvtQueue.length) {
				Event.stopObserving(this.elem, 'click', this.elem.lbEvtQueue.shift(), false);
			}
		}
	};
	/*-----------------------------------------------------------------------------------------------*/
	//kill lightbox
	function closeLightBox() {
		if(lightBox) lightBox.deactivate();
	};
	
	// Onload, make all links that need to trigger a lightbox active
	function initialize(){
		addLightboxMarkup(); 
		lbox = document.getElementsByClassName('lbOn');
		for(i = 0; i < lbox.length; i++) {
			valid = new lightbox(lbox[i]);
		}
	};
	
	// Add in markup necessary to make this work. Basically two divs:
	// Overlay holds the shadow
	// Lightbox is the centered square that the content is put into.
	function addLightboxMarkup() {
		bod 				= document.getElementsByTagName('body')[0];
		overlay 			= document.createElement('div');
		overlay.id		= 'overlay';	
		lb					= document.createElement('div');
		lb.id				= 'lightbox';
		lb.className 	= 'loading';
		lb.innerHTML	= '<div id="lbLoadMessage">' +
							  '<p>Loading</p>' +
							  '</div>';
		bod.appendChild(overlay);
		bod.appendChild(lb);
	};
	// ************** end of lightbox ************** //
	
	
	function submit_Reminder(formObj, id, hideDivObj,showDivObj){
		
		if(checkForm(formObj)){
			var params = formObj.serialize();
			var currentemail = (params.split('=')[1]).replace('%40', '@');
			if (IPUI.validate.isValidEmail(currentemail) == true) {
				new Ajax.Request('/ajax/scheduleReminder.jsp', {
					// add no cache?
					parameters: 'save=0&scheduleid=' +id + '&'+params+'&hours=24&timezone=GMT',  
					onSuccess: function(xml){
						var response 	= xml.responseXML.getElementsByTagName('response')[0];
							//var responseContent = showDivObj.innerHTML;
							if (response.childNodes[0].nodeValue == '0') {
								Element.hide(hideDivObj);
								Element.show(showDivObj);
							}
							else {
								///showDivObj.style.background = 'black';
								Element.hide(hideDivObj);
								Element.show(showDivObj);
								//remove styles out of below and add to css
								showDivObj.style.background = 'black';
								showDivObj.style.border = '1px solid #fff';
								showDivObj.innerHTML = '<p style="color: #fff; margin: 25px;">Sorry there was a problem with your request.<br />Please try again later.</p><a style="background: transparent url(/media/global/reminder-close-btn.gif) repeat scroll 0%; width: 76px; height: 25px; text-indent: -9999px; margin: 20px; cursor: pointer; display: block;" onclick="closeLightBox()" id="close-btn">close</a>';
							}
					
					}
				});
			} else if (IPUI.validate.isValidEmail(currentemail) == false){
				var emailAlert = new Element('span');
				emailAlert.innerHTML = 'Please Enter A Valid Email Address';
				emailAlert.style.color = 'red';
				$('reminderform-emailtext').innerHTML= ''
				$('reminderform-emailtext').appendChild(emailAlert);
			return; 
			}
			
		}
	};
	
//Omniture Tracking Code. 
//There were conflicts with pages using swfobject1.5 in IE not being tracked propely.
//Fixed it by placing function call from html document because ir needed to load before swfobject.
function setOmniture(){
	var urlData = IPUI.url.info(window.location.href);
	var path = IPUI.general.replace(urlData.directoryPath,'/',':');
	var pathParts = path.split(':');

	
	// path = ':';
	for (var i=0; i< (pathParts.length-1); i++) {
		if (i == 0) {
			path = ':';
		} else if ( i == (pathParts.length-1)) {
			path = path;
		} else {
			path += pathParts[i].capitalize() + ':';  
		}
	}
	
	if(urlData.fileName == ''){
		var fileName = 'index';
	}else{
		var fileExtension = '.'+urlData.fileName.split('.')[1];
		if(fileExtension){
			var fileName = IPUI.general.replace(urlData.fileName,fileExtension,'');	
		} else {
			var fileName = urlData.fileName;
		}
	}

	//set omniture
	s.server = '';
	s.channel = '';
	s.pageName='Sports'+path+''+fileName.capitalize();
	s.hier1 = s.pageName;
	s.prop1= 'sports';
	s.prop2= s.hier1.split(':')[1] ? s.hier1.split(':')[1] : '';
	s.prop3= s.hier1.split(':')[2] ? s.hier1.split(':')[2] : '';
	s.prop4= s.hier1.split(':')[3] ? s.hier1.split(':')[3] : '';
	
	//video-portal
	if( (s.hier1.split(':')[2] == 'Video-portal') || (s.hier1.split(':')[2] == 'Video-portal-infl') ){
		var videoId = getQuerystring('id');
		fileName = 'Videos';
		s.pageName='Sports'+ path +''+fileName+':'+videoId;
		s.hier1 = s.pageName;			
		s.prop3 = fileName;
		s.prop4 = videoId;
	}
	var s_code=s.t();if(s_code)document.write(s_code)
};


