$(document).ready(function() {
    $(function() {
        $("#dialog").dialog("destroy");

        var tq_name = $("#tq_name"), tq_email = $("#tq_email"), tq_question = $("#tq_question"), allFields = $([]).add(tq_name).add(tq_email).add(tq_question), 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; } }
        function checkRegexp(o, regexp, n) { if (!(regexp.test(o.val()))) { o.addClass('ui-state-error'); updateTips(n); return false; } else { return true; } }

        $("#dialog-form").dialog({
            autoOpen: false,
            height: 350,
            width: 350,
            modal: true,
            buttons: {
                'Submit': function() {
                    var bValid = true;
                    allFields.removeClass('ui-state-error');

                    bValid = bValid && checkLength(tq_name, "Name", 3, 16);
                    bValid = bValid && checkLength(tq_email, "Email", 6, 80);
                    bValid = bValid && checkLength(tq_question, "Question", 1, 255);

                    bValid = bValid && checkRegexp(tq_name, /^[a-z]([0-9a-z_\s])+$/i, "Name may consist of a-z, 0-9, underscores, begin with a letter.");
                    // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                    bValid = bValid && checkRegexp(tq_email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "e.g. name@domain.com");
                    // bValid = bValid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");

                    if (bValid) {
                        $("#tq_overlay").addClass('tq_overlay_active');
                        var queryStringData = "name=" + tq_name.val() + "&email=" + tq_email.val() + "&question=" + tq_question.val();
                        if ($("#tq_productid").val() != '') { queryStringData += "&productid=" + $("#tq_productid").val() }
                        var tmpHTML = $('#dialog-form').html();
                        $('#tq_overlay_msg').addClass('tq_overlay_msg_active');
                        $('#tq_overlay_msg').html("<p><img src='/images/loading.gif' /> Processing enquiry...</p>");
                        $.ajax({ type: "GET", url: "/jaq/submit_technical_question.aspx", dataType: "xml", data: queryStringData, cache: false,
                            success: function(xml) {
                                $(xml).find('response').each(function() {
                                    if ($(this).find('status').text() == 'success') {
                                        $('#tq_overlay_msg').html('<p>Enquiry has been successfully processed.</p>');
                                        setTimeout(function() { $("#dialog-form").dialog('close'); }, 2000);
                                    }
                                    else {
                                        $('#tq_overlay_msg').addClass('ui-state-error');
                                        $('#tq_overlay_msg').html('<p>' + $(this).find('errormsg').text() + '</p>');
                                        setTimeout(function() { ResetForm(); }, 4000);
                                    }
                                });
                            }, error: function(x, e) {
                                $('#tq_overlay_msg').addClass('ui-state-error');
                                //srcTarget.innerHTML = "\u00A30.00";
                                if (x.status == 0) {
                                    //alert('You are offline!!\n Please Check Your Network.');
                                    $('#tq_overlay_msg').html('<p>You are offline!!\n Please Check Your Network.</p>');
                                } else if (x.status == 404) {
                                    //alert('Requested URL not found.');
                                    $('#tq_overlay_msg').html('<p>Requested URL not found.</p>');
                                } else if (x.status == 500) {
                                    //alert('Internel Server Error.');
                                    $('#tq_overlay_msg').html('<p>Internel Server Error.</p>');
                                } else if (e == 'parsererror') {
                                    //alert('Error.\nParsing JSON Request failed.');
                                    $('#tq_overlay_msg').html('<p>Error.\nParsing JSON Request failed.</p>');
                                } else if (e == 'timeout') {
                                    //alert('Request Time out.');
                                    $('#tq_overlay_msg').html('<p>Request Time out.</p>');
                                } else {
                                    //alert('Unknow Error.\n' + x.responseText);
                                    $('#tq_overlay_msg').html('<p>Unknow Error.\n' + x.responseText + '</p>');
                                }
                                setTimeout(function() { ResetForm(); }, 4000);
                            }
                        });
                    }
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            },
            close: function() {
                allFields.val('').removeClass('ui-state-error');
                ResetForm();
            }
        });

        function ResetForm() {
            $("#tq_overlay").removeClass('tq_overlay_active');
            $('#tq_overlay_msg').removeClass('tq_overlay_msg_active');
            $('#tq_overlay_msg').removeClass('ui-state-error');
            $('#tq_overlay_msg').html('');
            $("#tq_overlay").addClass('tq_overlay');
            $('#tq_overlay_msg').addClass('tq_overlay_msg');
        }

        $('#create-user').click(function(event) {
            allFields.val('').removeClass('ui-state-error');
            $('#dialog-form').dialog('option', 'position', [(event.clientX - 150), (event.clientY)]);
            $('#dialog-form').dialog('open');
        });
    });
});