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; 
        }
      );
    }
  }
}
*/
var zipLooking = null;
function city_lookup(zipLength) {
    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 ( zipLength  && ( z.value.strip().length >= zipLength ) && 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'
            });
            return false;
        } /*var url = '/wsp/' + inst + '/ajax.cgi?func=order.zipcode&debug=off&JSON=';*/
        var url = "/wsp/" + inst + "/ajax.cgi?func=tussilago.tojson&JSON=1&opt=zip";

        try {
           zipLooking.transport.abort();
        }catch(e){};
        zipLooking = new Ajax.Request(url, {
            method: 'get',
            parameters: {
                postalCode: z.value.strip(),
                debug: 'off'
            },
            onLoading: function () { /*c.value = WO.freetext('city_lookup');*/
                showErrorMsg(WO.freetext('looking_up_zipcode'), {
                    targetElement: form,
                    errorID: 'zipcode-error-message'
                });
            },
            onSuccess: function (r) {
                try {
                    var j = eval('(' + r.responseText + ')');
                    if (j.status == 1) {
                        var v = j.result.strip();
                        if (!v.blank()) {
                            $(c).removeClassName('invalid');
                        }
                        c.value = v;
                        if ($('zipcode-error-message')) {
                            $('zipcode-error-message').remove();
                        }
                    }
                    else { /* timed out */
                        showErrorMsg(WO.freetext(j.errorCode.strip()), {
                            targetElement: form,
                            errorID: 'zipcode-error-message'
                        });
                    }
                } catch (e) {
                    c.value = "";
                    showErrorMsg(WO.freetext('zipcode_not_found'), {
                        targetElement: form,
                        errorID: 'zipcode-error-message'
                    });
                    // alert('City look up error: ' + e.description);
                }
            }
        });
    }
}

function decidas_person_lookup() {
    var address = $('o_street') || $('ORDERS.D_ADDRESS');
    var zipcode = $('o_zipcode') || $('ORDERS.D_ZIPCODE');
    var firstname = $('o_fname') || $('ORDERS.D_FNAME');
    var lastname = $('o_lname') || $('ORDERS.D_LNAME');
    var ssnumber = $('ORDERS.USER_SSN_ID');
    var custid = $('ORDERS.CUSTID');

    /* console.log('Firstname: ' + firstname.value + ' Lastname: ' + lastname.value + ' Address: ' + address.value + ' Zipcode: ' + zipcode.value); */
 
    if (custid.value > 0) {
       /* console.info('custid is set - ' + custid.value + ' - person found by tussilago - exiting'); */
       return false;
    }
    
    if (!address || !zipcode || !firstname || !lastname) {
        return false;
    }

    var form = address.up('form', 0);
    var cls = 'no-ajax-lookup';
    var isAjaxLookup = !address.hasClassName(cls);

    if ( ( address.value.strip().length > 0  ) && form && isAjaxLookup ) {
        var errCls = 'invalid';
        address.removeClassName(errCls);
        if ($('zipcode-error-message')) {
            $('zipcode-error-message').remove();
        }

        var url = "/wsp/" + inst + "/ajax.cgi?func=ws.tojson&JSON=1&opt=decidaspersonsearch";

        try {
           addressLooking.transport.abort();
        }
        catch(e){};

        addressLooking = new Ajax.Request(url, {
            method: 'get',
            parameters: {
                address: address.value.strip(),
                zip: zipcode.value.strip(),
                name: firstname.value.strip() + ' ' + lastname.value.strip(),
                
                debug: 'off'
            },
            onLoading: function () { 
                showErrorMsg(WO.freetext('decidas_looking_up_address'), {
                    targetElement: form,
                    errorID: 'zipcode-error-message'
                });
            },
            onSuccess: function (r) {
                try {
                    var j = eval('(' + r.responseText + ')');
                    /* console.dir(j); */
                    if (j.PersonIdentified == 'true') {
                        /* console.info("Person found"); */
                        var adr = j.AddressStreet.strip();
                        var fname = j.FirstName.strip();
                        var lname = j.LastName.strip();
                        var pnr = j.PersonNr.strip();
                        if (!adr.blank()) {
                            $(address).removeClassName('invalid');
                        }
                        address.value = adr;
                        /* WOSUP00000-365 2.may 2011 - SHGSVE wants the original typed name to be stored - commented out assigning value from WS*/
                        /* firstname.value = fname; */
                        /* lastname.value = lname; */
                        ssnumber.value = pnr;

                        if ($('zipcode-error-message')) {
                            $('zipcode-error-message').remove();
                        }
                    }
                    else { /* timed out */
                        showErrorMsg(WO.freetext(decidas_person_not_found), {
                            targetElement: form,
                            errorID: 'zipcode-error-message'
                        });
                    }
                } catch (e) {
                    showErrorMsg(WO.freetext('decidas_person_not_found'), {
                        targetElement: form,
                        errorID: 'zipcode-error-message'
                    });
                    address.value = '';
                    /* console.info('Decidas person lookup 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;
    }
}
