// Javascripts for the BreezeBrowser "EOS" template

// Read parameters from URL
var parsed = window.location.search.substring(1)
var order  = getParm(parsed,"order")
var page   = getParm(parsed,"page")
var slide  = getParm(parsed,"slide")
var delay  = getParm(parsed,"delay")
var printme= getParm(parsed,"print")

// various
var maxItemLength = (item.length>specialItem.length) ? item.length : specialItem.length
bgcolor_topFrame	= "#A4A1A1"
bgcolor_checkout	= "#605F5F"
bgcolor_printPage	= "#ffffff; background-image:none"
var onMouseOver = "this.style.backgroundColor='#ffffff'"
var onMouseOut  = "this.style.backgroundColor=''"
var itemQty = new Array()
var TextFile = ""
var TagFile  = ""
var subTotal = 0
var totalVal = 0
var percentDiscountByTotal = 0
var returnLink = ""	// not used
if(delay == "") delay = defaultDelay
// address formatting (ZIP code first or last)
if(addr_format == "zcs") {		// zip code   city
	var zip_del   = " "
	var city_del  = "\n"
	var state_del = "\n"
} else {				// city, ST   zip code
	var city_del  = ", "
	var state_del = " "
	var zip_del   = "\n"
}

// print index navigation bar
function printNavigation() {
	if(numPages == 1) return

	indexPage = "index3.htm?page="
	//left part
	document.write('<table border="0" cellpadding="5"><tr><td class="navigation">')
	if (page > 1) {
	   prevPage = page - 1
	   document.write('<a href="' + indexPage + prevPage + '">')
	   document.write('<img src="larr.gif" border="0" alt="forrige side"></a>')
	}
	//middle part
	document.write('</td>\n<td class="navigation" align="center">sider ')
	for(i=1; i<=numPages; i++) {
	   	if(i==page) document.write('<span class="currentPage">'+i+'</span> | ')
	   	else	    document.write('<a href="' + indexPage + i + '">'+i+'</a> | ')
	}
	if (numPages > 1) {
	   if(page > 0)	    document.write('<a href="' + indexPage + 'all">alle</a>')
	   else		    document.write('<span class="currentPage">alle</span>')
	}
	//right part
	document.write('</td><td class="navigation">')
	if (page < numPages && page > 0) {
	   nextPage = page
	   nextPage++
	   document.write('&nbsp;&nbsp;<a href="' + indexPage + nextPage + '">')
	   document.write('<img src="rarr.gif" border="0" alt="next page"></a>')
	}
	document.write('</td></tr></table>\n')
}

// print the item's input fields
function printItemForm(i, imageNumber, text, price) {
	price = price * 100
	qty = eval('parent.frames[0].document.forms[0].qty_of_item_'+i+'_of_image_'+imageNumber+'.value')
	document.write('<tr>')
	document.write('<td><input type="button" value="<" onClick="this.form.item_'+i+'.value=--this.form.item_'+i+'.value">&nbsp;')
	document.write('<input class="mono" type="text" name="item_'+i+'" size="3" value="'+qty+'" ')
	document.write(' onClick="newVal=this.value; if(this.value==0)newVal=1; if(this.value==1)newVal=0; this.value=newVal" ')
	document.write(' onChange="this.value=onlyNumbers(this.value)">&nbsp;')
	document.write('<input type="button" value=">" onClick="this.form.item_'+i+'.value=++this.form.item_'+i+'.value"></td>')
	document.write('<td bgcolor="#cccccc"><b>' + text + '</b></td>')
	document.write('<td bgcolor="#cccccc" align="right">' + currency + price2Strg(price) + '</td></tr>')
}

// print the item's quantity & price
function printItemOrder(filename, qty, text, price) {
	price = price * 100 * qty
	if(useDiscountByCopies == 1)
		price -= price * calcDiscountByCopies(qty) / 100
	subTotal += price
	document.write('<tr bgcolor="#cccccc"><td>' + text + '</td>')
	document.write('<td align="right">' + qty + '</td>')
	document.write('<td align="right">' + currency + price2Strg(price))
	document.write('<input type="hidden" name="' + filename + ' -> ' + text + ': " value="' + qty + '"></td></tr>')
	// details in text file
	TextFile += qty + " x " + text + " (" + currency + price2Strg(price) + ")\n"
}


// calculate total price
function calcTotal() {
	var newSubtotal  = 0
	var newSubtotal2 = 0
	var newSubtotal3 = 0
	var newSubtotal4 = 0
	detailsTxt  = "Detaljer:\n\n"
	detailsTxt += "Subtotal = " + price2Strg(subTotal) + "\n"
	
	// calculate discount by total
	amountDiscountByTotal = 0
	newSubtotal = subTotal
	if(useDiscountByTotal == 1) {
		percentDiscountByTotal = calcDiscountByTotal(subTotal)
		amountDiscountByTotal  = subTotal * percentDiscountByTotal / 100
		
		newSubtotal = subTotal - amountDiscountByTotal
		detailsTxt += "Rabat = " + percentDiscountByTotal + "% af " + price2Strg(subTotal) + " = " + price2Strg(amountDiscountByTotal) + "\n"
		detailsTxt += "Ny Subtotal = " + price2Strg(subTotal) + ' - ' + price2Strg(amountDiscountByTotal) + ' = ' + price2Strg(newSubtotal) + "\n\n"
	}
	
	// calculate postage
	postage = 0
	if(shippingPercentage + shippingFixAmount + shippingPerItem > 0) {
		subTotalCalcVal = subTotal - amountDiscountByTotal
		if(shippingPercentage > 0) postage += shippingPercentage * subTotalCalcVal / 100
		if(shippingPerItem    > 0) postage += shippingPerItem * numberOfItems * 100
		if(shippingFixAmount  > 0) postage += shippingFixAmount * 100

		newSubtotal2 = eval(newSubtotal + postage)
		detailsTxt += "Afsendelse = " + price2Strg(postage) + " (tryk på Afsendelse / Porto for detaljer)\n"
		//detailsTxt += "new subtotal = " + price2Strg(newSubtotal) + ' + ' + price2Strg(postage) + ' = ' + price2Strg(newSubtotal2) + "\n\n"
	}
	
	// calculate additional postage
	morePostage = 0
	for(i=0; i<shipOption.length; i++) {
		if(shipOption[i]["used"] == 1) {
			myADDval = eval('parent.frames[0].document.forms[0].shipOption_' + i + '.value')
			myADDval = parseInt(myADDval, 10) * 100
			morePostage += myADDval
			
			detailsTxt += shipOption[i]["title"] + " = " + price2Strg(myADDval) + "\n"
		}
	}
	newSubtotal3 = eval(postage + morePostage)
	detailsTxt += "\n"
	
	// calculate tax
	tax = 0
	if(taxPercentage > 0) {
		taxCalcVal = subTotal - amountDiscountByTotal
		if(tax_inclShipping == 1) taxCalcVal += postage + morePostage
		taxAmount = taxPercentage * taxCalcVal / 100				// value in case tax option is set
		myTax = parent.frames[0].document.forms[0].customerTax.value		// tax option (taxPercentage or 0)
		if(myTax != 0) tax = taxAmount
		
		newSubtotal4 = newSubtotal3 + tax
		detailsTxt += "Tax = " + myTax + "% of " + price2Strg(taxCalcVal) + " = " + price2Strg(tax) + "\n"
		if(tax_inclShipping == 1) detailsTxt += "(tax includes shipping costs)\n\n"
		else			  detailsTxt += "(tax does not include shipping costs)\n\n"
		//detailsTxt += "new subtotal = " + price2Strg(newSubtotal3) + ' + ' + price2Strg(tax) + ' = ' + price2Strg(newSubtotal4) + "\n\n"
	}
	
	// total value
	totalVal = subTotal - amountDiscountByTotal + postage + morePostage + tax
	
	detailsTxt += "Total = " 
	detailsTxt 			+=       price2Strg(newSubtotal)
	if(postage > 0)	    detailsTxt	+= "+" + price2Strg(postage)
	if(morePostage > 0) detailsTxt	+= "+" + price2Strg(morePostage)
	if(tax > 0)	    detailsTxt	+= "+" + price2Strg(tax)
	detailsTxt			+= " = "+price2Strg(totalVal) + "\n\n"

}

// print sub total
function printSubTotal() {
	if(subTotal != totalVal) {
		txt = '<td class="total tableGrad_1">Ialt:</td>'
		txt+= '<td class="total" align="right">' + currency + price2Strg(subTotal) + '</td>'
		txt+= '<td></td>'
		document.write('<tr>' + txt + '</tr>\n')
	}
}

// print discount (by sub total)
function printDiscount() {
	if(useDiscountByTotal > 0) {
		txt = '<td class="total tableGrad_1"><a href="javascript:discountByTotalRules()">Rabat</a> (' + percentDiscountByTotal + '%):</td>'
		txt+= '<td class="total" align="right">' + '- ' + currency + price2Strg(amountDiscountByTotal) + '</td>'
		txt+= '<td></td>'
		document.write('<tr>' + txt + '</tr>\n')
	}
}

// print shipping & handling
function printPostage() {
	if(postage > 0) {
		txt = '<td class="total tableGrad_1"><a href="javascript:shippingRules()">Afsendelse / Porto</a>:</td>'
		txt+= '<td class="total" align="right">' + currency + price2Strg(postage) + '</td>'
		txt+= '<td></td>'
		document.write('<tr>' + txt + '</tr>\n')
	}
}

// print all shipping options (w/ extra cost)
function printAllShipOptions(textonly) {
	for(i=0; i<shipOption.length; i++)
		if(shipOption[i]["used"] == 1) printShipOption(textonly, i)
}

// print one shipping option with selection field
function printShipOption(textonly, i) {
	txt = ""
	myADDval = eval('parent.frames[0].document.forms[0].shipOption_' + i + '.value')
	myADDval = parseInt(myADDval, 10) * 100			// selected value
	price    = parseInt(shipOption[i]["price"], 10) * 100	// default price
	if(textonly == 1) {
		if(myADDval > 0) {
			txt = '<td class="total tableGrad_1">' + shipOption[i]["title"] + ':</td>'
			txt+= '<td class="total" align="right">'
			txt+= currency + price2Strg(myADDval) + '</td>'
			txt+= '<td></td>'
		}
	} else {
		if(myADDval == 0)				// remember last setting
			selectNoADDval = " selected"
		else	selectNoADDval = ""
		txt = '<td class="total tableGrad_1">' + shipOption[i]["title"] + ':</td>'
		txt+= '<td class="total" align="right">'
		txt+= currency + '<select name="shipOption_' + i + '" class="mono" '
		txt+= 'onChange="thisVal=this.options[this.selectedIndex].value; '
		txt+= '  parent.frames[0].document.forms[0].shipOption_' + i + '.value=thisVal; '
		txt+= '  calcTotal(); updateTaxField(); updateTotalField()">'
		txt+= '<option value="' + shipOption[i]["price"] + '">' + price2Strg(price) + '</option>'
		txt+= '<option value="0"' + selectNoADDval + '>-no-</option>'
		txt+= '</select></td>'
		txt+= '<td></td>'
	}
	if(txt != "") document.write('<tr>' + txt + '</tr>\n')
}

// print tax
function printTax(textonly) {
	txt = ""
	if(taxPercentage > 0) {
		myTax = parent.frames[0].document.forms[0].customerTax.value
		if(textonly == 1) {
			if(myTax > 0) {
				txt = '<td class="total tableGrad_1">Moms (' + taxPercentage + '%):</td>'
				txt+= '<td class="total" align="right">'
				txt+= currency + price2Strg(tax) + '</td>'
				txt+= '<td></td>'
			}
		} else {
		    if(taxAlways == 1) {
			txt = '<td class="total tableGrad_1">Moms (' + taxPercentage + '%):</td>'
			txt+= '<td class="total" align="right">'
			txt+= currency + '<select name="tax" class="mono">'
			txt+= '<option value="'+ taxPercentage +'">' + price2Strg(tax) + '</option>'
			txt+= '</select></td>'
			txt+= '<td></td>'
		    } else {
			if(myTax == 0) {				// remember last setting
					selectTaxNO  = " Valgt"
					selectTaxYES = ""
			} else {	selectTaxYES = " Valgt"
					selectTaxNO = ""
			}
			txt = '<td class="total tableGrad_1">Tax (' + taxPercentage + '%):</td>'
			txt+= '<td class="total" align="right">'
			txt+= currency + '<select name="tax" class="mono" '
			txt+= 'onChange="thisTax=this.options[this.selectedIndex].value; '
			txt+= '  parent.frames[0].document.forms[0].customerTax.value=thisTax; '
			txt+= '  calcTotal(); updateTotalField()">'
			txt+= '<option value="'+ taxPercentage +'"' + selectTaxYES + '>' + price2Strg(tax) + '</option>'
			txt+= '<option value="0"' + selectTaxNO + '>' + price2Strg(0) + '</option>'
			txt+= '</select></td>'
			txt+= '<td class="mini"> &larr; Please set to ' + price2Strg(0) + ' if you<br>'
			txt+= ' &larr; do NOT live in ' + taxCountry + '.</td>'
		    }
		}
	}
	if(txt != "") document.write('<tr>' + txt + '</tr>\n')
}

// print total
function printTotal(textonly) {
	if(textonly == 1) lineSep = ' style="border-top:2px solid black"'
	else 		  lineSep = ''
	txt = '<td class="total" bgcolor="#333333"' + lineSep + '><font color="white">Ialt:</font></td>'
	txt+= '<td class="total" bgcolor="#333333"' + lineSep + ' align="right"><font color="white">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
	if(textonly == 1) {
		txt+= currency + price2Strg(totalVal) + '</td>'
		txt+= '<td></td>'
	} else {
		totalStrg = price2Strg(totalVal)
		txt+= currency + '<input type="text" name="total" size="' + totalStrg.length + '" class="mono"'
		txt+= ' value="' + totalStrg + '" onFocus="this.blur()"></td>'
	}
	txt+= '<td></td>'
	document.write('<tr>' + txt + '</tr>\n')
	
	if(textonly != 1 && showCalcDetails == 1)
	document.write('<tr><td class="mini tableGrad_2" colspan="2" align="right"><a href="javascript:alert(detailsTxt)">Detaljer</a></td><td></td></tr>')
}

// update tax field (if calculated with postage)
function updateTaxField() {
	if(taxPercentage > 0 && tax_inclShipping == 1) {
		document.forms[0].tax.options[0].text  = price2Strg(taxAmount)
		document.forms[0].tax.options[0].value = taxPercentage		// set value after text change!
		//history.go(0)
	}
}

// update total field
function updateTotalField() {
	document.forms[0].total.value = price2Strg(totalVal)
}

// add an item to the shopping cart
function add2cart(imageNumber, caption, url, image, width, height, file, quantity, price, options)
{
	this.imageNumber	= imageNumber
	this.caption		= caption
	this.url		= url
	this.image		= image
	this.width		= width
	this.height		= height
	this.file		= file
	this.quantity		= quantity
	this.price		= price
	this.options		= options
}

// print contact information as Text
function printContactText() {
	txt = ""
	if(myName	!= "") txt+= myName	+ "\n"
	if(myStreet	!= "") txt+= myStreet	+ "\n"
	if(zip_del == " ")
	if(myZip	!= "") txt+= myZip	+ zip_del
	if(myCity	!= "") txt+= myCity	+ city_del
	if(myState	!= "") txt+= myState	+ state_del
	if(zip_del != " ")
	if(myZip	!= "") txt+= myZip	+ zip_del
	if(myCountry	!= "") txt+= myCountry	+ "\n"
	if(myPhone1	!= "") txt+= "Phone: "  + myPhone1	+ "\n"
	if(myPhone2	!= "") txt+= "       "  + myPhone2	+ "\n"
	if(myFax	!= "") txt+= "Fax:   "  + myFax		+ "\n"
	if(myEmail	!= "") txt+= myEmail	+ "\n"
	if(myWWW	!= "") txt+= myWWW	+ "\n"
	return(txt)
}

// print contact information in HTML
function printContactHtml(style) {
	// change \n to <br>
	zip_del_br   = (zip_del.indexOf("\n")   >= 0) ? "<br>" : zip_del
	city_del_br  = (city_del.indexOf("\n")  >= 0) ? "<br>" : city_del
	state_del_br = (state_del.indexOf("\n") >= 0) ? "<br>" : state_del





	txt = ""
	txt+= '<p class="' + style + '">'
	if(myName	!= "") txt+= "<b>"      + myName	+ "</b><br>\n"
	if(myStreet	!= "") txt+= myStreet	+ "<br>\n"
	if(zip_del == " ")
	if(myZip	!= "") txt+= myZip	+ zip_del_br
	if(myCity	!= "") txt+= myCity	+ city_del_br
	if(myState	!= "") txt+= myState	+ state_del_br
	if(zip_del != " ")
	if(myZip	!= "") txt+= myZip	+ zip_del_br
	if(myCountry	!= "") txt+= myCountry	+ "<br>\n"
	if(myPhone1	!= "") txt+= "Phone: "  + myPhone1	+ "<br>\n"
	if(myPhone2	!= "") txt+= myPhone2	+ "<br>\n"
	if(myFax	!= "") txt+= "Fax: "    + myFax		+ "<br>\n"
	if(myEmail	!= "") txt+= 'E-Mail: <a href="mailto:' + myEmail + '">' + myEmail + '</a><br>\n'
	if(myWWW	!= "") txt+= '<a href="http://' + myWWW + '" target="_blank">' + myWWW + '</a><br>\n'
	txt+= "</p>"
	document.write(txt)
}

// print customer information as Text
function printCustomerInfoText(f) {
	zip_del_bl   = (zip_del.indexOf("\n")   >= 0) ? "\n  " : zip_del
	city_del_bl  = (city_del.indexOf("\n")  >= 0) ? "\n  " : city_del
	state_del_bl = (state_del.indexOf("\n") >= 0) ? "\n  " : state_del

	txt = "  "
	if(f.realname.value	!= "") txt+= f.realname.value	+ "\n  "
	if(f.addr1.value	!= "") txt+= f.addr1.value	+ "\n  "
	if(f.addr2.value	!= "") txt+= f.addr2.value	+ "\n  "
	if(zip_del == " ")
	if(f.zip.value		!= "") txt+= f.zip.value	+ zip_del_bl
	if(f.city.value		!= "") txt+= f.city.value	+ city_del_bl
	if(f.state.value	!= "") txt+= f.state.value	+ state_del_bl
	if(zip_del != " ")
	if(f.zip.value		!= "") txt+= f.zip.value	+ zip_del_bl
	if(f.country.value	!= "") txt+= f.country.value	+ "\n  "
	if(f.phone.value	!= "") txt+= "Phone: "  + f.phone.value	+ "\n  "
	if(f.phone2.value	!= "") txt+= "       "  + f.phone2.value+ "\n  "
	if(f.fax.value		!= "") txt+= "Fax:   "  + f.fax.value	+ "\n  "
	if(f.email.value	!= "") txt+= f.email.value	+ "\n  "
	if(f.email2.value	!= "") txt+= f.email2.value	+ "\n  "
	if(f.comments.value	!= "") txt+= "\nBesked:\n"	+ f.comments.value + "\n\n"
	return(txt)
}

// print customer information in HTML
function printCustomerInfo(f) {
	// change \n to <br>
	zip_del_br   = (zip_del.indexOf("\n")   >= 0) ? "<br>" : zip_del
	city_del_br  = (city_del.indexOf("\n")  >= 0) ? "<br>" : city_del
	state_del_br = (state_del.indexOf("\n") >= 0) ? "<br>" : state_del

	txt = ""
	if(f.realname.value	!= "") txt+= f.realname.value	+ "<br>\n"
	if(f.addr1.value	!= "") txt+= f.addr1.value	+ "<br>\n"
	if(f.addr2.value	!= "") txt+= f.addr2.value	+ "<br>\n"
	if(zip_del == " ")
	if(f.zip.value		!= "") txt+= f.zip.value	+ zip_del_br
	if(f.city.value		!= "") txt+= f.city.value	+ city_del_br
	if(f.state.value	!= "") txt+= f.state.value	+ state_del_br
	if(zip_del != " ")
	if(f.zip.value		!= "") txt+= f.zip.value	+ zip_del_br
	if(f.country.value	!= "") txt+= f.country.value	+ "<br>\n"
	if(f.phone.value	!= "") txt+= "Phone: "  + f.phone.value	+ "<br>\n"
	if(f.phone2.value	!= "") txt+= f.phone2.value	+ "<br>\n"
	if(f.fax.value		!= "") txt+= "Fax: "    + f.fax.value	+ "<br>\n"
	if(f.email.value	!= "") txt+= 'E-Mail: <a href="mailto:' + f.email.value + '">' + f.email.value + '</a><br>\n'
	if(f.email2.value	!= "") txt+= '<a href="mailto:' + f.email2.value + '">' + f.email2.value + '</a><br>\n'
	if(f.comments.value	!= "") txt+= '<br>Comments:<br><table border="1" cellspacing="0" cellpadding="5"><tr><td><pre>' + f.comments.value + '</pre></td></tr></table>\n'
	document.write(txt)
}

// print customer information hidden fields
function printCustomerHiddenFields() {
	txt = ""
	txt+= '<input type="hidden" name="realname"	value="">\n'
	txt+= '<input type="hidden" name="addr1"	value="">\n'
	txt+= '<input type="hidden" name="addr2"	value="">\n'
	txt+= '<input type="hidden" name="city"		value="">\n'
	txt+= '<input type="hidden" name="state"	value="">\n'
	txt+= '<input type="hidden" name="zip"		value="">\n'
	txt+= '<input type="hidden" name="country"	value="">\n'
	txt+= '<input type="hidden" name="phone"	value="">\n'
	txt+= '<input type="hidden" name="phone2"	value="">\n'
	txt+= '<input type="hidden" name="fax"		value="">\n'
	txt+= '<input type="hidden" name="email"	value="">\n'
	txt+= '<input type="hidden" name="email2"	value="">\n'
	txt+= '<input type="hidden" name="comments"	value="">\n'
	for(i=0; i<shipOption.length; i++)
		txt+= '<input type="hidden" name="shipOption_' + i + '"  value="0">\n'
	txt+= '<input type="hidden" name="customerTax"  value="' + taxPercentage + '">\n'
	document.write(txt)
}

// copy customer information to hidden fields in top frame
function saveCustomerInfo(from,to) {
	if(parent.frames[0].document.forms[0].noi.value > 0) {
		to.realname.value	= from.realname.value
		to.addr1.value		= from.addr1.value
		to.addr2.value		= from.addr2.value
		to.city.value		= from.city.value
		to.state.value		= from.state.value
		to.zip.value		= from.zip.value
		to.country.value	= from.country.value
		to.phone.value		= from.phone.value
		to.phone2.value		= from.phone2.value
		to.fax.value		= from.fax.value
		to.email.value		= from.email.value
		to.email2.value		= from.email2.value
		to.comments.value	= from.comments.value
	}
}

// print the customer input fields
function printCustomerInputFields() {
	printCustomerInputData("Navn"     ,"realname")
	printCustomerInputData("Adresse","addr1"   )
	printCustomerInputData("Adress 2","addr2"   )
	printCustomerInputData("By"     ,"city"    )
	printCustomerInputData("State"    ,"state"   )
	printCustomerInputData("Postnr." ,"zip"     )
	printCustomerInputData("Country"  ,"country" )
	printCustomerInputData("Telefon"    ,"phone"   )
	printCustomerInputData("Phone 2"  ,"phone2"  )
	printCustomerInputData("Fax"      ,"fax"     )
	printCustomerInputData("E-Mail"   ,"email"   )
	printCustomerInputData("E-Mail 2" ,"email2"  )
	document.write('<tr><td valign="top">Besked: </td><td><TEXTAREA name="comments" rows="5" cols="30" wrap="hard">')
	document.write(parent.frames[0].document.forms[0].comments.value + '</textarea></td></tr>')
}

// print the customer input fields
function printCustomerInputData(fieldname, varname) {
	customer_realname = 2		// always mandatory!
	varvalue = eval('parent.frames[0].document.forms[0].' + varname + '.value')
	prio = eval('customer_' + varname)
	if(prio > 0) {
		txt = '<tr><td> ' + fieldname + ':</td>'
		txt+= '<td><input type="text" size="40" name="' + varname + '" '
		txt+= 'value="' + varvalue + '">'
		if(prio == 2) txt+= ' *'
		txt+= '</td></tr>\n'
		document.write(txt)
	} else {
		document.write('<input type="hidden" name="' + varname + '" value="">')
	}
}


// calculate discount by copies
function calcDiscountByCopies(qty) {
	var percentDiscount = 0
	for(copies in discountByCopies) {
		if(qty >= copies && discountByCopies[copies] > percentDiscount)
			percentDiscount = discountByCopies[copies]
	}
	return percentDiscount
}

// calculate discount after total
function calcDiscountByTotal(subtotal) {
	var percentDiscount = 0
	for(value in discountByTotal) {
		if(subtotal >= value*100 && discountByTotal[value] > percentDiscount)
			percentDiscount = discountByTotal[value]
	}
	return percentDiscount
}

// alert with the discount (by copies) rules
function discountByCopiesRules() {
	txt = "If you order more copies of the same items\nthe following discount will be offered:\n\n"
	for(copies in discountByCopies) {
		txt += copies + " copies and more: " + discountByCopies[copies] + "% discount\n"
	}
	alert(txt + "\n")
}

// alert with the discount (by total) rules
function discountByTotalRules() {
	currTxt = currency		// workaround b/c &euro; does not show up as symbol
	if(currency.indexOf("&") == 0) {
		currTxt = currency.replace(/[&;]/g,"")
		currTxt = "[" + currTxt.toUpperCase() + "] "
	}

	txt = "Udregning af rabat:\n\n"
	for(value in discountByTotal) {
		txt += "Ved køb for " + currTxt + value + " eller mere udløses: " + discountByTotal[value] + "% rabat.\n"
	}
	alert(txt + "\n")
}

// alert with the shipping rules
function shippingRules() {
	currTxt = currency		// workaround b/c &euro; does not show up as symbol
	if(currency.indexOf("&") == 0) {
		currTxt = currency.replace(/[&;]/g,"")
		currTxt = "[" + currTxt.toUpperCase() + "] "
	}

	txt = "Afregning for afsendelse af ordre:\n\n"
	if(shippingPercentage > 0) txt += shippingPercentage + "% of the sub total\n"
	if(shippingPerItem    > 0) txt += currTxt + shippingPerItem + " per item\n"
	if(shippingPercentage > 0 ||
	   shippingPerItem    > 0) if(shippingFixAmount  > 0) txt += "plus a "
	if(shippingFixAmount  > 0) txt += "fast pris på " + currTxt + shippingFixAmount + "\n\n"
	alert(txt)
}


// misc. Validation functions
function checkCustomerForm() {
	var errMsg = ""	
	errMsg += checkCustomerData("Navn"     ,"realname")
	errMsg += checkCustomerData("Adresse","addr1"   )
	errMsg += checkCustomerData("Address 2","addr2"   )
	errMsg += checkCustomerData("By"     ,"city"    )
	errMsg += checkCustomerData("Postnr" ,"zip"     )
	errMsg += checkCustomerData("State"    ,"state"   )
	errMsg += checkCustomerData("Country"  ,"country" )
	errMsg += checkCustomerData("Telefon"    ,"phone"   )
	errMsg += checkCustomerData("Phone 2"  ,"phone2"  )
	errMsg += checkCustomerData("Fax"      ,"fax"     )
	errMsg += checkCustomerData("E-Mail"   ,"email"   )
	errMsg += checkCustomerData("E-Mail"   ,"email2"  )

	if (errMsg != "") {
		alert(errMsg)
		return false
	}
	else	return true
}

// misc. Validation functions
function checkCustomerData(fieldname, varname) {
	var err = ""
	customer_realname = 2		// always mandatory!
	varvalue = eval('document.forms[0].' + varname + '.value')
	prio = eval('customer_' + varname)
	if(prio == 2) {
		if(varname.indexOf("phone") >= 0) {
			err += checkPhone(varvalue, fieldname)
		} else {
		  if(varname.indexOf("email") >= 0)
			err += checkEmail(varvalue, fieldname)
		  else
			err += isEmpty(varvalue, fieldname)
		}
		//err += checkDropdown(f.choose.selectedIndex)
	}
	return err
}

function isEmpty(arg, fieldname) {
	var err = ""
	if (arg.length == 0) {
		err = "" + fieldname + " skal udfyldes.\n"
	}
	return err
}

function checkDropdown(choice) {
	var err = ""
	if (choice == 0) {
		err = "Du valgte ikke noget fra drop-down menuen.\n"
	}
	return err
}

function checkPhone (arg, fieldname) {
	var err = ""
	if (arg == "") {
	    err = "" + fieldname + " skal udfyldes.\n"
		return err
	}

	var stripped = arg.replace(/[\(\)\.\-\ ]/g, '') 	//strip out acceptable non-numeric characters
	if (isNaN(parseInt(stripped))) {
		err = "" + fieldname + " nummeret indeholder illegale tegn.\n"
	}
	//    if (!(stripped.length == 8)) {
	//	err = "Telefonnummeret har den forkerte længde\n"
	//    }
	return err
}

function checkEmail (arg, fieldname) {
	var err = ""
	if (arg == "") {
		err = "" + fieldname + " skal udfyldes.\n"
		return err;
	}

	var emailFilter=/^.+@.+\..{2,3}$/
	if (!(emailFilter.test(arg))) {
		err = "Skriv en rigtig e-mail adresse i" + fieldname + ".\n"
	}
	else {
		//test email for illegal characters
		var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
		if (arg.match(illegalChars)) {
		   err = "The " + fieldname + " e-mail adressen indeholder illegale tegn.\n"
		}
	}
	return err;
}

function isValidEmail(emailAddress) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return re.test(emailAddress)
}

function onlyNumbers(arg) {
	arg    = arg.replace(/\s+/g,"");	// delete all spaces
	if (! /^\d+$/.test(arg)) {
		alert('"' + arg + '" er ikke et nummer!\n')
		return "0"
	}
	else	return arg
}

function isNumbers(arg) {
	var err = ""
	  if (!arg.IsNumeric) {
		err = "Venligst skriv et nummer\n"
	  }
	return err
}


// format price string: 12350 -> 123.50 or 123,50
function price2Strg(x) {
	priceStr = Math.round(x) + ""
	len = priceStr.length
	if(len==2) priceStr =  "0" + priceStr
	if(len==1) priceStr = "00" + priceStr
	len = priceStr.length
	priceStr = priceStr.substring(0,len-2) + decimal + priceStr.substring(len-2)
	return (priceStr)
}

// add blanks for padding the price string in the text view
function middlePad(str1, str2) {
	lineLength = 25
	if(currency.indexOf("&") == 0) lineLength += currency.length - 1	// &euro; -> 1 char
	blanksAdd  = lineLength - str1.length - str2.length
	blanksStr  = ""
	for(var i=0; i<blanksAdd; i++) blanksStr += " "
	return (str1 + blanksStr + str2)
}

// reading a variable in the parsed string
function getParm(string,parm) {
	var startPos= string.indexOf(parm+"=")
	if (startPos> -1) {
		startPos= startPos+parm.length+1
		var endPos= string.indexOf("&",startPos)
		if (endPos== -1) endPos= string.length
		return unescape(string.substring(startPos,endPos))
	}
	return ''
}

// Alert & forward to homepage
function back2home(noi) {
	txt = "Dette vil annulere ordren for dette galleri!\n"
	txt+= "Klik \"OK\" hvis du stadig vil gå til hjemmesiden.\n"
	if(noi > 0) {
		if(confirm(txt))
			parent.location.href = "http://" + myWWW
	} else		parent.location.href = "http://" + myWWW
}

// Alert & forward to galleries
function back2galleries(noi) {
	txt = "Dette vil annulere ordren for dette galleri!\n"
	txt+= "Klik \"OK\" hvis du stadig vil gå tilbage.\n"
	if(noi > 0) {
		if(confirm(txt))
			parent.location.href = galleryIndex
	} else		parent.location.href = galleryIndex
}

// Forward to checkout (if cart not empty)
function go2cart(noi) {
	//if(noi == 0) {
	//	alert("Din kurv er tom!")
	//} else
		parent.frames[1].location.href = "index2.htm?order=html"
}


// ----------------------------------------------------
// Slideshow functions

// go to the next page
function next() {
	// only move to next page if slideshow is running
	if (slide == "on") {
		if (nextUrl.length <= 1)
			nextUrl = "index3.htm?page=" + page + "&delay=" + delay
		else	nextUrl += "?page=" + page + "&slide=on&delay=" + delay

		document.location.href = nextUrl
	}
}

// start/stop the slideshow
function start_stop(f) {
	if (slide == "on") {
		// disable the slideshow
		slide = ""
		f.ss_button.value = "Start Slideshow"
		// Remove the "&slide=on" from the page history
		thisUrl = location.href.replace("&slide=on","")
		if (document.images) location.replace(thisUrl);
	}
	else {
		// restart the slideshow
		slide = "on"
		setTimeout("next()", 1000)
		f.ss_button.value = "Stop Slideshow"
	}
	return false
}

// check if image has loaded
function poll() {
	if (slide == "on") {
		if (thePhoto.complete) setTimeout('next()', 1000 * delay)
		else setTimeout('poll()', 500)
	}
}
// ----------------------------------------------------

