﻿//a way of keeping object context after an ajax callback
//http: //knol.google.com/k/jason/jquery-callback-contexts/1fk6f8qeqtvqa/2?domain=knol.google.com&locale=en#
// $.context
jQuery.extend(
{
    context: function (context) {
        var co =
    {
        callback: function (method) {
            if (typeof method == 'string') method = context[method];
            var cb = function () { method.apply(context, arguments); }
            return cb;
        }
    };
        return co;
    }
});

function MyLib() {
}

MyLib.CopyProperties = function (CopyFrom, CopyTo) {
    for (var key in CopyFrom) {
        //references are kept
        CopyTo[key] = CopyFrom[key];
    }
};

function GenericErrorFunction(xhr, textStatus, errorThrown, ErrorFunction) {
    $("#loading").hide();
    if (ErrorFunction != undefined)
        ErrorFunction(xhr, textStatus, errorThrown);
    else
        alert('statuscode=' + xhr.statusCode + '/' + 'status=' + xhr.status + '/' + 'textstatus=' + textStatus + '/' + 'errorthrown=' + errorThrown + '/' + 'statustext=' + xhr.statusText + "/" + 'responsetext=' + xhr.responseText);
}

function GenericSuccessFunction(data, SuccessFunction) {
    $("#loading").hide();
    if (data.JsonResultInfo.NotAuthorized == true)
        alert("You are not authorized to do this");
    else if (data.JsonResultInfo.ErrorOccurred == true) {
        //display all error messages eventually
        alert("Error: " + data.JsonResultInfo.ErrorMessages[0]);
    }
    else if (SuccessFunction != undefined)
        SuccessFunction(data);
}

function AjaxPost(url, data, SuccessFunction, ErrorFunction) {
    $("#loading").show();
    $.ajax({ type: "POST", data: data, url: url, dataType: "json", success: function (data) { GenericSuccessFunction(data, SuccessFunction) }, error: function (xhr, textStatus, errorThrown) { GenericErrorFunction(xhr, textStatus, errorThrown, ErrorFunction) } });
}

function TemplateList() {
    this.CurPage = 1;
    this.NumRecords = -1;
    this.NumPages = -1;
    this.RecordsPerPage = 5;
    this.SortBy = "";
    this.Search = "";
    this.SearchElementID = null;
    this.SortElementID = null;
    this.CountURL = "";
    this.ListURL = "";
    this.AdditionalData = null;
    this.Template = null;
    this.CurPageElementID = null;
    this.NumPagesElementID = null;
    this.Records = null;

    this.Initialize = function (PageNumber, SortOrder, AdditionalData) {
        this.CurPage = PageNumber;
        this.SortBy = SortOrder;
        this.AdditionalData = AdditionalData;
    }

    this.GetItems = function () {
        if (this.NumRecords > -1 || this.CountURL == "") {
            var data = { Page: this.CurPage, NumPerPage: this.RecordsPerPage, SortOrder: this.SortBy };
            MyLib.CopyProperties(this.AdditionalData, data);
            AjaxPost(this.ListURL, data, $.context(this).callback('GetItemsSuccess'));
        }
        else {
            this.GetItemCount();
        }
    }

    this.GetItemsSuccess = function (result) {
        if (this.CurPageElementID != null)
            $("#" + this.CurPageElementID).text(this.CurPage);
        this.Records = result.Result.Records;
        $get(this.Template).activeData = true;
        $find(this.Template).set_data(this.Records);
    }

    this.GetItemCount = function () {
        var data = { Page: this.CurPage, NumPerPage: this.RecordsPerPage, SortOrder: this.SortBy };
        MyLib.CopyProperties(this.AdditionalData, data);
        AjaxPost(this.CountURL, data, $.context(this).callback('GetItemCountSuccess'));
    }

    this.GetItemCountSuccess = function (result) {
        this.NumRecords = result.Result;
        this.NumPages = parseInt((this.NumRecords - 1) / this.RecordsPerPage) + 1;
        //go back to page one if we're at a page that doesn't exist
        //this works because we get items later after getting the count
        if (this.NumPages < this.CurPage)
            this.CurPage = 1;
        if (this.NumPagesElementID != null)
            $('#' + this.NumPagesElementID).text(this.NumPages);
        this.GetItems();
    }

    this.WirePrevious = function (ele) {
        $(ele).click($.context(this).callback('PreviousClick'));
    }

    this.WireNext = function (ele) {
        $(ele).click($.context(this).callback('NextClick'));
    }

    this.WireRefresh = function (ele) {
        $(ele).click($.context(this).callback('RefreshClick'));
    }

    this.RefreshClick = function () {
        this.Refresh();
    }

    this.Refresh = function () {
        this.NumRecords = -1;
        this.CurPage = 1;
        if (this.SearchElementID != null)
            this.Search = $("#" + this.SearchElementID).val();
        if (this.SortElementID != null)
            this.SortBy = $("#" + this.SortElementID).val();
        this.GetItems();
    }

    this.PreviousClick = function () {
        if (this.CurPage > 1) {
            this.CurPage--;
            this.GetItems();
        }
    }

    this.NextClick = function () {
        if (this.CurPage < this.NumPages) {
            this.CurPage++;
            this.GetItems();
        }
    }

    this.ChangeTemplate = function (Template) {
        if (this.Template != null) {
            $get(this.Template).activeData = false;
            $find(this.Template).set_data(null);
        }
        this.Template = Template;
        {
            var t = $find(this.Template);
            $get(this.Template).activeData = true;
            $find(this.Template).set_data(this.Records);
        }
    }
}