/* - - - - - - - - - - - - - - - - - - - - - - -
Global functions
 - - - - - - - - - - - - - - - - - - - - - - - */


var browser=navigator.appName;
var isIE =  (browser=="Microsoft Internet Explorer");

//var isIE = window.event?true:false;
var isNS = !isIE;
var imgs = new Array();

 function numbers_only(e, idx) {
   var _ret = true;
   if (isIE) {
     code = window.event.keyCode;
   }
   if (isNS) {
     code = e.which;
   }
   if ( code == 16 || code == 17 || code == 8 || code == 0 || code == 13 || code == 37 || code == 9 || code == 39        //valid keyboard codes
         || code == 190) {   //. char
   } else if (code < 46 || code > 57) {
     _ret = false;
   }
   return (_ret);
 }

 function get_metalfactor(idx) {
   s = document.getElementById('style'+idx).value;
   if (s.indexOf('AGS') > -1) return 0.01039;
   if (s.indexOf('AGF') > -1) return 0.01039;
   if (s.indexOf('09') > -1 && s.indexOf('Y') > -1) return 0.0112;
   if (s.indexOf('09') > -1 && s.indexOf('W') > -1) return 0.0119;
   if (s.indexOf('09') > -1 && s.indexOf('R') > -1) return 0.0111;
   if (s.indexOf('18') > -1 && s.indexOf('Y') > -1) return 0.0155;
   if (s.indexOf('18') > -1 && s.indexOf('W') > -1) return 0.0162;
   if (s.indexOf('18') > -1 && s.indexOf('R') > -1) return 0.0152;
   if (s.indexOf('22') > -1) return 0.0178;
   if (s.indexOf('PLT') > -1) return 0.0201;
   alert('metal factor not found');
 }


//manage sizes
var available_sizes;
available_sizes = new Array();

function do_load_sizes(product_name_id, metal, idx, category) {
  s = document.getElementById('size'+idx).style.display = 'none';
  pc = document.getElementById('style'+idx).value; //metalstyle

//  category = wire_types[idx][3];
  results_div = 'sizeresults'+idx;
  loading_div = 'sizeloading'+idx;
  current_idx = idx;
  document.getElementById(results_div).style.display = 'none'; //hide the results
  document.getElementById(loading_div).style.display = ''; //show 'loading'
  xmlHttp=GetXmlHttpObject() //get the correct Ajax object
  if (xmlHttp==null) {
    alert ("Browser does not support HTTP Request")
    return
  }
  var url="/ajax/load_sizes.php" //build the URL to call that will populate the results pane
  url = url + '?style='+pc+
              '&category='+category+
              '&metal='+metal+
              '&pni='+product_name_id+
              '&idx='+idx;
  xmlHttp.onreadystatechange=product_sizestateChanged //set an event that is called when the state changes
  xmlHttp.open("GET",url,true) //connect to the url
  xmlHttp.send(null); //call the url
}
function product_sizestateChanged() {
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { //if it is complete...
    document.getElementById(loading_div).style.display = 'none'; //hide the 'loading'
    if (xmlHttp.responseText == '') {
      document.getElementById(results_div).innerHTML='<br>'; //fill the results
    } else {
      document.getElementById(results_div).innerHTML=xmlHttp.responseText; //fill the results
      load_size_html();
    }
    document.getElementById(results_div).style.display = ''; //show the 'results'
  } else {
    document.getElementById(results_div).innerHTML=='Loading...' //if there is a different state then just show loading
  }
}

function start_array(idx) {
  available_sizes[idx] = new Array();
}
function add_to_array(i, idx, code, text) {
  available_sizes[idx][i] = new Array();
  available_sizes[idx][i][0] = code;
  available_sizes[idx][i][1] = text;
}
function load_size_html() {
  sr = document.getElementById('size_results'+current_idx).value;
  sizes = sr.split(',');
  start_array(current_idx);
  array_index = 0;
  for(i=0;i<sizes.length;i=i+2) {
    add_to_array(array_index, current_idx, sizes[i], sizes[i+1]);
    array_index ++;
  };

  s = document.getElementById('size'+current_idx);

  //clear it out
  for(i=s.length-1;i>=0;i--) {
    s.remove(i);
  }
  //add the new ones
  for(i = 0;i<available_sizes[current_idx].length;i++) {
    var y=document.createElement('option');
    y.text=available_sizes[current_idx][i][1];
    y.value=available_sizes[current_idx][i][0];
    try {
      s.add(y, null);
    } catch(ex) {
      s.add(y); // IE only
    }
  }

  s.style.display = '';

  f = document.getElementById('finishing'+current_idx);
  if (f) {
    if (f.style.display == 'none') {
      f.style.display = '';
    } else {
      f.style.display = 'none';
    };
  };

  //size images
  si = document.getElementById('size_images'+current_idx).value;
  sizeimages = si.split(',');
  imgs[current_idx] = new Array();
  array_index = 0;
  for(i=0;i<sizeimages.length;i++) {   //skip the first one
    imgs[current_idx][i] = sizeimages[i];
  };
  //set first index to the main image
  id = document.getElementById('productimage'+current_idx);
  imgs[current_idx][0] = id.src;
}

function product_stateChanged() {
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { //if it is complete...
    document.getElementById(loading_div).style.display = 'none'; //hide the 'loading'
    if (xmlHttp.responseText == '') {
      document.getElementById(results_div).innerHTML='<br>'; //fill the results
    } else {
      document.getElementById(results_div).innerHTML=xmlHttp.responseText; //fill the results
      setup_uom();
      calc_price();
    }
    document.getElementById(results_div).style.display = ''; //show the 'results'
  } else {
    document.getElementById(results_div).innerHTML=='Loading...' //if there is a different state then just show loading
  }
}

//when the calculation is qty * price
 function calc_price_each(idx) {
   if (idx == undefined) {
   } else {
     p = document.getElementById('product_price' + idx);
     if (p) {
       pv = p.innerHTML;  //check to make sure a product has a price
       if (pv != '') {
         //if there is a unit weight associated with this unit - then use that one
         w = document.getElementById('product_weight' + idx);
         if (w && w.innerHTML != '') {
           wght = w.innerHTML;
         } else {
           //else the unit weight is the qty e.g. Grains
           w = document.getElementById('qty' + idx);
           wght = w.value;
         };

         if ( wght == NaN || wght == '' ) wght = 0;

         w = document.getElementById('display_weight' + idx);
         if (w) {
           x = parseFloat(wght);
           w.value = x.toFixed(2);
         };

         price = pv * wght;

         price = price * pv;

         prc = document.getElementById('price' + idx);
         prc.value = price.toFixed(2);  //round to 4dps at this stage.  IE5.5 and NS6+
       };
     };
   };
 }


function do_buy(idx,type) {
  if (idx == -1) {
    if (document.wire_form.freeformat.value == '') {
      alert('Please enter some details to help us find what you are looking for.');
    } else {
      document.location.href = '/shoppingcart.php?action=add&pcode='+type+'&qty=x&freeformat='+document.wire_form.freeformat.value;
    };
  } else {
    pcode = document.getElementById('results'+idx).innerHTML;
    prod_price = document.getElementById('product_price'+idx);
    qty = document.getElementById('qty'+idx).value;
    len = document.getElementById('length'+idx)
    if (typeof len != "undefined"  && len != null) {
      len = len.value;
    } else {
      len = false;
    };
    wdth = document.getElementById('width'+idx)
    if (wdth) {
      wdth = wdth.value;
    };
    sizecode = document.getElementById('size'+idx);
    if ( (sizecode) && (sizecode.value) && (sizecode.value != '') ) {
      sizecode = sizecode.value;
    } else {
      sizecode = '';
    };

    price = document.getElementById('price'+idx).value;

    fc = '';
    hm = '';
    fac = '';
    fcrq = document.getElementById('finishing_rqd'+idx);
    if (fcrq != null && fcrq.checked) {     //only add finishing codes if user has requested some
      if (typeof fin_charges!="undefined") {
        fcstart = '&fc=';
        cma='';
        for(i=0;i<fin_charges.length;i++) {
          cd = 'finishing_code'+idx+'_'+fin_charges[i][0];
          fchrgeid = document.getElementById(cd);
          if (fchrgeid != null) {
            if ( (fin_charges[i][0] != '') && (fchrgeid.checked) ) {
              fc = fc + fcstart + cma + fin_charges[i][0];
              cma = ',';
              fcstart = '';
            };
          };
        };
      };
    };

    hm = document.getElementById('hallmark_code'+idx);
    if (hm) {
      hm = '&hm='+hm.value;
    } else {
      hm = '';
    };

    fac = document.getElementById('fashion_code'+idx);
    if (fac) {
      fac = '&fac='+fac.value;
    } else {
      fac = '';
    };

    msg = '';
    ring_size_value = document.getElementById('ringsize'+idx);
    if (ring_size_value && (ring_size_value.style.display == '')) {   //if there is a ringsize and its showing, then must be set!
      //ring_size_value = ring_size_value.value;
      ring_size_value = ring_size_value.options[ring_size_value.selectedIndex].text
      if (ring_size_value == '') msg = msg + "Please select a ring size.\n";
    } else {
      ring_size_value = false;
    };

    if (prod_price == null || prod_price.innerHTML == '') msg = msg + "Please select a product.\n";
    if ( typeof len == "string" && len == '' )  msg = msg + "Please enter a length.\n";
    if (qty == '')   msg = msg + "Please enter a quantity.\n";

    if (msg == '') {
      if (pcode.indexOf('<') > -1) {
        p = pcode.substr(0, pcode.indexOf('<'));     //chop out just the product code
      } else {
        p = pcode;
      };
      //PCode, val1,val2,val3,type
      url = 'p='+p+'&t='+type+'&s='+sizecode+'&v1='+qty+fc+hm+fac;
      if (len) url = url + '&v2='+len;
      if (wdth) url = url + '&v3='+wdth;
      if (ring_size_value) url = url + '&ring_size_value='+ring_size_value;

      document.location.href = '/shoppingcart.php?action=add&'+url;
    } else {
      alert("Please correct the following errors before buying this product.\n\n" + msg);
    };
  };
}

function setup_uom() {
  wght_unit = document.getElementById('weight_unit' + current_idx);
  wght_result = '';
  if (wght_unit) {
    w = wght_unit.innerHTML;
    if (w == 'GM') wght_result = 'Gram'
    else if (w == 'KG') wght_result = 'Kilogram'
    else if (w == 'PA') {
		  wght_result = 'Per Item';
			//special for Findings/Ear Fittings/Scrolls
		  size_settings = document.getElementById('size'+current_idx);
			if (size_settings) {
			  if ((size_settings.value == 'XLGSC') ||
    				(size_settings.value == 'SDMED') ||
    				(size_settings.value == 'SCSMA') ||
    				(size_settings.value == 'SCSTD')) {
				  wght_result = 'Per Pair';
				};
			};
		}	
    else if (w == 'EA') wght_result = 'Each';
  };
  wght_unit_display = document.getElementById('uom'+current_idx);
  if (wght_unit_display) {
    wght_unit_display.innerHTML = wght_result;
  };
}

function calc_discounts(total_weight, current_price, idx, js_pcnt_intervals) {
//  js_ds = document.getElementById('discounts' + idx);
//  if ( (js_ds != null) && (current_price > 0)) {  //discounts are set
//    js_discount_string = js_ds.innerHTML;
//    js_discount_parts = js_discount_string.split('|');
//    js_pcnt_intervals = js_discount_parts[0].split(',');
//    js_pcnt_intervals[0] = js_pcnt_intervals[0].substr( js_pcnt_intervals[0].indexOf(':')+1 ); //chop off the INTVL
//    js_units          = js_discount_parts[1].split(':');
//    js_volumes        = js_discount_parts[2].split(',');
//    js_volumes[0] = js_volumes[0].substr( js_volumes[0].indexOf(':')+1 ); //chop off the QTY
//    js_fixed_amount   = js_discount_parts[3].split(',');
//    js_fixed_amount[0] = js_fixed_amount[0].substr( js_fixed_amount[0].indexOf(':')+1 ); //chop off the AMOUNT
//    js_type           = js_discount_parts[4].split(':');
//
//    if (js_units[1] == 'KG') {
      total_weight = total_weight / 1000;
//    }

    js_volumes = new Array();
    js_volumes[0] = 0;
    js_volumes[1] = 0.01;
    js_volumes[2] = 0.05;
    js_volumes[3] = 0.3;
    js_volumes[4] = 1;
    js_volumes[5] = 999999;


    //what is the max weight that there is a discount
//    if (js_volumes[4] != 0) { max_idx = 4; }
//    else if (js_volumes[3] != 0) { max_idx = 3; }
//    else if (js_volumes[2] != 0) { max_idx = 2; }
//    else if (js_volumes[1] != 0) { max_idx = 1; }
//    else if (js_volumes[0] != 0) { max_idx = 0; }
    max_idx = 5;

    //work out which volume we are looking at
    js_idx_set = false;
    js_use_idx = -1;
    for(ary_idx=max_idx; ary_idx >= 0; ary_idx--) {
      if ((js_idx_set == false) && (total_weight > js_volumes[ary_idx])) {
        js_use_idx = ary_idx;
        js_idx_set = true;
      };
    };

    if (js_use_idx != -1) {
//      if (js_type[1] == 1) { //percentage discount - values provided are the percentage to discount
        price = ((100 - js_pcnt_intervals[js_use_idx]) / 100) * current_price;
//      } else if (js_type[1] == 2) { //fixed amount discount
//        price = current_price - js_fixed_amount[js_use_idx];
//      }
    };
    return price;
}
//0 = INTVL:12.15000,15.70000,19.31000,0.00000,0.00000|
//1 = UNITS:KG|
//2 = PRICEQTY:0.0000,0.0500,0.3000,1.0000,0.0000|
//3 = AMOUNT:8.720000,58.750000,73.720000,88.720000,0.000000|
//4 = TYPE:2|</div>

