$(document).ready(
	function()
	{
		$('#viser-form :input').each(
			function()
			{
				var name = $(this).attr('name');
				if( $.jqURL.get(name) )
					$(this).val( unescape($.jqURL.get(name)) );
				if( $.jqURL.get('errors[' + name + ']') )
					writeError( this, urldecode( $.jqURL.get('errors[' + name + ']' ) ) );
			}
		);

		if( $.jqURL.get('errors[global]') )
		{
			$('#main-error').html( urldecode( $.jqURL.get('errors[global]' ) ) );
		}
	}
);

/**
	Credit for below
	http://www.quirksmode.org/dom/error.html
**/
var W3CDOM = ( document.getElementsByTagName && document.createElement );
function writeError( obj,message )
{
	validForm = false;
	if( obj.hasError ) return;
	if( W3CDOM )
	{
		obj.className += ' error';
		obj.onchange = removeError;
		var sp = document.createElement('span');
		sp.className = 'error';
		sp.appendChild(document.createTextNode(message));
		obj.parentNode.appendChild(sp);
		obj.hasError = sp;
	}
	else {
		errorstring += obj.name + ': ' + message + '\n';
		obj.hasError = true;
	}
}

function removeError()
{
	this.className = this.className.substring(0,this.className.lastIndexOf(' '));
	this.parentNode.removeChild(this.hasError);
	this.hasError = null;
	this.onchange = null;
}

function urldecode( encoded )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while( i < encoded.length )
   {
       var ch = encoded.charAt(i);
	   if(ch == "+")
	   {
	       plaintext += " ";
		   i++;
	   }
	   else if (ch == "%")
	   {
			if( i < ( encoded.length - 2 ) && HEXCHARS.indexOf( encoded.charAt( i+1 ) ) != -1 && HEXCHARS.indexOf( encoded.charAt( i+2 ) ) != -1 )
			{
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			}
		}
		else
		{
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};

