// (c) 2004-2007 Copyright Nedstat BV Netherlands.
// ALL RIGHTS RESERVED
window.onerror = function(){
    return true;
};
if (typeof ns_API == "undefined") 
    var ns_API = {
        loadEvents: [],
        reservedLabels: new RegExp(/^\s*(ns\_.*|agent|availscreen|colordepth|cookie|corporate|day|full\_loading\_time|html\_loading\_time|httpreferer|innersize|ip|java|lang|mimetypes|name|newcookie|offset|or|outersize|p|pie|plugins|referrer|screen|site|\_t|time|type|url|ver)\s*$/i),
        regCounter: new RegExp(/(?:https?):\/\/([^\/]+)\/([^\/]+)\/([^\/]+)\/s\?([\w_\-\.\[\]\(\)\$\~\{\}\*\^\,]{1,200})/)
    };
if (typeof ns_API.addEvent == "undefined") 
    ns_API.addEvent = (document.addEventListener) ? (function(element, type, handler){
        element.addEventListener(type, handler, false)
    }) : (document.attachEvent) ? (function(element, type, handler){
        element.attachEvent("on" + type, handler)
    }) : new Function;
if (typeof ns_API.isIE == "undefined") 
    ns_API.isIE =/*@cc_on!@*/ false;
;
if (typeof ns_API.isIE7 == "undefined") 
    ns_API.isIE7 = (ns_API.isIE && /MSIE\s*([7-9]|[1-9];\d+)/i.test(navigator.userAgent)) ? true : false;
if (typeof ns_API.getJSPageURL == "undefined") 
    ns_API.getJSPageURL = function(){
        return (document.URL) ? document.URL : document.location.domain + document.location.pathname + document.location.search
    };
if (typeof ns_API.onDocumentReady == "undefined") 
    ns_API.onDocumentReady = function(func){
        try {
            if (/webkit/i.test(navigator.userAgent)) {
                var _timer = setInterval(function(){
                    if (/loaded|complete/.test(document.readyState)) {
                        clearInterval(_timer);
                        func();
                    }
                }, 10);
            }
            else 
                if (ns_API.isIE) {
                    var id = "__ie_onload_" + new Date().getTime();
                    document.write("<script id=" + id + " defer src=javascript:void(0)><\/script>");
                    var script = document.getElementById(id);
                    script.onreadystatechange = function(){
                        if (/complete/i.test(this.readyState)) {
                            func();
                            this.parentNode.removeChild(this);
                        }
                    }
                }
                else 
                    if (document.addEventListener) {
                        document.addEventListener("DOMContentLoaded", func, false);
                    }
                    else {
                        ns_API.addEvent(window, "load", func);
                    }
        } 
        catch (e) {
            ns_API.addEvent(window, "load", func);
        }
    };
if (typeof ns_API.addLoadEvent == "undefined") {
    ns_API.addLoadEvent = function(func){
        ns_API.loadEvents.push(func);
    };
    ns_API.onDocumentReady(function(){
        for (var i = 0, loadEvent; (loadEvent = ns_API.loadEvents[i]); i++) 
            if (loadEvent instanceof Function) 
                loadEvent()
    });
}
if (typeof ns_API.constructLabel == "undefined") 
    ns_API.constructLabel = function(label){
        return label.replace(/[^\-_\.a-zA-Z0-9]/g, "___");
    };
if (typeof ns_API.startTime == "undefined") 
    ns_API.startTime = (typeof ns_loadingtime1 != "undefined" && !isNaN(parseInt(ns_loadingtime1))) ? ns_loadingtime1 : ns_API.addLoadEvent(function(){
        ns_API.startTime = new Date().getTime()
    });
if (typeof ns_API.log == "undefined") {
    ns_API.log = function(url, timeout, callBack){
        var key = ++ns_API.log.totalLogs + ":" + new Date().getTime();
        var image = new Image();
        var handler = function(){
            if (ns_API.log.timerItems[key]) {
                window.clearTimeout(ns_API.log.timerItems[key]);
                delete ns_API.log.timerItems[key];
            }
            if (callBack && callBack instanceof Function) {
                callBack();
            }
            delete ns_API.log.logImages[key];
            image.onload = image.onerror = image.onabort = new Function;
        };
        image.onload = image.onabort = image.onerror = handler;
        ns_API.log.timerItems[key] = window.setTimeout(handler, timeout);
        image.src = url;
    };
    ns_API.log.logImages = {};
    ns_API.log.timerItems = {};
    ns_API.log.totalLogs = 0;
}
ns_API.forms = {
    DEBUG: false,
    isProtoTyped: false,
    NORMALPREFIX: "ns_f_",
    HIDDENPREFIX: "ns_h_",
    PASSWORDPREFIX: "ns_h_",
    RESERVEDPREFIX: "ns_fo_",
    instances: [],
    isRegistered: function(instance){
        var registered = false;
        for (var i = 0, _instance; !registered && (_form = this.instances[i]); i++) 
            if (instance == _instance) 
                registered = true;
        if (!registered) 
            this.instances.push(instance);
        return registered;
    },
    getInstanceByForm: function(form){
        for (var i = 0, instance; (instance = this.instances[i]); i++) 
            if (instance.form == form) 
                return instance;
    },
    dispatchValidationError: function(form, fields, message, normal, hidden, passwords){
        var instance = this.getInstanceByForm(form);
        if (instance instanceof ns_API.form) 
            instance.onError.apply(instance, Array.prototype.slice.call(arguments, 1));
    }
};
ns_API.forms.exception = function(){
    this.totalErrors = 0;
    this.errorField = null;
    this.msg = "";
    this.overview = {}
};
ns_API.forms.exception.prototype.append = function(fields, message){
    var arr = fields.split(";");
    if (arr.length < 0) 
        return;
    this.errorField = arr[arr.length - 1];
    this.msg = message;
    for (var i = 0, fields; (field = arr[i]); i++) {
        field = (i + 1) + "_" + field.toLowerCase();
        if (this.overview[field]) 
            this.overview[field]++;
        else 
            this.overview[field] = 1;
    }
    this.totalErrors++;
};
ns_API.forms.exception.prototype.getOverview = function(){
    var arr = [];
    for (var field in this.overview) 
        arr.push(field + ":" + this.overview[field]);
    return arr;
};
ns_API.forms.exception.prototype.getLastErrorField = function(){
    return this.errorField;
};
ns_API.forms.exception.prototype.getTotalErrors = function(){
    return this.totalErrors;
};
ns_API.forms.exception.prototype.getLabels = function(type){
    var arr = [];
    if (this.getOverview().join("|") != "") 
        arr.push(ns_API.forms.RESERVEDPREFIX + "vfo=" + this.getOverview().join("|"));
    if (this.errorField) 
        arr.push(ns_API.forms.RESERVEDPREFIX + "vfl=" + this.errorField.toLowerCase());
    if (this.totalErrors > 0) 
        arr.push(ns_API.forms.RESERVEDPREFIX + "vf=" + this.totalErrors);
    arr.push(ns_API.forms.RESERVEDPREFIX + "vfe=" + escape(this.msg.substring(0, 255)));
    return arr;
};
ns_API.form = function(formName){
    this.MAXFIELDSIZE = 255;
    this.version = "1.0.0";
    this.formName = formName;
    this.form = null;
    this.url = null;
    this.sequence = 1;
    this.id = null;
    this.isFormAbandoned = false;
    this.isFormActive = false;
    this.isFormSubmitted = false;
    this.hasValidationError = false;
    this.error = new ns_API.forms.exception();
    this.lastField = null;
    this.startTime = null;
    this.fields = {
        SUBMIT: {
            NORMAL: "",
            HIDDEN: "",
            PASSWORD: ""
        },
        SUBMITABANDON: {
            NORMAL: "",
            HIDDEN: "",
            PASSWORD: ""
        },
        SUBMITVALFAIL: {
            NORMAL: "",
            HIDDEN: "",
            PASSWORD: ""
        }
    };
    this.init();
};
ns_API.form.prototype.init = function(){
    var scope = this;
    try {
        if (!this.formName) 
            throw "Please secify the name of the form to be measured";
        if (document.forms[this.formName]) 
            this.form = document.forms[this.formName];
        else 
            if (document.getElementById(this.formName) && /^form$/i.test(document.getElementById(this.formName).tagName)) 
                this.form = document.getElementById(this.formName);
            else 
                throw "Form not found on page [" + this.formName + "]";
        if (ns_API.forms.isRegistered(this)) 
            throw "Form already registered by ns_API";
        this.id = escape(this.formName) + "_" + new Date().getTime();
        this.addEvents();
        if (typeof HTMLFormElement != "undefined" && !ns_API.forms.isProtoTyped) {
            ns_API.forms.isProtoTyped = true;
            HTMLFormElement.prototype.ns_submit = HTMLFormElement.prototype.submit;
            HTMLFormElement.prototype.submit = function(){
                var instance = ns_API.forms.getInstanceByForm(this);
                if (instance) {
                    instance.isFormSubmitted = true;
                    instance.onSubmit();
                }
                this.ns_submit();
            }
        }
        else 
            if (ns_API.isIE) {
                var func = this.form.submit;
                this.form.onsubmit = function(){
                    var instance = ns_API.forms.getInstanceByForm(this);
                    if (instance) {
                        instance.isFormSubmitted = true;
                        instance.onSubmit();
                    }
                    func();
                }
            }
        try {
            this.url = window.ns_pixelUrl.match(ns_API.regCounter)[0];
        } 
        catch (e) {
        }
    } 
    catch (e) {
        this.throwException(e)
    }
};
ns_API.form.prototype.paramToFieldList = function(param, hasWildCard){
    return (param) ? /\s*\*\s*/.test(param) ? (hasWildCard) ? "*" : null : param.replace(/\s*([^;\s]+)\s*(;?)/g, "$1$2") : null;
};
ns_API.form.prototype.log = function(event, labels){
    try {
        if (!ns_API.forms.DEBUG && !ns_API.regCounter.test(this.url)) 
            throw "Please specify a valid sitestat url";
        labels.push("ns_jspageurl=" + ns_API.getJSPageURL());
        var loaded = false, px = (ns_API.isIE) ? new Image() : document.body.appendChild(document.createElement("img"));
        window.ns_forms_timer = function(px, loaded){
            return function(){
                loaded = true;
                if (window.ns_forms_timer_id) 
                    window.clearTimeout(window.ns_forms_timer_id);
                px.onload = px.onerror = function(){
                    return;
                }
            }
        }
(px, loaded);
        window.ns_forms_timer_id = window.setTimeout('window.ns_forms_timer()', 5000);
        px.onload = px.onerror = window.ns_forms_timer;
        px.src = this.url + labels.join("&");
    } 
    catch (e) {
        this.throwException(e);
    }
};
ns_API.form.prototype.addSubmitEvent = function(normal, hidden, password){
	if (!this.form) 
        return;
    var scope = this;
    this.fields.SUBMIT.normal = this.paramToFieldList(normal, true);
    this.fields.SUBMIT.hidden = this.paramToFieldList(hidden, true);
    this.fields.SUBMIT.password = this.paramToFieldList(password, true);
    ns_API.addEvent(this.form, "submit", function(){
        scope.onSubmit.apply(scope, arguments)
    });
};
ns_API.form.prototype.addAbandonEvent = function(normal, hidden, password){
    if (!this.form) 
        return;
    var scope = this;
    this.fields.SUBMITABANDON.normal = this.paramToFieldList(normal);
    this.fields.SUBMITABANDON.hidden = this.paramToFieldList(hidden);
    this.fields.SUBMITABANDON.password = this.paramToFieldList(password);
    if (ns_API.isIE) {
        ns_API.addEvent(window, "beforeunload", function(){
            scope.onAbandon.apply(scope, arguments)
        });
    }
    else {
        ns_API.addEvent(window, "unload", function(){
            scope.onAbandon.apply(scope, arguments)
        });
    }
};
ns_API.form.prototype.onError = function(field, message, normal, hidden, password){
    this.error.append(field, message);
    this.fields.SUBMITVALFAIL.normal = this.paramToFieldList(normal, true);
    this.fields.SUBMITVALFAIL.hidden = this.paramToFieldList(hidden);
    this.fields.SUBMITVALFAIL.password = this.paramToFieldList(password);
    this.hasValidationError = true;
    this.log("submitvalfail", this.getFormLabels("submitvalfail"));
};
ns_API.form.prototype.onSubmit = function(event){
	if (!this.isFormActive || this.hasValidationError || this.isFormAbandoned) 
        return;
    this.isFormSubmitted = true;
    this.isFormActive = false;
    var scope = this;
    if (ns_API.isIE) 
        this.log("submit", this.getFormLabels("submit"));
    else 
        ns_API.addEvent(window, "unload", function(){
            scope.log.call(scope, "submit", scope.getFormLabels("submit"))
        });
    this.sequence++;
};
ns_API.form.prototype.onAbandon = function(){
    if (this.isFormSubmitted || !this.isFormActive || this.isFormAbandoned) 
        return;
    this.isFormAbandoned = true;
    this.log("submitabandon", this.getFormLabels("submitabandon"));
};
ns_API.form.prototype.getFormLabels = function(type, a_labels){
    if (!/^(submitabandon|submit|submitvalfail)$/i.test(type)) 
        return;
    type = type.toLowerCase();
    if (this.lastField && /option/i.test(this.lastField.tagName)) 
        this.lastField = this.lastField.parentNode;
    var labels = ["&type=hidden", "ns_fo_ev=" + type, ns_API.forms.RESERVEDPREFIX + "id=" + this.id, ns_API.forms.RESERVEDPREFIX + "la=" + escape((this.lastField && this.lastField.name) ? this.lastField.name.toLowerCase() : ""), ns_API.forms.RESERVEDPREFIX + "sq=" + this.sequence, ns_API.forms.RESERVEDPREFIX + "t0=" + ((typeof ns_API.startTime == "number") ? new Date().getTime() - ns_API.startTime : null), ns_API.forms.RESERVEDPREFIX + "t1=" + ((this.startTime) ? new Date().getTime() - this.startTime : null)].concat((a_labels && a_labels instanceof Array) ? a_labels : []).concat(this.error.getLabels(type));
    this.writeDebugStatement("<b>event</b>&nbsp;[<font color='green'>" + type + "</font>]");
    this.writeDebugStatement("<b>default labels:</b><br><font color='steelblue'>" + labels.join("<br>") + "</font>");
    var regExp = new RegExp(), fields = this.fields[type.toUpperCase()], radios = "";
    for (var i = 0, field, label, escapedFieldName, func; (field = this.form[i]); i++) {
        if (!field.name || !field.type) 
            continue;
        if (field.type == "radio" && radios.indexOf(field.name) > -1) 
            continue;
        func = this[field.type.replace(/\-/g, "_") + "Value"];
        escapedFieldName = field.name.replace(/([\$\[\]])/g, "\\$1");
        regExp.compile(escapedFieldName + ";?", "i");
        if ((field.type == "hidden" && (!!fields.hidden && (/^(submit|submitvalfail)$/i.test(type) && fields["hidden"] == '*') || regExp.test(fields["hidden"]))) || (field.type == "password" && (!!fields.password && (/^(submit|submitvalfail)$/i.test(type) && fields["hidden"] == '*') || regExp.test(fields["password"]))) || ((/^(submit|submitvalfail)$/i.test(type) && fields["normal"] == '*') || regExp.test(fields["normal"]))) {
            if (func instanceof Function) {
                label = func.call(this, field);
                this.writeDebugStatement("<font color='steelblue'>called getFormLabel:</font><b>" + field.name + "</b>:<i>" + field.type + "</i>&nbsp;(<font color='green'>" + label + "</font>)");
                if (label) 
                    labels.push(label);
                if (field.type == "radio") 
                    radios += field.name + ";";
            }
        }
    }
    return labels;
};
ns_API.form.prototype.throwException = function(e){
    if (ns_API.forms.DEBUG) 
        alert("Form API\n" + (e.message || e));
};
ns_API.form.prototype.addEvents = function(){
    var scope = this;
    ns_API.addEvent(this.form, "keyup", function(event){
        event = event || window.event;
        if (event.ctrlKey || event.altKey || event.shiftKey) 
            return;
        scope.onUserEvent.call(scope, event, event.srcElement || event.target)
    });
    ns_API.addEvent(this.form, "mouseup", function(event){
        event = event || window.event;
        scope.onUserEvent.call(scope, event, event.srcElement || event.target)
    });
};
ns_API.form.prototype.onUserEvent = function(event, element){
    if (!(element && element.form && element.form == this.form)) 
        return;
    if (element.type != "submit") 
        this.lastField = element;
    this.isFormSubmitted = false;
    this.hasValidationError = false;
    this.isValidated = true;
    if (!/^(input|textarea|select|option)$/i.test(element.tagName) || this.isFormActive) 
        return;
    this.onStart();
};
ns_API.form.prototype.onStart = function(element){
    this.isFormActive = true;
    this.startTime = new Date().getTime();
    this.writeDebugStatement("<font color='red'>start of form <i>" + this.formName + "</i>:</font> " + new Date(this.startTime).toGMTString());
};
ns_API.form.prototype.writeDebugStatement = function(text){
    if (!ns_API.forms.DEBUG) 
        return;
    var element = (top.debugWindow) ? top.debugWindow.document.getElementById("debug") : document.getElementById("debug");
    if (element) 
        element.innerHTML = text + "<hr>" + element.innerHTML;
};
ns_API.form.prototype.getScriptVersion = function(){
    return this.version
};
ns_API.form.prototype.getURL = function(){
    return this.url;
};
ns_API.form.prototype.setURL = function(_url){
    this.url = _url;
};
ns_API.form.prototype.setMaxFieldSize = function(size){
    size = size || 0;
    this.MAXFIELDSIZE = (!isNaN(parseInt(size)) && parseInt(size) > 0) ? size : this.MAXFIELDSIZE;
};
ns_API.form.prototype.select_oneValue = function(field){
    return ns_API.forms.NORMALPREFIX + ns_API.constructLabel(field.name.toLowerCase()) + "=" + escape(field.options[field.selectedIndex].value.substring(0, this.MAXFIELDSIZE));
};
ns_API.form.prototype.select_multipleValue = function(field){
    var arr = [];
    for (var i = 0, options; (option = field.options[i]); i++) 
        if (option.selected) 
            arr.push(ns_API.forms.NORMALPREFIX + ns_API.constructLabel(field.name.toLowerCase()) + "=" + escape(option.value.substring(0, this.MAXFIELDSIZE)));
    return arr.join("&");
};
ns_API.form.prototype.textValue = function(field){
    return ns_API.forms.NORMALPREFIX + ns_API.constructLabel(field.name.toLowerCase()) + "=" + escape(field.value.substring(0, this.MAXFIELDSIZE));
};
ns_API.form.prototype.textareaValue = function(field){
    return this.textValue(field);
};
ns_API.form.prototype.radioValue = function(field){
    var value = "";
    for (var i = 0, radio; (radio = field.form[field.name][i]); i++) {
        if (radio.checked) {
            value = radio.value;
            break;
        }
    }
    return ns_API.forms.NORMALPREFIX + ns_API.constructLabel(field.name.toLowerCase()) + "=" + escape(value.substring(0, this.MAXFIELDSIZE));
};
ns_API.form.prototype.checkboxValue = function(field){
    return ns_API.forms.NORMALPREFIX + ns_API.constructLabel(field.name.toLowerCase()) + "=" + ((field.checked) ? "checked" : "unchecked");
};
ns_API.form.prototype.hiddenValue = function(field){
    return ns_API.forms.HIDDENPREFIX + ns_API.constructLabel(field.name.toLowerCase()) + "=" + escape(field.value.substring(0, this.MAXFIELDSIZE));
};
ns_API.form.prototype.passwordValue = function(field){
    return ns_API.forms.PASSWORDPREFIX + ns_API.constructLabel(field.name.toLowerCase()) + "=" + ((field.value == "") ? "no" : "yes");
};
