// POD Client Order Page Functions v2.4
// (C) 2004 Panic, Inc.
//
// May not be used without permission. Really.
//
// 12/08/03 - CS: Major rewrite, support for radio buttons, more flexible, etc.
// 02/16/04 - CS: Disable the submit button and display status animation on submit
// 05/09/05 - CS: Added internationalization (jp)
// 02/23/06 - CS: Added Paypal skip CC check block

// calcTotalNew()
//
// This script will calculate a total based on which items are selected.
// Requires the item checkbox to live as "item.name"
// And the item quantity to live as "name"
// These should be defined in the item configuration block in your .HTML

spinner_on  = new Image(16,16); spinner_on.src  = "/images-global/spinner.gif";
spinner_off = new Image(16,16); spinner_off.src = "/images-global/spacer.gif";

alert_on  = new Image(15,15); alert_on.src = "/images-global/buy-alert.gif"
alert_off = new Image(15,15); alert_off.src = "/images-global/spacer.gif"

function calcTotalNew() 
{
	boughtThings = "";
	theTotal = 0.00;

	// Check every set of radio button groups if defined

	if (radioArray.length != 0) 
	{
		for (var i=0; i < radioArray.length; i++) 
		{
			// Find out which item was checked

			j = document.orderform[radioArray[i]].length;

			for (var k=0; k < j; k++) 
			{
				if (document.orderform[radioArray[i]][k].checked) 
					radioValue = document.orderform[radioArray[i]][k].value;
			}

			// Find out where that item lives in the overall item array

			for (var m=0; m < checkedArray.length; m++) 
			{
				if (checkedArray[m] == radioValue) 
					radioIndex = m;
			}

			// Now add to the total!

			document.orderform[quantityArray[radioIndex]].value = Math.ceil(document.orderform[quantityArray[radioIndex]].value);

			if (document.orderform[quantityArray[radioIndex]].value == "") 
				document.orderform[quantityArray[radioIndex]].value = "1";

			if (document.orderform.pod_language.value == "jp") 
			{
				boughtThings = boughtThings + descriptArray[radioIndex] + " ("+document.orderform[quantityArray[radioIndex]].value+")\n";
			} 
			else 
			{
				boughtThings = boughtThings + document.orderform[quantityArray[radioIndex]].value+" qty. of "+descriptArray[radioIndex]+"\n";
			}

			theTotal = theTotal + priceArray[radioIndex] * document.orderform[quantityArray[radioIndex]].value;
		}
	}

	// Walk through each of the form items

	for (var i=0; i < quantityArray.length; i++) 
	{
		// If it's checked, add it to the total

		if (document.orderform[checkedArray[i]] && document.orderform[checkedArray[i]].checked) 
		{
			document.orderform[quantityArray[i]].value = Math.ceil(document.orderform[quantityArray[i]].value);
			
			if (document.orderform[quantityArray[i]].value == "") 
				document.orderform[quantityArray[i]].value = "1";

			if (document.orderform.pod_language.value == "jp") 
			{
				boughtThings = boughtThings + descriptArray[i]+" ("+document.orderform[quantityArray[i]].value+")\n";
			} 
			else 
			{
				boughtThings = boughtThings + document.orderform[quantityArray[i]].value+" qty. of "+descriptArray[i]+"\n";
			}

			theTotal = theTotal + priceArray[i] * document.orderform[quantityArray[i]].value;
		}
	}

	// Now update the page total
	// INTL: Change here

	if (parseFloat(navigator.appVersion) >= 3 && isNaN(theTotal)) 
	{
		if (document.orderform.pod_language.value == "jp") 
			alert("半角数字以外の文字は入力できません！ ");
		else 
			alert("You can only use numbers in the quantity fields. Please fix!");
	}
	else 
	{
		theTotal = theTotal + "";

		if ( theTotal > 100 && ((! document.orderform.pod_currency) || (document.orderform.pod_currency && document.orderform.pod_currency.value != "JPY")))
		{	
			theTotal = theTotal.substring(0, theTotal.length - 2) + "." + theTotal.substring(theTotal.length - 2, theTotal.length);
		}
	}

	// Now update the total text

	if (document.getElementById) 
		document.getElementById('total').innerHTML = theTotal;

	// If there's a Order Token field (used for duplicate order checking), set it to a UUID

	if (document.getElementById && document.getElementById("pod_orderToken")) 
		document.getElementById("pod_orderToken").value = new UUID();
}

// finalVerifyForm
//
// This script will make sure any form field that needs to be filled out, is.
// It iterates through all the form fields, looking for ones with alert graphics.
// If those are blank, then it lights up the alert graphic.
// Finally, it displays the last chance "confirmation" alert box if all is well.

function finalVerifyForm() {
  calcTotalNew();

  var errorFlag = 0;

  // Check every form element to make sure it's filled.
  // If it's a text field, and it has an "alert" image, and it's blank, then turn on the alert.
  // 
  // TEXT: If you want a text field to NOT validate, then don't give it an alert image.
  // CHECKBOX: Same rules apply here.

  for (x = 0; x < document.orderform.elements.length; x++) {

    // Text field test

    if (document.orderform.elements[x].type && document.orderform.elements[x].type == "text") {   // Is it a text field?
      if (document.images && document.images["alert-"+document.orderform.elements[x].name]) {     // Does it have a matching 'alert' graphic space?
        if (document.getElementById('PayPal') && document.getElementById('PayPal').checked && (document.orderform.elements[x].name == "cpi.card-number" || document.orderform.elements[x].name == "cpi_card-security")) {
          // Do nothing, since card number should not be tested if the payment type is PayPal
        } else {
          if (document.orderform.elements[x].value == "") {
            document.images["alert-"+document.orderform.elements[x].name].src = alert_on.src;
            errorFlag = 1;
          } else {
          document.images["alert-"+document.orderform.elements[x].name].src = alert_off.src;
          }
        }
      }
    }

    // Checkbox test

    if (document.orderform.elements[x].type && document.orderform.elements[x].type == "checkbox") {
      if (document.images && document.images["alert-"+document.orderform.elements[x].name]) {
        if (document.orderform.elements[x].checked == false) {
          document.images["alert-"+document.orderform.elements[x].name].src = alert_on.src;
          errorFlag = 1;
        } else {
	  document.images["alert-"+document.orderform.elements[x].name].src = alert_off.src;
        }
      }
    }
  }

  // INTL: Display error

  if (errorFlag == 1) {

    if (document.orderform.pod_language.value == "jp") {
      alert("注文の前に、マークが現れたすべての項目を埋めてください");
    } else {
      alert("You must fill out all marked fields before you can submit the form!");
    }

    return false;
  }

  if (document.orderform.pod_language.value == "jp") {
    str = "ご注文商品:\n"+boughtThings+"\n合計金額: "+theTotal+"\n\n内容が正しいことを確認して OK をクリックしてください";
  } else {
    str = "You're buying:\n"+boughtThings+"\nYour Total: $"+theTotal+"\n\nIs this correct? If so, click OK!";
  }

  if (confirm(str)) {

    // Turn on the status information

    document.orderform.submitter.disabled = true;
    document.images["spinner"].src = spinner_on.src;
    return true;
  }
  else {
    return false;
  }
}

// resetForm
//
// When hooked up to onUnload event, this will turn the submit button back on
// and turn off the animation once the page is left. This means, if the
// user clicks the back button to correct an error, they can then re-submit
// the form.

function resetForm() {
  document.orderform.submitter.disabled = false;
  document.images["spinner"].src = spinner_off.src;
}

////////////////////////
//
// UUID Generation Code
// Copyright (C) 2006-2008, Erik Giberti (AF-Design), All rights reserved.
//
////////////////////////

// On creation of a UUID object, set it's initial value
function UUID(){
	this.id = this.createUUID();
}

// When asked what this Object is, lie and return it's value
UUID.prototype.valueOf = function(){ return this.id; }
UUID.prototype.toString = function(){ return this.id; }

//
// INSTANCE SPECIFIC METHODS
//

UUID.prototype.createUUID = function(){
	//
	// Loose interpretation of the specification DCE 1.1: Remote Procedure Call
	// described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37
	// since JavaScript doesn't allow access to internal systems, the last 48 bits 
	// of the node section is made up using a series of random numbers (6 octets long).
	//  
	var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
	var dc = new Date();
	var t = dc.getTime() - dg.getTime();
	var h = '-';
	var tl = UUID.getIntegerBits(t,0,31);
	var tm = UUID.getIntegerBits(t,32,47);
	var thv = UUID.getIntegerBits(t,48,59) + '1'; // version 1, security version is 2
	var csar = UUID.getIntegerBits(UUID.rand(4095),0,7);
	var csl = UUID.getIntegerBits(UUID.rand(4095),0,7);

	// since detection of anything about the machine/browser is far to buggy, 
	// include some more random numbers here
	// if NIC or an IP can be obtained reliably, that should be put in
	// here instead.
	var n = UUID.getIntegerBits(UUID.rand(8191),0,7) + 
			UUID.getIntegerBits(UUID.rand(8191),8,15) + 
			UUID.getIntegerBits(UUID.rand(8191),0,7) + 
			UUID.getIntegerBits(UUID.rand(8191),8,15) + 
			UUID.getIntegerBits(UUID.rand(8191),0,15); // this last number is two octets long
	return tl + h + tm + h + thv + h + csar + csl + h + n; 
}


//
// GENERAL METHODS (Not instance specific)
//


// Pull out only certain bits from a very large integer, used to get the time
// code information for the first part of a UUID. Will return zero's if there 
// aren't enough bits to shift where it needs to.
UUID.getIntegerBits = function(val,start,end){
	var base16 = UUID.returnBase(val,16);
	var quadArray = new Array();
	var quadString = '';
	var i = 0;
	for(i=0;i<base16.length;i++){
		quadArray.push(base16.substring(i,i+1));	
	}
	for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){
		if(!quadArray[i] || quadArray[i] == '') quadString += '0';
		else quadString += quadArray[i];
	}
	return quadString;
}

// Replaced from the original function to leverage the built in methods in
// JavaScript. Thanks to Robert Kieffer for pointing this one out
UUID.returnBase = function(number, base){
	return (number).toString(base).toUpperCase();
}

// pick a random number within a range of numbers
// int b rand(int a); where 0 <= b <= a
UUID.rand = function(max){
	return Math.floor(Math.random() * (max + 1));
}

// end of UUID class file

