
var AUTH_COOKIE_NAME = "VEOH_GUIDE_AUTH";
var VEOH_COOKIE = "veohCookie";
var RECAPTCHA_PUBLIC_KEY = "6LcgyQAAAAAAAOcV5HwRlHcP2Z_SEJ4HDmPaiBJL";
var SRC_RECS = 0;
var SRC_MOST_POPULAR = 1;
var targetingInfo = "";

//ad stuff
var defaultAdHeight = 250;
var defaultAdWidth = 300;
var ad_pcategory = '';		
var timePassed = 0;

//Code that controls the communication with the spudts retrivieing information from the 
	function getShareObjectsCats(){
	    timePassed += 100; 
		var cat = document.getElementById('spudts');
		if (cat && cat['hasDataLoaded']&& cat.hasDataLoaded()){	
			getCatsSpudTS();
		}else if (timePassed < 1000) { 
			setTimeout("getShareObjectsCats()",100);
		} else { 
			fallback(); 
		}
	}	
	if(window.attachEvent) {
		window.attachEvent("onload", getShareObjectsCats);
	} else {
		window.addEventListener("load", getShareObjectsCats, false);
	}

	function fallback(){ 
		ad_pcategory = "pcategory=;";
		postLoadAds(); 
	}
	//setTimeout('fallback()',1000);  
	function getCatsSpudTS(){ 
		var dcTagsArr = '';
		var cat = document.getElementById('spudts');
		cats =  cat.getCategory();
		cats = cats.replace("[", ""); 
		cats = cats.replace("]","");
		dcTagsArr = cats.split(","); 
		for (i=0; i < dcTagsArr.length; i++) {
			ad_pcategory += 'pcategory='+encodeURIComponent(trim(dcTagsArr[i]))+';';	
		}
		postLoadAds();
	}
	
function getAuthToken()
{
	return getCookie( AUTH_COOKIE_NAME );
}

function toggleDisplay2(targetId) {
    if (document.getElementById(targetId)) {
        target = document.getElementById(targetId);
    	if (target.style.display == "" || target.style.display == "block") {
    		target.style.display = "none";
    	} else {
    		target.style.display = "";
    	}
    }
}

function submitForm ( formObj )
{
  formObj.submit();
}

function checkAll(theForm) { // check all the checkboxes in the list
  for (var i=0;i<theForm.elements.length;i++) {
    var e = theForm.elements[i];
		var eName = e.name;
    	if (eName != 'allbox' && 
            (e.type.indexOf("checkbox") == 0)) {
        	e.checked = theForm.allbox.checked;		
		}
	} 
}

/*  This function is to select all options in a multi-valued <select> */
function selectAll(elementId) {
    var element = document.getElementById(elementId);
	len = element.length;
	if (len != 0) {
		for (i = 0; i < len; i++) {
			element.options[i].selected = true;
		}
	}
}

/* This function is used to set cookies */
function setCookie(name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "=" 
	var start = document.cookie.indexOf(prefix) 

	if (start==-1) {
		return null;
	}
	
	var end = document.cookie.indexOf(";", start+prefix.length) 
	if (end==-1) {
		end=document.cookie.length;
	}

	var value=document.cookie.substring(start+prefix.length, end) 
	return unescape(value);
}

/* This function is used to delete cookies */
function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function visitorUID(){ 
	var cookie = getCookie(VEOH_COOKIE);
	if(cookie != null){
	 		cookie = cookie.replace(/"/g, '');
			var expires = new Date();
	    	expires.setTime(expires.getTime() + (24 * 365 * 60 * 60 * 1000)); // sets it for approx 1 year.
	    	//This is a fix for the bug when we keep appending firstVisit tag to the cookie
	    	var arr = cookie.split("&");	
	    	return arr[0]; 
		}
}

// This function is for stripping leading and trailing spaces
function trim(str) { 
    if (str != null) {
        var i; 
        for (i=0; i<str.length; i++) {
            if (str.charAt(i)!=" ") {
                str=str.substring(i,str.length); 
                break;
            } 
        } 
    
        for (i=str.length-1; i>=0; i--) {
            if (str.charAt(i)!=" ") {
                str=str.substring(0,i+1); 
                break;
            } 
        } 
        
        if (str.charAt(0)==" ") {
            return ""; 
        } else {
            return str; 
        }
    }
} 

function confirmDelete(obj) {   
    var msg = "Are you sure you want to delete this " + obj + "?";
    ans = confirm(msg);
    if (ans) {
        return true;
    } else {
        return false;
    }
}

function disableSubmit(submit)
{
	frm.submit.disabled = 1;
}

/*
 Next two functions are for selecting permalink text
*/
function selectText( strField )
{
	document.getElementById( strField ).select();
}

function getKey(e, textId)
{
	var evtObj;
	
	if(window.event)
	{
		evtObj = window.event;
	}
	else
	{
		evtObj = e;
	}
	
	//If Crtl+C is pressed allow it
	if(evtObj.keyCode == 67 || evtObj.keyCode == 99 || evtObj.keyCode == 84 
		|| evtObj.keyCode == 116 || evtObj.keyCode == 78 || evtObj.keyCode == 110)
	{
		if(evtObj.ctrlKey)
		{
			return true;
		}
	}
	else
	{
		return false;
	}
}

// Show the document's title on the status bar
window.defaultStatus=document.title;


var IFrameObj; // our IFrame object
function callToServer( url ) 
{
	if( !document.createElement ) 
	{
		return true
	};

	var IFrameDoc;
	if( !IFrameObj && document.createElement ) 
	{
		// create the IFrame and assign a reference to the
		// object to our global variable IFrameObj.
		// this will only happen the first time 
		// callToServer() is called
		try 
		{
			var tempIFrame=document.createElement( 'iframe' );
			tempIFrame.setAttribute( 'id', 'RSIFrame' );
			tempIFrame.style.border = '0px';
			tempIFrame.style.width = '0px';
			tempIFrame.style.height = '0px';
			IFrameObj = document.body.appendChild(tempIFrame);
			
			if( document.frames ) 
			{
				// this is for IE5 Mac, because it will only
				// allow access to the document object
				// of the IFrame if we access it through
				// the document.frames array
				IFrameObj = document.frames[ 'RSIFrame' ];
			}
		}catch( exception ) 
		{
			// This is for IE5 PC, which does not allow dynamic creation
			// and manipulation of an iframe object. Instead, we'll fake
			// it up by creating our own objects.
			iframeHTML = '\<iframe id="RSIFrame" style="';
			iframeHTML += 'border:0px;';
			iframeHTML += 'width:0px;';
			iframeHTML += 'height:0px;';
			iframeHTML += '"><\/iframe>';
			
			document.body.innerHTML += iframeHTML;
			
			IFrameObj = new Object();
			IFrameObj.document = new Object();
			IFrameObj.document.location = new Object();
			IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
			
			IFrameObj.document.location.replace = function(location) 
			{
				this.iframe.src = location;
			}
		}
	}
  
	if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) 
	{
		// we have to give NS6 a fraction of a second
		// to recognize the new IFrame
		setTimeout('callToServer( ' + url + ' )',10);
		return false;
	}
  
  	try
  	{
		if( IFrameObj.contentDocument ) 
		{
			// For NS6
			IFrameDoc = IFrameObj.contentDocument; 
		}
		else if( IFrameObj.contentWindow ) 
		{
			// For IE5.5 and IE6
			IFrameDoc = IFrameObj.contentWindow.document;
		} 
		else if( IFrameObj.document ) 
		{
			// For IE5
			IFrameDoc = IFrameObj.document;
		} 
		else 
		{
			return true;
		}
	}catch( exception )
	{
	}
	
	try
	{
		IFrameDoc.location.replace( url );
	}catch( exception )
	{
	}
	
	return false;
}

function checkIfEmailBad(theString)
{
	var regexPattern = /([a-zA-Z0-9_-]+)\@([a-zA-Z0-9_-]+)\.(([a-zA-Z0-9_-]+)(?![;,\n]))/;
	
	//If it doesn't fit the pattern it was bad
	if(!regexPattern.test(theString))
	{
		return true;
	}
	
// Else it was good
return false;
}


function checkEnter(e){ //e is event object passed from function invocation
	var characterCode; //literal character code will be stored in this variable
	
	if(e && e.which)
	{ 	//if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	}
	else{		
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}
	
	if(characterCode == 13)
	{ 
		return true;
	}
	else
	{
		return false;
	}	

}



// Drop Down Menus

function showDrop(id) {
	var d = document.getElementById(id);
	if (d) {
		if(d.nodeName.toLowerCase()=="div" && d.parentNode != document.body) {
			/* menu UL is wrapped in a DIV, meant to be reparented to <body> to cover flash ads/dropdowns/etc */
			document.body.appendChild(d.parentNode.removeChild(d));
		}
		d._isMouseOver=true;
		d.style.display='block';
	}
}

function hideDrop(id) {
	var d = document.getElementById(id);
	if (d) {
		d._isMouseOver=false;
		setTimeout(function() {
			var d = document.getElementById(id);
			if(d && !d._isMouseOver) {
				d.style.display='none';
			}
			d=null;
		}, 500);
		d=null;
	}
}



function showSMenu(i) {
	var mainID = 'topnav_' + i;
	var mainE = document.getElementById(mainID);
	if (mainE) {
		newID = mainID + 'hover';
		mainE.id = newID;
	}
	showDrop(i + '_drop');
}

function hideSMenu(i) {
	var mainID = 'topnav_' + i;
	var mainE = document.getElementById(mainID + 'hover');
	if (mainE) {
		mainE.id = mainID;
	}
	hideDrop(i + '_drop');
}

// toggle visibility for search options
function toggleSearch(targetId) {
    if (document.getElementById(targetId)) {
        target = document.getElementById(targetId);
		targetList = target.getElementsByTagName('li');
		for (i=0; i < targetList.length; i++) {
			if (targetList[i].style.display == "none"){
				targetList[i].style.display = "block";
			} else {
				targetList[i].style.display = "none";
			}
		}		
    }
}
function switchSearch(id, type) {
	switch(type)
	{  
	case 's':
	case 'c':
		setSearchTypeCookie('c');
		document.getElementById(id).type.value='c';
		if(document.getElementById(id).query.value == 'Search Videos'  || 
			document.getElementById(id).query.value == 'Search People' ||
			document.getElementById(id).query.value == 'Search Groups' ||
			document.getElementById(id).query.value == '')
		{
			document.getElementById(id).query.value = 'Search Channels'; 
		}
		else{
			//selectText('query');
		}
		
		document.getElementById('searchVideos').className='';
		document.getElementById('searchChannels').className='selected';
		document.getElementById('searchPeople').className='';
		document.getElementById('searchGroups').className='';
		break;
	case 'u':
		setSearchTypeCookie('u');
		document.getElementById(id).type.value='u';
		if(document.getElementById(id).query.value == 'Search Videos' || 
			document.getElementById(id).query.value == 'Search Channels' ||
			document.getElementById(id).query.value == 'Search Groups' ||
			document.getElementById(id).query.value == '')
		{
			document.getElementById(id).query.value = 'Search People'; 
		}
		else{
			//selectText('query');
		}
		
		document.getElementById('searchVideos').className='';
		document.getElementById('searchChannels').className='';
		document.getElementById('searchPeople').className='selected';
		document.getElementById('searchGroups').className='';
		break;
	case 'g':
		setSearchTypeCookie('g');
		document.getElementById(id).type.value='g';
		if(document.getElementById(id).query.value == 'Search Videos' || 
			document.getElementById(id).query.value == 'Search Channels' ||
			document.getElementById(id).query.value == 'Search People' ||
			document.getElementById(id).query.value == '')
		{
			document.getElementById(id).query.value = 'Search Groups'; 
		}
		else{
			//selectText('query');
		}
		
		document.getElementById('searchVideos').className='';
		document.getElementById('searchChannels').className='';
		document.getElementById('searchPeople').className='';
		document.getElementById('searchGroups').className='selected';
		break;
	default:
		setSearchTypeCookie('');
		document.getElementById(id).type.value='';
		if(document.getElementById(id).query.value == 'Search Channels' || 
			document.getElementById(id).query.value == 'Search People' ||
			document.getElementById(id).query.value == 'Search Groups' ||
			document.getElementById(id).query.value == '')
		{
			document.getElementById(id).query.value = 'Search Videos'; 
		}
		else{
			//selectText('query');
		}
	
		document.getElementById('searchVideos').className='selected';
		document.getElementById('searchChannels').className='';
		document.getElementById('searchPeople').className='';
		document.getElementById('searchGroups').className='';
		break;
	}
}

function fieldClear(id) {
	if(document.getElementById(id).query.value == 'Search Videos' || 
		document.getElementById(id).query.value == 'Search Channels' || 
		document.getElementById(id).query.value == 'Search People' ||
		document.getElementById(id).query.value == 'Search Groups')
	{
		document.getElementById(id).query.value = ''; 
	}
	else{
		selectText('query');
	}
}

/* Facebook - general*/
function sendToFacebook() {
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}


/* Not interested buttons for rec */
function updatedNotInterestedCookie(type, videoId)
{
	var expires = new Date();
	var value = "";
    expires.setTime(expires.getTime() + (24 * 30 * 60 * 60 * 1000)); // sets it for approx 1 month.

    var cookieName = 'notInterested' + type;
    
    if (getCookie(cookieName) != null) 
	{
		value = getCookie(cookieName) + ',' + videoId;
    } 
    else 
    {
    	value = videoId;
    }
 
    setCookie(cookieName,value,expires,"/", "www.veoh.com", 0);
}

function setTargetingInfo(str){
	targetingInfo = str;
}

/* Will be called from flash player, passed to adMgr */
function getUserTargetingInfo(){
	return getUcatCookiePcat() + targetingInfo;
}

// Will be called to parse pcategory key/vals to DC 
function getUcatCookiePcat() {
	var ad_pcategory = '';
	var dcTagsArr = '';
	var cookieValue = getUcatCookie();
	dcTagsArr = cookieValue.split(',');

	if (dcTagsArr.length > 0) {
		for (i=0; i < dcTagsArr.length; i++) {
			ad_pcategory += 'pcategory='+encodeURIComponent(trim(dcTagsArr[i]))+';';
		} 
	}
	else{
		ad_pcategory += 'pcategory='+encodeURIComponent(trim(cookieValue))+';';
	}
	return ad_pcategory;
}

function getUcatCookie() {
	var dcTags='';
	var spudTS_Cookie_Values = eval( "(" + getCookie('spudTS') + ")"); 

	if(spudTS_Cookie_Values)
	{
		try{
			spudTS_Cookie_Values = 	spudTS_Cookie_Values.evalJSON();
			if (spudTS_Cookie_Values.pcategory.length > 2 && spudTS_Cookie_Values.pcategory != null) {
				dcTags = spudTS_Cookie_Values.pcategory.substr(1,(spudTS_Cookie_Values.pcategory.length - 2));
			} 
		}catch(exception){}
	}
	
	return dcTags;
}

/* This function is used to get cookies */
function getCookieValue(key) {
	var keyToCheck = key;
	var cookieValue = getCookie(VEOH_COOKIE);
	if (cookieValue) {
		var cookieValueStripped = cookieValue.substr(1,(cookieValue.length - 1));
		var cookieArray = cookieValueStripped.split("&");
		for (i=0; i < cookieArray.length; i++) {
			var array2 = cookieArray[0].split("=");
			if (array2.length == 2) {
				var key = array2[0];
				if (key == keyToCheck) {
					returnValue = array2[1];
					break;
				}
			}
		}
	return returnValue;
	}
	return '';
}

function getCookies () { 
	var spudts = document.getElementById('spudts');
	if ( spudts ) { 
		spudts.setCookies ( document.cookie );
	}
}

function saveUserEmail()
{
	document.getElementById('newsletterSignupText').innerHTML = '';
	var email = document.getElementById('newsletterSignup').value;
	if ( !checkIfEmailBad(email) )
	{
		ajaxMethodHandler.saveUserEmail( saveEmailResponse, email );
	}
	else
	{
		document.getElementById('newsletterSignupText').innerHTML = 'Please provide a valid email address';
	}
}

function saveEmailResponse( model )
{
	if ( model['error'] != null )
	{
		//show error
		document.getElementById('newsletterSignupText').innerHTML = model['error'];
	}
	else
	{
		document.getElementById('newsletterSignupText').innerHTML = 'Email Saved';
	}
}
//setSearchTypeCookie();
function setSearchTypeCookie( value )
{
	var cookieValue = value;
    var expires = new Date();
    expires.setTime(expires.getTime() + (24 * 60 * 60 * 1000)); // sets it for approx 1 day.
   	setCookie('veohSearchTypeCookie',cookieValue,expires,"/", "www.veoh.com", 0);	
}


// for logo swap in nav
// define image files and give the filenames

/*img1     = new Image(150,56);
img1.src = "http://ll-appserver.veoh.com/images/topnav_logo_mouseout.gif";
img2     = new Image(150,56);
img2.src = "http://ll-appserver.veoh.com/images/topnav_logo_mouseover.gif";

img3     = new Image(70,25);
img3.src = "http://ll-appserver.veoh.com/images/miniNav/mininav_logo_mouseout.jpg";
img4     = new Image(70,25);
img4.src = "http://ll-appserver.veoh.com/images/miniNav/mininav_logo_mouseover.jpg";
*/

// change image

function changeimage(imgx,placex)  { 
    if (document.images) { 
        document.images[placex].src = eval(imgx + ".src");
    }
}



//--------- ad rotation ------------//



/**
 * updates the Ad iframe with provided URL while preserving 'back' button functionality;
 * deletes and recreates iframe with new URL and inserts new iframe into document
 *
 * @param	DOM Object, String	iframeHandle	DOM id of iframe to be updated
 * @param	String				url				new URL of ad iframe
 * @return	DOM Element							new instance of ad iframe with provided url
 */
function updateAdIframeUrl(iframeHandle, url)
{
	//first, make sure we have a valid iframe / iframe id
	if(!iframeHandle) {
		return false;
	}
	//acquire valid handle on iframe to be updated...
	var adIframe = typeof iframeHandle == "string" ? document.getElementById(iframeHandle) : iframeHandle;
	//...and make sure iframe to be updated exists in document
	if(!adIframe){
		return false;
	}
	
	var iframeId = adIframe.id;
	
	//now, make sure we have a valid handle and new URL for the iframe to be updated
	if( (!(adIframe)) || (url == '') ) {
		return false;
	}
	
	//acquire the ad iframe's height and width
	var originalHeight = adIframe.height;
	if(originalHeight < 10 && originalHeight > 1){
		originalHeight = defaultAdHeight;
	}
	var originalWidth = adIframe.width;
	if(originalWidth < 10){
		originalWidth = defaultAdWidth;
	}
		
	
	//try to get a handle for the iframe's container element (we will need this to reinsert the iframe into the document)
	var iframeParent = adIframe.parentNode;

	//now, remove the iframe from the document
	removeAdIframe(adIframe);
	
	//then, recreate the iframe with the provided url
	var newIframe = createAdIframe(iframeId, url, originalWidth, originalHeight);
	
	//now, insert the newly-created iframe into the container element
	return insertAdIframe(newIframe, iframeParent);
}


//removes ad iframe with given iframeId
function removeAdIframe(adIframe)
{
	//first, get a handle for the existing ad iframe in order to remove it
	var oldIframe = typeof adIframe == "string" ? document.getElementById(adIframe) : adIframe;
	if(!oldIframe){
		return false;
	}
	//remove the iframe to clear the browser history for the iframe (to preserve proper 'back' button functionality)
	oldIframe.parentNode.removeChild(oldIframe);

	return true;

}


//inserts specified ad iframe into the specified parent element
function insertAdIframe(adIframe, iframeParent)
{
	//first, make sure we have a valid iframe and parent...
	if(adIframe && iframeParent){
		//...and if so, go ahead and insert the newly-created iframe into the parent element of the previous iframe
		iframeParent.appendChild(adIframe);
		return adIframe;
	}
	else{
		return false;
	}
}



//creates and returns a new Ad Iframe with the src property set to url, or to 'about:blank' if no url is defined
function createAdIframe(iframeId, url, width, height)
{
	//first, make sure we have a valid id for the new iframe
	if(iframeId == null){
		return false;
	}
	//then, make sure we have a valid url for the new iframe
	if(url == '') {
		url = 'about:blank';
	}
	
	//create new iframe element
	var newIframe = document.createElement("iframe");
	
	//set iframe attributes...
	newIframe.id = iframeId;
	newIframe.name = iframeId;
	newIframe.src = url;
	
	newIframe.height = height;
	newIframe.width = width;
	newIframe.scrolling = "no";
	newIframe.frameBorder = "0"; newIframe.setAttribute("frameborder", "0");
	newIframe.align = "middle";
	newIframe.marginHeight = "0"; newIframe.setAttribute("marginheight", "0");
	newIframe.marginWidth = "0"; newIframe.setAttribute("marginwidth", "0");
	//...and styles
	newIframe.style.border = "none";
	newIframe.style.borderWidth = "0px";
	newIframe.style.zIndex = "3";

	return newIframe;
					
}

function postLoadAds() {
	setTimeout(
		function() {
			if(window["refreshAd"]) {
				refreshAd();
				return;
			}
			for(var i = 1; i<5; i++) {
				var adI = document.getElementById("postLoadedAd" + i);
				if(adI && adI.getAttribute("postLoadSrc") && adI.getAttribute("postLoadSrc").length > 0) {
					updateAdIframeUrl(adI, adI.getAttribute("postLoadSrc"));
					adI.removeAttribute("postLoadSrc");
				}
			}
		}, 
	250);
}
/*
function loadAds(){ 
	if(window.attachEvent) {
		window.attachEvent("onload", postLoadAds);
	} else {
		window.addEventListener("load", postLoadAds, false);
	}
}*/
//--------- end ad rotation ------------//




// stage6
function trackStage6(){
	try{
		var STAGE6_COOKIE = 'stage6';
		var cookie = getCookie(STAGE6_COOKIE);
		if(cookie != null){
			var arr = cookie.split("&");
			var dateCreated = "";
			var st = "";
			
			if(arr.length == 2){
				var temp = arr[0].split("=");
				if(temp.length == 2)
					{st = temp[1];}
				temp = arr[1].split("=");
				if(temp.length == 2)
					{dateCreated = temp[1];}
			}
			//log if it's within 7 days of dateCreated
			if(dateCreated != '' && st == 1){
				var today = new Date();
			    var todayUTC = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate(), today.getHours(),today.getMinutes(), today.getSeconds()) ;
				var diff = parseInt(todayUTC - dateCreated);
	 			if(diff >= 0 && diff <= 518400000){
	 				logAjaxResponse("Stage6", "/");	
	 				var newdate = new Date(parseInt(dateCreated));
	 				newdate.setTime(newdate.getTime() + (24 * 60 * 60 *  90 * 1000)); // sets it for approx 90 days.
	 				newCookieValue = cookie.replace("st=1&", "st=0&");
	 				
 					document.cookie =  STAGE6_COOKIE + "=" + newCookieValue + 
                      "; expires=" + newdate +
                      "; path=/";
	 				//setCookie(STAGE6_COOKIE,newCookieValue,newdate,"/", "www.veoh.com", 0);
	 			}
	 			
			}
		}
	}
	catch(exception){}
}

function actionAddFriend() {
	if (window.location.search.match('action=addFriend'))
	{
		document.addFriendForm.submit();
	}
}

function actionBlock() {
	if (window.location.search.match('action=block'))
	{
		document.blockUserForm.submit();
	}
}


/*
 * Makes the AJAX request to retrieve response for recommendations
 * @param permalinks - a string of one or more peramlinkIds, delimited by ','
 * @param contentRatingId - current content filter settings (optional)
 * @param maxResults - defaults to 100 on the server (optional)
 * @param callback - function that will accept the response object and do something with it
 * @param callBackupIfFails - a boolean that determine to get backup results if you don't get any recommendations
 * @returns array of video nodes with the first array item indicating source (default/rec), or false for failure
 */
function callRecs(permalinks, contentRatingId, maxResults, callback, callBackupIfFails, source, recVal, rId) {

	//var url = 'http://www.veoh.com/rest/v2/execute.xml?method=veoh.search.search&apiKey=EB90631D-1C20-3962-39F5-75D7C7F698C8&type=video&maxResults=100&query=%2Bid:(v1578723zrDsgbMD%20v1603781JsRbkshh%20v16461539J6YhX3p%20v16473127Wee4PDw%20v1645100dqYKZFSQ)';
	//var url = 'http://www.veoh.com/rest/v2/execute.xml?method=veoh.search.search&type=video&query='+ recVal + '&contentRatingId=2&apiKey=EB90631D-1C20-3962-39F5-75D7C7F698C8&' + (maxResults != null ? 'maxResults=' + maxResults : '');

	var url = 'http://www.veoh.com/recs/' + permalinks;
	var cgiArgs = '?';
	if(contentRatingId != null)
		cgiArgs += 'contentRatingId=' + contentRatingId + '&';
	if(maxResults != null)
		cgiArgs += 'maxResults=' + maxResults + '&';
	if(callBackupIfFails != null && callBackupIfFails == false)
		cgiArgs += 'fallback=no&';	// also tells recs service not to return backup results
	if(source != null && recVal != null)
		cgiArgs += 'source=' + source + '-' + recVal;	// logging
	
	url = url + cgiArgs;	

	try {
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(response) {
				if(response != null) {
					var rsp = response.responseXML.getElementsByTagName('rsp');
					var videoList = response.responseXML.getElementsByTagName('videoList');
					var videos = response.responseXML.getElementsByTagName('video');
	
					if((videos == null || videos.length < 4) && callBackupIfFails) {	// not enough results
						// back up call to get most popular instead
						return recsBackup(contentRatingId, maxResults, callback);
					}
					else {	// successful retrieval	
						if(callback != null) {

							// get echo
							var echo = "";
							if(rsp != null && rsp.length == 1){
								echo = rsp[0].getAttribute('echo');
							}
						
							// get hits
							var numHits;
							if(videoList != null && videoList.length == 1){
								numHits = parseInt(videoList[0].getAttribute('items'));
							}
							
							// insert flag to head of the array indicating this was a recs server return
							var flag = new Array(1);
							flag[0] = SRC_RECS;
							videos = flag.concat(videos);	
							return callback(videos,echo,source,numHits,maxResults,rId);
						}
						else {
							callback(null,null);
							return false;
						}
					}
				}
				else {
					callback(null,null);
					return false;
				}
			},
			onFailure: function() { 			
				callback(null,null);
				return false; 
			}
		});	
	} catch (e) { 
		//alert(e); 
		return false;
	}
}
/*
 * Backup AJAX request to get most popular videos in case not enough rec vids were returned
 * @param contentRatingId - current content filter settings (optional)
 * @param maxResults - defaults to 100 on the server (optional)
 * @param callback - function that will accept the response object and do something with it
 * @return array of video nodes with the first array item indicating source (default/rec) or false for failure
 */
function recsBackup(contentRatingId, maxResults, callback) {
	if(maxResults == null)
		maxResults = 20;
	if(contentRatingId == null)
		contentRatingId = 1;
		
	var url = 'http://www.veoh.com/rest/v2/execute.xml?method=veoh.search.search&apiKey=EB90631D-1C20-3962-39F5-75D7C7F698C8&type=video&sort=most%20popular&range=week';
 	url += '&maxResults=' + maxResults + '&contentRatingId=' + contentRatingId;
 	
 	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(response) {
			if(response != null) {	
				var videos = response.responseXML.getElementsByTagName('video');
				if(videos != null && videos != '') {
					// insert flag to head of the array indicating this was a default return
					var flag = new Array(1);
					flag[0] = SRC_MOST_POPULAR;
					videos = flag.concat(videos);
					return callback(videos);
				}
				else {
					return false;
				}
			}
			else {
				return false;
			}
		},
		onFailure: function() { 
			return false; 
		}
	});	
}
function goToNewHp(){
	window.location.href = 'http://www.veoh.com/setCookie.html?name=hpver&value=new&redirectUrl=http%3A//www.veoh.com/&sig=0a2cba403695e77c1e19e422592bf559b6cad61b';
}
function goToOldHp(){
	window.location.href = 'http://www.veoh.com/setCookie.html?name=hpver&value=old&redirectUrl=http%3A//www.veoh.com/&sig=761a3f3eca4ee5b3755f364887389c855fcf6df6';	
}		

(function() {
	window.textOverflowMgr = {
		'hasCssMaxHeights' : null,
		'hasCssEllipses' : null,

        'fixMLs' : function(root) {
			textOverflowMgr.toi = document.createElement("span");
			textOverflowMgr.toi.className="textOverflowIndicator";

			root = (root && root.nodeName ? root : null || document.getElementById("veohBody") || document.body);
			var allTags = root.getElementsByTagName("*"),
				testCN = new RegExp(/maxLines(\d)/);
			for(var i=0, z=allTags.length; i<z; i++) {
				var matches = testCN.exec(allTags[i].className);
				if(matches && matches.length==2) {
					if(allTags[i].className.indexOf("fixedML")==-1) {
						if(textOverflowMgr.hasCssMaxHeights == null) {
							var curStyle = allTags[i].currentStyle || allTags[i].ownerDocument.defaultView.getComputedStyle(allTags[i], "");
							textOverflowMgr.hasCssMaxHeights = (curStyle["maxHeight"] != null);
							textOverflowMgr.hasCssEllipses = (curStyle["textOverflow"] != null);
							curStyle = null;
						}
						if(!textOverflowMgr.hasCssEllipses || matches[1] != "1") {
							allTags[i].className += " fixedML";
							textOverflowMgr.fixEl(allTags[i], Number(matches[1]), allTags[i].className.indexOf("withMore") > -1);
						}
					}
				}
			}
        },
	
		'breakChars' : function(node) {
			var txt = (node.innerText || node.textContent), hTxt=txt;
            txt=txt.replace(/([\.\-\_])(\S)/g, "$1<wbr />$2");
            txt=txt.replace(/([^\d])(\d)/g, "$1<wbr />$2");
            if(txt != hTxt) node.innerHTML=txt;
		},
		
        'fixEl' : function(el, maxLines, withMore ) {
			//thanks to vphillips for the post at http://codingforums.com/archive/index.php?t-94422.html
			var tooMuch=false;
			if(maxLines == 1 && !withMore) {
				tooMuch = (el.scrollWidth > el.offsetWidth);
			} else {
				if(el.scrollWidth > el.offsetWidth) {
					textOverflowMgr.breakChars(el);
	            }
				tooMuch = (el.scrollHeight - el.offsetHeight > 5);
	            if(tooMuch && !textOverflowMgr.hasCssMaxHeights) {						
					//simulate max-height for ie6
					for(var l = maxLines; l > 1; l--) {
						if(el.scrollHeight >= (el.offsetHeight * l)) {
							el.style.height= 1.3 * l + "em";//todo well this is needed but not preferable
							break;
						}
					}
					tooMuch = (el.scrollHeight - el.offsetHeight > 5);
				}
			}
			if(tooMuch) {
				if(el.className.indexOf("withMore") > -1) {
					var toi = document.createElement("a");
					toi.className="textOverflowIndicator";
                    toi.innerHTML= "&nbsp;more &raquo;";
                    toi.title= "See more";
                    toi.href="#";
                    toi.onclick=function() {
						if(this.parentNode.style.height=="auto") {
                        	this.parentNode.style.height=this.parentNode.style._height;
                        	this.parentNode.style.maxHeight='';
                        	this.style.position='';
                        	this.style.display='';
							this.innerHTML=" more&raquo;";
                    		this.title= "See more";
						} else {
                        	this.parentNode.style._height=this.parentNode.style.height;
                        	this.parentNode.style.height='auto';
                        	this.parentNode.style.maxHeight='2000px';
                        	this.style.position='static';
                        	this.style.display='inline';
							this.innerHTML=" &laquo;less";
	                        this.title= "See less";
						}
                        return false;
                    };
				} else {
                    var toi=textOverflowMgr.toi.cloneNode(true);
                    toi.innerHTML= "...";
				}
                el.appendChild(toi);                                                                                                                                                         
            }
            el=toi=null;					
        }
	};
	
	if(window.attachEvent) {
	    window.attachEvent("onload", window.textOverflowMgr.fixMLs);
	}
	else {
	    window.addEventListener("load", window.textOverflowMgr.fixMLs, false);
	}

	/*uncomment and run in firefox to get an easy listing if <a>'s without titles in the firebug console*/
	/*
		if(typeof console != "undefined") {
			var aTags=document.getElementById("veohBody").getElementsByTagName("a"),
				noTitleCount = 0;
			for(var i=0, z=aTags.length; i<z; i++) {
				var a=aTags[i];
				if(a.href && a.href.length > 0) {
					if(!a.title || a.title.length == 0) {
						noTitleCount++;
						if(a.id && a.id.length > 0) {
							console.log("a#" + a.id + " is missing TITLE");
						}
						else if (a.className && a.className.length > 0) {
							console.log("a." + a.className + " is missing TITLE");
						}
						else {
							console.log("a(" + a.innerHTML.replace(/\</g, "&lt;").replace(/\>/g, "&gt;") + ") is missing TITLE");
						}
					}
				}
			}						
			console.log("A total of " + noTitleCount + " A tags are missing TITLEs.");
		}
	*/
})();


// generates a new searchid
function getNewSearchId(){
	var1 = ("" + Math.random()*1000000000).split(".");
	var2 = ("" + Math.random()*1000000000).split(".");
	return (var1[0] ? var1[0]: var1) + (var2[0] ? var2[0]: var2);
}

//adds a function to the onload property
function addLoadEvent(func)
{
	
    var old = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function(){
            if (old) {
                old();
            }
            func();
        }
    }
}

/*
 * utility functions for URL encoding / decoding
 */
function urlEncode (string) {
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";
	for (var n = 0; n < string.length; n++) {
		var c = string.charCodeAt(n);
		if (c < 128) {
			utftext += String.fromCharCode(c);
		}
		else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}
		else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		}
	}
	return utftext;
}

function urlDecode (utftext) {
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length ) {

		c = utftext.charCodeAt(i);

		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}
	}
	return string;
}