// JavaScript


//globals
	varLogRegisterSubmitClicked = false;
	
	
function DoLoadStuff()
	{
	varLogRegisterSubmitClicked = false;
	}


function open_win(varShowNum) 
	{ 
	// For use, install 'onclick' event for the element used to trigger a call to this routine.  Pass the show number
	// as a string.
	window.open("http://coloradooutspoken.net/watched.php?shownum=" + varShowNum,"_blank","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=450, height=325")
	}  
	
function log_sponsor(varSponsor) 
	{
	// For use, install 'onclick' event for the element used to trigger a call to this routine.  Pass the sponsor
	// name as a string.
	varURL = location.href
	varURL = varURL.slice(varURL.lastIndexOf("/"))
	window.open ("http://coloradooutspoken.net/sponsor.php?sponsor=" + varSponsor + "&lurl=" + varURL)
	}
	
	
function clearFormFields()
	{
	//clears all text and password fields from all forms on the page
	
	for (var i=0; i<document.forms.length; i++)						//enumerate all forms on the page
		{
		//for each form, go through all the elements
		for (var j=0; j<document.forms[i].length; j++)				
			{
			var formElement=document.forms[i].elements[j]
			//if the element is text or password, clear it
			if (formElement.type == 'text' || formElement.type == 'password')
				{
				formElement.value=''
				}
			}
		}
	}


function resetAllForms()
	{
	// resets all forms on the page
	for (var i=0; i<document.forms.length; i++)						//enumerate all the forms on the page
		{
		document.forms[i].reset()									//reset each form
		}
	}

function regHelp(varWhich)
	{
	// displays help information for user registration
	
	varDiv = document.getElementById('reghelp')
	switch (varWhich)
		{
		case 'username':
			varDiv.innerHTML = "Your Username can be any sequence of letters, digits, and punctuation marks up to a maximum length of 20 characters.  Case is not significant (username = UserName = USERname, etc.)"
			break;
			
		case 'email':
			varDiv.innerHTML = "Your email address must be properly formed and must contain no spaces.  Examples would include: john@domain.com, john.smith@domain.com, john_smith@domain.com<br /><br />Please enter a valid address, since we notify our winners by email.  If your address is invalid, we can't notify you when you win.<br /><br />We will not share your email address with anyone!"
			break;
			
		case 'phone':
			varDiv.innerHTML = "Your telephone number may be entered in any format: (303) 555-1212, 303-555-1212, 3035551212.  It must contain the number and the area code.<br /><br />If you don't want us to have your phone number, just enter any 10 digits."
			break;
			
		case 'pw':
			varDiv.innerHTML = "Your password can be any sequence of letters, digits, and punctuation marks up to a maximum of 20 characters.  Case IS significant (password is not the same as PAssWord).  You should try to include upper and lower case letters, digits, and punctuation marks in your password because such passwords are much harder for an unauthorized person to guess.<br /><br />Your password is encrypted before transmission to our site."
			break;
	
		}
		
	//show the help box
	varDiv.style.visibility="visible"
	varDiv.style.zIndex=1
	}

function hideHelp()
	{
	// removes the help box
	varDiv = document.getElementById('reghelp')
	varDiv.style.visibility="hidden"
	varDiv.style.zIndex=-1
	}

function hashString(varInString, varXorString)
	// a function to hash a string that has been XOR'd with another string
	{
	// XOR the strings and hash the result using SHA1 (code for the function must be included)
	return hex_sha1(XorStrings(varInString,varXorString))
	}
		
		
function XorStrings(varInString, varXorString)
	// a function to XOR one string with another; returns the XOR'd string
	{
	var i;
	var s = "";
	var x = 0;
	
	
	// ensure the XOR string is long enough
	while ( varXorString.length < varInString.length )
		{
		varXorString = varXorString + varXorString
		}
	
	// step through the strings
	for ( i = 0; i<=varInString.length-1; i++)
		{
		// XOR the character codes of the corresponding character in each string
		x = varInString.charCodeAt(i) ^ varXorString.charCodeAt(i)
		// convert the value to hex and concatenate it with the output string
		h = x.toString(16)					// to hex (could be only one character!)
		if (h.length == 1) h = "0" + h		// if so, install a leading zero
		s = s + h
		}
		
	// return the XOR'd string
	return s
	}
	

//-------------------------------------cursor placement/form functions

	function put_cursor(varElementId)
		{
		document.getElementById(varElementId).focus()
		}

	function submit_formById(varFormId)
		{
		document.getElementById(varFormId).submit()
		}

	function tabToNext(e,varWhere,event)
		{
		// this function processes a press of the Enter key
		//		if 'varWhere' is 'submit', the form containing the element in which the cursor
		//		was present when Enter was pressed is submitted;
		//		if 'varSubmit' is FALSE, a Tab character is written to the document
		
		var keycode;
		
		// get the keycode of the pressed key
		if (window.event) 
			{
			// must be IE
			keycode = window.event.keyCode;
			varIsIE = true;
			}
			else 
				{
				// test for Mozilla
				if (event) 
					{
					// is Mozilla
					keycode = event.which;
					varIsIE = false;
					}
					else 
						{
						return true;	//can't handle the event
						}
				}
		
		// do nothing if key is not Enter
		if (keycode != 13) return true;
		
		// action depends upon 'varWhere'; if varWhere = 'submit', submit the form
		if (varWhere == 'submit')
			{
			// TRUE, so submit the form containing the element
			e.form.submit();
			return false;
			}
			else
				{
				// FALSE: what we do depends upon the browser type
				if (varIsIE)
					{
					// for IE, we just need to substitute TAB for CR
					window.event.keyCode = 9
					}
					else
						// Mozilla is differetn...we must set the focus to the element named in varWhere
						{
						put_cursor (varWhere)
						}
				return true;
				}
		}
	
//-------------------------------------email functions

function em (a,b)
	{
	var s = "?subject=" + b
	return ('<a href=\"mailto:' + a + '@' + 'coloradooutspoken.net' + s + '\">Send email</a>')
	}
	
function lem (a,b)
	{
	window.open ("mailto:" + a + "@coloradooutspoken.net?subject=" + b)
	document.write ("Please close this window to return to Coloraod OutSpoken.")
	}
	
function this_url()
	{
	return location.href
	}
	

//-------------------------------------AJAX functions

function ajaxMakeHTTPObj ()
	{
	//this function attempts to create the required xmlHTTPRequest object
	var xmlHttp;
	try
		{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
		}
		catch (e)
			{
			// Internet Explorer
			try
				{
				xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
				}
				catch (e)
					{
					try
						{
						xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
						}
						catch (e)
							{
							alert("Your browser does not support the functionality needed to access our site.\n\nYou should consider upgrading your browser.");
							return false;
							}
					}
			}
	return xmlHttp;
	}
	

function ajaxLogRegister(varWhich, varFormId)
  {
	//prevent more than one click
	if (varLogRegisterSubmitClicked === true)
		{
		alert ("Your information has been submitted to the server. Clicking the button more will not speed up the process!")
		return
		}

  var xmlHttp;
  xmlHttp = ajaxMakeHTTPObj()
  
  //verify object created successfully
  if ( !xmlHttp )
  	{
  	alert ("An error has prevented this operation (LR-001). Please send an email to webmaster@coloradooutspoken.net to let us know.")
	}
	else
		{
		// this is the code that executes upon return from the php script
		xmlHttp.onreadystatechange=function()
		  {
		  if(xmlHttp.readyState==4)
			{
			// determine if response was an error or OK (for error, the first character is '0'; for 
			// OK, the first character is '1'
			varErrorCode = xmlHttp.responseText.slice(0,1)
			varHTML = xmlHttp.responseText.slice(1)
			
			// for the error case, we want the HTML to go to the "error" div
			if (varErrorCode == 0)
				{
				varErrDiv = document.getElementById('error_div')
				varErrDiv.style.color = '#ff0000'
				varErrDiv.innerHTML = varHTML
				}
				else
					// for the OK case, we want the HTML to go to the "content" div
					{
					document.getElementById("content").innerHTML = varHTML
					}
					
			varLogRegisterSubmitClicked = false		//allow future clicks
			}
		  }
		  
		//---------------------------------------------------------
		  
		  
		// note the button has been clicked
		varLogRegisterSubmitClicked = true
		
		// show the user that we're processing the input
		varErrDiv = document.getElementById('error_div')
		varErrDiv.style.color = '#000000'
		varErrDiv.innerHTML = 'Your information is being processed. Please wait...'
		
		// identify the script to execute and the method of passing values
		xmlHttp.open("POST","/php/" + varWhich + ".php",true);
		
		// for POSTed data, we must do this...
		xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		
		// build the POST data string
		varForm=document.getElementById(varFormId);	//create a form object
		
		varPostRequest = ''							//start with an empty string
		
		// loop for all elements in the form
		for (var i=0; i<varForm.length; i++)
			{
			varFormElement = varForm.elements[i]	//create an element object
			
			// if the element is a checkbox named 'emailok' then get its checked/unchecked state
			if (varFormElement.name == 'emailok')
				{
				// special case for this checkbox; send "on" if checked or "off" if not
				if (varFormElement.checked)
					{
					varCheckValue = "on"
					}
					else
						{
						varCheckValue = "off"
						}
				varPostRequest = varPostRequest + 'emailok=' + varCheckValue + "&"
				}
				else
					// for other elements, verify they are either text or password and include their values in the data
					{
					if ((varFormElement.type == "text") || (varFormElement.type == "password"))
						{
						// for passwords, we need to process further...
						if (varFormElement.name.indexOf("pw") > -1)		//see if element name contains "pw"
							{
							// passwords for log-in are XOR'd with the challenge value sent from the server and then hashed;
							// passwords for registration are just XOR'd with the challenge value (no hash)
							// passwords for edits may not exist; if not, send an empty string
							
							//see which function we're doing
							if (varWhich.indexOf("validate") > -1)
								{
								// doing log-in
								varValue = hashString(varFormElement.value, document.getElementById('challenge').value)
								}
								else if (varWhich.indexOf("register") > -1)
									{
									// doing registration
									varValue = XorStrings(varFormElement.value, document.getElementById('challenge').value)
									}
									else if (varWhich.indexOf("edit") > -1)
										{
										// doing edit
										varValue = varFormElement.value.trim()
										if (varValue.length > 0)
											{
											// user entered something
											varValue = XorStrings(varValue, document.getElementById('challenge').value)
											}
										}
										else
											{
											varValue="nothing"
											}
							}
							else
								{
								varValue = varFormElement.value
								}
						
						// add the parameter/value to the data
						varPostRequest = varPostRequest  + varFormElement.id + '=' + varValue + "&"
						}
					}
			}

		// for POST, we send the POST values as a string via 'xmlHttp.send'; the string is structured as:
		//		value_name1=value&value_name2=value&...&value_name_last=value  (ex. "count=23&name=smith")
		// trim off the trailing "&"
		varPostRequest = varPostRequest.slice(0,varPostRequest.length-1)
		xmlHttp.send(varPostRequest);	
		  
		/*	// for GETed data, we do this...
		xmlHttp.open("GET",target_url,true)
			// no '.setRequestHeader()' required
		xmlHttp.send(null);
		*/
		}
  }
  
function new_page(url)
	{
	// this function replaces the current page with a new one
	window.location.replace(url);
	}
  
function load_page(url)
	{
	// this function loads a new page
	window.location.assign(url);
	}

function lrtrim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function typeOf(value) {
    var s = typeof value;
    if (s === 'object') {
        if (value) {
            if (typeof value.length === 'number' &&
                    !(value.propertyIsEnumerable('length')) &&
                    typeof value.splice === 'function') {
                s = 'array';
            }
        } else {
            s = 'null';
        }
    }
    return s;
}


function isEmpty(o) {
//  isEmpty(v) returns true if v is an object containing no enumerable members.	
    var i, v;
    if (typeOf(o) === 'object') {
        for (i in o) {
            v = o[i];
            if (v !== undefined && typeOf(v) !== 'function') {
                return false;
            }
        }
    }
    return true;
}

String.prototype.entityify = function () {
/*
entityify() produces a string in which '<', '>', and '&' are replaced with their HTML entity equivalents. This is essential for placing arbitrary strings into HTML texts. So,

    "if (a < b && b > c) {".entityify()

produces

    "if (a &lt; b &amp;&amp; b &gt; c) {"
*/
    return this.replace(/&/g, "&amp;").replace(/</g,
        "&lt;").replace(/>/g, "&gt;");
};

String.prototype.quote = function () {
/*
 quote() produces a quoted string. This method returns a string that is like the original string except that it is wrapped in quotes and all quote and backslash characters are preceded with backslash.
*/
    var c, i, l = this.length, o = '"';
    for (i = 0; i < l; i += 1) {
        c = this.charAt(i);
        if (c >= ' ') {
            if (c === '\\' || c === '"') {
                o += '\\';
            }
            o += c;
        } else {
            switch (c) {
            case '\b':
                o += '\\b';
                break;
            case '\f':
                o += '\\f';
                break;
            case '\n':
                o += '\\n';
                break;
            case '\r':
                o += '\\r';
                break;
            case '\t':
                o += '\\t';
                break;
            default:
                c = c.charCodeAt();
                o += '\\u00' + Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }
        }
    }
    return o + '"';
};

String.prototype.supplant = function (o) {
/*
supplant() does variable substitution on the string. It scans through the string looking for expressions enclosed in { } braces. If an expression is found, use it as a key on the object, and if the key has a string value or number value, it is substituted for the bracket expression and it repeats. This is useful for automatically fixing URLs. So

param = {domain: 'valvion.com', media: 'http://media.valvion.com/'};
url = "{media}logo.gif".supplant(param);

produces a url containing "http://media.valvion.com/logo.gif".

*/
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

String.prototype.trim = function () {
//  The trim() method removes whitespace characters from the beginning and end of the string.

    return this.replace(/^\s+|\s+$/, "");
}; 