/**
  * (c) Paul Uithol, SMARTposition
  * http://www.smartposition.nl
  * 
  * date: 16 jan 2007
  * version: 0.1
  * -----------------
  * 0.1		basic (dom) functions
  *
  *
  * BUGS
  * -
  */
  

  
window.onload = function() {
	init();
}

window.onunload = function() {
	GUnload();
}

function init() {
	var requestParams = getRequestParams();
	console.log(requestParams);
	
	//get the GET parameters of the URL
	if (requestParams['geodata']) {
		gpxUrl = requestParams['geodata'];
	}
	if (requestParams['id']) {
		focusOn = requestParams['id'];
	}

	if (requestParams['tl']) {
		tailLength = requestParams['tl'];
	}
	
	if (requestParams['ts']) {
		trackStart = requestParams['ts'];
	}
	
	if (requestParams['zoom']) {
		zoomLevel = requestParams['zoom'];
	}
	
	if (requestParams['lat']) {
		initialLat = requestParams['lat'];
	}
	
	if (requestParams['lng']) {
		initialLong = requestParams['lng'];
	}
	
	
	setTimeout("reloadPage()", reloadPageInterval);
	
	setStatus("Initializing document");
	
	loadViewMap("map");
	Log.write("Map initialized");
	
	loadData();
	setStatus("Document initialized");	
}

function reloadPage() {
	params = document.location.search;

	params = insertGetParameter(params ,"id",focusOn);
	//add GPX parameters
	params = insertGetParameter(params ,"tl",tailLength);
	params = insertGetParameter(params ,"ts",trackStart);
	
	//add map parameters
	params = insertGetParameter(params ,"zoom",zoomLevel);
	params = insertGetParameter(params ,"lng",initialLong);
	params = insertGetParameter(params ,"lat",initialLat);
	
	//add UI parameters
	params = insertGetParameter(params ,"autocenter",autoCenter);
	params = insertGetParameter(params ,"audioalarm",audioAlarm);
	
	document.location.search = params;
	
	// reload, set the 'forceGet' parameter to true
	document.reload(true);
}//end reload page

/**
  * function that inserts, replaces or append a GET parameter
  *
  * @param url parameters
  * @param GET parameter name
  *
  * @return params (updated input)
  *
  */
function insertGetParameter(params,name,value){
	// does the URL have a search parameter already?
	if (params.indexOf(name+"=") > -1) {
		// otherwise, replace it with the item that currently has focus
		var param = new RegExp(name+"=[0-9a-zA-Z\.]+", "gi" );
		var newParam = name+"=" + value;
		
		params = params.replace(param, newParam);
	}
	else {
		// if not, add it
		if (params.length > 1) {
			params += "&"+name+"=" + value;
			
		}else {
			params = "?"+name+"=" + value;
		}
	}//end if-else parameter
	return params;
	
}//end insertGetParameter



function loadData() {
	if (gpxUrl.length > 0) {
		// Make URL unique to circumvent problems with caching
		
		// Does the URL have parameters?
		var searchStr = gpxUrl.lastIndexOf("?");
		
		// Is the URL pointing to a different directory?
		var dirSeperator = gpxUrl.lastIndexOf("/");
		
		var glue = "&";	
		if (searchStr == -1 || dirSeperator > searchStr) {
			glue = "?";
		}
		
		fetchUrl = gpxUrl + glue + "t=" + (new Date()).getTime();
		
		//add GET parameters
		fetchUrl += "&tl="+ tailLength;
		fetchUrl += "&ts="+ trackStart;

		GDownloadUrl(fetchUrl, function(data, responseCode){
			onGPXLoad(data, responseCode);
		});
	}

	return true;
}

function setStatus(status) {
	Log.write("status: " + status);
	
	var statusNode = document.createTextNode(status);
	
	setContents(document.getElementById("status"), statusNode);
}

function setGpxFile(url) {
	var gpxNode = document.createElement("a");
	gpxNode.setAttribute("href", "url");
	gpxNode.setAttribute("target", "_blank");
	gpxNode.appendChild(document.createTextNode("gpx file"));
	
	setContents(document.getElementById("gpx_file"), gpx);
}

/*
 * Set a node's content
 */
function setContents(node, content) {
		clearChildren(node);
		node.appendChild(content);
}

/*
 * Remove all children of a node
 */
function clearChildren(node) {
	for (i = node.childNodes.length - 1; i >= 0; i--){
		node.removeChild(node.childNodes[i]);
	}
	/*while(node.hasChildNodes()) {
		node.removeChild(node.lastChild)
	}*/
}

function printf(args) {
	var nS = "";
	var tS = arguments[0].split("%s");
	
	var L = [];
	for (var i = 1; i < arguments.length; i++)
    	L[i-1] = arguments[i];
	
	for (var i=0; i<tS.length; i++)
		if (tS[i].lastIndexOf('%')==tS[i].length-1) tS[i] += "s"+tS.splice(i+1,1)[0];
	
	if (tS.length != L.length+1) throw "printf input error";

	for(var i=0; i<L.length; i++)
		nS += tS[i] + L[i];
	return nS + tS[tS.length-1];
}

function getRequestParams() {
	var qs = location.search.substring(1);
	var nv = qs.split('&');
	var url = new Object();
	for(i = 0; i < nv.length; i++){
		eq = nv[i].indexOf('=');
		url[nv[i].substring(0,eq).toLowerCase()] = unescape(nv[i].substring(eq + 1));
	}
	return url;
}

function getTime() {
	var now = new Date();
	var secs = now.getSeconds();
	secs = (secs.length < 2) ? "0" + secs.toString() : secs.toString();
	return now.getHours() + ":" + now.getMinutes() + ":" + secs;
}

function getDate() {
	var now = new Date();
	return now.getDate() + "-" + (now.getMonth()+1) + "-" + takeYear(now);
}

function takeYear(date) {
	var x = date.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}

// Escape XML special markup chracters: tag delimiter < > and entity
// reference start delimiter &. The escaped string can be used in XML
// text portions (i.e. between tags).
function xmlEscapeText(s) {
  return ('' + s).replace(/&/, '&amp;').replace(/</, '&lt;').replace(/>/, '&gt;');
}

// Escape XML special markup characters: tag delimiter < > entity
// reference start delimiter & and quotes ". The escaped string can be
// used in double quoted XML attribute value portions (i.e. in
// attributes within start tags).
function xmlEscapeAttr(s) {
  return xmlEscapeText(s).replace(/\"/, '&quot;');
}

// Escape markup in XML text, but don't touch entity references. The
// escaped string can be used as XML text (i.e. between tags).
function xmlEscapeTags(s) {
  return s.replace(/</, '&lt;').replace(/>/, '&gt;');
}

/**
  * Check if variable is defined 
  * for IE 6 and FF
  */
function isDefined(variable){
	return (typeof(window[variable]) == "undefined")?  false: true;
}

/**
  * Simple popup function
  *
  */
function popup(url) {
	window.open( url, "SMARTposition", "status = 1, height = 300, width = 700, resizable = 1" );
}
