/**
*This function will help switch the current comany to the next company
*
*/
function companychangeAlert(currentVal,nextVal)
{	
	//Get the index of the selected company
	var ind = nextVal.options.selectedIndex;
	
	if(confirm("Are you sure you want to switch to "+nextVal.options[ind].text.toUpperCase()+" ?"))
	{
		dojo.byId("companySwitch").submit();
	}
	else
	{
		//Otherwise back to the existing Company
		nextVal.value = currentVal;
	}
	
}

function cancelForm(location)
{
	window.location = location;
}

function uploadWait()
{
	if (dojo.byId('uploadIndicator'))
	{
		dojo.byId('uploadIndicator').style.display = '';
	}
}

function confirmation(message, curpage, newpage)
{
	var answer = confirm(message);

	if(answer)
	{
		window.location = newpage;
	}
	else
	{
		window.location = curpage;
	}
}

function checkUncheckAll(id, checkUncheck, elem) {
	if (elem)
	{
		if (elem.checked == false)
		{
			checkUncheck = 'uncheck';
		}
	}
	dojo.query(id).forEach(function(node, index, arr){
		if (checkUncheck == 'uncheck') {
			node.checked = false;
		} else if(node.disabled != true) {
			node.checked = true;
		}
	  });
}


function checkall(id,pusherCompany,receiverCompany,relationType) {
	if(id == -1)
	{
		
		if( isNaN(dojo.byId('companies_id').value) || dojo.byId('companies_id').value =='')
		{
			alert('Wrong Company ID.');
			return false;
		}
		
		if (dojo.byId('relation_types--1').value == 'none')
		{
			alert('Please Select a Relation.');
			return false;
		}
	}
	
	
	if (relationType != 'relation_type' && dojo.byId('relation_types-' + id).value == 'none')
	{
			alert('Please Select a Relation.');
			return false;
	}
	
	
	for ( i=0; i < bitmasks.length; i++ ) 
	{
		if ( el = document.getElementById('bitmasks['+id+']['+bitmasks[i]+']') ) 
		{
			el.checked = true;
		}
	}
	
	if(dojo.byId(relationType).value == 'owner')
	{
		return;
	}
	
	dojo.xhrGet( 
			{
				handleAs: 'text',
				url: '/pusher/checkrecord/pcomp/' + pusherCompany +'/rcomp/' + receiverCompany + '/relation/' + dojo.byId(relationType).value,
				error: function (x) {
					alert('The Pusher record could not be loaded');
				},
				load: function(record, xx)
				{
					if(record == '0')
					{
						if(!confirm('The company will be a pusher to '+companyName+'. Do you want to proceed?'))
						{		
							for ( i=0; i < bitmasks.length; i++ ) 
							{
								if ( el = document.getElementById('bitmasks['+id+']['+bitmasks[i]+']') ) 
								{
									el.checked = false;
								}
							}
							return;
						}
					}
				}
		  }
	);
	
	
	
	
}


function uncheckall(id) {
	for ( i=0; i < bitmasks.length; i++ ) {
		if ( el = document.getElementById('bitmasks['+id+']['+bitmasks[i]+']') ) {
			el.checked = false;
		}
	}
}

function isOneChecked(id)
{
	var oneIsChecked = false;
	var i=0;
	var e = '';
	while(i < bitmasks.length && !oneIsChecked)
	{
		e = document.getElementById('bitmasks['+id+']['+bitmasks[i]+']');
		oneIsChecked = e.checked;
		i++;
	}
	return oneIsChecked;
}

// cookie functions http://www.quirksmode.org/js/cookies.html
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=/";
}

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;
}

/**
	This function is to check :
	1) if a Relation is selected.
	2) if 'Owner' is selected then check some rules
	Note: addBox is DOM reference to the current  Select Box
		  relation can be 'Asset' or 'Contract'
*/
function checkRelationToContractAsset(ddBox, relation, item,companyId1, receiverCompany)
{
	companyId = dojo.byId('companies_id').value;
	
	if(isNaN(companyId) || companyId =='')
	{
		alert('Wrong Company ID.');
		ddBox.value = 'none';
		return false;
	}
	
	if (ddBox[ddBox.selectedIndex].value == 'owner' || ddBox[ddBox.selectedIndex].value == 'var')
	{
		checkPusherRecord(companyId,receiverCompany,ddBox);
		checkall(-1);
		if(ddBox[ddBox.selectedIndex].value == 'owner')
		{
			var r = dojo.byId('relation_type');
			if (r[r.selectedIndex].value == 'owner')
			{
				dojo.addClass(r, 'errorHighlight');
				alert('Please change your relation to this '+relation+' to something other than owner.');
				r.focus();
			}
		}
	}
	else if (ddBox[ddBox.selectedIndex].value == 'none'  )
	{
	  uncheckall(-1);
	}
	else if(dojo.byId('bitmasks[-1][2]').checked || dojo.byId('bitmasks[-1][4]').checked || dojo.byId('bitmasks[-1][8]').checked )
	{
		checkPusherRecord(companyId,receiverCompany,ddBox);
	 	//$('bitmasks[-1][1]').checked=true;
	 	dojo.byId('bitmasks[-1][1]').checked=true;
	}
}

function checkOnwer(id, companyId, receiverCompany)
{
	if ( id[id.selectedIndex].value == 'owner' ) 
	{ 
		checkall(companyId); 
		var r = dojo.byId('relation_type'); 
		if ( r[r.selectedIndex].value == 'owner' ) 
			{  dojo.addClass(r,'errorHighlight'); 
				alert('Please change your relation to this Item to something other than owner.'); 
				r.focus(); 
				return false;
			}
	} 
	else if ( id[id.selectedIndex].value == 'none' ) 
	{ 
		uncheckall(companyId); 
	}
	else if(dojo.byId('bitmasks['+companyId+'][2]').checked || dojo.byId('bitmasks['+companyId+'][4]').checked || dojo.byId('bitmasks['+companyId+'][8]').checked )
	{
		checkPusherRecord(companyId,receiverCompany,id);
	}
}

/**
	This function is to validate the company number/Relation matching
	They cannot be exclusively empty.
*/
function updateContractAsset()
{
	//The id has been adultorated by the method "formSelect"
	//So, let's use the name instead.
	var vForm = dojo.byId('companyform');
	var relation_types_id = vForm['relation_types[-1]'];
	
	if (relation_types_id.value == 'owner' || relation_types_id.value == 'var')
	{
		checkall(-1);
	}

	if (relation_types_id.value == 'none'  && dojo.byId('companies_number').value !='')
	{
		alert('Please Select a Relation');
		return false;
	}
	if (relation_types_id.value != 'none'  && dojo.byId('companies_number').value =='')
	{
		alert('Please Enter a Company Number');
		return false;
	}

	if (relation_types_id.value != 'none'  && dojo.byId('companies_number').value !='' && !isOneChecked(-1) )
	{
		alert('At least one Privilege must be checked.');
		//$('bitmasks[-1][1]').checked=true;
		dojo.byId('bitmasks[-1][1]').checked=true;
		return false;
	}
	return true;
}

/**
 * This is used by the page sensitive help popups
 * @param {Object} mpage
 * @param {Object} subpage
 */
function helpwindow(mpage, subpage)
{
	// Need to open window for selected page/subpage
	context_help_win = window.open("/contexthelp/index/helpcontroller/" + mpage + "/helpaction/" + subpage, "","resizable,scrollbars,menubar=no,toolbar=no,status=no,width=400,height=500");
}

function reportprint(report)
{
	loc = location.href;
	lastCharIndex = loc.length - 1;
	lastChar = loc.charAt(lastCharIndex);
	sLastChar = loc.charAt(lastCharIndex - 1);
	if (lastChar == '#' && sLastChar == '/')
	{
		loc = loc.substring(0, lastCharIndex-1);
	}
	if (lastChar == '#' || lastChar == '/')
	{
		loc = loc.substring(0, lastCharIndex);
	}
	context_help_win = window.open(loc+"/print/1/", "" ,"resizable,scrollbars,menubar=no,toolbar=no,status=no,width=780,height=500");
}

/**
 * Dynamically load Select boxes from Json array of rows
 *
 * 	props.select_id:	// ID of the select_box
 * 	props.url:		// URL where JSON data is
 * 	props.value_key:	// row key to use as value
 * 	props.label_key:	// row key to use as label
 * 	props.options: [{ value: '1', label: 'lbl 1'}, {value: '2', label: 'lbl 2'}]  //array of value,label pairs as extra options
 */
function ajaxSelectBox(props)
{
	var handleAsVal = 'json';
	if (props.debug) {
		handleAsVal = 'text';
	}
	//get Region
	dojo.xhrGet({
		handleAs: handleAsVal,
		url: props.url,
		error: function (x) { alert(x); },
		load: function(response, xx)
		{
			if (props.debug) { alert(response); return; }

			var rOpt = dojo.byId(props.select_id);

			//default value
			var defaultValue = null;
			if (props.defaultValue) { defaultValue = props.defaultValue; }

			optionRemoveAll(rOpt);

			if (props.options)
			{
				for (var j = 0;  j < props.options.length; j++)
				{
					var dOpt = document.createElement('option');
					var dTxt = document.createTextNode(props.options[j].label);
					dOpt.appendChild(dTxt);
					dOpt.value = props.options[j].value;
					rOpt.appendChild(dOpt);
				}
			}

			for (var i = 0; i < response.length; i++)
			{
				var row = response[i];
				var val = arrVal(row, props.value_key);
				var lbl = arrVal(row, props.label_key);

				var xOpt = newOption(arrVal(row, props.value_key), arrVal(row, props.label_key));
				if (arrVal(row,props.value_key) == defaultValue && defaultValue != null)
				{
					xOpt.selected = true;
				}

				rOpt.appendChild(xOpt);
			}
		}
	});
}

function newOption(val, lbl)
{
	var opt = document.createElement('option');
	var txt = document.createTextNode(lbl);
	opt.appendChild(txt);
	opt.value = val;

	return opt;
}
function optionRemoveAll(sb) { removeNodeChildren(sb); }
function removeNodeChildren(node)
{
	if(node.hasChildNodes())
	{
		while(node.childNodes.length >= 1 )
		{
			node.removeChild(node.firstChild);
		}
	}
}

function removeNode(node)
{
	if (node) {
		node.parentNode.removeChild(node);
	}
}
function arrVal(theArray, key) { for (i in theArray) { if (i == key) { return theArray[i]; } } return null; }
function strpos( haystack, needle, offset){ var i = (haystack+'').indexOf( needle, offset ); return i===-1 ? false : i; }

/**
 * showHide will take a node and will display or hide the element
 * @param thisitem - id or reference to node
 * @param fction - action (show/hide) can be left blank
 * @param displayType - type of display property (block, table-row)
 */
function showHide(thisitem, fction, displayType)
{
	if (!displayType || (dojo.isIE < 8 && displayType=='table-row'))
	{
		displayType = '';
	}
	
	if (fction == 'hide') {
		dojo.style(thisitem, 'display', 'none');
	} else if (fction == 'show') {
		dojo.style(thisitem, 'display', displayType);
	} else {
		if (dojo.style(thisitem, 'display') != 'none') {
			dojo.style(thisitem, 'display', 'none');
		} else {
			dojo.style(thisitem, 'display', displayType);
		}
	}
}

function checkLineItem(obj, assetId, contractId,companyId, receiverCompany)
{
	var item = 'Asset';
	if(assetId == 0)
	{
		item = 'Contract';
	}
	
	var type_value = document.getElementById('relation_type').value;
	if(type_value != 'owner')
	{
		dojo.xhrGet( 
		{
			handleAs: 'text',
			url: '/asset/checklineitem/assetid/' + assetId +'/contractid/' + contractId,
			error: function (x) {
				alert('The Asset could not be loaded');
			},
			load: function(lineitem, xx)
			{
				if(lineitem > 0)
				{
					document.getElementById('relation_type').value = 'owner';
					alert("There are Line Items associated to the "+ item +".\n Please remove the line Items before you change the Owner.");
					
					return false;
				}
				if(type_value == 'none')
				{
					alert("Please verify that you want to remove all your company\'s permissions for this asset before you Update.");
				}
				
//				checkPusherRecord(companyId, receiverCompany, obj);
			}
		}
		);
	}
	
	
}


function checkPusherRecord(pusherCompany, receiverCompany, id)
{
	dojo.xhrGet( 
			{
				handleAs: 'text',
				url: '/pusher/checkrecord/pcomp/' + pusherCompany +'/rcomp/' + receiverCompany + '/relation/' + id.options[id.selectedIndex].value,
				error: function (x) {
					alert('The Pusher record could not be loaded');
				},
				load: function(record, xx)
				{
					if(record == '0')
					{
						
						if(!confirm('The company will be a pusher to '+companyName+'.. Do you want to proceed?'))
						{		
							for( var i=0; i< id.options.length; i++)
							{
								if( id.options[i].defaultSelected )
								{
									id.value =  id.options[i].value;
									break;
								}
							}
							
							return;
						}
					}
				}
		  }
	);
}


function checkBoxPusher(pusherCompany,receiverCompany,relationType,ckb)
{
//	alert(pusherCompany + ' - ' + receiverCompany + ' - ' + ckb.value);
	var bitmask = (ckb.name).substring(0,(ckb.name).length - 3);
	if( !(dojo.byId(bitmask + '[2]').checked
			||dojo.byId(bitmask + '[4]').checked 
			|| dojo.byId(bitmask + '[8]').checked) )
	{
		return false;
	}
	
	if(isNaN(pusherCompany) || pusherCompany =='')
	{
		alert('Wrong Company ID.');
		dojo.byId(bitmask + '[2]').checked = false;
		dojo.byId(bitmask + '[4]').checked = false;
		dojo.byId(bitmask + '[8]').checked = false;
		return false;
	}
	
	if (dojo.byId(relationType).value == 'none')
	{
		alert('Please Select a Relation.');
		dojo.byId(bitmask + '[2]').checked = false;
		dojo.byId(bitmask + '[4]').checked = false;
		dojo.byId(bitmask + '[8]').checked = false;
		return false;
	}
	
	if (dojo.byId(relationType).value == 'owner')
	{
		return false;
	}
	

	dojo.xhrGet( 
			{
				handleAs: 'text',
				url: '/pusher/checkrecord/pcomp/' + pusherCompany +'/rcomp/' + receiverCompany + '/relation/' + dojo.byId(relationType).value,
				error: function (x) {
					alert('The Pusher record could not be loaded');
				},
				load: function(record, xx)
				{
					if(record == '0')
					{
						if(!confirm('The company will be a pusher to '+companyName+'. Do you want to proceed?'))
						{		
							dojo.byId(bitmask + '[2]').checked = false;
							dojo.byId(bitmask + '[4]').checked = false;
							dojo.byId(bitmask + '[8]').checked = false;
							return;
						}
					}
				}
		  }
	);
}

function base64_encode( data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
 
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i=0, enc='';
 
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);
 
        bits = o1<<16 | o2<<8 | o3;
 
        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;
 
        // use hexets to index into b64, and append result to encoded string
        enc += b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
 
    switch( data.length % 3 ){
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }
 
    return enc;
}

/********************* BEGINING SOFTWARE BOX **************************/
var currentPage = 1;
var totalNumberOfPages = 1;
var dropDownDatabase = null;
var rowsPerPage = 20;

function renderNextPage(theUrl,assetType)
{
	currentPage = parseInt(currentPage) + 1;
	if (parseInt(currentPage) > parseInt(totalNumberOfPages)) 
	{
		currentPage = parseInt(totalNumberOfPages); 
	}
	else
	{
		showAttachedAsset(theUrl, assetType, currentPage);
	}
}

function renderPreviousPage(theUrl,assetType)
{
	currentPage--;
	if (currentPage < 1) {
		currentPage = 1; 
	}
	else
	{
		showAttachedAsset(theUrl, assetType, currentPage);
	}
}

function showAttachedAsset(theUrl,assetType,page)
 {
	var nbRecUrl = '';
	if(page == null)
	{
		page = 1;
		currentPage =1;
		nbRecUrl = '/nbr/1';
	}
	theUrl = theUrl +  'pageid/' + page + nbRecUrl ;
		
	if(dojo.byId('search_value').value != '')
	{
		theUrl = theUrl + '/search/'  + base64_encode(dojo.byId('search_value').value);
	}
	
	dojo.xhr('POST', {handleAs: 'json',
	sync: true,
	url : theUrl,
	handle : function(response, ioArgs){
		dropDownDatabase = response;
		
		if(dropDownDatabase.nbr != null){
			totalNumberOfPages = Math.ceil( parseInt(dropDownDatabase.nbr) / parseInt(rowsPerPage));
		}
		//filter
		var database = { identifier: dropDownDatabase.identifier, label : dropDownDatabase.label, items : []};
		var j = 0;
		for (i = 0; i < dropDownDatabase.items.length; i++)
		{
			if (dropDownDatabase.items[i].name.toLowerCase().indexOf(dropDownFilter.toLowerCase()) != -1)
			{
				database.items[j] = dropDownDatabase.items[i];
				j++;
			}
		}
	
		
		/* CREATE  UL */
		var tmpUl = document.createElement('ul');
		for (i = 0; i < database.items.length; i++)
		{
			if(database.items[i].value == -999)
			{
				continue;
			}
			
			var tmpLi = document.createElement('li');
			var tmpA = document.createElement('a');
			tmpA.href = "javascript:;";

			var value = database.items[i][database.identifier];
			var label = database.items[i][database.label];

			tmpA.onclick= function(){ dropDownHandler(this,assetType); };
			tmpLi.appendChild(tmpA);
			tmpUl.appendChild(tmpLi);
			
			var spValue = document.createElement('span');
			    spValue.innerHTML = database.items[i].value;
			    spValue.style.display = 'none';
			    
			var spName = document.createElement('span');
			    spName.innerHTML = database.items[i].name;
			    
			tmpA.appendChild(spValue);
			tmpA.appendChild(spName);
		}
	
	dojo.byId('current_page').innerHTML = 'Page ' + page + ' of ' + totalNumberOfPages;
	dojo.byId('inner_div').innerHTML = '';
	dojo.byId('inner_div').appendChild(tmpUl);
	dijit.byId('attached_software_list').show();
	
	}});
 }

var dropDownHandler = function(assetElem, asset_type) {
	addSwField(assetElem.childNodes[0].innerHTML, assetElem.childNodes[1].innerHTML,asset_type);
};


function addSwField(value,label,asset_type)
{
	var uid = new Date().getTime();
	var cont = dojo.byId('swCont');
	var tr = document.createElement('tr');
	var td1 = document.createElement('td');
	var td2 = document.createElement('td');
	var td3 = document.createElement('td');
	var lbl = document.createElement('label');
	    lbl.norwap;

	lbl.innerHTML = label;
		
	var input = document.createElement('input');
	input.id = asset_type+'_id_'+uid;
	input.value = value;
	input.type = 'hidden';
	input.name = asset_type+'_id[]';
	
	tr.appendChild(td1);
	tr.appendChild(td2);
	tr.appendChild(td3);
	td1.appendChild(lbl);
	td2.appendChild(input);
	td3.innerHTML = '<a onclick="removeSwField(this, '+uid+');" href="javascript:;"><img src="/images/icons/application_delete.png" alt="Remove" /><\/a>';
	cont.appendChild(tr);
}

function removeSwField(aTag, id)
{
	aTag.parentNode.parentNode.parentNode.removeChild(aTag.parentNode.parentNode); //tbody	
}

var dropDownFilter = '';
var listDialog = null;
var baseUrl = null;
/********************* END Of SOFTWARE BOX **************************/


/*** ADVACE FILTERS ***/
/**
 * Function to open or close the filters
 */
function showFilters()
{
	var nodea = dojo.query('#filters_cont');
	if (nodea.style('display') == 'none'){	
		dojo.fx.wipeIn({node: "filters_cont",duration: 500}).play();
		dijit.byId('view_r_filters').setLabel('Hide Filters');
		dijit.byId('view_r_filters').setValue('Hide Filters');
	} 
	else{
		dojo.fx.wipeOut({node: "filters_cont",duration: 500}).play();
		dijit.byId('view_r_filters').setLabel('View Filters');
		dijit.byId('view_r_filters').setValue('View Filters');
	}
	
}

/**
 * On input focus clear input if is the default value
 * @param val
 * @param id
 */
function doOnFocus(val, id) 
{
	if (val == 0 || val == '-999') {
		dijit.byId(id).setDisplayedValue('');
	}
}

/**
 * On input blur if the current value is blank then reset to default value
 * @param val
 * @param id
 */
function doOnBlur(val, id)
{	
	if (val == '') {
		dijit.byId(id).setValue('-999');
	}
}

/**
 * Reset loading message
 * @param id
 * @param dvalue
 */
function resetLoading(id, dvalue) {
	dijit.byId(id).setValue(dvalue);
}

/**
 * Set a loading message to the input while we load results
 * @param id
 */
function setLoading(id) {
	dijit.byId(id).setDisplayedValue('loading...');
}

/**
 * Function to post data programatically.
 * it simulates a post or get method
 * 
 * Example:
 * 	jsVirtualForm({
 * 		action : '/some/url',
 * 		method : 'post',
 * 		data : {
 * 			field_name : 'value',
 * 			field_2 : 'value 2',
 * 			multi_dimentional : {
 * 				key1 : 'val1',
 * 				key2 : 'val2'
 * 			}
 * 		}
 * 	});
 */
function jsVirtualForm(props_args)
{
	var props = props_args;

	if (!props.action) { props.action = ''; } 
	if (!props.method) { props.method = 'post'; }
	if (!props.data) { props.data = {}; }

	/* Create Form */
	var postForm = document.createElement('form');
	postForm.action = props.action;
	postForm.method = props.method;


	this.appendFieldsToForm = function(form, name, value)
	{
		if (typeof(value) == 'object')
		{
			for (i in value)
			{
				this.appendFieldsToForm(form, name + "[" + i + "]", value[i]);
			}
			return;
		}

		var temp = document.createElement('input');
		temp.name = name;
		temp.value = value;
		form.appendChild(temp);
	};

	/* Append Fields To Form */
	for (i in props.data)
	{
		this.appendFieldsToForm(postForm, i, props.data[i]);
	}
	/* Post Form */
	dojo.body().appendChild(postForm);
	postForm.submit();
	postForm.submit();
}

/**
 * Returns a URL string in Zend format
 * /controller/action/param1/value1/param2/value2#anchor
 *
 * Usage:
 * 	var url = urlWriter('contract', 'view', {id : 5047 }, '#optionalScrollAnchor');
 * 	window.location = url;
 *
 * @param string controller
 * @param string action
 * @param array params associative array
 * @param string anchor
 * @return string
 */
function urlWriter(controller, action, params, anchor)
{
	if (!controller) { controller = 'index'; }
	if (!action) { action = 'index'; }
	if (!params) { params = {}; }
	if (!anchor) { anchor = ''; }

	var url = '/' + controller + '/' + action;

	for (i in params)
	{
		if (params[i] == '') continue;
		url = url + '/' + i + '/' + escape(params[i]);
	}

	url = url + '#' + anchor.replace('#', '');

	return url;
}

/**
 * Returns dom element from JSON objects.
 *
 * { "t" : "Some Text"} === document.createTextNode("Some Text")
 * { "n" : "div" } === document.createElement('div')
 *
 * <div id="the_id">
 * 	<h1>Hello</h1>
 * 	<p>More Text</p>
 * </div>
 * same as:
 * {
 * 	"name" : "div",
 * 	"attribs" : { "id" : "the_id" }
 * 	"children" : [
 * 		{ "name" : "h1", "children" : [ { "text" : "Hello" } ] },
 * 		{ "name" : "p", "children" : [ { "text" : "More Text" } ] }
 * 	]
 * }
 *
 * @var Object json
 * @return Element
 */
function json2dom(json) {
	//var json = { "n" : "", "a" : {}, "c" : [] };
	if (json == null) { json = {}; }
	if (json.text) { return document.createTextNode(json.text); }


	var ret = dojo.create(json.name);

	if (json.attribs) { for (var k in json.attribs) {

		dojo.attr(ret, k, json.attribs[k]);
	} }


	if (json.children) {
		for (var k in json.children)
		{
			if (json.children[k].element)
			{
				ret.appendChild(json.children[k].element); //dom element
			}
			else
			{
				var child = json2dom(json.children[k]);

				ret.appendChild(child);

				//Attribs have to be re-done after append for IE to work
				if (json.children[k].attribs)
				{
					var childAttribs = json.children[k].attribs;
					for (var x in childAttribs)
					{
						dojo.attr(child, x, childAttribs[x]);
					}
				}
			}
		}
	}
	return ret;
}


/**
 * MMI Namespace
 * 
 * mmi.dialog.show()	// main dialog function
 * mmi.dialog.alert()	// alert dialog
 * mmi.dialog.deleteDialog() // delete dialog
 * mmi.dialog.close()	// close dialog
 * mmi.dialog.loading(msg) // shows a loading message
 */
var mmi = (function() {

	/*
	Private Section
	@dijit.dialog
	*/
	var dialogInstance = null;



	/*
	 Public Section
	*/
		

	/** Dialog NAMESPACE */
	this.dialog =
	{
	
		/* Show Dialog
		usage:
			mmi.dialog.show({
					title: "my title",
					content: "my message...!!",
					buttons: [
						  {label: "OK", onclick: function(){ alert('clicked'); }},
						  {label: "Cancel", onclick: function(){ alert('canceled'); }}
						  {label: "Some attribute", type: "div", attribs: { style:"width:1px solid black;"}, onclick: function(){ alert('canceled'); }}
						]
					});
		 */
		"show": function(props)
		{
			mmi.dialog.close(); //just in case it's already open
			
			dojo.require('dijit.Dialog');
			dojo.require('dijit.form.Button');
			
			var btn = null;
			var type = null;
			
			var emptyFunctionIfNoneGiven = function(func){ return func || function(){ return false; }; };
			
			/* Buttons */
			var buttons = document.createElement('div');
			dojo.attr(buttons, 'style',"margin-top:1em;");
			buttons.style.textAlign = 'center';
			if(typeof(props.buttons) != 'undefined')
			{
				for (var i = 0; i < props.buttons.length; i++)
				{
					var button = props.buttons[i];
					var label = typeof(button.label) == 'undefined' ? '' : button.label;
					var onclick = emptyFunctionIfNoneGiven(button.onclick);
					if (typeof(button.type) != "undefined" && button.type != "button")
					{
						if (button.type == "a")
						{
							btn = document.createElement('a');
							dojo.attr(btn, 'href',"javascript:;");
						}
						else
						{
							type = button.type;
							btn = document.createElement(type); //create element
						}
						
						var attribs = typeof(button.attribs) == 'undefined' ? {} : button.attribs;
						for (var j in attribs) { if (typeof j == 'string') { dojo.attr(btn, j, attribs[j]); } } //set attribs
						btn.appendChild(document.createTextNode(label));
						dojo.connect(btn, "onclick", onclick);
						buttons.appendChild(btn);
					}
					else
					{
						btn = new dijit.form.Button({ "label": label, "onClick": onclick });
						buttons.appendChild(btn.domNode);
					}

				}
			}

			/* Add messages and buttons to content */
			var msg = document.createElement('div');
			msg.innerHTML =  typeof(props.content) == 'undefined' ? '' : props.content;
			var content = document.createElement('div');
			content.appendChild(msg);
			content.appendChild(buttons);
			
			dialogInstance = new dijit.Dialog({
				"title": typeof(props.title) == 'undefined' ? '' : props.title,
				"content": content,
				"closable": typeof(props.closable) == 'undefined' ? true : props.closable
			}); // end dijit.Dialog
			
			dojo.body().appendChild(dialogInstance.domNode);
			dialogInstance.show();
			
		}, // end dialog.show

		"close": function()
		{
			if (dialogInstance)
			{
				dialogInstance.destroy(false);
			}
		},
		
		
		/*
		 Alert Dialog Box
		 usage:
			 mmi.dialog.alert("Some Message");
				 
			 mmi.dialog.alert(
					"Some Message",
					{ 
						title: "Alert Title", //optional
						onOk : function(){} //optional function to execute when clicking on OK
					 }
				 );
		 */
		"alert" : function(alertMsg, props)
		{
			props = typeof(props) == 'undefined'? {} : props;
			var title = typeof(props.title) == 'undefined' ? 'Alert' : props.title;
			var onOk = typeof(props.onOk) == 'undefined' ? function(){ mmi.dialog.close(); } : props.onOk;
			
			mmi.dialog.show({
					"title":title,
					"content": alertMsg,
					buttons:[ { label:"OK", "onclick": onOk } ]
					}); // end mmi.dialog.show
		},


		/*
		 Delete Dialog Box
		 usage:
			 mmi.dialog.deleteDialog({
					title: "some title", //optional
					content: "some message", //optional
					onCancel: function(){}, //optional, function to call when cancel button is pressed
					onDelete: function(){}, //function to call when delete button is pressed
					url: "/som/url", //optional url that will be called using ajax, and response would be sent to onDelete(response)
					post: {key1:"some value", key2:"some value2"} //optional array to post to url(requires a provided url) and response would be sent to onDelete(response)
				 });
		 */
		"deleteDialog": function(props) {
			props = typeof(props) == 'undefined'? {} : props;
			var title = typeof(props.title) == 'undefined' ? 'Delete' : props.title;
			var content = typeof(props.content) == 'undefined' ? 'Are you sure you want to delete this item?' : props.content;
			var onCancel = typeof(props.onCancel) == 'undefined' ? function(){ mmi.dialog.close(); return false; } : function(){ return props.onCancel(); };
			var onDelete = typeof(props.onDelete) == 'undefined' ? function(){ mmi.dialog.close(); } : props.onDelete;


			var functionOnDelete = onDelete;
			var url = typeof(props.url) == 'undefined' ? null : props.url;
			if (url)
			{
				var errorHandler = function (response) { mmi.dialog.alert("(Error): " + response); };
				var successHandler = function (response) {
					var resp = null;
					try {
						resp = eval('(' + response + ')');
						onDelete(resp);
					}
					catch (err) {
						errorHandler(response, err);
					}
				};
				
				// get Url Passed
				functionOnDelete = function() {
					mmi.dialog.loading("Deleting...");
					dojo.xhrGet({ "url": url, "error": errorHandler, "handle":  successHandler }); };
				var post = typeof(props.post) == 'undefined' ? null : props.post;
				
				// use post if post key->values passed
				if (post)
				{
					functionOnDelete = function() {
						mmi.dialog.loading("Deleting...");
						dojo.xhrPost({ "url": url, "content": post,  "error": errorHandler, "handle": successHandler }); };
				}
			}
			
			mmi.dialog.show({
					"title":title,
					"content": content,
					buttons:[
								{ label:"Delete", onclick:functionOnDelete },
							{ label:"or", type:"span", attribs:{style:"padding:0 1em;"} },
								{ label:"Cancel", type:"a", "onclick": onCancel }
							 ]
					}); // end mmi.dialog.show
			
		}, // end delete:function
		
		/**
		 * Loading Window
		 */
		"loading": function (msg)
		{
			if (!msg) { msg = 'Processing...'; }
			mmi.dialog.show({"title":"", "content": msg, "closable":false});
		}
		
	}; // end DIALOG NAMESPACE

	
	/*
	 * JSON NAMESPACE
	 */
	this.json = {
		isJsonString : function(str) {
			var json = false;
			try { eval('(' + str + ')');
				json = true;
			} catch (err) { json = false; }
			return json;
		},
		
		"decode" : function (str)
		{
			var json = null;
			try { json = eval('(' + str + ')'); }
			catch (err) { json = str; }
			return json;
		},
		
		"encode" : function(arr) {
		    var parts = [];
		    var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');

		    for(var key in arr)
		    {
		    if (typeof key == 'string' && typeof key == 'number') {
				var value = arr[key];
				if(typeof value == "object") { //Custom handling for arrays
				    if(is_list) { parts.push(array2json(value)); }/* :RECURSION: */
				    else { parts[key] = array2json(value); } /* :RECURSION: */
				} else {
				    var str = "";
				    if(!is_list) { str = '"' + key + '":'; }
	
				    //Custom handling for multiple data types
				    if(typeof value == "number") { str += value; } //Numbers
				    else if(value === false) { str += 'false'; }//The booleans
				    else if(value === true) { str += 'true'; }
				    else { str += '"' + value + '"'; } //All other things
				    // :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
				    
				    parts.push(str);
				}
			}
			}
		    var json = parts.join(",");
		    
		    if(is_list) { return '[' + json + ']'; } //Return numerical JSON
		    
		    return '{' + json + '}';//Return associative JSON
		    
		} // encode END
		
	}; // en JSON namespace
		

	return this;
}());

dojo.addOnLoad(function() {
	dojo.query("input[type='submit']").onclick(function(e){
		
		/* disablepreprocessing is a variable that if set in a page
		 * it would override the default function and not apply the Processing... label
		 */
		
		if(typeof(disablepreprocessing) == 'undefined') {
			var btn = e.target;
			var fform = btn.form;
			dojo.stopEvent(e); // prevent sending the form
			btn.value='Processing...';
			btn.disabled=true;
			fform.submit();
		}
		
	});
	
	dojo.query(".submitbtn").connect("onclick", formSubmitHandler);
});

var hasbeenSubmitted = false;
function formSubmitHandler(e)
{
	dojo.stopEvent(e); // prevent sending the form
	
	if (dojo.isFF || dojo.isIE) {
		var btn = e.target;
	}
	else {
		var btn = e.target.parentNode;
	}
	
	var mybtn = dijit.byId(btn.id);
	
	//isvalid needs to be declared and set if you are using client side validation
	if(typeof(isvalid) == 'undefined') {
		isvalid = true;
	}
	
	var dbtn = dojo.byId(btn.id);
	var fform = dbtn.form;
	
	mybtn.setAttribute('disabled', true);
	if (isvalid == 'true' || isvalid == true)
	{
		if (!hasbeenSubmitted) {
			mybtn.setLabel('Processing...');
			hasbeenSubmitted = true;
			fform.submit();
		}
	}
	else {
		mybtn.setAttribute('disabled', false);
	}
}

function clearValue(obj, defval)
{
	
	if (obj.value == defval)
	{
		obj.value = '';
	}
	else if (obj.value == '')
	{
		obj.value = defval;
	}
}
