﻿// initialize the objects we'll place in the global namespace
var JSComponents = (function() {
    return {
        // this method checks for any form elements that must have unique ids/names
        // currently this only includes radio buttons
        // if radio buttons are used, then the element index should be passed in the GatherPostData call to send the index
        //      that is appended to the radio buttons
        CleanFormIDs : function(wrapper, idx) {
            // for all radio elements in the current html element, add on the index value to the end of their id/name
            $(":input[@type=radio]", wrapper).each(function() {
                this.id = this.id + "-" + idx;
                this.name = this.name + "-" + idx;
            });

        },
        
        // when using double click functionality text on the page may become selected - this method can clear it
        ClearSelectedText : function() {
            if (document.selection && document.selection.empty) {
                document.selection.empty();
            } else if (window.getSelection) {
                var sel = window.getSelection();
                if (sel && sel.removeAllRanges)
                    sel.removeAllRanges();
            }
        },
        
        ConvertServerDataToLocal : function(data) {
            var result;
            try {
                result = eval("(" + data + ")");
                result.serverDataOk = true;
            }
            catch (ex) {
                //alert('error in data received from server');
                result = {};
                result.error = true;
                result.serverDataOk = false;
            }
            return result;
        },
    
        // creates an object to be passed to an ajax call, containing all of the necessary data for the server to process the request
        GatherPostData : function(wrapper, declarativeProperties) {
            var postData = {};

            // declarative properties are added as attributes to the wrapper div
            if (declarativeProperties && declarativeProperties.constructor == Array)
            {
                for (var idx = 0; idx < declarativeProperties.length; idx++)
                {
                    postData[declarativeProperties[idx]] = $(wrapper).attr(declarativeProperties[idx]);
                }
            }            
            
            // get the value of all inputs
            $(":input", wrapper).each(function(idx) {
                postData[this.id] = this.value;
            });
            
            return postData;
        },
        
        ServerPost : function(postData, successFn, errorFn, elem) {
            $.ajax({
                type: "POST",
                url: "/www/ClientCallback.tsc",
                async: true,
                cache: false,
                dataType: "html",
                global: false,
                data: postData,
                success: function(data, textStatus) { successFn(data, textStatus, elem); },
                error: function(xhrequest, textStatus, errorThrown) { errorFn(xhrequest, textStatus, errorThrown, elem); }
            });
        },
        
        StopFormSubmits : function() {
            $("form").submit(function () { return false; });
        }
    };
})();
var JSC = JSComponents;

// our event handler
// events can be subscribed to at any time
// any server control can fire off any event they want, and subscribers to that event will be processed
JSComponents.Event = (function() {
    var eventHandlers = [];
    var that = this;
    
    return {
        Subscribe : function(eventName, callback)  {
            if (!eventHandlers[eventName])
                eventHandlers[eventName] = [];
                
            eventHandlers[eventName].push(callback);
        },
    
        Fire : function(eventName, eventVars, eventSource) {
            //console.log(eventSource + "--" + eventName);
            if (eventHandlers[eventName] != null)
            {
                var handlerCount = eventHandlers[eventName].length;
                for (var i = 0; i < handlerCount; i++)
                {
                    var func = eventHandlers[eventName][i];
                    func(eventName, eventVars, eventSource);
                }
            }
        }
    }
})();
var JSCE = JSComponents.Event;

JSComponents.Cookies = (function() {
    return {
        CreateCookie : function(name, value, days) {
	        if (days) {
		        var date = new Date();
		        date.setTime(date.getTime()+(days*24*60*60*1000));
		        var expires = "; expires="+date.toGMTString();
	        }
	        else var expires = "";
	        document.cookie = name+"="+value+expires+"; path=/";
        },

        ReadCookie : function(name) {
	        var nameEQ = name + "=";
	        var ca = document.cookie.split(';');
	        for(var i=0;i < ca.length;i++) {
		        var c = ca[i];
		        while (c.charAt(0)==' ') c = c.substring(1,c.length);
		        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	        }
	        return null;
        },

        EraseCookie : function(name) {
	        JSComponents.Cookies.CreateCookie(name,"",-1);
        }
    }
})();
var JSCC = JSComponents.Cookies;

JSComponents.JSON = (function() {
    function f(n) {    // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    Date.prototype.toJSON = function () {
        return this.getUTCFullYear()   + '-' +
            f(this.getUTCMonth() + 1) + '-' +
            f(this.getUTCDate())      + 'T' +
            f(this.getUTCHours())     + ':' +
            f(this.getUTCMinutes())   + ':' +
            f(this.getUTCSeconds())   + 'Z';
    };

    var m = {    // table of character substitutions
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };

    function stringify(value, whitelist) {
        var a,          // The array holding the partial texts.
            i,          // The loop counter.
            k,          // The member key.
            l,          // Length.
            r = /["\\\x00-\x1f\x7f-\x9f]/g,
            v;          // The member value.

        switch (typeof value) {
        case 'string':
            return r.test(value) ?
                '"' + value.replace(r, function (a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) +
                                               (c % 16).toString(16);
                }) + '"' :
                '"' + value + '"';

        case 'number':
            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':
            return String(value);

        case 'object':
            if (!value) {
                return 'null';
            }
            if (typeof value.toJSON === 'function') {
                return stringify(value.toJSON());
            }
            a = [];
            if (typeof value.length === 'number' &&
                    !(value.propertyIsEnumerable('length'))) {
                l = value.length;
                for (i = 0; i < l; i += 1) {
                    a.push(stringify(value[i], whitelist) || 'null');
                }

                return '[' + a.join(',') + ']';
            }
            if (whitelist) {
                l = whitelist.length;
                for (i = 0; i < l; i += 1) {
                    k = whitelist[i];
                    if (typeof k === 'string') {
                        v = stringify(value[k], whitelist);
                        if (v) {
                            a.push(stringify(k) + ':' + v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (typeof k === 'string') {
                        v = stringify(value[k], whitelist);
                        if (v) {
                            a.push(stringify(k) + ':' + v);
                        }
                    }
                }
            }
            return '{' + a.join(',') + '}';
        }
    }

    return {
        Stringify: stringify
    }
})();
var JSCJ = JSComponents.JSON;

