﻿/*	
A set of Handy Tools and Functions for use with the jQuery API
jquery.fancy.forms and jquery.pir both make use of functions in this library
Created by Ryan Vettese
*/
(function ($) {

    $.modalSignin = function () { };

    $.clientID = function (id) {
        return $(":input[id^='" + id + "_']");
    }

    $.hiddenField = function (label, name, val) {
        return '<input name="' + name + '" type="hidden" value="' + val + '" />';
    }

    $.textField = function (label, name, val, width, maxlength) {
        return '<label for="' + name + '">' + label + '</label><input name="' + name + '" type="text" style="width:' + width + 'px" maxlength="' + maxlength + '" value="' + val + '" />';
    }

    $.selectField = function (label, name, val, width) {
        return '<label for="' + name + '">' + label + '</label><select name="' + name + '" style="width:' + width + 'px"><option value=""></option></select>';
    }

    $.loadSelectOptions = function (field, selectedValue, URL, params) {
        field.attr('disabled', true);
        $.ajax({
            type: "POST",
            url: URL,
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                return;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                return false;
            },
            success: function (response) {
                response = $.cleanAjaxResponse(response);
                if (response.length > 0) {
                    var optionString = "";
                    jQuery.each(response, function (i, n) {
                        optionString += '<option value="' + this.Id + '"' + (this.Id == selectedValue ? ' selected' : '') + '>' + $.denull(this.Name) + '</option>';
                    });
                    field.append(optionString);
                }
                $.fancy.drawOptions(field.attr('disabled', false));
            },
            complete: function () {
                return;
            }
        });
    }

    $.buttonField = function (name, label) {
        return '<a class="button" id="' + name + '" href="#"><ins>' + label + '</ins></a>';
    }

    $.makenull = function (str) {
        return ((str == null) || (typeof (str) == "undefined")) ? null : str;
    };

    $.denull = function (str) {
        return $.makenull(str) == null ? "" : str;
    };

    $.makezero = function (str) {
        return $.makenull(str) == null ? 0 : str;
    };

    $.showXhrErrorDialog = function (xhr, ajaxOptions, thrownError) {
        $.showErrorDialog('Whoops!', 'Something went horribly wrong. This is what the server said:<br/><br/>Status:' + xhr.statusText + '<br/><br/>Response:' + xhr.responseText + '<br/><br/>Error:' + thrownError, 600, 400)
    };

    $.showErrorDialog = function (title, message, w, h, modal) {
        $('<div></div>')
            .html(message)
            .dialog({
                title: title,
                modal: typeof(modal) == 'undefined' ? false : modal,
                width: typeof (w) == 'undefined' ? 400 : w,
                height: typeof (h) == 'undefined' ? 300 : h,
                buttons: {
                    "Ok": function () {
                        $(this).dialog("close");
                    }
                }
            });
    };

    $.showConfirmDialog = function (dialObj) {
        $('<div></div>')
            .html(dialObj.html)
            .dialog({
                title: dialObj.title,
                width: typeof (dialObj.w) == 'undefined' ? 300 : dialObj.w,
                height: typeof (dialObj.h) == 'undefined' ? 200 : dialObj.h,
                modal: true,
                resizable: false,
                draggable: false,
                buttons: {
                    "Cancel": function () {
                        //do nothing
                        $(this).dialog("close");
                    },
                    "Okay": function () {
                        dialObj.confirmCallback();
                        $(this).dialog("close");
                    }
                },
                close: function (event, ui) { $(this).dialog("destroy").remove(); }
            });
    };

    $.showInfo = function (title, message, w, h) {
        $('<div></div>')
        .html(message)
        .dialog({
            title: title,
            width: typeof (w) == 'undefined' ? 300 : w,
            height: typeof (h) == 'undefined' ? 200 : h
        });
    };

    $.getToken = function (onComplete) {
        $("form input[name='token']").remove();
        $.get(Vars.data.baseURL + "nuggets/Token.aspx", function (txt) {
            $("form").append('<input type="hidden" name="token" value="' + txt + '" />');
            onComplete();
        });
    };

    $.getFieldIds = function (response) {
        if (response.messages) {
            for (var i = 0; i < response.messages.length; i++) {
                response.messages[i].Key = $("#" + response.messages[i].Key);
            }
        }
    }

    $.addErrorMessage = function (response, key, message) {
        response.hasMessages = true;
        response.messages.push({ "Key": key, "Value": message });
    }

    $.validateBlank = function (response, key) {
        if ($.string(key.val()).blank()) {
            $.addErrorMessage(response, key, "${label} is required");
            return true;
        }
        return false;
    }

    $.validateEmail = function (response, key) {
        if ($.string(key.val()).isValidEmail()) {
            return true;
        }
        $.addErrorMessage(response, key, "${label} is not a valid email address");
        return false;
    }

    $.getAjaxMessage = function (response, messageKey) {
        var $m, $errorMessage;
        var $messages = new Array();

        if (response.messages) {
            for (var i = 0; i < response.messages.length; i++) {
                $m = response.messages[i];
                if ($m.Key == messageKey)
                    return $m.Value;
            }
            return "--";
        }
        else {
            return "--";
        }
    };

    $.showModalMessage = function (response, messagesNode) {
        $.showErrorDialog("There was an error", response.genericMessage);
    }

    $.showAjaxMessages = function (response, messagesNode) {
        var $messagesNode = typeof (messagesNode) == "undefined" ? $("#errorMessages") : messagesNode;
        var $m, $errorMessage;
        var $messages = new Array();
        $.resetErrorMessages(messagesNode);

        if (response.messages) {
            for (var i = 0; i < response.messages.length; i++) {
                $m = response.messages[i];
                $errorMessage = $m.Value;
                $m.Key.parent("div").addClass($m.Key.data("type") + '-box-error');
                $errorMessage = $.string($errorMessage).gsub("${label}", $.string($("label[for='" + $m.Key.attr("id") + "']").html()).gsub(" *", "").str).str;
                $messages[$messages.length] = $errorMessage;
            }
        }
        if (response.genericMessage && response.genericMessage.length > 0) {
            $messages[$messages.length] = response.genericMessage;
        }

        if ($messages.length > 0) {
            if (!$messagesNode) {
                debug("message node not defined");
                return;
            }

            jQuery.each($messages, function (i) {
                $messagesNode.append((i > 0 ? ', ' : '') + this);
            });

            $messagesNode.show();
        }
    };

    $.resetErrorMessages = function (messagesNode) {
        $("div.checkbox-box-error").removeClass('checkbox-box-error');
        $("div.text-box-error").removeClass('text-box-error');
        $("div.select-box-error").removeClass('select-box-error');
        var $messagesNode = typeof (messagesNode) == "undefined" ? $("#errorMessages") : messagesNode;
        $messagesNode.empty();
    };

    $.cleanAjaxResponse = function (obj) {
        if (obj.d)
            return obj.d;
        else
            return obj;
    };

    $.rgb2hex = function ($rgb) {
        if ($rgb.indexOf("#") >= 0)
            return $rgb;
        $rgb = $rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        return "#" + $.hex($rgb[1]) + $.hex($rgb[2]) + $.hex($rgb[3]);
    };

    $.hex = function ($x) {
        hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
        return isNaN($x) ? "00" : hexDigits[($x - $x % 16) / 16] + hexDigits[$x % 16];
    };

    $.isNumeric = function (n) {
        return typeof n === 'number' && isFinite(n);
    };

    $.random = function (size) {
        return Math.floor(Math.random() * size);
    };

    $.nocache = function () {
        return new Date().getTime();
    };

    $.doGet = function (url, params) {
        document.location = url + '?' + $.param(params);
    };

    $.doPost = function (url, params) {
        var $form = $("<form method='POST'>").attr("action", url);
        $.each(params, function (name, value) {
            $("<input type='hidden'>")
                .attr("name", name)
                .attr("value", value)
                .appendTo($form);
        });
        $form.appendTo("body");
        $form.submit();
    };

    //this function is to compare jQuery objects
    //in jQuery $(obj) == $(obj) resolves to FALSE.
    $.fn.equals = function (compareTo) {
        if (!compareTo || !compareTo.length || this.length != compareTo.length) {
            return false;
        }
        for (var i = 0; i < this.length; i++) {
            if (this[i] !== compareTo[i]) {
                return false;
            }
        }
        return true;
    };

    $.fn.exists = function () { return $(this).length > 0; }

    $.fn.bindAll = function (options) {
        var $this = this;
        jQuery.each(options, function (key, val) {
            $this.bind(key, val);
        });
        return this;
    }

})(jQuery);

/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/

/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
*       used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
*                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
*                             If set to null or omitted, the cookie will be a session cookie and will not be retained
*                             when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
*                        require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
* jQuery JSON Plugin
* version: 2.1 (2009-08-14)
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*
* Brantley Harris wrote this plugin. It is based somewhat on the JSON.org 
* website's http://www.json.org/json2.js, which proclaims:
* "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
* I uphold.
*
* It is also influenced heavily by MochiKit's serializeJSON, which is 
* copyrighted 2005 by Bob Ippolito.
*/

(function ($) {
    /** jQuery.toJSON( json-serializble )
    Converts the given argument into a JSON respresentation.

    If an object has a "toJSON" function, that will be used to get the representation.
    Non-integer/string keys are skipped in the object, as are keys that point to a function.

    json-serializble:
    The *thing* to be converted.
    **/
    $.toJSON = function (o) {
        if (typeof (JSON) == 'object' && JSON.stringify)
            return JSON.stringify(o);

        var type = typeof (o);

        if (o === null)
            return "null";

        if (type == "undefined")
            return undefined;

        if (type == "number" || type == "boolean")
            return o + "";

        if (type == "string")
            return $.quoteString(o);

        if (type == 'object') {
            if (typeof o.toJSON == "function")
                return $.toJSON(o.toJSON());

            if (o.constructor === Date) {
                var month = o.getUTCMonth() + 1;
                if (month < 10) month = '0' + month;

                var day = o.getUTCDate();
                if (day < 10) day = '0' + day;

                var year = o.getUTCFullYear();

                var hours = o.getUTCHours();
                if (hours < 10) hours = '0' + hours;

                var minutes = o.getUTCMinutes();
                if (minutes < 10) minutes = '0' + minutes;

                var seconds = o.getUTCSeconds();
                if (seconds < 10) seconds = '0' + seconds;

                var milli = o.getUTCMilliseconds();
                if (milli < 100) milli = '0' + milli;
                if (milli < 10) milli = '0' + milli;

                return '"' + year + '-' + month + '-' + day + 'T' +
                             hours + ':' + minutes + ':' + seconds +
                             '.' + milli + 'Z"';
            }

            if (o.constructor === Array) {
                var ret = [];
                for (var i = 0; i < o.length; i++)
                    ret.push($.toJSON(o[i]) || "null");

                return "[" + ret.join(",") + "]";
            }

            var pairs = [];
            for (var k in o) {
                var name;
                var type = typeof k;

                if (type == "number")
                    name = '"' + k + '"';
                else if (type == "string")
                    name = $.quoteString(k);
                else
                    continue;  //skip non-string or number keys

                if (typeof o[k] == "function")
                    continue;  //skip pairs where the value is a function.

                var val = $.toJSON(o[k]);

                pairs.push(name + ":" + val);
            }

            return "{" + pairs.join(", ") + "}";
        }
    };

    /** jQuery.evalJSON(src)
    Evaluates a given piece of json source.
    **/
    $.evalJSON = function (src) {
        if (typeof (JSON) == 'object' && JSON.parse)
            return JSON.parse(src);
        return eval("(" + src + ")");
    };

    /** jQuery.secureEvalJSON(src)
    Evals JSON in a way that is *more* secure.
    **/
    $.secureEvalJSON = function (src) {
        if (typeof (JSON) == 'object' && JSON.parse)
            return JSON.parse(src);

        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');

        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    };

    /** jQuery.quoteString(string)
    Returns a string-repr of a string, escaping quotes intelligently.  
    Mostly a support function for toJSON.
    
    Examples:
    >>> jQuery.quoteString("apple")
    "apple"
        
    >>> jQuery.quoteString('"Where are we going?", she asked.')
    "\"Where are we going?\", she asked."
    **/
    $.quoteString = function (string) {
        if (string.match(_escapeable)) {
            return '"' + string.replace(_escapeable, function (a) {
                var c = _meta[a];
                if (typeof c === 'string') return c;
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"';
        }
        return '"' + string + '"';
    };

    var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;

    var _meta = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    };
})(jQuery);

