
function validateStrLen(s, l) {
  if (s==null || s.length==0) return false;
  s = s.replace(/ /g, ''); // don't count spaces
  return (s.length >= l);
}

function validateEmail(s) {
  //if ((s==null) || (s.length==0)) return false;
  if (!validateStrLen(s, 6)) return false;
  var AtPos = s.indexOf('@');
  var DotPos = s.indexOf('.');
  var SpacePos = s.indexOf(' ');
  return ((SpacePos ==-1) && (AtPos > 1));
}

function validateName(s) {
  if (!validateStrLen(s, 6)) return false;
  return s.indexOf(' ') > 1;  // must incl space, but not as first char
}

function validatePhone(s) {
  if (!validateStrLen(s, 5)) return false;
  var i = parseInt(s);
  return (!isNaN(i));
}


var shoppingCart = {
//  "dirty" : false,
  "shippingVAT" : 0.25,
  "shippingMax" : 200,
  "shippingMin" : 0,
  "showProductID" : false,
  "cookieName" : "LabShoppingCart",
  "loaded" : false,
  "SummeryTableId" : "",
  "ContactFormId" : "",
  "EmptyBagText" : '',
  "TxtProductName" : "",
  "TxtPrice" : "",
  "TxtQuantity" : "",
  "TxtCost" : "",
  "TxtSubTotal" : "",
  "TxtVat"       : "",
  "TxtShipping" : "",
  "TxtTotal"     : "",
  "TxtOrderSent" : "",
  "TxtRefresh" : "",
  "shoppingBag" : null,  // should be a select node
  "lastProduct" : '',
  "serverpage" : "",
  "items" : [],
  "validateForm" : function() {
     var aName ="";
     var aValue = "";
     var frm = document.getElementById(this.ContactFormId);
     if (frm) {
       for (var i=0;i<frm.length;i++) {
         if (frm.elements[i].type=='text') {
           aName = frm.elements[i].name;
           aValue = frm.elements[i].value;
           switch (aName)  {
             case "name" :
               result = validateName(aValue);
               break;
             case "phone" :
               result = validatePhone(aValue);
               break;
             case "email":
               result = validateEmail(aValue);
               break;
             case "phonenumber":
               result = validatePhone(aValue);
               break;
             case "address":
               result = validateStrLen(aValue,4);
               break;
             case "zipcode":
               result = validateStrLen(aValue,4);
               break;
             case "city" :
               result = validateStrLen(aValue,1);
               break;
             default:
               result = true;
           }
           if (!result) {
             frm.elements[i].focus();
             frm.elements[i].select();
             return false;
           }
         }
       }
     }
     return true;
  },

  "refreshSummery" : function () {
     var obj = document.getElementById(this.SummeryTableId);
     if (obj)
       obj.innerHTML = this.getCheckoutForm();
  },
  "setQty" : function(idx, qty) {
     var q = parseInt(qty);
     if (!isNaN(q))
       this.items[idx].quantity = q;
  },
  "itemIndex" : function (aProductID) {
                  result = -1;
                  // check if productID exists, if so, add return index
                  for (var i=0; i < this.items.length;i++) {

                    var aName = this.items[i].pid;
                    if (aName == aProductID) {
                      return i;
                    }
                  }
                   return result;
                },
  "sendOrder" : function(formid) {
                   // send with mail
                   result = false;
                   if (labMailer)
                     if (labMailer.mailhost != "") {
                       labMailer.message = $(formid).serialize();
                       result = labMailer.send();
                     } else {
                       // send to custsom server page
                       new Ajax.Request('/some_url',
                         //method and stuff
                         {parameters: $(formid).serialize()   });
                       //getObject("Text1").innerHTML = $(formid).serialize(); //this.empty();
                     }
                 },

  'add' : function (pid, productName, price, VAT, quantity, shipping, docURL) {
            // check if productname exists, if so, add quantity
            this.lastProduct = pid;
            var Index = this.itemIndex(pid);
            if (Index == -1) {
              var item = {
                         "pid"         : pid,
                         "productname" : productName,
                         "price"       : price,
                         "VAT"         : VAT,
                         "quantity"    : quantity,
                         "shipping"    : shipping,
                         "url"         : docURL
                         };
              this.items.push(item);
            }
            else
              this.items[Index].quantity += quantity;
            this.refreshBag();
          },

  "delete" : function(aProductName) {
             },

  "empty" : function () {
              this.items = [];
              this.refreshBag();
              eraseCookie(this.cookieName);
            },
  "contentAsFormParams" : function() {
    result = "";
    sum = 0;
    VATsum = 0;
    shippingSum = 0;
    if (this.items.length > 0) {
       for (var i=0; i < this.items.length;i++) {
         result+= 'itemid'+ i + '=' + escape(this.items[i].pid) +'&';
         result+= 'itemname'+ i + '=' + escape(this.items[i].productname) +'&';
         result+= 'itemqty'+ i + '=' + escape(this.items[i].quantity) + '&';
         result+= 'itemqprice' + i + '=' + escape(this.items[i].price) + '&';
         itemSum = this.items[i].quantity * this.items[i].price;
         sum += itemSum;
         shippingSum += this.items[i].shipping;
         VATsum += itemSum * this.items[i].VAT;
       }
       shippingTotal = Math.max(this.shippingMin, Math.min(shippingSum + (shippingSum*this.shippingVAT)));
       VAT_Total = VATsum + (shippingTotal*this.shippingVAT);
       total = sum + shippingTotal + VAT_Total;
       result +=  'netsum=' + sum +'&';
       result +=  'shipping=' + shippingTotal+ '&';
       result +=  'vat=' + VAT_Total + '&';
       result +=  'totalsum=' + total;
    }
    return result;
  },
  "contentAsPlainText" : function() {
     // should also return a more readable text...
     return this.serialize();
  },
  "serialize" : function() {
     // should also return a more readable text...
     //var result = this.contentAsFormParams();
     var aName = "";
     var result = "";
     var frm = document.getElementById(this.ContactFormId);
     if (frm) {
       for (var i=0; i < frm.length;i++) {
         aName = frm.elements[i].name;
         if (aName!="")
           if (frm.elements[i].value !="")
             result+=aName +"=" + escape(frm.elements[i].value) +"&";
       }
     }
     result += this.contentAsFormParams();
     return result;
  },

  "getCheckoutForm" : function () {
                 result = "";
                 sum = 0;
                 VATsum = 0;
                 shippingSum = 0;
                 //if (this.items.length > 0) {
                   result += '<table style="width:100%">';
                   result += '<tr>';
                   result += '<th>' + this.TxtProductName + '</th>';
                   result += '<th>' + this.TxtQuantity + '</th>';
                   result += '<th>' + this.TxtPrice + '</th>';
                   result += '<th>' + this.TxtCost + '</th>';
                   result += '</tr>';
                   for (var i=0; i < this.items.length;i++) {
                     result +=  '<tr>';
                     result+= '<td>' + '<a href="' + this.items[i].url +'">' + this.items[i].productname + '</a>';
                     if (this.showProductID)
                       result+= ' (' + this.items[i].pid + ')';
                     result+= ' </td>';
                     result+= '<td align="right">';
                     result+=    '<input size="4" value="' + this.items[i].quantity + '"' + ' onblur="shoppingCart.setQty(' + i +',this.value)"></input>';
                     result+= '</td>';
                     result+= '<td align="right">' + this.items[i].price + '</td>';
                     itemSum = this.items[i].quantity * this.items[i].price;
                     result+= '<td align="right">' + itemSum + '</td>';
                     result += '</tr>';
                     sum += itemSum;
                     shippingSum += this.items[i].shipping;
                     VATsum += itemSum * this.items[i].VAT;
                   }
                   shippingTotal = Math.max(this.shippingMin, Math.min(shippingSum + (shippingSum*this.shippingVAT)));
                   VAT_Total = VATsum + (shippingTotal*this.shippingVAT);
                   total = sum + shippingTotal + VAT_Total;
                   result +=  '<tr style="background-color:#DCDCDC"><th align="middle" colspan="4"><button onclick="shoppingCart.refreshSummery();">' +this.TxtRefresh+'</button></th></tr>';
                   result +=  '<tr><th colspan="3" align="right">' + this.TxtSubTotal + '</th><td align="right">' + sum + '</td></tr>';
                   result +=  '<tr><th colspan="3" align="right">' + this.TxtShipping +'</th><td align="right">' + shippingTotal+ '</td></tr>';
                   result +=  '<tr><th colspan="3" align="right">' + this.TxtVat +'</th><td align="right">' + VAT_Total + '</td></tr>';
                   result +=  '<tr><th colspan="3" align="right">' + this.TxtTotal+'</th><td align="right">' + total + '</td></tr>';
                   result +='</table>';

                 //}

                 return result;
               },
  "refreshBag": function() {
                  if (this.shoppingBag) {
                    // clear the list
                    while (this.shoppingBag.length > 1) {
                      this.shoppingBag.remove(this.shoppingBag.length - 1);
                    }

//                    this.shoppingBag.childNodes.clear();
                    for (var i=0; i < this.items.length;i++) {
                      var txt = this.items[i].quantity + ' x ' + this.items[i].productname;
                      if (i == 0) {
                        this.shoppingBag.options[0].text = txt;
                      } else {
                          var fjk = document.createElement('option');
                          fjk.text = txt;
                          try { this.shoppingBag.add(fjk, null); }  // standard, not IE
                          catch(e) { this.shoppingBag.add(fjk); }   // IE only
                       }
                    }
                    if (this.items.length == 0) {
                      this.shoppingBag.options[0].text = this.EmptyBagText;
                      this.shoppingBag.selectedIndex = 0;
                      this.shoppingBag.parentNode.style.visibility="hidden";
                    }
                    else {
                      this.shoppingBag.parentNode.style.visibility="visible";
                      this.shoppingBag.selectedIndex = this.itemIndex(this.lastProduct);
                    }
                  }

              },

   "save"     : function() {
                  var s = '';
                  if (this.items.length > 0) {
                    for (var i=0; i < this.items.length;i++) {
                      if (i > 0) s += '&';
                      s += this.items[i].pid + '|';
                      s += this.items[i].productname + '|';
                      s += this.items[i].price + '|';
                      s += this.items[i].VAT + '|';
                      s += this.items[i].quantity + '|';
                      s += this.items[i].shipping + '|';
                      s += this.items[i].url;
                    }
                    createCookie(this.cookieName,s,1);
                  };
                  //else
                  //  eraseCookie(this.cookieName);

                },
   "load"     : function() {
                  if (document.cookie.length > 0) {
                    var s = readCookie(this.cookieName);
                    if (s) {
                      itemArray = s.split("&");
                      for (var i=0; i < itemArray.length; i++) {
                        rec = itemArray[i].toString();
                        recArray = rec.split("|");
                        this.add(recArray[0],             //id
                                 recArray[1],             //prod name
                                 parseFloat(recArray[2]), //price
                                 parseFloat(recArray[3]), //VAT
                                 parseInt(recArray[4]),   //qty
                                 parseInt(recArray[5]),   //shipping
                                 recArray[6]);            //url
                      }
                    }
                  }
                }
}

//alert(shoppingCart);
//shoppingCart.load();

function initWebShop(cookieName) {
  if (!shoppingCart.loaded) {
    shoppingCart.cookieName = cookieName;
    shoppingCart.load();
    shoppingCart.loaded = true;
  }

}

addUnLoadListener( function() {
  shoppingCart.save();
});

