function confirmLink(theQuestion,theLink)
{
	if (confirm('Are you sure you want to ' + theQuestion))
	{
		theLink.href += (theLink.href.charAt(theLink.href.length) != '/') ? '/' : '';
		theLink.href += 'true';
		return true;
	}
	else {
		return false;
	}
}

function addItemtoCart(product_variation_id, quantity, purchase_form_id)
{
	url = '/shoppingcart/additem/';
	
	if (product_variation_id && quantity)
	{
		url += product_variation_id + '/' + quantity;
		
		new Ajax.Updater ('message', url, {
							onComplete: function(transport){
								var response = $('additemResponse').value;
								
								if (response.match(/ok/))
								{
								  setTimeout("location.replace('/shoppingcart/')",0000);
								}
							}
						});
	}
	else
	{

		new Ajax.Updater ('message', url, {
							method: 'post',
							parameters: Form.serialize('purchase_product' + (purchase_form_id ? '_' + purchase_form_id : '')),
							onComplete: function(transport){									
								var response = $('additemResponse').value;
								if (response.match(/ok/))
								{
								  setTimeout("location.replace('/shoppingcart/')",0000);
								}
				  			}
						});
	}
}

function addItemtoCart2(product_id, quantity, purchase_form_id)
{
	url = '/shoppingcart/additem/';
	
	if (product_id && quantity)
	{
		url += product_id + '/' + quantity;
		
		new Ajax.Updater ('message', url, {
							onComplete: function(transport){
								var response = $('additemResponse').value;
								
								if (response.match(/ok/))
								{
								  setTimeout("location.replace('/shoppingcart/')",0000);
								}
							}
						});
	}
	else
	{

		new Ajax.Updater ('message', url, {
							method: 'post',
							parameters: Form.serialize('purchase_product_2' + (purchase_form_id ? '_' + purchase_form_id : '')),
							
							onComplete: function(){															
								
								var response = $('additemResponse').value;															
								
								if (response.match(/ok/))
								{
								  setTimeout("location.replace('/shoppingcart/')",0000);
								}
				  			}
						});
	}
}

function updateShoppingCart()
{
	new Ajax.Updater ('divShoppingCart', '/shoppingcart/update',
					  	{
							method: 'post',
							parameters: Form.serialize('shopping_cart_form'),
							evalScripts: true
						}
					);
}

var infoFields = {
			0: {
				"billing": "orderbillingname",
				"shipping": "ordershippingname",
				"required": 0
			},
			1: {
				"billing": "orderbillingaddress1",
				"shipping": "ordershippingaddress1",
				"required": 1
			},
			2: {
				"billing": "orderbillingaddress2",
				"shipping": "ordershippingaddress2",
				"required": 0
			},
			3: {
				"billing": "orderbillingcity",
				"shipping": "ordershippingcity",
				"required": 1
			},
			4: {
				"billing": "orderbillingstateid",
				"shipping": "ordershippingstateid",
				"required": 0
			},
			5: {
				"billing": "orderbillingzipcode",
				"shipping": "ordershippingzipcode",
				"required": 1
			},
			6: {
				"billing": "orderbillingphone",
				"shipping": "ordershippingphone",
				"required": 1
			},
			7: {
				"billing": "orderbillingcompany",
				"shipping": "ordershippingcompany",
				"required": 1
			},
			8: {
				"billing": "orderbillingcountry",
				"shipping": "ordershippingcountry",
				"required": 1
			},
			9: {
				"billing": "orderbillingintlstate",
				"shipping": "ordershippingintlstate",
				"required": 0
			},
			10: {
				"billing": "orderbillingintlzipcode",
				"shipping": "ordershippingintlzipcode",
				"required": 0
			},
			11: {
				"billing": "orderbillingnickname",
				"shipping": "ordershippingnickname",
				"required": 0
			},
            12: {
				"billing": "order_billing_customer_address_id",
				"shipping": "order_shipping_customer_address_id",
				"required": 0
			}
		}
			
function sameasbilling(dontchangestatus){
	var args = $A(arguments);
	var getShipping;

	if (args.length == 2){
		getShipping = args[1];
	}else{
		getShipping = true;
	}
	
	for (var field in infoFields){
		var shippingfield = $(infoFields[field]['shipping']);
		var billingfield = $(infoFields[field]['billing']);
		if ($('same_as_billing').value == 0 || dontchangestatus == true){
			if (billingfield.type && billingfield.type == "text"){
				$(infoFields[field]['shipping']).value = $(infoFields[field]['billing']).value;

                $(infoFields[field]['billing']).observe('change', function(event){
                                                              isSameAsShipping(this);
                                                             });
				/*$(infoFields[field]['billing']).onchange = function () {
                                                                isSameAsShipping(this);
                                                            };*/
			}else if (billingfield.type && billingfield.type == "select-one"){
				shippingfield.selectedIndex = billingfield.selectedIndex;
				/*$(infoFields[field]['billing']).onchange = function () {*/
                $(infoFields[field]['billing']).observe('change', function(event){
                                                                isSameAsShipping(this);
                                                                show_hide_intl('orderbilling');
                                                                show_hide_intl('ordershipping');
                                                            });
			}
            
			if (dontchangestatus == false){
				deactivate(shippingfield);
            }
		} else {
			if (dontchangestatus == false){
				activate(shippingfield);
            }
		}
	}
	
	show_hide_intl('ordershipping');
		
	if (dontchangestatus == false){
		if ($('same_as_billing').value == 0){
            $('same_as_billing').value = 1;
        }else if ($('same_as_billing').value == 1){
			$('same_as_billing').value = 0;
        }
	}
	
	if (getShipping){
		updateShipping();
	}
}

function isSameAsShipping(){
	if ($('same_as_billing').value==1){
		sameasbilling(true);
    }
}

function disableAllFields()
{
	for (var field in infoFields)
	{
		deactivate($(infoFields[field]['shipping']));
		deactivate($(infoFields[field]['billing']));
	}
}

function enableAllFields(){
	for (var field in infoFields)
	{
		if ($('same_as_billing').value==0){
			activate($(infoFields[field]['shipping']));
        }
		activate($(infoFields[field]['billing']));
	}
}

function deactivate(field){
	field.style.background = '#EEE';
	field.readOnly = true;
}
function activate(field){
	field.style.background = '#FFF';
	field.readOnly = false;
}
function updateShipping()
{
	var data = '';
	for (var field in infoFields)
	{	
		if ($(infoFields[field]['shipping']))
		{
			if ($(infoFields[field]['shipping']).value != '')
			{
				data += '&' + $(infoFields[field]['shipping']).name.substring($(infoFields[field]['shipping']).name.lastIndexOf('[')+1,$(infoFields[field]['shipping']).name.length-1) + '=' + $(infoFields[field]['shipping']).value;
			}
			else
			{
				if ($(infoFields[field]['required']==1))
				{
					Element.update('shipping_method','Please correct your shipping information.');
					//$('checkout_button').disabled = true;
					//document.getElementByID('checkout_button').disabled = true;
					return;
				}
			}
		}
		else return;	
	}
	
	Element.update('shipping_method','Loading Shipping Options...');
	
	//updateCosts();
	
	new Ajax.Updater('shipping_method','/shoppingcart/get_shipping/',
					 {
						 onLoading: function(request)
						 {
							 Element.show('throbber');
							 disableAllFields();
						 },
						 onLoaded: function(request)
						 {
							 Element.hide('throbber');
							 enableAllFields();
						},
						method: 'post',
						evalScripts:true,
						parameters: Form.serialize('checkout')/*data*/,
						requestHeaders:['X-Update', 'shipping_selection']
					});
	//$('checkout_button').disabled = false;
	//document.getElementByID('checkout_button').disabled = false;
}
function updateCosts(theSelect)
{
	if (theSelect && typeof(theSelect) == 'object')
	{
		var service = theSelect.value;
		if (service != '')
		{
			//$('shipping_cost').value = money_format($('shipping_'+service).value);
			Element.update('shipping_cost', money_format($('shipping_' + service).value));
			$('shipping_cost_value').value = $('shipping_'+service).value;
			calculateTotal();
		}
	}
	else {
		
		if (theSelect && typeof(theSelect) == 'number' || typeof(theSelect) == 'string')
		{
			Element.update('shipping_cost', '$' + theSelect);
			$('shipping_cost_value').value = theSelect;
		}
		else {
			Element.update('shipping_cost','$0.00');
			$('shipping_cost_value').value = '0.00';
		}
		
		calculateTotal();
	}
}

var total = 0;
function calculateTotal(reset)
{
	var shippingCost = $('shipping_cost_value').value;

	shippingCost = shippingCost * 1;

	if (shippingCost >= 0)
		total = total+shippingCost;
	
	$('total_cost').innerHTML = money_format(total);
	//Element.update('total_cost',(total + shippingCost));
}

function money_format(num) {
	num = num.toString().replace("/\$|\,/g",'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}
/*
var onload = function() {
	if (document.getElementById('shipping_method'))
	{
		updateCosts(document.getElementById('shipping_method'));
	}
	else {
		if (document.getElementById('shipping_cost_value').value != '0.00')
		{
			updateCosts(document.getElementById('shipping_cost_value').value);
		}
		else {
			updateCosts();
		}
	} 
}
*/
function update_cart()
{
	new Ajax.Updater('container','/shoppingcart/checkout/',
					 {
						 onLoading: function(request)
						 {
							 Element.show('throbber');
							 disableAllFields();
						 },
						 onLoaded: function(request)
						 {
							 Element.hide('throbber');
							 enableAllFields();
						},
						method: 'post',
						evalScripts:true,
						parameters: Form.serialize('checkout').replace(/checkout=Checkout/, '')/*data*/,
						requestHeaders:['X-Update', 'shipping_selection']
					});

}


/* product review */
/*
function RatingSystem ()
{
	this.ratingSpan = $('rating_stars');
	this.starImgs = new Array();
	
	this.starImage = new Image(16, 16);
	this.starImage.src = '/images/store/store_star_filled.png';

	this.bwStarImage = new Image(16, 16);
	this.bwStarImage.src = '/images/store/store_star_empty.png';

	this.loadEvents = function ()
	{
		for (var i = 0; i < this.ratingSpan.childNodes.length; i++)
		{
			var thisChild = this.ratingSpan.childNodes[i];

			if (thisChild.tagName && thisChild.tagName.toLowerCase() == 'img' && thisChild.className == 'rating_star')
			{
				this.starImgs[this.starImgs.length] = this.ratingSpan.childNodes[i];
			}
		}

		if (this.starImgs.length > 0)
		{
			for (star = 0; star < this.starImgs.length; star++)
			{
				this.starImgs[star].onclick = function () {
													var thisStar = parseInt(this.id.substring( this.id.indexOf('_')+1 ));
													setRating(thisStar);
												}

				this.starImgs[star].onmouseover = function () {
												var thisStar = parseInt(this.id.substring( this.id.indexOf('_')+1 ));
												showStars(thisStar);
												}

				this.starImgs[star].onmouseout = function () { clearStars(); }
			}
		}
	}


}

var myRatings = new RatingSystem;
myRatings.loadEvents();

function setRating (star)
{
	$('productreview_rating').value = parseInt(star);

}

function showStars (star)
{
	for (var x = 0; x < myRatings.starImgs.length; x++)
	{
		if (x < star)
		{
			myRatings.starImgs[x].src = myRatings.starImage.src;
		}
		else
		{
			myRatings.starImgs[x].src = myRatings.bwStarImage.src;
		}
	}
}

function clearStars ()
{
	var selected = parseInt($('productreview_rating').value);
	
	for (var x = myRatings.starImgs.length - 1; x >= 0; x--)
	{
		
		if (x < selected)
		{
			myRatings.starImgs[x].src = myRatings.starImage.src;
		}
		else
		{
			myRatings.starImgs[x].src = myRatings.bwStarImage.src;
		}
	}
}
*/
function submit_review (product_id)
{
	//var product_id = <?= !empty($this->data['Product']['id']) ? $this->data['Product']['id'] : 'false'; ?>	

	if (product_id)
	{
		new Ajax.Updater('review_container', '/productreviews/post/' + product_id ,
					{
						method: 'post',
						parameters: Form.serialize('write_review'),
						evalScripts: true
					});
	}
	else
	{
		alert ('Invalid product.');
	}
}

/* end product review */

//Shows + Hides international and domestic address entry data
function show_hide_intl(address_type){
	if($(address_type + 'country').value != 'us'){ //Hide domestic shipping form and bring out the international
		$$('.' + address_type + '_domestic').invoke('hide');
		$$('.' + address_type + '_international').invoke('show');
	}else{ //Hide international shipping form and bring out the domestic
		$$('.' + address_type + '_international').invoke('hide');
		$$('.' + address_type + '_domestic').invoke('show');
	}
}

function make_selection(element, selectedValue){
    if(Prototype.Browser.IE){
        if(selectedValue == null) {
            element.options[0].setAttribute('selected',true);
        } else {
            $A(element.options).each(
                    function(opt,count){
                        if(opt.value == selectedValue){
                            element.options[count].setAttribute('selected',true);
                        }
                    }
                );
        }
    }else{
        if(selectedValue == null) {
            element.selectedIndex = 0;
        } else {
            $A(element.options).each(
                    function(opt){ (opt.value == selectedValue ? opt.selected=true : ''); }
                );
        }
    }
}

function load_address(type,addressId){
    if(addressId.length==0){
        if($(type+"_address")){
            $$("#"+type+"_address input").each(function(e){
                e.value = "";
            });
            make_selection($("order"+type+"stateid"), 45);
            make_selection($("order"+type+"country"), "us");
        }
        return;
    }

    new Ajax.Request('/addresses/load_checkout/'+addressId, {
                                method:'get',
                                onSuccess: function(transport){
                                    var jsonAddr = transport.responseText.evalJSON(true);
                                    for(key in jsonAddr){
                                        if( $("order"+type+key) != undefined ){
                                            switch( $("order"+type+key).tagName.toLowerCase() ) {
                                                case 'select-one':
                                                case 'select':
                                                    make_selection($("order"+type+key), jsonAddr[key]);
                                                    break;
                                                case 'input':
                                                default:
                                                    $("order"+type+key).value = jsonAddr[key];
                                                    break;
                                            }
                                        }
                                    }
                                    show_hide_intl('ordershipping');
                                    show_hide_intl('orderbilling');
                                    isSameAsShipping();
                                }
                            });
    return;
}

function equal_column_height(eClass){
    if( eClass.match(/^\..*/) == null ){
        eClass = "."+eClass;
    }
    var columns = $$(eClass);
    var max_height = columns.invoke('getHeight').max();
    var min_height = columns.invoke('getHeight').min();
    if(max_height > min_height){
        columns.invoke('setStyle', {height: (max_height + 20) + 'px'});
    }
}

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
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) : null;
}
