﻿//-----------------------------------------------------------------------
// This file is part of the Microsoft Commerce Server Silverlight-based management applications
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT 
// WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING 
// BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// 
// It is required by the Commerce toolbar and it's modules.
//-----------------------------------------------------------------------

function MSCS_ShowHelp(topicId, fullCultureCode) {
    // Maps the id to a help page url then pops up a window for that location.
    // Add cases to support additional topic mappings.

    var url = null;

    switch (topicId) {
        case "MSCSCatalogItemRelationshipEditor":
            url = "http://go.microsoft.com/fwlink/?LinkID=153463";
            break;
        case "MSCSCatalogProductEditor":
            url = "http://go.microsoft.com/fwlink/?LinkId=153473";
            break;
        case "MSCSCatalogCategoryEditor":
            url = "http://go.microsoft.com/fwlink/?LinkId=153474";
            break;
        case "MSCSCatalogImageManager":
            url = "http://go.microsoft.com/fwlink/?LinkId=153475";
            break;
    }

    if (url == null) {
        alert("No help page defined for topic '" + topicId + "' for culture " + fullCultureCode + ". Please contact the system administrator.");
    }
    else {
        var helpWindow = window.open(url, "MSCS_ShowHelpWindow", 'copyhistory=no, directories=yes, height=600, location=yes, menubar=yes, resizable=yes, scrollbars=yes, toolbar=yes, status=yes, width=1000');
    }
}

function GetContext(context) {
    // The Commerce toolbar uses this function to find out if the page is in a certain "context"
    // When the context matches the context required by a module, that module is enabled.

    switch (context) {
        case "Product":
            if (document.getElementById("ProductContext") != null) {
                return true;
            }
            break;
        case "Category":
            if (document.getElementById("CategoryContext") != null) {
                return true;
            }
            break;
        case "CatalogRelationship":
            if ((document.getElementById("CategoryContext") != null) || (document.getElementById("ProductContext") != null)) {
                return true;
            }
            break;
    }

    return false;
}

function MSCS_GetParameter(paramName) {
    // Commerce Silverlight applications call this function to get values based on the current active page.

    switch (paramName) {
        case "CatalogItemId":
            if (MSCS_GetParameter('CatalogItemType') == 'Product') {
                // innerText property is only available on IE, ever other browser uses textContent
                if (document.all) {
                    return document.getElementById('mscs-product-id').innerText;
                }
                else {
                    return document.getElementById('mscs-product-id').textContent;
                }
            }
            else if (MSCS_GetParameter('CatalogItemType') == 'Category') {
                return document.getElementById('Category').value;
            }
            break;
        case "CatalogItemType":
            if (GetContext('Product') == true) {
                return "Product";
            }
            else if (GetContext('Category') == true) {
                return "Category";
            }
            else {
                return null;
            }
            break;
        case "HomeWeb":
            if (document.getElementById("HomeWeb") != null) {
                return document.getElementById("HomeWeb").innerText;
            }
            else {
                return "";
            }
            break;
        case "Catalog":
            if (document.getElementById("Catalog") != null) {
                return document.getElementById("Catalog").value;
            }
            else {
                return "";
            }
            break;
        default:
            return null;
            break;
    }
}

function MSCS_CatalogItemEditorClosed() {
    // This function is called when the Catalog Item Editor window closes
    // It currently reloads the page to display changes but can be modified to suit particular needs.
    window.location.reload(true);
}

function MSCS_CatalogItemRelationshipEditorClosed() {
    // This function is called when the Catalog Item Relationship Editor window closes
    // It currently reloads the page to display changes but can be modified to suit particular needs.
    window.location.reload(true);
}

function MSCS_ProductImageManagerClosed() {
    // This function is called when the Product Image Manager window closes
    // It currently reloads the page to display changes but can be modified to suit particular needs.
    window.location.reload(true);
}


/*

Floating "windows" functionality

*/


/* Mouse event static class */
function MouseEvent() {
    this.sourceElement = null;
    this.pagePosition = { x: 0, y: 0 };
    this.event = null;

    this.getMoveDelta = function(startPoint) {
        return { x: this.pagePosition.x - startPoint.x, y: this.pagePosition.y - startPoint.y };
    }
}

/* Mouse static class */
function Mouse() {
}

/* Static method to obtain mouse information in a non-browser-specific way */
Mouse.getEvent = function(mouseEvent) {
    mouseEvent = mouseEvent || window.event;

    var scrollX = document.body.scrollLeft;
    /* IE returns 0 when using DTD */
    if (scrollX == 0) {
        scrollX = document.documentElement.scrollLeft;
    }
    var scrollY = document.body.scrollLeft;
    /* IE returns 0 when using DTD */
    if (scrollY == 0) {
        scrollY = document.documentElement.scrollTop;
    }

    var newEvent = new MouseEvent();
    newEvent.sourceElement = mouseEvent.srcElement || mouseEvent.target;
    newEvent.pagePosition = { x: mouseEvent.clientX + scrollX,
        y: mouseEvent.clientY + scrollY
    };
    newEvent.event = mouseEvent;
    return newEvent;
}

/* Floater class */
function Floater(id, content, x, y, w, h, minW, minH, isModal, closeHandler) {

    /* Statics */

    if (Floater.allFloaters == null) {
        Floater.allFloaters = Array();
    }

    if (Floater.clearTopmost == null) {
        Floater.clearTopmost = function() {
            for (i = 0; i < Floater.allFloaters.length; i++) {
                if (Floater.allFloaters[i].isTopmost) {
                    Floater.allFloaters[i].isTopmost = false;
                    Floater.allFloaters[i].updatePosition();
                }
            }
        }
    }

    if (Floater.closeAsync == null) {
        Floater.closeAsync = function(floaterId) {
            var exec = function() {
                Floater.forceClose(floaterId);
            }
            window.setTimeout(exec, 100);
        }
    }

    if (Floater.forceClose == null) {
        Floater.forceClose = function(floaterId) {
            for (i = 0; i < Floater.allFloaters.length; i++) {
                if (Floater.allFloaters[i].id == floaterId) {
                    Floater.allFloaters[i].contentContainerElement.innerHTML = "";
                    document.body.removeChild(Floater.allFloaters[i].rootElement);
                    if (Floater.allFloaters[i].isModal) {
                        document.body.removeChild(Floater.allFloaters[i].modalLayer);
                    }
                    Floater.allFloaters.splice(i, 1);
                    break;
                }
            }

            /* Show the Commerce admin toolbar when no "windows" are left */
            if (Floater.allFloaters.length == 0) {
                var adminToolbarElement = document.getElementById("SilverlightToolBar_parent");

                if (adminToolbarElement != null) {
                    /* If IE, put back to it's place. For other browsers, simply set back to visible */
                    if (document.all) {
                        adminToolbarElement.style.position = "static";
                        adminToolbarElement.style.left = "0px";
                        adminToolbarElement.style.width = "100%";
                    }
                    else {
                        adminToolbarElement.style.visibility = "visible";
                    }
                }
            }
        }
    }

    /* End statics */

    var self = this;

    /* Properties */

    this.id = id;
    this.position = { x: x, y: y, z: 0 };
    this.minSize = { x: minW, y: minH };
    this.size = { w: Math.max(w, minW + 2), h: Math.max(h, minH + 52) };
    this.isModal = isModal;
    this.rootElement = document.createElement("div");
    this.rootElement.className = "floaters_rootElement";
    this.rootElement.style.position = "absolute";
    this.modalLayer = document.createElement("div");
    this.modalLayer.className = "floaters_modalLayer";
    this.headerElement = document.createElement("div");
    this.headerElement.className = "floaters_headerElement";
    this.contentContainerElement = document.createElement("div");
    this.contentContainerElement.className = "floaters_contentContainerElement";
    this.isTopmost = true;
    this.moveOffset = { x: 0, y: 0 };
    this.closeHandler = closeHandler;

    this.gripElement = this.headerElement;
    var defaultGripCursor = "move";

    this.gripElement.style.cursor = defaultGripCursor;

    /* End Properties */

    /* Methods */

    this.updatePosition = function() {
        self.rootElement.style.left = this.position.x + "px";
        self.rootElement.style.top = this.position.y + "px";
        if (this.isTopmost) {
            self.modalLayer.style.zIndex = 10000;
            self.rootElement.style.zIndex = 10000;
        } else {
            self.modalLayer.style.zIndex = this.position.z;
            self.rootElement.style.zIndex = this.position.z;
        }
    }

    this.updateSize = function() {
        self.rootElement.style.width = this.size.w + "px";
        self.rootElement.style.height = this.size.h + "px";
        self.contentContainerElement.style.height = this.size.h - 52 + "px";
        self.contentContainerElement.firstChild.style.height = this.size.h - 52 + "px";
    }

    this.close = function() {
        var canClose = true;
        if (self.closeHandler != null) {
            canClose = this.closeHandler(self);
        }

        if (canClose) {
            Floater.forceClose(self.id);
        }
        if (self.isModal) {
            document.onkeydown = null;
        }
    }

    /* End Methods */

    /* Set handlers */

    this.gripElement.onmousedown = function(e) {
        mouseEvent = Mouse.getEvent(e);
        if (mouseEvent.sourceElement == self.gripElement) {
            self.moveOffset = { x: mouseEvent.pagePosition.x - self.position.x, y: mouseEvent.pagePosition.y - self.position.y };
            Floater.clearTopmost();
            self.isTopmost = true;
            self.updatePosition();

            self.gripElement.onmouseup = function(e) {
                document.onmouseup = null;
                document.onmousemove = null;
                self.gripElement.style.cursor = defaultGripCursor;
                return false;
            };

            document.onmouseup = self.gripElement.onmouseup;

            document.onmousemove = function(e) {
                var moveMouseEvent = Mouse.getEvent(e);
                self.position.x = moveMouseEvent.pagePosition.x - self.moveOffset.x;
                self.position.y = moveMouseEvent.pagePosition.y - self.moveOffset.y;
                self.updatePosition();
                return false;
            }
            self.gripElement.style.cursor = "move";
            return false;
        }
        else return true;
    };

    /* End set handlers */

    /* Define "window" UI */

    this.rootElement.style.backgroundColor = "#000000";
    this.rootElement.style.paddingTop = "1px";
    this.rootElement.style.paddingLeft = "1px";
    this.rootElement.style.paddingRight = "1px";
    this.rootElement.style.paddingBottom = "1px";

    this.modalLayer.style.position = "absolute";
    this.modalLayer.style.left = "0px";
    this.modalLayer.style.top = "0px";

    var pageSize = {
        w: Math.max(window.innerWidth || 0, document.body.clientWidth || 0, document.documentElement.clientWidth || 0),
        h: Math.max(window.innerHeight || 0, document.body.clientHeight || 0, document.documentElement.clientHeight || 0)
    };
    this.modalLayer.style.width = pageSize.w + "px";
    this.modalLayer.style.height = pageSize.h + "px";

    this.modalLayer.style.backgroundColor = "black";
    this.modalOpacity = 0.7;
    this.modalLayer.style.opacity = this.modalOpacity;
    this.modalLayer.style.filter = "alpha(opacity=" + this.modalOpacity * 100 + ")";

    this.headerElement.style.height = "30px";
    this.headerElement.style.backgroundColor = "#BBBBBB";
    this.rootElement.appendChild(this.headerElement);

    this.contentContainerElement.style.backgroundColor = "#000000";
    this.contentContainerElement.style.paddingTop = "1px";
    this.contentContainerElement.style.paddingLeft = "1px";
    this.contentContainerElement.style.paddingRight = "1px";
    this.contentContainerElement.style.paddingBottom = "1px";
    this.contentContainerElement.appendChild(content);
    this.rootElement.appendChild(this.contentContainerElement);

    this.closeButton = document.createElement("input");
    this.closeButton.className = "floaters_closeButton";
    this.closeButton.setAttribute("type", "button");
    this.closeButton.style.cssFloat = "right";
    this.closeButton.style.styleFloat = "right";
    this.closeButton.setAttribute("value", "X");
    this.closeButton.style.width = "24px";
    this.closeButton.style.height = "24px";
    this.closeButton.onclick = function() {
        self.close();
        return false;
    }
    this.headerElement.appendChild(this.closeButton);

    this.footerElement = document.createElement("div");
    this.footerElement.className = "floaters_footerElement";
    this.footerElement.style.backgroundColor = "#BBBBBB";
    this.footerElement.style.height = "20px";
    this.rootElement.appendChild(this.footerElement);

    this.sizeGrip = document.createElement("div");
    this.sizeGrip.className = "floaters_sizeGrip";
    this.sizeGrip.style.width = "20px";
    this.sizeGrip.style.height = "20px";
    this.sizeGrip.style.cssFloat = "right";
    this.sizeGrip.style.styleFloat = "right";
    this.sizeGrip.style.cursor = defaultGripCursor;
    this.footerElement.appendChild(this.sizeGrip);

    this.gripMoveOffset = { startPos: { x: 0, y: 0 }, originalSize: { w: 0, h: 0} };

    this.sizeGrip.onmousedown = function(e) {
        var mouseEvent = Mouse.getEvent(e);
        if (mouseEvent.sourceElement == self.sizeGrip) {
            self.gripMoveOffset = {
                startPos: { x: mouseEvent.pagePosition.x,
                    y: mouseEvent.pagePosition.y
                },
                originalSize: {
                    w: self.size.w,
                    h: self.size.h
                }
            };

            self.sizeGrip.onmouseup = function(e) {
                document.onmouseup = null;
                self.closeButton.onmouseup = null;
                self.gripElement.onmouseup = null;
                document.onmousemove = null;
                self.sizeGrip.style.cursor = defaultGripCursor;
                self.size.w = Math.max(self.size.w, self.minSize.x + 2);
                self.size.h = Math.max(self.size.h, self.minSize.y + 52);
                self.updateSize();
                return false;
            };

            document.onmouseup = self.sizeGrip.onmouseup;
            self.closeButton.onmouseup = self.sizeGrip.onmouseup;
            self.gripElement.onmouseup = self.sizeGrip.onmouseup;

            document.onmousemove = function(e) {
                var moveMouseEvent = Mouse.getEvent(e);
                var moveDelta = moveMouseEvent.getMoveDelta(self.gripMoveOffset.startPos);
                self.size.w = Math.max(self.gripMoveOffset.originalSize.w + moveDelta.x, 28);
                self.size.h = Math.max(self.gripMoveOffset.originalSize.h + moveDelta.y, 1 + 52);
                self.updateSize();
                return false;
            }
            self.sizeGrip.style.cursor = "move";
            return false;
        }
        else return true;
    };

    /* End define border */

    /* Finalize and display */
    content.style.zIndex = this.position.z;

    Floater.allFloaters.push(self);
    this.position.z = Floater.allFloaters.length;
    this.updatePosition();
    this.updateSize();

    if (isModal) {
        document.body.appendChild(this.modalLayer);
        document.onkeydown = function(e) {
            /* Disable tab */
            if (event.keyCode == 9) {
                return false;
            }
        };
    }
    document.body.appendChild(this.rootElement);
}

function FloatSilverlight(objectId, xap, initParams, x, y, w, h, minW, minH, isModal, silverlightMethodToRequestClose) {

    if (objectId == null) {
        var randomId = Math.floor(Math.random() * 100000);
        objectId = "randomObjectId" + randomId;
    }

    var floaterId = "floater_" + objectId;

    var content = document.createElement("div");
    content.className = "slContentElement";

    /* Hide the Commerce admin toolbar when the first "window" is spawned */
    if (Floater.allFloaters == null || Floater.allFloaters.length == 0) {
        var adminToolbarElement = document.getElementById("SilverlightToolBar_parent");

        if (adminToolbarElement != null) {
            /* If IE, shrink and move offscreen. For other browsers, simply make invisible */
            if (document.all) {
                adminToolbarElement.style.position = "absolute";
                adminToolbarElement.style.left = "-1px";
                adminToolbarElement.style.width = "1px";
            }
            else {
                adminToolbarElement.style.visibility = "hidden";
            }
        }
    }

    /* The Silverlight application must execute the script provided in the onClose initparam when it wishes to "close" it's container */
    initParams = "onClose=Floater.closeAsync(\'" + floaterId + "\')," + initParams;

    content.innerHTML =
        "<object id=\"" + objectId + "\" data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" width=\"100%\" height=\"100%\">" +
        "	<param name=\"source\" value=\"" + xap + "\"/>" +
        "	<param name=\"initParams\" value=\"" + initParams + "\" />" +
        "	<param name=\"onerror\" value=\"onSilverlightError\" />" +
        "	<param name=\"background\" value=\"white\" />" +
        "	<param name=\"windowless\" value=\"false\" />" +
        "	<param name=\"minRuntimeVersion\" value=\"3.0.40624.0\" />" +
        "	<a href=\"http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0\" style=\"text-decoration: none;\">" +
        "		<img src=\"http://go.microsoft.com/fwlink/?LinkId=108181\" alt=\"Click here to install Silverlight\" style=\"border-style: none\"/>" +
        "	</a>" +
        "</object>";

    var closeHandler = function(floater) {
        if (silverlightMethodToRequestClose != null) {
            try {
                /* The Silverlight application must expose the following method */
                return eval("document.getElementById(objectId).Content." + silverlightMethodToRequestClose);
            } catch (exc) {
            }
        }
        return true;
    }

    var newFloater = new Floater(floaterId, content, x, y, w, h, minW, minH, isModal, closeHandler);

    return newFloater;
}

/* Example usage of FloatSilverlight */
function EditRelationship(relName) {

    var initParams = "CatalogItemRelationshipToEdit=CrossSells,Catalog=Adventure Works Catalog,CatalogItemType=Product,CatalogItemId=AW390-12";
    return FloatSilverlight(null, "/ClientBin/SilverlightApplication1.xap", initParams, 40, 30, 800, 600, true, "App.RequestClose()");
}

/*

END Floating "windows" functionality

*/


// Loads CatalogItemEditor from serach result page.
function MSCS_LoadProductEdit(initParams) {
    initParams += ",ResourceFileUris=CsManagementResources.xml MicrosoftCommerceCatalogItemEditorResources.xml";

    var xap = "/ClientBin/MicrosoftCommerceCatalogItemEditor.xap";
    var id = "EditProduct";

    return FloatSilverlight(id, xap, initParams, 40, 30, 800, 700, 800, 600, true, "App.RequestClose()");
}

// Make Edit Product Button visible on Serach Result page.
function MSCS_EnableEditButton() {
    var inputs = document.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs.item(i).getAttribute('name') == 'inputEditButton') {
            inputs.item(i).style.display = 'block';
        }
    }
}

