// JavaScript Document
// global variables (good for as long as a given page is on, lost when changing pages)
var fileID = null;
var loginIDval = getCookie("loginID");

// detect browser language and branch to relevant language page
function detect_language(){
	if (navigator.appName == 'Netscape') 
	var language = navigator.language; 
	else 
	var language = navigator.browserLanguage; 
	//alert("channel language: "+language);
	//if (language.indexOf('fr') > -1) document.location.href= "./intl/fr/overview.htm"; 	// francais
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_nbGroup(event, grpName) { //v6.0
  var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
    if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
      img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
      if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
      nbArr[nbArr.length] = img;
      for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
        if (!img.MM_up) img.MM_up = img.src;
        img.src = img.MM_dn = args[i+1];
        nbArr[nbArr.length] = img;
    } }
  } else if (event == "over") {
    document.MM_nbOver = nbArr = new Array();
    for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up);
      nbArr[nbArr.length] = img;
    }
  } else if (event == "out" ) {
    for (i=0; i < document.MM_nbOver.length; i++) {
      img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
    nbArr = document[grpName];
    if (nbArr)
      for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
    document[grpName] = nbArr = new Array();
    for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
      if (!img.MM_up) img.MM_up = img.src;
      img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
      nbArr[nbArr.length] = img;
  } }
}


/* start 100D player if installed, otherwise go to download page */
function start_play()
{
	try
	{	
		document.location.href="watch://";	/* start viewer */
		document.location.href="/intl/en/ch/ch1/featuring.html";	// open featuring page
	}
	catch(err)
	{
		alert("100Dimension does not seem to be installed on this computer. Downloading takes approximately 5 to 10 minutes.");
		document.location.href="/intl/en/overview2.html";
	}
}

/* Go to the correct download page based on detected OS */
function download_100D()
{
	if(navigator.appVersion.indexOf("Win")!=-1)
	{
		//document.location.href="/intl/en/soon.html";
		document.location.href="/download/Installer100D.exe";
	} 
	else if (navigator.appVersion.indexOf("Mac")!=-1)
	{
		document.location.href="/intl/en/soon.html";
		//document.location.href="/download/100Dimension_mac_0_6_en.exe";
	} 
	else
	{
		alert("The detected operating system "+navigator.appVersion+" is not currently supported");
	}
}

/* login form  [from http://www.webpasties.com/xmlHttpRequest/xmlHttpRequest_tutorial_1.html]*/
var http = getHTTPObject(); // We create the HTTP Object

function handleHttpResponse() { 
  if (http.readyState == 4) { 
    // Split the comma delimited response into an array  
	results = http.responseText.split(","); 
	if(results[0] == 1)
	{
		// success. validated loginID. Keep it. will need it later
		setCookie("loginID",loginIDval,987);  // expire in987days. Important: used to detect 100d's presence on this computer
		var queueSize = 0; // reset queue size
		setCookie("queueSize", queueSize, null);
		if(fileID != null){
			// login was initiated to request a first file. complete the request.
			userRequest(loginIDval, fileID);
		}
		
		
		document.getElementById('loginID').value = "";  // clear login field after saving it 
		// return to original page
		var WindowLocationb4Login = getCookie("WindowLocationb4Login");
		if(WindowLocationb4Login != ""){
			// we are here because the user wanted to select a show before log in.
			window.location.replace(WindowLocationb4Login);
		} else {
			// we are here because the user clicked on Login
			history.go(-1);
		}
	} 
	else if(results[0] == 0)
	{
		// NCC responded. loginID invalid
		//alert("Invalid loginID " + loginIDval);
	    document.getElementById('loginStatus').value = "Invalid address " + loginIDval;
		document.getElementById('loginID').value = "";  // clear login after saving it 
		document.getElementById('loginID').focus();
	}
	else if(results[0] == 2)
	{
		// NCC responded. Target is not online
		//alert("Target computer is not powered or not online. Cannot download shows." + loginIDval);
	    document.getElementById('loginStatus').value = "Target computer is not powered or not online. Cannot download shows." + loginIDval;
		document.getElementById('loginID').value = "";  // clear login after saving it 
		document.getElementById('loginID').focus();
	}
	else {
		// NCC not currently unavailable.
	    document.getElementById('loginStatus').value = "This service is temporarily unavailable. We apologize for the inconvenience. code=" + results[0];
		document.getElementById('loginID').value = "";  // clear login 
	}
  } 
}

function login2()
{
  document.getElementById('loginStatus').value = ""; // clear previous status field
  loginIDval = document.getElementById("loginID").value.toUpperCase(); 
  if(loginCheck(loginIDval) == false){
	document.getElementById('loginID').value = "";  // clear login 
	document.getElementById('loginID').focus();
  } 
  else 
  {
     loginURL = "verifyLogin.php?param="; // The server-side script
	 //alert("loginQUERY=GET"+loginURL + escape(loginIDval));
	 http.open("GET", loginURL + escape(loginIDval), true); 
	 http.onreadystatechange = handleHttpResponse; 
	 http.send(null);
  }
}

function logout()
{
   loginIDval = " ";
   setCookie("loginID",loginIDval,null);  // clear
   alert("Logout confirmed");
}


function getHTTPObject() { 
  var xmlhttp; 
  /*@cc_on 
    @if (@_jscript_version >= 5) 
      try { 
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
      } catch (e) { 
        try { 
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
        } catch (E) {
	      xmlhttp = false; 
	    } 
	  } 
    @else xmlhttp = false; 
    @end 
  @*/  
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { 
    try { 
	  xmlhttp = new XMLHttpRequest(); 
	} catch (e) { 
	  xmlhttp = false; 
	} 
  } return xmlhttp; 
} 

// input is already in uppercase
function loginCheck(entry){
  validChar='0123456789ABCDEF'; // hex
  strlen=entry.length;    
  if((strlen > 0) && (strlen != 16)){
	  //alert('Warning: illegal length. ID must be 16-character long');
	  document.getElementById('loginStatus').value = "illegal length. Address must be 16-character long";
	  return false;
  }
  if(strlen == 0){
	  return false;
  }
  // Now scan string for illegal characters
  for (i=0;i<strlen;i++){
    if(validChar.indexOf(entry.charAt(i))<0){
       //alert("Warning: illegal ID. ID includes only characters 0-9 and A-F");
	  document.getElementById('loginStatus').value = "illegal. Address includes only characters 0-9 and A-F";
	   return false;
	}
  } // end scanning loop
  return true;
}

/* user request for a fileID or channel -----------------------------*/
// sharing http with login (never simultaneous)
function userRequest(loginIDval, fileID)
{
	// userID length (8 bytes = 16 hex characters) and format already verified.
	reqURL = "/intl/en/userRequest.php?packet=" + escape(loginIDval);
	var fid0 = fileID.toString(16).toUpperCase(); // convert fileID to hex (variable length)
	// pad fileID to 12 hex characters
	// problem... limit to 10hex
	var pad = '';
	while(true){
		if((pad.length + fid0.length) < 10){
			// not enough pad yet
			pad += '0';
		} else {
			fid0 = pad + fid0;
			break;
		}
	}
	reqURL += escape(fid0);  // add an end of string?
	//alert(reqURL);
	http.open("GET", reqURL, true); 
	http.onreadystatechange = handleHttpResponse2; 
	http.send(null);
}

function handleHttpResponse2() { 
  if (http.readyState == 4) { 
    // Split the comma delimited response into an array  
	results = http.responseText.split(","); 
	var queueSize = getCookie("queueSize");
	queueSize++;
	setCookie("queueSize", queueSize, null);
	if(queueSize > 1)
		alert(queueSize + " shows queued");
	else
		alert(queueSize + " show queued");
	
//		alert("userRequest response "+results[0] + "  queueSize" + queueSize);
	if(results[0] == 1){
	}
  }
}

/* Display featured shows from XML file ----------------------------------*/
// Load import XML file
function featuredXML(xmlsource, xmlrecord)
{
	if (document.implementation && document.implementation.createDocument)
	{
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.async=false; //Enforce download of XML file first.
		xmlDoc.onload = createFeaturesTable;
	}
	else if (window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false; //Enforce download of XML file first.
		xmlDoc.onreadystatechange = function () 
		{
			if (xmlDoc.readyState == 4) 
				createFeaturesTable()
		};
	}
	else
	{
		alert('This browser does not support importXML');
		return;
	}
	xmlDoc.load(xmlsource);
}

function createFeaturesTable()
{
	var f = xmlDoc.getElementsByTagName(xmlrecord);
	if(f.length <= 0){
		return; // no featured show
	}
	document.write('<table id="t1" <tr>');
	
	for(var i=0; i<f.length; i++) {
		// fileID
		var fid = f[i].getElementsByTagName("FILEID")[0].firstChild;
		if(fid != null)
		{
			document.write('<td width = 50 align="center"><a href="" onclick="getShow(' + fid.nodeValue + '); return false;"><img src="/images/downloadIcon.gif" border="0"></a></td>');
		}

		var p = f[i].getElementsByTagName("PICTURE")[0].firstChild;
		if (p != null) 
		{
			document.write('<td width = 170 align="left"><a href="" onclick="getShow(' + fid.nodeValue + '); return false;"><img src="' + p.nodeValue + '" border="0"></td>');
		}
	}
	document.write('</tr><tr>');
	for(var i=0; i<f.length; i++) {
		var p = f[i].getElementsByTagName("TITLE")[0].firstChild;
		document.write('<td></td><td align="center">' + p.nodeValue + '</td>');
	}
	document.write('</tr></table>');
}


/* channel XML tables ----------------------------------*/
// Load import XML file
function importXML(xmlsource, xmlrecord)
{
	if (document.implementation && document.implementation.createDocument)
	{
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.async=false; //Enforce download of XML file first.
		xmlDoc.onload = createTable;
	}
	else if (window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false; //Enforce download of XML file first.
		xmlDoc.onreadystatechange = function () 
		{
			if (xmlDoc.readyState == 4) 
				createTable()
		};
	}
	else
	{
		alert('This browser does not support importXML');
		return;
	}
	xmlDoc.load(xmlsource);
}

function createTable()
{
	var f = xmlDoc.getElementsByTagName(xmlrecord);
	document.write('<table id="t1" class="sortable">');
	document.write('<tr><th width="32"></th><th width="200">Click image to select show</th><th width="600">Description</th></tr>');
	for(var i=0; i<f.length; i++) {
		
		// get the duration in the right format
		var dur = f[i].getElementsByTagName("DURATION")[0].firstChild.nodeValue;
		var seconds = Math.floor(dur % 60);
		if (seconds < 10) 
		{
			seconds = "0" + seconds;
		}
		var minutes = Math.floor((dur / 60) % 60);
		if (minutes < 10) 
		{
			minutes = "0" + minutes;
		}
		var hours = Math.floor((dur / 3600) % 24);

		if((hours != 0) || (minutes != 0) || (seconds != 0)){
			dur = 'Duration: ' + hours + ":" + minutes + ":" + seconds;
		} else {
			dur = " ";
		}
		
			
		
		// fileID
		var fid = f[i].getElementsByTagName("FILEID")[0].firstChild;
		if(fid == null)
		{
			// no fileID found
			document.write('<tr><td></td>');
		} else
		{
			document.write('<tr><td class="download" align="center"><a href="" onclick="getShow(' + fid.nodeValue + '); return false;"><img src="/images/downloadIcon.gif" border="0"></a></td>');
		}
		
		var p = f[i].getElementsByTagName("PICTURE")[0].firstChild;
		if (p == null) 
		{
			// no picture found
			document.write('<td></td>');
		}
		else 
		{
			document.write('<td align="center"><a href="" onclick="getShow(' + fid.nodeValue + '); return false;"><img src="' + p.nodeValue + '" border="0"></td>');
		}

		var l = f[i].getElementsByTagName("LINK")[0].firstChild;
		document.write('<td valign="top"><h3>' + f[i].getElementsByTagName("TITLE")[0].firstChild.nodeValue + '</h3>');
		// title is always present
		if(dur != " "){
			document.write(dur + '<br>');
		}
		var d = f[i].getElementsByTagName("DESCRIPTION")[0].firstChild;
		if(d != null){
			document.write(d.nodeValue);
		}
		if (l == null) 
		{
			// no link found
			document.write('</td>');
		}
		else 
		{
			document.write('<a href=' + l.nodeValue + '> More Info... </a><br></td>');
		}
		document.write('</tr>');
	}
	document.write('</table>');
}

function getShow(fid){
	if(loginIDval.length != 16) {
	   setCookie("WindowLocationb4Login", window.location, null);  // remember what page to go back to
	   //window.location.replace('/intl/en/login.html');  // no longer using login.html
	   window.location.href="/intl/en/getshow.html?fid="+fid;
	} 
	else 
	{
	  //alert("user "+ loginIDval + " requested fileID " + fid);
	  userRequest(loginIDval, fid);
	}
}

/* cookie... see http://www.w3schools.com/js/js_cookies.asp */
// set expiredays=null to expire at the end of session
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
		+ ";path=/";
}


function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

function test1()
{
	alert("test1");
}