
  function $(id) {
    return document.getElementById(id) || top.document.getElementById(id);
  }

  //chk if an object is an array or not.
  function isArray(obj) {    //returns true is it is an array
    if (obj.constructor.toString().indexOf("Array") == -1) {
      return false;
    }
    return true;
  }

  function addLoadEvent(func) {
      var oldonload = window.onload;
      if (typeof window.onload != 'function') {
          window.onload = func;
      } else {
          window.onload = function() {
              if (oldonload) {
                  oldonload();
              }
              func();
          }
      }
  }

  function tsub(i) {
    var lmnt = document.getElementById("sub"+i);
    var img  = document.getElementById("img_"+i);
    if ( lmnt.style.display=="none") {
        lmnt.style.display="block";
        var tmpstr = ''+img.src;
        tmpstr = tmpstr.replace('plus','minus');
        img.src= tmpstr; // "/image/minus.gif";
    } else {
        lmnt.style.display="none";
        var tmpstr = ''+img.src;
        tmpstr = tmpstr.replace('minus','plus');
        img.src= tmpstr; // "/image/plus.gif";
    }
  }

  var fields = new Array('itemid','itemcode', 'itemtitle','itemprice', 'itemgrossweight', 'n', 'opt1','opt2', 'maxn' );
  var shopdecimalpart = 1;
  var shopvatincl = 1;

  function setShopdecimalpart( sdp ) {
     if ( sdp && !isNaN(sdp) ) {
         shopdecimalpart = sdp;
     }
  }

  function alterError(value) {
      if ( value*1 == 0 ) return '0.00';
      var sign = 1;
      if ( value < 0 ) {
         sign = -1;
         value = -value;
      }
      dllrs = parseInt(value);
      cents = 100.001*(value*1 - dllrs);
      cents = parseInt( cents/shopdecimalpart+0.5) * shopdecimalpart;
      // cents = Math.round( cents/shopdecimalpart ) * shopdecimalpart;
      if ( cents == 0 ) {
          cents = '00';
      } else if ( cents > 0 && cents < 10 ) {
          cents = '0'+cents;
      } else if ( cents == 100 ) {
          dllrs += 1;
          cents = '00';
      }
      return sign < 0 ? '-'+dllrs+'.'+cents : dllrs+'.'+cents;
  }

  function _calcTariff(tariff, val) { // totweight is a global calculated in showBasket
     var tar = 0;
     for ( var step in tariff ) {
         if ( val < step ) {
           tar = tariff[step];
           break;
         }
     }
     return tar;
  }

  function itemstotal() {
      items = getItemList();
      totprice = 0;
      for ( var i in items ) {
          var itm = items[i];
          subtotal = alterError( alterError(itm['itemprice']) * itm['n'] );
          totprice += subtotal*1;
      }
      totprice = alterError(totprice);
      $('itemstotal').value = totprice; // itemstotal will always be present
      return totprice;
  }

  function toHash( array, fields ) {
      var hsh = []; // new Array();
      for ( var i in fields ) {
          hsh[ fields[i] ] = array[i];
      }
      return hsh;
  }

  function getVals( hsh ) {
      var arr = [];
      for ( var i in hsh ) {
          arr.push( hsh[i] );
      }
      return arr;
  }

  function getItemList() {
      index = document.cookie.indexOf("TheBasket");
      countbegin = document.cookie.indexOf("=", index)*1 + 1;
      countend   = document.cookie.indexOf(";", index);
      countend   = (countend==-1) ? document.cookie.length : countend;
      fulllist   = document.cookie.substring(countbegin+2, countend-1); //+1 to get rid of '.[' and ending ']'
      if ( fulllist.indexOf("|")==-1 ) return null;
      var items = fulllist.split(']['); // global used outside this function
      var items2 = [];
      for ( var i in items ) {
          var pieces   = items[i].split('|');
          var hsh = toHash( pieces, fields );
          items2.push( hsh );
      }
      return items2;
  }

  function getItemHash() {
     var list = getItemList();
     var hash = [];
     for ( var i in list ) {
        var item = list[i];
        hash[ item['itemid'] ] = item;
     }
     return hash;
  }

  function setCookieUsingHash( hsh1 ) {
      var cake = '';
      for ( var itemid in hsh1 ) {
          var item;
          item=hsh1[itemid];
          cake += '[';
          var tmp = [];
          for ( var i in fields ) {
              tmp.push( item[fields[i]] );
          }
          cake += tmp.join('|') + ']';
      }
      var index = document.cookie.indexOf("TheBasket");
      var countbegin = (document.cookie.indexOf("=", index) + 1);
      var countend = document.cookie.indexOf(";", index);
      if (countend == -1) {
          countend = document.cookie.length;
      }
      // ------------------------> . is here <---------------------
      // document.cookie = "TheBasket="+document.cookie.substring(countbegin, countend)+ cake;
      document.cookie = "TheBasket=." + cake;
  }

  function addItem( item ) {
      var n = parseInt( item['n'] );
      var dn = 0;

      if ( n >= 1000 || n != item['n'] ) {
          rc = alert('Felaktigt antal!');
      } else if ( n >= 1) {
          item['n'] = 0;
          var hash = getItemHash();
          if ( !hash[ item['itemid'] ] ) {
              hash[ item['itemid'] ] = item;
          }
          var maxn;
          var curn;
          maxn = item['maxn'];
          curn = hash[item['itemid']]['n'];
          dn = curn*1+n*1 <= maxn*1 ? n : Math.floor( maxn*1-curn*1 );
          if ( dn*1 != n ) {
              alert('slut i lager');
          }
          if ( dn != 0 ) {
              hash[ item['itemid'] ]['n'] = hash[ item['itemid'] ]['n']*1 + dn*1;
              setCookieUsingHash( hash );
          }
      } // else ignore
      return dn;
  }

  function updateItem(itemid, newquant) {
      hash = getItemHash(); // fulllist.split(']');
      var itm = hash[itemid];
      itm['n'] = newquant*1;
      if ( itm['n']*1 > itm['maxn']*1 ) {
          itm['n'] = itm['maxn']*1;
      }
      setCookieUsingHash( hash );
      itemstotal();
      self.location = self.location;
  }

  function removeItem( itemid ) {
      var hash = getItemHash();
      delete hash[itemid];
      setCookieUsingHash( hash );
      itemstotal();
      self.location = self.location;
  }

  function calcFreight( info, freightTariff ) {
      if ( !freightTariff ) return 0;
      var message='';
      var shipping = 0;
      if ( freightTariff ) {
         shipping = _calcTariff( freightTariff, info['totweight'] );
      }
      // alert( 'freightfree '+info['freightfree'] + ' totprice:' + info['totprice'] + 'shipping:'+shipping );
      if ( info['freightfree']*1 > 0 && info['freightfree']*1 < info['totprice']*1 ) {
          shipping = 0;
      }
      return alterError(shipping);
  }

  function calcDiscounts( info ) {
      // nothing so far
      return 0;
  }

  // dataformat: category1:vat1;category2:vat2;...
  function initVatCats( datastr ) {  // the data is sorted in order of decreasing specificity, ending with default /.*/.
      datastr = datastr.replace(/\s+/g,'');
      datastr = datastr.replace(/;$/,'');
      var cats = datastr.split(";");
      var vc = [];
      for ( i in cats ) {
         cats[i] = cats[i].replace(/%/g, ".*");
         var dual = cats[i].split(":");
         var cat = {};
         cat['regex']     = dual[0];
         cat['sum']       = 0;
         cat['vat']       = dual[1];
         cat['itemcodes'] = [];
         vc.push( cat );
      }
      return vc;
  }

   function calcVat( itm, vatcats ) {
     var vc = vatcats;
     var c = null;
     for ( i in vc ) {
       if ( itm['itemcode'].match( vc[i]['regex'] ) ) {
           c = vc[i];
           var k = shopvatincl*1==0 ? c['vat']/100 : 1-1/(1+c['vat']/100);
           // c['sum'] = c['sum']*1+itm['n']*itm['itemprice']*c['vat']/100;
           c['sum'] = c['sum']*1+itm['n']*itm['itemprice']*k;
           c['itemcodes'].push( itm['itemcode'] );
           break;
       }
     }
     if ( c == null ) {
       alert(' vat error ! please tell owner of shop ! ' );
     }
   }


  function showBasket( vatcats ) {
      var info = { 'totprice':0, 'totweight':0, 'vatcats':vatcats, 'html':'', 'hidden':'' };
      items = getItemList(); // fulllist.split('][');
      if ( items == null ) {
          return info;
      }
      var htm = '';
      var hid = '';
      var totweight = 0;
      var totprice  = 0;
      var subtotal  = 0;
      var subweight = 0;

      for ( var itemlist in items ) {
          var itm = items[itemlist];
          var option   = itm['opt1'] +' '+itm['opt2']; // +' '+itm['opt3']+' '+itm['opt4'];
          var linenr   = itemlist*1+1;
          itm['itemprice'] = alterError(itm['itemprice']);
          subtotal     = alterError(itm['itemprice'] * itm['n'])*1;
          totprice    += subtotal;
          subweight    = itm['itemgrossweight'] * itm['n'];
          totweight   += subweight;

          hid += '<input type="hidden" name="itemid'+linenr+'" value="'+itm['itemid']+'">';
          hid += '<input type="hidden" name="itemcode'+linenr+'" value="'+itm['itemcode']+'">';
          hid += '<input type="hidden" name="itemtitle'+linenr+'" value="'+itm['itemtitle']+'">';
          hid += '<input type="hidden" name="itemprice'+linenr+'" value="'+itm['itemprice']+'">';
          hid += '<input type="hidden" name="totalcost'+linenr+'" value="'+alterError(itm['itemprice']*itm['n'])+'">';
          hid += '<input type="hidden" name="optionA'+linenr+'" value="' + itm['opt1'] + '">';
          hid += '<input type="hidden" name="optionB'+linenr+'" value="' + itm['opt2'] + '">'+ "\n";

          htm += '<tr>';
          htm += '<td align="middle"><input type="text" name="quant'+linenr+'" value="'+itm['n']+'" size="3"></td>';
          if ( subtotal > 0 ) {
            htm += '<td><a href="?func=post&itemid='+itm['itemid']+'">'+itm['itemcode']+'</a></td>';
            htm += '<td align=left><a href="?func=post&itemid='+itm['itemid']+'">'+itm['itemtitle']+'</a></td>';
          } else { // probably a discount with hidden item
            htm += '<td><a href="">'+itm['itemcode']+'</a></td>';
            htm += '<td align=left><a href="">'+itm['itemtitle']+'</a></td>';
          }
          htm += '<td align=left>'+option+'</td>';
          htm += '<td align="right">'+ alterError(itm['itemprice']) +    '</td>';
          htm += '<td align="right">'+ alterError(subtotal) + '</td>';
          htm += '<td align="right">';
          htm += '  <a href="" onclick="updateItem('+itm['itemid']+',document.form0.quant'+linenr+'.value); return false;">';
          htm += '    <img src="/image/update.gif" width="13" border="0" alt="Uppdatera">';
          htm += '  </a>';
          htm += '  <img src="/image/space.gif"  width="3"  height="2"><a href="javascript:removeItem('+itm['itemid']+')">';
          htm += '  <img src="/image/remove.gif" width="13" border="0" alt="Radera"></a>&nbsp;';
          htm += '</td>';
          htm += '</tr>' + "\n";
          calcVat( itm, vatcats ); // since vats may vary depending on itemcategory // vat information is stored in vatCats
      }
      info['vatcats']   = vatcats;
      info['totprice']  = totprice;
      info['totweight'] = totweight;
      info['html'] = htm;
      info['hidden'] = hid;
      return info;
  }

  function calcSumVat( vatcats ) {
      var sumvat = 0;
      for ( i in vatcats ) {
         if ( isNaN( vatcats[i]['sum'] ) ) continue;   // may not be initialized
         sumvat += vatcats[i]['sum']*1;
      }
      return sumvat;
  }

  function fillpage( info ) {
      for ( i in info ) {
          if ( $(i) ) {
             // alert( i + ' ' + alterError( info[i] ) );
             $(i).value = alterError(info[i]);
          }
      }
  }

  function calcPage( vatCatsData, freightTariff, shopvatincl, freightfree ) {
      var vatcats      = initVatCats( vatCatsData );
      info             = showBasket( vatcats );
      info['freightfree'] = freightfree;
      info['shipping'] = calcFreight( info, freightTariff );
      info['discount'] = calcDiscounts( info );
      var itm = {};
      itm['itemcode']  = 'shipping';
      itm['itemprice'] = info['shipping'];
      itm['n']         = 1;
      calcVat( itm, info['vatcats'] );
      info['vat'] = calcSumVat( info['vatcats'] );

      if ( shopvatincl==1 ) {
          info['total'] = alterError(info['totprice'])*1+alterError(info['shipping'])*1-alterError(info['discount'])*1;
      } else {
          info['total'] = alterError(info['totprice'])*1+alterError(info['shipping'])*1-alterError(info['discount'])*1+alterError(info['vat'])*1;
      }
      return info;
  }

  function resetShoppingBasket() {
      // index = document.cookie.indexOf("TheBasket");
      document.cookie="TheBasket=.";
      itemstotal();
  }

  function clearBasket() {
      if (confirm('Vill du verkligen ta bort alla varor ur korgen')) {
          index = document.cookie.indexOf("TheBasket");
          document.cookie="TheBasket=.";
          self.location = "?func=emptybasket";
      }
  }

  /* ---------order_pg order_card ---------------------------- */
  function trim(str) {
     return str.replace(/^\s*|\s*$/g,"");
  }

  function formValidator(ffields ) {
      var error = 0;
      for ( var i=0; i < ffields.length; i++ ) {
          lmnt = document.getElementById( ffields[i] );
          if ( lmnt == null ) {
            continue;
          }
          if ( ffields[i]=='email' && lmnt.value.indexOf('@') ==-1 ) {
              setBorder(lmnt,1);
              error=1;
          } else if ( lmnt.value=="" ) {
              setBorder(lmnt,1);
              error=1;
          } else {
              setBorder(lmnt,0);
          }
      }
      if ( error==1 ) {
          return false;
      }
      return true;
  }

  function setBorder(t,b) {
      if( b ) {
          t.style.borderColor = '#ce0000';
          t.style.borderStyle = 'solid';
          t.style.borderWidth = '1px';
      } else {
          t.style.borderColor = '';
          t.style.borderStyle = '';
          t.style.borderWidth = '';
      }
  }
  /* ----------------------------------------- */

  function search() { // used in searchpane
      variable.location="?func=searchlist&searchstring="+ $('searchstring').value+'&chose='+$('chose').value;
  }

  function insertFlash() {
      var shoptop = document.getElementById('shoptop');
      if ( shoptop != null ) {
          shoptop.innerHTML =
          '<object width="960" height="187"><param name="movie" value="somefilename.swf">' +
          '<embed src="themes/shoppagott3/images/shoppagott.swf" width="960" height="187"></embed>';
      }
  }

  window.onload= function() { insertFlash() };

