var personalization = false;
var inven_qty;

function format_amount(num,currency)
{
   if (typeof(num) == "undefined") return 0;
   num = num.toString().replace(/\$|\,/g,'');
   if (num == '') return '';
   if (isNaN(num)) num = "0";
   var sign = (num == (num = Math.abs(num)));
   num = Math.floor(num*100+0.50000000001);
   var cents = num%100;
   num = Math.floor(num/100).toString();
   if (cents < 10) cents = "0" + cents;
   for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
      num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
   var curr_prefix = '';   var curr_suffix = '';
   if (typeof(currency) != "undefined") {
      if (currency == 'EUR') {
         curr_prefix = '€';   curr_suffix = ' EUR';
      }
      else if (currency == 'CAD') curr_prefix = 'Can$';
      else curr_prefix = '$';
   }
   return (((sign)?'':'-') + curr_prefix + num + '.' + cents + curr_suffix);
}

function parse_amount(num)
{
   num = num.toString().replace(/\$|\,/g,'');
   if (isNaN(num)) return 0;
   var float_num = parseFloat(num);
   if (isNaN(float_num)) return 0;
   return float_num;
}

function display_login(login_status)
{
    
            var ni = document.getElementById('loginBox');
            var newanchor = document.createElement('a');

          if (login_status)
          {
             newanchor.setAttribute("href","cart/my-account.php?Logout=Go&ContinueURL=/index.html");
             newanchor.setAttribute("title","Logout");
             newanchor.setAttribute("style","color:#ffffff;");
             newanchor.appendChild(document.createTextNode("Logout"));
          }
          else 
          {
             newanchor.setAttribute("href","cart/my-account.php?ContinueURL=/index.html");
             newanchor.setAttribute("title","Login");
             newanchor.setAttribute("style","color:#ffffff;");
             newanchor.appendChild(document.createTextNode("Login"));
          }
          ni.appendChild(newanchor);
}

function display_inventory(id)
{
    var attr_index = 0;
    var attr_compare = '';
    var attribute_field = document.DisplayProduct['attr_0_'+id];
    while (attribute_field) {
       var attribute_value = attribute_field.options[attribute_field.selectedIndex].value;
       if (attr_compare != '') attr_compare += '-';
       attr_compare += attribute_value;
       attr_index++;
       attribute_field = document.DisplayProduct['attr_'+attr_index+'_'+id];
    }
    var price_cell = document.getElementById('price_'+id);
    var avail_cell = document.getElementById('avail_'+id);

    var inventory_array = inventory_data[id];
    var price_value = '';   var avail_value = '';
    var lowest_price = 0;
    for (var index in inventory_array) {
       var price = inventory_array[index][6];
       if ((price_value == '') && (attr_compare != '') &&
           (inventory_array[index][3].substring(0,attr_compare.length) == attr_compare)) {
          price_value = format_amount(price,'USD');
       }
       if (inventory_array[index][3] == attr_compare) {
          price_value = format_amount(price,'USD');
          var qty = parseInt(inventory_array[index][5],10);
          if (qty <= 0) avail_value = 'Back Order';
          else avail_value = 'In Stock';
          break;
       }
       if (lowest_price == 0) lowest_price = price;
       else if (price < lowest_price) lowest_price = price;
    }
    if (price_value == '') {
       if (lowest_price == 0) price_value = 'n/a';
       else price_value = format_amount(lowest_price,'USD') + ' +';
    }
    price_cell.innerHTML = price_value;   avail_cell.innerHTML = avail_value;
    if (personalization) update_per_price();
}

function close_enlarge()
{
   var enlarge_div = document.getElementById('enlarge_div');
   enlarge_div.style.display = 'none';
   enlarge_div.innerHTML = '';
}

var current_image = null;

function enlarge_image(filename,width,height)
{
   if (current_image != null) filename = current_image;
   if (document.documentElement && document.documentElement.scrollWidth)
      var body_width = document.documentElement.scrollWidth;
   else if (document.body) var body_width = document.body.scrollWidth;
   else var body_width = -1;
   if (document.documentElement && document.documentElement.clientHeight)
      var client_height = document.documentElement.clientHeight;
   else if (document.body) var client_height = document.body.clientHeight;
   else var client_height = -1;
   var divX = (body_width - width) / 2;
   var divY = (client_height - height) / 2;
   var html = "<div><img src='images/large/" + filename + "' class='enlarge_image'>";
   html += "</div><div class='enlarge_footer'><table cellpading='0' cellspacing='0' width ='100' align='center'><tr><td><a href=\"\" onclick=\"close_enlarge();";
   html += " return false;\" ><img src=\"cartimages/close.gif\" alt=\"Close Window\" border='0' /></a></td><td><a href=\"\" style='color:#000' onclick=\"close_enlarge();";
   html += " return false;\" >Click to Close</a></td></tr></table></div>";
   var enlarge_div = document.getElementById('enlarge_div');
   enlarge_div.innerHTML = html;
   enlarge_div.style.width = width+"px";
   enlarge_div.style.height = height+"px";
   enlarge_div.style.left = divX+"px";
   enlarge_div.style.top = 250+"px";
   enlarge_div.style.display = '';
   enlarge_div.style.zIndex = '50';
}

function switch_image(filename)
{
   var product_image = document.getElementById('product_image');
   product_image.src = "images/medium/" + filename;
   current_image = filename;
}

function check_attributes(id)
{
    var attr_index = 0;
    var field_name = 'attr_0';
    if (id) field_name += '_'+id;
    var attribute_field = document.DisplayProduct[field_name];
    while (attribute_field) {
       var attribute_value = attribute_field.options[attribute_field.selectedIndex].value;
       if (attribute_value == '') {
          var label_field_name = 'label_'+attr_index;
          if (id) label_field_name += '_'+id;
          var label_field = document.getElementById(label_field_name);
          if (! label_field) label_field = document.getElementById('label_'+attr_index);
          if (! label_field)
             var label = attribute_field.options[attribute_field.selectedIndex].text;
          else var label = label_field.innerHTML;
          alert('You must select a '+label);   attribute_field.focus();   return false;
       }
       attr_index++;
       field_name = 'attr_'+attr_index;
       if (id) field_name += '_'+id;
       attribute_field = document.DisplayProduct[field_name];
    }
    return true;
}

function display_price(attr_id){
  var id = document.DisplayProduct.id.value;
  var attr_list = attribute_data[id];
  var index = 0;
  var attr_compare = '';
  var attr_count = 0;
  var adjustment = 0;
  var num_attr = 0;
  var qty_field = document.getElementsByName('qty')[0];
  var qty = (!isNaN(qty_field.value))?qty_field.value:0;
  var list_price_cell = document.getElementById('list_price'); //does not exist
  var price_cell = document.getElementById('qty_price_div');
  var sale_price_cell = document.getElementById('sale_price'); //does not exist
  var out_of_stock_cell = document.getElementById('out_of_stock'); // does not exist: should exist :(
  for(attr_list_id in attr_list){
    if(isNaN(attr_list_id)) continue;
	if(attribute_data[id][attr_list_id][7] == '1'){//7 is subproduct
	  var field_name = 'attr_'+index;
	  if(typeof(document.DisplayProduct[field_name]) == 'undefined') break;
	  var field = document.DisplayProduct[field_name];
	  if(typeof(field.options == ' undefined')) var field_value = field.value;
	  else field_value = field.options[field.selectedIndex].value;
	  if(attr_compare != '') attr_compare += '-';
	  attr_compare += field_value;
	  
	  attr_count ++;
	}
	var attr_list_field = document.DisplayProduct['attr_' + attr_list_id];
    if (attr_list_field && (attr_list_field.selectedIndex != -1)) {
      var option_id = attr_list_field.options[attr_list_field.selectedIndex].value;
      var option_data = attribute_options[id][attr_list_id][option_id];
      if (option_data) adjustment += parse_amount(option_data[4]);
    }
    index++;
  }
  var inventory_array = inventory_data[id]; // loads current product's invnetory data.
  var lowest_price = 0; // lowest price
  var inv_attributes_pos = inventory_fields.indexOf('attributes');
  var inv_qty_pos = inventory_fields.indexOf('qty');
  var inv_list_price_pos = array_index(inventory_fields,'list_price');
  var inv_price_pos = array_index(inventory_fields,'price');
  var inv_sale_price_pos = array_index(inventory_fields,'sale_price');
  for (var index in inventory_array) {
    if (isNaN(index)) continue;
	if(inv_attributes_pos>=0){
	   if(inventory_array[index][inv_attributes_pos] == '') num_attr = 0;
       else {
           attr_arr = inventory_array[index][inv_attributes_pos].split('-');
           num_attr = attr_arr.length;
       }
	}else{
	 num_attr = 0;
	}
	if(inv_qty_pos) var inventory_qty = inventory_array[index][inv_qty_pos];
	else var inventory_qty = false;
	if (inv_list_price_pos == -1) var list_price = '';//no list price in inventory
    else var list_price = inventory_array[index][inv_list_price_pos];//list price in inventory
    if (inv_price_pos == -1) {
      if (document.DisplayProduct.base_price)
        var price = parse_amount(document.DisplayProduct.base_price.value);
        else var price = '';
    }
    else var price = inventory_array[index][inv_price_pos];
    if (inv_sale_price_pos == -1) var sale_price = '';
    else var sale_price = inventory_array[index][inv_sale_price_pos];
	if (adjustment > 0) {
      if (list_price != '') list_price += adjustment;
      if (price != '') price += adjustment;
      if (sale_price != '') sale_price += adjustment;
    }
    if (num_attr != attr_count){
	  log('number of attrs in inventory does not match attr_count');
	  continue;
	}
	//add in qty
	if(list_price != '') list_price = list_price * qty;
	if(price != '') price= price * qty;
	if(sale_price != '') sale_price = sale_price * qty;
	
	log('inventory_array[index][inv_attributes_pos] == attr_compare::'+(inventory_array[index][inv_attributes_pos] == attr_compare));
	if (inventory_array[index][inv_attributes_pos] == attr_compare){
	  if(price_cell){
        if (price == '')price_cell.innerHTML = format_amount(0,'USD');
        else price_cell.innerHTML = format_amount(price,'USD');
	  }
      if (list_price != '') if(list_price_cell) list_price_cell.innerHTML = format_amount(list_price,'USD');
      if (sale_price != '') if(sale_price_cell) sale_price_cell.innerHTML = format_amount(sale_price,'USD');
	  if(inventory_qty!==false){
	    if (inventory_qty > 0 || inventory_qty == ""){
          if (out_of_stock_cell) out_of_stock_cell.innerHTML = '&nbsp;';
          if(document.getElementById('AddToCart')){
            if(document.getElementById('AddToCart').disabled == true){
              document.getElementById('AddToCart').disabled = false;
              document.getElementById('AddToCart').src = 'cartimages/add-to-cart.gif';
            }
          }
        }else{
          if (out_of_stock_cell) out_of_stock_cell.innerHTML = 'OUT OF STOCK';
          if(document.getElementById('AddToCart')){
            var backorder = confirm("Your current selection is out of stock. Would you like to backorder it?");
            if(!backorder){
              document.getElementsByName('AddToCart')[0].disabled = true;
              document.getElementsByName('AddToCart')[0].src = 'cartimages/add-to-cart-disabled.gif';
            }else{
		      document.getElementsByName('AddToCart')[0].disabled = false;
              document.getElementsByName('AddToCart')[0].src = 'cartimages/add-to-cart.gif';
            }
          }
        }
	  }
	  return;
    }
	if (num_attr > 0)
      if (lowest_price == 0) lowest_price = price;
      else if (price < lowest_price) lowest_price = price;
  }
  if (lowest_price == 0) price_cell.innerHTML = 'n/a';
  else { 
    if (list_price_cell)
        list_price_cell.innerHTML = format_amount(list_price,'USD') + "+";
    if (price_cell)
        price_cell.innerHTML = format_amount(lowest_price,'USD') + "+";
    if (sale_price_cell)
        sale_price_cell.innerHTML = format_amount(sale_price,'USD') + "+";
  }
}

function old_display_price(attr_id)
{
    var id = document.DisplayProduct.id.value;
    var attr_list = attribute_data[id];
    var attr_compare = '';
    var currency = 'USD';
    var index = 0;
    var num_attr = 0;
    var attr_count = 0;
    var adjustment = 0;
    for(attr_list_id in attribute_data[id]) {
      if (isNaN(attr_list_id)) continue;
	  log(attr_list_id);
	  log(attribute_data[id][attr_list_id][7]);//7 is subproduct
      if(attribute_data[id][attr_list_id][7] == '1')
      {
         var field_name = 'attr_' + index;
		 log(document.DisplayProduct[field_name]);
         if (typeof(document.DisplayProduct[field_name]) == "undefined") break;
         var field = document.DisplayProduct[field_name];
         if (typeof(field.options == "undefined")) var field_value = field.value;
         else field_value = field.options[field.selectedIndex].value;

         if (attr_compare != "") attr_compare += "-";
           attr_compare += field_value;
         
         attr_count++;
      }
       /*if (index > 0) attr_compare += "-";
       attr_compare += field_value;
       if (typeof(attr_images) != "undefined") {
          var attribute_image = document.getElementById('attribute_image');
          if (typeof(attr_images[field_value]) != "undefined")
             attribute_image.src = 'attrimages/medium/' + attr_images[field_value];
          else attribute_image.src = 'cartengine/images/blank.gif';
       }*/
       var attr_list_field = document.DisplayProduct['attr_' + attr_list_id];
       if (attr_list_field && (attr_list_field.selectedIndex != -1)) {
          var option_id = attr_list_field.options[attr_list_field.selectedIndex].value;
          var option_data = attribute_options[id][attr_list_id][option_id];
          if (option_data) adjustment += parse_amount(option_data[4]);
       }
       index++;
    }
    var list_price_cell = document.getElementById('list_price');

    var price_cell = document.getElementById('price');
    if (! price_cell) price_cell = document.getElementById('qty_price_div');
    var sale_price_cell = document.getElementById('sale_price');
    var out_of_stock_cell = document.getElementById('out_of_stock');
    var inventory_array = inventory_data[id];
    var lowest_price = 0;
    
    for (var index in inventory_array) {
       if (isNaN(index)) continue;
       else if (inventory_array[index][3] == '') num_attr = 0;
       else {
           attr_arr = inventory_array[index][3].split('-');
           num_attr = attr_arr.length;
       }
       var inventory_qty = inventory_array[index][5];
       var list_price_index = array_index(inventory_fields,'list_price');
       if (list_price_index == -1) var list_price = '';
       else var list_price = inventory_array[index][list_price_index];
       var price_index = array_index(inventory_fields,'price');
       if (price_index == -1) {
          if (document.DisplayProduct.base_price)
             var price = parse_amount(document.DisplayProduct.base_price.value);
          else var price = '';
       }
       else var price = inventory_array[index][price_index];
       var sale_price_index = array_index(inventory_fields,'sale_price');
       if (sale_price_index == -1) var sale_price = '';
       else var sale_price = inventory_array[index][sale_price_index];
       if (adjustment > 0) {
          if (list_price != '') list_price += adjustment;
          if (price != '') price += adjustment;
          if (sale_price != '') sale_price += adjustment;
       }
       if (num_attr != attr_count) continue;
       if (inventory_array[index][3] == attr_compare)
       {
          if (price == '') price_cell.innerHTML = format_amount(0,'USD');
          else price_cell.innerHTML = format_amount(price,'USD');
          if (list_price != '') list_price_cell.innerHTML = format_amount(list_price,'USD');
          if (sale_price != '') sale_price_cell.innerHTML = format_amount(sale_price,'USD');
          if (inventory_qty > 0 || inventory_qty == "")
          {
              if (out_of_stock_cell) out_of_stock_cell.innerHTML = '&nbsp;';
              if(document.getElementById('AddToCart'))
              {
                  if(document.getElementById('AddToCart').disabled == true)
                  {
                     document.getElementById('AddToCart').disabled = false;
                     document.getElementById('AddToCart').src = 'cartimages/add-to-cart.gif';
                  }
              }
          }
          else
          {
              if (out_of_stock_cell) out_of_stock_cell.innerHTML = 'OUT OF STOCK';
              if(document.getElementById('AddToCart'))
              {
                  var backorder = confirm("Your current selection is out of stock. Would you like to backorder it?");
                  if(!backorder)
                  {
                     document.getElementById('AddToCart').disabled = true;
                     document.getElementById('AddToCart').src = 'cartimages/add-to-cart-disabled.gif';
                  }
                  else
                  {
                     document.getElementById('AddToCart').disabled = false;
                     document.getElementById('AddToCart').src = 'cartimages/add-to-cart.gif';
                  }
              }
          }
          if (personalization) {
             update_per_price();   change_per_attribute(attr_id);
          }
          return;
       }
       if (num_attr > 0)
          if (lowest_price == 0) lowest_price = price;
          else if (price < lowest_price) lowest_price = price;
    }
    if (lowest_price == 0) price_cell.innerHTML = 'n/a';
    else { 
       if (list_price_cell)
          list_price_cell.innerHTML = format_amount(list_price,'USD') + "+";
       if (price_cell)
          price_cell.innerHTML = format_amount(lowest_price,'USD') + "+";
       if (sale_price_cell)
          sale_price_cell.innerHTML = format_amount(sale_price,'USD') + "+";
    }
    
    if (personalization) {
       update_per_price();   change_per_attribute(attr_id);
    }
}

function log(str){
  if(window)if(window.console)if(window.console.log)window.console.log(str);
}

function validate_form()
{
    var form = document.DisplayProduct;
    //parse_text_attribute(form);
    if (form.ids && (form.ids.value != '')) {
       var ids = form.ids.value;
       var id_array = ids.split(",");
       var qty_found = false;
       for (var index in id_array) {
          var id = id_array[index];
          var field_name = 'qty_' + id;
          var qty = form[field_name].value;
          if (qty == '') continue;
          if (isNaN(qty)) {
             form[field_name].value = '';   continue;
          }
          qty = parseInt(qty,10);
          if (isNaN(qty)) {
             form[field_name].value = '';   continue;
          }
          if (qty != 0) {
             qty_found = true;
             if (! check_attributes(id)) return false;
          }
       }
       if (! qty_found) {
          alert('You must supply at least one quantity before adding to cart.');
          return false;
       }
    }
    else if (form.id) {
       var qty = form['qty'].value;
       if (qty == '') qty = 0;
       if (isNaN(qty)) qty = 0;
       qty = parseInt(qty,10);
       if (isNaN(qty)) qty = 0;
       if (qty == 0) {
          alert('You must specify a quantity before adding to cart.');
          form['qty'].focus();   return false;
       }
       if (form['inve'].value < qty && form['inve'].value > 0)
       {
           alert("You have ordered more than we have in stock. Please lower the amount that your are ordering.");
           
           return false;
       }
       else if (form['inve'].value <= 0)
       {
           alert("We're sorry this item is out of stock.");
           return false;
       }
       if (! check_attributes(null)) return false;
    }
    if (personalization && (! validate_personalization())) return false;
    return true;
}


function onlyint(e,field)
{
    if (window.event) keynum = e.keyCode;
    else if (e.which) keynum = e.which;
    
    if(keynum == "0x0b") return true;//allow tabs
    if (keynum == "0x08") return true;
    if (keynum == "0x09") return true;
      if (keynum == "0x20") return true;
    if (keynum == "0x2d" && field == 'phone') return true;
    if (keynum == "0x2E" && field == 'currency') return true;
    if (keynum == "0x2F" && field == 'date') return true;
    if ((keynum >= "0x30") && (keynum <="0x39")) return true;
    return false;
}

function gift_wrapping(field)
{
    if(field.value == 2)
    {    
        document.DisplayProduct.attr_1[0].disabled = true;
        document.DisplayProduct.attr_1[1].disabled = true;
        document.DisplayProduct.attr_2[0].disabled = true;
        document.DisplayProduct.attr_2[1].disabled = true;
        
        document.getElementById('textFieldAttr').style.backgroundColor = "#eeeeee";
        document.getElementById('textFieldAttr').style.backgroundImage= "url(images/backgrounds/shadow.gif)";
        document.getElementById('textFieldAttr').style.borderTop = "1px solid #CCCCCC";
        document.getElementById('textFieldAttr').style.borderBottom = "1px solid #efefef";
        document.getElementById('textFieldAttr').style.borderLeft = "1px solid #efefef";
        document.getElementById('textFieldAttr').style.borderRight = "1px solid #efefef";
        document.getElementById('textFieldAttr').disabled = true;
    }
    else
    {    
        document.DisplayProduct.attr_1[0].disabled = false;
        document.DisplayProduct.attr_1[1].disabled = false;
        document.DisplayProduct.attr_2[0].disabled = false;
        document.DisplayProduct.attr_2[1].disabled = false;
        document.getElementById('textFieldAttr').style.backgroundColor = "#ffffff";
        document.getElementById('textFieldAttr').style.backgroundImage= "url(images/backgrounds/shadow.gif)";
        document.getElementById('textFieldAttr').style.borderTop = "1px solid #CCCCCC";
        document.getElementById('textFieldAttr').style.borderBottom = "1px solid #efefef";
        document.getElementById('textFieldAttr').style.borderLeft = "1px solid #efefef";
        document.getElementById('textFieldAttr').style.borderRight = "1px solid #efefef";
        document.getElementById('textFieldAttr').disabled = false;
    }
    //gw.invoke('disable');
}

function activate_textarea(field,id)
{
    $(field).value = "*"+id+"*";
}

function parse_text_attribute(form)
{
    var textInput = document.getElementById('textFieldAttr');
    
    if(form['fname'])
    {
        textInput.value = form['fname'].value+"|"+form['lname'].value+"|"+form['phone'].value+"|"+form['address'].value+"|"+form['city'].value+"|"+form['state'].value+"|"+form['zip'].value;
    }
}

