function popup(pageURL,x,y){
	var newwin = window.open( pageURL, "_blank", "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=" + x + ",height=" + y + ",resizable=no" );
}

function addItem(itemId){
	if($('td#leftCartContainer').length){
		$('td#leftCartContainer').load('/cart.php?action=add&p='+itemId);
	}
	else{
		$.getScript('/cart.php?action=add&getscript=y&p='+itemId);
	}
}

function removeItem(itemId){
	var callBack;
	if($('input[name="medium"]:checked').val() == 'download'){
		callBack = loadDownladCart;
	}
	else{
		callBack = loadDiscCart;
	}
	$('td#leftCartContainer').load('/cart.php?action=remove&p='+itemId, null, callBack);
}

function emptyCart(){
	var callBack;
	if($('input[name="medium"]:checked').val() == 'download'){
		callBack = loadDownladCart;
	}
	else{
		callBack = loadDiscCart;
	}
	$('td#leftCartContainer').load('/cart.php?action=empty', null, callBack);
}

function loadDownladCart(){
	$('div#mainCartContainer').load('/centerDownloadCart.php', null, calcTotal);
}

function loadDiscCart(){
	$('div#mainCartContainer').load('/centerDiscCart.php', null, calcTotal);
}

function calcTotal(){
	var subTotal = new Number($('#subTotal').attr('title'));
	var shippingCost = new Number($('input[name="deliveryMethod"]:checked').attr('title'));
	if(shippingCost.toString() == 'NaN'){
		shippingCost = new Number($('#shippingCost').attr('title'));
		if(shippingCost.toString() == 'NaN'){
			shippingCost = 0;
		}
	}
	
	var deliveryMethod = $('input[name="deliveryMethod"]:checked').val();
	if(!deliveryMethod){
		deliveryMethod = $('input[name="deliveryMethod"]').val();
	}
	
	if(deliveryMethod != ''){
		$.getJSON('/get.discount.php', {deliveryCost: shippingCost, itemCost: subTotal, deliveryMethod: deliveryMethod}, function(data){
			var deliveryDiscount = 0;
			var itemDiscount = 0;
			if(data['deliveryDiscount']){
				deliveryDiscount = data['deliveryDiscount'];
				shippingCost = shippingCost - data['deliveryDiscount'];
			}
			if(data['itemDiscount']){
				itemDiscount = data['itemDiscount'];
				subTotal = subTotal - data['itemDiscount'];
			}

			var total = (subTotal*100+shippingCost*100)/100;

			$('.subTotal').html('$' + numberFormat(subTotal, 2));
			//$('.subTotal').attr('title', itemDiscount?'You save $'+itemDiscount:'');
			if(itemDiscount){
				$('.subTotal').attr('title', 'Your saving $'+numberFormat(itemDiscount, 2));
				$('.subDiscount').html('Your saving $'+numberFormat(itemDiscount, 2));
			}
			else{
				$('.subTotal').attr('title', '');
				$('.subDiscount').html('');
			}
			$('.shippingCost').html('$' + numberFormat(shippingCost, 2));
			if(deliveryDiscount){
				$('.shippingCost').attr('title', 'Your saving $'+numberFormat(deliveryDiscount, 2));
				$('.shippingDiscount').html('Your saving $'+numberFormat(deliveryDiscount, 2));
			}
			else{
				$('.shippingCost').attr('title', '');
				$('.shippingDiscount').html('');
			}
			$('.totalCost').html('$' + numberFormat(total, 2));
			//$('.totalCost').attr('title', (deliveryDiscount+itemDiscount)?'You save $'+(deliveryDiscount+itemDiscount):'');
			if(deliveryDiscount*1+itemDiscount*1){
				$('.totalCost').attr('title', 'Your saving $'+numberFormat(deliveryDiscount*1+itemDiscount*1, 2));
				$('.totalDiscount').html('Your saving $'+numberFormat(deliveryDiscount*1+itemDiscount*1, 2));
			}
			else{
				$('.totalCost').attr('title', '');
				$('.totalDiscount').html('');
			}

		});


	}
	else{
		var total = (subTotal*100+shippingCost*100)/100;
		$('.subTotal').html('$' + numberFormat(subTotal, 2));
		$('.shippingCost').html('$' + numberFormat(shippingCost, 2));
		$('.totalCost').html('$' + numberFormat(total, 2));

	}
}


function numberFormat (number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands
    //
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/number_format
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +     input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +     improved by: davook
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Jay Klehr
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *     example 10: number_format('1.20', 2);
    // *     returns 10: '1.20'
    // *     example 11: number_format('1.20', 4);
    // *     returns 11: '1.2000'
    // *     example 12: number_format('1.2000', 3);
    // *     returns 12: '1.200'
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

/*
function numberFormat(number, decimals, point, separator){
	point = point ? point : '.';
	number = number.toString().split('.');

	if(separator){
		var tmp_number = new Array();
		var negative = false;
		if(number[0] < 0){
			negative = true;
			number[0] = number[0].substring(1); // strip the - sign
		}
		
		for(var i = number[0].length, j = 0; i > 0; i -= 3){
			var pos = i > 0 ? i - 3 : i;
			tmp_number[j++] = number[0].substring(i, pos);
		}
		number[0] = tmp_number.reverse().join(separator);
		if(negative){
			number[0] = '-' + number[0];
		}
	}

	if(decimals){
		number[1] = number[1] ? number[1] : '0';
		var size = decimals - number[1].toString().length;
		if(size < 0){
			number[1] = number[1].substring(0, decimals);
		}
		else{
			for(var i = 0; i < size; i++)
				number[1] += '0';
		}
	}

	return(number.join(point));
}
*/




// this will verify the form contents
function validateCheckoutForm(){
	var isError = false;
	var errorMsg = "";

	try{
		// make sure the form is complete
		if(document.checkoutForm.email.value == ''){
			isError = true;
			errorMsg += "\nAn email address must be included.";
		}
		if(document.checkoutForm.firstName.value == ''){
			isError = true;
			errorMsg += "\nYour first name must be included.";
		}
		if(document.checkoutForm.lastName.value == ''){
			isError = true;
			errorMsg += "\nYour last name must be included.";
		}
		if(document.checkoutForm.ccNumber){
			if(document.checkoutForm.ccNumber.value == ''){
				isError = true;
				errorMsg += "\nYour credit card number must be included.";
			}
			else{
				var found = false;
				for(var i = 0; i < cc_choices.length; i++){
						if(cc_choices[i] == document.checkoutForm.ccType.value){
							found = true;
							break;
						}
				}
				if(found == true && checkCreditCard (document.checkoutForm.ccNumber.value, document.checkoutForm.ccType.value) == false){
					isError = true;
					errorMsg += "\nThe credit card number is incorrect.";
				}
			}
		}
		if(document.checkoutForm.ccType && document.checkoutForm.ccType.value == ''){
			isError = true;
			errorMsg += "\nYour credit card type must be included.";
		}
		if(document.checkoutForm.ccYear && document.checkoutForm.ccYear.value == ''){
			isError = true;
			errorMsg += "\nYour credit card expirey year must be included.";
		}
		if(document.checkoutForm.ccMonth && document.checkoutForm.ccMonth.value == ''){
			isError = true;
			errorMsg += "\nYour credit card expirey month must be included.";
		}
		if(document.checkoutForm.ccCVV && document.checkoutForm.ccCVV.value == ''){
			isError = true;
			errorMsg += "\nA credit cards cvv must be included.";
		}
		if(document.checkoutForm.addr1.value == ''){
			isError = true;
			errorMsg += "\nA street address must be included.";
		}
		if(document.checkoutForm.municipality.value == ''){
			isError = true;
			errorMsg += "\nA city must be included.";
		}
		if(document.checkoutForm.postalCode.value == ''){
			isError = true;
			errorMsg += "\nA zip code must be included.";
		}
		if(document.checkoutForm.country.value == ''){
			isError = true;
			errorMsg += "\nA country must be included.";
		}

		if(isError == true){
			alert(errorMsg);
			return false;
		}
		else{
			return true;
		}
	}
	catch(e){
		if(e instanceof TypeError){
			alert("You must fill out the form completely and correctly!");
			alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message);
			return false;
		}
		else if(e instanceof SyntaxError){
			alert("There is an error in the JavaScript code. Please inform the webmaster of this site.");
			return false;
		}
		else if(e instanceof RangeError){
			alert("You must fill out the form completely and correctly!");
			return false;
		}
		else if(e instanceof ReferenceError){
			alert("There is an error in the site code. Please inform the webmaster of this site.");
			return false;
		}
		else{
			alert("An exception occurred in the script. Error name: " + e.name + ". Error message: " + e.message);
			return false;
		}
		
	}
	finally{
		//alert("finally");
	}
}

// creates popup that explains what a cvv number is
function openCVV(){
	thewindow = window.open('/cvv.php', 'cnew', config='height=650,width=500,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,directories=no,status=yes');
}

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

var cc_choices = new Array('Visa','MasterCard','DinersClub','CarteBlanche','AmEx');

function checkCreditCard (cardnumber, cardname) {

  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
  
  // Check that the number is numeric, although we do permit a space to occur  
  // every four digits. 
  var cardNo = cardnumber
  var cardexp = /^([0-9]{4})\s?([0-9]{4})\s?([0-9]{4})\s?([0-9]{1,4})$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardexp.exec(cardNo);
  cardNo = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}