/* variable so by set so we know how many weeks... */
var numWeeksSelling;
var vendors = [];
var creditInvoiceSubmit;
var alternatePickUpSubmit;

var showTabContent = function() {
	$$('.hiddenTab').setStyle('display', 'none');
	var choice = this.get('id');
	$(choice + 'Content').setStyle('display', 'block');
	$$('.menuItem').removeClass('tab-selected');
	$(choice).addClass('tab-selected');
};

var showSubTabContent = function () {
	$$('.hiddenSubTab').setStyle('display', 'none');
	var choice = this.get('id');
	$(choice + 'Content').setStyle('display', 'block');
	$$('.subMenuItem').removeClass('tab-selected');
	$(choice).addClass('tab-selected');
};

/* START Order Form Functions */
function fillWeek(weekNum) {
	$$('#orderTable select').each(function(selBox) {
		if (selBox.getProperty('name').split('_')[1] == weekNum) {
			if (selBox.getSelected()[0].value == 0) {
				selBox.getChildren()[1].setProperty('selected', 'selected');
				selBox.fireEvent('change');
			}
		}
	});
}

var changedQuantity = function () {
	var weekNum;
	weekNum = this.getProperty('name').split('_')[1];
	/* If this is the FMB select box and we're setting it to 0, then 0 out all other items */
	if (this.getProperty('id') == ('fmb_'+weekNum) && this.getSelected()[0].value == 0) {
		$$('#orderTable select').each(function(selBox) {
			if (selBox.getProperty('name').split('_')[1] == weekNum) { selBox.getFirst().setProperty('selected', 'selected'); }
		});
	}
	/* Make sure this lines FMB is set if we're selecting a partner item */
	weekNum = this.getProperty('name').split('_')[1];
	if (this.getProperty('id') != ('fmb_'+weekNum) && $('fmb_'+weekNum).getSelected()[0].value == 0) { $('fmb_'+weekNum).getChildren()[1].setProperty('selected', 'selected'); }
	calcTotals();
};

function calcTotals() {
	var price;
	var quantity;
	var cost;
	var weekNum;
	var totalVal = 0.0;
	var subTotals = [];
	for (var i=0; i < numWeeksSelling; i++) { subTotals[i] = 0.0; }
	/* Run through all the select boxes and re-calculate the new totals */
	$$('#orderTable select').each(function(selBox) {
		price = selBox.getProperty('name').split('_')[4];
		quantity = selBox.getSelected()[0].value;
		weekNum = selBox.getProperty('name').split('_')[1];
		cost = price * quantity;
		subTotals[weekNum] += cost;
		totalVal += cost;
	});
	/* Fill in the various totals boxes... */
	for (var i=0; i < subTotals.length; i++) {
		cost = Currency(subTotals[i]);
		$('W_'+i).set('html', cost);
	}
	cost = Currency(totalVal);
	$('saleTotal').set('html', cost);
}

function submitFMBorder() {
	var orders = [];
	for (var i=0; i < numWeeksSelling; i++) { orders[i] = new Hash(); }
	var numBags = 0;
	$$('#orderTable select').each(function(selBox) {
		var weekNum = selBox.getProperty('name').split('_')[1];
		pIdx = 'p' + selBox.getProperty('name').split('_')[3];
		orders[weekNum][pIdx] = new Hash();
		orders[weekNum][pIdx].vendor = vendors[selBox.getProperty('name').split('_')[2]];
		orders[weekNum][pIdx].locIdx = selBox.getProperty('name').split('_')[2];
		orders[weekNum][pIdx].pDesc = selBox.getNext('span').get('html');
		orders[weekNum][pIdx].pQuan = selBox.getSelected()[0].value;
		orders[weekNum][pIdx].pPrice = selBox.getProperty('name').split('_')[4];
		if (orders[weekNum][pIdx].locIdx == 0) numBags += orders[weekNum][pIdx].pQuan;
	});
	if (numBags == 0) {
		alert("You need to order at least 1 Farmers' Market Bag...");
		return false;
	}
	var formHash = new Hash();
	formHash.vendors = vendors;
	formHash.shipping = 0;
	formHash.tax = 0;
	formHash.total = $('saleTotal').get('html');
	formHash.numWeeksSell = numWeeksSelling;
	formHash.order = orders;
	//alert(JSON.encode(formHash));
	$('fmbJSON').value = JSON.encode(formHash);
	$('fmbOrderForm').submit();
}
/* END Order Form Functions */

/* START Manage Orders Functions */
function creditOrder() {
	var formHash = new Hash();
	formHash.invoiceNumber = $('invoiceNumber').value;
	formHash.creditAmount = $('creditAmount').value;
	creditInvoiceSubmit.setOptions({data: {'encFormData' : JSON.encode(formHash)}}).send();
}
function setAlternatePickUp() {
	if ($('altPUName').value == '' && $('origAltPU').value == '') {
		alert("You didn't enter a name...");
	} else {
		var formHash = new Hash();
		formHash.altName = $('altPUName').value;
		alternatePickUpSubmit.setOptions({data: {'encFormData' : JSON.encode(formHash)}}).send();
	}
}
/* END Manage Orders Functions */

/* Script to run when the DOM is loaded and ready */
window.addEvent('domready', function() {
	/* For the clickable menu tabs */
	$$('#mainContent li[class=menuItem]').each(function(tabDiv) {
		tabDiv.addEvent('click', showTabContent.bind(tabDiv));
	});
	if ($('Ordering')!= null) {
		$('Ordering').addClass('tab-selected');
		$('OrderingContent').setStyle('display', 'block');
	}
	
	/* For the clickable submenu tabs */
	$$('#mainContent li[class=subMenuItem]').each(function(tabDiv) {
		tabDiv.addEvent('click', showSubTabContent.bind(tabDiv));
	});
	if ($('PlaceOrder')!= null) {
		$('PlaceOrder').addClass('tab-selected');
		$('PlaceOrderContent').setStyle('display', 'block');
	}
	
	/* Add the onChange events to orderTable Select */
	$$('#orderTable select').each(function(selBox) {
		selBox.addEvent('change', changedQuantity.bind(selBox));
	});
	
	/* Calculate the totals (in case this is a page reload */
	if ($('orderTable')!= null) calcTotals();
	
	/* The tip div starts out in the upper left corner, visible and small... */
	$$('div[class=tippedItem]]').each( function(tipDiv) {
		tipDiv.setStyle('display', 'none');
	});
	
	/* Form Submission */
	creditInvoiceSubmit = new Request.JSON( {
		method : 'post',
		async : false,
		url : 'includes/ccCreditInvoice.php',
		data: {'encFormData' : ''},
		onRequest : function() {
			$('ccErrorDiv').set('html', '');
			$('creditQuestion').setStyle('display', 'none');
			$('creditProcessing').setStyle('display', 'block');
			mainSpinner.show(true);
		},
		onSuccess : function(response) {
			mainSpinner.hide(true);
			if (response.result == true) window.location = $('creditSuccessPage').value;
			else {
				$('creditProcessing').setStyle('display', 'none');
				$('ccErrorDiv').set('html', response.errorMsg);
			}
			return true;
		}
	});
	
	alternatePickUpSubmit = new Request.JSON( {
		method : 'post',
		async : false,
		url : 'includes/altPickUpSet.php',
		data: {'encFormData' : ''},
		onRequest : function() {
			$('setaltErrDiv').set('html', '');
			$('altPUSubmit').disabled = true;
			$('altPUSubmit').set('value', 'Processing...');
		},
		onSuccess : function(response) {
			if (response.result == true) window.location = '../fmb';
			else $('setaltErrDiv').set('html', response.errorMsg);
			return true;
		}
	});
});

//returns number as string in $ xxx,xxx.xx format.
function Currency(anynum) {
        anynum = "" + eval(anynum);  //evaluate (in case an expression sent)
        intnum = parseInt(anynum); //isolate integer portion
        intnum = Math.abs(intnum);
        intstr = ""+intnum;
        //add comma in thousands place.
        if (intnum >= 1000) {
                intlen = intstr.length;
                temp1=parseInt(""+(intnum/1000));
                temp2=intstr.substring(intlen-3,intlen);
                intstr = temp1+","+temp2;
        }
        if (intnum >= 1000000) {
                intlen = intstr.length;
                temp1=parseInt(""+(intnum/1000000));
                temp2=intstr.substring(intlen-7,intlen);
                intstr = temp1+","+temp2;

        }
        decnum = Math.abs(parseFloat(anynum)-parseInt(anynum)); //isolate decimal portion
        decnum = decnum * 100; // multiply decimal portion by 100.
        decstr = "" + Math.abs(Math.round(decnum));
        if (decstr.length>2) decstr=decstr.substring(0,2);
        while (decstr.length < 2) {decstr="0"+decstr; }
        retval = intstr + "." + decstr;
        if (anynum < 0) { retval="("+retval+")"; }
        return "$ "+retval;
}
