﻿function aqForm(id, action, page, onSuccess) {
    var form = {};

    form.id = id;
    form.action = action;
    form.page = page;

    form.declare = function(root) {
        $('#' + form.id).validate({ meta: "validate" });

        // Don't use "live" method: don't work in IE8
        $('#' + form.id, root).submit(function() {
            if (!$('#' + form.id).valid()) {
                alert('Invalid form!');
                return false;
            }

            values = $(this).formToArray();
            values.push({ name: 'aqservice', value: 'aqpull' });
            values.push({ name: 'aqid', value: form.action });

            $('body').css('cursor', 'wait');

            $.ajax({
                type: "POST",
                url: document.location.href,
                data: values,
                dataType: "xml",
                success: function(xml) {
                    var ok = page.serviceSuccess(xml);

                    if (onSuccess != null) {
                        onSuccess(ok);
                    }
                }
            });

            return false;
        });
    };

    return form;
};

function aqUpload(id, file, action, page, onSend, onSuccess) {
    var upload = {};

    upload.id = id;
    upload.file = file;
    upload.action = action;
    upload.page = page;

    upload.send = function() {
        /*
        prepareing ajax file upload
        url: the url of script file handling the uploaded files
        fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
        dataType: it support json, xml
        secureuri:use secure protocol
        success: call back function when the ajax complete
        error: callback function when the ajax failed
        */
        var url = document.location.href;

        if (url.indexOf('?') >= 0) {
            url += '&';
        }
        else {
            url += '?';
        }

        url += 'aqservice=aqupload&aqfile=' + upload.file + '&aqfilename=' + $('#' + upload.id).val();

        if (upload.action != null && upload.action != "") {
            url += "&aqid=" + upload.action;
        }

        if (onSend != null) {
            onSend();
        }

        $.ajaxFileUpload({
            url: url,
            secureuri: false,
            fileElementId: upload.id,
            dataType: 'xml',
            success: function(xml) {
                var ok = page.serviceSuccess(xml);

                if (onSuccess != null) {
                    onSuccess(ok);
                }
            }
        });
    };

    return upload;
};

function aqPage() {
    var page = {};

    page.rules = [];
    page.forms = [];
    page.uploads = {};

    page.serviceSuccess = function(xml) {
        var success = $('result success', xml).text();

        var res = true;

        if (success != 'true') {
            alert($('result message', xml).text());
            res = false;
        }

        var redirection = $('redirection', xml).text();

        if (null != redirection && redirection.length > 0) {
            document.location = redirection;
            return false;
        }

        $('part', xml).each(function(i, partElement) {
            var part = $(partElement);
            var text = part.text().replace('<!--[CDATA[', '').replace(']]-->', '');

            var node = $('#' + part.attr('id'));
            node.replaceWith(text);

            // Declare forms if necessary (since "live" method isn't used)
            for (var i = 0; i < page.forms.length; i++) {
                page.forms[i].declare($('#' + part.attr('id')));
            }

            // Rules remains with "live" events
        });

        $('body').css('cursor', '');
        return res;
    };

    page.pull = function(action, parameters, onSuccess) {
        if (null == parameters) {
            parameters = [];
        }

        parameters.push({ name: 'aqservice', value: 'aqpull' });
        parameters.push({ name: 'aqid', value: action });

        $('body').css('cursor', 'wait');

        $.ajax({
            type: "POST",
            url: document.location.href,
            data: parameters,
            dataType: "xml",
            success: function(xml) {
                var ok = page.serviceSuccess(xml);

                if (onSuccess != null) {
                    onSuccess(ok);
                }
            }
        });
    };

    $(document).ready(function() {
        // Declare forms
        for (var i = 0; i < page.forms.length; i++) {
            page.forms[i].declare(document);
        }

        // Apply rules
        for (var i = 0; i < page.rules.length; i++) {
            page.rules[i]();
        }

    });

    page.addRule = function(r) {
        page.rules.push(r);
    };

    page.addForm = function(f) {
        var form = aqForm(f.id, f.action, page, f.onSuccess);
        page.forms.push(form);
    };

    page.addUpload = function(u) {
        page.uploads[u.id] = aqUpload(u.id, u.file, u.action, page, u.onSend, u.onSuccess);
    }

    return page;
}