var bikky = document.cookie;
var userData = getCookie("userData") || "";
var today = new Date();
var EXPIRY = new Date(today.getTime() + 8 * 24 * 3600 * 1000); // 8 days
var DOMAIN = ".godset.dk";

  function getCookie(name) { // use: getCookie("name");
    var index = bikky.indexOf(name + "=");
    if (index == -1) return null;
    index = bikky.indexOf("=", index) + 1;
    var endstr = bikky.indexOf(";", index);
    if (endstr == -1) endstr = bikky.length;
    return unescape(bikky.substring(index, endstr));
  }

  function setCookieRaw(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" +escape(value) +
      ( (expires) ? ";expires=" + expires.toGMTString() : "") +
      ( (path) ? ";path=" + path : "") + 
      ( (domain) ? ";domain=" + domain : "") +
      ( (secure) ? ";secure" : "");
  }

  function setCookie(name, value) { // use: setCookie("name", value);
    setCookieRaw(name, value, EXPIRY, "/" , DOMAIN);
    //setCookieRaw(name, value, EXPIRY);
    bikky = document.cookie; // update bikky
  }

  // Return name of a name=value pair
  function nameOf(s) {
    return s.substring(0, s.indexOf("="));
  }

  // Return value of a name=value pair
  function valueOf(s) {
    t = parseInt(s.substring(s.indexOf("=")+1, s.length));
    if (t == NaN)
      return 0;
    return t;
  }

  // Return value for a given name
  function getCookieItem(name) {
    var start = 0;
    var end = 0;
    var s = "";
    while (start < userData.length) {
      end = userData.indexOf("!", start);
      if (end == -1) end = userData.length;
      s = userData.substring(start, end);
      if (name == nameOf(s)) return valueOf(s);
      start = end + 1;
    }
    return null;
  }

  // Return name/value pair number <n>, use nameOf() and valueOf() to split
  function getCookieItemNo(n) {
    var start = 0;
    var end = 0;
    var s = "";
    var num = 0;
    while (start < userData.length) {
      end = userData.indexOf("!", start);
      if (end == -1) end = userData.length;
      s = userData.substring(start, end);
      if (num == n) return s;
      start = end + 1;
      num++;
    }
    return null;
  }

  // Delete the shopping cart cookie
  function emptyCart() {
    // document.cookie="userData=; expires = Thu, 01-Jan-70 00:00:01 GMT; domain="+DOMAIN;
    setCookieRaw("userData", "", today, "/" , DOMAIN);
    bikky = document.cookie; // update bikky
    userData = "";
  }

  // Delete shopping cart and reload page
  function emptyCartRfsh() {
    emptyCart();
    history.go(0);
  }

  // Helper function
  function addCookieItem_userData(name, value) {
    var start = 0;
    var end = 0;
    var s = "";
    while (start < userData.length) {
      end = userData.indexOf("!", start);
      if (end == -1) end = userData.length;
      s = userData.substring(start, end);
      if (name == nameOf(s)) {
        var s1 = userData.substring(0, start);
        var s2 = userData.substring(end, userData.length);
        //alert("s1 = ("+s1+") s2 = ("+s2+")");
        userData = s1 + name + "=" + value + s2;
        return;
      }
      start = end + 1;
    }
    userData = userData + "!" + name + "=" + value;
    return;
  }

  // Set an Item (name/value pair)
  function addCookieItem(name, value) {
    addCookieItem_userData(name, value);
    setCookie("userData", userData);
    //history.go(0);
  }

// Debugging function to display cookie contents
function showMe() {
  display = getCookie("userData");
  alert(display)
}

// Add <qty> items number <num>
function addItemQty(num, qty) {
  var b = eval("qty");
  for (var i = 0; i < b.length; i++) {
    var oneChar = b.substring(i, i + 1);
    if (oneChar < "0" || oneChar > "9") {
      alert("Kun hele tal i feltet for antal!");
      //eval("document.form1.q"+num+".value = ''")
      return false;
    }
  }
  addCookieItem(num, b);
  return true;
}

// Add the items from this form (form:form<num> qty:q<num>) and reset the form value
function addItem(num) {
  var qty = eval("document.form"+num+".q"+num+".value")
  if (addItemQty(num, qty)) {
//    eval("document.form"+num+".q"+num+".value = 0")
      // history.go(0);
      return true;
  } else {
      return true;
      // return false;
  }
  // history.go(0);
}

// Get <qty> for item <num>
function getQty(num) {
  var qty = getCookieItem(num);
  if (qty > 0) {
    return qty
  } else {
    return 0
  }
}

// Count number of items in the cart
function countItems() {
  var i = 0;
  var p = getCookieItemNo(i);
  var sum = 0;
  while (p != null) {
    num = nameOf(p);
    qty = valueOf(p);
    if ((num > 0) && (qty > 0)) {
      sum = sum + qty;
    }
    i++;
    p = getCookieItemNo(i);
  }
  return sum;
}

// Update values in a specific form from the values in the cookie
function updateForm(form) {
  var i = 0;
  var p = getCookieItemNo(i);
  while (p != null) {
    num = nameOf(p);
    qty = valueOf(p);
    if ((num > 0) && (qty > 0)) {
      eval("if (document."+form+".q"+num+") {document."+form+".q"+num+".value = qty}")
    }
    i++;
    p = getCookieItemNo(i);
  }
}

// Update the cookie based on order form
function updateFromForm(form) {
  var i = 0;
  var q = 0;
  var s = "";
  for (i=0; i < 300; i++) {
    q = 0;
    eval("if (document."+form+".q"+i+") {if (document."+form+".q"+i+".value > 0) {q = eval(document."+form+".q"+i+".value)}}");
    if (q > 0) {
      s = s + "!" + i + "=" + q;
    }
  }
  userData = s;
  setCookie("userData", userData);
  return true;
}

// Validate the order form on submit
function validateOrderForm(form) {
  // Count number of items (id < 100)
  var cnt = 0;
  for (var i=0; i < 100; i++) {
    eval("if (form.q"+i+") if (form.q"+i+".value > 0) {cnt = cnt + eval(form.q"+i+".value)}")
  }

  // Check for multipla of 12
  if ((cnt % 12) != 0) {
    if (!confirm("Der er valgt "+cnt+" flasker,\ndet er ikke et helt antal kasser (12 fl).\nDet koster lidt ekstra for fragten.\nEr det ok?")) {
      return false;
    }
  }

  // Empty the shopping cart then
  // emptyCart();
  return true;
}

// Popup function
function openpopup(popurl, w, h){
  var s="width="+w+",height="+h+",status,resizable,scrollbars,";
  winpops=window.open(popurl,"",s)
}

// Email validation function - not really used in the shop - just useful
function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert("Den email adresse ser ikke rigtig ud (check @ og .)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("Der skal stå noget foran @ i den email adresse.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Den angivne IP adresse ser ikke rigtig ud!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("Det der står efter @ ser ikke rigtigt ud.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="Det der står efter @ ser ikke rigtigt ud (check hostnavn)!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}
