//////////////Basket Functions///////////////////////
function update_basket(name,price,itemid,add,t){
	if(basket_itemcount()>0){ //Basket has atleast 1 item
		return add? basket_additem(name,price,itemid,t):basket_removeitem(itemid);
	}else{ //Basket is currently empty	
		if(add){
			Element.Methods.remove(Element.firstDescendant($('basket')));
			return basket_additem(name,price,itemid,t);
		}
	}
}

function basket_itemcount(){
	return $('basket').select('.item').length;
}
function basket_additem(name,price,itemid,t){
	var item = document.createElement('p');
	item = $(item);
	item.addClassName("item");
	item.addClassName(t);
	item.id = itemid;
	item.setAttribute('price',price);
	item.appendChild(document.createTextNode(name+' ($'+price+')'));
		basket_total('remove'); //Delete old total
	$('basket').appendChild(item);
		basket_total('update');
	update_basket_height(); //Update basket height
}

function basket_removeitem(itemid){
	var item = Element.firstDescendant($('basket'));
	while(item){
		if(item.id == itemid){
			Element.Methods.remove(item); break;
		}
		item = item.nextSibling;
	}
	basket_total('update');
	if(!Element.firstDescendant($('basket'))){
		//Cart is empty, display message
		var node = document.createElement('p');
		node.appendChild(document.createTextNode('Select one or more services'));
		$('basket').appendChild(node);
	}
	update_basket_height(); //Update basket height
}

function basket_total(action){
	if(action == 'remove'){
		if($('basket_total')) Element.Methods.remove($('basket_total'));
	}else { //Add or Update total
		if(!$('basket_total')){
			var itemcount = basket_itemcount();
			if(itemcount > 0){
				var item = document.createElement('p');
				item.id = 'basket_total';
				item.appendChild(document.createElement('hr'));
				item.appendChild(document.createTextNode('Sub-Total: $'+basket_subtotal()));
				item.appendChild(document.createElement('br'));
				item.appendChild(document.createTextNode('Tax: $'+basket_tax()));
				item.appendChild(document.createElement('hr'));
				item.appendChild(document.createTextNode('Total: $'+basket_totalprice()+' ('+itemcount+' items)'));
				$('basket').appendChild(item);
			}
		}else{ //If total exists, remove it and then update it
			basket_total('remove');
			basket_total('update');
		}
	}
}

function basket_tax(){
	var rate = parseFloat($('gc_taxrate').value);
	var tax = rate * basket_subtotal();
	return tax.toFixed(2);
}

function basket_totalprice(){
	var total = parseFloat(basket_subtotal()) + parseFloat(basket_tax());
	return total.toFixed(2);
}

function basket_subtotal(){
	var item = Element.firstDescendant($('basket'));
	var total=0.0;
	while(item){
		item = $(item);
		if(item.hasClassName("item")){
			var price = parseFloat(item.getAttribute('price'));	
			if(!isNaN(price)) total += price;
		}
		item = item.nextSibling;
	}
	try{
		return total.toFixed(2);
	}catch(Error){
		return Math.round(total*100)/100;
	}
}

function basket_itemlist(t){
	if(null == t) t = 'service';
	var item = Element.firstDescendant($('basket'));
	var list = "";
	while(item){
		item = $(item);
		if(item.hasClassName("item") && item.hasClassName(t)) list += (list ? ',' : '') + item.id.replace(t + '-', '') ;
		item = item.nextSibling;
	}
	return list;
}

function update_basket_height(){
	$('basket').style.height = 'auto';
	if($('service-selector').offsetHeight >= $('basket').offsetHeight){
		$('basket').style.height = $('service-selector').offsetHeight + 'px';
	}else{
		$('basket').style.height = 'auto';
	}
}
/////////////////////////////////////////////////////
function design_preview(span){
	if($('gc_design_image')){
		$('gc_design_image').setAttribute('src',span.getAttribute('path'));
	}
	if($('gc_design_name')){
		$('gc_design_name').innerHTML = span.innerHTML;
	}
	
	//Remove all bold
	var designs = span.parentNode.getElementsByTagName('span');
	for(var i=0; i < designs.length ; i++)
		designs[i].style.fontWeight = '';

	//Set active to bold
	span.style.fontWeight='bold';
}

function cert_preview(prefix,salon_id) {
	var url = prefix + 'certificate/preview/?salon_id=' + salon_id + 
		'&image_id=' + selected_design_id() +
		'&to_display=' + encodeURIComponent($('to').value) +
		'&from_name=' + encodeURIComponent($('from').value) +
		'&note=' + encodeURIComponent($('message').value) +
		'&show_price=' + ($('showprice').checked? 1:0) +
		'&amount=';
		url += $('pick_service').checked? basket_totalprice():$('dollar_value').value;
		
		if($('pick_service').checked) {
			url += '&services=' + basket_itemlist('service');
			url += '&service_options=' + basket_itemlist('service-option');
		}

	window.open(url, 'cert_preview', 'height=750,width=975');
}
function selected_design_id(){
		// have to get the selected radio button by iteration
	var radios = $('cert_designs').getElementsByTagName('input');
	for (i=0;i<radios.length;i++) {
		if (radios[i].checked) {
			return radios[i].value;
		}
	}
	return 0;
}

function show_value_type()
{
	if ($('pick_dollar').checked){
		$('dollar_amount').show();
		$('service_amount').hide();
	}else if($('pick_service').checked){
		$('dollar_amount').hide();
		$('service_amount').show();
	}else{
		$('dollar_amount').hide();
		$('service_amount').hide();
	}
}
function show_delivery()
{
	//Email
	if ($('pick_email').checked){
		$('to_email_when').show();
	} else { 
	//No email (send it themselves)
		$('to_email_when').hide();
	}
}

function show_gift_design_cat(set)
{
	if('' == set) set = 0;
	// Show all, then hide the non-selected
	$$('#cert_designs .cert_design').invoke('show').
		reject(
			set 
			? function (elt) {return elt.id == 'design_' + set;}
			: function (elt, i) { return i == 0; }
		).invoke('hide');

		selectedOption = $A($('cert_design_cat').options).find( function (o) { return o.value == set } );
	if(selectedOption) $('cert_design_cat').selectedIndex = $A($('cert_design_cat').options).indexOf(selectedOption);
}

// elt is the calling link
// e.g. onclick show_description(this)
function show_description(elt){
	$(elt).next('.description').toggle();
}
function recipient_name()
{
	$('to').value = $('recipient_first').value + ' ' + $('recipient_last').value;
}

function show_submit(){
	//Enable submit buttom if they have a decent browser
	if(!document.getElementById || !document.createTextNode){ return; }
	$('btnsubmit').style.display = 'inline';	
}

function show_pick_dollar(){
	$('pick_dollar').checked = true;
}
function validate_fields(){
	clear_errors();
	
	//Insert a valid email?
	if($('pick_email').checked ==true){
		//Send via email
		if(!valid_email($('to_email').value)){
			show_error('to_email','Please specify a valid email address');
			return false;
		}
		//Valid send date?
		if(!valid_date($('email_when').value)){
			show_error('email_when','Please select a valid delivery date');
			return false;
		}
	}else if($('pick_print').checked == true){
		//Deliver themselves
	}else{
		show_error('delivery','Please select a method of delivery');
		return false;
	}
	
	//Money
	if($('pick_dollar').checked == true){
		//Entered a dollar amount
		if(!valid_amount($('dollar_value').value)){
			show_error('pick_dollar','Please enter a valid dollar amount in the specified range.');
			return false;
		}
	}else if($('pick_service').checked == true){
		//Selected some services
		if(basket_totalprice()==0 || basket_itemcount()==0){
			show_error('pick_service','Please select at least one service');
			return false;
		}else if(!valid_amount(basket_totalprice())){
			show_error('pick_service','Your basket total must be between $'+$('gc_min').value+' - $'+$('gc_max').value);
			return false;
		}
	}else{
		show_error('value','Please choose a dollar amount or service');
		return false;
	}
	
	//Pick a Design?
	if(selected_design_id() == 0){
		show_error('choose_design','Please choose a design');
		return false;
	}
	
	//Recipient First & Last
	if($('recipient_first').value.length == 0){
		show_error('recipient_first',"Please enter the recipient's first name");
		return false;
	}
	if($('recipient_last').value.length == 0){
		show_error('recipient_last',"Please enter the recipient's last name");
		return false;
	}
	
	//Display Names (To & From)
	if($('to').value.length == 0){
		show_error('to',"Please enter the recipient's display name");
		return false;
	}
	if($('from').value.length == 0){
		show_error('from',"Please enter the sender's display name");
		return false;
	}
	
	//Place DOM data into form elements
	/*if($('pick_service').checked){
		$('gc_items').value = basket_itemlist();
		$('gc_amount').value = basket_totalprice();
	}else {
		$('gc_amount').value=$('dollar_value').value;
	}*/
	
	//Disable submit button to prevent multiple submissions
	$('btnsubmit').disable();
	return true;
}


/*function select_radio(el){
	el.parentNode.parentNode.getElementsByTagName('input')[0].checked=true;
	highlight_cell(el); //IE Fix
}*/

/*function highlight_cell(content){
	var cell = content.parentNode.parentNode;
	var tables = document.getElementsByTagName('table');
	//Clear currently selected design
	for(var i=0; i<tables.length; i++){
		if(tables[i].className=="gift_cert_design_table"){
			var cells = tables[i].getElementsByTagName('td');
			for(var j=0; j<cells.length; j++){
				cells[j].style.backgroundColor = 'transparent';
			}
		}
	}
	//Select design
	cell.style.backgroundColor = 'yellow';
}*/

function highlight_cell_for_id(image_id) {
	$$('.cert_image_cell').invoke('removeClassName', 'highlighted_cell');
	$('cert_image_cell_' + image_id).addClassName('highlighted_cell');
}


/////////Salon functions////////////
function disable_certificate_inputs(){
	var inputs = document.getElementsByTagName('input');
	for(i in inputs)
		inputs[i].disabled = true;
	$('note').disabled = true;
}

function gc_toggle_services(){
	update_selected_services();
	if($('service_list').style.display == 'none'){
		$('service_list').style.display = 'block';
		$('amount').style.display = 'none';
		$('amount_span').style.display = 'inline';
		$('toggle').innerHTML = "Click Here to Enter a Price";
	}else{
		$('service_list').style.display = 'none';
		$('amount').style.display = 'inline';
		$('amount_span').style.display = 'none';
		$('toggle').innerHTML = "Click Here to Specify Services";
		
	}
}

function update_selected_services(){
	var inputs = document.getElementsByTagName('input');
	var total=0.00;
	for(i in inputs){
		if(inputs[i].type == 'checkbox' && inputs[i].name.substring(0,7)=="service" && inputs[i].checked == true)
			total += parseFloat(inputs[i].getAttribute('price'));
	}
	
	var tax = parseFloat($('gc_taxrate').value) * total;
	total += tax;
	$('amount').value = total.toFixed(2);
	$('amount_span').innerHTML = total.toFixed(2) + " (includes tax: $" + tax.toFixed(2) + ")";
}

function connectFields(field, check) {
	Event.observe(check, 'change', function () {
		$(field).disabled = $(check).checked;
	});
	$(field).disabled = $(check).checked;
}
