function updateSMSPreview() {
	var info = new Array();
	info = document.getElementById('expirationdate').value.split('/');
	var exp = info[0] + '/' + info[1] + '/' + info[2].substring(2);
	var text = $('#name').val() + ' @ ' + $('#shortname').val() + ' - ' + $('#offer').val() + ' - Exp: ' + exp;
	var count = text.length;
	
	if (130 - count <= 0) $('#characters').html('<span class="error">' + (130 - count) + '</span>'); 
	else $('#characters').text(130 - count);
	$('#smspreviewtext').text(text);
	$('#preview').val(text);
}

function autotab(original, destination) {
	if (original.getAttribute && original.value.length == original.getAttribute("maxlength")) $('#'+destination).focus();
}

function popUp(file, wide, tall) {
	popper = window.open(file,"popup_coupon","height="+tall+",width="+wide+",menubar=0,resizable=0,scrollbars=1,status=0,titlebar=0,toolbar=0,left=0,top=0");
	popper.focus();
}

function toggleCheckboxes(checked, form) {
	var el = document.getElementById(form);
	for (var i = 0; i < el.elements.length; i++) {
		if (el.elements[i].type == "checkbox" && el.elements[i].className != 'nocheck') el.elements[i].checked = checked;
	}
}

function toggleConditional(test, value, span1, span2, span3) {
	if (test == value) {
		if (span1 != '') document.getElementById(span1).style.display = '';
		if (span2 != '') document.getElementById(span2).style.display = '';
		if (span3 != '') document.getElementById(span3).style.display = '';
	}
	else {
		if (span1 != '') document.getElementById(span1).style.display = 'none';
		if (span2 != '') document.getElementById(span2).style.display = 'none';
		if (span3 != '') document.getElementById(span3).style.display = 'none';
	}
}

function toggleConditionalTR(test, value, id, elseid) {
	if (test == value) {
		document.getElementById(id).style.display = 'table-row';
		if (elseid != '' && elseid != undefined) document.getElementById(elseid).style.display = 'none';
	}
	else {
		document.getElementById(id).style.display = 'none';
		if (elseid != '' && elseid != undefined) document.getElementById(elseid).style.display = 'table-row';
	}
}

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 numbersonly(e, inputstring) {
	if (navigator.appName == 'Microsoft Internet Explorer')	key = window.event.keyCode;
	else key = e.which;
	if (key >= 48 && key <= 57) return true;
	//else if (key == 46 && inputstring.indexOf(".") == -1) return true;
	else if (key == 0 || key == 8) return true;
	else return false;
}

function numbersanddecimalonly(e, inputstring) {
	if (navigator.appName == 'Microsoft Internet Explorer')	key = window.event.keyCode;
	else key = e.which;
	
	if (key >= 48 && key <= 57) return true;
	else if (key == 46 && inputstring.indexOf(".") == -1) return true;
	else if (key == 0 || key == 8) return true;
	else return false;
}
	
function countChecks(activeRow, maxcount, inc1, inc2, inc3, group) {
	var count = 0;
	//alert(eval(group));
	//var radioArray = multigroup.split(",");
	var radioArray = eval(group).split(",");
	
	for (x = 0; x < radioArray.length; x++) {
		//alert( eval("document.item_details." + radioArray[x] + "[1].checked") );
		if (eval("document.item_details." + radioArray[x] + "[1].checked") == true) count += inc1;
		if (eval("document.item_details." + radioArray[x] + "[2].checked") == true) count += inc2;
		if (eval("document.item_details." + radioArray[x] + "[3].checked") == true) count += inc3;
	}
	
	if (count > maxcount) {
		alert("You have already selected the maximum number of items.");
		eval("document.item_details." + activeRow + "[0].checked = true;");
	}
}

function handleEnter(field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++)
			if (field == field.form.elements[i])
				break;
		i = (i + 1) % field.form.elements.length;
		field.form.elements[i].focus();
		return false;
	} 
	else
	return true;
}

function swapVisibility(show, hide) {
	if (show != '') document.getElementById(show).style.display = '';
	if (hide != '') document.getElementById(hide).style.display = 'none';
}

function toggleVisibility(divid, linkdiv, visibletext, hiddentext) {
	if (linkdiv == undefined) linkdiv = '';
	
	if (document.getElementById(divid).style.display == 'none') {
		document.getElementById(divid).style.display = '';
		if (linkdiv != '' && visibletext != '') document.getElementById(linkdiv).innerHTML = visibletext;
	}
	else {
		document.getElementById(divid).style.display = 'none';
		if (linkdiv != '' && hiddentext != '') document.getElementById(linkdiv).innerHTML = hiddentext;
	}
}

function paymentDetails(pmtmethod) {
	if (pmtmethod != 'cash' && pmtmethod != 'check') {
		$('#tip,#tiptotal,#tipcalc').css({ display:"table-row" });
		totalWithTip();
	}
	else {
		$('#tip,#tiptotal,#tipcalc').css({ display:"none" });
		var total = $('#totalwithouttip').html();
		total = parseFloat(total.replace(/\$/, ""));
		$('#order_total').val(roundNumber(total, 2));
	}
}

function totalWithTip() {
	var total = $('#totalwithouttip').html();
	total = parseFloat(total.replace(/\$/, ""));
	var tip = document.getElementById('tip_amount').value;
	if (tip == '') tip = 0;
	else tip = parseFloat(tip);
	$('#totalwithtip').html(formatCurrency(total + tip));
	$('#order_total').val(roundNumber(total + tip, 2));
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function togglePriceSchedule(display) {
	if (display == true) {
		document.getElementById('price_schedule').style.display = 'inline';
		document.getElementById('size1header').style.display = 'inline';
	}
	else {
		document.getElementById('price_schedule').style.display = 'none';
		document.getElementById('size1header').style.display = 'none';
	}
}

function toggleDailyAvailability(display) {
	if (display == false) {
		document.getElementById('showdays').style.display = 'inline';
	}
	else {
		document.getElementById('showdays').style.display = 'none';
	}
}

function toggleChildItemField(id, max, cssclass) {
	if (id != '' && id <= max) {
		$(cssclass).css("display","none");
	}
	else {
		$(cssclass).css("display","table-row");
	}
}

function attachOption(type) {
	var count = document.getElementById('form_option').elements.length;
	var fd = document.getElementById('optiondivs');
	var c = 0;
	var html = "";

	for (i = 0; i < count; i++) {
		var element = document.getElementById('form_option').elements[i]; 
		if (element.name.match("newoption") && element.name.match("_cat1price")) c++;
	}
	
	var newdiv = document.createElement('div');
	var divIdName = 'filediv'+c;
	newdiv.setAttribute('id',divIdName);
	if (type == 'select' || type == 'radio' || type == 'dropdown' || type == 'checkbox' || type == 'radiomulti') newdiv.innerHTML = "<table cellspacing=\"0\" cellpadding=\"2\" border=\"0\"><tr><td width=\"24\">&nbsp;</td><td><input type=\"text\" name=\"newoption_" + c + "_value\" id=\"newoption_" + c + "_value\" class=\"textbox_med\" /> <input type=\"text\" name=\"newoption_" + c + "_cat1price\" id=\"newoption_" + c + "_cat1price\" size=\"8\" class=\"textbox_number\" autocomplte=\"off\" /> <a href=\"#\" onclick=\"removeElement('" + divIdName + "')\">Remove</a></td></tr></table>";
	else if (type == 'text' || type == 'textnum') newdiv.innerHTML = "<table cellspacing=\"0\" cellpadding=\"2\" border=\"0\"><tr><td width=\"24\">&nbsp;</td><td><input type=\"text\" name=\"newoption_" + c + "_value\" id=\"newoption_" + c + "_value\" class=\"textbox_med\" /> <a href=\"#\" onclick=\"removeElement('" + divIdName + "')\">Remove</a></td></tr></table>";
	fd.appendChild(newdiv);
}

function removeElement(divNum) {
	var count = document.getElementById('form_option').elements.length;
	var c = 0;
	
	for (i = 0; i < count; i++) {
		var element = document.getElementById('form_option').elements[i]; 
		if (element.name.match("newoption") && element.name.match("_cat1price")) c++;
	}
	
	var d = document.getElementById('optiondivs');
	var olddiv = document.getElementById(divNum);
	d.removeChild(olddiv);
}

function generateElements(num, type) {
	var fd = document.getElementById('optiondivs');
	
	for (x = 0; x < num; x++) {
		c = x + 1;
		var newdiv = document.createElement('div');
		var divIdName = 'filediv'+c;
		newdiv.setAttribute('id',divIdName);
		if (type == 'select' || type == 'radio' || type == 'checkbox' || type == 'radiomulti') newdiv.innerHTML = "<table cellspacing=\"0\" cellpadding=\"2\" border=\"0\"><tr><td width=\"24\">&nbsp;</td><td><input type=\"text\" name=\"newoption_" + c + "_value\" id=\"newoption_" + c + "_value\" class=\"textbox_med\" /> <input type=\"text\" name=\"newoption_" + c + "_cat1price\" id=\"newoption_" + c + "_cat1price\" size=\"8\" class=\"textbox_number\" autocomplete=\"off\" /> <a href=\"#\" onclick=\"removeElement('" + divIdName + "')\">Remove</a></td></tr></table>";
		else if (type == 'text' || type == 'textnum') newdiv.innerHTML = "<table cellspacing=\"0\" cellpadding=\"2\" border=\"0\"><tr><td width=\"24\">&nbsp;</td><td><input type=\"text\" name=\"newoption_" + c + "_value\" id=\"newoption_" + c + "_value\" class=\"textbox_med\" /> <a href=\"#\" onclick=\"removeElement('" + divIdName + "')\">Remove</a></td></tr></table>";
		fd.appendChild(newdiv);
	}
}

function checkABA(s) {
	var i, n, t;
	
	// First remove any non-numeric characters
	t = "";
	for (i = 0; i < s.length; i++) {
		c = parseInt(s.charAt(i), 10);
		if (c >= 0 && c <= 9) t = t + c;
	}
	
	// Check the length, it should be nine digits
	if (t.length != 9) return false;
	
	// Now run through each digit and calculate the total
	n = 0;
	for (i = 0; i < t.length; i += 3) {
		n += parseInt(t.charAt(i), 10) * 3 +  parseInt(t.charAt(i + 1), 10) * 7 +  parseInt(t.charAt(i + 2), 10);
	}
	
	// If the resulting sum is an even multiple of ten (but not zero) the aba routing number is good
	if (n != 0 && n % 10 == 0) return true;
	else return false;
}

function checkBank(routing) {
	if (routing != '') {
		if (checkABA(routing) == true) {
			$.ajax({
				url: "/ajax/bankinfo.php?routing=" + routing,
				cache: false,
				success: function(html){
					$('#bankname').html(html);
				}
			});
		}
		else {
			if (routing.length != 9) $('#bankname').html('<span class="error">Routing number should be 9 digits</span>');
			else $('#bankname').html('<span class="error">Invalid routing number</span>');
		}
	}
	else {
		$('#bankname').html('');
	}
}

function clearText(textbox, resetvalue) {
	if (textbox.value == resetvalue) textbox.value = '';
}

function resetText(textbox, resetvalue) {
	if (textbox.value == '') textbox.value = resetvalue;
}

function showPreorderTimes(restaurant_id, preorderDate, currentTime, pickup, delivery, updateOrderType) {
	$('.preorder_date').removeClass('cal_selected white');
	$('#preorder_date_' + preorderDate).addClass('cal_selected white');
	document.getElementById('preordertime').style.display = 'inline';
	$.ajax({
		url: "/ajax/preordertimes.php?r=" + (restaurant_id * 1) + '&date=' + preorderDate + '&time=' + currentTime + '&pickup=' + (pickup * 1) + '&delivery=' + (delivery * 1) + '&updateordertype=' + updateOrderType,
		cache: false,
		success: function(html){
			$('#preordertime').html(html);
			$('#preorderdate').val(preorderDate);
		}
	});
}

function populateCouponEmailForm(client_id, handle) {
	$("#email_content").html('<iframe src="/tile/emailcoupon.php?id='+client_id+'&handle='+handle+'" frameborder="no" width="100%" height="360" class="relative"></iframe>');
}

function populateSMSForm(client_id) {
	$('#sms_content').html('<iframe src="/tile/sms.php?client_id=' + client_id + '" frameborder="0" width="100%" height="300"></iframe>');
}

/***********************************************************************************/
// http://www.mattkruse.com/javascript/checkboxgroup/index.html
/*
DESCRIPTION: This library lets you quickly and easily make multiple checkboxes
behave as a group by limiting the total number of boxes that can be checked
and/or have a master control checkbox. 

COMPATABILITY: Should work on all Javascript-compliant browsers.

USAGE:
// Create a new CheckBoxGroup object
var myOptions = new CheckBoxGroup();

// Tell the object which checkboxes exist in your group. You may make multiple
// calls to this function, and/or pass multiple arguments. You may specify
// field names exactly, or use a wildcard at the beginning or end of the 
// name.
myOptions.addToGroup("cb1","cb2","optionset*");
myOptions.addToGroup("*checkbox");

// Optionally set a "control" box which will effect all other boxes.
myOptions.setControlBox("masterCheckboxName");

// Specify how your control box will interact with the group. Options are
// either "some" or "all" ("all" is default).
// all: Checking the box will select all the other boxes. Unchecking it will
//      uncheck all the group checkboxes. Selecting all the checkboxes in
//      the group will automatically check the control box.
// some: Checking any checkbox in the group will check the control box. The
//       control box may not be unchecked if any option in the group is 
//       still checked. If no boxes in the group are checked, you may still
//       check the control box.
myOptions.setMasterBehavior("some");

// Optionally set the maximum number of boxes in the group which are allowed
// to be checked. You may pass a second argument which is an alert message to
// be displayed to the user if they exceed this limit.
myOptions.setMaxAllowed(3);
myOptions.setMaxAllowed(3,"You may only select 3 choices!");

// IMPORTANT: After defining the group and behavior, you must insert an action
// into EVERY checkbox's onClick event-handler. Just specify the name of the
// group object that the checkbox belongs to, and pass it 'this' as the argument.
<INPUT TYPE="checkbox" NAME="cb1" onClick="myOptions.check(this)">

// That's it! Your checkboxes will now behave as a group!

*/ 
function CheckBoxGroup() {
	this.controlBox=null;
	this.controlBoxChecked=null;
	this.maxAllowed=null;
	this.maxAllowedMessage=null;
	this.masterBehavior=null;
	this.formRef=null;
	this.checkboxWildcardNames=new Array();
	this.checkboxNames=new Array();
	this.totalBoxes=0;
	this.totalSelected=0;
	// Public methods
	this.setControlBox=CBG_setControlBox;
	this.setMaxAllowed=CBG_setMaxAllowed;
	this.setMasterBehavior=CBG_setMasterBehavior;	// all, some
	this.addToGroup=CBG_addToGroup;
	// Private methods
	this.expandWildcards=CBG_expandWildcards;
	this.addWildcardCheckboxes=CBG_addWildcardCheckboxes;
	this.addArrayCheckboxes=CBG_addArrayCheckboxes;
	this.addSingleCheckbox=CBG_addSingleCheckbox;
	this.check=CBG_check;
	}

// Set the master control checkbox name
function CBG_setControlBox(name) { this.controlBox=name; }

// Set the maximum number of checked boxes in the set, and optionally
// the message to popup when the max is reached.
function CBG_setMaxAllowed(num,msg) {
	this.maxAllowed=num;
	if (msg!=null&&msg!="") { this.maxAllowedMessage=msg; }
	}

// Set the behavior for the checkbox group master checkbox
//	All: all boxes must be checked for the master to be checked
//	Some: one or more of the boxes can be checked for the master to be checked
function CBG_setMasterBehavior(b) { this.masterBehavior = b.toLowerCase(); }

// Add checkbox wildcards to the checkboxes array
function CBG_addToGroup() {
	if (arguments.length>0) {
		for (var i=0;i<arguments.length;i++) {
			this.checkboxWildcardNames[this.checkboxWildcardNames.length]=arguments[i];
			}
		}
	}

// Expand the wildcard checkbox names given in the addToGroup method
function CBG_expandWildcards() {
	if (this.formRef==null) {alert("ERROR: No form element has been passed.  Cannot extract form name!"); return false; }
	for (var i=0; i<this.checkboxWildcardNames.length;i++) {
		var n = this.checkboxWildcardNames[i];
		var el = this.formRef[n];
		if (n.indexOf("*")!=-1) { this.addWildcardCheckboxes(n); }
		else if(CBG_nameIsArray(el)) { this.addArrayCheckboxes(n); }
		else { this.addSingleCheckbox(el); }
		}
	}


// Add checkboxes to the group which match a pattern
function CBG_addWildcardCheckboxes(name) {
	var i=name.indexOf("*");
	if ((i==0) || (i==name.length-1)) {
		searchString= (i)?name.substring(0,name.length-1):name.substring(1,name.length);
		for (var j=0;j<this.formRef.length;j++) {
			currentElement = this.formRef.elements[j];
			currentElementName=currentElement.name;
			var partialName = (i)?currentElementName.substring(0,searchString.length) : currentElementName.substring(currentElementName.length-searchString.length,currentElementName.length);
			if (partialName==searchString) {
				if(CBG_nameIsArray(currentElement)) this.addArrayCheckboxes(currentElement);
				else this.addSingleCheckbox(currentElement);
				}
			}
		}
	}

// Add checkboxes to the group which all have the same name
function CBG_addArrayCheckboxes(name) {
	if((CBG_nameIsArray(this.formRef[name])) && (this.formRef[name].length>0)) {
		for (var i=0; i<this.formRef[name].length; i++) { this.addSingleCheckbox(this.formRef[name][i]); }
		}
	}

function CBG_addSingleCheckbox(obj) {
	if (obj != this.formRef[this.controlBox]) {
		this.checkboxNames[this.checkboxNames.length]=obj;
		this.totalBoxes++;
		if (obj.checked) {
			this.totalSelected++;
			}
		}
	}

// Runs whenever a checkbox in the group is clicked
function CBG_check(obj, value) {
	var checked=obj.checked;
	if (this.formRef==null) {
		this.formRef=obj.form;
		this.expandWildcards();
		if (this.controlBox==null || obj.name!=this.controlBox) {
			this.totalSelected += (checked)?-1:1;
		}
	}
	if (this.controlBox!=null&&obj.name==this.controlBox) {
		if (this.masterBehavior=="all") {
			for (i=0;i<this.checkboxNames.length;i++) { this.checkboxNames[i].checked=checked; }
			this.totalSelected=(checked)?this.checkboxNames.length:0;
		}
		else {
			if (!checked) {
				obj.checked = (this.totalSelected>0)?true:false;
				obj.blur();
				}
			}
		}
	else {
		if (this.masterBehavior=="all") {
			if (!checked) {
				this.formRef[this.controlBox].checked=false;
				this.totalSelected--;
			}
			else { this.totalSelected++; }
			if (this.controlBox!=null) {
				this.formRef[this.controlBox].checked=(this.totalSelected==this.totalBoxes)?true:false;
				}
			}
		else {
			if (!obj.checked) { this.totalSelected--; }	
			else { this.totalSelected++; }
			if (this.controlBox!=null) {
				this.formRef[this.controlBox].checked=(this.totalSelected>0)?true:false;
			}
			if (this.maxAllowed!=null) {
				if (this.totalSelected>this.maxAllowed) {
					obj.checked=false;
					this.totalSelected--;
					if (this.maxAllowedMessage!=null) { alert(this.maxAllowedMessage); }
					return false;
				}
			}
		}
	}
}

function CBG_nameIsArray(obj) {
return ((typeof obj.type!="string")&&(obj.length>0)&&(obj[0]!=null)&&(obj[0].type=="checkbox"));
}
/***********************************************************************************/