/*
 * jquery.watermark.js
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 */
(function ($) {



    $.event.special.input = {
        setup: function (data, namespaces) {
            var timer,
            // Get a reference to the element
                elem = this,
            // Store the current state of the element
                state = elem.value,
            // Create a dummy element that we can use for testing event support
                tester = document.createElement(this.tagName),
            // Check for native oninput
                oninput = "oninput" in tester || checkEvent(tester),
            // Check for onpropertychange
                onprop = "onpropertychange" in tester;

            if ($.browser.msie && $.browser.version == "9.0") {

                //check if ie9 - it's not firing oninput or onpropertychange on selecting password from pass-manager
                oninput = false;
                onprop = false;
            }

            function checkState() {
                if (elem.value != state)
                    state = elem.value,
                    $(elem).trigger("input");
            }

            // Set up a function to handle the different events that may fire
            function handler(e) {
                // If it's a propertychange event, just trigger the input event
                if (e.type == "propertychange" && window.event.propertyName == "value")
                    $(this).trigger("input");

                // When focusing or mouseentering, set a timer that polls for changes to the value
                else if (e.type == "focus") {
                    checkState();
                    clearInterval(timer),
                    timer = window.setInterval(checkState, 250);
                }

                // When blurring or mouseleaving, cancel the aforeset timer
                else if (e.type == "blur")
                    window.clearInterval(timer);

                // For all other events, queue a timer to check state ASAP
                else
                    window.setTimeout(checkState, 0);
            }

            // Bind to native event if available
            if (oninput)
                return false;

            // Else fall back to propertychange if available
            else if (onprop)
                $(this).bind("propertychange", handler);

            // Else clutch at straws!
            else
                $(this).bind("focus blur paste cut keydown drop", handler);

            $(this).data("inputEventHandler", handler);
        },
        teardown: function () {
            $(this).unbind("focus blur propertychange paste cut keydown drop", $(this).data("inputEventHandler"));
        }
    };

    // Setup our jQuery shorthand method
    $.fn.input = function (handler) {
        return handler ? this.bind("input", handler) : this.trigger("input");
    }


    /*
    The following function tests an element for oninput support in Firefox.  Many thanks to
 
    http://blog.danielfriesen.name/2010/02/16/html5-browser-maze-oninput-support/
 
    */
    function checkEvent(el) {
        // First check, for if Firefox fixes its issue with el.oninput = function
        el.setAttribute("oninput", "return");
        if (typeof el.oninput == "function")
            return true;

        // Second check, because Firefox doesn't map oninput attribute to oninput property
        try {
            var e = document.createEvent("KeyboardEvent"),
                ok = false,
                tester = function (e) {
                    ok = true;
                    e.preventDefault();
                    e.stopPropagation();
                }
            e.initKeyEvent("keypress", true, true, window, false, false, false, false, 0, "e".charCodeAt(0));
            document.body.appendChild(el);
            el.addEventListener("input", tester, false);
            el.focus();
            el.dispatchEvent(e);
            el.removeEventListener("input", tester, false);
            document.body.removeChild(el);
            return ok;
        } catch (e) { }
    }






    $.extend($, {
        clearwatermarks: function () {
            $("[wmwrap='true']").find("input,textarea").watermark({ remove: true });
        },
        addwatermarks: function () {
            $("[watermark]").each(function (num, el) {

                //delay the check
                $(el).bind('input', function () {
                    setTimeout('$.checkwatermark()', 50);
                });

                $(el).watermark($(el).attr("watermark"));
            });
        },
        checkwatermark: function () {
            $("[watermark]").each(function (num, el) {
                if ($(el).val()) {
                    $(el).parent().children(":first").hide();
                }
            });
        },
        watermark: function (o) {
            o.el = $(o.el);
            if (o.remove) {
                if (o.el.parent().attr("wmwrap") == 'true') {
                    o.el.parent().replaceWith(o.el);
                }
            } else {
                if (o.el.parent().attr("wmwrap") != 'true') {
                    o.el = o.el.wrap("<span wmwrap='true' style='position:relative;'/>");
                    var l = $("<label/>");

                    if (o.html) { l.html(o.html); }
                    if (o.cls) { l.addClass(o.cls); }
                    if (o.css) { l.css(o.css); }

                    l.css({
                        position: "absolute",
                        left: "3px",
                        top: parseInt(o.el.css("paddingTop")),
                        display: "inline",
                        cursor: "text"
                    });

                    if (o.el.is("TEXTAREA")) {
                        if ($.browser.msie) {
                            l.css("width", o.el.width());
                        }
                        if ($.browser.mozilla || $.browser.safari) {
                            l.css("top", "");
                        }
                    }

                    if (!o.cls && !o.css) {
                        l.css("color", "#ccc");
                    }

                    var focus = function () {
                        l.hide();
                    };

                    var blur = function () {
                        if (!o.el.val()) {
                            l.show();
                        } else {
                            l.hide();
                        }
                    };

                    var click = function () {
                        o.el.focus();
                    };

                    if (o.inherit) {
                        if (typeof o.inherit == "string") {
                            l.css(o.inherit, o.el.css(o.inherit));
                        } else {
                            for (var x = 0; x < o.inherit.length; x++) {
                                l.css(o.inherit[x], o.el.css(o.inherit[x]));
                            }
                        }
                    }

                    o.el.focus(focus).blur(blur);
                    l.click(click);

                    if (o.el.val()) { l.hide(); }

                    o.el.before(l);
                }
            }
            return o.el;
        }
    });

    $.fn.watermark = function (o) {
        return this.each(function () {
            if (typeof (o) == "string") {
                try { o = eval("(" + o + ")"); } catch (ex) { o = { html: o }; }
            }
            o.el = this;
            return $.watermark(o);
        });
    };
})(jQuery);

//jQuery(document).ready(function () {
//	$.addwatermarks();
//});

