// Some general functions for load editing and confirmation

function evaluateCod(num) {
	if (num === undefined) { num = ''; }
	var cod = 'cod' + num;
	var codwhere = 'cod_where' + num;
	var codpaymentmethod = 'cod_payment_method'+num;
	
	if ($('quickpay_check' + num).checked || $('comchek_check' + num).checked) {
		$(cod).value = 0;
		$(codwhere).disable();
		$(cod).disable();
		$(codpaymentmethod).disable();
	} else {
		$(cod).enable();
		$(codwhere).enable();
		$(codpaymentmethod).enable();
	}
}

// num added to post multiple page to identify which row is in question
function evaluateCheckbox(option, num) {
	if(typeof(options) === "undefined") {return; }
	if (num === undefined) { num = ''; }
	if ($(options[option]['opp'] + "_check" + num).checked) {
		alert("You cannot select both Comchek and Quick Pay at the same time.");
		$(options[option]['opp'] + "_check" + num).checked = false;
	}
	if (options[option]['notify'] && $(option + "_check" + num).checked) {
		confirmPaymentOption(option, num);
	}
	evaluateCod(num);
}

function confirmPaymentOption( option, num) {
	if (num === undefined) { num = ''; }
	var left;
	var top;
	if (document.documentElement && document.documentElement.scrollTop) { // support Explorer 6+
		left = document.documentElement.scrollLeft;
		top = document.documentElement.scrollTop;
	} else {
		left = document.body.scrollLeft;
		top = document.body.scrollTop;
	}
	left += 200;
	top += 75;
	var oLeft = -left - 10;
	var oTop = -top - 10;
	var width = document.body.offsetWidth;
	var height = document.body.offsetHeight;
	
	var newdiv = document.createElement('div');
	newdiv.id = 'alertBox';
	newdiv.className = 'dp_dialog';
	newdiv.style.left = left + 'px';
	newdiv.style.top = top + 'px';

	var header = options[option]['name'];
	var message = options[option]['prompt'] + "<div style='margin-top: 15px'>"+
	"<table><tr><td><input type='checkbox' id='remove_warning'></td><td>&nbsp;</td>"+
	"<td><label for='remove_warning'>Don't display this message again</label></td></tr></table>"+
	"<div><input type='button' class='standard_button' id='agree' name='agree' onclick='confirmedAgreement(true,\""+option+"\",$(\"remove_warning\").checked, \""+num+"\")' value='"+options[option]['agree']+"'></div>"+
	"<div><input type='button' class='standard_button' id='cancel' name='cancel' onclick='confirmedAgreement(false,\""+option+"\",$(\"remove_warning\").checked, \""+num+"\")' value='"+options[option]['cancel']+"'></div></span>";
		
	newdiv.innerHTML = "<div class='dp_overlay' style='position: absolute; z-index: -1; left: " + oLeft + "px; top: " + oTop + "px; height: " + height + "px; width: " + width + "px; filter:alpha(opacity=25); opacity: 0.25; -moz-opacity:0.25; background-color: #FFFFFF; padding: 0;'>&nbsp;<" + "/div><div class='dp_dialog_header'><a href='javascript:void(0)' onclick='confirmedAgreement(false,\""+option+"\",$(\"remove_warning\").checked, \""+num+"\")'>X<" + "/a> &nbsp; " + header + "<" + "/div><div class='dp_dialog_contents' id='dp_dialog_contents'>" + message + "<" + "/div><" + "/div>";
	
	var oDiv = document.body; //getElementById('dp_page');
	oDiv.insertBefore(newdiv, oDiv.childNodes[0]);
	
	if (navigator.appVersion.indexOf('MSIE 6') > 0 && navigator.userAgent.indexOf('Opera') < 0) {
		var parent = $('dp_dialog_contents');
		var pLeft = getElementLeft(parent);
		var pTop = getElementTop(parent);
		// must cover each select independently because Picked-Up and Delivered prompts contain selects which must not be covered
		var els = document.getElementsByTagName('select');
		for (var i = 0; i < els.length; ++i) {
			var uni = $(els[i].name);
			if (overlaps(parent,uni)) {
				$(els[i].name).hide();
			}
			$(els[i].name).disable();
		}
	}
}

function confirmedAgreement(confirm, option, removeWarning, num) // confirmedAgreement(false,'comchek', false);
{
	if (num === undefined) { num = ''; }
	var url = '/protected/ajax_updateNotify.php?option=' + option;
	if (removeWarning) {
		options[option]['notify'] = 0; // turn off notify for the remainder of this page
		new Ajax.Request(url, {method: 'get'}); // update DB
	}
	removeNodeById("alertBox", option, !confirm, "num");
	if (!confirm) {
		$(option + "_check" + num).checked = false; // uncheck if they cancel
	}
	evaluateCod(num); // enable/disable box based on final call
}

function isNumberOnly( obj ) {
	obj.value = obj.value.replace(/[,\$ ]/g, '');
	return obj.value.search(/[^0-9\.]/) == -1;
}

function numberOnly( obj, field, leaveBlank, noMessage ) {
	obj.value = obj.value.replace(/[,\$ ]/g, '');
	if (obj.value.search(/[^0-9\.]/) > -1) {
		obj.style.backgroundColor = '#FFC0C0';
		
		if (noMessage) {
			return false;
		}
		
		var msg;
		switch (field) {
			case 'Price':
				msg = 'Please enter a numeric Price to Pay Carrier (total price to the trucker).\nTo enter a COD/COP amount, use the COD/COP field and choose "on Delivery" or "on Pickup".\nFor Prepay use COP. Notes can go in the Additional Information field.';
				break;
			case 'cod':
				msg = 'Please enter the numeric COD/COP amount if any and choose "on Delivery" or "on Pickup".\nFor Prepay use COP. Notes can go in the Additional Information field.';
				break;
			default:
				msg = field + ' can only be a number.';
		}
		
		alert (msg);
		return false;
	} else {
		if (obj.value == '') {
			if (!leaveBlank) {
				obj.value = '0';
			}
		} else {
			obj.value = roundCents(obj.value);
		}
		obj.style.backgroundColor = '';
	}
	return true;
}

function today_click( num ) { 
	if (num === undefined) { num = ''; }
	if ($('today' + num).checked) {
		var d = new Date();
		$('MON' + num).options[d.getMonth()].selected = 1;    // getMonth returns 0 based index
		$('DAY' + num).options[d.getDate()-1].selected = 1;   // getDate returns day, subtract 1 for index
		$('YR' + num).options[1].selected = 1;  // current year is always in 1 index
		$('YR' + num).disable();
		$('MON' + num).disable();
		$('DAY' + num).disable();
	}
	else {
		$('YR' + num).enable();
		$('MON' + num).enable();
		$('DAY' + num	).enable();
	}
}

// for server-side suggestion links, determine fieldset and set location
function setLocation( city, state, zip, metro, country, pre, post ) {
//console.log( city, state, zip, metro, country, pre, post );
	var id = pre + (post ? ' ' + post : '');
//console.log('id: ', id, ' // ', FatManager.fieldsets, ' // ', FatManager.fieldsets[id]);
	FatManager.fieldsets[id].set({city: city, state: state, zip: zip, metro: metro});
}


/**
 * form watcher object -- warn if abandoning edited page
 *
 * var ep = new editProtector(1); // watch for unsaved edits on document.forms[1]
 */
function editProtector( form ) {
	this.protected = true;
	this.form = form;
	this.message = 'You have unsaved changes.';
	this.exclude = [];
	
	// need to use native event to pass message
	var _this = this;
//	window.onload = function( ) { return _this.fixSubmitButtons(); };
	window.onbeforeunload = function( ) { return _this.modifiedCheck(); };
}

editProtector.prototype.release = function( ) {
	this.protected = false;
}

editProtector.prototype.fixSubmitButton = function( button ) {
//console.log('fixing button: ', button);
	
	var _func = button.onclick;
	var _this = this;
	button.onclick = function( ) {
//console.log('clicking button: ', this, _this);
		_this.protected = false;
		
		
//** Having trouble chaining prior onclick function
//** in FatClassifiedAdd
		
		if (typeof _func === 'function') {
//console.log('_func, _this, this ', _func, _this, this);
			_func().bind(this);
			(function( ) {alert('in _func()');}).bind(this);
//			(function( ) {_func();}).bind(this);
		}
	}
}

editProtector.prototype.fixSubmitButtons = function( ) {
//console.log('fixing buttons: ', this);
	if (typeof this.form == 'number') {
		this.form = $(document.forms[this.form]);
	}
//console.log('submits: ', this.form.getElements('input'));
	var _this = this;
//	this.form.getElements('input').each(function( button ) { if (button.type === 'submit') console.log('fix this: ', _this, button);});
	this.form.getElements('input').each(function( button ) { if (button.type === 'submit') _this.fixSubmitButton(button);});
}

editProtector.prototype.modifiedCheck = function( ) {
//console.log('checking form: ', this);
		if (typeof this.form == 'number') {
//console.log('convert num to form ', this, this.form);
			this.form = document.forms[this.form];
		}
		
//		if (!this.protected) {
		if (!this.protected || !this.form) {
//console.log('unprotected');
//return 'asdf';
			return null;
		}
		
		var warn = false;
		for (var i = 0; i < this.form.elements.length; ++i) {
			var el = this.form.elements[i];
			if (this.exclude.indexOf(el.name) > -1) {
				continue;
			}
			if (el.disabled) {
				continue;
			}
			switch (el.type) {
				case 'button':
					continue;
				case 'select-one':
				case 'select-multiple':
					var opts = el.options;
					for (var q = 0; q < opts.length; ++q) {
						if (opts[q].selected != opts[q].defaultSelected) {
							warn = true;
							break;
						}
					}
					break;
				case 'checkbox':
				case 'radio':
					if (el.checked != el.defaultChecked) {
						warn = true;
					}
					break;
				default:
					if (el.value != el.defaultValue) {
						warn = true;
					}
			}
			if (warn) {
//console.log('send message');
				return this.message;
			}
		}
//console.log('no message');
		return null;
};
