﻿//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);
        }
    }
}

function CreateMegaMenu() {
    function megaHoverOver() {
        $('.hidewithmenu').hide();
        $(this).find(".sub").stop().fadeTo('fast', 1).show();

        //Calculate width of all ul's
        (function ($) {
            jQuery.fn.calcSubWidth = function () {
                rowWidth = 0;
                //Calculate row
                $(this).find('ul').each(function () {
                    rowWidth += $(this).width();
                });
            };
        })(jQuery);

        if ($(this).find(".row").length > 0) { //If row exists...
            var biggestRow = 0;
            //Calculate each row
            $(this).find(".row").each(function () {
                $(this).calcSubWidth();
                //Find biggest row
                if (rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });
            //Set width
            $(this).find(".sub").css({ 'width': biggestRow });
            $(this).find(".row:last").css({ 'margin': '0' });

        } else { //If row does not exist...

            $(this).calcSubWidth();
            //Set Width
            $(this).find(".sub").css({ 'width': rowWidth });
        }

        if ($(this).find(".sub").offset().left + $(this).find(".sub").width() - 50 > $('#CatalogMenuBar').offset().left + $('#CatalogMenuBar').width()) {
            var leftAdjust = $(this).find(".sub").offset().left + $(this).find(".sub").width() - 50 - $('#CatalogMenuBar').offset().left - $('#CatalogMenuBar').width();
            $(this).find(".sub").css({ 'left': -leftAdjust });
        }
        else if ($(this).find(".sub").offset().left == $('#CatalogMenuBar').offset().left) {
            $(this).find(".sub").css({ 'left': 10 });

        }

    }

    function megaHoverOut() {
        $(this).find(".sub").stop().fadeTo('fast', 0, function () {
            $(this).hide();
            $('.hidewithmenu').show();
        });
    }


    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
        interval: 150, // number = milliseconds for onMouseOver polling interval    
        over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
        timeout: 50, // number = milliseconds delay before onMouseOut    
        out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
    };

    $("ul#topnavmm li .sub").css({ 'opacity': '0' });
    $("ul#topnavmm li").hoverIntent(config);
}

function ChangeBundleQuantity(BundleID, Quantity, AddToExistingQuantity) {
    if (isNumber(Quantity)) {
        if (Quantity < 1)
            alert("Quantity must be at least 1");
        else
            window.location = "/cart.mvc/AddBundleToCart?BundleID=" + BundleID + "&Quantity=" + Quantity + "&AddToExistingQuantity=" + AddToExistingQuantity;
    }
    else {
        window.alert("You must input a valid quantity");
    }
}

function ChangeItemQuantity(ProductID, Attributes, Quantity, AddToExistingQuantity) {
    if (isNumber(Quantity)) {
        if (Quantity < 1)
            alert("Quantity must be at least 1");
        else
            window.location = "/cart.mvc/AddItemToCart?ProductID=" + ProductID + "&Attributes=" + Attributes + "&Quantity=" + Quantity + "&AddToExistingQuantity=" + AddToExistingQuantity;
    }
    else {
        window.alert("You must input a valid quantity");
    }
}

function RemoveBundle(BundleID) {
    window.location = "/cart.mvc/RemoveBundleFromCart?BundleID=" + BundleID;
}

function RemoveItem(ProductID, Attributes) {
    window.location = "/cart.mvc/RemoveItemFromCart?ProductID=" + ProductID + "&Attributes=" + Attributes;
}

function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); }

