// phone number vars
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

// frm to english mapping
var english_map = { 'cc_number' : 'credit card number' };

function empty(v) {
	return !v || v == null || trim(v) == "" ? true : false;
}

function to_english(v) {
	return english_map[v] ? english_map[v] : v.replace("_", " ");
}

function check_required(frm, required_fields) {
	//alert(required_fields);
	msgs = new Array();
	
	for(x = 0; x < required_fields.length; x++) {
		if(empty(frm.elements[required_fields[x]].value)) {
			msgs[msgs.length] = 'Please enter your ' + to_english(required_fields[x]) + '.';
			highlight(frm.elements[required_fields[x]]);
		} else
			reset_box(frm.elements[required_fields[x]]);
	}
	
	return msgs;
}

function show_form_error(msgs) {
	text = '';
	for(x = 0; x < msgs.length; x++)
		text += '<li>' + msgs[x] + '</li>';
	
	custom_alert('There were problems with your submission:<ul>' + text + '</ul>');
	
	return false;
}

function highlight(ptr) {
	$(ptr).addClassName('highlight');
}

function reset_box(ptr) {
	$(ptr).removeClassName('highlight');
}

function isnum(x) {
	var RegExp = /^(-)?(\d*)(\.?)(\d*)$/;
	var result = x.match(RegExp);
	return result;
}

// trims a string of its leading and trailing whitespaces
function trim(strText) {
	// this will get rid of leading spaces
	while (strText.substring(0,1) == ' ')
	strText = strText.substring(1, strText.length);

	// this will get rid of trailing spaces
	while (strText.substring(strText.length-1,strText.length) == ' ')
		strText = strText.substring(0, strText.length-1);

	return strText;
}

function strip_chars_in_bag(s, bag) {
	var i;
	var returnString = "";

	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++) {   
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}

	return returnString;
}

function check_international_phone(strPhone){
	s=strip_chars_in_bag(strPhone, validWorldPhoneChars);
	return (isnum(s) && s.length >= minDigitsInIPhoneNumber);
}

function navigate_frame(url) {
	window.location.replace(url);
}	

function get_url_attributes(frm, id) {
	t 	= '';
	
	for(x = 0; x < frm.elements.length; x++) {
		e = frm.elements[x];
		if(e.type == 'select-one' && e.name.indexOf('attribute') > -1) {
			t += 'attribute[' + x + ']=' + e.options[e.selectedIndex].value + '&';
		}
	}
	
	return t;
}

function purchase_gift_certificate(frm) {		
	f = function(o) {
		alert(o.responseText);
		xmlDoc 		= create_xml_doc(o.responseText);		
		page 		= xmlDoc.getElementsByTagName("xml");			
				
		error		= get_xml_value(page[0].getElementsByTagName("alert")[0]);	
		content		= get_xml_value(page[0].getElementsByTagName("content")[0]);	
		
		if(error)
			custom_alert(error);		
			
		if(content)
			$('gift_certicate_content').innerHTML = content;
	}
	
	msgs = check_required(frm, [ 'first_name', 'last_name', 'email', 'phone', 'address', 'city', 'state', 'zip', 'cc_number', 'amount' ]);
	
	if(msgs.length)
		return show_form_error(msgs);	
	
	if(!confirm('Process transaction?  Clicking \'OK\' will confirm and process your credit information.'))
		return;	
		
	fvars = $(frm).serialize() + 'j=' + ut();

	new Ajax.Request(gift_cert_processor_url, { 
		postBody: fvars,
		method: 'post', 
		onSuccess: f
	});		
}

function quick_cart_add(frm, callback) {
	f = function(o) {		
		if(callback)
			callback(o)
			
		custom_alert(o.responseText);
	}
	
	id 			= frm.pid.value;
	
	$('buyForm_' + String(id)).style.display = 'none';
	$('loaderCircle_' + String(id)).style.display = 'block';
	
	quantity	= frm.quantity.value;
	attributes 	= get_url_attributes(frm, id);
	
	var msgs = new Array();

	if(empty(quantity) || !isnum(quantity) || (isnum(quantity) && parseInt(quantity) <= 0) ) {
		msgs[msgs.length] = "Please enter a valid product quantity.";
		highlight(frm.quantity);
		$('loaderCircle_' + String(id)).style.display = 'none';
		$('buyForm_' + String(id)).style.display = 'block';
	} else
		reset_box(frm.quantity);
		
	if(msgs.length) {
		return show_form_error(msgs);	
		$('loaderCircle_' + String(id)).style.display = 'none';
		$('buyForm_' + String(id)).style.display = 'block';
	}
	
	fvars = attributes + '&' + store_flag + '=add_cart&pid=' + id + '&quantity=' + quantity + '&j=' + ut();
	
	new Ajax.Request(cart_quick_add_url, { 
		postBody: fvars,
		method: 'POST', 
		onSuccess: function(transport) {
		
			//alert(transport.responseText);
			//f();
			custom_alert(transport.responseText);
			//alert(transport.responseText);
		},
		onFailure: function(transport) {
			alert(transport.responseText);
		},
		onComplete: function(transport) {
			$('loaderCircle_' + String(id)).style.display = 'none';
			$('buyForm_' + String(id)).style.display = 'block';
		}
	});	
}	

function count_textarea(ptr, ml, i) {
	t = ptr.innerHTML ? ptr.innerHTML : ptr.value;	
	c = document.getElementById(i);	
	l = t.length;
	
	ptr.innerHTML 		= l >= ml ? ptr.innerHTML.substring(0, ml) : ptr.innerHTML;
	ptr.value 			= l >= ml ? ptr.value.substring(0, ml) : ptr.value;		
	
	c.innerHTML 		= l > 0 ? l + ' characters' : '';
	
	c.style.color 		= l >= ml ? 'red' : '';
	c.style.fontWeight 	= l >= ml ? 'bold' : '';

	return true;
}

function cart_remove_all() {
	inputs = document.getElementsByTagName('input');
	
	for(x = 0; x < inputs.length; x++) {
		e = inputs[x];
		
		if(e.type == 'checkbox' && e.name.indexOf('remove') > -1)
			e.checked = e.checked ? false : true;
	}
}
/*
function populate_billing_address(ptr) {		
	if(empty(ptr.address.value) || empty(ptr.city.value) || empty(ptr.zip.value) || empty(ptr.state.value))
		custom_alert('You must first fully fill out your shipping information.');
	else {
		ptr.billing_address.value = ptr.address.value;
		ptr.billing_city.value = ptr.city.value;
		ptr.billing_zip.value = ptr.zip.value;
		ptr.billing_state.value = ptr.state.value;
		ptr.billing_country.selectedIndex = ptr.country.selectedIndex;
	}
}
*/
function validate_buy_form(ptr, action) {
	var msgs = new Array();

	if(empty(ptr.quantity.value) || !isnum(ptr.quantity.value) || (isnum(ptr.quantity.value) && parseInt(ptr.quantity.value) <= 0) ) {
		msgs[msgs.length] = "Please enter a valid product quantity.";
		highlight(ptr.quantity);
	} else
		reset_box(ptr.quantity);
		
	if(msgs.length)
		return show_form_error(msgs);	
	
	ptr.sview.value = action;

	ptr.submit();
}

function validate_cart_form(ptr) {
	var msgs = new Array();

	count = ptr.elements.length;
	for (x = 0; x < count; x++) {
		if(ptr.elements[x].type == "text" && ptr.elements[x].id != "promo") {
			k = ptr.elements[x].value.replace(/^\s+|\s+$/g,"");
			if(empty(k) || !isnum(k)) {
				msgs[msgs.length] = "Please enter a valid product quantity.";
				highlight(ptr.elements[x]);
			} else
				reset_box(ptr.elements[x]);
		}
	}
	
	if(msgs.length)
		return show_form_error(msgs);	
	
	ptr.submit();
}

function validate_login_form(ptr) {
	msgs = check_required(ptr, [ "store_username", "store_password" ]);	

	if(msgs.length)
		return show_form_error(msgs);
	
	ptr.submit();
}

function validate_register_form(ptr) {
	//'username'
	//msgs = check_required(ptr, [ 'fname', 'lname', 'address', 'city', 'state', 'zip', 'billing_address', 'billing_city', 'billing_state', 'billing_zip' ]);
	msgs = check_required(ptr, [ 'fname', 'lname', 'billing_address', 'billing_city', 'billing_state', 'billing_zip' ]);
	
	update = ptr.sview.value == 'update_customer_go' ? true : false;
	
	//if (!update) {
	//	check_required(ptr, ['password']);
	//}
	
	if(!update && empty(ptr.password_conf.value)) {
		msgs[msgs.length] = "Please enter your a password.";
		highlight(ptr.password_conf);
	} else {
		// ensure the address is properly formed
		if (ptr.password_conf.value != ptr.password.value) {
			msgs[msgs.length] = "Please ensure your supplied passwords match.";
			highlight(ptr.password_conf);
		} else
			reset_box(ptr.password_conf);
	}
		
	if(empty(ptr.phone.value)) {
		msgs[msgs.length] = "Please enter your phone number.";
		highlight(ptr.phone);
	} else {
		if(check_international_phone(ptr.phone.value) == false) {
			msgs[msgs.length] = "Please enter a valid phone number.";
			highlight(ptr.phone);
		} else
			reset_box(ptr.phone);
	}
	
	// email address
	if(empty(ptr.email.value)) {
		msgs[msgs.length] = "Please enter your email address.";
		highlight(ptr.email);
	} else {		
		// ensure the address is properly formed
		if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(ptr.email.value)==false) {
			msgs[msgs.length] = "Please enter a valid email address.";
			highlight(ptr.email);
		} else 
			reset_box(ptr.email);
	}

	if(msgs.length)
		return show_form_error(msgs);	

	ptr.submit();
}

function validate_lost_password_form(ptr) {
	msgs = new Array();
	
	// email address
	if(empty(ptr.email.value)) {
		msgs[msgs.length] = "Please enter your email address.";
		highlight(ptr.email);
	} else {		
		// ensure the address is properly formed
		if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(ptr.email.value)==false) {
			msgs[msgs.length] = "Please enter a valid email address.";
			highlight(ptr.email);
		} else 
			reset_box(ptr.email);
	}

	if(msgs.length)
		return show_form_error(msgs);	
	
	ptr.submit();
}

function toggleProductDisplay(theContainer) {
	if ($(theContainer + '_inner').style.display != 'none') {
		$(theContainer).removeClassName('active');
		new Effect.Fade($(theContainer + '_inner'), { from: 1.0, to: 0.0, duration: .5 });
	} else {
		$(theContainer).addClassName('active');
		new Effect.Appear($(theContainer + '_inner'), { from: 0.0, to: 1.0, duration: .5 });
	}
}

function ut() {
	var foo = new Date;
	var unixtime_ms = foo.getTime();
	var unixtime = parseInt(unixtime_ms / 1000); 
	return unixtime;
}

/*function custom_alert(msg) {
	s = document.viewport.getScrollOffsets();
	p = document.viewport.getDimensions(); 
	
	d = $('custom_alert');
	
	if(!d) {
		d = $(document.createElement('div'));
		d.addClassName('custom_alert');
		d.setAttribute('id', 'custom_alert');
		document.body.appendChild(d);
	}	
	
	d.innerHTML = msg;
	
	d.setStyle({
		left: 	(s.left + (p.width - d.getWidth()) / 2) + "px",
		top: 	(s.top + (p.height - d.getHeight()) / 2) + "px"
	});
	
	d.hide();
	Effect.Appear(d);
	setTimeout('Effect.Fade(\'custom_alert\')', 3000);
}*/

function setShippingHiddenDisplayOptions(theSenderValue) {
	if ( $('shipping_method_inner_' + theSenderValue).style.display == 'none') {
		var shippingMethodInnerOptions = $$('.shipping_method_inner');
		
		for (i = 0; i < shippingMethodInnerOptions.length; i++) {
			if ('shipping_method_inner_' + theSenderValue != shippingMethodInnerOptions[i].id) {
				new Effect.Fade(shippingMethodInnerOptions[i], { duration: .3, from: 1.0, to: 0.0 });
			}
		}
		new Effect.Appear($('shipping_method_inner_' + theSenderValue), { duration: .3, from: 0.0, to: 1.0 });
	}
}

function show_product_attributes(product_id) {
	if (($F('product_attributes_' + product_id + '_is_scaling') != "yes") && ($F('product_attributes_' + product_id + '_is_out') != "yes")) {
		$('product_attributes_' + product_id + '_container').style.display = 'block';
		$('product_attributes_' + product_id + '_is_scaling').value = 'yes';	
		new Effect.Move($('product_attributes_' + product_id), {
			duration: .3,
			x: 140, 
			transition: Effect.Transitions.sinoidal,
			afterFinish: function() {
				$('product_attributes_' + product_id + '_is_out').value = 'yes';
				$('product_attributes_' + product_id + '_is_scaling').value = 'no';
			}
		});
	} else if (!$F('product_attributes_' + product_id + '_is_scaling') != "yes")
		hide_product_attributes(product_id);
}

function hide_product_attributes(product_id) {
	//new Effect.BlindLeftStore($('product_attributes_' + product_id), {duration: .5});
	if ($F('product_attributes_' + product_id + '_is_scaling') != "yes") {
		$('product_attributes_' + product_id + '_is_scaling').value = 'yes';
		new Effect.Move($('product_attributes_' + product_id), {
			duration: .3,
			x: -140, 
			transition: Effect.Transitions.sinoidal,
			afterFinish: function() {
				$('product_attributes_' + product_id + '_is_out').value = 'no';
				$('product_attributes_' + product_id + '_is_scaling').value = 'no';
				$('product_attributes_' + product_id + '_container').style.display = 'none';
			}
		});
	}
}

function check_quick_buy_form(product_id) {
	var is_good = true;
	
	var inputs = $$('#quick_buy_' + String(product_id) + ' .quick_buy_input');
	//alert(inputs.length);
	
	return is_good;
}

function product_buy_now(product_id) {
	//alert(product_id);
	if (check_quick_buy_form(product_id)) {
		$('quick_buy_' + String(product_id)).submit();
	} else {
		show_product_attributes(product_id);
	}
}

function form_has_element_named(form_id, check_name) {
	var doesIt = -1;
	
	var formElements = $(form_id).getElements();
	for (var i = 0; i < formElements.length && doesIt == -1; i++)
		if (formElements[i].name == check_name)
			doesIt = i;
	
	return doesIt;
}

function attach_attributes_to_form(form_id) {
	var attributes = $$('.attribute');
	var newElements = new Array();
	var formElements = $(form_id).getElements();
			
	for (var i = 0; i < attributes.length; i++) {
		var currentIndex = form_has_element_named(form_id, attributes[i].name);
		
		if (currentIndex == -1) {
			newElements[newElements.length] 			= document.createElement('input');
			newElements[newElements.length - 1].name 	= attributes[i].name;
			newElements[newElements.length - 1].value 	= attributes[i].value;
			newElements[newElements.length - 1].type 	= 'hidden';
			
			$(form_id).appendChild(newElements[newElements.length - 1]);
		} else {
			formElements[currentIndex].value = attributes[i].value;
		}
	}
}

function submit_buy_now_form() {
	attach_attributes_to_form('buy_now_product_info');
	
	/*var debugElements = $('buy_now_product_info').getElements();
	for (var i = 0; i < debugElements.length; i++)
		alert(debugElements[i].name + " => " + $F(debugElements[i]));*/
	
	$('buy_now_product_info').submit();
}

function submit_add_to_cart_form() {
	attach_attributes_to_form('add_to_cart_product_info');
	
	/*var debugElements = $('add_to_cart_product_info').getElements();
	for (var i = 0; i < debugElements.length; i++)
		alert(debugElements[i].name + " => " + $F(debugElements[i]));*/
	//found in the product info template
	if(verify_add_to_cart_form()) {
		//alert(verify_add_to_cart_form());
		$('add_to_cart_product_info').submit();
	} else {
		return false;
	}
}

function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : '';
}