// call on any page at load to preserve any session ID (put on all static pages)

function Patch_Links() {
    var sid = Get_Session_ID();
    if(!sid) return;     // no session, no patch
    Patch_Links_To(sid);
}

function Set_Session_URL(url,sid) {
    var whereat = url.indexOf("session=");
    if(whereat == -1) { // not if already there
	var x = url.indexOf("?");
	if(x != -1) {       // has some CGI already
	    url = url.slice(0,x+1)+"session="+sid+"&"+url.slice(x+1);
	} else {            // none
	    url += '?session='+sid;
	}
	return url;
    } else {  // it has a session
	var idend = url.indexOf("&",whereat);
	var nurl;
	if(sid == '') {   // we are deleting the session
	    nurl = url.slice(0,whereat);
	    if(idend != -1)
		nurl += url.slice(idend+1);
	} else {          // updating it
	    var nurl = url.slice(0,whereat+8)+sid;  // new sid
	    if(idend != -1) {  // last or only parameter
		nurl += url.slice(idend);
	    }
	}
    }
    return nurl;
}

function Patch_Links_To(sid) {
    var hr = "";
    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) {
	    document.links[i].href = Set_Session_URL(hr,sid);
	}
    }
    // patch the quicksearch form (or other similar) as well
    if(document.getElementById('session'))
	document.getElementById('session').value = sid;
}

