function getDiscountMessage(product) {
 var sep1 = " AND ";
 var sep2 = " OR ";
 var first = true;
 var option_string = "";

 if(hasOption(getProperty(settings, product + "_free_option"), "FM")) {
  if(option_string != "") { if(first) { option_string += sep1; first = false; } else option_string += sep2; }
   option_string += "Motor";
 }

 if(hasOption(getProperty(settings, product + "_free_option"), "FWR")) {
  if(option_string != "") { if(first) { option_string += sep1; first = false; } else option_string += sep2; }
  option_string += "Remote & Wind Sensor";
 } 

 if(hasOption(getProperty(settings, product + "_free_option"), "FWIOS")) {
  if(option_string != "") { if(first) { option_string += sep1; first = false; } else option_string += sep2; }
  option_string += "Interior Wall Switch & Wind Sensor and Outdoor plug-in switch & wind sensor";
 } 

 if(hasOption(getProperty(settings, product + "_free_option"), "FRS")) {
  if(option_string != "") { if(first) { option_string += sep1; first = false; } else option_string += sep2; }
  option_string += "Remote & Sun Sensor";
 } 

 if(hasOption(getProperty(settings, product + "_free_option"), "FRWS")) {
  if(option_string != "") { if(first) { option_string += sep1; first = false; } else option_string += sep2; }
  option_string += "Remote, Wind & Sun Sensor";
 } 

 var discount_string = getMoneyString(getFloatProperty(settings, product + "_discount_edge"));
 var monthname = ["January", "February", "March", "April", "May",
                  "June", "July", "August", "September", "October",
                  "November", "December"];
 var productName = {"a2bq": "Grande", "bqn": "Elegante", "bn": "Mirage",
                    "ptn": "Surrender",
                    "euro": "Sleek", "v8": "Ferrara", "ba": "Vertidrop"};
 var hoodText = {
   "a2bq": "(with or without the flat hood)",  
   "bqn": "(with or without the bullnose hood)",
   "ptn": "(with or without the bullnose hood)",
   "ba": "",
   "v8": "with semi cassette hood",
   "euro": "",
   "bn": ""
 };

 var curdate = new Date();
 var nextdate = null;
 var date_string = "";
 for(var i = 1; i < dates.length; i++) {
   var date_ar = dates[i][0].split("-");
   var month = parseFloat(date_ar[0]) - 1;

   var day   = parseFloat(date_ar[1]);
   var expdate = new Date(curdate.getFullYear(), month, day);

   //alert(date_ar[0] + ":" + date_ar[1]);
   //alert(month + ":" + day + ":" + curdate.getFullYear());
   //alert(expdate - curdate);
   if(expdate > curdate)
   if(nextdate == null || expdate - curdate < nextdate - curdate) {
     nextdate = expdate;
     date_string = dates[i][1];
     //alert(date_string + ":" + i + ":" + expdate);
     if(date_string == "") {
       date_string = "midnight " + monthname[month] + " " + nextdate.getDate() + ", " + nextdate.getFullYear();
     }
   }
 }

 var discount_message = getProperty(settings, "specials_message"); 
 discount_message = discount_message.replace(/FREE_OPTIONS/, option_string);
 discount_message = discount_message.replace(/PRICE/, discount_string);
 discount_message = discount_message.replace(/EXPIRATION_DATE/, date_string);
 discount_message = discount_message.replace(/PRODUCT/, productName[product]);
 discount_message = discount_message.replace(/HOOD/, hoodText[product]);

 if(option_string == "") {
   // No free options
   return "";
 }

 return discount_message;
}

function hasOption(set, value) {
 var set_ar = set.split(",");

 for(var i = 0; i < set_ar.length; i++) {
  if(set_ar[i] == value) return true;
 }
 return false;//set_ar.indexOf(value) != -1;
}

function popWindow(url, width, height) { 
 popUp = open(url, 'thewin', 'toolbar=0, scrollbars=1, location=0, status=0, menubar=0, resizable=1'); 
 popUp.resizeTo(width, height); 
 popUp.focus();
} 

// Cookie handling
function setCookie( sName, sValue, nSeconds) {
  var expires = "";
  if ( nSeconds ) {
    var d = new Date();
    d.setTime( d.getTime() + nSeconds * 1000 );
    expires = "; expires=" + d.toGMTString();
  }

  document.cookie = sName + "=" + sValue + expires + "; path=/";
};

function getCookie(sName) {
  if(id != "{id}") { return "null"; }
  var re = new RegExp( "(\;|^)[^;]*(" + sName + ")\=([^;]*)(;|$)" );
  var res = re.exec( document.cookie );
  return res != null ? unescape(new String(res[3]).split("+").join(" ")) : "null";
};

function removeCookie( name ) {
  setCookie( name, "", -1 );
};

String.prototype.trim = function() {
 return this.replace(new RegExp("^[\\' ']+"), "").replace(new RegExp("[\\' ']+$"), "");
}

function getFeaturesList(product, width, projection) {
 for(var i = 1; i < features.length; i++) {
  if(features[i][0].trim() != "" && features[i][0].trim() != product) {
   continue;
  }

  if(features[i][1].trim() != "" && compare(features[i][1].trim(), width) != 0) {
   continue;
  }

  if(features[i][2].trim() != "" && compare(features[i][2].trim(), projection) != 0) {
   continue;
  }

  return features[i][3];
 }

 return "";
}

function getShippingCost(data, product, location, width) {
 for(var i = 1; i < data.length; i++) {
  if(data[i][0].trim() == location) {
   if(data[i][2].trim() != "" && data[i][2].trim() != product) {
    continue;
   }

   if(data[i][3].trim() != "" && compare(width, data[i][3].trim()) < 0) {
    continue;
   } 

   if(data[i][4].trim() != "" && compare(width, data[i][4].trim()) > 0) {
    continue;
   } 

   return parseFloat(data[i][1]);
  }
 }

 return 0;
}

function moveStatus() {
 if(window.status != "" && window.status.charAt(0) == " ") {
  window.status = window.status.substring(1);
  setTimeout("moveStatus()", 50);
 }
}

function setStatus(status, row, hide) {
 hide = hide || 1;

 if(row) {
  getRow(row).style.backgroundColor = "red";
  showHelpTip(row, status, hide);
  document.getElementById("xtip_total").innerHTML = "Items in red on the price estimator still need to be completed";
  document.getElementById("xtip_total").className = "tip_show";
  document.getElementById("xtip_total").style.backgroundColor = "red";
 } else {
  hideHelpTips();
  document.getElementById("xtip_total").className = "tip";
 }

 window.status = status != "" ? 
     "                                           " + 
     "                                           " +
     status : "";
 moveStatus();
}

function showHelpTip(name, hint, hide) {
 hide = hide || 1;

 if(hide == 1) {
  hideHelpTips();
 }

 var el = document.getElementById("tip_" + name);

 el.innerHTML = hint;//.split(" ").join("&nbsp;");
 el.className = "tip_show";
}

function hideHelpTips() {
 for(var name in document.all) {
  if(name.indexOf("tip_") != 0) continue;
  var el = document.getElementById(name);

  el.className = "tip";
  el.innerHTML = "";
 }
}

function getMoneyString(value) {
 value = "" + Math.ceil(parseFloat(value));
 var result = "";

 for(var i = value.length - 1; i >= 0; i--) {
  result = value.charAt(i) + result;

  if((value.length - i) % 3 == 0 && (i != 0)) {
   result = "," + result;
  }
 }

 return "$" + result;
}

function findProjection(chart, projection) {
 var i = 0;

 // Skip all non-numeric values at the beginning
 while(isNaN(parseFloat(chart[0][i]))) {
  i++;
 }

 // Try to find the closest value, round up
 while((i < chart[0].length) && !isNaN(parseFloat(chart[0][i])) 
   && (compare(projection, chart[0][i]) == 1)) {
  i++;
 }

 if(i == chart[0].length || isNaN(parseFloat(chart[0][i]))) {
  i--;
 }

 return i;
}

function findWidth(chart, width) {
 var i = 0;

 // Skip all non-numeric values at the beginning
 while(isNaN(parseFloat(chart[i][0]))) {
  i++;
 }

 // Try to find the closest value, round up
 while((i < chart.length) && !isNaN(parseFloat(chart[i][0])) 
   && (compare(width, chart[i][0]) == 1)) {
  i++;
 }

 if(i == chart.length || isNaN(parseFloat(chart[i][0]))) {
  i--;
 }

 return i;
}

function findColumn(chart, col) {
 for(var i = 0; i < chart[0].length; i++) {
  if(chart[0][i].toLowerCase() == col.toLowerCase()) {
   return i;
  }
 }

 alert("Error: Column " + col + " is not found in chart table.");
 return -1;
}

function findRow(chart, row) {
 var value = "";

 for(var i = 0; i < table.length; i++) {
  if(table[i][0].toLowerCase() == row.toString().toLowerCase()) {
   return i;
  }
 }

 alert("Error: Row " + row + " is not found in chart table.");
 return -1;
}

function getChartPrice(chart, width, projection) {
 return parseFloat(chart[findWidth(chart, width)][findProjection(chart, projection)]);
}

function getMotorPrice(chart, width, projection) {
 return parseFloat(chart[findWidth(chart, width)][findProjection(chart, projection)]);
}

function getHandlePrice(handle) {
 var price = 0;

 for(var i = 0; i < handle_price.length; i++) {
  if(handle >= handle_price[i][0]) price = parseFloat(handle_price[i][1]);
 }

 return price;
}

function getRetailPrice(price) {
 return Math.round(price * getFloatProperty(settings, "retail_percent") / 100);
}

// Get "ft" part from "6.11" style string
function getFt(value) {
 return Math.floor(parseFloat(value));
}

// Get "in" part from "6.11" style string
function getIn(value) {
 var in_value = parseInt(value.substring(value.indexOf(".") + 1));

 if(value == in_value) return 0;

 return in_value;
}

function compare(value1, value2) {
 var ft1 = getFt(value1);
 var in1 = getIn(value1);
 var ft2 = getFt(value2);
 var in2 = getIn(value2);

 // First is greater than second
 if(ft1 > ft2 || (ft1 == ft2 && in1 > in2)) {
  return 1;
 }

 // First is lesser than second
 if(ft1 < ft2 || (ft1 == ft2 && in1 < in2)) {
  return -1;
 }

 // First and second are equal
 return 0;
}

// Generate proper string of ft & in
function toFtIn(ft, inch) {
 while(inch > 11) {
  ft++;
  inch -= 12;
 }

 while(inch < 0) {
  ft--;
  inch += 12;
 }

 return ft + "." + inch;
}

// Get a property value from two columns table (useful for settings)
function getProperty(table, key, col) {
 var value = "";
 col = col || 1;

 for(var i = 0; i < table.length; i++) {
  if(table[i][0].toLowerCase() == key.toString().toLowerCase()) {
   value = table[i][col];
  }
 }

 return value;
}

function getFloatProperty(table, key, col) {
 col = col || 1;
 return parseFloat(getProperty(table, key, col));
}

function getIntProperty(table, key, col) {
 col = col || 1;
 return parseFloat(getProperty(table, key));
}

function getBooleanProperty(table, key, col) {
 var value = getProperty(table, key);
 col = col || 1;

 return (parseInt(value) > 0) || (value.toLowerCase().indexOf("y") != -1);
}

function trimFabricsList(list, type) {
 var result = [];

 result[result.length] = list[0];

 for(var i = 1; i < list.length; i++) {
  if(list[i][0].toLowerCase() == type.toLowerCase()) {
   result[result.length] = list[i];
  }
 }

 return result;
}

function trimFabricsListByColor(list, color, ptn) {
 var result = [];

 result[result.length] = list[0];

 for(var i = 1; i < list.length; i++) {
  if(("" + list[i][4]).toLowerCase().indexOf(("" + color).toLowerCase()) != -1) {
   if(ptn && ("" + list[i][0]).toLowerCase() != "sunbrella_pantheon") continue;
   if(!ptn && ("" + list[i][0]).toLowerCase() == "sunbrella_pantheon") continue;

   result[result.length] = list[i];
  }
 }

 return result;
}

function setText(control, value) {
 if(value + "" == "null") return;
 if(typeof(control) == "undefined") {
  return "Control undefined";
 }

 if(value == "" && getCookie(control.name) == "null") return;
 if(value == "" && getCookie(control.name) != "") return setText(control, getCookie(control.name));
 control.value = value;
}

function setSelect(control, value) {
 if(value + "" == "null") return;
 if(typeof(control) == "undefined") {
  return "Control undefined";
 }

 if(value == "" && getCookie(control.name) == "null") return;
 if(value == "" && getCookie(control.name) != "") return setSelect(control, getCookie(control.name));

 for(var i = 0; i < control.options.length; i++) {
  if(control.options[i].value == value) {
   control.options[i].selected = true;
  }
 }
}

function setRadio(control, value) {
 if(value + "" == "null") return;
 if(typeof(control) == "undefined") {
  return "Control undefined";
 }


 if(value == "" && getCookie(control.name) == "null") return;
 if(value == "" && getCookie(control.name) != "") return setRadio(control, getCookie(control.name));

 for(var i = 0; i < control.length; i++) {
  if(control[i].value == value) {
   control[i].checked = true;
  }
 }
}

function setCheckbox(control, value) {
 if(value + "" == "null") return;
 if(typeof(control) == "undefined") {
  return "Control undefined";
 }

 if(value == "" && getCookie(control.name) == "null") return;
 if(value == "" && getCookie(control.name) != "") return setCheckbox(control, getCookie(control.name));

 var value_ar = value.split(";");
 for(var i = 0; i < control.length; i++) {
  for(var j = 0; j < value_ar.length; j++) {
   if(control[i].value == value_ar[j]) {
    control[i].checked = true;
   }
  }
 }
}
