// Set namespace
if (typeof(wwx) == "undefined") {
  wwx = {
    id: 'module webworxx',
    eurosign: '\u20AC',
    voorkeurstaal: 'nl',
    keys: function (obj) {
      // Return an Array of the property names of an object (in the order determined by for propName in obj).
      var rval = [];
      for (var prop in obj) {
          rval.push(prop);
      }
      return rval;
    },
    values: function (obj) {
      // Return an Array of the property values of an object (in the order determined by for propName in obj).
      var rval = [];
      for (var prop in obj) {
          rval.push(obj[prop]);
      }
      return rval;
    },
    items: function (obj) {
      // Return an Array of [propertyName, propertyValue] pairs for the given obj (in the order determined by for propName in obj).
      var rval = [];
      var e;
      for (var prop in obj) {
          var v;
          try {
              v = obj[prop];
          } catch (e) {
              continue;
          }
          rval.push([prop, v]);
      }
      return rval;
    },
    neemTekst: function(cd) { 
      return Teksten[wwx.voorkeurstaal][cd];
    }
  };
}
if (typeof(wwx.widgets) == "undefined") {
  wwx.widgets = {
    id: 'module wwx.widgets'
  };
}



Teksten = {
  'nl': {
    /* Verwerking betaling */
    'PS_MOMENT_PLZ':'Momentje a.u.b...',
    'PS_STORE_PMIN':'Opslaan betalingsinformatie',
    'PS_PRC_ERROR1':'Verwerkingsfout',
    'PS_PRC_ERROR2':'Fout tijdens het verwerken van uw order, probeer het a.u.b. opnieuw',
    'PS_AUTHORIZED':'Betaling is geautoriseerd',
    'PS_IN_PROCESS':'Uw bestelling wordt in behandeling genomen.',
    'PS_CF_MAIL'   :'U ontvangt over enkele ogenblikken een bevesting van uw bestelling per e-mail',
    'PS_CANCEL_BCS':'U heeft de betaling geannuleerd',  
    'PS_NO_ORD_WOP':'Zonder betaling kunnen wij uw bestelling niet in behandeling nemen. Probeer het opnieuw!',
    'PS_AUTH_ERROR':'Fout tijdens autorisatie van uw betaling',     
    'PS_TRY_AGAIN' :'Probeer het later opnieuw!', 
    'PS_WAIT_AUTH' :'Afhandelen betaling',
    'PS_WAIT_AUTH2':'Na invoer van uw gegevens wordt betaling afgrerond...',
    'PS_PAYM_REJCT':'Betaling is geweigerd',
    'PS_NO_PROCESS':'Uw bestelling wordt niet in behandeling genomen, probeer later opnieuw.',

    /* Buttons */
    'BT_CONTINUE'  :'Doorgaan...',
    'BT_MY_REGISTR':'Mijn gegevens',
    'BT_GO_BACK'   :'Winkel verder',
    'BT_GO_PREV'   :'Winkel verder',

    /* Check out form */
    'CO_CHOUT_FORM':'Ophalen van het checkoutformulier',
    'CO_STEP1'     :'Aanmelden/Inloggen',
    'CO_STEP1BACK' :'Terug',
    'CO_STEP1_PW'  :'(wachtwoord vergeten)',
    'CO_STEP1_VE'  :'Vul het e-mailadres in waarmee u geregistreerd bent en klik op "Doorgaan...", wij zenden u dan z.s.m een nieuw wachtwoord.',
    'CO_STEP1_VE2'  :'Vul het e-mailadres in waarmee u geregistreerd bent en klik op "Doorgaan...',    
    'CO_STEP1_LI'  :'(inloggen)', 
    'CO_STEP1_RG'  :'(aanmelden)', 
    'MSG_NEWPW'    :'Over enkele ogenblikken ontvangt u per e-mail een nieuw wachtwoord', 
    'MSG_REGPW'    :'Vul a.u.b. het emailadres in waarmee u zich heeft aangemeld!', 
    'MSG_VALID_EMAIL':'Vul een valide e-mail adres in',
    'CO_STEP1_VE1' :'Vul het e-mailadres in waarmee u geregistreerd bent en klik op "Doorgaan..."',    
    'CO_STEP1_VE2':'Vul het e-mailadres in waarmee u geregistreerd bent gevolgd door TAB-toets.',
    
    'CO_STEP2'     :'Registratie',
    'CO_STEP3'     :'Afleveradres/Betaling',
    'CO_FETCH_FORM':'U bent nog niet geregistreerd als klant, ophalen van het registratieformulier',
    'CO_LOGGED_IN' :'U bent nu ingelogd, we gaan verder met het plaatsen van uw bestelling.',    
    'CO_INVALID_PW':'Uw wachtwoord is onjuist, probeer opnieuw.',            
    'CO_LOGGED_OUT':'U bent nu uitgelogd.',
    'CO_FORM_INCMP':'Invoervelden met een rode omkadering zijn nog niet correct ingevuld,\ncorrigeer deze voordat u verder gaat.',
    'CO_STORE_REG' :'Opslaan registratieformulier',                    
    'CO_REG_COMPL1':'Uw registratie is verwerkt...',                    
    'CO_CONFIRMORD':'Bestelling ontvangen',
    'CO_CONFIRMTXT':'Bedankt voor uw bestelling. Uw bestelling wordt momenteel verwerkt. Over enkele ogenblikken ontvangt u een bevestiging van uw bestelling en uw betaling per email.',
    'CO_DELIV_ADDR':'Afleveradres:',
    'CO_REG_COMPL2':'U bent nu geregistreerd, we gaan verder met het plaatsen van uw bestelling.',      
    'CO_YOUR_ORDER':'Uw bestelling:',  
    'CO_DEAR':'Beste ',

    /* Basket */                                        
    'BA_ARTICL_SEL':'Dit artikel staat al in uw winkelwagentje.',
    'BA_ART_TOTPRC':'Producten, Totaalprijs:',
    'BA_ART_REST'  :'Let op! De verzending is gratis, als u nog voor',
    'BA_ART_REST2'  :'extra bestelt. ',
    
    'BA_SPEC_AANB' :'Speciale aanbiedingen',

    /* Product overview */
    'PO_ORDER'     : 'Bestel',
    'PO_MOREINFO'  :'Meer info',
    'PO_BACK_OV'   :'Terug naar overzicht',

    /* algemeen */
    'Inhoud:': 'Inhoud:',
    'Prijs:': 'Prijs:',
    'QAANSWER':'Antwoord'
  },
  'de': {
    /* Verwerking betaling */
    'PS_MOMENT_PLZ':'Moment bitte...',
    'PS_STORE_PMIN':'Speicherung der Kontodaten.',
    'PS_PRC_ERROR1':'Datenverarbeitungsfehler',
    'PS_PRC_ERROR2':'Verarbeitungsfehler bei Ihrer Bestellung! Bitte probieren Sie es erneut.',
    'PS_AUTHORIZED':'Die Bezahlung ist autorisiert',
    'PS_IN_PROCESS':'Ihre bestellung ist in Berarbeitung.',
    'PS_CF_MAIL'   :'Sie erhalten umgehend eine e-Mail mit einer Bestätigung Ihrer Bestellung',
    'PS_CANCEL_BCS':'Sie haben den Bezahlvorgang abgebrochen',  
    'PS_NO_ORD_WOP':'Ohne Bezahlung können wir Ihre Bestellung nicht bearbeiten. Bitte probieren Sie es erneut!',
    'PS_AUTH_ERROR':'Fehler bei der Autorisierung Ihrer Bezahlung',     
    'PS_TRY_AGAIN' :'Bitte versuchen Sie es später wieder!', 
    'PS_WAIT_AUTH' :'Auf Bestätigung warten',     
    'PS_WAIT_AUTH2':'Warte auf Autorisierung Ihrer Bezahlung...',
    'PS_PAYM_REJCT':'Bezahlung wurde verweigert',
    'PS_NO_PROCESS':'Ihre Bestellung konnte nicht bearbeitet werden. Bitte probieren Sie später noch einmal.',

    /* Buttons */
    'BT_CONTINUE'  :'Einkauf fortsetzen',                  
    'BT_MY_REGISTR':'Meine Daten',
    'BT_GO_BACK'   :'Zurück zum Shop',
    'BT_GO_PREV'   :'Zurück zum Shop',

    /* Check out form */
    'CO_CHOUT_FORM':'Ophalen van het checkoutformulier',    
    'CO_STEP1'     :'Anmelden/Einloggen',
    'CO_STEP1BACK' :'Zuruck', 
    'CO_STEP1_PW'  :'(Kennwort vergessen)', 
    'CO_STEP1_VE'  :'Geben Sie die emailadresse ihrer registrierung und wählen Sie "Einkauf fortsetzen...", Wir senden sie sofort ein neues Kennwort.',
    'CO_STEP1_LI'  :'(einloggen)', 
    'CO_STEP1_RG'   :'(anmelden)', 
    'CO_STEP2'     :'Registrierung',
    'CO_STEP3'     :'Lieferadresse/Bezahlung',
    'CO_FETCH_FORM':'U bent nog niet geregistreerd als klant, ophalen van het registratieformulier',
    'CO_LOGGED_IN' :'Sie sind jetzt eingeloggt. Ihre Bestellung wird nun bearbeitet.',    
    'CO_INVALID_PW':'Falsches Kennwort. Versuchen Sie es erneut.',            
    'CO_LOGGED_OUT':'Sie sind jetzt ausgeloggt.',
    'CO_FORM_INCMP':'Die rot markierten Eingabefelder sind noch nicht korrekt ausgefüllt. Bitte korrigieren Sie diese, bevor Sie fortfahren.',
    'CO_STORE_REG' :'Speicher registrierung',                    
    'CO_REG_COMPL1':'Erfolgreiche Registrierung...',                    
    'CO_CONFIRMORD':'Bestellung empfangen',
    'CO_CONFIRMTXT':'Vielen Dank für Ihren Auftrag. Ihre Bestellung ist zur Zeit in der Bearbeitung. In Kürze erhalten Sie eine e-Mail, die Ihren Auftrag und Ihre Bezahlung bestätigt. per email.',
    'CO_DELIV_ADDR':'Lieferadresse:',
    'CO_REG_COMPL2':'Sie sind jetzt als Kunde registriert. Ihre Bestellung wird nun bearbeitet.',      
    'MSG_NEWPW'    :'Sie werden in einige momenten ein neues Kennwort bekommen', 
    'MSG_REGPW'    :'Geben Sie bitte die emailaddresse ihrer registrierung!', 
    'MSG_VALID_EMAIL':'Geben Sie ein correctes email ein',
    'CO_STEP1_VE1' :'Geben Sie die emailadresse ihrer registrierung und wählen Sie "Einkauf fortsetzen..."',    
    'CO_STEP1_VE2' :'Geben Sie die emailadresse ihrer registrierung gefolgd durch die TAB-taste.', 
    'CO_YOUR_ORDER':'Ihre Bestellung:',
    'CO_DEAR':'Sehr geehrter ',

    /* Basket */                                        
    'BA_ARTICL_SEL':'Dieser Artikel steht bereits auf Ihrer Einkaufsliste.',
    'BA_ART_TOTPRC':'Produkte, Gesamtpreis:',
    'BA_ART_REST'  :'Achtung! Es fehlen nur noch',
    'BA_ART_REST2'  :'und die Versandkosten entfallen!',
    'BA_SPEC_AANB' :'Sonderangebote',

    /* Product overview */
    'PO_ORDER'     :'Bestellen',
    'PO_MOREINFO'  :'Mehr infos',
    'PO_BACK_OV'   :'Zurück zur Übersicht',
    
    /* algemeen */
    'Inhoud:': 'Inhalt:',
    'Prijs:': 'Preis:',
    'QAANSWER':'Antwort'

  },
  'en': {
    /* Verwerking betaling */
    'PS_MOMENT_PLZ':'One moment please...',
    'PS_STORE_PMIN':'Store paymentinformation',
    'PS_PRC_ERROR1':'Error during processing',
    'PS_PRC_ERROR2':'Error while processing your order, please try again',
    'PS_AUTHORIZED':'Payment is authorized',
    'PS_IN_PROCESS':'Your order will be processed.',
    'PS_CF_MAIL'   :'You will receive a confirmation by e-mail',
    'PS_CANCEL_BCS':'You cancelled payment',  
    'PS_NO_ORD_WOP':'Without payment we cannot process your order. Please try again!',
    'PS_AUTH_ERROR':'Error during authorisation of your payment',     
    'PS_TRY_AGAIN' :'Please try again later!', 
    'PS_WAIT_AUTH' :'Wait for approval',     
    'PS_WAIT_AUTH2':'Waiting for approval of your payment...',
    'PS_PAYM_REJCT':'Payment is refused',
    'PS_NO_PROCESS':'Your order will not be processed, Please try again later.',   
    
    /* Buttons */   
    'BT_CONTINUE'  :'Continue check out',                  
    'BT_MY_REGISTR':'My data',
    'BT_GO_BACK'   :'Continue shopping',
    'BT_GO_PREV'   :'Continue shopping',

    /* Check out form */
    'CO_STEP1'     :'Register/Log in',
    'CO_STEP1_PW'  :'(forgot password)', 
    'CO_STEP1BACK' :'Back', 
    'CO_STEP1_VE'  :'Enter the same e-mail address as in your registration and click on "Continue check out...", we will send you a new password ASAP.',
    'CO_STEP1_LI'  :'(log in)', 
    'CO_STEP1_RG'   :'(register)',     
    'CO_STEP2'     :'Registration',
    'CO_STEP3'     :'Delivery address/Payment',
    'CO_FETCH_FORM':'Fetch the check out form...',
    'CO_LOGGED_IN' :'Succesful logged in, let\'s continue your order.',    
    'CO_INVALID_PW':'Incorrect password, please try again.',            
    'CO_LOGGED_OUT':'You are logged out now.',
    'CO_FORM_INCMP':'Invoervelden met een rode omkadering zijn nog niet correct ingevuld,\ncorrigeer deze voordat u verder gaat.',
    'CO_STORE_REG' :'Storing registration form',                    
    'CO_REG_COMPL1':'Your registration is processed...',
    'CO_REG_COMPL2':'You are registered, let\'s continue your order.', 
    'CO_CONFIRMORD':'Order confirmation',
    'CO_CONFIRMTXT':'Thank you for your order. Your order will be executed right away. You will receive a confirmation of the order and your payment within a few minutes by email.',
    'CO_DELIV_ADDR':'Delivery address:',
    'MSG_NEWPW'    :'We have sent you a new password', 
    'MSG_REGPW'    :'Please enter the same e-mail address as in your registration!', 
    'MSG_VALID_EMAIL':'Enter a valid e-mail address',
    'CO_STEP1_VE2'  :'Enter the same e-mail address as in your registration and click on "Continue check out..."',    
    'CO_STEP1_VE2' :'Enter the same e-mail address as in your registration followed by the TAB-key.',
    'CO_YOUR_ORDER':'Your order:',
    'CO_DEAR':'Dear ',
         
    /* Basket */                                        
    'BA_ARTICL_SEL':'This item is in your basket already.',
    'BA_ART_TOTPRC':'Products, PRICE TOTAL:', 
    'BA_SPEC_AANB' :'Special offers',
    'BA_ART_REST'  :'Attention! ',
    'BA_ART_REST2'  :'are missing for a free shipping.',

    /* Product overview */
    'PO_ORDER'     :'Order',
    'PO_MOREINFO'  :'More info',
    'PO_BACK_OV'   :'Back to overview',

    /* algemeen */
    'Inhoud:': 'Content:',
    'Prijs:': 'Price:',
    'QAANSWER':'Answer'
  }
};

function get_page(art_no) {
  my_form = document.getElementById('myfrm');
  document.getElementById('start').value=parseInt(art_no,10);
  my_form.submit();
}
var myShoppingBasket = null; 

jQuery(function() {
  jQuery('#partnerslideshow').cycle('fade');
  get_prefered_language();
  // Set up a shopping basket
  try {
    myShoppingBasket = new wwx.widgets.ShoppingBasket();
    if (myShoppingBasket.basketopen) {
      myShoppingBasket.show();
      jQuery('#basketlist').removeClass('closed');
      jQuery('#basketlist').addClass('opened');
    } else {
      myShoppingBasket.hide();
      jQuery('#basketlist').removeClass('opened');
      jQuery('#basketlist').addClass('closed');
    }
  } catch(e3) {
    //log(e3);
  }
});

function languageSelected() {
  if (jQuery('#qaquery').length>0) {
    initqasearch();
  }
  if (/shop-products.htm/.test(location.pathname)) {
    srch = location.search.slice(1);
    qs = parse_search();
    if (typeof qs.id == 'undefined') {
      if (typeof(qs.cat) == 'undefined') {
        qs.cat = 'CAT-Nutrition';
      }
      product_overview = new wwx.born.ProductOverview(qs.cat);
    } else if (typeof qs.id != 'undefined') {
      product_overview = new wwx.born.ProductOverview(qs.cat, qs.id);          
    } 
  }
  jQuery('#maillist_verzendlijst')[0].value = 'mailinglist_born_'+wwx.voorkeurstaal;
}

parse_search = function() {
  srch = location.search.slice(1).split('=');
  rec = {}
  for (var x=0; x< srch.length; x+=2) {
    rec[srch[x]] = srch[x+1];
  }
  return rec;
};

ie_random = function() {
  return  Math.floor(Math.random()*100000);
};

get_prefered_language = function() {
  jQuery.getJSON('DesignerScripts/fetchLanguage?rn='+ie_random(), function(data) {
    if (data == 'def'){
      data = "nl";
    }
    wwx.voorkeurstaal = data; 
    if (wwx.voorkeurstaal.length>2) {
      wwx.voorkeurstaal = wwx.voorkeurstaal.slice(0,2);
    }
    
    switch(wwx.voorkeurstaal) {
      case 'de':
        jQuery("#h_art").replaceWith('<li id="h_art" class="column_art">Artikel</li>');
        jQuery("#h_price").replaceWith('<li id="h_price" class="column_price">Preis</li>');
        jQuery("#h_nr").replaceWith('<li id="h_nr" class="column_nr">Anzahl</li>');
        jQuery("#h_tot").replaceWith('<li id="h_tot" class="column_tot">Gesamt</li>');
        break;
      case 'en':
        jQuery("#h_art").replaceWith('<li id="h_art" class="column_art">Product</li>');
        jQuery("#h_price").replaceWith('<li id="h_price" class="column_price">Price</li>');
        jQuery("#h_nr").replaceWith('<li id="h_nr" class="column_nr">Qty</li>');
        jQuery("#h_tot").replaceWith('<li id="h_tot" class="column_tot">Total</li>');
        break;
      default:
        jQuery("#h_art").replaceWith('<li id="h_art" class="column_art">Product</li>');
        jQuery("#h_price").replaceWith('<li id="h_price" class="column_price">Prijs</li>');
        jQuery("#h_nr").replaceWith('<li id="h_nr" class="column_nr">Aantal</li>');
        jQuery("#h_tot").replaceWith('<li id="h_tot" class="column_tot">Totaal</li>');
        break;
    }
    languageSelected();    
  });
};

switch_language = function(lc)  { 
  if (lc == 'nl') {
    lc = 'def';
  }
  jQuery.getJSON('DesignerScripts/switchLanguage?lc='+lc+'&rn='+ie_random(), function(data) {
    if (document.all) {
      if (location.search === "") {
        location.search="?rn="+ie_random();
      } else {
        location.search=location.search+"&"+ie_random();
      }
    } else {
      location.reload();
    }
  });
};

toggle_visibility = function(elmid) {
  jQuery('#'+elmid+':hidden').show();
  jQuery('#'+elmid+':visible').hide();
};

// ------------------------------------------------ AJAX maillist subscription ---------------------------------------------------
send_maillist_subscription = function () {
  jQuery.post(
    'aanm_nieuwsbrief.htm/action', 
    jQuery("#digibrief").serialize(), 
    function(data) {
      jQuery('#digibrief_klein_message').replaceWith('<div id="digibrief_klein_message" style="padding-bottom:4px;display:block">'+data.message+'</div>');
      setTimeout(function() {
        jQuery('#digibrief_klein_message').hide();
      }, 7000);      
    },"json");
};
// ------------------------------------------------ AJAX Q&A search --------------------------------------------------------------
var qaold = '';

doliveqasearch = function () {
  res = $('qaresults');
  qaqry = $('qaquery').value;
  if (qaqry != qaold) {
    if (qaqry == '') {
      res.innerHTML = '';
      res.style.display = 'none';
    } else
      intraxxion.submitform('DesignerTemplates/qaresults.html', $('qaform'), displayqaresults);
  }
  qaold = qaqry;
  setTimeout('doliveqasearch()', 700) ;
};
initqasearch = function () {
  doliveqasearch();
};
displayqaresults = function (data) {
  $('qaresults').style.display = 'block';
  $('qaresults').innerHTML = data.responseText;
};

fetch_questions = function (subject_id ) {
  tt = $(subject_id).previousSibling;
  if ((tt.className != 'subjecttitle') && (tt.className != 'selected')) { 
    tt = tt.previousSibling;
  }
  
  if ($(subject_id).style.display == 'none') {
    $('subject').value = subject_id;
    tt.className = 'selected';    
    intraxxion.submitform('qandapage.htm/fetch_questions', $('subjform'), displaysubjectresults);
  } 
  if ($(subject_id).style.display == 'block') {
    $(subject_id).style.display = 'none';
    tt.className = 'subjecttitle';    
  }
};

displaysubjectresults = function (data) {
  resultset = JSON.parse(data.responseText);
  var newDiv = DIV({'id':resultset.id,'class':'subjectcontent'}) 
  for (x = 0; x < resultset.rows.length;x++) {
    hdr = DIV({'id':resultset.rows[x].id,'class':'answertitle'}, resultset.rows[x].pagetitle)
    connect(hdr,'onclick', this, 
      function(e) {
        toggle_visibility('CN_'+e.target().id);
      }
    );
    newDiv.appendChild(hdr);
    cnt = DIV({'id':'CN_'+resultset.rows[x].id,'class':'answercontent'});
    cnt.innerHTML = '<span class="answer">'+wwx.neemTekst('QAANSWER')+':</span>'+resultset.rows[x].content;
    newDiv.appendChild(cnt);
  }
  swapDOM(resultset.id, newDiv);
  $(resultset.id).style.display = 'block';
};
// ------------------------------------------------ Checkout (Controller) -------------------------------------------------
var shopfrontname = 'shop-products.htm'

Checkout = function(elem) {
  bindMethods(this);
  this.elem = elem;
  this.loggedIn = new CheckoutLogin(this);
  this.customer = null;
  this.checkoutPayment = null;
  this.costs = null;
  this.step1 = null;
  this.step2 = null;
  this.step3 = null;
  this.init();
};

Checkout.prototype = {
  
  init: function() {
    this.costs = new wwx.born.Costs(this.costsReady);
    this.specials = new wwx.born.SpecialsOverview();
  },
  costsReady: function() {
    this.renderCheckoutPage();
    this.showCheckoutPage();
  },
  renderCheckoutPage: function() {
    // Render the checkout page part.
    this.checkout = DIV({'style':'clear:both','id':'checkout'},null);
    specialscnt = DIV({'id':'specialscontainer'},
      DIV({'id':'specialsheader'}, wwx.neemTekst('BA_SPEC_AANB')),
      DIV({'id':'specialscontent'}, null));
    this.step1 = DIV({'id':'maincontent','style':'display:block'},
      specialscnt,
      DIV({'id':'steps'},
        DIV({'id':'step1'}, 'Stap 1.', BR(null), wwx.neemTekst('CO_STEP1')),
        DIV({'id':'step2'}, 'Stap 2.', BR(null), wwx.neemTekst('CO_STEP2')),
        DIV({'id':'step3'}, 'Stap 3.', BR(null), wwx.neemTekst('CO_STEP3'))
      ), this.checkout
    );
  },
  showCheckoutPage: function() {
    swapDOM(this.elem, this.step1);
    
    // Indicate the status.
    setOpacity($('step1'), 1);
    setOpacity($('step2'), 0.6);
    setOpacity($('step3'), 0.6);      

    // Check if  customer is already logged in
    connect(this.loggedIn, 'customerLoggedIn', this, this.customerLoggedIn);
    connect(this.loggedIn, 'customerLoginComplete', this, this.customerLoginComplete);
    
    connect(this.loggedIn, 'customerNotLoggedIn', this, this.customerNotLoggedIn);
    connect(this.loggedIn, 'loadCustomer', this, this.loadCustomer);
    
    this.specials.init();  
    connect($('specialsheader'),'onclick', function(e) {
      if ($('specialscontent').style.display == 'none') {
        blindDown($('specialscontent'));
        if (hasElementClass($('specialsheader'),'closed')) {
          removeElementClass($('specialsheader'), 'closed');
        }
      } else {
        blindUp($('specialscontent'));
        addElementClass($('specialsheader'), 'closed');
      }
    });
    this.loggedIn.checkLoggedIn();
  },
  customerLoggedIn: function() {
    // Load customers data and proceed with payment (step 3) + c_email is sent by the signal
    if (this.customer != null) {
      // Cleanup events
      disconnectAll(this.customer)
    }
    this.customer = new CheckoutCustomer(c_email);
    connect(this.customer, 'customerLoaded', this, this.customerLoginComplete);
    connect(this.customer, 'unknownCustomer', this, this.registerNewCustomer);
  },
  customerLoginComplete: function() {
    this.checkoutPayment = new CheckoutPayment(this.customer);    
  },
  customerNotLoggedIn: function() {
    // Load login form and proceed with login (step 1)
    this.loggedIn.loadChoiceForm();
  },
  loadCustomer: function() {
    // load the customer object + c_email is sent by the signal
    if (this.customer != null) {
      // Cleanup events
      disconnectAll(this.customer)
    }
    this.customer = new CheckoutCustomer(c_email);
    connect(this.customer, 'customerLoaded', this, this.proceedWithLogin);
    connect(this.customer, 'unknownCustomer', this, this.registerNewCustomer);
  },
  proceedWithLogin: function() {
    this.loggedIn.proceedWithLogin(this.customer.customerdata.id);
  },
  registerNewCustomer: function() {
    swapDOM($('checkout'),
      DIV({'id':'checkout'},
        H1(null, ('PS_MOMENT_PLZ')),
        DIV(null, wwx.neemTekst('CO_FETCH_FORM'))));
        
    connect(this.customer, 'customerLoginComplete', this, this.customerLoginComplete);
    this.customer.loadRegistrationForm();
  }
};
// ------------------------------------------------ Checkout Login (step 1) -----------------------------------------------

CheckoutLogin = function(checkout) {
  bindMethods(this);
  this.choiceform = shopfrontname+'/01-checkout-choice-'+wwx.voorkeurstaal+'.json'
  this.checkLoginMethod = shopfrontname+'/json_logged_in';
  this.loginMethod =  shopfrontname+'/login-customer.json';
  this.checkout = null; 
  this.checkoutDiv = null;
  this.loggedIn = false;
  this.elem = checkout.elem;
  this.key = '';
};

CheckoutLogin.prototype = {
  checkLoggedIn: function() {  
    myShoppingBasket.freeze();    
    d = loadJSONDoc(this.checkLoginMethod,{'rn':ie_random()});
    d.addCallbacks(this.checkLoggedInReady,this.checkLoggedInFailed);
  },
  checkLoggedInReady: function(data) {
    if (data.status) {
      this.loggedIn = true;
      this.key = data.key;
      c_email = data.mail;
      signal(this, 'customerLoggedIn', c_email);
    } else {
      signal(this, 'customerNotLoggedIn');
    }
    this.loadFormDef1(); 
  },
  checkLoggedInFailed: function(err) {
    /*log('CheckoutPayment.checkLoginFailed');*/
  },
  loadChoiceForm:function() {
    this.loginForm = new WxGui.Form.Form();       
    this.loginForm.init('choiceform', this.elem, this.choiceform, false, this.choiceFormReady);   
  },
  choiceFormReady:function(err, frm) {
    this.checkout = DIV({'style':'clear:both','id':'checkout'}, 
                      H1({'id':'choiceheader'},'1.'+wwx.neemTekst('CO_STEP1')), 
                      err, frm, 
                      DIV({'id':'msgdiv'})
                    );
    swapDOM($('checkout'), this.checkout);                
    
    // Create buttons 
    this.backbutton = DIV({'class':'formbutton','style':'display:none'}, wwx.neemTekst('CO_STEP1BACK'));
    
    this.frmbutton1 = DIV({'class':'formbutton'}, wwx.neemTekst('BT_GO_PREV'));
    this.frmbutton2 = DIV({'class':'formbutton'}, wwx.neemTekst('BT_CONTINUE'));
    buttons = DIV({'id':'checkoutbuttons'}, this.backbutton, this.frmbutton1, this.frmbutton2);
    appendChildNodes($('checkout'), buttons);

    // hide labels and requ
    jQuery('.label, .required, .notrequired').hide();

    // Connect buttons
    connect(this.backbutton, 'onclick', function(e) {
      myShoppingBasket.checkout();
    });
    connect(this.frmbutton1, 'onclick', function(e) {location.reload()});
    connect(this.frmbutton2, 'onclick', this,
      function(e) {        
        mychoice = this.loginForm.getFieldValue('choice');
        idfield = this.loginForm.getField('id');
        jQuery('.label, .required, .notrequired').show();
        switch (mychoice) {
          case 'PW':     
            swapDOM($('choiceheader'),H1({'id':'choiceheader'}, '1.'+wwx.neemTekst('CO_STEP1')+' '+wwx.neemTekst('CO_STEP1_PW')))
            this.loginForm.getField('id').setVisible();
            this.loginForm.getField('id').setFocus();
            disconnectAll(this.frmbutton2);
            showElement(this.backbutton);
            connect(this.frmbutton2, 'onclick', this,
              function(e) {
                if (this.loginForm.getField('id').checkValue()) {
                  this.sendNewPassword();
                } else {
                  alert(wwx.neemTekst('MSG_VALID_EMAIL'))
                }
              }
            );            
            break;
          case 'Register':
            swapDOM($('choiceheader'),H1({'id':'choiceheader'}, '1.'+wwx.neemTekst('CO_STEP1')+' '+wwx.neemTekst('CO_STEP1_RG')))
            this.loginForm.getField('id').setVisible();
            this.loginForm.getField('id').setFocus();
            disconnectAll(this.frmbutton2);
            showElement(this.backbutton);
            connect(this.frmbutton2, 'onclick', this,
              function(e) { 
                mailfield = this.loginForm.getField('id')
                if (mailfield.checkValue()) {
                  c_email = this.loginForm.getFieldValue('id');
                  signal(this,'loadCustomer', c_email);
                } else {
                  alert(wwx.neemTekst('MSG_VALID_EMAIL'))
                }
              }
            );            
            break;
          default:            
            swapDOM($('choiceheader'),H1({'id':'choiceheader'}, '1.'+wwx.neemTekst('CO_STEP1')+' '+wwx.neemTekst('CO_STEP1_LI')))
              this.loginForm.getField('id').setVisible();
              this.loginForm.getField('id').setFocus();
              idfield.afterFieldValidated = bind(function() {
                // Fetch the customer            
                c_email = this.loginForm.getFieldValue('id');
                signal(this,'loadCustomer', c_email);
              },this); 
              showElement(this.backbutton);
                
              break;          
        }
        this.loginForm.getField('choice').setInvisible();
      }    
    );
    
  },
  sendNewPassword: function() { 
    idf = this.loginForm.getField('id');
    if (idf.checkValue()) {
      var req=getXMLHttpRequest();
      req.open("POST", shopfrontname+'/checkout-forgotten-password', true);
      req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      var data=encodeURIComponent('id')+'='+encodeURIComponent(this.loginForm.getFieldValue('id'));
      var d = sendXMLHttpRequest(req, data);
      d.addCallbacks(
        function(data) {
          res = JSON.parse(data.responseText);
          if (res.status == 'OK') {                                                    
            alert(wwx.neemTekst('MSG_NEWPW'));
            location.reload();
          } else { 
            idf.setFocus();
            alert(wwx.neemTekst('MSG_REGPW'));
          }
        },
        function(err) {
          alert('Fout tijdens verzenden!')
        }
      );
    } else {                                  
      idf.setFocus();
      alert(wwx.neemTekst('MSG_REGPW'));
    }
  },
  proceedWithLogin: function(id) {
    pwf = this.loginForm.getField('passwd');
    pwf.setVisible();
    pwf.setFocus();
    pwf.afterFieldValidated = bind(function() {
      this.login(id, this.loginForm.getFieldValue('passwd'));
    }, this);
  },
  login:function(id, pwd) {
    var req=getXMLHttpRequest();
    req.open("POST", this.loginMethod, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var data=encodeURIComponent('__ac_name')+'='+encodeURIComponent(id)
             +'&'+encodeURIComponent('__ac_password')+'='+encodeURIComponent(pwd);
    var d = sendXMLHttpRequest(req, data);
    d.addCallbacks(this.loginReady,this.loginFailed);
  },
  loginReady:function(data) {
    li = JSON.parse(data.responseText);
    if ((li.status == 'LOGGEDIN') || (li.status == 'LOGGEDOUT')) {    
      this.loggedIn = true;
      swapDOM($('msgdiv'), DIV({'id':'msgdiv'},
        wwx.neemTekst('CO_LOGGED_IN')));
      callLater(1.0, swapDOM, $('msgdiv'), DIV({'id':'msgdiv'}) );
      callLater(1.0, signal, this, 'customerLoginComplete');
    } else if (li.status == 'NAMEPASSWD'){
      this.loggedIn = false;
      swapDOM($('msgdiv'), DIV({'id':'msgdiv'},
        wwx.neemTekst('CO_INVALID_PW')));
        this.loginForm.getField('passwd').setFocus();
      callLater(3.0, swapDOM, $('msgdiv'), DIV({'id':'msgdiv'}) );
    }
  },
  loginFailed:function(err) {
    alert(err);
  }
};

// ------------------------------------------------ Checkout Customer (step 2) ----------------------------------------------

function logout() {
  d = doSimpleXMLHttpRequest('logged_out');
  d.addCallbacks(
    function(data) {
      location.reload();
    }, 
    function(err) {   
      /*log(err);*/
    }
  );
}

CheckoutCustomer = function(id) {
  bindMethods(this);
  this.e_mail = id;
  this.formdefinition = shopfrontname+'/checkout-registration-form-'+wwx.voorkeurstaal+'.json';
  this.loadMethod = shopfrontname+'/checkout-load-customer.json';
  this.storeMethod = shopfrontname+'/checkout-store-customer.json';  
  this.registrationForm = null;
  this.customerdata = {
    'id':'',
    'c_rel':'',
    'pw':'',
    'cf':'',
    'e_mail':'',
    'nm':'',
    'nm_first':'',
    'nm_sur':'',
    'gender':'',
    'ad':'',
    'nr_ad':'',
    'ext_ad':'',
    'pc_ad':'',
    'city_ad':'',
    'c_country':'',
    'phone':'',
    'fax':'',
    'a_ad':'',
    'a_nr_ad':  '',   
    'a_ext_ad': '',  
    'a_pc_ad':  '',   
    'a_city_ad':'', 
    'found':false
  };
  this.customerLoaded = false;
  this.loadCustomer();
};

CheckoutCustomer.prototype = {
  loadCustomer: function() {   
    d = loadJSONDoc(this.loadMethod,{'id':this.e_mail,'rn':ie_random()});
    d.addCallbacks(this.loadCustomerReady, this.loadCustomerFailed);
  },
  loadCustomerReady: function(data) {
    if (data.found == true) {
      // customer loaded, ask for passwd and continue
      this.customerdata = data;  
      this.customerLoaded = true;
      signal(this, 'customerLoaded');
    } else {
      signal(this, 'unknownCustomer');
    }
  },
  loadCustomerFailed: function(err) {
    /*log('CheckoutCustomer.loadCustomerFailed: '+err);*/
  },
  // Registration
  loadRegistrationForm: function() {
    this.registrationForm = new WxGui.Form.Form();
    this.registrationForm.init('registrationForm', 
                                $('checkout'), 
                                this.formdefinition, 
                                false,
                                this.registrationFormReady);   
  },
  registrationFormReady: function(err,frm) {
    setOpacity($('step1'), 0.6);
    setOpacity($('step2'), 1);
    setOpacity($('step3'), 0.6);
                                       
    this.checkoutDiv = DIV({'id':'checkout','style':'display:block'},
        H1(null, '2. '+wwx.neemTekst('CO_STEP2')), err, frm
      );
    swapDOM($('checkout'), this.checkoutDiv);   
    this.registrationForm.setFieldValue('e_mail', this.e_mail) ;
    pwd = this.registrationForm.getField('passwd');
    pwd.toggleEditable();
    pwd.toggleRequired();
    pwd.setFocus();

    cfm = this.registrationForm.getField('confirm');
    cfm.leaveField = bind(function() {
        passwd = this.wform.getField('passwd');
        rv = compare(this.value, passwd.value);
        return (rv == 0)
      },cfm);
      
    this.frmbutton1 = DIV({'class':'formbutton'}, wwx.neemTekst('BT_CONTINUE'));
    this.frmbutton2 = DIV({'class':'formbutton'}, wwx.neemTekst('BT_GO_PREV'));

    buttons = DIV({'id':'checkoutbuttons'}, this.frmbutton2, this.frmbutton1);
    appendChildNodes($('checkout'), buttons);

    connect(this.frmbutton1, 'onclick', this.registerFormValues);
    connect(this.frmbutton2, 'onclick', this.backToShop);

    if (this.customerLoaded) {      
      this.registrationForm.getField('passwd').setNotRequired();
      this.registrationForm.getField('passwd').setNotEditable();
      this.registrationForm.getField('passwd').setInvisible();   
      
      this.registrationForm.getField('confirm').setNotRequired();
      this.registrationForm.getField('confirm').setNotEditable();
      this.registrationForm.getField('confirm').setInvisible();

      this.registrationForm.setFieldValue('id', this.customerdata.id);
      this.registrationForm.setFieldValue('nm_first', this.customerdata.nm_first);
      this.registrationForm.setFieldValue('nm_sur', this.customerdata.nm_sur);
      this.registrationForm.setFieldValue('gender', this.customerdata.gender);
      this.registrationForm.setFieldValue('ad', this.customerdata.ad);
      this.registrationForm.setFieldValue('nr_ad', this.customerdata.nr_ad);
      this.registrationForm.setFieldValue('pc_ad', this.customerdata.pc_ad);
      this.registrationForm.setFieldValue('city_ad', this.customerdata.city_ad);
      this.registrationForm.setFieldValue('phone', this.customerdata.phone);
      this.registrationForm.setFieldValue('fax', this.customerdata.fax);
      this.registrationForm.setFieldValue('c_country', this.customerdata.c_county);
    } else {                                             
      this.registrationForm.getField('passwd').setRequired();
      this.registrationForm.getField('passwd').setEditable();
      this.registrationForm.getField('passwd').setVisible();   
      
      this.registrationForm.getField('confirm').setRequired();
      this.registrationForm.getField('confirm').setEditable();
      this.registrationForm.getField('confirm').setVisible();

      this.registrationForm.getField('passwd').setFocus();
    }
  },
  showRegistrationForm: function() {
    this.registrationForm.setFieldValue('id', this.customerdata.id);
    this.customerLoaded = true;
    
    swapDOM($('checkout'), this.checkoutDiv);
    setOpacity($('step1'), 0.6);
    setOpacity($('step2'), 1);
    setOpacity($('step3'), 0.6);
    
  },  
  backToShop: function(evt) {
    location.reload();
  },
  registerFormValues: function(evt) {      
    correct = this.registrationForm.checkForm();
    if (this.registrationForm.formOK) {
      this.form2Data = this.registrationForm.getFieldValues();
      for (var fd=0; fd < this.form2Data.length; fd++) {
        fdrec = this.form2Data[fd];
        this.customerdata[fdrec.id] = fdrec.value
      }
      if (this.customerLoaded == false) {
        this.customerdata.id = 'AUTO';
        this.customerdata.c_rel = 'AUTO';
      }
      this.updateRegistration();
    } else {
      alert(wwx.neemTekst('CO_FORM_INCMP'));
    }                                                  
  },
  updateRegistration: function() {
    var req=getXMLHttpRequest();
    req.open("POST", this.storeMethod, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var data=encodeURIComponent('formdata')+'='+encodeURIComponent(serializeJSON(this.customerdata))
    var d = sendXMLHttpRequest(req, data);
    swapDOM($('checkout'), 
      DIV({'id':'checkout'},
        H1(null,wwx.neemTekst('PS_MOMENT_PLZ')),
        DIV(null,wwx.neemTekst('CO_STORE_REG'))
      )
    );   

    res = d.addCallbacks(this.updateRegistrationReady, this.updateRegistrationFailed);                 
  },
  updateRegistrationReady: function(data) {    
    this.customerdata = evalJSON(data.responseText);   
    swapDOM($('checkout'), 
      DIV({'id':'checkout'},
        H1(null,wwx.neemTekst('CO_REG_COMPL1')),
        DIV(null,wwx.neemTekst('CO_REG_COMPL2'))));   

    if (myShoppingBasket.co.checkoutPayment != null) {
      myShoppingBasket.co.checkoutPayment = new CheckoutPayment(this);
    } else {
      signal(this,'customerLoginComplete');
      this.customerLoaded = true;
    }
  },
  updateRegistrationFailed: function(err) {
    alert(err);
  }
}
// ------------------------------------------------ Checkout Payment (step 3) -----------------------------------------------

CheckoutPayment = function(customer) {
  bindMethods(this);
  this.storeMethod = 'TWYP/add_payment';
  this.baseUrl = 'http://www.bornsport.com/TWYP/';
  this.formdefinition = shopfrontname+'/checkout-'+wwx.voorkeurstaal+'.json';
  this.loadHiddenFields();
  this.customer = customer;
  this.payservice = 'https://twyp.secure-ing.com/ncol/prod/orderstandard.asp';
  this.fields = [];
  this.formloaded = false;
  this.paymentDiv = null;
  this.discount = null;
};

CheckoutPayment.prototype = {
  loadHiddenFields: function() {
    d = loadJSONDoc('payment/get_payment_fields',{'rn':ie_random()});
    d.addCallbacks(this.loadHiddenFieldsReady, this.loadHiddenFieldsFailed);
  },
  loadHiddenFieldsReady: function(data) {
    this.fields = data;
    this.showForm();
  },
  loadHiddenFieldsFailed: function(err) {
    log(err);
  },
  loadForm: function() {
    setOpacity($('step1'), 0.6);
    setOpacity($('step2'), 0.6);
    setOpacity($('step3'), 1);

    swapDOM($('checkout'), 
      DIV({'id':'checkout'},
        H1(null, wwx.neemTekst('PS_MOMENT_PLZ')),
        DIV(null,wwx.neemTekst('CO_CHOUT_FORM'))));   
    
    this.checkoutform = new WxGui.Form.Form();       
    this.checkoutform.init('lastform', $('maincontent'), this.formdefinition, false, this.formReady);       
  },
  addHiddenField: function(ob) {
    return INPUT({'type':'hidden','name':ob[0],'id':ob[0], 'value':ob[1]});
  },
  hideForm: function() {
    if (this.formloaded) {
      hideElement(this.checkoutform.formelement);   
      hideElement($('checkoutbuttons'));
    }
  },
  showForm: function() {
    if (this.formloaded) {
      showElement(this.checkoutform.formelement);   
      showElement($('checkoutbuttons'));
    } else {
      this.loadForm();
    }    
  },
  formReady: function(frm, err) {
    this.frmbutton1 = DIV({'class':'formbutton'}, wwx.neemTekst('BT_CONTINUE'));
    this.frmbutton2 = DIV({'class':'formbutton'}, wwx.neemTekst('BT_MY_REGISTR'));
    this.frmbutton3 = DIV({'class':'formbutton'}, wwx.neemTekst('BT_GO_BACK'));
    buttons = DIV({'id':'checkoutbuttons'}, this.frmbutton3, this.frmbutton2, this.frmbutton1);
    
    this.paymentDiv = DIV({'id':'checkout','style':'display:block'},
        H1(null, wwx.neemTekst('CO_STEP3')),
        frm
    );
    if (!discountCodeUsed) {
      this.discount = new wwx.born.DiscountCode(this.checkoutform.getField('action_code'));
    } else {
      this.checkoutform.getField('action_code').setNotEditable();
    }
    
    swapDOM($('checkout'), this.paymentDiv);
    
        
    this.checkoutform.setFieldValue('id', this.customer.customerdata.id);
    if (this.customer.customerdata.a_ad == '') {
      this.checkoutform.setFieldValue('ad', this.customer.customerdata.ad);
      this.checkoutform.setFieldValue('nr_ad', this.customer.customerdata.nr_ad);
      this.checkoutform.setFieldValue('pc_ad', this.customer.customerdata.pc_ad);
      this.checkoutform.setFieldValue('city_ad', this.customer.customerdata.city_ad);
    } else {
      this.checkoutform.setFieldValue('ad', this.customer.customerdata.a_ad);
      this.checkoutform.setFieldValue('nr_ad', this.customer.customerdata.a_nr_ad);
      this.checkoutform.setFieldValue('pc_ad', this.customer.customerdata.a_pc_ad);
      this.checkoutform.setFieldValue('city_ad', this.customer.customerdata.a_city_ad);      
    }

    appendChildNodes($('checkout'), buttons); 
    
    psiframe = createDOM('IFRAME', {'name':'payservice','id':'payservice','frameborder':'0', 'style':'display:none'},null);
    hiddenfields = FORM( {'method':'post','action':this.payservice,'id':'paymentform','name':'paymentform','style':'display:none','target':'payservice'}, 
                            map(this.addHiddenField, this.fields)
    );

    if ($('hiddenelements')) { 
      swapDOM($('hiddenelements'), DIV({'id':'hiddenelements'}, psiframe, hiddenfields));
    } else {
      appendChildNodes($('maincontent'), DIV({'id':'hiddenelements'}, psiframe, hiddenfields));
    } 
    this.formloaded = true;

    // Go and checkout the payment
    connect(this.frmbutton1, 'onclick', this, 
      function(e) {
        this.updateRelationData(); 
        this.storePaymentRecord(); 
      }
    );
    
    // Show registration / profile      
    connect(this.frmbutton2, 'onclick', this, 
      function(evt) {
        this.hideForm();
        this.updateRelationData();
        if (this.customer.registrationForm == null) {
          this.customer.loadRegistrationForm();
        } else {
          this.customer.showRegistrationForm();
        }
      }
    );
    
    // Go back to the store / cancel checkout
    connect(this.frmbutton3, 'onclick', function(evt) {
      location.reload();
    });   
    
    connect(this, 'paymentRecordStored', this, function() {
      /* Blind specials */
      blindUp($('specialscontent'));
      addElementClass($('specialsheader'), 'closed');
      
      var lang = 'nl_NL';
      if (wwx.voorkeurstaal==='en') {
        lang = 'en_US';
      }
      if (wwx.voorkeurstaal==='de') {
        lang = 'de_DE';
      }
      $('language').value = lang;
      $('PM').value = this.checkoutform.getFieldValue('payment');      
      $('amount').value = this.order.amount;
      $('orderID').value = this.order.id
      $('CN').value = this.customer.customerdata.nm_sur + ', '+this.customer.customerdata.nm_first;
      $('EMAIL').value = this.customer.customerdata.e_mail;
      $('ACCEPTURL').value = this.baseUrl+this.order.id+'/payment_accepted';
      $('declineurl').value = this.baseUrl+this.order.id+'/payment_rejected';
      $('exceptionurl').value = this.baseUrl+this.order.id+'/payment_exception';
      $('cancelurl').value = this.baseUrl+this.order.id+'/payment_canceled';
      /*rec = serializeJSON({
        'AMOUNT':$('amount').value,
        'CURRENCY':$('currency').value,
        'OPERATION':$('operation').value,
        'ORDERID':$('orderID').value,
        'PSPID':$('PSPID').value
      });*/

      d = loadJSONDoc('payment/getSHA', {'st':$('orderID').value+$('amount').value+$('currency').value+$('PSPID').value+$('operation').value}); // XXX //

      d.addCallbacks(
        function(data) {
          $('SHASign').value = data.sha;
          showElement($('payservice'));
          hideElement($('checkout'));
          $('paymentform').submit();
        },
        function(err) {
          $('SHASign').value = '';
        }
      )
    });                          
    
  },
  updateRelationData: function() {
    var req=getXMLHttpRequest();
    req.open("POST", this.customer.storeMethod, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
    this.customer.customerdata.a_ad = this.checkoutform.getFieldValue('ad');
    this.customer.customerdata.a_nr_ad = this.checkoutform.getFieldValue('nr_ad');
    this.customer.customerdata.a_pc_ad = this.checkoutform.getFieldValue('pc_ad');
    this.customer.customerdata.a_city_ad = this.checkoutform.getFieldValue('city_ad');
    
    var data=encodeURIComponent('formdata')+'='+encodeURIComponent(serializeJSON(this.customer.customerdata))
    var d = sendXMLHttpRequest(req, data);
    swapDOM($('checkout'), 
      DIV({'id':'checkout'},
        H1(null,wwx.neemTekst('PS_MOMENT_PLZ')),
        DIV(null,wwx.neemTekst('CO_STORE_REG'))
      )
    );   

    res = d.addCallbacks(this.updateRelationDataReady, this.updateRelationDataFailed);                 
  },
  updateRelationDataReady: function(data) {    
    this.customerdata = evalJSON(data.responseText);
  },
  updateRelationDataFailed: function(err) {
    alert(err);
  },
  storePaymentRecord: function() {
    myShoppingBasket.updateTotals();
    paymentData = {'amount': Math.round(myShoppingBasket.totalamt * 100),
                   'c_rel':this.customer.customerdata.id,
                   'currency':'EUR',
                   'theorder':serializeJSON(myShoppingBasket.getBasketData())
                  }
    myShoppingBasket.freeze();
    var req=getXMLHttpRequest();
    req.open("POST", this.storeMethod, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var data=encodeURIComponent('jsonrep')+'='+encodeURIComponent(serializeJSON(paymentData))
    var d = sendXMLHttpRequest(req, data);
    swapDOM($('checkout'), 
      DIV({'id':'checkout'},
        H1(null, wwx.neemTekst('PS_MOMENT_PLZ')),
        DIV(null, wwx.neemTekst('PS_STORE_PMIN'))
      )
    );   
    res = d.addCallbacks(this.storePaymentRecordReady, this.storePaymentRecordFailed); 
  },
  storePaymentRecordReady: function(data) {
    mydata = evalJSON(data.responseText);
    if (mydata.status == 'SUCCESS') {
      this.order = mydata.object;       
      signal(this, 'paymentRecordStored');
    } else {
      // iets gaat fout
      swapDOM($('checkout'), 
        DIV({'id':'checkout'},
          H1(null, wwx.neemTekst('PS_PRC_ERROR1')),
          DIV(null,wwx.neemTekst('PS_PRC_ERROR2'))
        )
      );   
    }
    return;
  },
  storePaymentRecordFailed: function(err) {
    /*log(err);*/
  } 
};

// ------------------------------------------------ ProductOverview -------------------------------------------------------
var product_overview = null;

/*
show_product = function(id, cat) {              
  if (location.href.split('/')[location.href.split('/').length-1].split('?')[0] == 'shop-products.htm') {
    product_overview = new wwx.born.ProductOverview(cat, id);                                                     
  } else {
    location.href = 'shop-products.htm?cat='+cat+'&id='+id
  }
};*/
if (typeof(wwx.born == "undefined")) {
  wwx.born = {
    id: 'module wwx.born',
    show_product: function(id, cat) {
      // Front end function to show product summary for a product              
      if (location.href.split('/')[location.href.split('/').length-1].split('?')[0] == 'shop-products.htm') {
        product_overview = new wwx.born.ProductOverview(cat, id);                                                     
      } else {
        location.href = 'shop-products.htm?cat='+cat+'&id='+id
      }
    }
  };
}
wwx.born.SpecialsOverview = function() {
  return {
    // public vars
    id: "wwx.born.SpecialsOverview",
    description: 'Specials class voor Born Store',
    category: 'CAT-AAN',
    fetchUrl: 'shop-products.htm/fetch',
    data: {},
    products: {},
    view: null,
    prod: null,
    viewid : 'specialscontent',

    // public methods
    init: function() {
      bindMethods(this);
      this.fetchProducts();
      return this;
    },
    
    fetchProducts: function() {
      d = loadJSONDoc(this.fetchUrl,{'cat':'CAT-AAN','rn':ie_random()});
      d.addCallbacks(this.fetchProductsReady, this.fetchProductsFailed);
    },
    
    addDataField: function(ob) {
      this.data[ob.id] = ob.value;
      return ob;
    },
    
    addProduct: function(ob) {
      this.products[ob[0].fields[0].value] = new wwx.born.Product(ob, this);
      return ob;
    },
    
    fetchProductsReady: function(data) {    
      map(this.addDataField, data.category[0].fields); 
      map(this.addProduct, data.products); 

      this.render(); 
      if (this.prod == null) {
        swapDOM($(this.viewid), this.view);
      } else {
        prd = this.products[this.prod];          
        prd.renderView();   
        swapDOM($(this.viewid), prd.view);
        navi = getElementsByTagAndClassName('A','prodcat', $('productnavigatie'))
        for (x =0 ;x < navi.length; x++) {      
          ob = navi[x];
          removeElementClass(ob,'selected');
          if (this.category == ob.id) 
            addElementClass(ob,'selected')
        }
      }    
      return;
    },
    
    fetchProductsFailed: function(err) {
      /*log(err);*/
    },
    
    render: function() {    
      k = keys(this.products);    
      plist = map(this.addToProductList, k);    
      products = map(this.getProductSummaryView, plist);

      this.view = DIV({'id':this.viewid},products);  
    },
    
    addToProductList: function(key) {
      return this.products[key];
    },
    
    getProductSummaryView: function(ob) {
      return ob.summaryView;
    },
    
    getProductView: function(ob) {
      return ob.view;
    }
    
  }.init();
};

wwx.born.ProductOverview = function(category, prod) {
  // private
  
  return {
    // public vars
    id: "wwx.born.ProductOverview",
    description: 'Productoverzicht class voor Born Store',
    category: category,
    fetchUrl: 'shop-products.htm/fetch',
    data: {},
    products: {},
    view: null,
    prod: prod,
    viewid: 'maincontent',

    // public methods
    init: function() {
      bindMethods(this);
      this.fetchProducts();
      return this;
    },
    
    fetchProducts: function() {
      d = loadJSONDoc(this.fetchUrl,{'cat':this.category,'rn':ie_random()});
      d.addCallbacks(this.fetchProductsReady, this.fetchProductsFailed);
    },
    
    addDataField: function(ob) {
      this.data[ob.id] = ob.value;
      return ob;
    },
    
    addProduct: function(ob) {
      this.products[ob[0].fields[0].value] = new wwx.born.Product(ob, this);
      return ob;
    },
    
    fetchProductsReady: function(data) {
      context = this;
      jQuery.each(data.category[0].fields, function(ix, ob) {
        context.data[ob.id] = ob.value;
      }); 
      jQuery.each(data.products, function(ix, ob) {
        context.products[ob[0].fields[0].value] = new wwx.born.Product(ob, context);
      });      
      this.render(); 
      if (this.prod == null) {
        swapDOM($(this.viewid), this.view);
      } else {
        prd = this.products[this.prod];          
        prd.renderView();   
        swapDOM($(this.viewid), prd.view);
        navi = getElementsByTagAndClassName('A','prodcat', $('productnavigatie'))
        for (x =0 ;x < navi.length; x++) {      
          ob = navi[x];
          removeElementClass(ob,'selected');
          if (this.category == ob.id) 
            addElementClass(ob,'selected')
        }
      }    
      return;
    },
    
    fetchProductsFailed: function(err) {
      log(err);
    },
    
    render: function() {    
      k = keys(this.products);    
      plist = map(this.addToProductList, k);    
      products = map(this.getProductSummaryView, plist);

      this.view = DIV({'id':this.viewid},
        products,
        DIV({'id':'dealerlocator'}, A({'href':'borns_sportscare_verkooppunten.htm','border':'0'}, IMG({'src':'DesignerImages/dealer-button.gif','border':'0','alt':'DEALER LOCATOR'})))
      );  
    },
    
    addToProductList: function(key) {
      return this.products[key];
    },
    
    getProductSummaryView: function(ob) {
      return ob.summaryView;
    },
    
    getProductView: function(ob) {
      return ob.view;
    }
    
  }.init();
};

// ---------------------------------------------- Product -----------------------------------------------------------------
wwx.born.Product = function(fields, overview) {
  return {
    // public vars
    id: "wwx.born.Product",
    description: 'Product class voor Born Store',
    overview: overview,
    fields: fields,
    summaryView: null,
    view: null,
    data: {},
    orderButtonSummary: null,
    summaryView: null,
    backToSummaryButton: null,
    baseprice: 0.00,
    price: 0.00,
    saleprice: 0.00,
    op_voorraad: "1",    
    init: function() {        
      bindMethods(this);
      if (wwx.voorkeurstaal!='en')
        this.formatNumber = numberFormatter("#,##0.00","","de_DE");
      else
        this.formatNumber = numberFormatter("#,##0.00","","en_US");

      dt = map(this.addDataTab, this.fields);

      switch  (prices_to_select) {           
        case 'OVERIG':
          this.baseprice = this.data.prijs_overig;
          this.price = this.data.prijs_overig;
          this.saleprice = this.data.aanbieding_prijs_overig;          
          break;
        case 'NL_BE':
        default: 
          this.baseprice = this.data.prijs_NL_BE;
          this.price = this.data.prijs_NL_BE;
          this.saleprice = this.data.aanbieding_prijs_NL_BE;          
          break;
      }                                                      
      if (this.data.aanbieding == '1') {
        this.price = this.saleprice;
      }       

      this.data.actualprice = this.price                     
      if (this.overview != null) {
        this.renderSummaryView();         
        this.renderView();
      } 
      return this;    
    },
    addDataTab: function(ob1) {     
      return map(this.addDataField, ob1.fields); 

    },
    addDataField: function(ob2) {
      this.data[ob2.id] = ob2.value;
      return ob2;
    },
    renderSummaryView: function() {
      this.moreInfoButton = DIV({'class':'summarymoreinfo'}, wwx.neemTekst('PO_MOREINFO'));         
      this.orderButtonSummary = DIV({'class':'summaryorder'});

      prijs = 
      this.summaryView = DIV({'class':'productsummary'},
        DIV({'class':'summaryimage','style':'background:url('+this.data.thumburl+') no-repeat'},
          (this.data.nieuw_product=='1') ? IMG({'class':'salelabel','src':'DesignerImages/label-new.png'}) : 
          (this.data.aanbieding=='1') ? IMG({'class':'salelabel','src':'DesignerImages/label-save-money.png'}) : 
          (this.data.op_voorraad=='0') ? IMG({'class':'salelabel','src':'DesignerImages/label-sold-out.png'}) : null
        ),
        DIV({'class':'summarydescription'},
          DIV({'class':'summarytext'}, 
            DIV({'class':'summarytitle'},this.data.title),
            (this.data.aanbieding=='1') ? 
            DIV(null,
            DIV({'class':'doorgestreept'},wwx.eurosign+' '+this.formatNumber(this.baseprice)+' '),
            DIV({'class':'aanbiedingsprijs'},wwx.eurosign+' '+this.formatNumber(this.price))) :
            DIV({'class':'summaryprijs'},wwx.eurosign+' '+this.formatNumber(this.price)),
            this.orderButtonSummary
          )
        )
      );

      // Connect click events to methods
      connect(this.summaryView, 'onclick', this, this.showMoreInfo);
      if (this.data.op_voorraad == '1') {
        connect(this.orderButtonSummary, 'onclick', this, this.orderProduct);
      } 
      return this.summaryView;
    },
    showMoreInfo: function(e) {
      if (e.target().className != 'summaryorder') {
        if ($('specialscontent')) {
          swapDOM($('specialscontent'), this.view);                     
        } else {
          swapDOM($('maincontent'), this.view);           
        }
        window.scrollTo(0,0);
      }
    },
    orderProduct: function(e) {
      line = this;
      myShoppingBasket.orderProduct(line);
    },
    renderView: function() {
      this.orderButtonView = DIV({'class':'vieworder'},wwx.neemTekst('PO_ORDER'));
      this.backToSummaryButton = DIV({'class':'summarybutton'},wwx.neemTekst('PO_BACK_OV'));
      productcontent = DIV(null,null);   
      productcontent.innerHTML = (typeof(this.data.descr)=="string") ? this.data.descr : this.data.descr.join('\n');
      this.viewid = ($('specialscontent')) ? 'specialscontent' : 'maincontent';
      this.view = DIV({'id':this.viewid},
        DIV({'class':'productview'},
          H1(null, this.data.title), productcontent
        ),
        DIV({'class':'productinfoview'},  
          DIV({'class':'overviewimage','style':'background:url('+this.data.imgurl+') no-repeat'},
          (this.data.nieuw_product=='1') ? IMG({'class':'salelabeloverview','src':'DesignerImages/label-new.png'}) : 
          (this.data.aanbieding=='1') ? IMG({'class':'salelabeloverview','src':'DesignerImages/label-save-money.png'}) : 
          (this.data.op_voorraad=='0') ? IMG({'class':'salelabeloverview','src':'DesignerImages/label-sold-out.png'}) : null
          ), 
          UL({'class':'productinfo'},
            LI({'class':'title'}, wwx.neemTekst('Inhoud:')),
            LI(null, this.data.inhoud)
          ),
          UL({'class':'productinfo'},
            LI({'class':'title'}, wwx.neemTekst('Prijs:')),
            (this.data.aanbieding=='1') ? 
            LI(null,
              DIV({'class':'doorgestreept'},wwx.eurosign+' '+this.formatNumber(this.baseprice)+' '),
              DIV({'class':'aanbiedingsprijs'},wwx.eurosign+' '+this.formatNumber(this.price))) :
            LI(null,wwx.eurosign+' '+this.formatNumber(this.price))
          ),
          this.orderButtonView, this.backToSummaryButton
        )
      );
      connect(this.backToSummaryButton, 'onclick', this, this.showSummary);
      if (this.data.op_voorraad=='1') {
        connect(this.orderButtonView, 'onclick', this, this.orderProduct);
      } 
    },
    showSummary: function(e) {
      swapDOM($(this.viewid), this.overview.view);
    }
  }.init();
};

// ------------------------------------------------ ShoppingBasket ---------------------------------------------------------------
wwx.widgets.ShoppingBasket = function() {
  return {
    id: "wwx.widgets.ShoppingBasket",
    description: 'ShoppingBasket class voor Webworxx Store (singleton)',
    sessionrecord: 'shoppingbasket',
    data: [],
    lines: {},
    basketopen: false,
    orid: null,
    totalamt: 0,
    totalart: 0,
    customer: null,
    
    init: function() {
      bindMethods(this);
      if (wwx.voorkeurstaal!='en') {
        this.formatNumber = numberFormatter("#,##0.00","","de_DE");
      } else {
        this.formatNumber = numberFormatter("#,##0.00","","en_US");
      }
      jQuery('body').append('<form style="display:none" id="basketform" name="basketform"><input type="hidden" name="shoppingbasket" id="shoppingbasket" /></form>')
      this.loadBasket();
            
      jQuery('#basketlist').click(function(e) {
        // toggle visibility of basket
        if (myShoppingBasket.basketopen) {
          myShoppingBasket.hide();
        } else {
          myShoppingBasket.show();
        }
        myShoppingBasket.updateBasket();
        if (myShoppingBasket.basketopen) {
          myShoppingBasket.show();
        } else {
          myShoppingBasket.hide();
        }
      });
      jQuery('#basketpay').click(this.checkout);
      return this;
    },
    orderProduct: function(line) {
      // line comes as an argument from the signal
      if (line.data.title == "VERZENDKOSTEN") {
        if (wwx.voorkeurstaal == 'en') {
          line.data.title = 'SHIPMENT COSTS';
        }
        if (wwx.voorkeurstaal == 'de') {
          line.data.title = 'VERSANDKOSTEN';
        }
      }

      if (typeof this.lines[line.data.id] == "undefined" ) {
        this.lines[line.data.id] = new wwx.widgets.ShoppingBasketItem(line.data, 1);
        appendChildNodes($('basketcontent'), this.lines[line.data.id].line);
        Highlight(this.lines[line.data.id].line, {'startcolor':'#e5e5e5','duration': 2.0});
        if (!document.all) {
          this.lines[line.data.id].orderedinput.focus();
          this.lines[line.data.id].orderedinput.select();
        }
        if (line.overview) {
          if (line.overview.id == 'wwx.born.SpecialsOverview') {
            costs = new wwx.born.Costs(function() {});
          }
        }
        this.updateTotals();
      } else {
        if (line.data.c_cat != 'CAT-SEND') {
          alert(wwx.neemTekst('BA_ARTICL_SEL'));
        }
      }
      if (!this.basketopen) {
        this.show();
      }
    },
    getOrderedProduct: function(product_id) {
      selpr = this.lines[product_id];
      return selpr;
    },
    freeze: function () {
      forEach(map(this.addToProductList, items(this.lines)), 
        function(ob) {
          ob.freeze();
        }
      );
    },
    reset: function() {
      forEach(map(this.addToProductList, items(this.lines)), 
        function(ob) {
          ob.reset();
        }
      );        
    },
    redraw: function() {
      // redraw each line
      forEach(map(this.addToProductList, items(this.lines)), 
        function(ob) {
          ob.redraw();
        }
      );
      this.updateTotals();
    },
    refresh: function() {
      // Make list of lines object
      newLines = {};
      forEach(map(this.addToProductList, items(this.lines)), 
        function(ob) {
          if (ob.ordered !== 0) {
            newLines[ob.data.id] = ob;
          }
        }
      );
      this.lines = newLines;
      this.updateTotals();
    },
    addToProductList: function(ob) {
      return ob[1];
    },
    addToProductData: function(ob) {
      ro = {'id':ob[1].data.id, 'ordered':ob[1].ordered, 'data':ob[1].data};
      return ro;
    },
    updateTotals:function() {
      this.totalamt = 0;
      this.totalart = 0;
      context = this;
      var verzend = 0;
      plist = map(this.addToProductList, items(this.lines));
      for (x=0; x<plist.length;x++) {
        ob = plist[x];
        if (ob.data.c_cat == 'CAT-SEND') {
          switch  (prices_to_select) {           
            case 'OVERIG':
              verzend = ob.data.prijs_overig;
              break;
            case 'NL_BE':
            default: 
              verzend = ob.data.prijs_NL_BE;
              break;
            }
        }
        this.totalart += ob.ordered;
        this.totalamt += ob.total;
      }
      var product_totaal = this.totalamt - verzend;
      if (product_totaal > 0 && product_totaal < 75) {
        jQuery('#basketmessage').html(wwx.neemTekst('BA_ART_REST')+' € '+this.formatNumber(75 - product_totaal)+' '+wwx.neemTekst('BA_ART_REST2'));
      } else {
        jQuery('#basketmessage').html('');
      }
      jQuery('#baskettotaltxt')
        .replaceWith('<div id="baskettotaltxt">'
          +this.totalart+' '+wwx.neemTekst('BA_ART_TOTPRC')+' '+wwx.eurosign+' '+this.formatNumber(this.totalamt)+'</div>');
      this.updateBasket();
    },
    totalsSplitByVat: function() {
      this.totalamt = 0.00;
      this.totalamtLaag = 0.00;
      this.totalamtHoog = 0.00;
      myLines = items(this.lines);
      for (line=0;line < myLines.length; line++) {
        ob = myLines[line][1];
        this.totalamt += ob.total;
        if (ob.btw_hoog == "1") {
          this.totalamtHoog += ob.total;
        } else {
          this.totalamtLaag += ob.total;          
        }
      }
      return {'totalamt':this.totalamt, 'totalLaag':this.totalamtLaag, 'totalHoog': this.totalamtHoog};
    },
    loadBasket: function() {
      d = loadJSONDoc('load_shoppingbasket',{'rn':ie_random()});
      d.addCallbacks(this.loadBasketReady, function() {});
    },
    loadBasketReady: function(data) {
      if (data != []) {
        for (a=0;a<data.products.length;a++) {
          if (typeof(this.lines[data.products[a].id]) == "undefined" ) {       
            if ((data.products[a].data.c_art != 'VERZ') && (data.products[a].data.c_cat != 'CAT-DISCOUNT')) {
              this.lines[data.products[a].id] = new wwx.widgets.ShoppingBasketItem(data.products[a].data, data.products[a].ordered);
              appendChildNodes($('basketcontent'), this.lines[data.products[a].id].line);
            }
          }
        }
        if (data.basketopen) {
          this.show();
        } else {
          this.hide();
        }
        this.updateTotals();
      }
      return;
    },
    getBasketData: function() {
      dlist = map(this.addToProductData, items(this.lines));
      return dlist;    
    },
    updateBasket: function() { 
      dlist = map(this.addToProductData, items(this.lines));
      $('shoppingbasket').value = serializeJSON({'basketopen':this.basketopen, 'products':dlist});
      var req=getXMLHttpRequest();
      req.open("POST", 'update_json_shoppingbasket', true);
      req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      var data=queryString($('basketform'));
      var d = sendXMLHttpRequest(req, data);
      res = d.addCallbacks(this.updateBasketReady,this.updateBasketFailed);                 
    },
    updateBasketReady: function(data) {
      if (/payment_accepted/.test(location.href)) {
        this.reset();
      }
      return;
    }, 
    updateBasketFailed: function(err) {
      /*log('Shoppingbasket.updateBasketFailed: '+err.message);*/
    },
    toggleVisibility: function(e) {
      if (this.basketopen) {
        this.hide();
      } else {
        this.show();
      }
      this.updateBasket();
      if (myShoppingBasket.basketopen) {
        myShoppingBasket.show();
      } else {
        myShoppingBasket.hide();
      }
    },    
    show: function() {
      jQuery('#basketcontent').show().removeClass('closed').addClass('opened');
      this.basketopen=true;
    },
    hide: function() {
      jQuery('#basketcontent').hide().removeClass('opened').addClass('closed');
      this.basketopen=false;
    },     
    checkout: function() {
      this.hide();
      this.co = new Checkout($('maincontent'));
    }
  }.init();
};

// ------------------------------------------------ ShoppingBasketItem -------------------------------------------------------
wwx.widgets.ShoppingBasketItem = function(data, ordered) {
  return {
    // Public
    id: "wwx.widgets.ShoppingBasketItem",
    description: 'ShoppingBasketItem class voor Webworxx Store',
    data:  data,
    ordered:  ordered,
    line:  null,
    price:  0.00,
    saleprice:  0.00,
    btw_hoog: "0",
    op_voorraad: "1",
    
    init: function() {
      bindMethods(this);
      if (wwx.voorkeurstaal!='en')
        this.formatNumber = numberFormatter("#,##0.00","","de_DE");
      else
        this.formatNumber = numberFormatter("#,##0.00","","en_US");

      switch  (prices_to_select) {           
        case 'OVERIG':
          this.price = this.data.prijs_overig;
          this.saleprice = this.data.aanbieding_prijs_overig;          
          break;
        case 'NL_BE':
        default: 
          this.price = this.data.prijs_NL_BE;
          this.saleprice = this.data.aanbieding_prijs_NL_BE;          
          break;
      }        
      this.btw_hoog = this.data.btw_hoog;
      this.op_voorraad = this.data.op_voorraad;
      if (this.data.aanbieding == '1') {
        this.price = this.saleprice;
      }
      this.data.actualprice = this.price;
      this.render();

      return this;
    },
    render: function() {
      this.orderedinput = INPUT({'type':'text','style':'width:20px;text-align:right;border-color:#d50018;padding:0 1px;font-weight:bold', 'value':this.ordered});
      this.columnicon = LI({'class':'column_icon'})
      this.calculateTotal();
      connect(this.orderedinput,'onblur', this.updateOrdered);
      connect(this.columnicon,'onclick', this.remove);
      this.line = UL({'class':'basketline'},
      this.columnicon,
      LI({'class':'column_art'},this.data.title),
      LI({'class':'column_price'},this.formatNumber(this.price)),
      LI({'class':'column_nr'},this.orderedinput),
      this.column_total
      );
    },
    freeze: function () {
      this.orderedinput.setAttribute('disabled','true') 
      disconnectAll(this.columnicon);
      setOpacity(this.columnicon, 0,3);
      hideElement($('basketpay'));
    },
    reset: function() {
      this.remove();
    },
    calculateTotal: function() {
      this.total = this.ordered * this.price;
      this.column_total = LI({'class':'column_tot'},this.formatNumber(this.total));
    },
    updateOrdered: function() {
      this.ordered = parseInt(this.orderedinput.value);
      this.redraw();
    },
    redraw: function() {
      oldline = this.line;
      // disconnect events
      this.removeEvents();
      this.render();
      swapDOM(oldline, this.line);
      //signal(window,'basketItemChanged');
      myShoppingBasket.updateTotals();
    },
    remove: function() {
      // Signal that this line has to be removed, needs to be picked up by the shoppingbasket
      this.ordered = 0;
      this.total = 0;
      this.column_total = LI({'class':'column_tot'},this.formatNumber(this.total));
      this.removeEvents();
      productID = this.data.id;
      removeElement(this.line);
      //signal(window, 'basketItemRemoved', productID);
      myShoppingBasket.refresh();
    },
    removeEvents: function() {
      disconnectAll(this.orderedinput);
      disconnectAll(this.columnicon);    
    }    
  }.init();
};


/* Costs.js */

wwx.born.Costs = function(callback) {
  return {
    costs: null,
    url:'shop-products.htm/fetch_costs',
    init:function() {
      this.fetchCosts();
      return this;
    },
    fetchCosts: function() {
      d = loadJSONDoc(this.url,{'rn':ie_random()});
      d.addCallbacks(this.fetchCostsReady, function() {});
    },                                               
    fetchCostsReady: function(data) {  
      this.costs = new wwx.born.Product(data.verzendkosten, null);
      /* Remove old costs record */
      try {
        myShoppingBasket.getOrderedProduct(this.costs.data.id).remove();
      } catch (e) {}
      this.costs.orderProduct();     

      if (parseFloat(data.data.drempel) <= parseFloat(myShoppingBasket.totalamt)-this.costs.price) {
        line = myShoppingBasket.getOrderedProduct(data.data.product_id);
        line.orderedinput.value = '0';
        line.saleprice = 0.00;  
        line.price = line.saleprice;
        line.total = line.saleprice;
        line.data.prijs_NL_BE = line.saleprice;
        line.data.prijs_overig = line.saleprice;   
        line.data.actualprice = line.saleprice;
      }
      myShoppingBasket.redraw();
      myShoppingBasket.refresh();
      myShoppingBasket.freeze();
      callback();
      return;
    }
  }.init();
};

var discountCodeUsed = false;
wwx.born.DiscountCode = function(field) {
  return {
    url:  'shop-products.htm/fetch_discounts',
    actionField: field,
    discount: null,
    btwLaag: 6,
    btwHoog: 19,
    kortingBTWLaag: 0.00,
    kortingBTWHoog: 0.00,
    
    init:function() {   
      bindMethods(this);
      this.actionField.afterFieldValidated = bind(function() {
        // Find the discount code   
        if (this.actionField.value!=='') {        
          this.fetchDiscount();
        }
      },this);
      return this;
    },
    fetchDiscount: function() {                  
      this.actionField.syncValue();
      d = loadJSONDoc(this.url,{'code':this.actionField.value,'rn':ie_random()});
      d.addCallbacks(this.fetchDiscountReady, this.fetchDiscountFailed);
    },                                               
    fetchDiscountReady: function(data) {  
      if (data.success) {
        // recalculate costs
        costs = myShoppingBasket.getOrderedProduct('PRD-16937');
        costs.remove();
        
        amounts = myShoppingBasket.totalsSplitByVat();

        forEach(data.discount, function(ob) {
          ndiscount = new wwx.born.Product(ob.discount, null);
          ndiscount.orderProduct();
          line = myShoppingBasket.getOrderedProduct(ob.data.product_id);
          line.orderedinput.value = '-1';
          
          var bedrag = 0.00;
          if (ob.data.btw_hoog == '1') {
            bedrag = amounts.totalHoog;
          } else {
            bedrag = amounts.totalLaag;            
          }
          korting = numberFormatter("0.00","","en_US")(bedrag*(parseFloat(ob.data.discount)/100));
          line.saleprice = -1 * parseFloat(korting);  
          line.price = line.saleprice;
          line.total = -1 * line.price;    
          line.data.prijs_NL_BE = line.saleprice;
          line.data.prijs_overig = line.saleprice;   
          line.data.actualprice = line.saleprice;
          myShoppingBasket.redraw();
          myShoppingBasket.refresh();
          myShoppingBasket.freeze();
        });
        
        field.setNotEditable();
        discountCodeUsed = true;
        
        costs = new wwx.born.Costs(
          function() {
            myShoppingBasket.redraw();
            myShoppingBasket.refresh();
            myShoppingBasket.freeze();
          }
        );
      } else {
        alert('Ongeldige kortingscode');
      }      
      return;
    },
    getTotalDiscount: function() {
      
    },
    getVatFromAmount: function(amt, vat) {
      return (amt/(float(amt)+vat))/100;
    },
    calculateDiscount: function() {
      
    },
    fetchDiscountFailed: function(err) {
      /*log(err);*/
    }
  }.init();
};

function send_callback() {
  myShoppingBasket.reset();
}
