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);
}

function focusDiv(divId)
{
	var focusDiv = document.getElementById(divId);
	var height = focusDiv.scrollHeight;
	window.scrollBy(0,height);
}


/*
<!-- 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 hideElement(elementId,elementLinkId) {
//	alert("ID: " + feedbackId);
	var id = document.getElementById(elementId);
	var linkId = document.getElementById(elementLinkId);
	$(function() {
		//var options = {};
		$(id).hide('slide');
		$(linkId).hide('slide');
		return false;
	});
}

// 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,loadingElement) {
	var clickId  = document.getElementById(clickElement);
	var targetId = document.getElementById(targetElement);
	
	var loadingId = targetId;
	if(loadingElement != null)
		loadingId = document.getElementById(loadingElement);
	
	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");
			//$.blockUI.defaults.overlayCSS.backgroundColor = 'red';
			//$.blockUI.defaults.overlayCSS.opacity = '0.0';
			//$.blockUI.defaults.showOverlay = false;
			//$.blockUI.defaults.allowBodyStretch = false;
			//$.blockUI.defaults.css.width = '100';
			$.blockUI.defaults.overlayCSS = {};
			$(loadingId).block({
				message: '<h3 class="loading-message"><div id="loading-image"></div>Loading data ...</h3>'
			});
			//alert("DS: " + dataString);
			$.ajax({
				url: urlString,
				data: dataString,
				dataType: "html",
				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) {
	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;
					$.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;
	
	if( typeof callbackFunction == "function" ) {
		$(entryFieldId).autocomplete({ 
			serviceUrl: urlString,
			minChars: minCharacters, 
//			delimiter: /(,|;)\s*/, 	// regex or character
//			maxHeight:400,
//			width:300,
			deferRequestBy: delay, 	//miliseconds
			params: parameters, 	//aditional parameters
			onSelect: callbackFunction
		});
	}
	else {
		$(entryFieldId).autocomplete({ 
			serviceUrl: urlString,
			minChars: minCharacters, 
			deferRequestBy: delay, 	//miliseconds
			params: parameters 	//aditional parameters
		});
	}
};


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