/*
   Adapted and enhanced examples taken from http://www.cmarshall.net/ and http://www.joostdevalk.nl/code/sortable-table/
   Author: Paul R. Allen
     Date: 25-May-2007
*/

/* This is how we ensure that we can have multiple browsers on the same page. It keeps track of them for us. */
var	g_browser_id_max;

/* This is where the AJAX call returns its results.
	in_browse_results contains the response text.
	inParam contains the DOM ID of the HTML element to have its HTML replaced.
*/
function processBrowseResults ( in_browse_results, inParam ) {
	var browse_results = in_browse_results;
	pos404=in_browse_results.indexOf('404 Not Found');
	if (pos404 >= 0) {
		alert("This directory ("+inParam+") does not contain the required html file (_ddtv.xml).");
	} else {
	  saveInnerHTML = document.getElementById(inParam).innerHTML
	  var switchHTML = (saveInnerHTML.length == 0?true:(saveInnerHTML.indexOf("a_class_dir_link_closed") != -1?true:false));
	  //if (saveInnerHTML.length == 0) alert("saveInnerHTML="+saveInnerHTML+"<-"+saveInnerHTML.length+", switchHTML="+switchHTML);
	  //else alert("saveInnerHTML="+saveInnerHTML+"<-"+saveInnerHTML.length+", switchHTML="+switchHTML+", idx="+saveInnerHTML.indexOf("a_class_dir_link_closed"));
	  if (switchHTML) {
	    document.getElementById(inParam).innerHTML = browse_results+"<!--SAVEDHTML>"+saveInnerHTML+"-->";
	    startSort();
	  } 
	}
}

/* This is where the initial HTTPRequest is made. */
function initBrowser( in_request, in_id ) {
	var url;
	if (in_request == '') url = '/_ddtv.xml';
	else url = '/'+in_request+'/_ddtv.xml';
	g_ajax_obj.CallXMLHTTPObjectGETParam ( url, processBrowseResults, in_id );
}

/* This function actually creates the file browser XHTML. */
function createBrowser ( dir_root ) {
	/* We test to make sure the browser supports AJAX. We display a warning otherwise. */
	if ( !SupportsAjax ( ) ) {
		document.write ( '<h1>Your browser does not support AJAX!</h1>' );
	} else {
		/* What we do here, is to ensure that the <div> containing the browser has a unique ID.
			All contained <div> and <dl> tags will have IDs that are derived from this. */
		/* If it's uninitialized, we set it explicitly to zero. This forces it to be an integer. */
		if ( !g_browser_id_max ) { g_browser_id_max = 0 };
	
		/* We keep incrementing the ID as we find elements with that ID. */
		while ( document.getElementById('ajax_browser_'+g_browser_id_max++) );
		
		/* This is the <div> tag ID. It should be unique. */
		var	div_id = 'ajax_file_browser_'+g_browser_id_max;
		
		/* This is the main <div>. */
		document.writeln ('<div id="'+div_id+'"></div>');
		
		var	query = '';
		
		/* If there was a subdirectory defined, we add it to the query. */
		if ( (dir_root != undefined) && dir_root ) {
			query += dir_root;
		}
		
		/* We do an initBrowser() to populate the browser. */
		initBrowser ( query, div_id );
	}
}

/* Closes current node and replaces the innerHTML with previously saved HTML. */
function nodeClose ( in_request ) {
	var savedInnerHTML = document.getElementById(in_request).innerHTML;
	firstposSaved=savedInnerHTML.lastIndexOf('<!--SAVEDHTML>')+14;
	lastposSaved=savedInnerHTML.length-3;
	document.getElementById(in_request).innerHTML = savedInnerHTML.substring(firstposSaved,lastposSaved);
}

/* Open specified node, make HTTPRequest to get the xml file content. */
function nodeOpen ( in_request ) {
	var url;
	if (in_request == '') url = '/_ddtv.xml';
	else url = '/'+in_request+'/_ddtv.xml';
	///alert("nodeOpen("+in_request+")->url='"+url+"'");
	g_ajax_obj.CallXMLHTTPObjectGETParam ( url, processBrowseResults, in_request );
}

/* Enable sort on all of the currently displayed tables. */
var reference;
function enableSort() {
  // Allow all current page tables to be sorted.
	sortables_init();			
	clearInterval(reference);
}

/* Set up a window timer to call the enableSort() function. */
function startSort() {
	clearInterval(reference);
	reference = setInterval("enableSort()",100);
}

function processURLParameters() 
{
	var sURL = window.document.URL.toString();
	var posQplus1 = sURL.indexOf("?")+1;
	//alert("sURL="+sURL+", indexOf?="+posQplus1+" len="+sURL.length);
	
	if (sURL.indexOf("?") > 0 && sURL.length > posQplus1)
	{
		var arrParams = sURL.split("?");
		//alert("arrParams->"+arrParams);
			
		var arrURLParams = arrParams[1].split("&");
		//alert("arrURLParams->"+arrURLParams);
		
		//var arrParamNames = new Array(arrURLParams.length);
		//var arrParamValues = new Array(arrURLParams.length);
		var arrParam = new Array(arrURLParams.length,2);

		var i = 0;
		//alert("arrURLParams.length->"+arrURLParams.length);
		for (i=0;i<arrURLParams.length;i++)
		{
			var sParam =  arrURLParams[i].split("=");
/*			
			arrParamNames[i] = sParam[0];
			if (sParam[1] != "")
				arrParamValues[i] = unescape(sParam[1]);
			else
				arrParamValues[i] = "No Value";
		  arrParam[i,0] = arrParamNames[i];
		  arrParam[i,1] = arrParamValues[i];
		for (i=0;i<arrURLParams.length;i++)
		{
			alert(arrParamNames[i]+" = "+ arrParamValues[i]);
		}
*/
      //alert(i+"sParam[0]"+sParam[0]);
			arrParam[i,0] = sParam[0];
			if (sParam[1] != "") {
				//alert(i+"sParam[1]="+unescape(sParam[1]));
				arrParam[i,1] = unescape(sParam[1]);
			} else {
				//alert(i+"sParam[1]=No Value");
				arrParam[i,1] = "No Value";
			}
			//alert("arrParam[i,1] = "+arrParam[i,1]);
  		nodeOpen(arrParam[i,1]);
		}
    //return arrParam;
	}
/*
	else
	{
		alert("No parameters.");
	}
*/
}

function getURLParameters(pURL) {
  var sURL;
  if(arguments.length) {
    sURL = pURL;
  } else {
    sURL = window.document.URL.toString();
  }
	if (sURL.indexOf("?") > 0) {
		return (sURL.split("?"))[1];
  } else {
    return "";
  }
}

function getQueryString() {
  var sQueryString = getURLParameters()
	if (sQueryString.length > 0) {
		return "?"+sQueryString;
  } else {
    return "";
  }
}

/* Enable the URL. */
var reference2;
function enableURL() {
  // Allow all current page tables to be sorted.
	processURLParameters();

  // Allow all current page tables to be sorted.
	sortables_init();			
	clearInterval(reference2);
}
/* Process the URL. */
function startURL() {
	clearInterval(reference2);
	reference2 = setInterval("enableURL()",100);
}

var downloadURL;
function download( url ) {
	downloadURL = url;
  window.location = downloadURL;
  //sm('box',640,480);	
}

function agree2terms(ynDownload) {
  if (ynDownload == true) {
	  window.location = downloadURL;
  //} else {
	//  alert("Data not downloaded.");
  }
}

function windowOpen(url, name, w, h) {
  var width = w;
  var height = h;
  var top = ((screen.height - height) / 2) - 50;
  var left = ((screen.width - width) / 2) - 10;
  window.open(url,name,'toolbar=yes,menubar=no,scrollbars=yes,resizable=yes,width='+width+',height='+height+',top='+top+',left='+left+',screenX=0,screenY=0');
}

function set_cookie ( name, value, expires_year, expires_month, expires_day, path, domain, secure )
{
  var cookie_string = name + "=" + escape ( value );

  if ( expires_year )
  {
    var expires = new Date ( expires_year, expires_month, expires_day );
    cookie_string += "; expires=" + expires.toGMTString();
  }

  if ( path )
	cookie_string += "; path=" + escape ( path );

  if ( domain )
	cookie_string += "; domain=" + escape ( domain );

  if ( secure )
	cookie_string += "; secure";
    
  document.cookie = cookie_string;

}

function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

function setCookiesAndForwardToNextPage(){
	  var username = "yes";
	  var cookie_year;
    var cookie_month;
    var cookie_day;
    set_cookie ( "username", username, cookie_year, cookie_month, cookie_day );
    window.location="DataDownloadFileLister.html"+getQueryString();
}

