﻿if (!Sitecore || Sitecore == 'undefined') {
    var Sitecore = new Object();
}

if (!Sitecore.Wfm || Sitecore.Wfm == 'undefined') {
    Sitecore.Wfm = new Object();
}


Sitecore.Wfm.AttributeKey = {
    FieldIDKey: "fieldid",
    TrackEventKey: "trackevent"
}

Sitecore.Wfm.ClientEvent = Class.create({
    initialize: function(fieldid, type, value, formid, pageid, ticks) {
        this.FieldID = fieldid;
        this.Type = type;
        this.Value = value;
        this.FormID = formid;
        this.PageID = pageid
        this.Ticks = ticks;
    }
});

Sitecore.Wfm.Tracker = Class.create({

    formId: null,
    pageId: null,
    fieldId: null,
    fieldValue: null,
    eventCountHolderId: null,

    init: function(ctrlid, formid, pageid, eventCountHolderId) {
        this.formId = formid;
        this.pageId = pageid;

        this.eventCountHolderId = eventCountHolderId;
        this.bind(ctrlid);
    },

    bind: function(ctrlid) {
        var tracker = this;

        $$("#" + ctrlid + " input[type!='submit'], #" + ctrlid + " select, #" + ctrlid + " textarea").each(function(element) {
            Event.observe(element, 'blur', tracker._onBlurObserve.bindAsEventListener(tracker));
            Event.observe(element, 'focus', tracker._onFocusObserve.bindAsEventListener(tracker));
        });
    },

    _onFocusObserve: function(event) {
        var element = Event.element(event);
        var owner = Sitecore.Wfm.getAttributeAncestor(element, Sitecore.Wfm.AttributeKey.FieldIDKey, false);

        if (owner != null) {
            var fullfieldID = Sitecore.Wfm.getCssValue(owner, Sitecore.Wfm.AttributeKey.FieldIDKey);

            if (this.fieldId != fullfieldID) {
                var hiddenValue = $(owner.id + "_complexvalue");
                var value = null;

                if (hiddenValue == null && element.type == "checkbox") {
                    value = element.checked ? "1" : "0";
                }
                else {
                    value = (hiddenValue == null ? element.getValue() || element.value : hiddenValue.getValue()).toString();
                }


                this.fieldId = fullfieldID;
                this.fieldValue = value;
            }
        }
    },

    _onBlurObserve: function(event) {
        var element = Event.element(event);

        var target = event.explicitOriginalTarget || event.srcElement || document.activeElement;

        var owner = Sitecore.Wfm.getAttributeAncestor(element, Sitecore.Wfm.AttributeKey.FieldIDKey, false);

        if (owner != null) {

            var fullfieldID = Sitecore.Wfm.getCssValue(owner, Sitecore.Wfm.AttributeKey.FieldIDKey);

            var hiddenValue = $(owner.id + "_complexvalue");

            if (hiddenValue == null && element.type == "checkbox") {
                value = element.checked ? "1" : "0";
            }
            else {
                value = (hiddenValue == null ? element.getValue() || element.value : hiddenValue.getValue()).toString();
            }

            if (this.fieldId != fullfieldID || (this.fieldId == fullfieldID && this.fieldValue != value)) {

                this.fieldId = fullfieldID;
                this.fieldValue = value;

                if (element.type == "password" || element.hasClassName("scWfmPassword")) {
                    value = "<schidden></schidden>";
                }

                var ClientEvent = this._getEvent(fullfieldID, "Field Completed", value.replace(/<schidden>.*<\/schidden>/, '<schidden></schidden>'));

                var validationevent = this._checkClientValidation(element); ;
                this._trackEvents([ClientEvent, validationevent].flatten());
            }
        }
    },

    _checkClientValidation: function(element) {
        var tracker = this;
        var events = [];
        if (element.Validators != null) {
            element.Validators.each(function(current) {

                var validator = Element.extend(current);

                if (validator.isvalid == false) {
                    var ClientEvent = tracker._getEvent(
                                           Sitecore.Wfm.getCssValue(validator, Sitecore.Wfm.AttributeKey.FieldIDKey),
                                           Sitecore.Wfm.getCssValue(validator, Sitecore.Wfm.AttributeKey.TrackEventKey),
                                           validator.errormessage);
                    events.push(ClientEvent);
                }
            });
        }
        return events;
    },


    _trackEvents: function(events) {
        var body = "track=" + escape(encodeURIComponent(Object.toJSON(events)));

        new Ajax.Request("/sitecore modules/web/Web Forms for Marketers/Tracking.aspx" + location.search,
                         { method: 'post', postBody: body, asynchronous: true });
    },

    _getEvent: function(fieldId, eventKey, text) {

        var eventCount = $(this.eventCountHolderId).getValue();
        ++eventCount;
        $(this.eventCountHolderId).value = eventCount;
        return new Sitecore.Wfm.ClientEvent(fieldId,
                                        eventKey, text,
                                        this.formId, this.pageId,
                                        eventCount);
    },

    _trackData: function(fieldId, eventKey, text) {
        var ClientEvent = this._getEvent(fieldId, eventKey, text);

        var body = "track=" + escape(Object.toJSON([ClientEvent]))

        new Ajax.Request("/sitecore modules/web/Web Forms for Marketers/Tracking.aspx" + location.search,
                         { method: 'post', postBody: body, asynchronous: true });
    }
});
