// this file contains al methods for the store
// copyright by RomanticRoad e.k., Munich  All Rights Reserved

// this is are global arrays that holds the store's data

/* product constructor: encapsulates one product 
   Parameters:
   		@description: a description of the article
		@artnr: the article's number assigned by the shop owner
		@price: the unit price of the article
*/ 

function Product( description, artnr, pricestr )
{
	var pricedec = pricestr.replace(",",".");
	var price = parseFloat(pricedec);
	this.pricestr = pricestr;
	this.price = price;
	this.artnr = artnr;
	this.description = description;
	this.qty = 0;
}

function genProduct(prodObj,prodnum)
{
	var  prodimg =   "../../../images_shop/" +   prodObj.artnr +   ".jpg";
	var  prodqty = "qty_" + prodnum; 
	var  storeq  = "storeQty(" + prodnum + ")";	
	var prodyy =  "opener.products[" + prodnum + "]";
			
	if (prodObj.artnr != "blank")
	{
	document.write("<table cellpadding='5' cellspacing='5'  width='600'><tr><td align='center' valign='top' width='120'>" +  "\n" +
	"<a href='javascript:void(0)'  onClick='popBig(" + prodyy + ")'  ><img src='" + prodimg + "'  width='100'  class='prodpic' border='1' /></a></td>" + "\n" +
	"<td align='left'  valign='middle' >" + prodObj.description + "<br />" + prodObj.artnr + "<br /><br />" + prodObj.pricestr + " &euro;" +  
	"<p class='form'>Quantity  &nbsp; <input name='" + prodqty + "' type='text' size='2'  onChange='" + storeq + "'  /></p></td></tr></table><br /><br />");
	}
}

function popBig(prodObjx)
{
	var pgtitle = "Griefenkunst Shop " + prodObjx.artnr;
	var class1 = "store";
	var dwinw = 550;
	var dwinh = 570;
	var imgbig =  "../../../images_shop/" +   prodObjx.artnr +   "big.jpg";

	winThree = window.open("","bigPic","width=" + dwinw + ",height=" + dwinh + ",left=0,top=0,status=no");

	winThree.document.write("<html><head><title>" + pgtitle + "</title><link rel='stylesheet' href='../storename.css' type='text/css' /></head>"  + "\n" + 
	"<body class='" + class1 + "'  onLoad='this.focus();' ><div align='center'>"  + "\n" + 
	"<img src='" + imgbig + "'  class='prodpic' />");  + "\n"; 
	winThree.document.write("<form><table border='0'><tr><td align='center'><input type='button' onClick='self.close();' " + 
	"onMouseOver='this.value=\"Window\"' onMouseOut='this.value=\"  Close  \"' class='" + class1 + "' value='  Close  ' /></td></tr></table>" +
	 "</form></div></body></html>");
	winThree.document.close();
}


// method returns the text to be contained in the mail for one ordered item
function getMailText ( p )
{
	return 	p.qty + " x " + 
			p.artnr + ", " + 
			p.description + " - " + 
			formatNumber( p.price, 2, '.') + " EUR = " + 
			formatNumber( eval(p.qty * p.price), 2, '.') + " EUR";
}
function setShipping ( s )
{
	opener.purchaser["shipping"] = s;
	document.forms[0].elements['shipping'].value=formatNumber(s,2,'.');
}
function getShipping ()
{
	if( opener.purchaser["shipping"] ) {
		return opener.purchaser["shipping"];
	}
	else {
		return opener.shippingDefault;
	}
}


/* open a new  window centered on the user's screen */
function openCentered( url, width, height, options )
{
	/*gets top and left positions based on user's resolution so window is centered.*/
	leftPos = (window.screen.width/2) - (width/2 + 10);
	topPos = (window.screen.height/2) - (height/2 + 25);
	
	var win2 = window.open( url,"OrderForm", "width=" + width + ",height=" + height +",left=" + leftPos + 
			",top=" + topPos + ", screenX=" + leftPos + ",screenY=" + topPos + "," + options );

	win2.focus();
}


// the productId has to correspond with the number in the products.js
function storeQty( productId ) 
{
	
	// read the quantity
	var fieldName = "qty_" + productId;
	var qtyfield = document.forms[0].elements[fieldName];
	var cq = qtyfield.value;
	
	// remove leading zeros
	while ((cq.charAt(0) == "0")  && (cq.length > 1))
	{
		cq = cq.substring(1);
	}
	cq = cq.substring(0,3);

	if( cq < 0 ) {
		alert("Eingabe nicht zulässig.");
		cq = 0;
	}
	
	// write the corrected amount back
	qtyfield.value = cq;
	
	// save quantity in opener
	opener.products[productId].qty = cq;
	
	// document.forms[0].total.value = "re-sum";
}

// stores purchaser info
function storePur( propertyName )
{
	var fieldName = "pur_" + propertyName;
	with( document.forms[0] )
	{
		// type == "radio" || elements[fieldName].type == "checkbox"
		if( elements[fieldName].length > 0 )
		{
			for( i=0; i<elements[fieldName].length; i++)
			{
				if( elements[fieldName][i].checked == true )
				{
					opener.purchaser[propertyName] = elements[fieldName][i].value;
				}
			}
		}
		else
		{
			opener.purchaser[propertyName] = elements[fieldName].value;
		}
	}
}

// inits checkout form
function initCheckOut( )
{
	// init purchaser info
	with( document.forms[0] )
	{
		for( i=0; i<elements.length; i++)
		{
			// elements[i].name loops through all form-element-names
			var eltName = elements[i].name;
			if( eltName.indexOf("pur_") >= 0 )
			{
				// determine the propertyname from the form-element-name
				var propertyName = eltName.substr( 4, eltName.length - 4 );
				// restore the property value
					// handle radio buttons
					if( elements[i].type == "radio" )
					{
						if ( opener.purchaser[propertyName] )
						{
							// set the selected attribute if the value fits
							if( elements[i].value == opener.purchaser[propertyName] )
							{
								elements[i].checked=true;
							}
						}
					}
					// handle text fields
					else if( elements[i].type == "text" )
					{
						if ( opener.purchaser[propertyName] )
							elements[i].value = opener.purchaser[propertyName];
						else
							elements[i].value = "";
						
					}
			}
		}
	}
	this.focus();

}

// delete purchaser info
function clearCheckOut( )
{
	opener.purchaser = new Array();
	initCheckOut();
}

// update totals
function updateTotals()
{
	var mailText=""; // This is the productlist, that will be contained in the ordermail.

	with( document.forms[0] )
	{
		var sum = 0;
		for( i=0; i<elements.length; i++)
		{
			// elements[i].name loops through all form-element-names
			var eltName = elements[i].name;
			if( eltName.indexOf("qty_") >= 0 )
			{
				// determine the product's id from the form-element-name
				var productId = eltName.substr( 4, eltName.length - 4 );
				var p = opener.products[productId];
				// recalc total for product
				var totalName="tot_"+i;
				// set product total
				elements[i+1].value = formatNumber( p.qty * p.price, 2, '.' ); 
				sum += p.qty * p.price;
				//alert( totalName + "=" + elements[i+1].value );
				
				// get new mailtext
				mailText = mailText + getMailText ( p ) + "\n";
			}
		}
		sum += getShipping();
		// set total
		elements['total'].value = formatNumber( sum, 2, '.' );
		// set mailtext
		elements['mailtext'].value = mailText;
	}
}

/* print products
	Parameter:
	@printAll: if this is true, the function prints all products, even those with qty==0
 */
function printOrder( printAll )
{

	var sum=0;
	var rownum=0;
	var mailText=""; // This is the productlist, that will be contained in the ordermail.
	
	for( i=0; i<opener.products.length; i++ )
	{
		var p = opener.products[i];
		if( p.qty > 0 || printAll==true )
		{
			var bgClass = "COrowEven";
			if( rownum++ % 2 == 0 ) 
			{ 
				bgClass = "COrowOdd";
			}
			
			document.writeln("<tr class='" + bgClass + "'>");
			document.writeln( "<td>" + p.artnr + "&nbsp;</td>" +
				
			"<td valign='top' class='COdescription'>" + p.description + "&nbsp;</td>" +
			"<td valign='top' class='COprice'>" + formatNumber( p.price, 2, '.' ) + "&euro;&nbsp; </td>" +
			"<td valign='top' class='COqty'><input type='text' class='COqty' name='qty_" + i + "' value='" + p.qty + "' size='2' " +
			"onChange='storeQty(" + i + ");updateTotals();'></td>" +
			"<td valign='top' class='COrowTotal'><input type='text' class='COrowTotal' name='tot_" + i + 
			"' value='" + formatNumber( eval(p.qty * p.price), 2,'.') + "' size='5' onFocus='blur()'> &euro;</td>");

			
			mailText = mailText + getMailText ( p ) + "\n";
			
			document.writeln("</tr>");
			// sum up the sum
			sum += p.qty * p.price;
			
		}
	}

	// any items orderd?
	if( rownum>0 )
	{
		// the contents of this hidden field will be contained in the email
		document.writeln("<input type='hidden' name='mailtext' value='"+ mailText +"'>");

		// shipping
		document.writeln("<tr class='COtotal'>");
		document.writeln( "<td colspan='4' align='right'><b>Shipping Costs:</b></td>" );
		document.writeln( "<td class='COtotal'><input align='right' type='text' name='shipping' class='COtotal' value='" + formatNumber( getShipping(), 2, '.') + "' size='5' onFocus='blur()'> &euro;</td>");
		document.writeln("</tr>");		
		sum += getShipping();

		// complete total
		document.writeln("<tr class='COtotal'>");
		document.writeln( "<td colspan='4' align='right'><b>Total:</b></td>" );
		document.writeln( "<td class='COtotal'><input align='right' type='text' name='total' class='COtotal' value='" + formatNumber( sum, 2, '.') + "' size='5' onFocus='blur()'> &euro;</td>");
		document.writeln("</tr>");
	}
	else
	{
		document.writeln("<tr class='COtotal'>");
		document.writeln( "<td colspan='5' align='center'><strong>No Items Ordered</strong></td>" );
		document.writeln("</tr>");	
	}
}
// restore the quantity from the products array
function initForm()
{

	with( document.forms[0] )
	{
		for( i=0; i<elements.length; i++)
		{
			// elements[i].name loops through all form-element-names
			var eltName = elements[i].name;
			if( eltName.indexOf("qty_") >= 0 )
			{
				// determine the product's id from the form-element-name
				var productId = eltName.substr( 4, eltName.length - 4 );
				// restore the ordered quantity
				elements[i].value = opener.products[productId].qty;
			}
		}
	}
	this.focus();
}
// check if the required fields are set
function checkForm()
{
	var p = opener.purchaser;
	var errors="";

	// check if all the fields above are there
	for( var property in opener.reqFields )
	{
		if( !p[property] || p[property]=="" )
		{
			errors += "The field " + opener.reqFields[property] + " needs a value.\n";
		}
	}
	if ( errors != "" )
	{
		alert(errors);
		return false;
	}
	
	if ( !document.forms[0].total || document.forms[0].total.value == 0 )
	{
		alert("Please check your order.")
		return false;
	}
	// order is ok!!
	return true;
}

// print the order
function winPrint()
{
	if( checkForm() )
	{
		window.print();
	}
}

// Utility functions ...

// since JavaScript doesn't include a formatnumbers we use this one ...
function formatNumber(Number,Decimals,Separator)
{
 // **********************************************************
 // Placed in the public domain by Affordable Production Tools
 // March 21, 1998
 // Web site: http://www.aptools.com/
 //
 // November 24, 1998 -- Error which allowed a null value
 // to remain null fixed. Now forces value to 0.
 //
 // October 28, 2001 -- Modified to provide leading 0 for fractional number
 // less than 1.
 //
 // This function accepts a number to format and number
 // specifying the number of decimal places to format to. May
 // optionally use a separator other than '.' if specified.
 //
 // If no decimals are specified, the function defaults to
 // two decimal places. If no number is passed, the function
 // defaults to 0. Decimal separator defaults to '.' .
 //
 // If the number passed is too large to format as a decimal
 // number (e.g.: 1.23e+25), or if the conversion process
 // results in such a number, the original number is returned
 // unchanged.
 // **********************************************************
 Number += ""          // Force argument to string.
 Decimals += ""        // Force argument to string.
 Separator += ""       // Force argument to string.
 if((Separator == "") || (Separator.length > 1))
  Separator = "."
 if(Number.length == 0)
  Number = "0"
 var OriginalNumber = Number  // Save for number too large.
 var Sign = 1
 var Pad = ""
 var Count = 0
 // If no number passed, force number to 0.
 if(parseFloat(Number)){
  Number = parseFloat(Number)} else {
  Number = 0}
 // If no decimals passed, default decimals to 2.
 if((parseInt(Decimals,10)) || (parseInt(Decimals,10) == 0)){
  Decimals = parseInt(Decimals,10)} else {
  Decimals = 2}
 if(Number < 0)
 {
  Sign = -1         // Remember sign of Number.
  Number *= Sign    // Force absolute value of Number.
 }
 if(Decimals < 0)
  Decimals *= -1    // Force absolute value of Decimals.
 // Next, convert number to rounded integer and force to string value.
 // (Number contains 1 extra digit used to force rounding)
 Number = "" + Math.floor(Number * Math.pow(10,Decimals + 1) + 5)
 if((Number.substring(1,2) == '.')||((Number + '')=='NaN'))
  return(OriginalNumber) // Number too large to format as specified.
 // If length of Number is less than number of decimals requested +1,
 // pad with zeros to requested length.
 if(Number.length < Decimals +1) // Construct pad string.
 {
  for(Count = Number.length; Count <= Decimals; Count++)
   Pad += "0"
 }
 Number = Pad + Number // Pad number as needed.
 if(Decimals == 0){
  // Drop extra digit -- Decimal portion is formatted.
  Number = Number.substring(0, Number.length -1)} else {
  // Or, format number with decimal point and drop extra decimal digit.
 Number = Number.substring(0,Number.length - Decimals -1) +
          Separator +
          Number.substring(Number.length - Decimals -1,
          Number.length -1)}
 if((Number == "") || (parseFloat(Number) < 1))
  Number="0"+Number // Force leading 0 for |Number| less than 1.
 if(Sign == -1)
  Number = "-" + Number  // Set sign of number.

Number = Number.replace(".",",")
 return(Number)
}
