﻿/// <reference path="jquery-1.4.2.js"/>

$(function() {
    $('body').append('<form id="dialogForm" action="#" style="display:none;"></form>');

    $('.linkToModal', '#content').each(function() {
        var $link = $(this);

        var $dialog = $('<div class="contentModal"></div>')
            .dialog({
                modal: true,
                autoOpen: false,
                resizable: false,
                title: $link.attr('title'),
                width: 500,
                open: function(event, ui) {
                    $('#dialogForm').get(0).reset();
                    var validator = $('#dialogForm').validate()
                    validator.resetForm();
                    $("#summary").html('');
                    $('#dialogForm')
                        .css('display', 'inline')
                        .find('input:first').focus();
                    $(this).dialog('option', 'position', 'center');
                },
                close: function(event, ui) {
                    $('#dialogForm')
                        .removeClass('submitted')
                        .css('display', 'none');
                }
            });

        $.ajax({
            type: "POST",
            url: scriptServiceURL + "/GetSubscriptionFormMarkup",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                var a = 0;
            },
            success: function(markup) {
                $dialog.html(markup.d);

                $dialog.find('textarea').parents('tr:first').css('vertical-align', 'top');

                $dialog.find('.adviceText').each(function() {
                    var $input = $(this);
                    var originalValue = $input.val();
                    $input.focus(function() {
                        if ($.trim($input.val()) == originalValue) $input.val('').removeClass('adviceText');
                    })
                    .blur(function() {
                        if ($.trim($input.val()) == '') $input.val(originalValue).addClass('adviceText');
                    });
                });

                $dialog.find('textarea').bind('keyup mouseup', function() {
                    var v = $(this).val();
                    if (v.length > 500) {
                        var st = $(this).scrollTop();
                        $(this).val(v.substring(0, 500));
                        $(this).scrollTop(st);
                    }
                });

                $dialog.parents('.ui-dialog:first').appendTo($('#dialogForm'));

                $.validator.addMethod(
                    'emailsMatch',
                    function(value) { return value == $('#email').val(); },
                    '<img src="images/unchecked.gif" title="Email addresses do not match" alt="Error" />'
                );

                $.validator.addMethod('nameChars',
                        function(value, element, regexp) { return !new RegExp("[^a-zA-Z_\\-\\'\\s]", 'g').test(value); },
                        '<img src="images/unchecked.gif" title="Contains invalid characters" alt="Error" />'
                );

                $.validator.messages.required = "<img src='images/unchecked.gif' title='Required' alt='Error' />";
                $.validator.messages.email = "<img src='images/unchecked.gif' title='Please enter a vaid email address' alt='Error' />";

                var validator = $("#dialogForm").bind("invalid-form.validate", function() {
                    var invalids = validator.numberOfInvalids();
                    $("#summary").html("There " +
		                (invalids > 1
		                ? "are " + invalids + " problems"
		                : "is 1 problem") + " with your details below. For more information, hover over the crosses.");
                }).validate({
                    debug: true,
                    errorElement: "label",
                    errorContainer: $("#summary"),
                    errorPlacement: function(error, element) {
                        error.appendTo(element.parent("td").next("td"));
                    },
                    success: function(label) { label.html("<img src='images/checked.gif' alt='Valid' />"); },
                    rules: {
                        firstName: { required: true, nameChars: true },
                        lastName: { required: true, nameChars: true },
                        email: { required: true, email: true },
                        confirmEmail: { emailsMatch: true, required: true, email: true }
                    }
                });
            }
        });

        $link.click(function() {
            $dialog.dialog('open')
	            .find('textarea').each(function() {
	                var $ta = $(this);
	                $ta.css('overflow-x', 'hidden');

	                $ta.width($ta.parents('td:first').width());
	                $ta.height($ta.parents('tr:first').height());
	            });
            return false;
        });
    });
});

function submitSubscribe() {
    var $f = $('#dialogForm');
    $f.validate();
    if ($f.valid()) {
        var firstName = encodeURIComponent($f.find('#firstName').val()),
            lastName = encodeURIComponent($f.find('#lastName').val()),
            email = encodeURIComponent($f.find('#email').val()),
            message = encodeURIComponent($f.find('#message').val());

        $.ajax({
            type: "POST",
            url: scriptServiceURL + "/Subscribe",
            data: '{ "firstName":"' + firstName + '","lastName":"' + lastName + '","email":"' + email + '","optionalMsg":"' + message + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "html",
            success: function(markup) {
                $f.addClass('submitted');
            }
        });
    }
}
