function updateAction(form,newaction) { form.action.value = newaction; }

function toggleDisplay(elementId,boolVisible)
{
//	alert(boolVisible);
	var objElement = document.getElementById(elementId);
	if(!boolVisible)
		objElement.style.display = "none";
	else 
		objElement.style.display = "";
}

function updateShipping(cartCost,shippingBase,shippingExtra,shippingExcess,shippingReplaceFlag,idShipping,idTotal,idShippingExcess)
{
	// calculate the cost of the shipping
	var totalCost = 0;
	var shippingCost = 0;
	var shippingCostExcess = 0;
	if(shippingReplaceFlag == 1)
	{
		shippingCost = shippingExtra;
	}
	else
	{
		shippingCost = shippingBase + shippingExtra;
		shippingCostExcess = shippingExcess;
	}
	
	totalCost = cartCost + shippingCost + shippingCostExcess;
	
	// update the div id tags
	var shippingElement = document.getElementById(idShipping);
	shippingElement.innerHTML = '$' + shippingCost.toFixed(2);
	var totalElement = document.getElementById(idTotal);
	totalElement.innerHTML = '$' + totalCost.toFixed(2);
	var shippingExcessElement = document.getElementById(idShippingExcess);
	shippingExcessElement.innerHTML = '$' + shippingCostExcess.toFixed(2);
}

// public variable for the following function
var ajax_js = "";
var ajax_js_flag = 0;

function evalAjaxJS(idDiv,mode)
{
	var responseDiv = document.getElementById(idDiv);
	var response = responseDiv.innerHTML;
	var startString = "<!-- TD_javascript";
	var endString = "TD_javascript_end -->";

	// mode is reserved in case we want to add append functionality
	// default mode used currently is 'REPLACE'
	
	alert("Running eval js");
	
	if(response.match(startString)) {
		var startArray = response.split(startString);
		for (i=0; i < startArray.length; i++){
			if(startArray[i].match(endString)) {
				var endArray = startArray[i].split(endString);
				ajax_js = endArray[0];
				ajax_js_flag = 1;
				break;
			}
		}
	}
	alert("Finished running eval js");	
}

function updatePaymentCosts(cartCost,shipping,paymentCost,idPayment,idTotal)
{
	// calculate the cost of the cart + shipping + paymentCost
	var totalCost = cartCost + shipping + paymentCost;
	
	// update the div id tags
	var paymentElement = document.getElementById(idPayment);
	paymentElement.innerHTML = '$' + paymentCost.toFixed(2);
	
	var totalElement = document.getElementById(idTotal);
	totalElement.innerHTML = '$' + totalCost.toFixed(2);
}

function sjtest() {
//	alert("updating div");

	eval(ajax_js);
	alert(option_field_num);
	
/*	var d = new Date();
	var timenow = d.getTime();
	
	var productDiv = document.getElementById('product_information');
	var sjDiv = document.getElementById('sjtestdiv2');
	sjDiv.innerHTML = "Inner HTML (" + timenow + "): " + productDiv.innerHTML;
	
	alert(productDiv.innerHTML);
*/
}

//function updateOptionCosts(idOptionField,optionNameArray,numberOptions,povIdArray,povAlterArray,numberPOV)
function updateOptionCosts()
{	
/*	alert("Running option costs");
	// if the ajax js function hasn't been sucked in, quit the function
	if(!ajax_js_flag)
		return 0;
	alert("Found an update to the JS");	
	eval(ajax_js);
*/	
	// find the active option values
	var optionCost = 0;
	for (loop=0; loop < option_field_num; loop++){
		var optionField = document.getElementById(option_field_name[loop]);
		var selectedId = optionField.selectedIndex;
		var valueId = optionField.options[selectedId].value;
	//	alert("VI (" + option_field_name[loop] + "): " + valueId);
		if(valueId > 0) {
			// lookup the alter value for the select POV
			for (i=0; i < pov_num; i++){
				if(pov_id[i] == valueId) {
					optionCost += pov_alter[i];
					break;
				}
			}
		}
	}
	
	// update the option cost tag
	var OCElement = document.getElementById('option_costs');
	OCElement.innerHTML = '$' + optionCost.toFixed(2);
}


/*
<!-- Dynamic Version by: Nannette Thacker -->
<!-- http://www.shiningstar.net -->
<!-- Original by :  Ronnie T. Moore -->
<!-- Web Site:  The JavaScript Source -->
<!-- Use one function for multiple text areas on a page -->
<!-- Limit the number of characters per textarea -->
*/

function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit) 
		// if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	else
		// otherwise, update 'characters left' counter
		cntfield.value = maxlimit - field.value.length;
}

function toggleRow(checkValue,selector,selectorTarget,mode,speed) {
	var matched=0;
	$.each(checkValue,function(key,value){  
		if($(selector).val() == value) { 
			if(mode == 1) 	{ $(selectorTarget).hide(speed); }
			else 		{ $(selectorTarget).show(speed); }
			matched=1;
			return false;
		}
	});
	
	if(!matched) {
		if(mode == 1) 	{ $(selectorTarget).show(speed); }
		else 		{ $(selectorTarget).hide(speed); }
	}
}


// array used for handling the APIs of jquery dialogs (necessary to programmatically close the dialogs on submit)
function JQDialogArray() { this.jqda = []; } 
JQDialogArray.prototype.add = function(a) { this.jqda[this.jqda.length] = a; }
JQDialogArray.prototype.reset = function(a) { this.jqda = []; }
JQDialogArray.prototype.close = function() {
	for( var i=0; i<this.jqda.length; i++ ) {
		this.jqda[i].close();
	}
} 
var jqueryDialogAPI = new JQDialogArray();

// array used for auto complete field APIs
function JQACArray() { this.jqaca = []; } 
JQACArray.prototype.add = function(a) { this.jqaca[this.jqaca.length] = a; }
JQACArray.prototype.reset = function(a) { this.jqaca = []; }
JQACArray.prototype.initialize = function() {
	for( var i=0; i<this.jqaca.length; i++ ) {
		this.jqaca[i].initialize();
	}
} 
JQACArray.prototype.fixPosition = function() {
	for( var i=0; i<this.jqaca.length; i++ ) {
		this.jqaca[i].fixPosition();
	}
} 
var jqueryACAPI = new JQACArray();


// JQuery handler array and functions
function JQarray() { this.jqhs = []; } 
JQarray.prototype.add = function(f) {
	if( typeof f!= "function" )
		f = new Function(f);
	this.jqhs[this.jqhs.length] = f;
}
JQarray.prototype.execute = function() {
	for( var i=0; i<this.jqhs.length; i++ )
		this.jqhs[i]();
} 
// create the click handler array
var jqueryHandlers = new JQarray();


function registerClickHandler(clickElement,targetElement,urlString,dataString,filterFormElement,loadingElement,preSubmitFunction) {
	var clickId  = document.getElementById(clickElement);
	var targetId = document.getElementById(targetElement);
	var filterFormId = document.getElementById(filterFormElement);
	
	var loadingId = targetId;
	if(loadingElement != null)
		loadingId = document.getElementById(loadingElement);
	
	if( typeof preSubmitFunction != "function" )
		preSubmitFunction = new Function(preSubmitFunction);
	
	if(clickId != null && targetId != null) {
		// if there is already a click handler bound to this ID, unbind it
		var myEvents = $(clickId).data('events');
		if(myEvents) 
			$(clickId).unbind("click");
		
		$(clickId).click(function(event) {
			event.preventDefault();
			$(this).attr("disabled", "true");
			
			preSubmitFunction();
			var dataStringSubmit = dataString;
			if(filterFormId != null)
				dataStringSubmit = $(filterFormId).serialize() + dataString;
			
			//$.blockUI.defaults.overlayCSS = {};
			$(loadingId).block({
				message: '<h3 class="loading-message"><div id="loading-image"></div>Loading data ...</h3>'
			});
			
			$.ajax({
				url: urlString,
				data: dataStringSubmit,
				dataType: "html",
				cache: false,
				success: function(scriptOutput){
					$(targetId).html(scriptOutput);
					$(loadingId).unblock();
				},
				error: function() {
					alert("Error talking to server");
				},
				complete: function() {
					$(this).attr("disabled", "false");
					jqueryHandlers.execute();
				}
			});
		});
	}
};

function registerFormClickHandler(clickElement,targetElement,urlString,formName) {
	var clickId  = document.getElementById(clickElement);
	var targetId = document.getElementById(targetElement);
	var formId = document.getElementById(formName);
	
	if(clickId != null && targetId != null && formId != null) {
		// if there is already a click handler bound to this ID, unbind it
		var myEvents = $(clickId).data('events');
		if(myEvents) 
			$(clickId).unbind("click");
		
		$(clickId).click(function(event) {
			event.preventDefault();
			$(targetId).slideUp("slow");
			$.ajax({
				url: urlString,
				data: $(formId).serialize(),
				dataType: "html",
				success: function(scriptOutput){
					$(targetId).show("slow");
					$(targetId).html(scriptOutput);
				},
				error: function() {
					alert("Error talking to server");
				},
				complete: function() {
					//$(this).attr("disabled", "false");
					jqueryHandlers.execute();
				}
			});
		});
	}
};

function registerObserveHandler(observedElement,targetElement,urlString,dataString,minCharacters,interval,successFunction,loadingHTML) {
	var observedId  = document.getElementById(observedElement);
	var targetId = document.getElementById(targetElement);
	
	if( typeof successFunction != "function" )
		successFunction = new Function(successFunction);
	
	if(observedId != null && targetId != null) {
		var existingValue = $(observedId).val();
		var isRunning=0;
//		alert("Existing: " + existingValue);
		setInterval(function() {
			// should prevent duplicate instances
			if(isRunning == 0) {
				//var newValue = $(observedId).attr("value");
				var newValue = $(observedId).val();
				var fullDataString = dataString + newValue;
//				alert("New: " + newValue + " (" + existingValue + ") (" + newValue.length + ")");
				if(newValue.length >= minCharacters && newValue != existingValue) {
//					alert("Value has changed - running ajax call");
					isRunning=1;
					if(loadingHTML) { $(targetId).html(loadingHTML); }
					$.ajax({
						url: urlString,
						data: fullDataString,
						dataType: "html",
						success: function(scriptOutput){
							//$(targetId).show("fast");
							$(targetId).html(scriptOutput);
							successFunction();
//							alert("Successfully run");
						},
						error: function() {
							alert("Error talking to server");
						},
						complete: function() {
							isRunning=0;
							existingValue = newValue;
						}
					});
				}
			}
			//runCount++;
			//alert("Ran interval function " + runCount + " times");
		},interval);
	}
};

function registerAutoCompleteHandler(entryField,urlString,parameters,minCharacters,delay,callbackFunction) {
	var entryFieldId  = document.getElementById(entryField);
	
	if(entryFieldId == null)
		return 0;
	
	var ach;
	if( typeof callbackFunction == "function" ) {
		ach = $(entryFieldId).autocomplete({ 
			serviceUrl: urlString,
			minChars: minCharacters, 
			deferRequestBy: delay,
			params: parameters,
			onSelect: callbackFunction
		});
	}
	else {
		ach = $(entryFieldId).autocomplete({ 
			serviceUrl: urlString,
			minChars: minCharacters, 
			deferRequestBy: delay,
			params: parameters
		});
	}
	
	jqueryACAPI.add(ach);
};

function registerAutoCompleteHandler_new(entryField,urlString,parameters,minCharacters,delay,callbackFunction) {
	var entryFieldId  = document.getElementById(entryField);
	
	if(entryFieldId == null)
		return 0;
	
	if( typeof callbackFunction == "function" ) {
		$(entryFieldId).autocomplete(urlString,{ 
			minChars: minCharacters,
			delay: delay,
			extraParams: parameters
		}).result(callbackFunction);
	}
	else {
		$(entryFieldId).autocomplete(urlString,{ 
			minChars: minCharacters,
			delay: delay,
			extraParams: parameters
		});
	}
};

function registerAjaxFormHandler(formElement,targetElement,completeFn) {
	$("#"+formElement).ajaxForm({
		//target: '#' + targetElement,
		beforeSubmit: function() {
			jqueryDialogAPI.close();
			jqueryDialogAPI.reset();
			$('#' + targetElement).block({
				message: '<h3 class="loading-message"><div id="loading-image"></div>Loading data ...</h3>'
			});
		},
		error: function() { alert("Error talking to server"); },
		success: function(scriptOutput) { $('#' + targetElement).html(scriptOutput);},
		complete: function() {
			$('#' + targetElement).unblock();
			if(typeof completeFn == "function") { completeFn(); }
			jqueryHandlers.execute();
		}
	});
}

//$(window).load(function(){ jqueryHandlers.execute() });
$(document).ready(function(){ jqueryHandlers.execute() });