/** FormSubmitter is a generic class to submit forms via AJAX
 * It works like this:
 * 1. Create the html form 'u_formname_form', you do not need to include an onsubmit property
 * 2. Create a php file in the BASEURL folder with the name 'u_formname.php' to
 *	  handle the form submission. ($_POST['submitMethod'] will == ajax)
 * 3. If you want a simple element replacement, init with submitAction=elementid and type='Updater'
 * 4. If you want to do something with the return, add it to a list instead of replacing the whole
 *    thing, for instance, init with submitAction=yourjavascriptfunction passed as an object 
 *    and type='Request'
 *
 * note, the prefix for formname is a convention only
 *   u_  == update
 *   i_  == insert
 *   d_  == delete
 *   s_  == select 
 * Requires prototype.js http://prototype.conio.net/
 * Based on an example from http://www.sergiopereira.com/articles/prototype.js.html
 */
var FormSubmitter = Class.create();
FormSubmitter.prototype = {

	initialize: function(frm, submitAction, type) {
		this.frm = frm;
		this.submitAction = submitAction;
		this.type = type;
		//assigning our method to the event
		this.frm.onsubmit = this.submitform.bindAsEventListener(this);
		this.frm.elements['submitMethod'].value = 'ajax';
		
	},
  
  
  /** 
   * hijack original callback, decode the JSON response if needed, then call the original callback
   *
   *  this is causing problems in IE, so forget it for now
   *
	callback: function(t) {
		debugger;
		if( t.responseText.charAt(0) == '{' ) { // a first character as a { denotes a JSON response
			var jsonObj = eval('(' + t.responseText + ')');
			this.clientCallback( jsonObj );
		}
		else {
			this.clientCallback( t );
		}
	}, */ 
   
	submitform: function(evt) {
		
		//var url = this.buildurl();
		var url = this.frm.action;

		//build the POST query
		submitdata = "submitMethod=ajax"; 
		for (i=0; i < this.frm.elements.length; i++) {
			//skip what we don't need, ESPECIALLY don't include submitMethod=normal
			if(this.frm.elements[i].name != 'submitMethod' && this.frm.elements[i].name != 'submit') {
				submitdata += "&" + this.frm.elements[i].name + "=" + encodeURIComponent(this.frm.elements[i].value);
			}
		}
		
		if(this.type == 'Request') {
			//var foo = new Ajax.Request(url, { method:'post', clientCallback:this.submitAction, postBody:submitdata, onSuccess:this.callback, onFailure:errFunc});
			var foo = new Ajax.Request(url, {method:'post', postBody:submitdata, onSuccess:this.submitAction, onFailure:errFunc});
			// new Ajax.Request(url, {method:'post', postBody:submitdata, onSuccess:function(t){alert(t.responseText);}, onFailure:errFunc});
		} else {
			new Ajax.Updater(this.submitAction, url, {method:'post', postBody:submitdata, onFailure:errFunc});
		}
		
		this.frm.reset();
		return false;
	}, 

	buildurl: function() {
		alert('ac ' + this.frm.action);
		var fa = this.frm.action.split('/');
		
		var tmp = '';
		while(tmp == '') {
			tmp = fa.pop();
		}
		return window.location.protocol + '//' 	+ window.location.host + '/' + tmp + '/';
	}
};

function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}



/**
 * field is just there to let the class know which
 *    field to return (since it doesn't necessarily know
 *    which field changed)
 */
var ipeCallback = function(field) {
	return '&field='+field+'&submitMethod=ajax';
};

var errFunc = function(t) {
    alert('Error ' + t.status + ' -- ' + t.statusText);
};


var postMetatags = function() {
	var frm = document.forms['metatag_form']; 
	var url = BASEURL+'u_meta.php';
	var submitdata = "hid=" + frm.elements['hid'].value 
		+ "&cid=" + frm.elements['cid'].value
		+ "&metatags=" + frm.elements['metatags'].value
		+ "&submitMethod=ajax";
	new Ajax.Updater('tags', url, {method:'post', postBody:submitdata, onFailure:errFunc});
	frm.reset();
	return false;
};

/**
 * from quirksmode.org
 * link: http://www.quirksmode.org/js/findpos.html  
 */
function findPos(obj) {
	var origional = obj;
	var pos = new Object();
	pos.left = pos.top = 0;
	
	if (obj.offsetParent) {
		pos.left = obj.offsetLeft
		pos.top = obj.offsetTop
		while (obj = obj.offsetParent) {
			pos.left += obj.offsetLeft
			pos.top += obj.offsetTop
		}
	}
	
	pos.right = pos.left + origional.offsetWidth;
	pos.bottom = pos.top + origional.offsetHeight;
	return pos;
}

/**
 * Popup Functions
 */
function popupHide(boxname) {
	$(boxname).style.display = 'none';
}

var popup = Class.create();
popup.prototype = {
	initialize: function(boxname, pos) {
		this.boxname = boxname;
		this.pos = pos;
	}
}

/**
* a collection of popUp windows that can only be shown one at a time.
* I.e. opening one of the popups closes all the others in the collection
*/
var popupCollection = Class.create();
popupCollection.prototype = {
	initialize: function() {
		this.popups = new Object;
	},
	
	/**
	 * boxname - the id of the div to pop up
	 * relative_to - the id of the div to position the pop up relative to
	 * relative_horizontal - [top|bottom], currently ignored
	 * relative_vertical - [left|right], currently ignored
	 */
	add: function(boxname, relative_to, relative_horizontal, relative_vertical) {
		if( ! this.popups[boxname]) {
			var rel = $(relative_to);
			this.popups[boxname] = new popup(boxname, findPos(rel));
		}
	},
	
	show: function(boxname) {
		this.hide();
		var box = $(boxname);
		box.style.display = 'block';
		box.style.position = 'absolute';
		box.style.top = this.popups[boxname].pos.bottom + "px";
		box.style.left = this.popups[boxname].pos.left + "px";

		window.scroll(0, this.popups[boxname].pos.bottom - 50);
		var databox = $(boxname+'data');
	 	if(databox) {
			databox.focus();
			databox.select();
		}
		return false;
	},
	
	hide: function() {
		for( var boxname in this.popups ) {
			$(boxname).style.display = 'none';
		}
	}
	
} /* popupCollection */



var changeMobileStep1 = function(t) {
	eval("var resp = " + t.responseText);
	if(resp.error_message) {
		alert(resp.error_message);
	} else if(resp.error_messages) {
		alert(resp.error_messages);
	} else {
		changeMobileGoToStep2();
	}
}

var changeMobileStep2 = function(t) {
	eval("var resp = " + t.responseText);
	if(resp.error_message) {
		alert(resp.error_message);
	} else if(resp.error_messages) {
		alert(resp.error_messages);
	} else {
		changeMobileGoToStep3();
	}
}

function changeMobileGoToStep1() {
	document.forms.sendvalidatemobile.style.display = 'block';
	document.forms.validatemobile.style.display = 'none';
}
function changeMobileGoToStep2() {
	document.forms.sendvalidatemobile.style.display = 'none';
	document.forms.validatemobile.style.display = 'block';
}
function changeMobileGoToStep3() {
	document.forms.sendvalidatemobile.style.display = 'none';
	document.forms.validatemobile.style.display = 'none';
	$('validatemobile_complete').style.display = 'block';
}
function changeMobileDone() {
	$('change_mobile').style.display = 'none';
   $('send_channel').style.display = 'block';
}


function banner_hide(key) {
	createCookie('banner',key,700);
	$('banner').style.display = 'none';
	$('banner_break').style.display = 'none';
}

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/;domain=" + location.hostname + "";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}


function getValue(id,getwhat) {
	var item;
	var btype;
	if (document.getElementById)
	{
		btype ="IE5 NS6 ";
		item = document.getElementById(id);
	}
	else
	{
		if (document.layers)
		{ // Netscape 4
			btype ="NS4 ";
			item = document.id;
		}
		else if (document.all)
		{
			btype ="IE4 ";
			item = document.all(id);
		}
	}
	
	if(item && getwhat == "innerHTML" ) { return item.innerHTML; }
	if(item && getwhat == "value" ) { return item.value; }
	if(item && getwhat == "selectedIndex" ) { return item.options[item.selectedIndex].value; }
	if(item && getwhat == "item" ) { return item; }
	
	return false;
}

function reportError()
{
	
	alert("You connection to our server maybe be down. try refresh or stop on your browser");
}


function hidediv(id) {
	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		//alert("Hiding IE5 NS6 " + id);
		document.getElementById(id).style.display = 'none';
	}
	else {
		if (document.layers) { // Netscape 4
			//alert("Hiding NS 4 " + id);
			document.id.display = 'none';
		}
		else { // IE 4
			// alert("Hiding IE 4" + id);
			document.all.id.style.display = 'none';
		}
	}
}

function showdiv(id) {
	//safe function to show an element with a specified id
	//alert("Showing " + id);                  
	if (document.getElementById) { // DOM3 = IE5, NS6
		//alert("Showing IE5 NS6 " + id);
		document.getElementById(id).style.display = 'block';
	}
	else {
		if (document.layers) { // Netscape 4
			//alert("Showing NS 4 " + id);
			document.id.display = 'block';
		}
		else { // IE 4
			//alert("Showing IE 4" + id);
			document.all.id.style.display = 'block';
		}
	}
}



// ajax response

/**
 * a manage function.
 * @author Rohan, I assume
 */
function runAjaxResponsePage(t,showalert)
{
	if ( showalert == 'all') alert("repsonse "+ t.responseText);
	eval("var decoded_data = " + t.responseText);
	var whichdiv = decoded_data.whichdiv;
	if(whichdiv != '')
	{
		if ( showalert == 'whichdiv' || showalert =='all') alert(whichdiv + '\n' + decoded_data.text);
		$(whichdiv).innerHTML = decoded_data.text;
	}
	var js = decoded_data.runJS;
	if(js != '')
	{
		if ( showalert == 'JS' || showalert =='all')    alert('JS ' + decoded_data.runJS);
		eval(decoded_data.runJS);
	}
	
	return ;
}

/* a simple confirm, but if we use this we can expand it later to be a nice
 * pop up box
 */
function hpConfirm(question) {
	return confirm(question);
}

function l3_navigation_change() {
	var f = document.l3_navigation;
	if(f.range) {
		var frange = f.range.options[f.range.selectedIndex].value;
	}
	var ftype = f.type.options[f.type.selectedIndex].value;
	
	var url = f.action;

	if(frange) {
		url += frange + '/' ;
	}
	
	if( ftype != 'alltypes' ) {
		url += ftype + '/';
	}
	document.location = url;
	
}


function featureSwap(type, num) {
   /**
    * the prefix for the swapped divs
    */
	var feafix = 'fea_'+type+'_';

	/**
	 * feafix + i should always exist. But we're going to check anyway.
    */
	var feaverify;

	/**
    * the prefix for the selection thumbnails
    */
	var thmfix = 'fthm_'+type+'_';

	/**
	 * just like the divs, we'll double check that the thumbs exists.
    * avoids possible js errors.
    */
	var thmverify;

	for(var i = 1; i <= 6; i++) {
		feaverify = $(feafix+i)
		if(feaverify) {
			feaverify.style.display = 'none';
		}
		thmverify = $(thmfix+i);
		if(thmverify) {
			thmverify.className = '';
			thmverify.blur();
      }
	}
	$(feafix+num).style.display = 'block';
	$(thmfix+num).className = 'selected';

	return false;
}