$(document).ready(function() {
	/**
     * jQuery UI Dialog
     */

    // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
    $("#foundadeal-form").dialog("destroy");

    var $subject = $("#subject"),
        $message = $("#message"),
        $tags = $("#tags"),
        $allFields = $([]).add($subject).add($message).add($tags),
        $tips = $(".validateTips");

    function updateTips($t) {
        $tips.text($t).addClass('ui-state-highlight');

        setTimeout(function() {
            $tips.removeClass('ui-state-highlight', 1500);
        }, 500);
    }

    function checkLength($o, $n, $min, $max) {
        if ($o.val().length > $max || $o.val().length < $min) {
            $o.addClass('ui-state-error');
            updateTips("Length of " + $n + " must be between " + $min + " and " + $max + ".");
            return false;
        } else {
            return true;
        }
    }

    var $foundadeal = $("#foundadeal-form").dialog({
        autoOpen: false,
        height: 'auto',
        width: 'auto',
        modal: true,
        draggable: false,
        resizable: false,
        buttons: {
            Submit: function() {
    			$allFields.removeClass('ui-state-error');
    			
    			if (checkLength($subject, "subject", 1, 127) && checkLength($message, "message", 1, 1023)) {
    				$mail = jQuery.Zend.jsonrpc({url: 'index/mail'});
    				$mail.send($subject.val(), $message.val(), $tags.val());
    				$(this).dialog('close');
    			}
            },

            Cancel: function() {
                $(this).dialog('close');
            }
        },
        close: function() {
            $allFields.val('').removeClass('ui-state-error');
        }
    });

    $('#foundadeal-link').click(function() {
        $foundadeal.dialog('open');
    });
});   
