﻿//AJAX error
function ServiceCallError(XMLHttpRequest, textStatus, errorThrown) {
    alert("Sorry, we are unable to process your request at this time.");
    //alert(XMLHttpRequest);
    //alert(textStatus);
}

//Add a Book Edition to the cart
//viewPath: route to the AddToCart action including the bookEdition Id
//viewPathQuickViewCart: route to the QuickViewCart Action
//viewPathCart: route to the Shopping Cart Action
//redirectToCart: boolean value on whether to redirect to the cart after adding an item
function AddToCart(viewPath, viewPathQuickViewCart, viewPathCart, redirectToCart) {
    
    //Show AJAX Animation
    showAnimation("", true, "Adding to Cart...");

    //successful ajax call
    var successCallback = function(data) {

        //Update the QuickView cart count
        UpdateQuickViewCart(viewPathQuickViewCart)

        //Hide AJAX Animation
        hideAnimation();

        //Redirect to shopping cart if necessary
        if (redirectToCart) {
            location.href = viewPathCart;
        }

    };

    //Update the Cart
    $.ajax({
        type: "GET",
        url: viewPath,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            ServiceCallError(XMLHttpRequest, textStatus, errorThrown);
        },
        success: successCallback
    });

}

//Clear all input fields that are children of this element
function ClearFields(elementId) {

    //Clear all Input fields
    $("#" + elementId).find("input").each(function() {
        $(this).val("");
    });

    //Clear out Textareas
    jQuery("#CalendarAdminDetail").find("textarea").each(function() {
        $(this).val("");
    });

    //Clear Selects
    jQuery("#CalendarAdminDetail").find("select").each(function() {
        $(this).empty();
    });

}

//Update the QuickView cart count
function UpdateQuickViewCart(viewPathQuickViewCart) {

    //used to prevent caching in IE
    var random = new Date().getTime();
    
    $("#QuickViewCart").load(viewPathQuickViewCart + "/" + random);

}

//String Buffer to make building strings faster
//http://www.softwaresecretweapons.com/jspwiki/javascriptstringconcatenation
function StringBuffer() {
    this.buffer = [];
}

StringBuffer.prototype.append = function append(string) {
    this.buffer.push(string);
    return this;
};

StringBuffer.prototype.toString = function toString() {
    return this.buffer.join("");
};

//Format currency
function formatCurrency(num) {

    num = num.toString().replace(/\$|\,/g, '');

    if (isNaN(num)) {
        num = "0";
    }

    sign = (num == (num = Math.abs(num)));

    num = Math.floor(num * 100 + 0.50000000001);

    cents = num % 100;

    num = Math.floor(num / 100).toString();

    if (cents < 10) {
        cents = "0" + cents;
    }

    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    }
        
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

//Replace all parameters with there appropriate values (used for URL.RouteUrl() in asp.net MVC)
function buildRouteUrl(urlString, parametersJSON) {

    for (var parameter in parametersJSON) {

        if (parameter != undefined) {
        
            //Replace parameters
            urlString = urlString.replace("%5B" + parameter + "%5D", parametersJSON[parameter]);
        }
    
    }

    return urlString;

}

//Initialize the Overlay
function initializeOverlay() {

    //Setup the Overlay
    $("#SiteOverlay").overlay({
        expose: {
            color: '#333',
            loadSpeed: 200,
            opacity: 0.9
        },
        onClose: function() {
            $("#SiteOverlayContent").unbind();
            $("#SiteOverlayContent").html("");
        }
    });

}

//Load the Overlay
function getOverlay() {

    return $("#SiteOverlay").overlay();
    
}

//Load the Overlay
    //viewPath:         route to the action to load
    //overlayHeight:    height of overlay
    //overlayWidth:     width of overlay
    //callback:         callback function
function loadOverlay(viewPath, overlayHeight, overlayWidth, callback) {

    $("#SiteOverlayContent").css("height", overlayHeight);
    $("#SiteOverlayContent").css("width", overlayWidth);

    //Get the overlay
    var overlayAPI = $("#SiteOverlay").overlay();

    overlayAPI.load();

    //Load overlay content
    $("#SiteOverlayContent").load(viewPath, "", function() { eval(callback); });
}

//Set up the Drag and Drop stuff
    //itemIdAttribute:      html attribute name that contains the Id of the item to be deleted
    //itemDisplayAttribute: html attribute name that contains the Display of the item to be deleted
    //recycleImagePath:     path to the recycle image
function setupAdminDragDrop(itemIdAttribute, itemDisplayAttribute, recycleImagePath) {

    //Set up the Draggable Author
    $(".draggableDeleteItem").draggable({
        revert: "invalid", // when not dropped, the item will revert back to its initial position
        containment: $("#demo-frame").length ? "#demo-frame" : "document", // stick to demo-frame if present
        helper: "clone",
        cursor: "move"
    });

    //Unbind Droppable so we don't get multiple hookups
    $(".adminTrash").unbind("droppable");

    //Set up the Droppable author rows
    $(".adminTrash").droppable({
        accept: ".draggableDeleteItem",
        activeClass: "ui-state-highlight",
        drop: function(ev, ui) {
            addItemToTrash(ui.draggable, itemIdAttribute, itemDisplayAttribute, recycleImagePath);
        },
        hoverClass: "ui-state-active"
    });
}

//Add Item to the Trash
    //$item:                jQuery item passed on the jQuery UI Drop 
    //itemIdAttribute:      html attribute name that contains the Id of the item to be deleted
    //itemDisplayAttribute: html attribute name that contains the Display of the item to be deleted
    //recycleImagePath:     path to the recycle image
function addItemToTrash($item, itemIdAttribute, itemDisplayAttribute, recycleImagePath) {

    //Add Item to Trash
    var itemId = $item.attr(itemIdAttribute);
    var itemDisplay = $item.attr(itemDisplayAttribute);

    //Check if item is already in trash
    if ($("#TrashItems li[" + itemIdAttribute + "='" + itemId + "']").length <= 0) {

        $("#TrashItems").append("<li " + itemIdAttribute + "='" + itemId + "'>" +
                                    "<a onclick='removeItemFromTrash(\"" + itemIdAttribute + "\", \"" + itemId + "\")' style='cursor: pointer; margin-right: 10px;'>" +
                                        "<img src='" + recycleImagePath + "' title='Undo Delete' style='border: none; height: 16px;' />" +
                                    "</a>" +
                                    itemDisplay +
                                "</li>");
    }
}

//Remove Author from the Trash
    //itemIdAttribute:      html attribute name that contains the Id of the item to be deleted
    //itemId:               id to be removed
function removeItemFromTrash(itemIdAttribute, itemId) {
    //Remove Item from Trash
    $("#TrashItems li[" + itemIdAttribute + "='" + itemId + "']").remove();
}

//Delete all Authors in the Trash
    //animationMessage:     Message to display with animation
    //itemIdAttribute:      html attribute name that contains the Id of the item to be deleted
    //deleteViewPath:       Path to the Action to delete
function emptyTrash(animationMessage, itemIdAttribute, deleteViewPath) {

    //Show AJAX Animation
    showAnimation("", true, animationMessage);

    var itemsToDelete = [];

    $("#TrashItems li").each(function(index) {
        itemsToDelete.push($(this).attr(itemIdAttribute));
    });

    //successful ajax call
    var successCallback = function(data) {

        //Hide AJAX Animation
        hideAnimation();

        //Clear out Trash display items
        $("#TrashItems").html("");

        //Update the Results list
        updateResults(0, true);

    };

    //Build RouteUrl
    var routeUrl = deleteViewPath;
    var parametersJSON = { id: itemsToDelete.join(",") };
    
    $.ajax({
        type: "GET",
        dataType: "html",
        url: buildRouteUrl(routeUrl, parametersJSON),
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            ServiceCallError(XMLHttpRequest, textStatus, errorThrown);
        },
        success: successCallback
    });

}

