var req;
var fld;
var inst = WO.setup.inst;
var script_frontend = WO.script.frontend;
var salesoffice = WO.shopinfo.SALESOFFICE;


function loadXMLDoc(url) 
{
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}

function processReqChange() 
{
    // only if req shows "complete"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
         response  = req.responseXML.documentElement;
         method    = response.getElementsByTagName('method')[0].firstChild.data;
         result    = response.getElementsByTagName('result')[0].firstChild.data;
         eval(method + '(\'\', result)');
        } else {
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
    }
}

function hkasse_lookup() {  
  var pid = document.getElementById("hkasse_productnu");
  if(pid) {
    var pnu = pid.value; 
    var txt = document.getElementById("hkasse_txt");
    if(pnu == '') {
      if(txt) {
        txt.innerHTML = '';
      }
    }
    else {
      var url = "/wsp/"+inst+"/ajax.cgi?func=catalog.hkasse_lookup&debug=off&JSON=&productnu="+pnu;
      jQuery.get(url,
        function(data){
          if(txt) {
            txt.innerHTML = data;
          }
        }
      );
    }
  }
}
/*
function city_lookup() {  
  var zipcode = document.getElementById("ORDERS.D_ZIPCODE");
  var city = document.getElementById("ORDERS_D_CITY");
  var city_input = document.getElementById("city_input");
  if(zipcode && city && city_input) {
    var code = zipcode.value; 
    if(code != '') {
      var url = "/wsp/"+inst+"/ajax.cgi?func=order.zipcode&debug=off&JSON=&o_zipcode="+code;
      jQuery.get(url,
        function(data){
          city.innerHTML = data;
          city_input.value = data; 
        }
      );
    }
  }
}
*/
function city_lookup(){
  var z = $('o_zipcode') || $('ORDERS.D_ZIPCODE');
  var c = $('o_city') || $('ORDERS.D_CITY');
  if(!z || !c){ return false; }
  var form = z.up('form', 0) || c.up('form',0);
  var cls = 'no-ajax-lookup';
  var isAjaxLookup = !z.hasClassName(cls);
  if(z.value.strip().length >= 4 && form && isAjaxLookup ){
   var errCls = 'invalid';
   z.removeClassName(errCls);
   if($('zipcode-error-message')){ $('zipcode-error-message').remove(); }
   if(isNaN(z.value.strip())){
     z.addClassName(errCls);
     showErrorMsg(WO.freetext('zipcode_error'),{targetElement: form, errorID:'zipcode-error-message'});
   }
    var url = '/wsp/' + inst + '/ajax.cgi?func=order.zipcode&debug=off&JSON=';
    new Ajax.Request(url, {
       method: 'get',
       parameters: { o_zipcode: z.value.strip(), debug:'off' },
       onLoading: function(){
         c.value = WO.freetext('city_lookup');
       },
       onSuccess: function(r){
         try {
           var v = r.responseText.strip();
           if(!v.blank()){ $(c).removeClassName('invalid'); }
           c.value = v;
         }catch(e){
           alert('City look up error: ' + e.description);
         }
       }
    });
  }
}
function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function identifyCustomer(ziplength) {
  var fname = document.getElementById('USER.FIRSTNAME').value;
  var lname = document.getElementById('USER.LASTNAME').value;
  var address = document.getElementById('USER.ADDRESS').value;
  var zip = document.getElementById('USER.ZIPCODE').value;
//  var email = document.getElementById('USER.EMAIL').value;
//  var phone = document.getElementById('USER.TELEPHONE').value;
  var tid = document.getElementById('USER.TUSSILAGO_ID').value;
  var coaddress="";
  var telephone="";
  var telephone_night="";
  var mobilephone="";
  var email="";

  if (fname.length <= 0 || lname.length <= 0 || address.length <= 0 || zip.length != ziplength) {
    return;
  }
  if (tid == 0) {
    var url = "/wsp/" + inst + "/ajax.cgi?func=tussilago.tojson&debug=off&JSON=1&opt=identcust";
    url += "&firstName=" + encodeURIComponent(fname);
    url += "&lastName=" + encodeURIComponent(lname);
    url += "&address=" + encodeURIComponent(address);
    url += "&postalCode=" + encodeURIComponent(zip);
//    url += "&email=" + encodeURIComponent(email);
//    url += "&telephone=" + encodeURIComponent(phone);

    $j.getJSON(url,
      function(data){
        if (data.status == 1) {
           // stupid IE shows "null" in fields if data.result.x is null after tussilago call.
           if (data.result.address1 != null) coaddress=data.result.address1;
           if (data.result.telephoneDay != null) telephone=data.result.telephoneDay;
           if (data.result.telephoneEvening != null) telephone_night=data.result.telephoneEvening;
           if (data.result.mobileTelephone != null) mobilephone=data.result.mobileTelephone;
           if (data.result.email != null) email=data.result.email;
           document.getElementById('USER.ADDRESS2').value = coaddress;
           document.getElementById('USER.ADDRESS').value = data.result.address2;
           document.getElementById('USER.ZIPCODE').value = data.result.postalCode;
           document.getElementById('USER.CITY').value = data.result.postOffice;
           document.getElementById('USER.TELEPHONE').value = telephone;
           document.getElementById('USER.TELEPHONE_NIGHT').value = telephone_night;
           document.getElementById('USER.MOBILEPHONE').value = mobilephone;
           document.getElementById('USER.EMAIL').value = email;
           document.getElementById('USER.TUSSILAGO_ID').value = data.result.customerId;
        } else if (data.status > 1) { 
           // Contact customer service
	   var url = script_frontend + 'func=frontend.show&template=modal_contact_cs&tussstatuscode='+data.status+'&tusserrorcode='+data.errorCode;
	   var data = null;
	   var method = 'GET';
   	   myPageReq(data, url, method);
        }
      }
    );
  }
}

function zipLookup(ziplength) {
  var zipval = document.getElementById('USER.ZIPCODE').value;
  if (zipval.length == ziplength) {
    var url = "/wsp/" + inst + "/ajax.cgi?func=tussilago.tojson&JSON=1&debug=off&opt=zip";
    url += "&postalCode=" + zipval;
    $j.getJSON(url,
      function(data){
        if (data.status) {
          document.getElementById('USER.CITY').value = data.result;
        } else {
          document.getElementById('USER.CITY').value = '';
        }
      }
    );
  } else {
    document.getElementById('USER.CITY').value = '';
  }
}

var aj_userid = undefined;

function login_userid() {  
  var usernameinput = document.getElementById("username");
  var passwordinput = document.getElementById("password");
  if(usernameinput && passwordinput) {
    var usernameval = usernameinput.value; 
    var passwordval = passwordinput.value; 
    var url = "/wsp/" + inst + "/ajax.cgi?func=user.login&debug=off&logincode=" + WO.session.logincode + "&login_ext=yes&output=json&username=" + encodeURIComponent(usernameval) + "&password=" + encodeURIComponent(passwordval);
    $j.getJSON(url,
      function(data){
        alert("data.userobj.USER_ID: " + data.userobj.USER_ID);
        aj_userid = data.userobj.USER_ID;
      }
    );
    return aj_userid;
  } else {
    return undefined;
  }
}
