var arrayObj = null;
var currentEdit = null;
function objSort(array,property,order) {
	array.sort(function(a,b) {
		if(order == 'D') {
			var temp = a;
			a = b;
			b = temp;
		}
		if(typeof a[property] != 'string') {
			return a[property] - b[property];
		} else {
			x = 0;
			if (a[property] < b[property]) {
				x=-1;
			}  else {
				x=1;
			}
			return x;
		}
	});
}

/* Function printf(format_string,arguments...)
* Javascript emulation of the C printf function (modifiers and argument types
*    "p" and "n" are not supported due to language restrictions)
*
* Copyright 2003 K&L Productions. All rights reserved
* http://www.klproductions.com
*
* Terms of use: This function can be used free of charge IF this header is not
*               modified and remains with the function code.
*
* Legal: Use this code at your own risk. K&L Productions assumes NO resposibility
*        for anything.
********************************************************************************/
function printf(fstring)
{ var pad = function(str,ch,len)
{ var ps='';
for(var i=0; i<Math.abs(len); i++) ps+=ch;
return len>0?str+ps:ps+str;
}
var processFlags = function(flags,width,rs,arg)
{ var pn = function(flags,arg,rs)
{ if(arg>=0)
{ if(flags.indexOf(' ')>=0) rs = ' ' + rs;
else if(flags.indexOf('+')>=0) rs = '+' + rs;
}
else
rs = '-' + rs;
return rs;
}
var iWidth = parseInt(width,10);
if(width.charAt(0) == '0')
{ var ec=0;
if(flags.indexOf(' ')>=0 || flags.indexOf('+')>=0) ec++;
if(rs.length<(iWidth-ec)) rs = pad(rs,'0',rs.length-(iWidth-ec));
return pn(flags,arg,rs);
}
rs = pn(flags,arg,rs);
if(rs.length<iWidth)
{ if(flags.indexOf('-')<0) rs = pad(rs,' ',rs.length-iWidth);
else rs = pad(rs,' ',iWidth - rs.length);
}
return rs;
}
var converters = new Array();
converters['c'] = function(flags,width,precision,arg)
{ if(typeof(arg) == 'number') return String.fromCharCode(arg);
if(typeof(arg) == 'string') return arg.charAt(0);
return '';
}
converters['d'] = function(flags,width,precision,arg)
{ return converters['i'](flags,width,precision,arg);
}
converters['u'] = function(flags,width,precision,arg)
{ return converters['i'](flags,width,precision,Math.abs(arg));
}
converters['i'] =  function(flags,width,precision,arg)
{ var iPrecision=parseInt(precision);
var rs = ((Math.abs(arg)).toString().split('.'))[0];
if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
return processFlags(flags,width,rs,arg);
}
converters['E'] = function(flags,width,precision,arg)
{ return (converters['e'](flags,width,precision,arg)).toUpperCase();
}
converters['e'] =  function(flags,width,precision,arg)
{ iPrecision = parseInt(precision);
if(isNaN(iPrecision)) iPrecision = 6;
rs = (Math.abs(arg)).toExponential(iPrecision);
if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs.replace(/^(.*)(e.*)$/,'$1.$2');
return processFlags(flags,width,rs,arg);
}
converters['f'] = function(flags,width,precision,arg)
{ iPrecision = parseInt(precision);
if(isNaN(iPrecision)) iPrecision = 6;
rs = (Math.abs(arg)).toFixed(iPrecision);
if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs + '.';
return processFlags(flags,width,rs,arg);
}
converters['G'] = function(flags,width,precision,arg)
{ return (converters['g'](flags,width,precision,arg)).toUpperCase();
}
converters['g'] = function(flags,width,precision,arg)
{ iPrecision = parseInt(precision);
absArg = Math.abs(arg);
rse = absArg.toExponential();
rsf = absArg.toFixed(6);
if(!isNaN(iPrecision))
{ rsep = absArg.toExponential(iPrecision);
rse = rsep.length < rse.length ? rsep : rse;
rsfp = absArg.toFixed(iPrecision);
rsf = rsfp.length < rsf.length ? rsfp : rsf;
}
if(rse.indexOf('.')<0 && flags.indexOf('#')>=0) rse = rse.replace(/^(.*)(e.*)$/,'$1.$2');
if(rsf.indexOf('.')<0 && flags.indexOf('#')>=0) rsf = rsf + '.';
rs = rse.length<rsf.length ? rse : rsf;
return processFlags(flags,width,rs,arg);
}
converters['o'] = function(flags,width,precision,arg)
{ var iPrecision=parseInt(precision);
var rs = Math.round(Math.abs(arg)).toString(8);
if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
if(flags.indexOf('#')>=0) rs='0'+rs;
return processFlags(flags,width,rs,arg);
}
converters['X'] = function(flags,width,precision,arg)
{ return (converters['x'](flags,width,precision,arg)).toUpperCase();
}
converters['x'] = function(flags,width,precision,arg)
{ var iPrecision=parseInt(precision);
arg = Math.abs(arg);
var rs = Math.round(arg).toString(16);
if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
if(flags.indexOf('#')>=0) rs='0x'+rs;
return processFlags(flags,width,rs,arg);
}
converters['s'] = function(flags,width,precision,arg)
{ var iPrecision=parseInt(precision);
var rs = arg;
if(rs.length > iPrecision) rs = rs.substring(0,iPrecision);
return processFlags(flags,width,rs,0);
}
farr = fstring.split('%');
retstr = farr[0];
fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
for(var i=1; i<farr.length; i++)
{ fps=fpRE.exec(farr[i]);
if(!fps) continue;
if(arguments[i]!=null) retstr+=converters[fps[4]](fps[1],fps[2],fps[3],arguments[i]);
retstr += fps[5];
}
return retstr;
}
/* Function printf() END */
function _gel(x) {
	return document.getElementById(x);
}
var xmlhttpbusy = false;
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
}
if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

function toggleForm(form,disabled) {
	if(form.elements.length < 1) {
		form = _gel(form);
	}
	if(form.elements.length > 0) {
		for(i=0;i<form.elements.length;i++) {
			form.elements[i].disabled = disabled;
		}
	}
}

function checkValues(form) {
	if(form.elements.length < 1) {
		form = _gel(form);
	}
	var completed = 0;
	var required = 0;
	for(var i=0;i<form.elements.length;i++) {
		if(form.elements[i].getAttribute('required') == 'required') {
			required++;
			if(form.elements[i].value != '-1' && form.elements[i].value != '') {
				completed++;
			}
		}
	}
	if(completed >= required) {
		form.submit();
	}
}

function numberFormat (number, decimals, dec_point, thousands_sep)
{
  var exponent = "";
  var numberstr = number.toString ();
  var eindex = numberstr.indexOf ("e");
  if (eindex > -1)
  {
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }
  
  if (decimals != null)
  {
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0)
  {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : ',';
  if (thousands_sep != null && thousands_sep != "")
  {
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  
  return sign + integer + fractional + exponent;
}

function getMaxWeight(array) {
	var maxWeight = -1;
	for(var i = 0;i<array.length;i++) {
		if(maxWeight < array[i]['Weight']) {
			maxWeight = array[i]['Weight'];
		}
	}
	return maxWeight;
}

function editItem(form,url,id) {
	var formElements = _gel(form).elements;
	var parameters = '';
	eval('var array = ' + id);
	arrayObj = new Object();
	for(var i = 0;i<formElements.length;i++) {
		if(typeof formElements[i].name != 'undefined' && formElements[i].name != '') {
			parameters += formElements[i].name + '=' + encodeURI(formElements[i].value) + '&';
		}
	}
	for(var i in array[0]) {
		switch(i) {
			default:
			if(typeof formElements[i] != 'undefined') {
				arrayObj[i] = formElements[i].value;
			}
			break;
		}
	}
	parameters = parameters.substr(0,parameters.length-1);
	postRequest(url,parameters,function(msg) {
		if(arrayObj['Weight'] < 0) {
			arrayObj['Weight'] = 0;
		} else if(arrayObj['Weight'] > getMaxWeight(array)) {
			arrayObj['Weight'] = getMaxWeight(array);
		}
		var oldWeight = getArrayObject(arrayObj['IDN'],'IDN',array)['Weight'];
		var newWeight = arrayObj['Weight'];
		if(newWeight < oldWeight) {
			for(var i = 0;i<array.length;i++) {
				if((array[i]['Weight'] >= newWeight) && (array[i]['Weight'] < oldWeight)) {
					array[i]['Weight']++;
				}
			}
		}
		if(newWeight > oldWeight) {
			for(var i = 0;i<array.length;i++) {
				if((array[i]['Weight'] <= newWeight) && (array[i]['Weight'] > oldWeight)) {
					array[i]['Weight']--;
				}
			}
		}
		for(var i in arrayObj) {
			getArrayObject(_gel('editorForm').elements['IDN'].value,'IDN',array)[i] = arrayObj[i];
		}
		hideDisplay('editorRow');
		buildTable(id,'Weight');
	});
}

function addItem(form,url,id) {
	var formElements = _gel(form).elements;
	var parameters = '';
	eval('var array = ' + id);
	arrayObj = new Object();
	for(var i = 0;i<formElements.length;i++) {
		if(typeof formElements[i].name != 'undefined' && formElements[i].name != '') {
			parameters += formElements[i].name + '=' + encodeURI(formElements[i].value) + '&';
			if(formElements[i].name != 'Submitted') {
				arrayObj[formElements[i].name] = formElements[formElements[i].name].value;
				formElements[formElements[i].name].value = '';
			}
		}
	}
	arrayObj['Weight'] = getMaxWeight(array) + 1;
	parameters = parameters.substr(0,parameters.length-1);
	postRequest(url,parameters,function(msg) {
		var newIDN = parseInt(msg);
		arrayObj['IDN'] = newIDN;
		array.push(arrayObj);
		hideDisplay('adder');
		buildTable(id,'Weight');
	});
}

function postRequest(url,parameters,finishedHook) {
	if(!xmlhttpbusy) {
		xmlhttp.onreadystatechange=function() {
			if (xmlhttp.readyState==4 && xmlhttp.status == 200) {
				xmlhttpbusy = false;
				finishedHook(xmlhttp.responseText);
			}
		}
		xmlhttp.open('POST',url,true);
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", parameters.length);
		xmlhttp.setRequestHeader("Connection", "close");
		xmlhttp.send(parameters);
	}
	xmlhttpbusy = true;
}

function addSpaces(string) {
	if(typeof string != 'string') {
		return string;
	}
	var op = string[0];
	for(var i = 1;i<string.length;i++) {
		if(string.charCodeAt(i) >= 65 && string.charCodeAt(i) <= 90) {
			op += ' ' + string[i];
		} else {
			op += string[i];
		}
	}
	return op;
}

function toggleDisplay(div) {
	if(_gel(div).style.display == 'none') {
		showDisplay(div);
	} else {
		hideDisplay(div);
	}
}

function showDisplay(div) {
	_gel(div).style.display = 'block';
}

function hideDisplay(div) {
	_gel(div).style.display = 'none';
}

function getArrayObject(x,property,array) {
	for(i=0;i<array.length;i++) {
		if(array[i][property] == x) {
			return array[i];
		}
	}
	return false;
}

function removeItem(x,url,id) {
	if(confirm('Are you sure you want to delete this item?')) {
		hideDisplay('editorRow');
		eval('var array = ' + id);
		var cWeight = array[x]['Weight'];
		for(var i = 0;i<array.length;i++) {
			if(array[i]['IDN'] == x) {
				array.splice(i,1);
			}
			if(cWeight > array[i]['Weight']) {
				array[i]['Weight']--;
			}
		}
		var parameters = 'IDN=' + x;
		postRequest(url,parameters,function(msg) {
			buildTable(id,'Weight');
		});
	}
}

function showEditItem(x,id,e) {
	if(elementClicked(e) != 'A') {
		eval('var array = ' + id);
		var obj = getArrayObject(x,'IDN',array);
		var formElements = _gel('editorForm').elements;
		for(var i in obj) {
			formElements[i].value = obj[i];
		}
		showDisplay('editorRow');
	}
}
/**
* Taken from http://www.w3schools.com/js/tryit.asp?filename=try_dom_event_srcelement
* Modified to return a value instead of alert.
*
* @param {Object} e
*/
function elementClicked(e) {
	var targ
	if (!e) var e = window.event
	if (e.target) targ = e.target
	else if (e.srcElement) targ = e.srcElement
	if (targ.nodeType == 3) // defeat Safari bug
	targ = targ.parentNode
	var tname
	tname=targ.tagName
	return tname;
}
/**
* Alters the weight of an item.
*
* @param {Object} x
* @param {Object} id
* @param {Object} direction
*/
function moveItem(x,id,direction) {
	eval('var array = ' + id);
	if(direction == 'down') {
		var additive = 1;
	} else if(direction == 'up') {
		var additive = -1;
	}

	postRequest(window.location.pathname,'IDN=' + x +'&action=' + direction,function(msg){
		var firstObj = getArrayObject(x,'IDN',array);
		var secondObj = getArrayObject(firstObj['Weight'] + additive,'Weight',array);
		firstObj['Weight']+=additive;
		secondObj['Weight']+=(additive*-1);
		buildTable(id,'Weight');
	});
}

function buildTable(id,sort,order) {
	eval('var array = ' + id);
	objSort(array,sort,order);
	if(order == 'D') {
		order = 'A';
	}  else {
		order = 'D';
	}
	var div = _gel(id);
	var ohtml = '';
	if(array.length == 0) {
		ohtml = '<table width="100%"><tr><td class="noItem">No items created.</td></tr></table>';
	} else {
		ohtml += '<table width="100%">';
		ohtml += '<tr>';
		for(var i in array[0]) {
			if(i != 'IDN') {
				ohtml += '<th><a href="#" onclick="buildTable(\''+ id + '\',\'' + i + '\',\'' + order + '\');return false;">' + addSpaces(i) + '</a></th>';
			}
		}
		ohtml += '</tr>';
		for(var i=0;i<array.length;i++){
			ohtml += '<tr onclick="toggleForm(_gel(\'editorForm\'),false);showEditItem(' + array[i]['IDN'] + ',\'' + id + '\',event);" class="listItem">';
			for(var j in array[i]) {
				switch(j) {
					case 'IDN':
					break;

					case 'Weight':
					ohtml += '<td>';
					if(array[i][j] < getMaxWeight(array)) {
						ohtml += '<div class="moveDown"><a href="#" onclick="moveItem(' + array[i]['IDN'] + ',\'' + id + '\',\'down\');return false;">D</a></div>';
					}
					if(array[i][j] > 0) {
						ohtml += '<div class="moveUp"><a href="#" onclick="moveItem(' + array[i]['IDN'] + ',\'' + id + '\',\'up\');return false;">U</a></div>';
					}
					ohtml += '</td>';

					break;
					case 'Status':
					if(array[i][j] == 1) {
						ohtml += '<td>Active</td>';
					} else {
						ohtml += '<td>Inactive</td>';
					}
					break;

					default:
					if(j.substr(-5) == 'Price') {
						ohtml += '<td>$' + numberFormat(array[i][j],2,'.',',') + '</td>';
					} else {
						ohtml += '<td>' + array[i][j] + '</td>';
					}
					break;
				}

			}
			ohtml += '</tr>';
		}
		ohtml += '</table>';
	}
	div.innerHTML = ohtml;
}
function logWrite(txt) {
	if(!_gel('debugLog')) {
		var newDiv = document.createElement('div');
		newDiv.id = 'debugLog';
		document.getElementsByTagName('body')[0].appendChild(newDiv);
		_gel('debugLog').style.width='400px';
		_gel('debugLog').style.height='200px';
		_gel('debugLog').style.bottom='20px';
		_gel('debugLog').style.overflow='auto';
	}
	_gel('debugLog').innerHTML += txt + '<br />';
}
