var lastFrame		= {},
	effectsStack	= [],
	V				= {}
try{document.execCommand("BackgroundImageCache", false, true)}catch(err){}
//******************************************************************************
//******************************************************** MATERIAL FUNCTIOS ***
//******************************************************************************
function setMaterial()
{
	var materials = document.mainForm.printMaterial
	for(i=0; i<	materials.length; i++)
	{
		if(materials[i].checked)
		{
			var material = materials[i].value
			break
		}
	}
	switch(material)
	{
		case "canvas":
			//$("printSurfaceFinishes").style.display 	= "none"
			$("frame_cont").style.display 				= "block"
			document.getElementById("printSurfaceFinish_matty").style.display = "none"
			document.getElementById("printSurfaceFinish_matty1").style.display = "none"
			$("isOnKapa").parentNode.style.display 		= "none"
			$("isLamination").parentNode.style.display	= "none"
			$("isStrech").parentNode.style.display 		= "block"
			$("isWrap").parentNode.style.display 		= "block"
			$("isOnKapa").disabled 						= true
			$("isLamination").disabled 					= true
			$("isStrech").disabled 						= false
			$("isStrech").checked = true
			$("isWrap").disabled 						= false
			$("finish_material").innerHTML 				= "Canvas "
			$("finish_onkapa_row").style.display		= "none"
			$("finish_lamination_row").style.display	= "none"
			try{$("finish_strech_row").style.display	= "table-row"}catch(e){$("finish_strech_row").style.display	= "block"}
			setFrame()
		break
		case "photo":
			document.getElementById("printSurfaceFinish_matty").style.display = "block"
			document.getElementById("printSurfaceFinish_matty1").style.display = "block"
			//$("printSurfaceFinishes1").style.display 	= "block"
			//$("printSurfaceFinishes2").style.display 	= "block"
			$("frame_cont").style.display 				= "block"
			$("isOnKapa").parentNode.style.display 		= "block"
			$("isLamination").parentNode.style.display 	= "block"
			$("isStrech").parentNode.style.display 		= "none"
			$("isWrap").parentNode.style.display 		= "none"
			$("isOnKapa").disabled 						= false
			$("isLamination").disabled 					= false
			$("isStrech").disabled 						= true
			$("isWrap").disabled 						= true
			$("finish_material").innerHTML 				= "Photo "
			$("finish_strech_row").style.display		= "none"
			try{$("finish_onkapa_row").style.display	= "table-row"}catch(e){$("finish_onkapa_row").style.display	= "block"}
			try{$("finish_lamination_row").style.display= "table-row"}catch(e){$("finish_lamination_row").style.display	= "block"}
			setFrame()
		break
		case "poster":
			document.getElementById("printSurfaceFinish_matty").style.display = "block"
			document.getElementById("printSurfaceFinish_matty1").style.display = "block"
			//$("printSurfaceFinishes").style.display 	= "block"
			$("frame_cont").style.display 				= "none"
			//$("framesList").style.display 				= "none"
			$("isOnKapa").parentNode.style.display 		= "block"
			$("isLamination").parentNode.style.display 	= "block"
			$("isStrech").parentNode.style.display 		= "none"
			$("isWrap").parentNode.style.display 		= "none"
			$("isOnKapa").disabled 						= false
			$("isLamination").disabled 					= false
			$("isStrech").disabled 						= true
			$("isWrap").disabled 						= true
			//$("finish_material").innerHTML 				= "Poster "
			$("finish_material").innerHTML 				= "Adhesive p. paper "
			$("finish_strech_row").style.display		= "none"
			try{$("finish_onkapa_row").style.display	= "table-row"}catch(e){$("finish_onkapa_row").style.display	= "block"}
			try{$("finish_lamination_row").style.display= "table-row"}catch(e){$("finish_lamination_row").style.display	= "block"}		
			clearFrame(true)
		break
	}
//	setPasrpartuType()
	calculatePrice()
}
	
//******************************************************************************
//********************************************************* EFFECT FUNCTIONS ***
//******************************************************************************
function setEffect(objRef)
{
	var effectId	= 0, 
		effectPrice	= "no", 
		effectName	= "",
		pic 		= $("mainpic"),
		name 		= $("finish_effect_name"),
		price		= $("finish_effect_price"),
		divs 		= $("effectsList").getElementsByTagName("table")

	if(typeof objRef == "number")
	{
		for(i=0; i<divs.length; i++)
		{
			if(divs[i].getAttribute("effectId") == objRef)
			{
				objRef = divs[i]
				break
			}	
		}
	}
		
	if(objRef)
	{
	 	effectId	= objRef.getAttribute("effectId")
		effectPrice	= objRef.getAttribute("effectPrice")
		effectName	= objRef.getAttribute("effectName")
	}
	
	for(i=0; i<divs.length; i++)
		divs[i].className = null

	if(effectId > 0)
	{
		$("filterLoader").style.visibility = "visible"
		var newPic = new Image()
		newPic.onload = function (){pic.src = "/pics/effect/" + V.picId + ".jpg?" + Math.random();$("filterLoader").style.visibility = "hidden"}
		newPic.src = "/canvas/vp.asp?picId=" + V.picId + "&effectId=" + effectId + "&" + Math.random()
		objRef.className = "selected"
		$("effectId").value = effectId	
		if(effectPrice == 0)
			price.innerHTML = "no charge"
		else		
			price.innerHTML = renderPrice(effectPrice)
		name.innerHTML = " - " + effectName
		
		V.effectPrice = effectPrice
		
		effectsStack.push(effectId)
	}
	else
	{
		price.innerHTML = "";
		name.innerHTML = "";
		pic.src = "/pics/small/" + V.picId + ".jpg";
		V.effectPrice = 0;
		$("effectId").value = 0;
	}
	
	calculatePrice()
}
function undoEffect()
{
	var 
		lastDiv		= null,
		divs 		= $("effectsList").getElementsByTagName("table"),
		lastEffect 	= parseInt(effectsStack[effectsStack.length-2])
	
	if(isNaN(lastEffect))
		revertEffects()
			
	for(i=0; i<divs.length; i++)
	{
		//alert(divs[i].getAttribute("effectId"));
		if(divs[i].getAttribute("effectId") == lastEffect)
		{
			lastDiv = divs[i]
			break
		}
	}
	
	if(lastDiv)
	{
		setEffect(lastDiv)
		effectsStack.length = effectsStack.length-2
	}
	else
		revertEffects()	
}
function revertEffects()
{
	setEffect(null)
	effectsStack.length = 0
	V.effectPrice = 0
}
//******************************************************************************
//********************************************************** FINISH FUNCTIOS ***
//******************************************************************************
function isOnKapaToggle()
{
	var objRefLam = $("isLamination"),
		objRefKap = $("isOnKapa")
		
	if(objRefLam.checked)
	{	
		objRefKap.checked = true
	}
	else
	{
		var frameId		= parseInt($("frameId").value),
			materials 	= document.mainForm.printMaterial		
		for(i=0; i<	materials.length; i++)
		{
			if(materials[i].checked)
			{
				material = materials[i].value
				break
			}
		}
		if(frameId && material == "photo")
			objRefKap.checked = true
	}
	calculatePrice()
}
function isStrechToggle()
{
	var material	= "",
		objWrap 	= $("isWrap"),
		objStrech	= $("isStrech"),
		frameId		= parseInt($("frameId").value),
		materials 	= document.mainForm.printMaterial
	for(i=0; i<	materials.length; i++)
	{
		if(materials[i].checked)
		{
			material = materials[i].value
			break
		}
	}
	if(frameId && material == "canvas")
		objStrech.checked = true
	if(objWrap.checked && !objStrech.checked)
		objWrap.checked = false
	calculatePrice()
}
function isLaminationToggle()
{
	var objRefLam = $("isLamination"),
		objRefKap = $("isOnKapa")
		
	if(objRefLam.checked && !objRefKap.checked)
	{
		if(!window.kapaAlerted)
		{
			alert("Lamination requires kapa")
			window.kapaAlerted = true
		}
		objRefKap.checked = true
	}		
	calculatePrice()
}
function isWrapToggle()
{
	var objWrap 	= $("isWrap"),
		objStrech 	= $("isStrech")
		
	if(objWrap.checked)
	{
		if(!window.wrapAlerted)
		{
			//alert("לידיעתך, עיטוף גלריה מחייב מתיחה על פרופיל עץ.\n לתשומת ליבך – עיטוף גלריה גורע כ – 7 ס\"מ מהרוחב ומהגובה הסופי של התמונה לטובת ההיקף בפאות הצדדיות בתמונה. אם ברצונך לשמור על מימדי חזית התמונה כפי שהוגדרו, אנא חזור לשלב 1 ושנה אותם בהתאמה.")
			msg="Please note - Gallery wrap will crop the original picture\n"
				+ "width & height approximately 2.5 to 3 inches. \n"
				+ "It will also decrease the actual size of the stretched \n"
				+ "picture approximately 3 inches from width and height. \n"
				+ "If you wish to maintain the original dimensions you've \n"
				+ "picked for your picture, please go back to step1 and \n"
				+ "increase width and height in 3 inches." ;
			alert(msg);
			window.wrapAlerted = true
		}		
		if(objWrap.checked && !objStrech.checked)
		{
			objStrech.checked = true
		}		
		paspartuClear("inner")
		paspartuClear("outer")
		//clearFrame(true)
		clearFrame()
	}
	else
	{
		setDimensionsDisplay()
	}
}

//******************************************************************************
//*********************************************************** FRAME FUNCTIOS ***
//******************************************************************************
function setFrame(objRef)
{	
	if(typeof objRef == "number")
	{
		var divs = $("framesList").getElementsByTagName("LI")
		for(i=0; i<divs.length; i++)
		{
			if(divs[i].getAttribute("num") == objRef)
			{
				objRef = divs[i]
				break
			}	
		}
	}

	if(objRef)
	{
		lastFrame.num		= objRef.getAttribute("num")
		lastFrame.color		= objRef.getAttribute("color")
		lastFrame.material	= objRef.getAttribute("material")
		lastFrame.width 	= objRef.getAttribute("width")
		lastFrame.price_a 	= parseInt(objRef.getAttribute("price_a"))
		lastFrame.price_b	= parseInt(objRef.getAttribute("price_b"))
		lastFrame.depth		= objRef.getAttribute("depth")
		lastFrame.profile	= objRef.getAttribute("profile")
	}
	if(!lastFrame.num)
		return

	var printMaterial = "",
		materials 	= document.mainForm.printMaterial
		
	for(i=0; i<	materials.length; i++)
	{
		if(materials[i].checked)
		{
			var printMaterial = materials[i].value
			break
		}
	}
	if(printMaterial == "canvas")
	{
		if(!$("isStrech").checked)
		{	
			if(!window.strechAlerted)
			{
				//alert("לידיעתך, מיסגור של תמונה על בד ציירים מחייב מתיחה על פרופיל עץ")
				window.strechAlerted = true
			}
			$("isStrech").checked = true
		}
	}
	if(printMaterial == "photo")
	{
		if(!$("isOnKapa").checked)
		{	
			if(!window.onKapaAlerted)
			{
				//alert("לידיעתך, מיסגור של תמונה על נייר צילום מחייב הדבקה על קאפה")
				window.onKapaAlerted = true
			}
			$("isOnKapa").checked = true
		}
	}
	
	$("isWrap").checked = false
	
	$("frame_tl").style.backgroundImage = "url(/images/frames/tl/" + lastFrame.num + ".gif)"
	$("frame_t").style.backgroundImage = "url(/images/frames/t/" + lastFrame.num + ".gif)"
	$("frame_tr").style.backgroundImage = "url(/images/frames/tr/" + lastFrame.num + ".gif)"
	$("frame_l").style.backgroundImage = "url(/images/frames/l/" + lastFrame.num + ".gif)"
	$("frame_r").style.backgroundImage = "url(/images/frames/r/" + lastFrame.num + ".gif)"
	$("frame_bl").style.backgroundImage = "url(/images/frames/bl/" + lastFrame.num + ".gif)"
	$("frame_b").style.backgroundImage = "url(/images/frames/b/" + lastFrame.num + ".gif)"
	$("frame_br").style.backgroundImage = "url(/images/frames/br/" + lastFrame.num + ".gif)"
	
	//$("frame_selected_cont").innerHTML = ""
	var ddd = ""+ "<table align=right width=400><tr><td class=text>"
						+ "<strong>Color</strong>: " + lastFrame.color
						+ "&nbsp;&nbsp;</td><td class=text><strong>Material</strong>: " + lastFrame.material
						+ "&nbsp;&nbsp;</td><td class=text><strong>Profile</strong>: " + lastFrame.profile
						+ "&nbsp;&nbsp;</td><td class=text><strong>Width</strong>: " + lastFrame.width + " Inch."
					 	+ "&nbsp;&nbsp;</td><td class=text><strong>Depth</strong>: " + lastFrame.depth + " Inch."
					+ "</td></tr><td class=text colspan=5>"
					+ "<table align=right width=300>"
					+ "<tr>"
					+ "	<td class=text align=right>"
						+ "Side Look"
					+ "	</td>"
					+ "	<td class=text align=right>"
					+ "	Profile look"
					+ "	</td>"
					+ "	<td class=text align=right>"
					+ "	Front look"
					+ "	</td>"
					+ "</tr>"
					+ "<tr>"
						+ "<td class=text align=right>"
						+ "<img src=\"/images/frames/s/" + lastFrame.num + ".gif\">"
						+ "</td>"
						+ "<td class=text align=right>"
						+ "<img src=\"/images/frames/p/" + lastFrame.num + ".gif\">"
						+ "</td>"
						+ "<td class=text align=right>"
						+ "<img src=\"/images/frames/f/" + lastFrame.num + ".gif\">"
						+ "</td>"
					+ "</tr>"
					+ "</table>"
					+ "</tr><tr><td colspan=5 class=texto11 align=left><br>&nbsp;&nbsp;<a href='javascript:void(0)' onClick='javascript:window.close()'><span class=texto>Close Window</span></a>&nbsp;&nbsp;</td></tr></table>"
	
	try{
		var win = window.open("", "win", "width=430,height=200"); // a window object
		win.document.open("text/html", "replace");
		win.document.write("<HTML><HEAD><link href=\"/include/imagic.css\" rel=\"stylesheet\" media=\"screen, print\"><TITLE></TITLE></HEAD><BODY>"+ddd+"</BODY></HTML>");
		win.document.close();
	}
	catch(e){};
	$("noFrame").value = 0
	$("finish_frame").innerHTML = "מחיר"

	$("frameId").value = lastFrame.num

	setDimensionsDisplay()
	calculatePrice()
}

function clearFrame(remeberLast)
{
	var noFrame = $('noFrame').value = Math.abs($('noFrame').value-1)
	if(noFrame)
	{
		$("frame_tl").style.backgroundImage = "none"
		$("frame_t").style.backgroundImage = "none"
		$("frame_tr").style.backgroundImage = "none"
		$("frame_l").style.backgroundImage = "none"
		$("frame_r").style.backgroundImage = "none"
		$("frame_bl").style.backgroundImage = "none"
		$("frame_b").style.backgroundImage = "none"
		$("frame_br").style.backgroundImage = "none"
		$("finish_frame").innerHTML = "no"
	}
	$("frameId").value = ""
	$("frame_selected_cont").innerHTML = "Remove Frame"
	if(!remeberLast)
	{
		lastFrame.num		= null
		lastFrame.color		= null
		lastFrame.material	= ""
		lastFrame.width 	= 0
		lastFrame.price_a 	= 0
		lastFrame.price_b	= 0
		lastFrame.depth		= 0
		lastFrame.profile	= ""
	}
	setDimensionsDisplay()
	calculatePrice()
}

function framesFilter()
{
	var items 	= $("framesList").getElementsByTagName("td"),
		material= $("frame_filter_material").value,
		color	= $("frame_filter_color").value
	for(i=0; i<items.length; i++)
	{
		if((items[i].getAttribute("color") == color || !color) && (items[i].getAttribute("material") == material || !material))
			items[i].style.display = "list-item"
		else
			items[i].style.display = "none"
	}
}
/*
function framesFilter1()
{
	
	var ni = document.getElementById('framesList');
	ni.innerHTML="";
	var newdiv = document.createElement('tr');
		
	var items1 	= $("framesList").getElementsByTagName("td")
	for(i=0; i<items1.length; i++)
	{
		ni.removeChild(items1[i]);
	}
	
	var items 	= $("framesList1").getElementsByTagName("td"),
		material= $("frame_filter_material").value,
		color	= $("frame_filter_color").value
	for(i=0; i<items.length; i++)
	{
		if((items[i].getAttribute("color") == color || !color) && (items[i].getAttribute("material") == material || !material))
		{
			//items[i].style.display = "list-item"
			newdiv.appendChild(items[i]);
			//alert(items[i]);
		}
		if(i%8==0){
			ni.appendChild(newdiv);
			newdiv = document.createElement('tr');
		}
		//items1[i].style.display = "none"
		//ni.removeChild(items1[i]);
	}
	
	ni.appendChild(newdiv);
	
}
*/

//******************************************************************************
//******************************************************** PASPARTU FUNCTIOS ***
//******************************************************************************
function setPaspartuSize(type,size)
{
	if(isNaN(parseInt(size)))
		size = $("paspartu_" + type + "_width").value;
	if(size && !$("paspartu_" + type + "_colorId").value)
	{
		alert("Select color before size");
		$("paspartu_" + type + "_width").selectedIndex = 0;
		return;
	}
	$("paspartu_" + type).style.padding = (size*2) + "px"
	if(size)
		$("isWrap").checked = false
	setDimensionsDisplay()
	calculatePrice()
}

function setPaspartuColor(type,color)
{
	if(!color)
		color = $("paspartu_" + type + "_colorId").value;

	if(color)
		$("paspartu_" + type).style.backgroundColor = "#" + color.split(":")[0];
	else
		paspartuClear(type);
			
	window.focus();
}

function setPaspartuPattern(objRef,type,fileNum)
{
	if($("paspartu_" + type + "_colorId").disabled) 
		return	
	if(objRef)	
	{
		clearPaspartuPatternSelection(type)
		objRef.className = "selected"
	}
	if(fileNum)
	{
		$("paspartu_" + type).style.backgroundImage = "url(/images/paspartu/" + fileNum + ".gif)"
		$("paspartu_" + type + "_patternId").value = fileNum
	}
}
function clearPaspartuPatternSelection(type)
{ 
	$("paspartu_" + type).style.backgroundImage = "none"
	
	var images = $("paspartu_" + type + "_list").getElementsByTagName("IMG")
	for(i=0; i<images.length; i++)
		images[i].className = null	
	
	$("paspartu_" + type + "_patternId").value = ""
}
function setPasrpartuType(type)
{
	if(!type)
	{
		var types = document.mainForm.paspartuType
		for(i=0; i<types.length; i++)
		{
			if(types[i].checked)
			{
				type = types[i].value
				break
			}
		}
	}
	switch(type)
	{
		case "3d":
			paspartuClear('inner')
			$("paspartu_outer_cont").style.display = "block"
			$("paspartu_inner_cont").style.display = "none"
			$("paspartu_inner").style.border = "2px inset #d0d0d0"
		break
		case "print":
			$("paspartu_outer_cont").style.display = "block"
			$("paspartu_inner_cont").style.display = "block"
			$("paspartu_inner").style.border = "0px none"
		break
		case "none":
			paspartuClear('inner')	
			paspartuClear('outer')
			$("paspartu_outer_cont").style.display = "none"
			$("paspartu_inner_cont").style.display = "none"
			$("paspartu_inner").style.border = "0px none"
		break
	}
	setDimensionsDisplay()
	calculatePrice()
}

function paspartuClear(type)
{
	setPaspartuSize(type,0)
	$("paspartu_" + type).style.padding = "0px"
	$("paspartu_" + type).style.backgroundColor = "transparent"
	$("paspartu_" + type + "_colorId").selectedIndex = 0
	$("paspartu_" + type + "_width").selectedIndex = 0
	$("paspartu_" + type + "_patternId").value = ""
	setDimensionsDisplay()
	calculatePrice()
}

//******************************************************************************
//************************************************** DIMENSIONS CALCULATIONS ***
//******************************************************************************
function recalculateDimensions(fromId, toId)
{
	var newFromValue = parseInt($("print" + fromId).value) || 0
	if(newFromValue > V["maxFilePrint" + fromId])
	{
		//alert("בהתאם לרזולוציית התמונה שנטענה, גודל ההדפסה אינו יכול לחרוג מהערכים המקסימליים הבאים:\nגובה: " + V.maxFilePrintHeight  + "\nרוחב: " + V.maxFilePrintWidth + "\n" + "לתשומת ליבך – גודל התמונה יותאם אוטומטית לערכים המקסימליים שצויינו")
		alert("Your photo resolution allows enlarging for a maximum size of " + V.maxFilePrintWidth + " width and " + V.maxFilePrintHeight  + " height.\n Please note that the size of the width and height will be adjusted automatically to those values. ")
		$("print" + fromId).value = newFromValue = V["maxFilePrint" + fromId]
	}
	//im change
	//$("print" + toId).value = Math.round(newFromValue * (V["file" + toId]/V["file" + fromId]))
	setDimensionsDisplay()
	calculatePrice()
}

function setDimensionsDisplay()
{
	var pi  = ($("paspartu_inner_width").disabled ? 0:parseInt($("paspartu_inner_width").value)),
		po  = ($("paspartu_outer_width").disabled ? 0:parseInt($("paspartu_outer_width").value)),
		w = (parseInt($("printWidth").value) || V.maxFilePrintWidth) +  pi*2 + po*2 + lastFrame.width*2,
		h = (parseInt($("printHeight").value) || V.maxFilePrintHeight) + pi*2 + po*2 + lastFrame.width*2

	if($("isWrap").checked)
	{
		w -= 7
		h -= 7
	}

	//$("dimensionsDisplay_width").innerHTML = " <span>" + w +"</span> ס\"מ "
	//$("dimensionsDisplay_height").innerHTML = " <span>"	+ h	+ "</span> ס\"מ "
	
	$("finish_printDimensions").innerHTML = $("printWidth").value + " X " + $("printHeight").value
}

//******************************************************************************
//******************************************************* PRICE CALCULATIONS ***
//******************************************************************************
function calculatePrice()
{
	var price				= 0,
		materials 			= document.mainForm.printMaterial,
		frameId				= parseInt($("frameId").value),
		picPrice			= parseFloat($("picPrice").value)	|| 0,
		w 					= parseInt($("printWidth").value) 	|| 0,
		h 					= parseInt($("printHeight").value) 	|| 0,
		effectPrice			= $("effectId").disabled 	|| !parseInt($("effectId").checked) ? 0:V.effectPrice,
		paspartuSize		= ($("paspartu_inner_width").disabled ? 0:parseInt($("paspartu_inner_width").value)) + ($("paspartu_outer_width").disabled ? 0:parseInt($("paspartu_outer_width").value)),
		laminationPrice		= 0,
		onKapaPrice 		= 0,
		materialPrice		= 0,	
		framePrice			= 0,
		strechPrice			= 0,
		paspartuPrice		= 0

	for(i=0; i<	materials.length; i++)
	{
		if(materials[i].checked)
		{
			var materialPrice_a = V["priceParameter_a_" + materials[i].value],
				materialPrice_b = V["priceParameter_b_" + materials[i].value]
			break
		}
	}
//################################################### CALCULATE CANVAS PRICE ###
//******************************************************************************
//רוחב כפול גובה חלקי 10000 לקבלת שטח במטר מרובע כפול מחיר רץ של החומר ועוד מחיר בסיס
//------------------------------------------------------------------------------
	if(w && h)
		materialPrice = w * h / 10000 * materialPrice_a + materialPrice_b

//#################################################### CALCULATE FRAME PRICE ###
//******************************************************************************
//רוחב ועוד גובה חלקי 100 וכפול 2 כדי לקבל הקף במטרים כפול מחיר רץ של המסגרת ועוד מחיר בסיס
//------------------------------------------------------------------------------
	framePrice = (w + h) / 100 * 2 * lastFrame.price_a + lastFrame.price_b
	if(paspartuSize)
		framePrice	+= paspartuSize / 100 * 8 * lastFrame.price_a 

//################################################### CALCULATE STRECH PRICE ###
//******************************************************************************
//רוחב ועוד גובה חלקי 100 וכפול 2 כדי לקבל הקף במטרים כפול מחיר רץ של המתיחה ועוד מחיר בסיס
//------------------------------------------------------------------------------
	if(!$("isStrech").disabled && $("isStrech").checked)
	{
		strechPrice = (w + h) / 100 * 2 * V.priceParameter_a_strech + V.priceParameter_b_strech
		if(paspartuSize)
			strechPrice  += paspartuSize * 8 / 100 * V.priceParameter_a_strech
	}

//################################################### CALCULATE ONKAPA PRICE ###
//******************************************************************************
//רוחב כפול גובה חלקי 10000 לקבלת שטח במטר מרובע כפול מחיר רץ של קאפה
//ועוד שטח פספרטו, אם קיים, כפול מחיר קאפה
//------------------------------------------------------------------------------
	if(!$("isOnKapa").disabled && $("isOnKapa").checked)
	{	
		onKapaPrice = w * h / 10000 * V.onKapaPrice
		if(paspartuSize)
			onKapaPrice += (2 * paspartuSize * (w + h) + 4 * paspartuSize * paspartuSize) / 10000 * V.onKapaPrice
	}
//******************************************************************************

//############################################### CALCULATE LAMINATION PRICE ###
//******************************************************************************
//רוחב כפול גובה חלקי 10000 לקבלת שטח במטר מרובע כפול מחיר רץ של למינציה
//ועוד שטח פספרטו, אם קיים, כפול מחיר למינציה
//------------------------------------------------------------------------------
	if(!$("isLamination").disabled && $("isLamination").checked)
	{	
		laminationPrice = w * h / 10000 * V.laminationPrice
		if(paspartuSize)
			laminationPrice += (2 * paspartuSize * (w + h) + 4 * paspartuSize * paspartuSize) / 10000 * V.laminationPrice
	}
//******************************************************************************

//################################################# CALCULATE PASPARTU PRICE ###
//******************************************************************************
//פספרטו בריבוע כפול 4 לחישוב שטח הפינות ועוד אורך פלוס רוחב כפול פספרטו כפול 2 
//לחישוב יתרת השטח הכולל של פספרטו חלקי 10000 לקבלת מטר מרובע 
//כל זה כפול מחיר מטר רץ של החומר
//------------------------------------------------------------------------------
	if(paspartuSize)
		paspartuPrice = (2 * paspartuSize * (w + h) + 4 * paspartuSize * paspartuSize) / 10000 * materialPrice_a
//******************************************************************************

//#################################################################### TOTAL ###
	price = materialPrice + framePrice + paspartuPrice + strechPrice 
			+ effectPrice + laminationPrice + onKapaPrice + picPrice
//******************************************************************************

//################################################################## DISPLAY ###
	$("finish_material_price").innerHTML = materialPrice ? renderPrice(materialPrice):""
	$("finish_frame").innerHTML = framePrice ? renderPrice(framePrice):"no"
	$("finish_strech").innerHTML = strechPrice ? renderPrice(strechPrice):"no"
	$("finish_paspartu").innerHTML = paspartuPrice ? renderPrice(paspartuPrice):"no"
	$("finish_onkapa").innerHTML = onKapaPrice ? renderPrice(onKapaPrice):"no"
	$("finish_lamination").innerHTML = laminationPrice ? renderPrice(laminationPrice):"no"
	$("unitPrice").value = price.toFixed(2)
	$("finish_unitPrice").innerHTML = renderPrice(price)
//******************************************************************************
	
	calculateFinishTotal()
}
function calculateFinishTotal()
{
	var price = $("unitPrice").value * $("finish_copies").value
	$("finish_total").innerHTML = renderPrice(price)
}
function calculatePriceAddition(amount,state)
{
	if(state !== -1 && state !== 1)
		state = state ? 1:-1
	calculatePrice(amount*state)
}
//******************************************************************************
//******************************************************** SUPPORT FUNCTIONS ***
//******************************************************************************	
function toggleTabs(num)
{
	if(window.lastTabNum == num || !stepValidator())
		return

	var tablinks = $("tabs_menu").getElementsByTagName("SPAN"),
		tabconts = $("tabs").childNodes
	
	//im change
	for(i=0;i<5;i++){
		tabconts = $("tabcont_"+(i+1))
		if(i!=num){
			tabconts.style.display = "none";
			$("tab_"+(i+1)).style.backgroundImage = "url(http://magnipic.co.uk/images/progress-button.gif)"
		}
		else{
			tabconts.style.display = "block";
			$("tab_"+(i+1)).style.backgroundImage = "url(http://magnipic.co.uk/images/progress-button1-gray.gif)"
		}
	}
	/*
	if(!isNaN(window.lastTabNum))
	{
		//tablinks[window.lastTabNum].style.backgroundImage = "url(none)"
		//tablinks[window.lastTabNum].style.color = "#ffffff"
		tabconts[window.lastTabNum].style.display = "none"
	}
	//tablinks[num].style.backgroundImage = "url(/images/canvas/tabs/" + (num+1) + "_on.gif)"
	//tablinks[num].style.color = "#000000"
	tabconts[num].style.display = "block"	
	*/
	window.lastTabNum = num
}
function doSubmit()
{
	if(stepValidator(0) && stepValidator(1) && stepValidator(2) && stepValidator(3) && stepValidator(4))
		document.mainForm.submit()
}
function stepValidator(num)
{
	num = num || window.lastTabNum
	switch(num)
	{
		case 0:
			var h = parseInt($("printHeight").value),
				w = parseInt($("printWidth").value)
			if(!h || !w)
			{
				alert("Please enter your desired width or height")

				if(!w)
					$("printWidth").focus()
				else
					$("printHeight").focus()
					
				return false
			}
			if(w > V.maxFilePrintWidth || h > V.maxFilePrintHeight)
			{
				//alert("בהתאם לרזולוציית התמונה שנטענה, גודל ההדפסה אינו יכול לחרוג מהערכים המקסימליים הבאים:\nגובה: " + V.maxFilePrintHeight  + "\nרוחב: " + V.maxFilePrintWidth + "\n" + "לתשומת ליבך – גודל התמונה יותאם אוטומטית לערכים המקסימליים שצויינו")
				//alert("Your photo resolution allows enlarging for a maximum size of " + V.maxFilePrintWidth + " width and " + V.maxFilePrintHeight  + " height.\n Please note that the size of the width and height will be adjusted automatically to those values. ")
				msg="Image's resolution allows enlarging to the following maximum dimensions:  \n"
				+" Height: " + V.maxFilePrintHeight  + "\n"
				+" Width: " + V.maxFilePrintWidth + "\n"
				+" Please note - picture's size will be adjusted automatically to these dimensions" ;
				alert(msg);//alert("Your photo resolution allows enlarging for a maximum size of " + V.maxFilePrintWidth + " width and " + V.maxFilePrintHeight  + " height.\n Please note that the size of the width and height will be adjusted automatically to those values. ")
				$("printWidth").value = V.maxFilePrintWidth
				$("printHeight").value = V.maxFilePrintHeight
				setDimensionsDisplay()
				calculatePrice()
				toggleTabs(0)
				return false
			}
			if(w < V.minPrintWidth || h < V.minPrintHeight)
			{
				//alert("גודל הדפסה אינו יכול להיות קטן מערכים המינלים\nרוחב: " + V.minPrintWidth  + "\nגובה: " + V.minPrintHeight + "\n" + "לתשומת ליבך – גודל התמונה יותאם אוטומטית לערכים המינמליים שצויינו")
				//alert("Please note - we are displaying only a preview of the processed picture in order to avoid the time required for the process. The final result is sharper and has much more details.")
				msg="Minimum Picture's dimensions are as follows: \n"
				+" Height: " + V.minPrintHeight  + "\n"
				+" Width: " + V.minPrintWidth + "\n"
				+" Please note - picture's size will be adjusted automatically to these dimensions" ;
				alert(msg);
				if(V.maxFilePrintWidth < V.maxFilePrintHeight)
				{
					$("printWidth").value = V.minPrintWidth				
					recalculateDimensions("Width", "Height")
				}
				else
				{
					$("printHeight").value = V.minPrintHeight
					recalculateDimensions("Height", 'Width')
				}
				setDimensionsDisplay()			
				calculatePrice()
				toggleTabs(0)
				return false
			}
		break
		case 1:
			/*** NO VALIDATION ***/
		break
		case 2:
			var materials = document.mainForm.printMaterial,
				material = ""
			for(i=0; i<	materials.length; i++)
			{
				if(materials[i].checked)
				{
					material = materials[i].value
					break
				}
			}
			if(!$("printSurfaceFinish_gloss").checked && !$("printSurfaceFinish_mat").checked && material!="canvas")
			{
				alert("Please choose your desired treatment - glossy or matt.")
				toggleTabs(2)
				return false
			}
		break
		case 3:
			var ici = $("paspartu_inner_colorId").selectedIndex,
				iwi = $("paspartu_inner_width").selectedIndex,
				oci	= $("paspartu_outer_colorId").selectedIndex,
				owi	= $("paspartu_outer_width").selectedIndex

			if(!(oci == 0 && owi == 0) && !(oci != 0 && owi != 0))
			{
				alert("Please choose top mat width, or remove mat")
				toggleTabs(3)
				return false
			}

			if(!(ici == 0 && iwi == 0) && !(ici != 0 && iwi != 0))
			{
				alert("Please choose mat width, or remove mat")
				toggleTabs(3)
				return false
			}
		break
		case 4:
		break
	}
	return true
}
function nubersOnlyType(e)
{
	var keyCode	= e.keyCode
		
	if(!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105) && keyCode != 8 && keyCode != 9 && keyCode != 46)
		return false
	
	return true
}
function zoom()
{
	open("/canvas/zoom.asp?oi=" + $("imgId").value
		+"&piw=" + $("paspartu_inner_width").value
		+"&pow=" + $("paspartu_outer_width").value
		+"&pic=" + $("paspartu_inner_colorId").value.split(":")[0]
		+"&poc=" + $("paspartu_outer_colorId").value.split(":")[0]
		+"&wc=" + $("wall").style.backgroundColor.replace(/#/,"")
		+"&fn=" + lastFrame.num
		+"&ei=" + $("effectId").value
		,'win','width=200,height=100,scrollbars=no')
}
function displayPic()
{
	displayPicInterval = setInterval("doDisplayPic()",50)
	displayPicValue = -5
}
function doDisplayPic()
{
	$("frame_table").style.opacity = displayPicValue/100
	$("frame_table").style.filter = "alpha(opacity=" + window.displayPicValue + ")"
	
	displayPicValue += 5
	if(displayPicValue > 100)
		clearInterval(displayPicInterval)		
}
//******************************************************************************
//***************************************************** WALL COLOR FUNCTIONS ***
//******************************************************************************
function setWallColor(c)
{
	$("wall").style.backgroundColor = c
}

function toggleWallColorDialog()
{
	//$("wallColorDialogWrapper").style.visibility = $("wallColorDialogWrapper").style.visibility == "visible" ? "hidden":"visible"
	$("wallColorDialogWrapper").style.display = $("wallColorDialogWrapper").style.display == "block" ? "none":"block"
}

//************************************************************* COLOR PICKER ***
var eventListeners = []
myAddEventListener(window, 'unload', cleanupEventListeners)
function hexToRgb(hex_string, default_)
{
    if (default_ == undefined)
    {
        default_ = null;
    }
    if (hex_string.substr(0, 1) == '#')
    {
        hex_string = hex_string.substr(1);
    }
    var r;
    var g;
    var b;
    if (hex_string.length == 3)
    {
        r = hex_string.substr(0, 1);
        r += r;
        g = hex_string.substr(1, 1);
        g += g;
        b = hex_string.substr(2, 1);
        b += b;
    }
    else if (hex_string.length == 6)
    {
        r = hex_string.substr(0, 2);
        g = hex_string.substr(2, 2);
        b = hex_string.substr(4, 2);
    }
    else
    {
        return default_;
    }
    r = parseInt(r, 16);
    g = parseInt(g, 16);
    b = parseInt(b, 16);
    if (isNaN(r) || isNaN(g) || isNaN(b))
    {
        return default_;
    }
    else
    {
        return {r: r / 255, g: g / 255, b: b / 255};
    }
}
function rgbToHex(r, g, b, includeHash)
{
    r = Math.round(r * 255);
    g = Math.round(g * 255);
    b = Math.round(b * 255);
    if (includeHash == undefined)
    {
        includeHash = true;
    }
    r = r.toString(16);
    if (r.length == 1)
    {
        r = '0' + r;
    }
    g = g.toString(16);
    if (g.length == 1)
    {
        g = '0' + g;
    }
    b = b.toString(16);
    if (b.length == 1)
    {
        b = '0' + b;
    }
    return ((includeHash ? '#' : '') + r + g + b).toUpperCase();
}
function trackDrag(node, handler)
{
    function fixCoords(x, y)
    {
        var nodePageCoords = pageCoords(node);
        x = (x - nodePageCoords.x) + document.documentElement.scrollLeft;
        y = (y - nodePageCoords.y) + document.documentElement.scrollTop;
        if (x < 0) x = 0;
        if (y < 0) y = 0;
        if (x > node.offsetWidth - 1) x = node.offsetWidth - 1;
        if (y > node.offsetHeight - 1) y = node.offsetHeight - 1;
        return {x: x, y: y};
    }
    function mouseDown(ev)
    {
        var coords = fixCoords(ev.clientX, ev.clientY);
        var lastX = coords.x;
        var lastY = coords.y;
        handler(coords.x, coords.y);
        function moveHandler(ev)
        {
            var coords = fixCoords(ev.clientX, ev.clientY);
            if (coords.x != lastX || coords.y != lastY)
            {
                lastX = coords.x;
                lastY = coords.y;
                handler(coords.x, coords.y);
            }
        }
        function upHandler(ev)
        {
            myRemoveEventListener(document, 'mouseup', upHandler);
            myRemoveEventListener(document, 'mousemove', moveHandler);
            myAddEventListener(node, 'mousedown', mouseDown);
        }
        myAddEventListener(document, 'mouseup', upHandler);
        myAddEventListener(document, 'mousemove', moveHandler);
        myRemoveEventListener(node, 'mousedown', mouseDown);
        if (ev.preventDefault) ev.preventDefault();
    }
    myAddEventListener(node, 'mousedown', mouseDown);
    node.onmousedown = function(e) { return false; };
    node.onselectstart = function(e) { return false; };
    node.ondragstart = function(e) { return false; };
}
function findEventListener(node, event, handler)
{
    var i;
    for (i in eventListeners)
    {
        if (eventListeners[i].node == node && eventListeners[i].event == event
         && eventListeners[i].handler == handler)
        {
            return i;
        }
    }
    return null;
}
function myAddEventListener(node, event, handler)
{
    if (findEventListener(node, event, handler) != null)
    {
        return;
    }
    if (!node.addEventListener)
    {
        node.attachEvent('on' + event, handler);
    }
    else
    {
        node.addEventListener(event, handler, false);
    }
    eventListeners.push({node: node, event: event, handler: handler});
}
function removeEventListenerIndex(index)
{
    var eventListener = eventListeners[index];
    delete eventListeners[index];
    if (!eventListener.node.removeEventListener)
    {
        eventListener.node.detachEvent('on' + eventListener.event,
                                       eventListener.handler);
    }
    else
    {
        eventListener.node.removeEventListener(eventListener.event,
                                               eventListener.handler, false);
    }
}
function myRemoveEventListener(node, event, handler)
{
    removeEventListenerIndex(findEventListener(node, event, handler));
}
function cleanupEventListeners()
{
    var i;
    for (i = eventListeners.length; i > 0; i--)
    {
        if (eventListeners[i] != undefined)
        {
            removeEventListenerIndex(i);
        }
    }
}
function hsvToRgb(hue, saturation, value)
{
    var red;
    var green;
    var blue;
    if (value == 0.0)
    {
        red = 0;
        green = 0;
        blue = 0;
    }
    else
    {
        var i = Math.floor(hue * 6);
        var f = (hue * 6) - i;
        var p = value * (1 - saturation);
        var q = value * (1 - (saturation * f));
        var t = value * (1 - (saturation * (1 - f)));
        switch (i)
        {
            case 1: red = q; green = value; blue = p; break;
            case 2: red = p; green = value; blue = t; break;
            case 3: red = p; green = q; blue = value; break;
            case 4: red = t; green = p; blue = value; break;
            case 5: red = value; green = p; blue = q; break;
            case 6: // fall through
            case 0: red = value; green = t; blue = p; break;
        }
    }
    return {r: red, g: green, b: blue};
}
function rgbToHsv(red, green, blue)
{
    var max = Math.max(Math.max(red, green), blue);
    var min = Math.min(Math.min(red, green), blue);
    var hue;
    var saturation;
    var value = max;
    if (min == max)
    {
        hue = 0;
        saturation = 0;
    }
    else
    {
        var delta = (max - min);
        saturation = delta / max;
        if (red == max)
        {
            hue = (green - blue) / delta;
        }
        else if (green == max)
        {
            hue = 2 + ((blue - red) / delta);
        }
        else
        {
            hue = 4 + ((red - green) / delta);
        }
        hue /= 6;
        if (hue < 0)
        {
            hue += 1;
        }
        if (hue > 1)
        {
            hue -= 1;
        }
    }
    return {
        h: hue,
        s: saturation,
        v: value
    };
}
function pageCoords(node)
{
    var x = node.offsetLeft;
    var y = node.offsetTop;
    var parent = node.offsetParent;
    while (parent != null)
    {
        x += parent.offsetLeft;
        y += parent.offsetTop;
        parent = parent.offsetParent;
    }
    return {x: x, y: y};
}
function makeColorSelector(startColor,sufix,setColorId,setValueId)
{
	//alert(setColorId);
	//alert(setValueId);
    var rgb, 
		hsv,
		startColor			= startColor || "FFFFFF",
		sufix				= sufix || "",
		colorSelectorDiv 	= this,
		satValDiv 			= $("colorPicker_palletBG" + sufix),
	    crossHairs			= $("colorPicker_crosshair" + sufix),
		huePos				= $("colorPicker_colorScroll_arrows" + sufix),
		hueDiv 				= $("colorPicker_colorScroll_cont" + sufix)
    trackDrag(satValDiv, satValDragged)	
    trackDrag(hueDiv, hueDragged)
   	setNewColor(startColor)
    function colorChanged()
    {
        var hex 		= rgbToHex(rgb.r, rgb.g, rgb.b),
        	hueRgb 		= hsvToRgb(hsv.h, 1, 1),
        	hueHex 		= rgbToHex(hueRgb.r, hueRgb.g, hueRgb.b)
	    if(setColorId)
			$(setColorId).style.background = hex
		if(setValueId)
			$(setValueId).value = hex
        satValDiv.style.background = hueHex;
        crossHairs.style.left = ((hsv.v*199)-10).toString() + 'px'
        crossHairs.style.top = (((1-hsv.s)*199)-10).toString() + 'px'
        huePos.style.top = ((hsv.h*199)-5).toString() + 'px'
    }
    function rgbChanged()
    {
        hsv = rgbToHsv(rgb.r, rgb.g, rgb.b)
        colorChanged()
    }
    function hsvChanged()
    {
        rgb = hsvToRgb(hsv.h, hsv.s, hsv.v)
        colorChanged()
    }
	function satValDragged(x, y)
    {
        hsv.s = 1-(y/199);
        hsv.v = (x/199);
        hsvChanged();
    }
    function hueDragged(x, y)
    {
        hsv.h = y/199;
        hsvChanged();
    }
    function setNewColor(color)
    {
        rgb = hexToRgb(color, {r: 0, g: 0, b: 0});
        rgbChanged();
    }
}                 