﻿//http://www.netlobo.com/url_query_string_javascript.html

urlDecode = function(encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output.replace(/\+/g, " ");
}

function getUrlParam( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return urlDecode(results[1]);
}

function getUrlParamNames( ) // gpn stands for 'get parameter names'
{
	var params = new Array( );
	var regex = /[\?&]([^=]+)=/g;
	while( ( results = regex.exec( window.location.href ) ) != null )
		params.push( results[1] );
	return params;
}

function getUrlQuery() {
	return window.location.href.match(/(\?.*)?$/)[0];
}

function pullInQuerystring(form) {
    ///Pull through all existing qs variables:
    var names = getUrlParamNames();
    for(var i=0; i < names.length; i++) {
        var key = names[i];
        
        //except ones we're going to overwirte e.g. "step":
        if(form[key]) { continue; }
        
        var e = document.createElement("input");
        e.setAttribute("type", "hidden")
        e.setAttribute("name", key);
        e.setAttribute("value", getUrlParam(key))
        form.appendChild(e);
    }
}

htmlToText = function(ch, preserveLineBreaks) {

    if(typeof(preserveLineBreaks) == "undefined") {
        preserveLineBreaks = true;
    }
    
    if(ch == null) {
        return null;
    }
    
    ch = new String(ch);
    
  	//http://www.asp-php.net/tutorial/asp-php/glossaire.php?glossid=57
	ch = ch.replace(/&/g,"&amp;");
	ch = ch.replace(/\"/g,"&quot;");
	ch = ch.replace(/\'/g,"&#039;");
	ch = ch.replace(/</g,"&lt;");
	ch = ch.replace(/>/g,"&gt;");
	
	if(preserveLineBreaks) {
    	ch = ch.replace(/\n/g,"&nbsp;<br/>");
    }
    
	return ch;
}

setCookie = function(sName, sValue)
{
  document.cookie = sName + "=" + escape(sValue) + "; expires=; ; path=/"
}

getCookie = function(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
    {
		if(!aCrumb[1])
		{
			//alert("returning nothing");
			return ""
		}
		else
		{
			//alert("returning: " + unescape(aCrumb[1]))
			return urlDecode(aCrumb[1]);
		}
    }
  }

  // a cookie with the requested name does not exist
  return "";
}