// Javascript Document

//*********************************************************//
// Javascript Files found across the site
// In this file you will find:
// 0. AddLoad Event to substitute window.onload
// 1. Image Swap
// 2. Bookmark Script for Articles
// 3. Toggle script to show/hide elements using its ID
// 3a. Toggle script to show/hide 2 elements using its IDs
// 4. Star Rating System
// 5. Refresh Hot Topics list
// 6. Carousel of logos in the footer
//
//*********************************************************//

// 0. AddLoad Event to substitute window.onload
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
// END - AddLoad Event to substitute window.onload

// 1. Image Swap for all images inside an A element

//If the browser is W3 DOM compliant, execute setImageSwaps function
if (document.getElementsByTagName && document.getElementById) {
if (window.addEventListener) window.addEventListener('load', setImageSwaps, false);
else if (window.attachEvent) window.attachEvent('onload', setImageSwaps);
}
//When document loads, apply the prepareImageSwap function to various images with our desired settings
function setImageSwaps() {
prepareImageSwap(document.body);
//Note that once an image is processed, it won't be processed again, so you should set more specific images first, e.g. document.body, as it is the grand
//container, has to be processed last.
}
//The following is the function that do the actual job

function prepareImageSwap(elem,mouseOver,mouseOutRestore,mouseDown,mouseUpRestore,mouseOut,mouseUp) {
//Do not delete these comments.
//Non-Obtrusive Image Swap Script by Hesido.com
//V1.1
//Attribution required on all accounts
	if (typeof(elem) == 'string') elem = document.getElementById(elem);
	if (elem == null) return;
	var regg = /(.*)(-off\.)([^\.]{3,4})$/
	var prel = new Array(), img, imgList, imgsrc, mtchd;
	imgList = elem.getElementsByTagName('img');

	for (var i=0; img = imgList[i]; i++) {
		if (!img.rolloverSet && img.src.match(regg)) {
			mtchd = img.src.match(regg);
			img.hoverSRC = mtchd[1]+'-on.'+ mtchd[3];
			img.outSRC = img.src;
			if (typeof(mouseOver) != 'undefined') {
				img.hoverSRC = (mouseOver) ? mtchd[1]+'-on.'+ mtchd[3] : false;
				}
			if (img.hoverSRC) {preLoadImg(img.hoverSRC);}
			if (img.outSRC) {preLoadImg(img.outSRC);}
			img.rolloverSet = true;
		}
	}

	function preLoadImg(imgSrc) {
		prel[prel.length] = new Image(); prel[prel.length-1].src = imgSrc;
	}

}

function imgHoverSwap(imageId) {document.getElementById(imageId).src = document.getElementById(imageId).hoverSRC;}
function imgOutSwap(imageId) {document.getElementById(imageId).src = document.getElementById(imageId).outSRC;}
// END - Image Swap for all images inside an A element

// 2. Bookmark Script for Articles/Media
function Bookmark (siteName){
	var url="";
	var bookUrl=location.href;

	if (typeof bookmarkUrl != "null" && typeof bookmarkUrl != "undefined" && bookmarkUrl!="") {
		bookUrl=bookmarkUrl;
	}

	var w = 700; //This is the width of the window
	var h = 400; //This is the height of the window
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	winParameters = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+''

	if(siteName=="Facebook")
	{url="http://www.facebook.com/share.php?u="+bookUrl+"&title="+document.title;}
	else if(siteName=="Digg")
	{url="http://digg.com/submit?url="+bookUrl+"&title="+document.title;}
	else if(siteName=="StumbleUpon")
	{url="http://www.stumbleupon.com/submit?url="+bookUrl+"&title="+document.title;}
	else if(siteName=="Reddit")
	{url="http://reddit.com/submit?url="+bookUrl+"&title="+document.title;}
	else//Delicious
	{url="http://del.icio.us/post?v=4&noui&jump=close&url="+encodeURIComponent(bookUrl)+"&title="+encodeURIComponent(document.title);}

	window.open(url,siteName,winParameters);

}
// END - Bookmark Script for Articles

// 3. Toggle script to show or hide elements using its ID

function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

function toggle2(obj1,obj2) {
	var el1 = document.getElementById(obj1);
	var el2 = document.getElementById(obj2);
	if ( el1.style.display != 'none' ) {
		el1.style.display = 'none';
		el2.style.display = '';
	}
	else {
		el1.style.display = '';
		el2.style.display = 'none';
	}
}

// END - Toggle scripts to show or hide elements using its ID(s)

// 4. Star Rating System

var UT_RATING_IMG = '/images/icon-ratingStar-on.gif';
var UT_RATING_IMG_HOVER = '/images/icon-ratingStar-on.gif';
var UT_RATING_IMG_HALF = '/images/icon-ratingStar-on.gif';
var UT_RATING_IMG_BG = '/images/icon-ratingStar-off.gif';
var UT_RATING_IMG_REMOVED = '/images/icon-ratingStar-off.gif';

function UTRating(ratingElementId, maxStars, objectName, formName, ratingMessageId, componentSuffix, size, messages)
{
	this.ratingElementId = ratingElementId;
	this.maxStars = maxStars;
	this.objectName = objectName;
	this.formName = formName;
	this.ratingMessageId = ratingMessageId
	this.componentSuffix = componentSuffix
	this.messages = messages;
	this.starTimer = null;
	this.starCount = 0;
	if(size=='S') {
		UT_RATING_IMG      = '/images/icon-ratingStar-on.gif'
		UT_RATING_IMG_HALF = '/images/icon-ratingStar-on.gif'
		UT_RATING_IMG_BG   = '/images/icon-ratingStar-off.gif'
	}

	// pre-fetch image
	(new Image()).src = UT_RATING_IMG;
	(new Image()).src = UT_RATING_IMG_HALF;

	function showStars(starNum, skipMessageUpdate) {
		this.clearStarTimer();
		this.greyStars();
		this.colorStars(starNum);
		if(!skipMessageUpdate)
			this.setMessage(starNum, messages);
	}

	function setMessage(starNum) {
		// this is for info purposes -> messages = new Array("Rate This feature", "Not Funny", "Almost Funny", "Funny", "Funnier", "Funniest");
		document.getElementById(this.ratingMessageId).innerHTML = this.messages[starNum];
	}

	function colorStars(starNum) {
		for (var i=0; i < starNum; i++) {
			document.getElementById('star_'  + this.componentSuffix + "_" + (i+1)).src = UT_RATING_IMG;
		}
	}

	function greyStars() {
		for (var i=0; i < this.maxStars; i++)
			if (i <= this.starCount) {
				document.getElementById('star_' + this.componentSuffix + "_"  + (i+1)).src = UT_RATING_IMG_BG;
			}
			else
			{
				document.getElementById('star_' + this.componentSuffix + "_"  + (i+1)).src = UT_RATING_IMG_BG;
			}
	}

	function setStars(starNum) {
		this.starCount = starNum;
		this.drawStars(starNum);
		document.forms[this.formName]['rating'].value = this.starCount;
	}

	function drawStars(starNum, skipMessageUpdate) {
		this.starCount=starNum;
		this.showStars(starNum, skipMessageUpdate);
	}

	function clearStars() {
		this.starTimer = setTimeout(this.objectName + ".resetStars()", 300);
	}

	function resetStars() {
		this.clearStarTimer();
		if (this.starCount)
			this.drawStars(this.starCount);
		else
			this.greyStars();
		this.setMessage(0);
	}

	function clearStarTimer() {
		if (this.starTimer) {
			clearTimeout(this.starTimer);
			this.starTimer = null;
		}
	}
	this.clearStars = clearStars;
	this.clearStarTimer = clearStarTimer;
	this.greyStars = greyStars;
	this.colorStars = colorStars;
	this.resetStars = resetStars;
	this.setStars = setStars;
	this.drawStars = drawStars;
	this.showStars = showStars;
	this.setMessage = setMessage;
}


function resetRatingDivs() {

	if (document.getElementById('starRating')!=null) {
		document.getElementById("starRating").style.display='none';
	}

	if (document.getElementById('notRatedDiv')!=null) {
		document.getElementById("notRatedDiv").style.display='none';
	}
	if (document.getElementById('ratedDiv')!=null) {
		document.getElementById("ratedDiv").style.display='none';
	}

}

function populateRating(contentId,returnUrl,averageRating,userRating,voteCount) {

	if (contentId!='' && document.getElementById("starRating")!=null) {

		if (document.getElementById("averageRatingStars")!=null) {

			var averageStarsImage='/images/stars_0.gif';

			if (averageRating!='') {
				averageStarsImage='/images/stars_'+averageRating+'.gif';
			}


			document.getElementById("averageRatingStars").src=averageStarsImage;
		}

		if (document.getElementById("rateReturnUrl")!=null) {

			document.getElementById("rateReturnUrl").value=returnUrl;

		}

		if (document.getElementById("rateContentId")!=null) {

			document.getElementById("rateContentId").value=contentId;
		}

		if (userRating!='') {

			if (document.getElementById("ratingGiven")!=null) {
				document.getElementById("ratingGiven").value=messages[userRating];
			}

			if (document.getElementById("userRatingStars")!=null) {

				document.getElementById("userRatingStars").src='/images/stars_'+userRating+'.gif';

			}

			if (document.getElementById("rateThisOff")!=null) {

				document.getElementById("rateThisOff").style.display='none';
			}
		}

		document.getElementById("starRating").style.display='block';
                document.getElementById("voteCount").innerHTML = "(" + voteCount + " votes)";
	}
}

// END - Star Rating System

// BEGIN - AJAX-related functions to refresh content
function getXMLHttpObj() {
	var xmlHttp;
	try {
  	// Firefox, Opera 8.0+, Safari
  	xmlHttp=new XMLHttpRequest();
  	} catch (e) {
  	// Internet Explorer
  	try {
	    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
	    	try {
      			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      		} catch (e) {
      			alert("Your browser does not support AJAX!");
      			return false;
      		}
    	}
  	}
  	return xmlHttp;
}

function refreshHotTopics(index) {
	var xmlHttp = getXMLHttpObj();
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			if (xmlHttp.status == 200) {
                document.getElementById("theHotTopicModule").innerHTML=xmlHttp.responseText;
  			}
  		}
  	}
	xmlHttp.open("GET",'/content/refreshHotTopics.do?hotTopicsIndex='+index,true);
	xmlHttp.send(null);
}
// END - AJAX-related functions to refresh content

// 6. Carousel of logos for the footer

// This is the JS for the carousel of logos
var opacitySpeed = 2;	// Speed of opacity - switching between large images - Lower = faster
var opacitySteps = 10; 	// Also speed of opacity - Higher = faster
var slideSpeed = 5;	// Speed of thumbnail slide - Lower = faster
var slideSteps = 8;	// Also speed of thumbnail slide - Higher = faster
var columnsOfThumbnails = 6;	// Hardcoded number of thumbnail columns, use false if you want the script to figure it out dynamically. count also the last div which is empty.

var rdLogos_imageToShow = false;
var rdLogos_currentOpacity = 100;
var rdLogos_slideWidth = false;
var rdLogos_thumbTotalWidth = false;
var rdLogos_viewableWidth = false;
var currentUnqiueOpacityId = false;
var rdLogos_currentActiveImage = false;
var rdLogos_thumbDiv = false;
var rdLogos_thumbSlideInProgress = false;
var browserIsOpera = navigator.userAgent.indexOf('Opera')>=0?true:false;
var leftArrowObj;
var rightArrowObj;
var thumbsColIndex = 1;
var thumbsLeftPos = false;

function initGalleryScript()
{
	leftArrowObj = document.getElementById('btn-footer-arrow-left');
	leftArrowObj.style.visibility='hidden';
	rightArrowObj = document.getElementById('btn-footer-arrow-right');
	leftArrowObj.style.cursor = 'pointer';
	rightArrowObj.style.cursor = 'pointer';
	leftArrowObj.onclick = moveThumbnails;
	rightArrowObj.onclick = moveThumbnails;
	var innerDiv = document.getElementById('rdLogos_thumbs_inner');
	rdLogos_slideWidth = innerDiv.getElementsByTagName('DIV')[0].offsetWidth;
	rdLogos_thumbDiv = document.getElementById('rdLogos_thumbs_inner');
	rdLogos_thumbDiv.style.left = '0px';
	var subDivs = rdLogos_thumbDiv.getElementsByTagName('DIV');
	rdLogos_thumbTotalWidth = 0;
	var tmpLeft = 0;
	for(var no=0;no<subDivs.length;no++){
		if(subDivs[no].className=='strip_of_thumbnails'){
			rdLogos_thumbTotalWidth = rdLogos_thumbTotalWidth + rdLogos_slideWidth;
			subDivs[no].style.left = tmpLeft + 'px';
			subDivs[no].style.top = '0px';
			tmpLeft = tmpLeft + subDivs[no].offsetWidth;
		}
	}

	rdLogos_viewableWidth = document.getElementById('rdLogos_thumbs').offsetWidth;
}

function moveThumbnails()
{
	if(rdLogos_thumbSlideInProgress)return;
	rdLogos_thumbSlideInProgress = true;
	if(this.id=='btn-footer-arrow-left'){
		thumbsColIndex--;
		rightArrowObj.style.visibility='visible';
		if(rdLogos_thumbDiv.style.left.replace('px','')/1>=0){
			leftArrowObj.style.visibility='hidden';
			rdLogos_thumbSlideInProgress = false;
			return;
		}
		slideThumbs(slideSteps,0);
	}else{
		thumbsColIndex++;
		leftArrowObj.style.visibility='visible';
		var left = rdLogos_thumbDiv.style.left.replace('px','')/1;
		var showArrow = true;
		if(rdLogos_thumbTotalWidth + left - rdLogos_slideWidth <= rdLogos_viewableWidth)showArrow = false;
		if(columnsOfThumbnails)showArrow = true;
		if(!showArrow)
		{
			rightArrowObj.style.visibility='hidden';
			rdLogos_thumbSlideInProgress = false;
			return;
		}
		slideThumbs((slideSteps*-1),0);
	}
}

function slideThumbs(speed,currentPos)
{
	var leftPos;
	if(thumbsLeftPos){
		leftPos= thumbsLeftPos;
	}else{
		var leftPos = rdLogos_thumbDiv.style.left.replace('px','')/1;
		thumbsLeftPos = leftPos;
	}
	currentPos = currentPos + Math.abs(speed);
	var tmpLeftPos = leftPos;
	leftPos = leftPos + speed;
	thumbsLeftPos = leftPos;
	rdLogos_thumbDiv.style.left = leftPos + 'px';
	if(currentPos<rdLogos_slideWidth)setTimeout('slideThumbs(' + speed + ',' + currentPos + ')',slideSpeed);else{
		if(tmpLeftPos>=0 || (columnsOfThumbnails && thumbsColIndex==1)){
			document.getElementById('btn-footer-arrow-left').style.visibility='hidden';
		}
		var left = tmpLeftPos;
		var showArrow = true;
		if(rdLogos_thumbTotalWidth + left - rdLogos_slideWidth <= rdLogos_viewableWidth)showArrow=false;
		if(columnsOfThumbnails){
			if((thumbsColIndex+1)<columnsOfThumbnails)showArrow=true; else showArrow = false;
		}
		if(!showArrow){
			document.getElementById('btn-footer-arrow-right').style.visibility='hidden';
		}
		rdLogos_thumbSlideInProgress = false;
	}
}

// END - Carousel of logos for the footer
