/**
 * to be run only when dom ready
 */
function pageLoaded()
{
	//console.log(order_data.order.location.ski_shop);
	setSelectSelectedIndexByValue( $('ski_shop'), order_data.order.location.ski_shop );
	$('extra_details').value = order_data.order.location.extra_details;

	saveLocation();
	selectPerson(0);
	savePerson();
	updatePartyView();
	validateCheckoutData();
	updateCartView();
}


//
// Product Functions
//
function addProduct(id_cat, id_type, id_prod)
{
	//window.alert("addProduct id_type = "+id_type);
	person_item_list = order_data['order']['person'][curr_person]['item_list'];

	// first check if the product is already in the customers list
	for (i=0; i<person_item_list.length; i++)
	{
		if (person_item_list[i].id_prod == id_prod)
		{
			return false;
		}
	}
	
	// is there a product from the same cat/type? then remove it
	for (i=0; i<person_item_list.length; i++)
	{
		if (person_item_list[i].id_cat == id_cat && person_item_list[i].id_type == id_type )
		{
			productSelected(id_cat, id_type, person_item_list[i].id_prod, false);
			person_item_list.splice(i,1);
			break;
		}
	}

	// Now we just add the product to the customers list in the data model
	// get the indices of the product
	idx_cat = catIndex(id_cat);
	idx_type = typeIndex(idx_cat,id_type);
	idx_prod = prodIndex(idx_cat,idx_type,id_prod);

	person_item_list.push( {
		"id_cat":id_cat, 
		"id_type":id_type, 
		"id_prod":id_prod,
		"prod_name":equipment_data[idx_cat]['type'][idx_type]['product'][idx_prod]['name'],
		"prod_price_normal":price_data[order_data['order']['person'][curr_person]['duration']][id_prod]['normal'],
		"prod_price_discount":price_data[order_data['order']['person'][curr_person]['duration']][id_prod]['discount']
	});
	
	productSelected(id_cat, id_type, id_prod, true);

	updateTotal();
	updateCartView();
	updatePartyView();
	validateCheckoutData();
}

function removeProduct(id_cat, id_type, id_prod, idx_person)
{
	person_item_list = order_data['order']['person'][idx_person]['item_list'];
	for (i=0; i<person_item_list.length; i++)
	{
		if (
			person_item_list[i].id_cat == id_cat && 
			person_item_list[i].id_type == id_type  && 
			person_item_list[i].id_prod == id_prod 
		)
		{
			productSelected(id_cat, id_type, id_prod, false);
			person_item_list.splice(i,1);
			break;
		}
	}
	updateTotal();
	updateCartView();
	updatePartyView();
	validateCheckoutData();
}

function productSelected(id_cat, id_type, id_prod, is_selected)
{
	try {
		if (is_selected)
		{
			$('prod_name_image_'+id_cat+"_"+id_type+"_"+id_prod).src = "/images/tick.png";
			$('prod_name_seltxt_'+id_cat+"_"+id_type+"_"+id_prod).innerHTML = ARRAY_lang['selected'];
		}
		else
		{
			$('prod_name_image_'+id_cat+"_"+id_type+"_"+id_prod).src = "/images/control_blank.png";
			$('prod_name_seltxt_'+id_cat+"_"+id_type+"_"+id_prod).innerHTML = ARRAY_lang['click_select'];
		}
	} catch (e) {
		//console.error(e);
	}
}



//
// Location Functions
//
function editLocation()
{
//	editing_location = true;
	
	// Change view to allow Editing the location details
	if ( $('location-pane').style.display != "block" )
	{
		$('location-pane').style.display = "block";
		document.getElementById('toggle_icon_location').src = "/images/control_eject_blue.png";
	}
	else
	{
		cancelEditLocation();
	}
}

function cancelEditLocation()
{
//	editing_location = false;
	
	// Change view to hide the persons details
	document.getElementById('location-pane').style.display = "none";
	document.getElementById('toggle_icon_location').src = "/images/control_eject_blue_flip.png";
	
	// Toggles to Party details
	togglePersonPane(true);	
}

function saveLocation()
{
	tmp_location = new Object();
	tmp_location['ski_shop'] = document.getElementById('ski_shop').options[document.getElementById('ski_shop').selectedIndex].value;
	tmp_location['extra_details'] = document.getElementById('extra_details').value;

	order_data['order']['location'] = tmp_location;

//	cancelEditLocation();
	validateCheckoutData();
}



//
// Person Functions
//
function addPerson()
{
	// Add the person to the data model	
	order_data['order']['person'].push( {"id":0, "name":"", "sex":"M", "date":order_data['order']['person'][0]['date'], "duration":6, "price_discount":0, "price_normal":0, "height":0, "weight":0, "boots":0, "skill":0, "item_list":[] });
	order_data['order']['num_people']++;

	editPerson(order_data['order']['person'].length-1);
	validateCheckoutData();
	updatePartyView();
	window.location.hash = "party";
}

function togglePersonPane(state)
{
	if (state != undefined && state != null)
	{
		// specifically open or close
		if (state)
		{
			// true = open
			document.getElementById('party-pane').style.display = "block";
			document.getElementById('toggle_icon_party').src = "/images/control_eject_blue.png";
		}
		else
		{
			// false = close
			document.getElementById('party-pane').style.display = "none";
			document.getElementById('toggle_icon_party').src = "/images/control_eject_blue_flip.png";
		}
	}
	else
	{
		// toggle it
		if ( document.getElementById('party-pane').style.display != "block" )
		{
			document.getElementById('party-pane').style.display = "block";
			document.getElementById('toggle_icon_party').src = "/images/control_eject_blue.png";
		}
		else
		{
			document.getElementById('party-pane').style.display = "none";
			document.getElementById('toggle_icon_party').src = "/images/control_eject_blue_flip.png";
		}
	}
}

function editPerson(id_person)
{
	if (id_person == undefined)
	{
		id_person = curr_person;
	}
	selectPerson(id_person);

	// Change view to allow Editing the persons details
	if ( $('party-pane').style.display != "block" )
	{
		$('party-pane').style.display = "block";
	}
//	else
//	{
//		cancelEditPerson();
//	}
}

function cancelEditPerson()
{
	// Change view to hide the persons details
	//$('party-pane').style.display = "none";
	togglePersonPane(false);
}

function savePerson()
{
//	alert("test");
	tmp_person = new Object();
	tmp_person['name'] = document.getElementById('name').value;
	tmp_person['sex'] = (document.getElementsByName('sex')[0].checked == true) ? "M" : "F";
	tmp_person['date'] = document.getElementById('date').value;
	tmp_person['duration'] = document.getElementById('duration').options[document.getElementById('duration').selectedIndex].value;
	tmp_person['height'] = document.getElementById('height').options[document.getElementById('height').selectedIndex].value;
	tmp_person['weight'] = document.getElementById('weight').options[document.getElementById('weight').selectedIndex].value;
	tmp_person['boots'] = document.getElementById('boots').options[document.getElementById('boots').selectedIndex].value;
	tmp_person['skill'] = document.getElementById('user_skill').options[document.getElementById('user_skill').selectedIndex].value;

	// Carry over the items and prices
	tmp_person['id'] = order_data['order']['person'][curr_person]['id'];
	tmp_person['item_list'] = order_data['order']['person'][curr_person]['item_list'];
	tmp_person['price_discount'] = order_data['order']['person'][curr_person]['price_discount'];
	tmp_person['price_normal'] = order_data['order']['person'][curr_person]['price_normal'];

	order_data['order']['person'][curr_person] = tmp_person;

	selectPerson(curr_person);
	validateCheckoutData();
}

function removePerson(id_person)
{
	if (window.confirm("Remove party member and their equipment?"))
	{
		// Remove the person from the data model
		order_data['order']['person'].splice(id_person,1);
		order_data['order']['num_people']--;
		curr_person = 0;

		selectPerson(curr_person);
		validateCheckoutData();
	}
}

function selectPerson(id_person)
{
	// Add the person to the data model
	old_person = curr_person;
	curr_person = id_person;

	tmp_person = order_data['order']['person'][id_person];
	member_name = tmp_person['name'] == (undefined || "") ? (ARRAY_lang['person']+" "+(id_person+1)) : tmp_person['name'];

	updateSelectedProducts();

	// Load the Person details into the fields...
	document.getElementById('name').value = tmp_person['name'];
	document.getElementsByName('sex')[(tmp_person['sex'] == "F" ? 1 : 0)].checked = true;
	if (tmp_person['date'] == undefined || tmp_person['date'] == "")
	{
		var today = new Date();
		today.setDate(today.getDate()+2);
		tmp_person['date'] = today.getFullYear()+"-"+(today.getMonth()+1)+"-"+today.getDate();
	}
	document.getElementById('date').value = tmp_person['date'];
	document.getElementById("date_required").value = tmp_person['date'].split('-').reverse().join("/")
	setSelectSelectedIndexByValue( document.getElementById('duration'), tmp_person['duration'] );
	setSelectSelectedIndexByValue( document.getElementById('height'), tmp_person['height'] );
	setSelectSelectedIndexByValue( document.getElementById('weight'), tmp_person['weight'] );
	setSelectSelectedIndexByValue( document.getElementById('boots'), tmp_person['boots'] );
	setSelectSelectedIndexByValue( document.getElementById('user_skill'), tmp_person['skill'] );

	// Change view to show the persons name
//	document.getElementById('view_party_head').innerHTML = '<img src="/images/exclamation.png" border="0" onclick="editPerson('+curr_person+')" class="addname" align="absmiddle" /><span onclick="editPerson('+curr_person+')" class="addname">&nbsp;'+ARRAY_lang['edit_personal_details']+member_name+'</span>';
//	document.getElementById('view_equipment_head').innerHTML = ARRAY_lang['select_equipment_for']+member_name;

	var new_duration = order_data['order']['person'][curr_person]['duration'];
	if ( curr_duration != new_duration )
	{
		curr_duration = order_data['order']['person'][curr_person]['duration'];

		if ( price_data[new_duration] == undefined )
		{
			getAllPrices( curr_duration );
		}
		else
		{
			updatePriceView();
			updateCartPrices();
		}
	}

//	validateCheckoutData();
	updateTotal();
	updateCartView();
	updatePartyView();
}



//
// Checkout functions
//
function validateCheckoutData()
{
	// test that the location fields are complete 
	// AND each persons fields are complete 
	// AND there is at least one product selected

	var location_complete = true;
	var persons_complete = true;
	var equipment_complete = true;
	
	var tmp_order = order_data.order;

	// Test location
	if ( !(parseInt(tmp_order.location.ski_shop) > 0) || tmp_order.location.extra_details == "" )
	{
		location_complete = false;
	}

	// Test customers details
	for(i=0; i<tmp_order.num_people; i++)
	{
		tmp_person = tmp_order.person[i];

		if (!checkPersonHasDetails(i))
		{
			persons_complete = false;
		}

		if (!checkPersonHasItems(i))
		{
			equipment_complete = false;
		}
	}

	requirements_text = "";

	if ( location_complete )
	{
		//requirements_text += '<img src="/images/tick.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_complete_location']+'</span><br/>';
		$("view_location_head").innerHTML = '<img src="/images/tick.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_complete_location']+'</span><br/>';
	}
	else
	{
		//requirements_text += '<img src="/images/exclamation.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_missing_location']+'</span><br/>';
		$("view_location_head").innerHTML = '<img src="/images/exclamation.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_missing_location']+'</span><br/>';
	}

	if ( persons_complete )
	{
		//requirements_text += '<img src="/images/tick.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_complete_people']+'</span><br/>';
		$("view_party_head").innerHTML = '<img src="/images/tick.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_complete_people']+'</span><br/>';
	}
	else
	{
		//requirements_text += '<img src="/images/exclamation.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_missing_people']+'</span><br/>';
		$("view_party_head").innerHTML = '<img src="/images/exclamation.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_missing_people']+'</span><br/>';
	}

	if ( equipment_complete )
	{
		//requirements_text += '<img src="/images/tick.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_complete_equipment']+'</span>';
		$("view_equipment_head").innerHTML = '<img src="/images/tick.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_complete_equipment']+'</span>';
	}
	else
	{
		//requirements_text += '<img src="/images/exclamation.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_missing_equipment']+'</span>';
		$("view_equipment_head").innerHTML = '<img src="/images/exclamation.png" border="0" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['reqd_missing_equipment']+'</span>';
	}

//	$("checkout_requirments").innerHTML = requirements_text;

//	var path_button_save_checkout = path_button_save_checkout || 'save_all_checkout';
//	var path_button_save_checkout_grey = path_button_save_checkout_grey || 'save_all_checkout_grey';

	if (
		location_complete && persons_complete && equipment_complete
	)
	{
		$("checkout_text").innerHTML = ARRAY_lang['checkout_button_complete']+"<br/><br/>";

		var tmp_html = '';
		tmp_html += '<form method="post" name="frm_checkout" id="frm_checkout" onsubmit="return checkCartValue();">';
		tmp_html += '<input id="order_data_field" type="hidden" value=\''+Object.toJSON(order_data)+'\' name="order_data_field"/>';
		tmp_html += '<input type="image" name="checkout" src="/catalog/includes/languages/'+lang_folder+'/images/buttons/'+path_button_checkout+'.png" value="checkout" />';
		tmp_html += '</form>';
		
		$("checkout_button").innerHTML = tmp_html;
		
		var tmp_html = '';
		tmp_html += '<img class="action_button" border="0" src="/catalog/includes/languages/'+lang_folder+'/images/buttons/'+path_button_save_checkout+'.png" onclick="document.getElementById(\'frm_checkout\').submit();" />';
		
		$("save_checkout_button").innerHTML = tmp_html;
	}
	else
	{
		$("checkout_text").innerHTML = ARRAY_lang['checkout_button_instr']+"<br/><br/>";

		var tmp_html = '';
		tmp_html += '<input id="order_data_field" type="hidden" value="" name="order_data_field"/>';
		tmp_html += '<img border="0" src="/catalog/includes/languages/'+lang_folder+'/images/buttons/'+path_button_checkout_grey+'.png"/>';

		$("checkout_button").innerHTML = tmp_html;
		
		var tmp_html = '';
		tmp_html += '<img class="action_button" border="0" src="/catalog/includes/languages/'+lang_folder+'/images/buttons/'+path_button_save_checkout_grey+'.png" />';
		
		$("save_checkout_button").innerHTML = tmp_html;
		
	}
}

function checkCartValue()
{
	// Check that the deposit amount is greater than 1
	if( (order_data['order']['price_discount'] * 0.2) > 1 )
	{
		return true;
	}
	else
	{
//		window.alert("Deposit must be greater than 1");
		return false;
	}
}

function checkPersonHasItems(id_person)
{
	if (order_data['order']['person'][id_person].item_list.length == 0)
	{
		//window.alert("products found");
		return false;
	}
	else
	{
		return true;
	}
}

function checkPersonHasDetails(id_person)
{
	if (
		!checkPersonHasSkill(id_person) ||
		!checkPersonHasName(id_person) 
	)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function checkPersonHasHeight(id_person)
{
	if ( parseInt(order_data['order']['person'][id_person].height) < 0 ) { return false; }else{ return true;}
}
function checkPersonHasWeight(id_person)
{
	if ( parseInt(order_data['order']['person'][id_person].weight) < 0 ) { return false; }else{ return true;}
}
function checkPersonHasBoots(id_person)
{
	if ( parseInt(order_data['order']['person'][id_person].boots) < 0 ) { return false; }else{ return true;}
}
function checkPersonHasSkill(id_person)
{
	if ( parseInt(order_data['order']['person'][id_person].skill) < 0 ) { return false; }else{ return true;}
}
function checkPersonHasName(id_person)
{
	if ( order_data['order']['person'][id_person].name == "" ) { return false; }else{ return true;}
}



//
// View Functions
//
function switchCat(new_cat)
{
	if ( new_cat != curr_cat )
	{
		// Update the selected tab
		$("cat_tab_"+curr_cat).removeClassName("selected");
		$("cat_tab_"+new_cat).addClassName("selected");
		
		// Update the displayed tab content
		$("cat_"+curr_cat).setStyle({display: "none"});
		$("cat_"+new_cat).setStyle({display: "block"});

		// Swap the old for the new
		curr_cat = new_cat;
	}
}



function switchType(new_type)
{
	//window.alert("curr_cat = "+curr_cat+"\n"+"new_type = "+new_type);

	if ( new_type != curr_cat_type[curr_cat] )
	{
		// Update the selected tab
		$("type_tab_"+curr_cat+"_"+curr_cat_type[curr_cat]).removeClassName("type_selected");
		$("type_tab_"+curr_cat+"_"+new_type).addClassName("type_selected");

		// Update the displayed tab content
		$("type_"+curr_cat+"_"+curr_cat_type[curr_cat]).setStyle({display: "none"});
		$("type_"+curr_cat+"_"+new_type).setStyle({display: "block"});

		// Swap the old for the new
		curr_cat_type[curr_cat] = new_type;
	}
}



function switchVariant( prod_id, dir )
{
	document.getElementById("var_"+prod_id+"_"+prod_variants[prod_id][curr_prod_variant[prod_id]]).style.display = "none";
	if( dir=="up" )
	{
		curr_prod_variant[prod_id] = (curr_prod_variant[prod_id]+1) >= prod_variants[prod_id].length ? 0 : curr_prod_variant[prod_id]+1;
	}
	else
	{
		curr_prod_variant[prod_id] = (curr_prod_variant[prod_id]-1) < 0 ? prod_variants[prod_id].length-1 : curr_prod_variant[prod_id]-1;
	}
	document.getElementById("var_"+prod_id+"_"+prod_variants[prod_id][curr_prod_variant[prod_id]]).style.display = "";
}



function updateCartView()
{
	cartview = '<table width="100%" cellspacing="0" cellpadding="0" class="orderSummary">'+"\n";
	cartview += '<tr>';
	cartview += '<td class="top" colspan="2">'+ARRAY_lang["order_summary"]+'</td>';
	cartview += '</tr>';

	for(i=0; i<order_data['order']['num_people']; i++)
	{
		tmp_person = order_data['order']['person'][i];

		member_icon = '';
		member_name = tmp_person['name'] == "" ? (ARRAY_lang['person']+" "+(i+1)) : tmp_person['name'];
		if ( i == curr_person )
		{
			member_icon = '&nbsp;<img src="/images/bullet_go_left.png" border="0" class="addname" align="absmiddle" />';
			member_name = "<strong>"+member_name+"</strong>";
		}

		cartview += '<tr class="line1">';
		cartview += '<td class="name" colspan="2">';
		if (order_data['order']['num_people'] > 1)
		{
			cartview += '<img src="/images/delete.png" border="0" onclick="removePerson('+i+')" class="addname" align="absmiddle" />&nbsp;';
		}
		else
		{
			cartview += '<img src="/images/shim.png" border="0" class="addname" align="absmiddle" />&nbsp;';
		}
		cartview += '<span onclick="selectPerson('+i+')" class="addname">'+member_name+member_icon+'</span>';
		cartview += '</td>';
		cartview += '</tr>';

		if (tmp_person['item_list'].length > 0)
		{
			for(j=0; j<tmp_person['item_list'].length; j++)
			{
				tmp_item_list = tmp_person['item_list'][j];

				cartview += '<tr>';
				cartview += '<td><span style="float:left;"><img src="/images/delete.png" width="16" height="16" border="0" onclick="removeProduct('+tmp_item_list['id_cat']+','+tmp_item_list['id_type']+','+tmp_item_list['id_prod']+', '+i+')" class="addname" />&nbsp;</span>';
				cartview += '<span style="display: block">'+tmp_item_list['prod_name']+'</span>';
				cartview += '</td>';
				cartview += '<td style="text-align: right;" nowrap>&euro; <span>'+tmp_item_list['prod_price_discount']+'</span></td>';
				cartview += '</tr>';
			}
		}
		else
		{
			cartview += '<tr>';
			cartview += '<td colspan="2">'+ARRAY_lang['person_items_empty']+'</td>';
			cartview += '</tr>';
		}

	}

	cartview += '<tr class="line2">';
	cartview += '<td colspan="2" class="name">';
	cartview += '<span onclick="addPerson()" class="addname">';
	cartview += '<img src="/images/add.png" border="0" onclick="addPerson()" align="absmiddle" />'+'&nbsp;'+ARRAY_lang['add_new_person']+'</span>';
	cartview += '</span>';
	cartview += '</td>';
	cartview += '</tr>';

	cartview += '<tr class="total">';
	cartview += '<td align="right">'+ARRAY_lang["total"]+':&nbsp;</td>';
	cartview += '<td nowrap>&euro; <span id="summaryTotal">'+(order_data['order']['price_discount']).toFixed(2)+'</span></td>';
	cartview += '</tr>';
	cartview += '</table>';
	
	// update the view container innerHTML
	document.getElementById("orderCart").innerHTML = cartview;

}



function updatePartyView()
{
	partyview = ''+"\n";
	for(i=0; i<order_data['order']['num_people']; i++)
	{
		tmp_person = order_data['order']['person'][i];

//		member_icon = '';
		if (
			checkPersonHasSkill(i) &&
			checkPersonHasName(i)
		)
		{
			member_icon = '&nbsp;<img src="/images/tick.png" border="0" align="absmiddle" />';
		}
		else
		{
			member_icon = '&nbsp;<img src="/images/exclamation.png" border="0" align="absmiddle" />';
		}
		member_name = tmp_person['name'] == "" ? (ARRAY_lang['person']+" "+(i+1)) : tmp_person['name'];
		member_class = '';
		if ( i == curr_person )
		{
//			member_icon = '&nbsp;<img src="/images/bullet_go_left.png" border="0" class="addname" align="absmiddle" />';
			member_name = "<strong>"+member_name+"</strong>";
			member_class = ' class="selected"';
		}
		//partyview += '<span onclick="selectPerson('+i+')" class="partyselector">'+member_name+member_icon+'</span>'+"\n";
		partyview += '<li'+member_class+'><a href="javascript:selectPerson('+i+')">'+member_name+member_icon+'</a></li>';
	}

	// update the party view container innerHTML
	document.getElementById("view_member_names").innerHTML = partyview;

}


function updatePriceView()
{
	for(i=0; i<equipment_data.length; i++)
	{
		for (j=0; j<equipment_data[i]['type'].length; j++)
		{
			for (k=0; k<equipment_data[i]['type'][j]['product'].length; k++)
			{
				var id_prod = equipment_data[i]['type'][j]['product'][k]['id'];
				var price_normal = price_data[curr_duration][id_prod]['normal'];
				var price_discount = price_data[curr_duration][id_prod]['discount'];
				$('prod_price_days_'+id_prod).innerHTML = (curr_duration+"&nbsp;"+ARRAY_lang['days']);
				$('prod_ol_price_days_'+id_prod).innerHTML = (curr_duration+"&nbsp;"+ARRAY_lang['days']);
				document.getElementById('prod_price_normal_'+id_prod).innerHTML = price_normal;
				document.getElementById('prod_price_discount_'+id_prod).innerHTML = price_discount;
			}
		}
	}
}



function updateSelectedProducts()
{
	// First unselect all previous persons products
	if (old_person >= 0)
	{
		person_item_list = order_data['order']['person'][old_person]['item_list'];
		for (i=0; i<person_item_list.length; i++)
		{
			productSelected(person_item_list[i].id_cat, person_item_list[i].id_type, person_item_list[i].id_prod, false);
		}
	}

	// Next select the current persons products
	if (curr_person >= 0)
	{
		person_item_list = order_data['order']['person'][curr_person]['item_list'];
		for (i=0; i<person_item_list.length; i++)
		{
			productSelected(person_item_list[i].id_cat, person_item_list[i].id_type, person_item_list[i].id_prod, true);
		}
	}
}



//
// Price Functions
//
function updateTotal()
{
	var total_price_discount = 0;
	var total_price_normal = 0;

	person_list = order_data['order']['person'];

	// first check if the product is already in the customers list
	for (i=0; i<person_list.length; i++)
	{

		var person_price_discount = 0;
		var person_price_normal = 0;

		person_item_list = person_list[i]['item_list'];

		for (j=0; j<person_item_list.length; j++)
		{
			person_price_discount += parseFloat(person_item_list[j].prod_price_discount);
			person_price_normal += parseFloat(person_item_list[j].prod_price_normal);
		}
		person_list[i].price_discount = person_price_discount;
		person_list[i].price_normal = person_price_normal;

		total_price_discount += parseFloat(person_list[i].price_discount);
		total_price_normal += parseFloat(person_list[i].price_normal);
	}

	order_data['order']['price_discount'] = total_price_discount;
	order_data['order']['price_normal'] = total_price_normal;
}



function updateCartPrices()
{
	person_item_list = order_data['order']['person'][curr_person]['item_list'];

	for (j=0; j<person_item_list.length; j++)
	{
		person_item_list[j].prod_price_discount = price_data[curr_duration][person_item_list[j].id_prod].discount;
		person_item_list[j].prod_price_normal = price_data[curr_duration][person_item_list[j].id_prod].normal;
	}
	updateTotal();
	updateCartView();
}



//
// Calendar functions
//
function dateShowCalendar(id)
{
	// assign the passed img element for the onclick event
	var el = document.getElementById(id);
	if (dateCal != null)
	{
		dateCal.hide();
	}
	else
	{
		dateCal = new Calendar(6, null, calSelected, calCloseHandler);
		dateCal.weekNumbers = false;
		dateCal.showsOtherMonths = false;
		dateCal.setDateStatusHandler(dateStatusHandler);
		dateCal.setDateFormat("%Y-%m-%d");
		dateCal.create();
	}
	var new_date = new Date();
//	new_date.setDate(new_date.getDate()+86400000);

	date_parts = document.getElementById("date").value.split('-');
	new_date.setFullYear(date_parts[0]);
	new_date.setMonth(date_parts[1]-1);
	new_date.setDate(date_parts[2]);
	new_date.setHours(0,0,0,0);
	
	dateCal.setDate(new_date);
	dateCal.showAtElement(el, "Tr");			// show the calendar
}
function calCloseHandler(cal)
{
	cal.hide();								// hide the calendar
}
function calSelected(cal, date)
{
	if (cal.dateClicked) {
		document.getElementById("date").value = date;
		document.getElementById("date_required").value = date.split('-').reverse().join("/");

		cal.callCloseHandler();
		savePerson();
	}
}
/*
 * function used by the popup calendar object to disable previous dates in the popup calendars
 */
function dateStatusHandler(date) {
	var retVal = false;
	var tmp_today = new Date();

	tmp_today.setDate(tmp_today.getDate()+1);

	if (date<=tmp_today) {
		retVal = true;
	}
	return retVal;
}



//
// General Form Object Manipulation Functions
//

//
// function set the selectedIndex - compares value passed to value of each option
//
function setSelectSelectedIndexByValue( sel, value )
{
	sel.selectedIndex = 0;
	for (var i=0; i<sel.length; i++)
	{
		if ( sel.options[i].value == value )
		{
			sel.selectedIndex = i;
		}
	}
}



//
// Misc Utility functions
//
function catIndex(id_cat)
{
	for (i=0; i<equipment_data.length; i++)
	{
		if (equipment_data[i]['id'] == id_cat)
		{
			return i;
		}
	}
	return false;
}

function typeIndex(idx_cat, id_type)
{
	for (i=0; i<equipment_data[idx_cat]['type'].length; i++)
	{
		if (equipment_data[idx_cat]['type'][i]['id'] == id_type)
		{
			return i;
		}
	}
	return false;
}

function prodIndex(idx_cat, idx_type, id_prod)
{
	for (i=0; i<equipment_data[idx_cat]['type'][idx_type]['product'].length; i++)
	{
		if (equipment_data[idx_cat]['type'][idx_type]['product'][i]['id'] == id_prod)
		{
			return i;
		}
	}
	return false;
}



//
// Sajax functions
//

// Called when the user changes the "Duration" selector
function getAllPrices( duration )
{
	if (price_data[duration] == undefined )
	{
		x_getAllPrices( duration, getAllPrices_callback );
	}
	
}

function getAllPrices_callback( response )
{
	price_data[order_data['order']['person'][curr_person]['duration']] = response.evalJSON(true);
	updatePriceView();
	updateCartPrices();
}

