﻿
//Uses jquery and jquery.form to have improved ajax form handling
//with in page error viewing, and TinyMCE editor support


function RegisterAjaxForm(formId, beforeSubmitCallback, successCallBack, updateElementId) {
    var form = $("#" + formId);
    var formInfo = new FormInfo(formId, beforeSubmitCallback, successCallBack, updateElementId);
    ChangeToAjaxForm(form, formInfo);
}

function FormInfo(formId, beforeSubmitCallback, successCallBack, updateElementId) {


    this.formId = formId;

    this.options = {};

    if (null != updateElementId && updateElementId != '') {
        this.updateElementId = updateElementId;
        this.options.target = "#" + updateElementId;

    }

    if ("" != successCallBack) {

        this.options.success = ReturnFunction(successCallBack);
    }

    if ("" != beforeSubmitCallback) {
        this.beforeSubmitCallback = ReturnFunction(beforeSubmitCallback);
    }





}

function ReturnFunction(functionSent) {
    if (typeof functionSent == 'function') {
        return functionSent;
    }

    return eval(functionSent);
}

function ChangeToAjaxForm(form, currentFormInfo) {

    form.submit(

                    function () {

                        if ("" != currentFormInfo.beforeSubmitCallback && typeof (currentFormInfo.beforeSubmitCallback) != "undefined")
                            currentFormInfo.beforeSubmitCallback();

                        if (typeof (tinyMCE) != "undefined")
                            tinyMCE.triggerSave(true, true);

                        /*currentFormInfo.options.error = function(XMLHttpRequest, textStatus, errorThrown)
                        {
                        return ShowError(XMLHttpRequest);
                        }*/

                        if ($(currentFormInfo.options.target).length == 0) {
                            alert(currentFormInfo.options.target + " was not found!");
                        }


                        form.ajaxSubmit(currentFormInfo.options);


                        // !!! Important !!! 
                        // always return false to prevent standard browser submit and page navigation 
                        return false;

                    }
                );
}

function ShowError(event, request, settings) {

    var errorMessage = "<div> Error with ajax request: " + settings.url + "<br/><br/>" + request.responseText + "</div>";

    if (ShowAjaxErrors) {
        $("html").html(errorMessage);
    }
    else {
        $("#ShowAjaxErrors").html(errorMessage);
    }

    throw "Error with ajax request" + settings.url;
    return false;

}


var formsLoaded = false;

// wait for the DOM to be loaded
$(document).ready(function () {

    if (formsLoaded == true)
        return;

    var ajaxForms = $(".improvedAjaxForm");


    for (var i = 0; i < ajaxForms.length; i++) {
        form = $(ajaxForms[i]);
        currentFormInfo = new FormInfo(form.attr('id'), form.attr('beforeSubmitCallback'), form.attr('successCallBack'), form.attr('updateElementId'));
        ChangeToAjaxForm(form, currentFormInfo);
    }

    $(document).ajaxError(ShowError);

    formsLoaded = true;
});




function FadeInMessage(query) {

    div = $(query);
    div.stop(true, true);
    div.fadeIn("slow", function () { div.fadeOut(6000); });
}



function GetPage(url, updateElement, callBack) {
    //debugger;
    if (typeof (updateElement) == 'string') {
        updateElement = $("#" + updateElement);


    }



    $.ajax({
        type: "GET",
        url: url,
        async: false,

        /*error: function(XMLHttpRequest, textStatus, errorThrown)
        {
        return ShowError(XMLHttpRequest);
        },*/
        success: function (html) {
            if (updateElement != null) {

                updateElement.html(html);

            }
            if (typeof (callBack) != "undefined") {
                callBack(html);
            }

        }
    });

}



function PopulateDropdown(dataItems, dropDownSelector, clearList) {
    var list = $(dropDownSelector)[0];

    if (clearList == true)
        list.options.length = 0;

    jQuery.each(dataItems, function (i, val) {

        var option = new Option(val, val);
        list.options.add(option);
    });
}




function CustomDialog() {

    var self = this;

    self.Width = "";
    self.Height = "";
    self.InnerDivID = "Inner_" + self.DialogID;

    self.FindOrCreateDialogDiv = function () {
        self.DialogDiv = $("#" + self.DialogID);

        if (self.DialogDiv.length == 0) {

            var divHtml = "<div id=" + self.DialogID + "></div>";

            $("body").append(divHtml);

            self.DialogDiv = $("#" + self.DialogID);

            self.DialogDiv.dialog(
            {
                autoOpen: false
            }
            );

            if (self.Width != "") {
                self.DialogDiv.dialog("option", "width", self.Width);
            }

            if (self.Height != "") {
                self.DialogDiv.dialog("option", "height", self.Height);
            }

            self.DialogDiv.dialog("option", "resizable", false);

            self.DialogDiv.bind('dialogclose', function (event, ui) {
                //remove the dialog from the dom when closed
                self.DialogDiv.remove();
            });
        }
    }

    self.ShowDialog = function () {

        $("body").append("<div id=" + self.InnerDivID + "></div>");
        var innerDiv = $("#" + self.InnerDivID);

        if (self.DialogUrl) {
            GetPage(self.DialogUrl, innerDiv);
        }

        self.FindOrCreateDialogDiv();

        self.DialogDiv.html(innerDiv);

        self.DialogDiv.dialog('open');



    }

    self.CloseDialog = function (event) {
        self.DialogDiv.dialog('close');

    }
}


function UploadifyError(event, ID, fileObj, errorObj) {
    if (errorObj.info == 404)
        alert('Could not find upload script. Use a path relative to: ' + '<?= getcwd() ?>');
    else
        alert('There was an error uploading the file. error ' + errorObj.type + ": " + errorObj.info);
}

    
