var cookie_data;

var version = '0';   // anti-caching tweaker

function $(id) {
    return document.getElementById(id);
}

function Check_Logon_Status(calledby) {
    if(typeof(cp_info) != 'undefined' && cp_info.userid) {
	Set_Logon_Status(true,cp_info);
	return;
    }
    /* August 2009 - logging in to route planner page fails, and I
     * don't see how it ever worked.  Removing this check means it
     * looks at the session ID which should do what we need */
    //    if(typeof(calledby) == 'string' && calledby == 'homepage') {
    // Jan 2010 - new dynamic session code loaded when needed
    var sid = Get_Session_ID();
    if(sid) {
	Talk_To_Server('autologin',{session:sid},null,null,Set_Logon_Status,null);
	return;
    }
    //    }
    Read_Canalgaz_Cookies();
    if(cookie_data.userid && cookie_data.rpwd) {
	Talk_To_Server('autologin',{user:cookie_data.userid,rpwd:cookie_data.rpwd},null,null,Set_Logon_Status,null);
	return;
    }
    Set_Logon_Status(false);
}

function Do_Logon() {
    var q = document.getElementById('workspace');
    if(q == null) {
	var wksp = document.createElement('div');
	wksp.style.display = 'none';
	wksp.id = 'workspace';
	document.body.appendChild(wksp);
    }    
    Dynamic_HTML('workspace','logon.html',Show_Login_Box);
}

function Show_Login_Box() {
    Popup('login_box','li_username');
}

function Log_Me_Out() {
    Set_Logon_Status(false);
}

function Talk_To_Server(mode,params,good,bad,action,subparams) {
    var cgi = 'mode='+mode;
    var subp = [];
    var xmlhttp;
    if(mode != 'autologin') {
	for(var i in params) {
	    var x = document.getElementById(params[i]);
	    if(x.type == 'checkbox')
		cgi += '&'+i+'='+x.checked;  
	    else
		cgi += '&'+i+'='+x.value;
	}
	// we need to get values in sub params now, as they will be gone later
	for(var i in subparams) {
	    subp[i] = document.getElementById(subparams[i]);
	}
	var sid = Get_Session_ID();
	if(sid)
	    cgi += '&session='+sid;
    } else {
	cgi = 'mode=login';
	for(var i in params) {
	    cgi += '&'+i+'='+params[i];
	}
    }
    Kill_Popup('login_box');
    xmlhttp = XMLHTTP_Item();
    xmlhttp.onreadystatechange=function() {
	if (xmlhttp.readyState==4) {
	    if (xmlhttp.status==200) {
		var r = xmlhttp.responseText.replace(/\n/g,'');
		r = r.replace(/\r/g,'');
		if(r.charAt(0) == '?') {
		    if(bad)
			alert(bad);
		    if(action)
			action(false,r.slice(1),subparams);
		} else if(r.charAt(0) == '!') {
		    if(good)
			alert(good,null,subp);
		    if(action)
			action(true,r.slice(1),subp);
		}
		else
		    alert("Server sent faulty response");
	    }  
	}
    };
    xmlhttp.open("GET",Prune_Link()+"cgi-bin/logon.cgi?"+cgi,true);
    xmlhttp.send(null);
}

// avoid asynchronous problems
function Works_Of_Log_In(ison,retval,params) {
    Set_Logon_Status(ison,retval,params);
    // reload the window (gazetteer, say, might change dramatically)
    // but don't do it for the index page or any page with a "noreload"
    if(window.location.href.indexOf('cgi-bin') != -1 && !cp_info.noreload) {
    	window.location.href = Set_Session_URL(window.location.href,cp_info.session);
    }
    // set the new session ID if there is a place for it
    var sesid = document.getElementById('sessionid');
    if(sesid) {
	sesid.value = cp_info.session;
    }
}

function Log_Me_In() {
    if(typeof(cp_info) == 'undefined')
	cp_info = new Object();
    Talk_To_Server('login',{user:'li_username',pwd:'li_password',sticky:'li_remember'},null,"User name or password not recognised",Works_Of_Log_In,{sticky:'li_remember'});
}

function Send_Password() {
    Talk_To_Server('send_password',{user:'li_username'},"Your password has been sent by email","User name not recognised");
}

function Create_Account() {
    var p1 =  document.getElementById('ca_password').value;
    var p2 =  document.getElementById('ca_reppassword').value;
    if(p1 != p2) {
	alert("Passwords don't match");
	return;
    }
    if(p1 == '') {
	alert("Password empty");
	return;
    }
    Talk_To_Server('create',{user:'ca_username',display:'ca_dispname',email:'ca_emailadd',pwd:'ca_password',sticky:'ca_remember'},"Your account has been created","Sorry, that user already exists",Set_Logon_Status,{sticky:'ca_remember'});
}

function Transfer_Account() {
    Talk_To_Server('transfer_account',{user:'ta_username',pwd:'ta_password',type:'ta_type'},"Account transferred","User name or password not recognised",Set_Logon_Status,{sticky:'ta_remember'});
}
    
function Popup_Create_Account() {
    Popup('create_account_box','ca_username');
}

function Popup_Transfer_Account() {
    Popup('transfer_account_box','ta_username');
}

function Set_Logon_Status(ison,retval,params) {
    var box = document.getElementById('logon_status');
    if(!box)
	return;          // no status on pages without a menu
    var cdata = [];
    if(ison) {
	if(typeof(retval) == 'string')
	    var info = eval('('+retval+')');
	else
	    var info = retval;
	cdata.userid = info.userid;
	cdata.rpwd = info.rpwd;
	// if needed, it will have been loaded
	if(typeof(Patch_Links_To) == 'function') {
	    Patch_Links_To(info.session);
	}
	if(typeof(cp_info) != 'undefined' && info.session) {
	  cp_info.session = info.session;
	}
	if(typeof(params) != 'undefined') {
	    if(params.sticky && params.sticky.checked) {
		Set_Cookie(cdata,365);
	    } else {
		if(cookie_data && (cookie_data.userid != cdata.userid || cookie_data.rpwd != cdata.rpwd)) {   // not sticky, and not the same as before
		    Set_Cookie(cdata,-1);
		}
	    }
	}
	var t = 'Logged on as '+info.display;
	t+='<br><span class="linklike" onclick="Log_Me_Out()">Log out</span>';
	box.innerHTML = t;
	Check_Rights(info);
    } else {
	box.innerHTML = '<span class="linklike" onclick="Do_Logon()" style="font-size: 100%">Log in/Create account</span>';
	Set_Cookie('',-1);
    }
    // some pages change when you log-on
    if(typeof(Setup_Editables) == 'function') {
	Setup_Editables(ison);
    }
    Show_Hidden_Menu_Items(ison);
    var st = 'none';
    if(ison) st = 'block';
    var a = $('edit_menu');
    if(a) a.style.display=st;
    if(typeof(amiloggedon) != "undefined")  // a global in any file that needs the info
	amiloggedon = ison;
}

function Show_Hidden_Menu_Items(ison) {
    var i = 0;
    var a = document.getElementsByTagName("div");
    while (element = a[i++]) {
	if(element.className.indexOf('useronly') != -1) {
	    if(ison)
		element.style.display = 'block';
	    else
		element.style.display = 'none';
	}
    }
}

function Check_Rights(userrec) {
    if(userrec.ismod) {
	var a = $('moderator');
	if(a) a.style.display = "block";
    }
}

var popupis = '';

function Popup(contentsId,focusId, style) {
  var id = document.getElementById(contentsId);
  if(id == null)
    throw new UserException("No block for popup");
  var div = document.getElementById('popup_div');
  if(div == null) {
    var div = document.createElement('div');
    div.style.display = "none";
    div.id = 'popup_div';
    document.body.appendChild(div); 
  }
  if(style)
      div.className = style;
  else
      div.className = "popUp";
  // create out of sight
  div.style.left = "-2000px";
  div.style.top = "0px";
  
  div.innerHTML = '<div style="text-align:right; font-size:70%"><span class="linklike" onclick="Kill_Popup(\'any\')">Close</span></div>';
  div.innerHTML += id.innerHTML.replace(/INACTIVE_/g,'');
  div.style.display = "block";
  // Get window size, coping with browser (IE - obviously!) oddities
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
    //    alert(myWidth+','+myHeight);
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
 // adjust position now since once displayed, size is known
  div.style.left = ((myWidth - div.offsetWidth)/2) + 'px';
  div.style.top = ((myHeight - div.offsetHeight)/2) + 'px';
  div.style.zIndex = 500;
  if(focusId && focusId != "")
      document.getElementById(focusId).focus();
  grayOut(true);
  popupis = contentsId;
}

window.Kill_Popup =function(what) {
    if(what != 'any')
	if(what != popupis)      // prevents wrong box getting killed
	    return;
  var div = document.getElementById('popup_div');
  if(div) {
    div.innerHTML = '';
    div.style.display = 'none';
    grayOut(false);
  }
}

function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    /* I don't know what is going wrong here, but I'm only getting the height of the header bar in Firefox.  So fake it */
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
	if(document.body.offsetHeight < 200)
	    pageHeight = '100%';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
      if(document.body.offsetHeight < 200)
	  pageHeight = '100%';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }   
    //set the shader to cover the entire page and make it visible.
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.display='block';                          
  } else {
     dark.style.display='none';
  }
}

function Dynamic_HTML(divid, filename, tocall) {
  var area = document.getElementById(divid);
  var xmlhttp = XMLHTTP_Item();
  xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4) {
	  if (xmlhttp.status==200) {
	      area.innerHTML = xmlhttp.responseText;
	      if(tocall)
		  tocall();
	  }  
      }
  };
  xmlhttp.open("GET", Prune_Link()+"html/"+filename+"?v="+version, true);
  xmlhttp.send(null);
}

function Set_Cookie(holds,expireoffset) {
    var hlst = '';
    if(holds) {
	for(var i in holds) {
	    if(hlst)
		hlst += '&';
	    hlst += i+':'+holds[i];
	    cookie_data[i] = holds[i];
	}
    }
    var cstring = 'CanalPlanAC9=' + escape(hlst);
    var today = new Date();
    var expire = new Date();
    if (expireoffset) {
	expire.setTime(today.getTime() + 3600000*24*expireoffset);
	cstring += ";path=/;expires="+expire.toGMTString();
    }
    document.cookie = cstring
}

function XMLHTTP_Item() {
  var xmlhttp=null;
  // first for all but IE, else for IE
  if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest()
  } else if (window.ActiveXObject) {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  }
  if (xmlhttp == null) {
    throw("noxmlhttp");
  }
  return xmlhttp;
}

function Read_Canalgaz_Cookies() {
  cookie_data = new Object;
  var carray = document.cookie.split(";");
  for(var i=0; i<carray.length;i++) {
    var tcookie = carray[i].split("=");
    // there may be spaces in the cookie strings
    if(tcookie[0].replace(/^\s+|\s+$/g, '') == 'CanalPlanAC9') {
      var ns = unescape(tcookie[1].replace(/^\s+|\s+$/g, ''));
      if(ns) {        // cookie could be there but empty
	  var iarray = ns.split("&");
	  for(var j=0; j<iarray.length;j++) {
	      var titem = iarray[j].split(":");
	      if(titem.length == 2)
		  cookie_data[titem[0]] = titem[1].replace(/\+/g," ");
	      else
		  cookie_data[titem[0]] = '--empty--';
	  }
      }
    }
  }
}

// check for login before allowing save and delete of routes
function Save_Etc_Route(id,mode) {
    /* create a hidden submit_4 and "click on it" to submit.  This
     * means that anything that has been added to the form will not be
     * lost before saving */
    function Revector_4(id,mode) {
	var e = document.createElement('input');
	var c = document.createElement('div');
	e.type="submit";
	c.style.display = "none";
	e.name = "submit_4";
	e.value = mode + ':' + id;
	document.canalform.appendChild(c);
	c.appendChild(e);
	e.click();
    }
    if(mode == 'load' || amiloggedon) {
	Revector_4(id,mode);
	return;
    }
    alert("You must be logged on to "+mode+" a route");
}

/* This is messy, but works - tweaked Aug 2009 to cope with url re-writing */
function Prune_Link() {
    var x = ""+window.location;  // force to string
    var tr = x;
    var patts = ['/html/','/cgi-bin/','/place/','/gazetteer/','/waterway/'];
    for(i in patts) {
	var q = x.indexOf(patts[i]);
	if(q != -1)
	    tr = x.slice(0,q);
    }
    if(tr == x) {   // didn't work, must be index
	var q = x.indexOf('/index.html');
	tr = x.slice(0,q);
    }
    return tr+'/';    
}

// January 2010.  Use whenever you want to get the current session ID.
// Can check a variety of sources, and provides the right session ID
// to build into links and page loads.

// This querystring object is from
// http://adamv.com/dev/javascript/files/querystring.js
/* Client-side access to querystring name=value pairs
	Version 1.3
	28 May 2008
	
	License (Simplified BSD):
	http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};
	
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
};

// main function
function Get_Session_ID() {
    // we try all sorts of different routes.  First, was I given it
    // anyway?
    if(typeof(cp_info) != 'undefined' && cp_info.session) {
	return cp_info.session;
    }
    if(typeof(cp_info) != 'undefined' && cp_info.sesid) {
	return cp_info.sesid;
    }
    // otherwise, is it already in a useful URL?
    for(var i=0;i < document.links.length;i++) {
	hr = document.links[i].href;
	// find links within the site
	if(hr.indexOf("http://"+window.location.hostname) == 0) {
	    var whereat = hr.indexOf("session=");
	    if(whereat != -1) {
		var idend = hr.indexOf("&",whereat);
		if(idend != -1)
		    return hr.substring(whereat+8,idend);
		else
		    return hr.substring(whereat+8);
	    }
	}
    }
    // if not, try for a query string
    var qs = new Querystring();
    // however, a session ID extracted from a query string won't have
    // had the serial number incremented, so we have to do that by
    // hand
    var sid = qs.get('session');
    if(sid) {
	var parts = sid.split("_");
	var n = parseInt(parts[1]);
	n += 1;
	return parts[0]+'_'+n;
    } else
	return sid;   // NULL
}
