/* parsesearch */
/*
	parseSearch() parses the documents search string to Javascript variables by
	evaluating key-value pairs. It distinguishes between numeric, boolean and
	string values;
*/
function parseSearch() {
	aKeyValues = document.location.search.substring(1).split("&");
	for (i = 0; i < aKeyValues.length; i++) {
		aKeyValue = aKeyValues[i].split("=");
		if (aKeyValue[0] == "joostinstalled") {
			if (aKeyValue[1] == "true") { rValue = true;	}
			if (aKeyValue[1] == "false") {	rValue = false; }
			joostinstalled = rValue;
		}
	}
}
parseSearch();

/* /parsesearch */





/* header images */
var headerFrontImages = new Array(
																		'image1.jpg',
																		'image2.jpg',
																		'image3.jpg',
																		'image4.jpg',
																		'image5.jpg',
																		'image6.jpg',
																		'image7.jpg',
																		'image8.jpg',
																		'image9.jpg',
																		'image10.jpg',
																		'image11.jpg',
																		'image12.jpg',
																		'image13.jpg',
																		'image14.jpg',
																		'image15.jpg',
																		'image16.jpg'
																	);

/* Download button */

function createDownloadButtonIcon() {
	var agt		= navigator.userAgent.toLowerCase();
	if (agt.indexOf("mac") != -1) {
		document.write('<div class="downloadIcon"><a onclick="setupAutoDownload();" href="http://www.joost.com/download/macosx/" title="Download Joost Beta 1.1 - Mac OS X"><img src="/rsc/images/content/components/downloadjoost/joost_download_appicon.png" alt="Download Joost Beta 1.1 - Mac OS X"/><br/></a></div>');
	}
	else {
		var questionMarkPos=location.hash.indexOf('?');
		var fixedHash=(questionMarkPos!=-1)?location.hash.substring(0,questionMarkPos):location.hash;
		if (typeof(tinyUrl) != "undefined") {
			if (fixedHash.length>0) fixedHash+=";program="+tinyUrl; else fixedHash="#program="+tinyUrl;
		}
		document.write('<div class="downloadIcon"><a onclick="setupAutoDownload();" href="http://www.joost.com/download/windows/'+fixedHash+'" title="Download Joost Beta 1.1 - Windows"><img src="/rsc/images/content/components/downloadjoost/joost_download_appicon.png" alt="Download Joost Beta 1.1 - Windows"/><br/></a></div>');
	}
}
function createDownloadButtonText() {
	var agt		= navigator.userAgent.toLowerCase();
	if (agt.indexOf("mac") != -1) {
		if (agt.indexOf("intel") != -1) {
			document.write('<p><a onclick="setupAutoDownload();" href="http://www.joost.com/download/macosx/" title="Download Joost Beta 1.1 - Mac OS X"><span class="downloadJoost">Download Joost</span><br/><span class="version">Joost Beta 1.1 - Mac OS X</span></a></p>');
		}
		else {
			document.write('<p><a href="http://www.joost.com/download/macosx/" title="Download Joost Beta 1.1 - Intel Mac"><span class="downloadJoost">Download Joost</span><br/><span class="version">Joost Beta 1.1 - Intel Mac</span></a></p>');
		}
	}
	else {
		var questionMarkPos=location.hash.indexOf('?');
		var fixedHash=(questionMarkPos!=-1)?location.hash.substring(0,questionMarkPos):location.hash;
		if (typeof(tinyUrl) != "undefined") {
			if (fixedHash.length>0) fixedHash+=";program="+tinyUrl; else fixedHash="#program="+tinyUrl;
		}
		document.write('<p><a onclick="setupAutoDownload();" href="http://www.joost.com/download/windows/'+fixedHash+'" title="Download Joost Beta 1.1 - Windows"><span class="downloadJoost">Download Joost</span><br/><span class="version">Joost Beta 1.1 - Windows</span></a></p>');
	}
}

function createDownloadBlock(linkToBinaries) {
	var agt		= navigator.userAgent.toLowerCase();
	if (!linkToBinaries) {
		if (agt.indexOf("mac") != -1) {
			if (agt.indexOf("intel") != -1) {
				document.write('<a href="http://www.joost.com/download/macosx/" title="Download Joost Beta 1.1 - Mac OS X"><img src="/rsc/images/content/download.jpg" alt="Download Joost Beta 1.1 - Mac OS X" width="510" height="151" /><br/></a>');
				document.write('<div class="overlay"><a href="http://www.joost.com/download/macosx/" title="Download Joost Beta 1.1 - Mac OS X"><span class="downloadJoost">Download Now</span><br/><span class="version">Joost Beta 1.1 - Mac OS X</span></a></div>');
			}
			else {
				document.write('<a href="http://www.joost.com/download/macosx/" title="Download Joost Beta 1.1 - Intel Mac"><img src="/rsc/images/content/download.jpg" alt="Download Joost Beta 1.1 - Intel Mac" width="510" height="151" /><br/></a>');
				document.write('<div class="overlay"><a href="http://www.joost.com/download/macosx/" title="Download Joost Beta 1.1 - Intel Mac"><span class="downloadJoost">Download Now</span><br/><span class="version">Joost Beta 1.1 - Intel Mac</span></a></div>');
			}
		}
		else {
				document.write('<a href="http://www.joost.com/download/windows/" title="Download Joost Beta 1.1 - Windows"><img src="/rsc/images/content/download.jpg" alt="Download Joost Beta 1.1 - Windows" width="510" height="151" /><br/></a>');
				document.write('<div class="overlay"><a href="http://www.joost.com/download/windows/" title="Download Joost Beta 1.1 - Windows"><span class="downloadJoost">Download Now</span><br/><span class="version">Joost Beta 1.1 - Windows</span></a></div>');
		}
	}
	else {
		if (agt.indexOf("mac") != -1) {
			if (agt.indexOf("intel") != -1) {
				document.write('<a href="http://downloads.joost.com/downloads/Joost-Beta-1.1.7.dmg" title="Download Joost Beta 1.1 - Mac OS X"><img src="/rsc/images/content/download.jpg" alt="Download Joost Beta 1.1 - Mac OS X" width="510" height="151" /><br/></a>');
				document.write('<div class="overlay"><a href="http://downloads.joost.com/downloads/Joost-Beta-1.1.7.dmg" title="Download Joost Beta 1.1 - Mac OS X"><span class="downloadJoost">Download Now</span><br/><span class="version">Joost Beta 1.1 - Mac OS X</span></a></div>');
			}
			else {
				document.write('<a href="http://downloads.joost.com/downloads/Joost-Beta-1.1.7.dmg" title="Download Joost Beta 1.1 - Intel Mac"><img src="/rsc/images/content/download.jpg" alt="Download Joost Beta 1.1 - Intel Mac" width="510" height="151" /><br/></a>');
				document.write('<div class="overlay"><a href="http://downloads.joost.com/downloads/Joost-Beta-1.1.7.dmg" title="Download Joost Beta 1.1 - Intel Mac"><span class="downloadJoost">Download Now</span><br/><span class="version">Joost Beta 1.1 - Intel Mac</span></a></div>');
			}
		}
		else {
				document.write('<a href="http://downloads.joost.com/downloads/JoostSetup-Beta-1.1.7.exe" title="Download Joost Beta 1.1 - Windows"><img src="/rsc/images/content/download.jpg" alt="Download Joost Beta 1.1 - Windows" width="510" height="151" /><br/></a>');
				document.write('<div class="overlay"><a href="http://downloads.joost.com/downloads/JoostSetup-Beta-1.1.7.exe" title="Download Joost Beta 1.1 - Windows"><span class="downloadJoost">Download Now</span><br/><span class="version">Joost Beta 1.1 - Windows</span></a></div>');
		}
	}
}

/* hide downloadbutton */
if (findJoost()) {
	document.write('<style type="text/css">.mainContent .downloadBox { display: none; }</style>');
}

function home_configureProposition() {
	if (findJoost()) {
		document.getElementById('valueproposition').style.display='none';
		document.getElementById('contentproposition').style.display='block';
	}
	else {
		document.getElementById('valueproposition').style.display='block';
		document.getElementById('contentproposition').style.display='none';
	}
}

function watch_configureProposition() {
	if (findJoost()) {
		document.getElementById('downloadproposition').style.display='none';
		document.getElementById('watchproposition').style.display='block';
	}
	else {
		document.getElementById('downloadproposition').style.display='block';
		document.getElementById('watchproposition').style.display='none';
	}
}



/* set show count */
function setShowsCount() {
	if (document.getElementById('shows_count') != null) {
		document.getElementById('shows_count').innerHTML = "<p>28,000+ TV shows, 480+ Channels</p>";
		document.getElementById('shows_count').style.display = 'block';
	}
}

addEvent(window,'load',setShowsCount);


/* Home newsletter */

var newsletter = {
	mail: 'name@example.com',
	focus: function() {
		if(arguments[0].value==this.mail) arguments[0].value='';
	},
	blur: function() {
		if(arguments[0].value=='') arguments[0].value=this.mail;
	}
}

/* Facebook Beacon code inclusion */
function facebookInclude(scriptURL) {
  var head = document.getElementsByTagName('head').item(0);
  var script = document.createElement('script');
  script.setAttribute('language', 'javascript');
  script.setAttribute('type', 'text/javascript');
  script.setAttribute('src', scriptURL);
  head.appendChild(script);
  return false;
}

/* Joost sniffer */

function returnJoostLink() {
  document.getElementById('playnow_start').style.display='block';
  document.getElementById('playnow_opening').style.display='none';
}


function clickJoostLink() {
  document.getElementById('playnow_start').style.display='none';
  document.getElementById('playnow_opening').style.display='block';
	try {
    Facebook.publish_action('enjoy', 'http://joost.com/'+tinyUrl);
  } catch (e) {}
  if (window.pageTracker) pageTracker._trackPageview('/'+tinyUrl+'?buttonPlay');
  setTimeout ( "returnJoostLink()", 20000 );
}

function findJoost() {

	//searchOverwrite
	try{
		if (joostinstalled == false) return false;
		if (joostinstalled == true) return true;
	} catch(e) {}
	//end of searchOverwrite

	//if browser = IE
	try {
	  var plug = new ActiveXObject("JOOSTPLUGIN.JoostPluginCtrl.1");
	  return true;
	}catch(e){}
	//if browser is any other
	try{
	  if(navigator.mimeTypes["application/x-joost-spoon"].enabledPlugin != null )  {
	    return true;
	  }
	} catch(e) {
          navigator.plugins.refresh(false);
          try {
            if (navigator.mimeTypes["application/x-joost-spoon"].enabledPlugin != null ) {
              return true;
            }
          } catch (e1) {}
        }
	return false;
}

function sniffJoost() {
	var joostFound = findJoost();
	var questionMarkPos=location.hash.indexOf('?');
	var fixedHash=(questionMarkPos!=-1)?location.hash.substring(0,questionMarkPos):location.hash;

	 if (tinyUrl!="") {
	  //create text if joost is  found
	  if(joostFound) {
	    document.getElementById('playnow_start').style.display = 'block';
	    var buttonLink = document.getElementById('button-watchit-link');
	    if (buttonLink) {
	    	if (fixedHash.indexOf("play=now") > -1) {
	      	buttonLink.setAttribute("href","joost://" + tinyUrl);
	    	}
	    	else{
	      	buttonLink.setAttribute("href","joost://" + tinyUrl + fixedHash);
	      }
	      buttonLink.onclick = clickJoostLink;
	    }
	    var programLink = document.getElementById('program-title-link');
	    if (programLink) {
	    	if (fixedHash.indexOf("play=now") > -1) {
		      programLink.setAttribute("href","joost://" + tinyUrl);
	    	}
	    	else{
		      programLink.setAttribute("href","joost://" + tinyUrl + fixedHash);
				}
	      programLink.onclick = clickJoostLink;
	    }
	    // include the Facebook code
	    facebookInclude('http://facebook.com/beacon/beacon.js.php?source=5586658845');
	  } else {
	      document.getElementById('playnow').style.display = 'none';
    }
	}
	// launch client immediately if #play=now
	var hash=fixedHash+'';
	if (hash && hash.match(/(?:#|,)(?:play=now)/gim)) {
	  var buttonLink = document.getElementById('button-watchit-link');
	  if (joostFound && buttonLink && buttonLink.onclick) {
			$("#button-watchit-link").trigger("click");
			location=buttonLink.href;
	  }
	}
}

function showhide(layer_ref) {
	obj		= document.getElementById(layer_ref);
	if (obj.style.display != "none") {
		obj.style.display	= "none";
	} else {
		obj.style.display	= "block";
	}
    return false;
}


function doLoginFromFlash(username,password) {
	document.getElementById('username').value = username;
	document.getElementById('password').value = password;
	document.getElementById('jsaction').value = 'signin';
	document.getElementById('loginform').submit();
}

function doForgotFromFlash (username) {
	document.getElementById('username').value = username;
	document.getElementById('jsaction').value = 'lostpassword';
	document.getElementById('loginform').submit();
}
function doForgotFromHTML () {
	document.getElementById('jsaction').value = 'lostpassword';
	document.getElementById('loginform').submit();
}

function doLogoutFromFlash() {
	document.getElementById('jsaction').value = 'signout';
	document.getElementById('loginform').submit();
}


function showLogin() {
	if (document.getElementById('login_form') != undefined) {
		document.getElementById('login_form').style.display = "block";
		document.getElementById('login_signin').style.display = "none";
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	var c = readCookie(name);
	createCookie(name,"",-1);
	return c;
}

/* Auto download */

function setupAutoDownload() {
	// Set cookie autodownload to yes, approx 1 minute
	createCookie("autodownload", "yes", 0.001);
}

function attemptAutoDownload(location) {
	// If the cookie is valid, start downloading
	if (eraseCookie("autodownload") == "yes") {
		if (typeof(trackerExecute) == "function") trackerExecute("URL", location);
		window.location = location;
	}
}

var shown=null;

var browser = {

    name: null,
    version: null,
    agent: null,

    init : function(){

        if (window.navigator){
            this.agent = window.navigator.userAgent;
        }else{
            this.agent = navigator.userAgent;
        }

        if (this.agent.indexOf("Firefox") >= 0){
            this.name = "Firefox";
            var startVersion = this.agent.substring(this.agent.indexOf("Firefox") + "Firefox/".length, this.agent.length);
            this.version = parseInt(startVersion, 10);
        }else if (this.agent.indexOf("Safari") >= 0){
            this.name = "Safari";
            var startVersion = this.agent.substring(this.agent.indexOf("Safari") + "Safari/".length, this.agent.length);
            this.version = parseInt(startVersion, 10);
        }else if (this.agent.indexOf("MSIE") >= 0){
            this.name = "IE";
            var startVersion = this.agent.substring(this.agent.indexOf("MSIE") + "MSIE ".length, this.agent.length);
            this.version = parseInt(startVersion, 10);
        }
        return this;
    }

};

browser.init();

function displayGeoRestriction(e) {
    //event under IE
    if (!e) var e = window.event;

    //get the target FF
    if (e.target) targ = e.target;
    //IE
    else if (e.srcElement) targ = e.srcElement;
    //SAFARI
    if (targ.nodeType == 3) targ = targ.parentNode;

    //OK cool we have the target
    var current = targ.id;
    if(shown != null) {
        shown.style.display = "none";
    }
    shown = document.getElementById("windows_" + current);

    shown.style.display = "block";

}

function closeGeo(e){
    //event under IE
    if (!e) var e = window.event;

    //get the target FF
    if (e.target) targ = e.target;
    //IE
    else if (e.srcElement) targ = e.srcElement;
    //SAFARI
    if (targ.nodeType == 3) targ = targ.parentNode;

    //OK cool we have the target
    var current = targ.id;
    if(shown != null) {
        shown.style.display = "none";
    }
    shown = document.getElementById("windows_" + current);

    if(shown != null) {
         shown.style.display = "none";
    }
    return false;
}


/**
* Will look for a json array of data stored in featureboxData_REGION.js called promos
* If it finds any data it will randomly choose one of the promo sets of data and display it in the corresponding box
*/
function randomizePromoImages(){
	$.get("/rsc/js/featureboxchannels_"+region+".js", { baseRevision: escape(baseRevision) }, loadPromoImages);
}

function loadPromoImages(data){
	//Store the data as json object
    channelData1 = eval("(" + data.toString() + ")");
    //If there are promos iterate through each promo and set a random set of data to it from the list in featureboxchannels_REGION.js
    if (channelData1.promos != null){
		indexOfBox = 0;
    	$(".rotateablePromoContent").each(function(){
	    	boxPosition=$(".featured .featuredBox").index(this);
      		rndChoice = rndInt(channelData1.promos[boxPosition].length);
    		promoData = channelData1.promos[boxPosition][rndChoice];
    		loadPromo($(this), promoData);
    	});
    }
}

function loadPromo(target, data){
	//set the image
    imagePath = $("img",target).attr("src");
    imagePath = imagePath.substring(0,imagePath.lastIndexOf("/"));
    imagePath = imagePath + "/" + data.image;
    $("img", target).attr("src",imagePath);
    //set the alt on  the image
    $("img", target).attr("alt", data.title);
    //set the link on  the image
    $("a", target).attr("href", data.link);
}


/**
*
* Generic Utility Functions
*
*/

/*
* Returns a random Integer in the range of 0 - ceil
*/

function rndInt(ceil){
	rnd = Math.floor(Math.random()*(ceil));
	return rnd;
}

/*
* Returns a truncated string from that give if it is greater than the maxlength.
*/
function getSizedString(s,maxLength){
	if (s.length > maxLength){
		s = s.substring(0, (maxLength - 3));
		s = s.replace(/^\s+|\s+$/g, ''); //trim it
		s = s + "...";
	}
	return s;
}

// Helper function to support older browsers, ahem IE!
[].indexOf || (Array.prototype.indexOf = function(v, n){
	n = (n == null) ? 0 : n;
	var m = this.length;
	for (var i=n; i<m; i++)
		if (this[i] == v)
			return i;
	return -1;
});


// Helper function to rebuild the screen after page-content has resized (for IE)
function rebuildScreen() {
	if (browser.name == "IE") {
		screenRebuilder = window.setTimeout(function () { window.resizeBy(0,-10); window.setTimeout(function () { window.resizeBy(0,10); }, 1);}, 1);
	}
}
