/*
Event.observe(window, "load", function() {
	if ($("artikel_in_bag_overlay")) {
		$("artikel_in_bag_overlay").observe("click", hideAfteraddingtoBagMessage);
		Event.observe(window, "scroll", positionBagMessage);
		Event.observe(document, "scroll", positionBagMessage);
	}
});
*/

function showAfteraddingtoBagMessage() {
	var windowDimensions = document.viewport.getDimensions();
	var windowOffset = document.viewport.getScrollOffsets();
	
	
	var overlayHeight = (document.body.clientHeight < windowDimensions.height) ? windowDimensions.height : document.body.clientHeight;
	
	var windowLeft = windowOffset.left + (windowDimensions.width - 320) / 2
	var windowTop = windowOffset.top + (windowDimensions.height - 100) / 2
	
	
	//$("artikel_in_bag_overlay").setStyle({ width: document.body.clientWidth + "px", height: document.body.clientHeight + "px" });
	
	
	$("artikel_in_bag_overlay").setStyle({ height: overlayHeight + "px" });
	$("artikel_in_bag_window").setStyle({ left: windowLeft + "px", top: windowTop + "px" });	
		
	$("artikel_in_bag_overlay").appear({ to: 0.25, duration: 1.0 });
	$("artikel_in_bag_window").appear({ duration: 1.0 });	
}

function positionBagMessage() {
	var windowDimensions = document.viewport.getDimensions();
	var windowOffset = document.viewport.getScrollOffsets();
	
	
	var windowLeft = windowOffset.left + (windowDimensions.width - 320) / 2
	var windowTop = windowOffset.top + (windowDimensions.height - 100) / 2

	$("artikel_in_bag_window").setStyle({ left: windowLeft + "px", top: windowTop + "px" });	

}


function hideAfteraddingtoBagMessage() {
	$("artikel_in_bag_overlay").fade({ duration: 0.25 });
	$("artikel_in_bag_window").fade({ duration: 0.25 });

}


function addAccessoireToBag(formId) {
	$("accesoire_" + formId + "_fields").hide();
	$("accesoire_" + formId + "_busy").show();
		
	new Ajax.Request("/shop/front/item_to_bag.asp", {
		parameters: $("accesoire_" + formId).serialize(),		
		onSuccess: function(response) {
			$("accesoire_" + formId + "_tr").addClassName("model_in_bag");
			updateBagResponse(response.responseText);
			showAfteraddingtoBagMessage();
		},
		onFailure: function(response) {
			alert("This accessoire cant be added to the orderlist.");
		},				
		onComplete: function() {
			$("accesoire_" + formId + "_busy").hide();		
			$("accesoire_" + formId + "_fields").show();
		}
	});
}


function addMachineToBag(formId) {
	$("machine_" + formId + "_fields").hide();
	$("machine_" + formId + "_busy").show();
		
	new Ajax.Request("/shop/front/item_to_bag.asp", {
		parameters: $("machine_" + formId).serialize(),		
		onSuccess: function(response) {
			updateBagResponse(response.responseText);
			showAfteraddingtoBagMessage();
		},
		onFailure: function(response) {
			alert("The tools cant be added to the list.");
		},				
		onComplete: function() {
			$("machine_" + formId + "_busy").hide();		
			$("machine_" + formId + "_fields").show();
		}
	});

}

function updateBagAantal(formId) {
	$("bag_" + formId + "_fields").hide();
	$("bag_" + formId + "_busy").show();
		
	new Ajax.Request("/shop/front/item_to_bag.asp", {
		parameters: $("bag_" + formId).serialize(),		
		onSuccess: function(response) {
			document.location = document.location
		},
		onFailure: function(response) {
			alert("The amount cant be changed.\nPlease try again later");
		},				
		onComplete: function() {
			$("bag_" + formId + "_busy").hide();		
			$("bag_" + formId + "_fields").show();
		}
	});

}

function addPartToBagFast(formId) {
	$("partnumber_" + formId + "_fields").hide();
	$("partnumber_" + formId + "_busy").show();
		
	new Ajax.Request("/shop/front/item_to_bag.asp", {
		parameters: $("partnumber_" + formId).serialize(),		
		onSuccess: function(response) {
			$("partnumber_" + formId + "_tr").addClassName("model_in_bag");
			updateBagResponse(response.responseText);
			showAfteraddingtoBagMessage();
		},
		onFailure: function(response) {
			alert("The part can not be added to the orderlist.\nPlease try again later");
		},				
		onComplete: function() {
			$("partnumber_" + formId + "_busy").hide();		
			$("partnumber_" + formId + "_fields").show();
		}
	});

}


function addPartToBag(formId) {
	$("partnumber_" + formId + "_fields").hide();
	$("partnumber_" + formId + "_busy").show();
		
	new Ajax.Request("/shop/front/item_to_bag.asp", {
		parameters: $("partnumber_" + formId).serialize(),		
		onSuccess: function(response) {
			$("partnumber_" + formId + "_tr").addClassName("model_in_bag");
			showAfteraddingtoBagMessage();
			updateBagResponse(response.responseText);
			highlightInDrawing($("partnumber_" + formId + "_partnr").value);			
		},
		onFailure: function(response) {
			alert("Can not add part to orderlist\nPlease try again.");
		},				
		onComplete: function() {
			$("partnumber_" + formId + "_busy").hide();		
			$("partnumber_" + formId + "_fields").show();
		}
	});
}

function confirmBagDelete() {
	return confirm("Are you sure you want to delete this item from your basket?");
}

function confirmOfferteRegelDelete() { // Offerte regel verwijderen
	return confirm("Are you sure you want to delete this item from your quote?");
}

function confirmOfferteDelete() {
	return confirm("Are you sure you want to delete this quote?\nWARNING: This action can not be undone");
}

function updateBagResponse(inMessage) {
	$("artikel_in_bag_artikelinfo").update(inMessage);
}

function showUploadStatus() {
	if ($("uploadStatusbar")) {
		$("uploadStatusbar").hide();
	}
	if ($("uploadResults")) {
		$("uploadResults").hide();
	}
	$("uploadFields").hide();
	$("uploadStatus").show();
}

function show_upload() {
	$("uploadResults").hide();
	$("uploadFields").show();
	
}

function removeNewOfferteLine(event) {
	var bagregelId = this.readAttribute("bagregelId");
	if (confirmOfferteRegelDelete()) {
		if (bagregelId.substring(0,4) != "NEW_") {
			var removeid = new Element("input", { "type": "hidden", "name": "bagid_remove", "value": bagregelId });
			$("shop_form").insert(removeid);
		}	
		$("tr_" + bagregelId).remove();
	}
	calcOfferteRegels(); // recalc regels
}

function calcOfferteRegels() {
	var regels = $$("input.bag_id");
	totaal = 0;
	for (e = 0; e < regels.length; e++) {
		var bag_id = regels[e].getValue();
		var aantal = parseInt($F("bag_" + bag_id + "_aantal"));		
		var prijs = $F("bag_" + bag_id + "_prijs");
		//	prijs = prijs.replace(".", "");
		//	prijs = prijs.replace(",", ".");			
			prijs = prijs.replace(",", "");
			prijs = parseFloat(prijs);
			
		// console.log(prijs);
		if ((!isNaN(prijs)) && (!isNaN(aantal)))   {
			subtotaal = (prijs * aantal);
			totaal = totaal + subtotaal;
		}
	}	
	//$("bag_calculated_price").update(totaal.toFixed(2));	
	$("bag_calculated_price").update(formatNumber(totaal, 2));	
}

function checkPriceNumber() {
	var value = this.value;		
		prijs = prijs.replace(",", "");
		// value = value.replace(".", "");
		// value = value.replace(",", ".");					
				
	if (isNaN(parseFloat(value))) {
		alert("The given price is incorrect.");		
	}
}

function checkAantalNumber() {
	var value = this.value;		
		value = value.replace(".", "");
		value = value.replace(",", ".");					
				
	if (isNaN(parseInt(value))) {
		alert("The given amount is incorrect");		
	}
}

function addOfferteRegel() {	
	var itemIndex = parseInt($("newitems").value);
		itemIndex++;
	
	var existing_lines = parseInt($("existing_lines").value);
	

	var bagregelId = "NEW_" + itemIndex;
	var trClassName = (((itemIndex + existing_lines) % 2) == 0) ? "even" : "odd";
	
	
	var trEl = new Element("tr", { "class" : trClassName, "id": "tr_" + bagregelId });
	var inputRegelId = new Element("input", { "type" : "hidden", "name": "bag_id", "value": bagregelId, "class": "bag_id" });
	var inputTitel = new Element("input", { "type" : "text", "name": "bag_" + bagregelId + "_titel", "class": "offerteItem_titel_input" });
	
	var inputPrijs = new Element("input", { "type" : "text", "name": "bag_" + bagregelId + "_prijs", "id": "bag_" + bagregelId + "_prijs", "class": "offerteItem_prijs_input price_field_style", "value": "0" });
		inputPrijs.observe("blur", calcOfferteRegels);
		inputPrijs.observe("blur", checkPriceNumber);
		
	var inputAantal = new Element("input", { "type" : "text", "name": "bag_" + bagregelId + "_aantal", "id": "bag_" + bagregelId + "_aantal", "class": "offerteItem_aantal_input", "value": "1" });
		inputAantal.observe("blur", calcOfferteRegels);
		inputAantal.observe("blur", checkAantalNumber);
	
	
	
	var deleteLinkFunction = function() {
		removeNewOfferteLine(bagRegelId) 
	}
	
	var deleteLink = new Element("a", { "href" : "#", "bagregelId": bagregelId });
		deleteLink.observe("click", removeNewOfferteLine);
		deleteLink.insert(new Element("img", { "src": "/shop/images/icon_delete.gif", "alt": "Delete", "title": "Delete", "border": "0" }));
	
	trEl.appendChild(new Element("td").insert({ top: inputRegelId, bottom: inputTitel }));
	trEl.appendChild(new Element("td").insert(inputPrijs));
	trEl.appendChild(new Element("td").insert(inputAantal));
	trEl.appendChild(new Element("td", { "class" : "last_item" } ).insert(deleteLink));
	
	$("OfferteLijstNew").appendChild(trEl);
	$("newitems").value = itemIndex
}


function formatNumber (inValue, decimal) {
     //decimal  - the number of decimals after the digit from 0 to 3
     //-- Returns the passed number as a string in the xxx,xxx.xx format.
       anynum = inValue;
       divider =10;
       switch(decimal){
            case 0:
                divider =1;
                break;
            case 1:
                divider =10;
                break;
            case 2:
                divider =100;
                break;
            default:       //for 3 decimal places
                divider =1000;
        } 

       workNum=Math.abs((Math.round(anynum*divider)/divider)); 

       workStr=""+workNum 

       if (workStr.indexOf(".")==-1){workStr+="."} 

       dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
       pStr= "." + workStr.substr(workStr.indexOf(".") + 1) 

       while (pStr.length-1< decimal){pStr+="0"} 

       if(pStr ==',') pStr =''; 

       //--- Adds a comma in the thousands place.
       if (dNum>=1000) {
          dLen=dStr.length
          dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
       } 

       //-- Adds a comma in the millions place.
       if (dNum>=1000000) {
          dLen=dStr.length
          dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
       }
       retval = dStr + pStr
       //-- Put numbers in parentheses if negative.
       if (anynum<0) {retval="("+retval+")";} 

    //You could include a dollar sign in the return value.
      //retval =  "$"+retval
      return retval;
}



