/* *************************************************
 * WAIT MODAL popup
 *
***************************************************/
var waitmodal;

function get_waitmodal_template_1(message) {
	return '<div class="floatright"><a href="#" onclick="return waitmodal_close();">X</A></div>\
	<h6>\
	<span class="imglink sel"><span class="pngspan"><img src="/direct/master/ext/silk-1.3/clock.png" width="16" height="16" align="top" /> Status</span></span>\
	</h6><p>'+message+'</p>';
}

// open or update the waitmodal with the following message
function waitmodal_set(message,templateid) {
	if(templateid==1) {
		templatedmessage = get_waitmodal_template_1(message);
	}
	else {
		templatedmessage = get_waitmodal_template_1(message);
	}
	if(!waitmodal) {
		waitmodal = new Control.Modal('modalwaitlocation', {
			contents: templatedmessage,
			opacity: 0.8,
    		position: 'relative',
    		width: 300,
    		height: 50,
    		overlayCloseOnClick: false
		});
		waitmodal.open();
	}
	else {
		waitmodal.update(templatedmessage);
	}
}
function waitmodal_close() {
	if(waitmodal) {
		waitmodal.close();
	}
	waitmodal = null;
	return false;
}

/* *************************************************
 * generic SEARCH SUBMIT
 *
***************************************************/

function ajax_searchsubmit(formid, desturl, redirecturl) {
	
	zm = $('zeroresultsmessage');
	if(zm) {
		zm.hide();
	}
	
	urlparams = '';
	if(formid.length) {
		urlparams = $(formid).serialize();
	}
	
	waitmodal_set('Searching...');

	new Ajax.Request(desturl,
	{
		method: 'post',
  		parameters: urlparams,
    	onSuccess: function(transport) {
		
		try {
			var json = transport.responseText.evalJSON(true);
		} catch(e) {
			page_debug_add_error('there was an error');
			page_debug_add_error(transport.responseText);
			return false;
		}
		
		// handle response
		page_debug_add_debug(json);
		if(json.errorcode) {
			//alert('f');
		}
		else {
			//alert('g');
		}
		if(json.errorcode == 'zeroresults') {
			//alert('no results');
		}	
		//alert(json.searchresults_resultcount);
		//Object.inspect(json);
		if(json.searchresults_resultcount) {
			waitmodal_set('Found '+json.searchresults_resultcount+ ' Items. Loading Results...');
			if(json.dump) {
				return false;	// stop for debugging.
			}
			window.location.href = redirecturl;
		}
		else {
			zm = $('zeroresultsmessage');
			if(zm) {
				zm.show();
			}
			waitmodal_close();
		}
		
		// TODO if no json we have a script error. popup the response?
		//alert(json ? Object.inspect(json) : "no JSON object");
      //var response = transport.responseText || "no response text";
      //alert("Success! \n\n" + response);
      // TODO onXXX for session expired:
    },
    onFailure: function(){ alert('Something went wrong...'); return false; }
  });

	return false;
}

/* *************************************************
 * generic DIV REPLACEMENT
 *
 * params
 * formid, if present will attach the form contents in.
 * popunder, if present will activate the popunder window once complete
 * popover, if present will activate the popover window once complete
 *
***************************************************/
function ajax_replacediv(containerid, desturl, params) {
	
	if(!params) { params = {} };
	
	waitmessage = (params.waitmessage) ? params.waitmessage : 'Please Wait, Updating...';
	showpopup = (params.nowait) ? false : true;

	urlparams = '';
	if(params.formid) {
		urlparams = $(params.formid).serialize(true);
	}
	if(params.formgroup) {
		urlparams = '';
		arr = params.formgroup.split(':');	
		for(i=0;i<arr.length;i++) {
			id = arr[i];
			p = $(id).serialize();
			if(p.length>0) {
				if(urlparams.length>0) urlparams += '&';	
				urlparams += p;
			}
		}
	}
	
	if(showpopup) {
		waitmodal_set(waitmessage);
	}
	
	new Ajax.Updater(containerid, desturl,
	{
		method: 'post',
  		parameters: urlparams,
    	evalScripts: true,
    	onSuccess: function(transport) {
			if(showpopup) {
				waitmodal_close();
			}
			
			if(params.popunder) {
				$('page-popover').hide();
				$('page-popunder').show();
			}
			if(params.popover) {
				$('page-popunder').hide();
				$('page-popover').show();
			}
    	},
    	onFailure: function(){ alert('Something went wrong...'); return false; }
  	});

	return false;
}
	
function show_popover() {
	$('page-popunder').hide();
	$('page-popover').show();
	return false;
}
function show_popunder() {
	$('page-popover').hide();
	$('page-popunder').show();
	return false;
}

/* *************************************************
 * DEBUG
 *
***************************************************/

function page_debug_add_debug(json) {
	if(!json.debug) return;
	if(!$('page-debug')) return;
	h = $A(json.debug);
	h.each(function(node){
		new Insertion.Top('page-debug', '<div class="debugitem">'+node+'</div>');
	});
}
function page_debug_add_error(message) {
	if(!$('page-debug')) return;
	new Insertion.Top('page-debug', '<div class="erroritem"><pre>'+message+'</pre></div>');
}

/* *************************************************
 * EFFECTS
 *
***************************************************/
function ef_ri(o) {
	Element.addClassName(o, 'thover');
}
function ef_ro(o) {
	Element.removeClassName(o, 'thover');
}

/* *************************************************
 * dirtyform fields
 *
***************************************************/
var dirtyform_origformid;
var dirtyform_origfields;

function setup_dirtyform_fields(formid) {
	dirtyform_origformid = formid;
	dirtyform_origfields = Form.serialize(formid);
}
function dirtycheck() {
	dirtyform_newfields = Form.serialize(dirtyform_origformid);
	
	if(dirtyform_newfields == dirtyform_origfields) {
		// no changes, ok.
		return true;
	}
	
	// TODO dirrtycheck, pop message to confirm, if yes, save it and goto the url on this link
	// else don't or conmtinue anyway.
	
	return false;
}

/* *************************************************
 * list selectors
 *
***************************************************/

function ajax_toggle_listbrowse_selection(event, rid, contentid, url) {

    // dont let the clickthru to singledest item go thru
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }

	// get the current toggle status
	thisid = 'rid_sel_'+rid;
	selectstat = $(thisid).hasClassName('ridsel');
	
	// toggle it
	selectstat = !selectstat;
	selectstatint = (selectstat) ? 1 : 0;
	
	// send to the server 
	url += '&rid='+rid+'&toggle='+selectstatint;

	if(selectstat) {
		$(thisid).addClassName('ridsel');
	}
	else {
		$(thisid).removeClassName('ridsel');
	}

	new Ajax.Updater(contentid, url,
	{
		method: 'get',
    	onSuccess: function(transport) {
			
			//alert(transport.responsetext);	
			// change the img class to show success
			
			// output the response to the updater class space (n items selected)
	    },
	    onFailure: function(){ alert('Something went wrong...'); return false; }
  	});

	return false;
}


/* *************************************************
 * account invoiceing
 *
***************************************************/

	function getfloat(str) {
		var n = parseFloat(str);
		if(isNaN(n)) n = 0;
		return n;
	}
	function getint(str) {
		var n = parseInt(str);
		if(isNaN(n)) n = 0;
		return n;
	}
	function account_invoice_calc() {
		
		// get item total
		itemtotal = getfloat($('inf__account_invoice_item1price').getValue()) + getfloat($('inf__account_invoice_item2price').getValue()) + getfloat($('inf__account_invoice_item3price').getValue()) + getfloat($('inf__account_invoice_item4price').getValue()) + getfloat($('inf__account_invoice_item5price').getValue()) + getfloat($('inf__account_invoice_item6price').getValue());
		itemtaxtotal = getfloat($('inf__account_invoice_item1price').getValue())*getint($('inf__account_invoice_item1tx').getValue())+getfloat($('inf__account_invoice_item2price').getValue())*getint($('inf__account_invoice_item2tx').getValue())+getfloat($('inf__account_invoice_item3price').getValue())*getint($('inf__account_invoice_item3tx').getValue())+getfloat($('inf__account_invoice_item4price').getValue())*getint($('inf__account_invoice_item4tx').getValue())+getfloat($('inf__account_invoice_item5price').getValue())*getint($('inf__account_invoice_item5tx').getValue())+getfloat($('inf__account_invoice_item6price').getValue())*getint($('inf__account_invoice_item6tx').getValue());
		
		disc = getint($('inf__account_invoice_discount').getValue());
		if(disc>0) {
			adjtotal = itemtotal * ((100-disc)/100.0);
			adjtaxtotal = itemtaxtotal * ((100-disc)/100.0);
		}
		else {
			adjtotal = itemtotal;
			adjtaxtotal = itemtaxtotal;
			
		}
		
		discamt = itemtotal-adjtotal;
		taxamt = getfloat($('inf__account_invoice_taxrate').getValue())*adjtaxtotal;
		depositamt = getfloat($('inf__account_invoice_itemdeposit').getValue());
		
		finaltotal = adjtotal+taxamt+depositamt;
		
		paymenttotal = getfloat($('inf__account_invoice_pmt1amt').getValue()) + getfloat($('inf__account_invoice_pmt2amt').getValue()) + getfloat($('inf__account_invoice_pmt3amt').getValue()) + getfloat($('inf__account_invoice_pmt4amt').getValue()) + getfloat($('inf__account_invoice_pmt5amt').getValue()) + getfloat($('inf__account_invoice_pmt6amt').getValue());
		
		accountbalance = finaltotal-paymenttotal;
		
		// todays date
		tdt = new Date();
		dt1 = Date.parse($('cl_show_inf__account_invoice_pmt1expdate').innerHTML);
		dt2 = Date.parse($('cl_show_inf__account_invoice_pmt2expdate').innerHTML);
		dt3 = Date.parse($('cl_show_inf__account_invoice_pmt3expdate').innerHTML);
		dt4 = Date.parse($('cl_show_inf__account_invoice_pmt4expdate').innerHTML);
		dt5 = Date.parse($('cl_show_inf__account_invoice_pmt5expdate').innerHTML);
		dt6 = Date.parse($('cl_show_inf__account_invoice_pmt6expdate').innerHTML);
		dtfinal = Date.parse($('cl_show_inf__account_invoice_duedate').innerHTML);
		// overdue is total payments < sum(payments expected past due)
		actpay = paymenttotal;
		exppay = 0;
		if(!isNaN(dt1) && dt1<tdt) exppay += getfloat($('inf__account_invoice_pmt1expamt').getValue());
		if(!isNaN(dt2) && dt2<tdt) exppay += getfloat($('inf__account_invoice_pmt2expamt').getValue());
		if(!isNaN(dt3) && dt3<tdt) exppay += getfloat($('inf__account_invoice_pmt3expamt').getValue());
		if(!isNaN(dt4) && dt4<tdt) exppay += getfloat($('inf__account_invoice_pmt4expamt').getValue());
		if(!isNaN(dt5) && dt5<tdt) exppay += getfloat($('inf__account_invoice_pmt5expamt').getValue());
		if(!isNaN(dt6) && dt6<tdt) exppay += getfloat($('inf__account_invoice_pmt6expamt').getValue());
		if(!isNaN(dtfinal) && dtfinal<tdt) exppay = finaltotal;
		
		overduebalance = exppay - actpay;
		
		// dont accum credit for prepay across invoices.
		if(overduebalance<0) overduebalance = 0;
		
		$('inf__account_invoice_itemtotal').value = itemtotal;
		$('inf__account_invoice_itemtaxtotal').value = itemtaxtotal;
		$('inf__account_invoice_adjtotal').value = adjtotal;
		$('inf__account_invoice_adjtaxtotal').value = adjtaxtotal;
		$('inf__account_invoice_discamt').value = discamt;
		$('inf__account_invoice_taxamt').value = taxamt;
		$('inf__account_invoice_depositamt').value = depositamt;
		$('inf__account_invoice_finaltotal').value = finaltotal;
		$('inf__account_invoice_paymenttotal').value = paymenttotal;
		$('inf__account_invoice_accountbalance').value = accountbalance;
		$('inf__account_invoice_overduebalance').value = overduebalance;
		
		$('ac_itemtotal').update(formatCurrency(itemtotal));
		$('ac_discamt').update(formatCurrency(discamt));
		$('ac_taxamt').update(formatCurrency(taxamt));
		$('ac_depositamt').update(formatCurrency(depositamt));		
		$('ac_finaltotal').update(formatCurrency(finaltotal));
		$('ac_paymenttotal').update(formatCurrency(paymenttotal));
		$('ac_accountbalance').update(formatCurrency(accountbalance));
		$('ac_overduebalance').update(formatCurrency(overduebalance));
		
		//$('fff').update(overdueamt);
	}

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}


function swapfck(id) {
	var oEditor = FCKeditorAPI.GetInstance(id);
	$(id).value = oEditor.GetHTML();
}



