//alert("test");
var postBarb = document.getElementById("postBarb");
var postBarbRow = document.getElementById("postBarbRowsRow");
var postCrankedRow = document.getElementById("postCrankedRow");
var postSpacingRow = document.getElementById("postSpacingRow");
var addPosts = document.getElementById("addPosts");
var addPostKit = document.getElementById("addPostKit");
var baseDesc = document.getElementById("theDescription").value;
var baseCost = document.getElementById("cost").value;
var basePrice = document.getElementById("price").value;
var postPlated = document.getElementById("postPlated");
var fullLengths = document.getElementById("fullLength");
var waste = document.getElementById("wasteInPrice");
var wastediv = document.getElementById("pipetopostwaste");
var postCoating = document.getElementById("postCoating");
var kitItemTable = document.getElementById("kitItemTable");


// KIT INFO
var pmKitCode = document.getElementsByName("kitCode");
var pmKitCost = document.getElementsByName("kitCost");
var pmKitPrice = document.getElementsByName("kitPrice");
var pmKitDesc = document.getElementsByName("kitDesc");
var pmKitQty = document.getElementsByName("kitQty");
var pmKitAdd = document.getElementsByName("kitAdd");

//POWDERCOAT VARS
var pcCode = document.getElementById("postCoatingCode");
var pcDesc= document.getElementById("pcDesc");
//POWDER LISTN
postCoatingCode.addEventListener("change", function() { powderQtyModifier(); },false);
postCoating.addEventListener("change", function() { 
		if(this.value>"0"){ toggleClass("postPowder","1"); kitCodes("postCoatingCode","Powder","rate");  } 
		else toggleClass("postPowder","0"); },false);

//BARB
postBarb.addEventListener("change", function() { if( postBarb.selectedIndex=="1" ){ postBarbRow.style.display=""; postCrankedRow.style.display="";postSpacingRow.style.display="";} }, false);
postBarb.addEventListener("change", function() { if( postBarb.selectedIndex!="1" ){ postBarbRow.style.display="none"; postCrankedRow.style.display="none";postSpacingRow.style.display="none";} }, false);

//BASE PLATE VARS
var bpDesc = document.getElementById("postPlatedMsg");
var bpCode = document.getElementById("postPlates");
//BASE PLATE LISTEN
bpCode.addEventListener("change", function() {	baseplateConfirm(); },false);
postPlated.addEventListener("change", function() { 
	if(this.value=="No"){
		bpCode.style.display="none";
	} else { 
		bpCode.style.display="";
	}
	//kitCodes("postPlates","Base P","Flan"); 
	},false);

//CRANK LISTEN
document.getElementById("postCrank").addEventListener("change", function() { 
		if(document.getElementById("postCrank").selectedIndex=="5"){ 
			var ytop = document.getElementsByClassName("y-top");
			for(i=0;i<ytop.length;i++){
				ytop[i].style.display="";
			} 
		} 
	}, false);
document.getElementById("costToggle").addEventListener("mouseup", function() { 
									var pipeCostings = document.getElementsByClassName("pipeCosting");
									for(i=0;i<pipeCostings.length;i++){
										if(pipeCostings[i].style.display=="none"){
											pipeCostings[i].style.display="";
										} else pipeCostings[i].style.display="none";
									} 
								}, false);

fullLengths.addEventListener("change", function() { pipewastecalc(); }, false);
waste.addEventListener("change", function() { pipewastecalc(); }, false);

function pipewastecalc (){
	var pwx = parseInt(document.getElementById("fullLength").value);
	var postLength = parseInt(document.getElementById("postLength").value);
	zz = Math.floor(pwx/postLength);
	yy = pwx % postLength;
	xx = yy / zz;
	wastediv.innerHTML=yy+" remaining after "+zz+" posts, adding "+xx+" waste to ea. post";
	return xx;
}

function powderQtyModifier (){
	var kitItemTable = document.getElementById("kitItemTable");
	var postLength = parseInt(document.getElementById("postLength").value);
	var postQty =parseInt(document.getElementById("postQty").value);
	pcDesc.innerHTML=pcCode.options[pcCode.selectedIndex].getAttribute("data-desc")+"<br>"; 
	//if(postQty<"1" || isNaN(postQty)){ alert("Error setting powdercoating costs, Zero Qty?");   }
	//if(postLength<"1" || isNaN(postLength)){ alert("Error setting powdercoating costs, Post Length?");   }
	var pwdCost = "0";
	var pwdPrice= "0";
	var pwdMarkup = document.getElementById("postCoatingMargin").value;
	var newQty = (postLength/1000);
	for(var i=0;i<pmKitCode.length;i++){
		pmKitAdd[i].checked=false;
		kitr = i+1;
		kitItemTable.rows[kitr].style.backgroundColor="";
		if(pmKitCode[i].value.match(pcCode.options[pcCode.selectedIndex].text)){
			pmKitQty[i].value=newQty;
			factor = pmKitPrice[i].value/pmKitCost[i].value;
			if(parseInt(pwdMarkup)>0) { 
				pwdCost = newQty*(pmKitCost[i].value*(pwdMarkup/100+1));
				pwdPrice= parseInt(pwdCost*factor);
			} else { 
				pwdCost = newQty*pmKitCost[i].value;
				pwdPrice= newQty*pmKitPrice[i].value;
			}
			//pmKitAdd[i].checked=true;
			//kitItemTable.rows[kitr].style.backgroundColor="var(--main-highlight-color)";
		} 
	}
	if(pwdCost=="0"){ alert("No Powdercoating code is set"); }
	var powderCost = [pwdCost,pwdPrice];
	return powderCost;
}
//###################################
//#  SWAGING
//###################################
function baseplateConfirm () {
	bpDesc.innerHTML=bpCode.options[bpCode.selectedIndex].getAttribute("data-desc")+"<br>";
}
/*
function powderCodes() {
	var powderForm = document.getElementById("postCoatingCode");
	powderForm.options.length=0;
	//option.text = pcCodes[i].value;
	alert("HERE W GO");
	console.log(pcCodes);
	for(var i=0;i<pcCodes.length;i++){
		if(pmKitDesc[i].value.match("Powder") && pcCodes[i].value.match("PCP")){
			var option = document.createElement("option");
			option.text = pcCodes[i].value;
			option.setAttribute("data-desc",powderDesc[i].value);
			powderForm.add(option);
		}
	}
}
*/
function kitCodes(target,keyword, keyword2=null) {
	var target = document.getElementById(target);
	target.options.length=0;
	target.style.display="";
	var option = document.createElement("option");
	option.text = "Please Select";
	target.add(option);
	for(var i=0;i<pmKitCode.length;i++){
		if(pmKitDesc[i].value.toLowerCase().match(keyword.toLowerCase()) && pmKitDesc[i].value.toLowerCase().match(keyword2.toLowerCase())){
			var option = document.createElement("option");
			option.text = pmKitCode[i].value;
			option.setAttribute("data-desc",pmKitDesc[i].value);
			target.add(option);
		}
	}
}

function productionCosts (){
	var url = "plugins/pipe/pipetopostsave.php?itemid="+y+"&call=savecalcs";
}

function addThePosts (){
	updatePrice();
	var baseCost = document.getElementById("cost").value;
	var basePrice = document.getElementById("price").value;
	var waste = document.getElementById("wasteInPrice");
	//alert(basePrice);
	var description = baseDesc;
	var processCount=parseInt(1);
	var productionCutCost=parseFloat(document.getElementById("pipeCutCost").value);
	if( parseInt(document.getElementById("postLength").value) ==  parseInt(document.getElementById("fullLength").value)){
		var productionCost=parseInt("0");
	} else var productionCost=parseFloat(document.getElementById("pipeCutCost").value);
	var productionCrimpCost=parseFloat(document.getElementById("pipeCrimpCost").value);
	var productionCrankCost=parseFloat(document.getElementById("pipeCrankCost").value);
	var productionWeldCost=parseFloat(document.getElementById("pipeWeldCost").value);
	var productionSwageCost=parseFloat(document.getElementById("pipeSwageCost").value);
	var productionYCost=parseFloat(document.getElementById("postBarbYtop").value);
	var productionBaseplateCost=parseFloat(5);

	//alert("Crimp="+productionCrimpCost+" Cut="+productionCost+" Crank="+productionCrankCost+" Y-Top"+productionYCost);
	
	//### UPDATE DESCRIPTION AND ADJUST MANUFACTURING PROCESS COUNT ###
	
	//Type
	var postTypeIndex=document.getElementById("postType").selectedIndex;
	var postType=document.getElementById("postType").options[postTypeIndex].value;
	description+=" "+postType;
	var pipecranks="0";


	if(postType=="Stay - Backstay"){ productionCost+=(productionCrankCost); }
	if(postType=="Stay - Backstay - DBL Bend"){ productionCost+=(productionCrankCost*2); }
	if(postType=="Stay - Diagonal Bent Inground"){ productionCost+=(productionCrankCost); }
	if(postType=="Stay - Diagonal Bent Inground - DBL Bend"){ productionCost+=(productionCrankCost*2); }
	
	//Length
	var postLength = parseInt(document.getElementById("postLength").value);
	description+=" "+postLength+"mm long";

	//Barb
	var postBarbRows = document.getElementById("postBarbRows").value;
	var postBarbSpacing = document.getElementById("postBarbSpacing").value;
	if(postBarb.selectedIndex=="1"){ 
		description+=" with "+postBarbRows+" Rows Barb @ "+postBarbSpacing+" spacing"; 
		processCount++; 
		productionCost+=productionCrimpCost;   
	}

	//Crank
	var postCranked = document.getElementById("postCrank");
	if(postCranked.selectedIndex>"0"){ 
		description+=" "+postCranked.value; 
		processCount++;
		productionCost+=productionCrankCost;  
	}
	if(postCranked.selectedIndex>"4"){ productionCost+=productionYCost;  }
	//Plated
	var postPlated = document.getElementById("postPlated");
	if(postPlated.selectedIndex=="1"){ 
		description+=" Base Plated - "
			+bpCode.options[bpCode.selectedIndex].getAttribute('data-code'); 
		processCount++; 
		productionCost+=parseFloat(bpCode.options[bpCode.selectedIndex].getAttribute("data-cost"));  
		productionCost+=productionWeldCost;
	}
	
	// Coating
	var postCoatingIndex=document.getElementById("postCoating").selectedIndex;
	var postCoating=document.getElementById("postCoating").options[postCoatingIndex].value;
	if(postCoating!="0") { 
		var pwdPrices= powderQtyModifier(); 
		description+=" "+postCoating; 
	} else { pwdPrices= ["0","0"];  }
	// SWAGING
	//var postSwagingIndex=document.getElementById("postSwaging").selectedIndex;
	//var postSwaging=parseInt(document.getElementById("postSwaging").options[postSwagingIndex].value);
	if(document.getElementById("postSwaging").value>"0"){ 
		description+=" Swaged ";  
		productionCost+=productionSwageCost;
	}
	
	//### CALCULATE PRICE ###
	if(waste.value=="Yes"){
		var pipeWaste = pipewastecalc();
		priceWaste = (pipeWaste/1000) * basePrice;
		costWaste = (pipeWaste/1000) * baseCost;
	} else { 
		costWaste =parseInt(0);
		priceWaste = parseInt(0);
	}
	
	//### GET DETAILS FOR  MANUFACTURE COST KPI
	//## BASE HOURLY RATE -- FACT-HR-RATE (ID = 3849)
	//## CUT -- ITEM
	
	//## DENT
	//## CRANK & DENT
	//## BASE PLATE
	//
	var pipePrice = basePrice;
	var processCost=(3*processCount);
	
	var postQty=document.getElementById("postQty").value;
	var pipeQty=((postLength/1000)*postQty);
	var postPrice = (postLength/1000)*pipePrice + (processCost/postQty) + parseInt(pwdPrices[1]) + priceWaste + productionCost;
	var postCost = (postLength/1000)*baseCost + (processCost/postQty) + parseInt(pwdPrices[0]) + costWaste + productionCost;
	document.getElementById("price").value=Math.round(postPrice*100)/100;
	document.getElementById("cost").value=Math.round(postCost*100)/100;
	
	//### UPDATE QTY ###
	var qty = document.getElementById("qty");
	qty.value=document.getElementById("postQty").value;
	
	document.getElementById("theDescription").value=description;
	
	document.getElementById("extra").value="qty:"+pipeQty+"::";
	document.getElementById("extra").value+="flange:"+bpCode.value+"::";
	document.getElementById("extra").value+="coating:"+postCoating+"::";
	document.getElementById("extra").value+="fullLength:"+fullLengths.value;
	updateNew();
	
}

addPosts.addEventListener("mouseup", function () { 
				hideAll(); 
				addThePosts();  } , false);
addPostKit.addEventListener("mouseup", function () {
				hideAll(); 
				addThePosts();  
				document.getElementById('kitform').classList.toggle('popupDivLarge');  } , false);
//postPlated.addEventListener("change", function() { if( postPlated.selectedIndex=="1" ){ alert("This will update the post description, use kits or add your baseplates and fasteners seperately"); } }, false);

