﻿//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
$.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.DateDiff = function(date1, date2, interval) {
    var second = 1000, minute = second * 60, hour = minute * 60, day = hour * 24, week = day * 7;
    var timediff = date2 - date1;
    if (isNaN(timediff)) return NaN;
    switch (interval) {
        case "years": return date2.getFullYear() - date1.getFullYear();
        case "months": return (
            (date2.getFullYear() * 12 + date2.getMonth())
            -
            (date1.getFullYear() * 12 + date1.getMonth())
        );
        case "weeks": return Math.floor(timediff / week);
        case "days": return Math.floor(timediff / day);
        case "hours": return Math.floor(timediff / hour);
        case "minutes": return Math.floor(timediff / minute);
        case "seconds": return Math.floor(timediff / second);
        case "milliseconds": return timediff;
        default: return undefined;
    }
}

MyLib.EqualHeight = function(group) {
    tallest = 0;
    group.each(function () {
        thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}

MyLib.CopyProperties = function(CopyFrom, CopyTo) {
    for (var key in CopyFrom) {
        //references are kept
        CopyTo[key] = CopyFrom[key];
    }
};

function SwapImage(imgId) {
    var img = $("#" + imgId);

    img.hover(function () {
        img.attr("src", img.attr("src").replace(/_off/, "_on"));
    }, function () {
        img.attr("src", img.attr("src").replace(/_on/, "_off"));
    });  
}

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.GetItems = function() {
        if (this.NumRecords > -1 || this.CountURL == "") {
            var data = { Page: this.CurPage, NumPerPage: this.RecordsPerPage, SortOrder: this.SortBy, Search: this.Search };
            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 = { Search: this.Search };
        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;
        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.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);
        }
    }
}