/** 
 * This file is a server-side merge of tw-sack.js and gadgets.js.php
 * 
 * ------------------------------ tw-sack.js -------------------------------
 */
 
/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}

/** 
 * ----------------------------- gadgets.js.php ------------------------------
 */
 
var gu_gadgets_formless = false;
var gu_gadgets_subcribe_url = "http://www.sunsations-tanning.ca/news/subscribe.php";
var gu_gadgets_ajax_url = "http://www.sunsations-tanning.ca/news/ajax.php";
var gu_gadgets_ajax_proxy = "";

/**
 * The callback for errors from the AJAX interface
 */
function gu_ajax_on_error(msg)
{
	msg = msg.replace(/<(?:.|\s)*?>/g, "");
	
	alert(msg);
}

/**
 * Because AJAX doesn't support cross-domain requests, this function allows a proxy
 * to be set as the destination for AJAX requests
 * @param url The url of the proxy script which must be on this domain
 */
function gu_gadgets_set_ajax_proxy(url)
{
	gu_gadgets_ajax_proxy = url;
}

/**
 * Creates a basic subscribe link to the subscribe page
 * @param list_id The ID of a list (optional)
 * @param text The text of the link 
 * @return The gadget HTML 
 */
function gu_gadgets_create_basic_link(list_id, text)
{
	var sub_url = gu_gadgets_subcribe_url + ((list_id > 0) ? ("?list=" + list_id) : '');
	
	return '<a href="' + sub_url + '">' + text + '</a>';
}

/**
 * Creates a basic subscribe form which redirects to the subscribe page
 * @param list_id The ID of a list (optional)
 * @param btn_text The submit button label (optional)
 * @param prefix The prefix applied to all IDs of elements
 * @return The gadget HTML  
 */
function gu_gadgets_create_basic_form(list_id, btn_text, prefix)
{
	var html = '';
	if (!gu_gadgets_formless)
		html += '<form name="' + prefix + 'subscribe_form" id="' + prefix + 'subscribe_form" method="post" action="' + gu_gadgets_subcribe_url + '">';
	
	html += '<input name="' + prefix + 'subscribe_address" id="' + prefix + 'subscribe_address" type="text" />';
	html += '<input name="' + prefix + 'subscribe_list" id="' + prefix + 'subscribe_list" type="hidden" value="' + list_id + '" />';
	
	if (btn_text != '')
		html += '<input name="' + prefix + 'subscribe_submit" id="' + prefix + 'subscribe_submit" type="submit" value="' + btn_text + '"/>';
	else
		html += '<input name="' + prefix + 'subscribe_submit" id="' + prefix + 'subscribe_submit" type="hidden" value="" />';	
	
	if (!gu_gadgets_formless)
		html += '</form>';
	return html;
}

/**
 * Creates a link which uses AJAX to submit a subscription
 * @param list_id The ID of a list
 * @param text The text of the link 
 * @return The gadget HTML
 */
function gu_gadgets_create_ajax_link(list_id, text)
{
	if (list_id == '' || list_id == 0)
		return 'This gadget requires a valid list';
		
	return '<a href="javascript:gu_gadgets_submit_ajax_link(\'' + list_id + '\')">' + text + '</a>';
}

/**
 * Creates a subscribe form which uses an inline AJAX submission
 * @param list_id The ID of a list
 * @param btn_text The submit button label (optional)
 * @param prefix The prefix applied to all IDs of elements 
 * @return The gadget HTML
 */
function gu_gadgets_create_ajax_form(list_id, btn_text, email_hint, prefix)
{
	if (list_id == '' || list_id == 0)
		return 'This gadget requires a valid list';

	var html = '';
	if (!gu_gadgets_formless)
		html += '<form name="' + prefix + 'subscribe_form" id="' + prefix + 'subscribe_form" method="get" action="" onsubmit="gu_gadgets_submit_ajax_form(this, \'' + prefix + '\'); return false;">';
	html += '<input name="' + prefix + 'subscribe_address" id="' + prefix + 'subscribe_address" type="text" />';
	html += '<input name="' + prefix + 'subscribe_list" id="' + prefix + 'subscribe_list" type="hidden" value="' + list_id + '" />';
	if (btn_text != '')
		html += '<input name="' + prefix + 'subscribe_submit" id="' + prefix + 'subscribe_submit" type="submit" value="' + btn_text + '"/>';
	if (!gu_gadgets_formless)
		html += '</form>';
	if (email_hint != '')
		html += '<script type="text/javascript">gu_gadgets_textfield_hint(document.getElementById("' + prefix + 'subscribe_address"), "' + email_hint + '");</script>';	
	return html;		
}

/**
 * Shortcut functions for outputting gadgets
 */
 
function gu_gadgets_write_basic_link(list_id, text)
{
	document.write(gu_gadgets_create_basic_link(list_id, text));
}

function gu_gadgets_write_basic_form(list_id, btn_text, prefix)
{
	document.write(gu_gadgets_create_basic_form(list_id, btn_text, prefix));
}

function gu_gadgets_write_ajax_link(list_id, text)
{
	document.write(gu_gadgets_create_ajax_link(list_id, text));
}

function gu_gadgets_write_ajax_form(list_id, btn_text, email_hint, prefix)
{
	document.write(gu_gadgets_create_ajax_form(list_id, btn_text, email_hint, prefix));
}


/**
 * Adds a hint value to the specified text field, i.e., when the box doesn't have focus it displays
 * the hint value, but when the user gives it focus the hint dissappears.
 * @param input The input to add the hint to
 * @param hint The hint value
 */
function gu_gadgets_textfield_hint(input, hint)
{	
	// Add custom hint property
	input.hint = hint;
	
	input.onfocus = function()
	{
		if (this.value == this.hint)
			this.value = '';
		this.style.fontStyle='normal';
		this.style.color='#000';
	}
	
	input.onblur = function()
	{
		if (this.value == '') {		
			this.style.fontStyle='italic';
			this.style.color='#BBB';
			this.value = this.hint;
		}	
	}

	input.style.fontStyle='italic';
	input.style.color='#BBB';
	input.value = hint;
}

/**
 * Gets the url for AJAX requests, using the proxy if it has been specified
 * @return The AJAX request URL
 */
function gu_gadgets_get_ajax_url()
{
	if (gu_gadgets_ajax_proxy != null && gu_gadgets_ajax_proxy != "")
		return gu_gadgets_ajax_proxy + "?url=" + escape(gu_gadgets_ajax_url);
	
	return gu_gadgets_ajax_url;
}

/**
 * Submits an AJAX subscribe request for the given list. The email address is requested in a client-side Javascript prompt.
 * @param list_id The ID of the list.
 */
function gu_gadgets_submit_ajax_link(list_id)
{
	var address = prompt("Please enter your email address");
	if (address == null)
		return;
		
	var url = gu_gadgets_get_ajax_url();
	
	var mysack = new sack(url);    
	mysack.execute = 1;
	mysack.method = "POST";
	mysack.setVar("action", "subscribe");
	mysack.setVar("address", address);
	mysack.setVar("list", list_id);
	mysack.onError = function()
	{
		alert("An error occured whilst requesting subscription");
	};
	mysack.runAJAX();
}

/**
 * Submits an AJAX subscribe request using params from the specified form
 */
function gu_gadgets_submit_ajax_form(form, prefix)
{
	var txt_address = eval("form." + prefix + "subscribe_address");
	var txt_list = eval("form." + prefix + "subscribe_list");
	var btn_submit = eval("form." + prefix + "subscribe_submit");
	
	var address = (("hint" in txt_address) && (txt_address.value == txt_address.hint)) ? "" : txt_address.value;
	var list = txt_list.value;
	
	if (address == "" || list == "")
		return;
		
	var old_hint = txt_address.hint;
	
	gu_gadgets_textfield_hint(txt_address, "Requesting...");
	txt_address.disabled = true;
	if (btn_submit)	
		btn_submit.disabled = true;
	
	var url = gu_gadgets_get_ajax_url();
	
	var mysack = new sack(url);   
	mysack.execute = 1;
	mysack.method = "POST";
	mysack.setVar("action", "subscribe");
	mysack.setVar("address", address);
	mysack.setVar("list", list);
	mysack.onCompletion = function()
	{
		if (old_hint != '')
			gu_gadgets_textfield_hint(txt_address, old_hint);
		else
			txt_address.value = '';
		txt_address.disabled = false;
		if (btn_submit)		
			btn_submit.disabled = false;
	};
	mysack.onError = function()
	{
		alert("An error occured whilst requesting subscription");
		txt_address.disabled = false;
		if (btn_submit)	
			btn_submit.disabled = false;
	};
	mysack.runAJAX();
}
