/*******************************************************************
 * Create the global object for storing properties and methods.
 *******************************************************************/
var globalObj = {
	init:function(){
		//Startup methods
		globalObj.relEvents();
		globalObj.doSurvey();
		// enable drop down menu capability for GNS in IE6
		if (document.all && document.getElementById) {
			navRoot = document.getElementById("nav");
			
			for (i = 0; i < navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				
				if (node.nodeName == "LI") {
					node.onmouseover = function() {
						this.className += " over";
		  			}
		  			node.onmouseout = function() {
		 				this.className = this.className.replace(" over", "");
		  			}
				}
		  	}
		}		
	},
	relEvents:function(){
		var relType;
		var self = globalObj.relEvents;
		self.col = document.getElementsByTagName('a');
		duff(self.col, function(e){
			relType = e.getAttribute('rel');
			switch(relType){
				case 'external':
					//addEvent(e,"click",function(){return popup(this.href, 'popup', 'scrollbars=yes, menubar=yes, toolbar=yes, resizable=yes')});
					break;
				case 'footer':
					//addEvent(e,"click",function(){return popup(this.href, 'definitions', 'height=350,width=600, scrollbars=yes')});
					break;
				default:
					break;
			}
		});
	},
	doSurvey:function(){
		var isMoveInstalled = false;
		if ( navigator && navigator.plugins ) {
			if ( navigator.plugins.length > 0 ) {
				outer: for ( i = 0; i < navigator.plugins.length; i++ ) {
					inner: for ( i2 = 0; i2 < navigator.plugins[i].length; i2++ ) {
						var plugin = navigator.plugins[i][i2].type;
						if ( plugin.indexOf('movenetworks') != -1 || plugin.indexOf('moveplay') != -1 ) {
							isMoveInstalled = true;
							break outer;
						}
					}
				}
			} else {
				var ieTest = document.createElement('div');
				var ieTestId = '_qmpTempOCX';
				document.body.appendChild(ieTest);
				ieTest.innerHTML = '<OBJECT ID="' + ieTestId + '" style="width:0; height:0" CLASSID="CLSID:e3e02f12-2adb-478c-8742-5f0819f9f0f4"><PARAM name="VersionTest" value="0"></OBJECT>';
				var ieTestObj = document.getElementById(ieTestId);
				if ( ieTestObj && ieTestObj.Version ) {
					isMoveInstalled = true;
				}
				ieTest.innerHTML = '';
				document.body.removeChild(ieTest);
				ieTest = null;
			}
		}
		if ( isMoveInstalled ) {
			globalObj.track('PLUGINS_MOVE_INSTALLED');
		} else {
			globalObj.track('PLUGINS_MOVE_NOT_INSTALLED');
		}
	},
	track:function(name){
		if ( name && _hbLink ) {
			_hbLink(name);
		}
	}
}
addEvent(document, "readystatechange", globalObj.init);


/*******************************************************************
 * Content specific event handling functions.
 *******************************************************************/
 
//video player external opener
function launchApp(site, url, title) {
	if (!url)
		url = location.href;
	if (!title)
		title = document.title;
		
	switch (site){
		case "facebook":         
			url = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(url) + "&t=" + encodeURIComponent(title);
			break;
		case "digg":
			url = "http://digg.com/submit?phase=2&url=" + encodeURIComponent(url) + "&title=" + encodeURIComponent(title);
			break;
		case "del.icio.us":
			url = "http://del.icio.us/post?v=4;url=" + encodeURIComponent(url) + ";title=" + encodeURIComponent(title);
			break;
		default:
			break;
	}	
	window.open(url, "external", "scrollbars=1,width=700,height=500");
}

//changing tabs (movies, blog page)
function change_tab(activeId, inactiveId) {
	activeTab = document.getElementById(activeId + "tab");
	inactiveTab = document.getElementById(inactiveId + "tab");
	activeContent = document.getElementById(activeId + "content");
	inactiveContent = document.getElementById(inactiveId + "content");
	activePage = document.getElementById(activeId + "page");
	inactivePage = document.getElementById(inactiveId + "page");

	if (activeTab){	activeTab.getElementsByTagName('A')[0].className = "active"; }
	if (inactiveTab){ inactiveTab.getElementsByTagName('A')[0].className = ""; }

	if (activeContent){ activeContent.style.display = "block"; }
	if (inactiveContent){ inactiveContent.style.display = "none"; }

	if (activePage){ activePage.style.display = "block"; }
	if (inactivePage){ inactivePage.style.display = "none"; }
}

/* start show and hide panel */
function showPanel(id) {
	obj = document.getElementById(id);
	if (obj) {
		obj.style.display = "block";
	}			
	return obj;
}

function hidePanel(id) {
	obj = document.getElementById(id);
	if (obj) {
		obj.style.display = "none";
	}
	return obj;
}
/* end show and hide panel */

/*******************************************************************
 * Utility functions and general event handling functions.
 *******************************************************************/
function popup(href, name, specs) {
	// if the specs are not passed, assign the default parameters
	if (typeof specs != "string") specs = "";  // empty implies 'yes' to all
	var windowObj = window.open(href, name.replace(/-/g, ""), specs);
	windowObj.focus();
	return false;
}

function popupHtml(href, name, specs) {
	// if the specs are not passed, assign the default parameters
	if (typeof specs != "string") specs = "";  // empty implies 'yes' to all
	var windowObj = window.open(href, name.replace(/-/g, ""), specs);
	windowObj.focus();
}

function isPresent(param) {
	return typeof param != "undefined" && param != null;
}

function duff(objectArray, method) {
	var arrayLength = objectArray.length;
	var loopLength = arrayLength % 8;
	var index = 0;
	while (loopLength--) {
		method(objectArray[index++]);
	}
	loopLength = parseInt(arrayLength / 8);
	while (loopLength--) {
		method(objectArray[index++]);
		method(objectArray[index++]);
		method(objectArray[index++]);
		method(objectArray[index++]);
		method(objectArray[index++]);
		method(objectArray[index++]);
		method(objectArray[index++]);
		method(objectArray[index++]);
	}
}

// function used to get specified parent. requires obj and tagname of parent you wish to stop at
// example getParent(document.getElementById("foo"),"div")
// should be replaced with getAncestor()
function getParent(objT,stopAt) {
	return getAncestor(objT,stopAt);
}
	
function addEvent(element, type, handler) {
	if (isPresent(element.type) && element.type.indexOf("select-") == 0 ) {
		element["on" + type] = handler;
		return;
	}
	if (!handler.$$guid) handler.$$guid = addEvent.guid++;
	if ( !isPresent(element.events) ) element.events = new Object();
	var handlers = element.events[type];
	if (!handlers) {
		handlers = element.events[type] = new Object();
		handlers.order = new Array();
		if (element["on" + type] && (element != document || type != "readystatechange") ) {
			handlers[0] = element["on" + type];
			handlers.order[0] = 0;
		}
	}
	handlers[handler.$$guid] = handler;
	handlers.order[handlers.order.length] = handler.$$guid;
	if (element != document || type != "readystatechange") {
		element["on" + type] = handleEvent;
	}
}
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.events && element.events[type]) {
		var handlers = element.events[type];
		var id = handler.$$guid;
		if (delete handlers[handler.$$guid]) {
			for (var i = 0; i < handlers.order.length; i++) {
				if (handlers.order[i] == handler.$$guid) {
					var newOrder = handlers.order.slice(0, i);
					if (i + 1 != handlers.order.length) {
						newOrder = newOrder.concat( handlers.order.slice(i + 1) );
					}
					handlers.order = newOrder;
				}
			}
		}
	}
}

function handleEvent(event) {
	var returnValue = true;
	event = isPresent(event) ? event : isPresent(document.getElementById) ? fixEvent(window.event) : window.event;
	var handlers = this.events[event.type];
	var order = handlers.order;
	for (var i = 0; i < order.length; i++) {
		this.$$handleEvent = handlers[ order[i] ];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
}

function endOfPageScriptExists() {
	var scripts = document.getElementsByTagName("SCRIPT");
	if (scripts.length == 0) {
		return false;
	}
	var lastScript = scripts.item(scripts.length - 1);
	if (lastScript.childNodes.length > 0) {
		for (var i = 0; i < lastScript.childNodes.length; i++) {
			var currentNode = lastScript.childNodes.item(i);
			if (currentNode.nodeType == 3 && currentNode.nodeValue.indexOf("handleReadyStateChange()") != -1) {
				return true;
			}
		}
	}
	else {
		return lastScript.innerHTML.indexOf("handleReadyStateChange()") != -1;
	}
	return false;
}

window.intervalId = 0;

function handleReadyStateChange() {
	if (window.intervalId != 0) {
		if ( endOfPageScriptExists() ) {
			clearInterval(window.intervalId);
			window.intervalId = 0;
		}
		else {
			return;
		}
	}
	var event = new Object();
	event.readyState = "complete";
	event.srcElement = document;
	event.target = document;
	event.currentTarget = document;
	event.type = "readystatechange";
	if ( !isPresent(document.events) ) {
		document.Events = new Object();
		var dummyEvents = new Object();
		dummyEvents.readystatechange = dummyHandlers;
		document.events = dummyEvents;
	}
	if ( !isPresent(document.events.readystatechange) ) {
		var dummyHandlers = new Object();
		dummyHandlers.order = new Array();
		document.events.readystatechange = dummyHandlers;
	}
	document.$$handleEvent = handleEvent;
	document.$$handleEvent(event);
}

function fixEvent(event) {
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
}

fixEvent.preventDefault = function() {
	this.returnValue = false;
}

fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
}

//positioning the detail panel by referencing the parent div
function toggleDetailPanel(id, xPos, yPos) {
	objPanel = showPanel(id)
	x = findPosX(obj.parentNode);
	y = findPosY(obj.parentNode);
	objPanel.style.left = x + xPos + "px";
	objPanel.style.top = y + yPos + "px";
}	

/* start finding position X and Y */
function findPosX(obj){
	var curleft = 0;
	if(obj.offsetParent) {
		while(1) {
		  curleft += obj.offsetLeft;
		  if(!obj.offsetParent)
			break;
		  obj = obj.offsetParent;
		}
	} else if(obj.x) {
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj){
	var curtop = 0;
	if(obj.offsetParent){
		while(1){
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	} else if(obj.y) {
		curtop += obj.y;
	}
	return curtop;
}
/* end finding position X and Y */

/* start making request */
function makeRequest(url) {
	var httpRequest;

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType) {
			httpRequest.overrideMimeType('text/xml');
			// See note below about this line
		}
	} 
	else if (window.ActiveXObject) { // IE
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {}
		}
	}

	if (!httpRequest) {
		return false;
	}
	return httpRequest
}
/* end making request */

/* start pagination */
function pagination(id, page_number, page_size) {
	for (i=0; i < page_size; i++) {
		strId = id + (i+1);
		objPaging = document.getElementById(strId);
		if (objPaging != null){
			objPaging.style.display = 'none';
		}
		offloadButton(id, (i+1));
	}
	objCurrentPaging = document.getElementById(id + page_number);
	if (objCurrentPaging != null) {
		objCurrentPaging.style.display = 'block';
	}
	applyButton(id, page_number);
}

function applyButton(id, page_number) {
	obj = document.getElementById(id + 'page_' + page_number);
	if (obj != null) {
		obj.innerHTML = '<div class="buttn indicator"><div class="btnleft"><!--ie--></div><div class="btnmid">' 
						+ page_number
						+ '</div><div class="btnright"><!--ie--></div></div>';
		obj.className = "current";
	}
}

function offloadButton(id, page_number) {
	obj = document.getElementById(id + 'page_' + page_number);
	if (obj != null) {
		obj.innerHTML = page_number;
		obj.className = "paging";
	}
}
/* end pagination */

/*functions below pull the string value of a target div -- an alternative to innerHTML*/
ABCF = {
	flashContent: []

};

function getFeed(target) {
	return ABCF.flashContent[target];
}
function getHtml(target) {
	var target = getTarget(target);
	var result = '';
	for ( var e = 0; e < target.childNodes.length; e++ ) {
		var node = target.childNodes[e];
		if ( typeof(node.nodeName) == typeof('string') && node.nodeName.indexOf('#') == -1 ) {
			result += '<' + node.nodeName.toLowerCase();
			for ( var a = 0; a < node.attributes.length; a++ ) {
				var attribute = node.attributes[a];
				if ( attribute.nodeValue ) {
					var stripHtmlValue = attribute.nodeValue;
					
					if ( typeof(attribute.nodeValue) == typeof('string') ) {
						stripHtmlValue = stripText(attribute.nodeValue);
					}
					result += ' ' + attribute.nodeName.toLowerCase() + 
						'="' + stripHtmlValue + '"';
				}
			}
			result += '>';
		}
		if ( typeof(node.nodeValue) == typeof('string') ) {
			result += stripText(node.nodeValue);
		}
		result += getHtml(node);
		if ( typeof(node.nodeName) == typeof('string') && node.nodeName.indexOf('#') == -1 ) {
			result += '</' + node.nodeName.toLowerCase() + '>';
		}
	}
	return result;
}
function getTarget(target) {
	return typeof(target) == typeof('string') ? document.getElementById(target) : target;
}
function stripText(text) {
	return text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}


/**************************************************/

/* Generate Random ID for Video Player Modules    */

/**************************************************/

var id;
var isFirst = true;

function generateId() {		
	if (isFirst) {		
		isFirst = false;
		id = Math.round(Math.random() * 1000);
	}
	return id;
}


/**************************************************/

/* Get the location of the page                   */

/**************************************************/

function getLocation() {	
	return location.href;
}





/************************************************************************************/

/***** function to write out Flash embed block passed to it as string *****/

var addedFlashVars = "";

function writeFlash(theFlash, flashId){
	var targetId = 'fl' + flashId;
	var target = getTarget(targetId);
	if ( target ) {
		var html = getHtml(target);
		ABCF.flashContent[targetId] = html;
	}
	document.write(theFlash);
}
/**************************************************************************/

function getXML(args){
	var theXML = getFeed("fl"+args);
	return theXML;
}

/**************************************************************************/

function loadXMLDoc(url) {
    var req;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
		req = new XMLHttpRequest();
        } catch(e) {
		req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	if(req) {
		//req.onreadystatechange = processReqChange;
		req.open("GET", url, true);
		req.send("");
	}
}



function featuredPromoIndex(i) {
	if(i != 1) {		
		try {
			document.getElementById("featuredPromoExtras").style.display = "none";
			document.getElementById("featuredPromoExtras").style.marginTop = "-9999px";
		}
		catch(err) {

		}
		
	} else  {		
		try {
			document.getElementById("featuredPromoExtras").style.display = "block";
			document.getElementById("featuredPromoExtras").style.marginTop = "-61px";
	
		}
		catch(err) {

		}		
	}

}


/************************************************************************************/

/***** function to replace cms content with ad served content *****/

var adHtml;

function adToggle(isAd) {
	$(adDiv).children("div.countdown").html(" ");
	var showAd = '<a href="javascript:adToggle(true);">show ad</a>';
	var hideAd = '<a href="javascript:adToggle();">hide ad</a>';
	
	if (!isAd) {
		toggleMessage = showAd;
		$(adDiv).hide();
		$('#player').html("");
        	$(contentDiv).show();
	} else {
		toggleMessage = hideAd;
		$(contentDiv).hide();		
        	$('#player').html(playerObject);
        	$(adDiv).show();
	}
	$("#adDisplayToggle").html(toggleMessage);	
}

function detectAds(contentDiv, adDiv, isVideo) {
    var length = $(adDiv).children("div.ad_container").children().size();

    if (length > 0) {        
        $(contentDiv).hide();
        $(adDiv).show();
        
        if (!isVideo && delay > 0) {		
		adCountdown(delay);		
	}
    } else {
	$(contentDiv).show();
	$(adDiv).hide();
    }
}

function adCountdown(delay) {
    // countdown message to display
    var message = 'Your content will be displayed in ' + delay + ' seconds.';
	var getAdInit = '<a href="javascript:adToggle(adDiv,contentDiv)">show ad</a>';
	
    
    // adDiv should have a child div with class countdown
    $(adDiv).children("div.countdown").html(message);

    delay--;
    var timer = setTimeout('adCountdown(' + delay + ')', 1000);
    
    if (delay < 0) {
        clearTimeout(timer);
        $(adDiv).hide();
        $(contentDiv).show();
		$("#adDisplayToggle").html(getAdInit);
		
    }
}

function getScrollWidth()
	{
	   var w = window.pageXOffset ||
		   document.body.scrollLeft ||
		   document.documentElement.scrollLeft;
		   
	   return w ? w : 0;
	}

function getScrollHeight()
	{
	   var h = window.pageYOffset ||
		   document.body.scrollTop ||
		   document.documentElement.scrollTop;
		   
	   return h ? h : 0;
	}

function resizeClickDivs(){

		if (window.innerWidth) {
			document.getElementById("clickableLeft").style.width = ((window.innerWidth-1020)/2)+"px";
			document.getElementById("clickableLeft").style.height = (window.innerHeight)+"px";
			document.getElementById("clickableRight").style.width = ((window.innerWidth-1020)/2)+"px";
			document.getElementById("clickableRight").style.height = (window.innerHeight)+"px";
		}else if (document.all) {
			document.getElementById("clickableLeft").style.width = ((document.body.clientWidth-1020)/2)+"px";
			document.getElementById("clickableLeft").style.height = (document.body.clientHeight)+"px";
			document.getElementById("clickableRight").style.width = ((document.body.clientWidth-1020)/2)+"px";
			document.getElementById("clickableRight").style.height = (document.body.clientHeight)+"px";
		}

}

function gutterInit(){
			//adding empty function to catch body onLoad trigger in case reskin ad is not served
}

function gutterClickable(){
			document.getElementById("clickableLeft").onclick = goGutter;
			document.getElementById("clickableRight").onclick = goGutter;
			document.getElementById("clickableLeft").style.cursor = "pointer";
			document.getElementById("clickableRight").style.cursor = "pointer";
}
