/*! NV Forms v3 <http://nvinteractive.co.nz>
Copyright (c) NV Interactive
	
References:
jquery-1.3.x.js
		
Release Notes:
3.0.2 Watermark class no longer added for fields with no watermark
3.0.1 Fixed default button behaviour for multiple forms when enterkey is pressed.
3.0 rewrote as a jquery plugin
*/


//
// create closure
//
(function ($) {

    //
    // plugin definition
    //
    $.fn.nvforms = function (options) {
        debug("selection count: " + this.size());
        // build main options before element iteration
        var opts = $.extend({}, $.fn.nvforms.defaults, options);

        // iterate and reformat each matched element
        return this.each(function () { processform(this, opts) });
    };

    //
    // private function for debugging
    //
    function debug(msg) {
        if (window.console && window.console.log)
            window.console.log('nvforms: ' + msg);
    };

    //
    // define and expose our format function
    //
    processform = function (element, opts) {
        $this = $(element);
        // build element specific options
        var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

        //Add custom css classes to form elements - mostly to distinguish things like <input type=text> from an <input type="radio">
        for (var c in o.cssClasses) {
            $(":" + c, $this).addClass(o.cssClasses[c]);
        }

        //fix readonly fields
        $("label + div, label + span", $this).addClass("text readonly");

        //fix fileuploads
        $("label + a", $this).wrap("<div class='text'></div");

        //Fix readonly checkboxes
        $(".checkbox-group label span", $this).addClass("value")
            .filter(":contains('Yes')").addClass("true").end()
            .filter(":contains('No')").addClass("false").end()
            ;

        //Add focus events to all inputs
        $(":input", $this).focus(fc).blur(bl);

        //Add watermarks if neccessary
        $(":text, :password, textarea", $this).each(function () { addWaterMark(this, o) })

        //select input contents on focus
        $(":text, :password", $this).focus(function () { this.select() });

        //keypress events to submit form
        $(":text, :password", $this).data("form", $this).keypress(keypress);


        //remove watermarks when form submitted
        $(".default", $this).data("form", $this).click(submitForm);


        //Error handling
        $(".error").closest(".field-group").addClass("invalid")

    };


    //
    // Tools
    //
    addWaterMark = function (e, o) {

        $e = $(e);

        //alert( $(this).closest(".field").metadata().watermark );

        //first try to get hidden label
        var watermark = $("[for=" + e.id + "]").css("display") == "none" && o.addWatermarksForHiddenLabels ? $("[for=" + e.id + "]").text() : "";

        //then check against metadata (i.e. class="{watermark: 'watermark value'}")
        if ($e.closest(".field").length > 0) {
            watermark = $.metadata ? $e.closest(".field").metadata().watermark || watermark : watermark;
        }

        //Check against metadata on the field itself
        watermark = $.metadata ? $e.metadata().watermark || watermark : watermark;

        if (watermark == "" || watermark == undefined) return;

        //set watermark
        if ($e.val() == "" || $e.val() == watermark) $e.addClass("watermark").val(watermark);
        $e.data("watermark", watermark);

        //setup events within closure
        var watermarkfocus = function () {
            $this = $(this);
            var w = $this.data("watermark");
            if ($this.val() == w) $this.removeClass("watermark").val("");
        }

        var watermarkblur = function () {
            $this = $(this);
            var w = $this.data("watermark");
            if ($this.val() == "") $this.addClass("watermark").val(w);
        }

        //add events to remove watermark when focused
        $e.blur(watermarkblur).focus(watermarkfocus);

    }

    //
    // Events
    //

    fc = function (e) {
        $(this).addClass("focus");
    }

    bl = function (e) {
        $(this).removeClass("focus");

        //$.fn.nvforms.validateField(this);
    }

    keypress = function (e) {

        if (e.which != 13) return;

        //trigger a default button click
        $(".default", $(e.target).data("form")).click();

        return false;

    }

    submitForm = function (e) {

        debug("submit form");

        e.stopPropagation();

        var t = e.target;

        var f = $(t).data("form");
        clearwatermark(f);

        //target is a input[type=button]
        //we do nothing for now, just let the click happen...
        if (t.tagName.toLowerCase() == "input" && t.type.toLowerCase() == "button") return;

        //target is an href
        //we bundle the fields into a querystring and set the window.location
        if (t.tagName.toLowerCase() == "a") {
            window.location = createQuery($(t), f);
            return false;
        }

        var d = $(".default", f);
        if (d.attr("href") != undefined) {
            window.location = createQuery(d, f);
            return false;
        }

        return true;

    }

    createQuery = function (a, f) {
        var query = a.attr("href") + "?";
        $(":input", f).each(function (index) {
            query += index != 0 ? "&" : "";
            query += $(this).attr("name") + "=" + encodeURI($(this).val());
        });

        return query;
    }

    clearwatermark = function (form) {

        //remove watermarks
        $(":text", form).each(
			function () {
			    var w = $(this).data("watermark");
			    if (w == undefined) return;
			    if (this.value == w)
			        this.value = "";
			});
    }




    //
    // plugin defaults
    //
    $.fn.nvforms.defaults = {
        debug: false,
        addWatermarksForHiddenLabels: true,
        cssClasses: {
            text: "text",
            password: "text",
            radio: "radio",
            checkbox: "checkbox",
            button: "button",
            submit: "submit",
            file: "file"
        }

    };
    //
    // end of closure
    //
})(jQuery);
