var totalFlavoursSelected = 0;
var totalMixinsSelected = 0;
var mixinsPrice = 1.00;
var cakeSmallPrice = 50;
var cakeMediumPrice = 75;
var cakeLargePrice = 100;
var icecreamSmallPrice = 11.00;
var icecreamLargePrice = 19.00;
var typeSelected;
var sizeSelected;
var flavours;
var mixins; 
var currentFlavoursPanel = 0;
var currentMixinsPanel = 0;
var totalFlavoursPanel = 0;
var totalMixinsPanel = 0;

function moveNext(target,xpoints){
	if(target=='flavours-list'){
		if(currentFlavoursPanel < totalFlavoursPanel){
			currentFlavoursPanel++;
		}
		to = currentFlavoursPanel;
	}else if(target=='mixins-list'){
		if(currentMixinsPanel < totalMixinsPanel){
			currentMixinsPanel++;
		}
		to = currentMixinsPanel;
	}
	xpos = -(to * xpoints);
	new Effect.Move(target,{x:xpos,y:0,mode:'absolute'});
}
function movePrev(target,xpoints){
	if(target=='flavours-list'){
		if(currentFlavoursPanel > 0){
			currentFlavoursPanel--;
		}
		to = currentFlavoursPanel;
	}else if(target=='mixins-list'){
		if(currentMixinsPanel > 0){
			currentMixinsPanel--;
		}
		to = currentMixinsPanel;
	}
	xpos = -(to * xpoints);
	new Effect.Move(target,{x:xpos,y:0,mode:'absolute'});
}
function updateTitle(title){
	document.title = title;
}
function move(target,xpoints){
	new Effect.Move(target, {x: xpoints, y:0, duration:1.0, 
							 delay:0.3, transition: Effect.Transitions.sinoidal});
}
function init(){
	YAHOO.util.Event.addListener('flavours-select','change',flavourCallback);
	YAHOO.util.Event.addListener('mixins-select','change',mixinsCallback);
}
function updateType(){
	sizeSelected = "";
	for (counter = 0; counter < document.orderForm.types.length; counter++)
	{
		if (document.orderForm.types[counter].checked){
			typeSelected = document.orderForm.types[counter].value;
		}
	}
	if(typeSelected == "tub"){
		new Effect.Fade('cake-size',{afterFinish:function(){
			new Effect.Appear('tub-size');
		}});
		
	}else if(typeSelected == "cake"){
		new Effect.Fade('tub-size',{afterFinish:function(){
			new Effect.Appear('cake-size');
		}});
		
	}
	updatePrice();
}
function updateSizePrice(){
	if(typeSelected == "tub"){
		var idToInspect = "tubsize";
	}else if(typeSelected == "cake"){
		var idToInspect = "cakesize";
	}
	for (counter = 0; counter < document.orderForm[idToInspect].length; counter++)
	{
		if (document.orderForm[idToInspect][counter].checked){
			sizeSelected = document.orderForm[idToInspect][counter].value;
		}
	}
	updatePrice();
}
function flavourCallback() {
	var id = this.id;
	totalFlavoursSelected = 0;
	flavours = "";
	ele = document.getElementById(id);
	for (var i = 0; i < ele.options.length; i++){
	    if (ele.options[i].selected){
				if(flavours != ""){ flavours += ", "; }
				flavours += ele.options[i].value;
				totalFlavoursSelected++;
			}
	}
	if (totalFlavoursSelected > 3){
		ele.options[ele.selectedIndex].selected = false;
	}
	document.getElementById('flavours').value = flavours;
	updatePrice();
}
function mixinsCallback() {
	var id = this.id;
	totalMixinsSelected = 0;
	mixins = "";
	ele = document.getElementById(id);
	for (var i = 0; i < ele.options.length; i++){
	    if (ele.options[i].selected){
				if(mixins != ""){ mixins += ", "; }
				mixins += ele.options[i].value;
				totalMixinsSelected++;
			}
	}
	document.getElementById('mixins').value = mixins;
	updatePrice();
}
function updatePrice(){
	var priceField = document.getElementById('total-price-value');
	var totalMixins = totalMixinsSelected * parseFloat(mixinsPrice);
	var sizePrice = 0;
	if(typeSelected=="tub"){
		if(sizeSelected=="1/2L"){
			sizePrice = icecreamSmallPrice;
		}else if(sizeSelected=="1L"){
			sizePrice = icecreamLargePrice;
		}
	}else{
		if(sizeSelected=="small"){
			sizePrice = cakeSmallPrice;
		}else if(sizeSelected=="regular"){
			sizePrice = cakeMediumPrice;
		}else if(sizeSelected=="large"){
			sizePrice = cakeLargePrice;
		}
	}
	total = totalMixins + sizePrice;
	total = formatNumber(total,2);
	priceField.innerHTML = total;
	document.getElementById('total').value = total;
	updateSummary();
}
function updateSummary(){
	if(typeSelected == null){ typeSelected = "no type specified"; }
	if(sizeSelected == null){ sizeSelected = "no size specified"; }
	if(flavours == null){ flavours = "no"; }
	if(mixins == null){ mixins = "no"; }
	document.getElementById('order-summary').innerHTML = "<span class='bigblue'>Your order summary:</span> " + typeSelected + " (" + sizeSelected + ") " + "with <span class='flavours'>" + flavours + "</span> ice creams and <span class='mixins'>" + mixins + "</span> mix-ins";
}
function formatNumber (num, decplaces) {
    num = parseFloat(num);
    if (!isNaN(num)) {
        var str = "" + Math.round (eval(num) * Math.pow(10,decplaces));
        if (str.indexOf("e") != -1) {
            return "Out of Range";
        }
        while (str.length <= decplaces) {
            str = "0" + str;
        }
        var decpoint = str.length - decplaces;
        return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
    } else {
        return "NaN";
    }
}
function checkYouremail (field) {
	var fieldID = field.id;
	var strng = field.value;
	var error="";
	if (strng == "") {
		YAHOO.util.Dom.addClass(fieldID,"error");
	    error = "Your e-mail address is required.\n";
	}

	var emailFilter=/^.+@.+\..{2,3}$/
	if (!(emailFilter.test(strng))) { 
	    error = "Invalid e-mail address.\n";
		YAHOO.util.Dom.addClass(fieldID,"error");
	}else {
	    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
	    if (strng.match(illegalChars)) {
			YAHOO.util.Dom.addClass(fieldID,"error");
	        error = "The email address contains illegal characters.\n";
		}
	}
	if(!error){
		YAHOO.util.Dom.removeClass(fieldID,"error");
	}
	return error;    
}
function isEmpty(field) {
	var strng = field.value;
	var error = "";
	var fieldID = field.id;
	  if (strng.length == 0) {
		 
		YAHOO.util.Dom.addClass(fieldID,"error");
	     error = "Please fill in the required field(s).\n"
	  }else if(strng != ''){
		YAHOO.util.Dom.removeClass(fieldID,"error")
	}
	return error;	  
}
function checkWholeForm(id) {
	var theForm = document.getElementById(id);
	var why = "";
	if(id == "orderForm"){
		if(why==''){ why+=isEmpty(theForm.firstname); }else{ isEmpty(theForm.firstname); }
		if(why==''){ why+=isEmpty(theForm.surname); }else{ isEmpty(theForm.surname); }
		if(why==''){ why+=isEmpty(theForm.address); }else{ isEmpty(theForm.address); }
		if(why==''){ why+=isEmpty(theForm.postcode); }else{ isEmpty(theForm.postcode); }
		if(why==''){ why+=isEmpty(theForm.mobile); }else{ isEmpty(theForm.mobile); }
		if(why==''){ why+=isEmpty(theForm.pickup_date); }else{ isEmpty(theForm.pickup_date); }
		if(why==''){ why+=isEmpty(theForm.pickup_month); }else{ isEmpty(theForm.pickup_month); }
		if(why==''){ why+=isEmpty(theForm.pickup_year); }else{ isEmpty(theForm.pickup_year); }
		if(why==''){ why+=isEmpty(theForm.pickup_hour); }else{ isEmpty(theForm.pickup_hour); }
		if(why==''){ why+=isEmpty(theForm.pickup_minute); }else{ isEmpty(theForm.pickup_minute); }
		if(typeSelected == null){
			why += "Please select your order type.\n";
		}else{
			if(sizeSelected == null){
				why += "Please select your order size.\n";
			}
		}
		if(flavours == null){
			why += "Please select at least 1 ice cream flavour.\n";
		}
		why+=checkYouremail(theForm.email);
	}else if(id=="newsletterForm"){
		why+=checkYouremail(theForm.email);
	}
	if (why != "") {
	//	submitForm(id);
	    alert(why);
	    return false;
 	}else{
		submitForm(id);
		return false;
	}
}
function submitForm(id){ 
	var f = document.getElementById(id);
	if(window.XMLHttpRequest){ 
		var xmlReq = new XMLHttpRequest(); 
	} else if(window.ActiveXObject) { 
		var xmlReq = new ActiveXObject('Microsoft.XMLHTTP'); 
	} 
	var formData = '', elem = ''; 
	for(var s=0; s<f.elements.length; s++){ 
		elem = f.elements[s]; 
		if(formData != ''){ 
			formData += '&'; 
		} 
		formData += elem.name+"="+elem.value; 
	} 
	xmlReq.onreadystatechange = function(){ 
		if(xmlReq.readyState == 4){ 
			if(id=="orderForm"){
				document.getElementById('response').innerHTML = xmlReq.responseText;
			}else if(id=="newsletterForm"){
				new Effect.Opacity("newsletter-table",{from:1.0,to:0.0,afterFinish:function(){
					document.getElementById("newsletter-table").innerHTML = xmlReq.responseText;
					setTimeout(function(){ new Effect.Opacity("newsletter-table",{from:0.0,to:1.0}); return false; },500);
				}});
				
			}
		} 
	} 
	xmlReq.open(f.method, f.action, true); 
	xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
	xmlReq.send(formData); 
	return false; 
}
window.onload = init;