﻿/* CRUNCH[MemX.Base] */
///////////////////////////////////////////
// Memory Express jQuery Functionality   //
// http://www.memoryexpress.com/         //
///////////////////////////////////////////

/** jQuery No Conflict **/
//var jQ = jQuery.noConflict();

/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function () {
    var initializing = false, fnTest = /xyz/.test(function () { xyz; }) ? /\b_super\b/ : /.*/;
    // The base Class implementation (does nothing)
    this.Class = function () { };

    // Create a new Class that inherits from this class
    Class.extend = function (prop) {
        var _super = this.prototype;

        // Instantiate a base class (but only create the instance,
        // don't run the init constructor)
        initializing = true;
        var prototype = new this();
        initializing = false;

        // Copy the properties over onto the new prototype
        for (var name in prop) {
            // Check if we're overwriting an existing function
            prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function (name, fn) {
            return function () {
                var tmp = this._super;

                // Add a new ._super() method that is the same method
                // but on the super-class
                this._super = _super[name];

                // The method only need to be bound temporarily, so we
                // remove it when we're done executing
                var ret = fn.apply(this, arguments);
                this._super = tmp;

                return ret;
            };
        })(name, prop[name]) :
        prop[name];
        }

        // The dummy class constructor
        function Class() {
            // All construction is actually done in the init method
            if (!initializing && this.init)
                this.init.apply(this, arguments);
        }

        // Populate our constructed prototype object
        Class.prototype = prototype;

        // Enforce the constructor to be what we expect
        Class.prototype.constructor = Class;

        // And make this class extendable
        Class.extend = arguments.callee;

        return Class;
    };
})();

/********* Common Functions ***********/

$(document).ready(function() {
    var cb = $("#colorbox");
    if (cb == null)
        return;

    cb.prependTo("body");
});

function LookupVariable(varName, context) {
    var varItem = null;

    if (context != null)
        varItem = $("var." + varName, context);
    else
        varItem = $("var." + varName);

    if (varItem == null)
        return "";

    return varItem.html();
}

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

/******** Global Registrations ********/

// Any element with class="Event_NoPropigation" will prevent click's from bubbling up the chain!
$(document).ready(function () {

    var globalInit_NoPropigation = function () {
        $(".Event_NoPropigation").each(function () {
            $(this).click(function (e) {
                e.stopPropagation();
            });
        });
    };

    setTimeout(globalInit_NoPropigation, 30); // After Load
});

/******** Validation ***********/

function validate_range(self, min, max) {
    var val = $(self).attr('value');

    if (!IsNumeric(val))
        $(self).attr('value', min);

    if (val > max)
        $(self).attr('value', max);
    if (val < min)
        $(self).attr('value', min);
}

$(document).ready(function() {
    $("a.Colorbox_IFrameLink").colorbox({ width: "60%", height: "75%", iframe: true });
});


/*+=========================================================================================+*/
/*| Helper Functions                                                                        |*/
/*+=========================================================================================+*/

function FindVariable(jQItem, className, isNumeric) {
    var lookup = "var." + className;

    var result = null;

    if (jQItem == null || jQItem == undefined) {
        result = $(lookup);
    }
    else {
        result = jQItem.find(lookup);
    }

    if (result == null || result == undefined)
        return (isNumeric) ? NaN : null;

    return (isNumeric) ? Number(result.html()) : result.html();
}

function TestExistance(values) {
    if (!$.isArray(values)) {
        return (values == null || values == undefined || values == NaN)
            ? false
            : true;
    }
    else {
        for (var i = 0; i < values.length; i++) {
            if (values[i] == null || values[i] == undefined || values == NaN)
                return false;
        }

        return true;
    }
}


function FunctionExists(func) {
    return func && typeof func == "function";
}

function AssertDependantFunctions(funcs) {
    for (var i = 0; i < funcs.length; i++) {
        if (!FunctionExists(funcs[i]))
            return false;
    }

    return true;
}

/***** Memx Plugin: Ghosted Input *****/

(function ($) {
    $.fn.unghosted = function() {
        return this.each(function() {
            var $this = $(this);
            var options = $this.data('options');

            $this.data('edited', true);
            
            if (options) {
                $this.css('color', options.returnColor);
            }
        });
    };
    
    $.fn.ghosted = function(options) {

        var defaults = {
            text: "Enter Value",
            ghostedColor: "#444",
            returnColor: "#000",
            remove: false
        };

        var options = $.extend(defaults, options);

        return this.each(function() {
            var item = $(this);
            item.data('edited', false);
            item.data('options', options);

            var initialValue = item.val();
            
            if (initialValue == null || initialValue == undefined || initialValue == '')
            {
                item.css('color', options.ghostedColor);
                item.val(options.text);

                item.click(function(e) {
                    var input = $(this);
                    if (!input.data('edited'))
                    {
                        if (options.remove) {
                            input.val('');
                        }
                        else {
                            if (this.createTextRange) {
                                range = this.createTextRange();
                                range.moveEnd('character', this.value.length);
                                range.select();
                            }
                            else if (this.setSelectionRange) {
                                this.setSelectionRange(0, this.value.length);
                            }
                        }
                    }
                });
                
                if (options.remove) {
                    item.blur(function() {
                        var input = $(this);
                        if (!input.data('edited')) {
                            var iVal = input.val();
                            if (iVal != '' && iVal != options.text)
                                input.data('edited', true);
                            else
                                input.val(options.text);
                        }
                    });
                }

               item.keypress(function() {
                    var input = $(this);
                    if (!input.data('edited'))
                    {
                        input.data('edited', true);
                        input.css('color', options.returnColor);
                    }
                });
            }
        });
    }
})(jQuery);


var MemX = MemX || { };
MemX.Core = {};

(function($, $memx) {
    $(document).ready(function() {
        $memx.Body = $("body");
    });

    $memx.Core.GetBody = function() {
        if (!$memx.Body) {
            $memx.Body = $("body");
        }

        return $memx.Body;
    };
})(jQuery, MemX);

(function($, $memx) {

    $memx.Core.Rollovers = { };
    $memx.Core.Rollovers.ToLoad = [];

    $memx.Core.Rollovers.Register = function(context) {
        $memx.Core.Rollovers.ToLoad.push(context);
    };
    
    $memx.Core.Rollovers.InitializePendingRollovers = function() {
        for(var context in $memx.Core.Rollovers.ToLoad) {
            $memx.Core.Rollovers.Initialize($memx.Core.Rollovers.ToLoad[context]);
        }
    };

    $memx.Core.Rollovers.Initialize = function(context) {
        var selector = '';
        if (typeof context == "string")
            selector = $(context);
        else {
            selector = context;
        }
        
        selector.hover(
            function () {
                $(this).addClass("Highlighted");
            },
            function () {
                $(this).removeClass("Highlighted");
            }
        );
    };
    
    function autoInitializeRollovers() {
        $memx.Core.Rollovers.InitializePendingRollovers();
    }
    
    $(window).load(autoInitializeRollovers);
    
})(jQuery, MemX);

(function ($, $memx) {

    var $core = $memx.Core;

    //#region MemX.Core.TimedTrigger Class

    var TimedTrigger = function () { this.SetValues(null); };
    TimedTrigger.prototype.SetValues = function (values) {
        if (!values)
            values = [null, null, null, null];

        this.Timeout = values[0];
        this.Root = values[1];
        this.Callback = values[2];
        this.Args = values[3];
    };

    TimedTrigger.prototype.Stop = function () {
        if (this.Timeout) {
            clearTimeout(this.Timeout); // Stop it!
        }
    };

    TimedTrigger.prototype.Start = function (timeout, root, callback, args) {
        var trigger = this;
        this.Stop();
        this.SetValues([setTimeout(function () { trigger.Trigger.call(trigger); }, timeout), root, callback, args]);
    };

    TimedTrigger.prototype.Trigger = function () {
        if (this.Callback)
            this.Callback.apply(this.Root, this.Args);
        else
            $.handleError('Unable to Trigger Callback', 'The callback provided was null/undefined');

        this.SetValues(null);
    };

    $core.TimedTrigger = TimedTrigger;

    //#endregion

})(jQuery, MemX);

(function($, $memx) {

    var $core = $memx.Core;

    //#region MemX.Core.VariableResults Class
    
    $core.VariableResults = function(jQResults, defaults, isJsonBlob) { this.Init(jQResults, defaults, isJsonBlob); };
    $core.VariableResults.prototype.Init = function(jQResults, defaults, isJsonBlob) {
        if (defaults) {
            for (var key in defaults) {
                this[key] = defaults[key];
            }
        }

        if (isJsonBlob) {
            var str = jQResults.html();
            if (str === "") str = '""';
            eval("var p=" + str + ";");
            
            for(var pkey in p) {
                this[pkey] = p[pkey];
            }
        } else {
            for(var i = 0; i < jQResults.length; i++) {
                var variable = jQResults[i];
                var variableName = variable.className;
                var variableVal = variable.textContent || variable.nodeValue || variable.innerHTML;

                this[variableName] = variableVal;
            }   
        }
    };

    $core.VariableResults.prototype.Get = function(key, defaultValue) {
        return (this[key] || defaultValue);
    };

    $core.VariableResults.prototype.GetAsInt = function(key, defaultValue) {
        if (!this[key]) return defaultValue;
        return parseInt(this[key]);
    };
    
    $core.VariableResults.prototype.GetAsFloat = function(key, defaultValue) {
        if (!this[key]) return defaultValue;
        return parseFloat(this[key]);
    };

    $core.VariableResults.prototype.GetAsJSON = function(key, defaultValue) {
        if (!this[key]) return defaultValue;
        eval('var p = ' + this[key] + ';');
        return p;
    };
    
    //#endregion

    $.fn.getVariables = function(defaults, isJsonBlob) {
        return new MemX.Core.VariableResults(this, defaults, isJsonBlob);
    };
    
})(jQuery, MemX);

(function($) {
    $(document).ready(function() {
        var overlay = $("body");
        overlay.ajaxStart(function() {
            $.showTooltip({ named: 'Loading' });
        });
        overlay.ajaxStop(function() {
            $.hideTooltip();
        });
    });
})(jQuery);
