// form focus function
function setFocus(fieldid)
{	
	document.getElementById(''+ fieldid +'').focus();
}

//required options check
function checkRequired() {
		
	var i = 0;
	var i2 = 0;
	var failure = true;
	titleArray = new Array();
	
	var titleText = '';
	
	if (!document.getElementById('adjustment[0]')) {
		failure = false;
	}
	else {
		var failure1 = false;
		while (document.getElementById('adjustment['+i+']'))
		{
			var required = document.getElementById('adjustment['+i+'][required]');
			if (required.value == 1) {
				var opt = document.getElementById('adjustment['+i+']');
				if  (opt.options[opt.selectedIndex].value <= 0) {
					failure1 = true;
					titleArray[i2] = document.getElementById('adjustment-name['+i+']').innerHTML;
					i2++;
				}
			}
			i++;
		}
		
		for(i=0; i < titleArray.length; i++) {
			titleText += titleArray[i] + '\n';
		}
		
		failure = failure1;
	}
	
	if (failure === true) {
		alert('You must select a value for the following options:\n\n' + titleText + '\nPlease make a selection and try your order again.');
		return false;
	}
	return true;
	
}

//dynamic JS detail page price change
function changePrice(totalAdj, origPrice) {
		
	var i;
	var re = new RegExp(/\((\+|\-)\$\d+\.\d+\)/);
	var newPrice = origPrice;
	var actualPrice = document.getElementById('net_value').innerHTML
	
	if (newPrice != actualPrice) {
		newPrice = actualPrice;
	}
	
	for (i=0; i<(totalAdj); i++) {
		var adj = document.getElementById('adjustment['+i+']');
		var reValue = re.exec(adj.options[adj.selectedIndex].text);
		
		if(reValue) {
			var value = reValue[0].substring(1, (reValue[0].length - 1));
			var valArray = value.split('$');
			newPrice = eval(newPrice + valArray[0] + valArray[1]);
		}
	}
	
	newPrice = parseFloat(newPrice);
	document.getElementById('net_value').innerHTML = newPrice.toFixed(2);
	if (newPrice != actualPrice) {
		Effect.Grow('net_value');
	}
}

// subfunction for adjust price to add dollar signs to the given price
function addDollarSign(price) {
	
	price = price + '';
	if (price.indexOf('-') == 0) {
		 return price = '-$' + eval(price.substring(1)).toFixed(2);
	} else {
		return price = '+$' + eval(price).toFixed(2);
	}
	
}

//adjusts price of the product as well as all relevant price adjustments
function adjustPrice(totalAdj, origPrice, curAdj) {
	
	var i;
	var re = new RegExp(/\((\+|\-)\$\d+\.\d+\)/);
	
	changePrice(totalAdj, origPrice);
	
	var adj = document.getElementById('adjustment['+curAdj+']');
	
	var selOptText = adj.options[adj.selectedIndex].text;
	var reSelValue = re.exec(selOptText);
	if (reSelValue) {
		var selValue = reSelValue[0].substring(1, (reSelValue[0].length - 1));
	} else {
		var selValue = '';
	}
	var selValArray = selValue.split('$');
	if (selValArray[0] && selValArray[1]) {
		var selPrice = eval(selValArray[0] + selValArray[1]).toFixed(2);
	} else {
		var selPrice = '';
	}
	
	for (i=0; i<(eval(adj.options.length)); i++) {
		
		var optText = adj.options[i].text;
		var reValue = re.exec(optText);
		var optTitle = '';
		if (reValue && (selOptText != optText)) {
			optTitle = optText.substr(0, (optText.length - reValue[0].length));
			
			var value = reValue[0].substring(1, (reValue[0].length - 1));
			var valArray = value.split('$');
			var oldOptPrice = valArray[0] + valArray[1];
			
			newOptPrice = (eval(oldOptPrice) - selPrice).toFixed(2);
			
			if (eval(newOptPrice) != 0) {
				newOptPrice = addDollarSign(newOptPrice);
				adj.options[i].text = optTitle + ' (' + newOptPrice + ')';
			}
			else {
				adj.options[i].text = optTitle;
			}
				
		} else if (reValue && (selOptText == optText)) {
			
			optTitle = optText.substr(0, (optText.length - reValue[0].length));
			adj.options[i].text = optTitle;
			
		} else if (!reValue && (selOptText != optText) && (reValue != reSelValue)) {
			newOptPrice = eval(0 - selPrice).toFixed(2);
			newOptPrice = addDollarSign(newOptPrice);
			adj.options[i].text = optText + ' (' + newOptPrice + ')';
		
		} else if (selValue != '' && selPrice != '') {
			
			adj.options[i].text = optText + ' (+$0.00)';
		
		}  else {
			adj.options[i].text = optText;
		
		} 
		
	}
	
}

function echeck(str, fieldtitle) {
	
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    if (!re.test(str)) {
		alert("You entered an invalid email in the \""+fieldtitle+"\" field.")
		return false
    }

	return true					
}

/////////////////// Credit Card Validation Functions
/////////////////////////////////////////////////////////
var validate_card_number_field = 'cc_number';
var validate_card_month_field = 'cc_expmonth';
var validate_card_year_field = 'cc_expyear';
var validate_card_ccv_field = 'ccid_number';
var validate_card_display_field = 'validate_card_display';
var validate_card_error_preface = '<strong>Credit card problem:</strong><br />';
var validate_card_success_preface = 'Card type: ';

Event.observe(window, 'load', validate_card_init, false);

function validate_card_init(){
	if ($(validate_card_number_field) != null) {
		Event.observe(validate_card_number_field, 'blur', validate_card_check, false);
		Event.observe(validate_card_month_field, 'blur', validate_card_check, false);
		Event.observe(validate_card_year_field, 'blur', validate_card_check, false);
		Event.observe(validate_card_ccv_field, 'blur', validate_card_check, false);
	} else {
		//alert(validate_card_number_field+' not found on this page');
	}
}

function validate_card_check(){
	if ($F(validate_card_number_field) == '') {
		return;
	}
	
	var url = '/cart/validate_card.php';
	var pars = 'ccn='+escape($F(validate_card_number_field))+'&ccm='+escape($F(validate_card_month_field))+'&ccy='+escape($F(validate_card_year_field))+'&ccv='+escape($F(validate_card_ccv_field))+'&ep='+validate_card_error_preface+'&sp='+validate_card_success_preface;
	
	var myAjax = new Ajax.Updater({}, url, {method: 'get', parameters: pars, onSuccess: validate_card_display});
}

function validate_card_display(originalRequest) {
	var d = $(validate_card_display_field);
	var n = $(validate_card_number_field);
	var m = $(validate_card_month_field);
	var y = $(validate_card_year_field);
	var v = $(validate_card_ccv_field);
	var display = originalRequest.responseText;
	if (display.length > 0) {
		d.innerHTML = display;
		if (display.substring(0, validate_card_error_preface.length) == validate_card_error_preface) {
			
			if (display.indexOf('Card has expired') > 0) {
				m.style.backgroundColor = '#FFE8E6';
				y.style.backgroundColor = '#FFE8E6';
				n.style.backgroundColor = '';
				v.style.backgroundColor = '';
				d.style.color = 'red';
			} else if (display.indexOf('Security Code') > 0) {
				m.style.backgroundColor = '';
				y.style.backgroundColor = '';
				n.style.backgroundColor = '';
				v.style.backgroundColor = '#FFE8E6';
				d.style.color = 'red';
			} else {
				n.style.backgroundColor = '#FFE8E6';
				d.style.color = 'red';
			}
		} else {
			n.style.backgroundColor = '';
			m.style.backgroundColor = '';
			y.style.backgroundColor = '';
			v.style.backgroundColor = '';
			d.style.color = 'green';
		}
		Event.observe(validate_card_number_field, 'keyup', validate_card_display_normal, false);
	}
}

function validate_card_display_normal() {
	var d = $(validate_card_display_field);
	var n = $(validate_card_number_field);
	d.innerHTML = '&nbsp;';
	n.style.color = '';
	Event.stopObserving(validate_card_number_field, 'keyup', validate_card_display_normal, false);
}
/////////////////////// End Credit Card Validation Functions
////////////////////////////////////////////////////////////////

/////////////////// Send This Product to a Friend Functions
/////////////////////////////////////////////////////////
function sendProductToFriend() { 
	var validform = new Validation('product-send-form', {onSubmit : false});
	if (validform.validate() && jcap('product-send-error')) {
		sendProductEmail();
	}
}

function sendProductEmail() {	
	var url = '/tools/emailproduct_process.php';
	var pars = Form.serialize('product-send-form');
	myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onSuccess: processResult,
 onFailure :  function(resp) {alert("There was an error sending your message.  Please try again.");}})
 
}

function processResult(resp) {
	var productid = $('product-send-productid').value;
	if (resp.responseText.indexOf('<p><strong>There was a problem sending the message.</strong></p>') >= 0) {
		Element.update('error-container', resp.responseText);
	} else {
		Modalbox.show('Sending status', '/tools/emailproduct.php?view=modalbox&id=' + productid + '&response=' + resp.responseText, {width: 460, height:220}); 
	}
}
/////////////////////// End Send This Product to a Friend Functions
////////////////////////////////////////////////////////////////