/**
 * @author Fahrettin Kutyol
 * This is the rebuilt for dojo 1.2.x of the former 0.4 widget by Josip Delic.
 * This widget had to be coded from scratch, because the fundamental design of widgets
 * had been changed since dojo 0.9.x. Unlike to the old version this widget doesn't extend
 * a tooltip widget.
 *
 *  Summary:
 *  loads shopcard via xhr and provides the content by a roll out and roll back animation.
 *
 *  Receiving tag attributes:
 *  'href' : The url where to fetch the information pane content
 *  'connectId': The node where to connect main actions
 */
dojo.provide("haufedojo.widget.shopcard");

// debug now goes that way.
console.debug("providing haufe.widget.shopcard");

// requirering the refactored widget superclass
dojo.require("dijit.z_Widget");
//dojo.require("haufedojohelp.data.HaufeUtils");

// building the widget class
dojo.declare("haufedojo.widget.shopcard", //our subclass
 dijit.z_Widget, // superclasses
{
    href: "", // get information from this url
    connectId: "", // bind primary mouse events to this id - EOF receiving tag attributes
    init: true, // if true, fires an action by the first mouseover
    connectNode: undefined, // node of the connectId
    endHeight: 0, // Height where the animation ends
    isShowing: false, // does the information show
    comingFromContent: false,// if a mouse over got fired this is how to test if it's reffering from the information pane
    rollBackTimer: undefined, // the timer to delay the roll back animation
    rollBackDelay: 200, // delay until roll back gets fired
    shadowNode: undefined, // shadow node
    shadowMargin: 4, // margin of the shadow
    isLoaded: false, // Wait until content is loaded
    // Called after Constructor
    postCreate: function(){
        // this is needed to check the domain
        this.haufeUtils = new haufedojohelp.data.HaufeUtils();

        // getting the widget css
        this.importCss("/haufedojo/widget/shopcard.css");

        this.domNode.className = "dojoShoppingCard";

        this.connectNode = dojo.byId(this.connectId);
        this.connectNode.style.zIndex = "1001";

        // creating the shadow element
        this.shadowNode = document.createElement("DIV");
        this.shadowNode.id = "myCardShadow";
        var shadowStyle = this.shadowNode.style;
        shadowStyle.position = "absolute";
        shadowStyle.display = "block";
        shadowStyle.visibility = "hidden";
        shadowStyle.backgroundColor = "black";
        dojo._setOpacity(this.shadowNode, 0.4);
        dojo.body().appendChild(this.shadowNode);

        // Callback function to set xhr response and adjust some boundings
        var callback = dojo.hitch(this, function(response, ioArgs){
            this.domNode.innerHTML = response;
            var connectBounds = dojo.coords(this.connectNode, true);
            var contentBounds = dojo.coords(this.domNode, true);

            dojo.body().appendChild(this.domNode);
            var leftPosition = Math.round(connectBounds.x + connectBounds.w - contentBounds.w);


            this.shadowNode.style.width = contentBounds.w + "px";
            this.domNode.style.visibility = "hidden";
            this.haufeUtils.widenDomain();
            console.debug("Document Domain: " + document.domain);
            if (document.domain === "lexware.de") {
                var lexwareMagicX = 132;
                var lexwareMagicY = 2;
                this.shadowNode.style.left = (leftPosition + this.shadowMargin + lexwareMagicX) + "px";
                this.domNode.style.left = (leftPosition + lexwareMagicX) + "px";
                this.domNode.style.top = (contentBounds.y + lexwareMagicY) + "px";
                this.shadowNode.style.top = (contentBounds.y + this.shadowMargin + lexwareMagicY) + "px";
            }
            else {
                this.shadowNode.style.left = (leftPosition + this.shadowMargin) + "px";
                this.domNode.style.left = leftPosition + "px";
                this.domNode.style.top = contentBounds.y + "px";
                this.shadowNode.style.top = (contentBounds.y + this.shadowMargin) + "px";
            }
            this.isLoaded = true;
        })

        // Loading the content using href
        dojo.xhrGet({
            url: this.href,
            load: callback,
            error: function(response, ioArgs){
                console.log("Failed XHR: ", response, ioArgs);
            }
        });
        // binding events to connectId
        this.connect(this.connectNode, "onmouseover", "onMouseOver");
        this.connect(this.connectNode, "onmouseout", "onMouseOut");
        // binding events to the content node
        this.connect(this.domNode, "onmouseover", "contentMouseOver");
        this.connect(this.domNode, "onmouseout", "contentMouseOut");
        // binding event if window resize
        this.connect(window, "onresize", "windowResize");


    },

    // Internal widget css requirement doesn't exist anymore in dojo 1.x
    // This is a hack to import a css file
    importCss: function(fileName){
        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", fileName);
        if (typeof fileref != "undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref);
    },

    // Connect node mouse over
    onMouseOver: function(evt){
        // cancel until content is loaded
        if (!this.isLoaded)
            return;

        // initializing the height by first call. needed because the real height can not be
        // fetched after loading of the content.
        if (this.init) {
            var newHeight = dojo.coords(this.domNode, true).h - this.shadowMargin;
            this.endHeight = newHeight;
            this.shadowNode.style.height = (newHeight + this.shadowMargin) + "px";
            this.init = false;
        }

        // cancelling the roll back timer
        if (this.rollBackTimer) {
            clearTimeout(this.rollBackTimer);
            this.rollBackTimer = undefined;
        }

        // cancelling mouse over animation if content already shows
        if (this.isShowing || this.comingFromContent)
            return;

        // content roll out animation
        dojo.animateProperty({
            node: this.domNode,
            properties: {
                height: {
                    start: '0',
                    end: this.endHeight,
                    unit: 'px'
                }
            },
            onPlay: dojo.hitch(this, function(){
                this.isShowing = true;
                this.domNode.style.visibility = "visible";
            }),
            onEnd: dojo.hitch(this, function(){

            })
        }).play();

        // shadow roll out animation
        dojo.animateProperty({
            node: this.shadowNode,
            properties: {
                height: {
                    start: '0',
                    end: this.endHeight + this.shadowMargin,
                    unit: 'px'
                }
            },
            onPlay: dojo.hitch(this, function(){
                this.shadowNode.style.visibility = "visible";
            }),
            onEnd: dojo.hitch(this, function(){

            })
        }).play();
    },

    // Connect node mouse out
    onMouseOut: function(evt){
        // cancel until content is loaded
        if (!this.isLoaded)
            return;

        // providing a delay
        this.rollBackTimer = setTimeout(dojo.hitch(this, this.onMouseOutFollow), this.rollBackDelay);
    },

    // Follow up after delay function for connect node mouse out
    onMouseOutFollow: function(){
        // content roll back animation
        dojo.animateProperty({
            node: this.domNode,
            properties: {
                height: {
                    start: this.endHeight,
                    end: '0',
                    unit: 'px'
                }
            },
            onPlay: dojo.hitch(this, function(){
            }),
            onEnd: dojo.hitch(this, function(){
                this.domNode.style.visibility = "hidden";
                this.comingFromContent = false;
                this.isShowing = false;
            })
        }).play();

        // shadow roll back animation
        dojo.animateProperty({
            node: this.shadowNode,
            properties: {
                height: {
                    start: this.endHeight + this.shadowMargin,
                    end: '0',
                    unit: 'px'
                }
            },
            onPlay: dojo.hitch(this, function(){
            }),
            onEnd: dojo.hitch(this, function(){
                this.shadowNode.style.visibility = "hidden";
            })
        }).play();
    },

    // content node mouse over
    contentMouseOver: function(evt){
        this.isShowing = true;
        if (this.rollBackTimer) {
            clearTimeout(this.rollBackTimer);
            this.rollBackTimer = undefined;
        }
    },

    // content node mouse out
    contentMouseOut: function(evt){
        this.comingFromContent = true;
        this.rollBackTimer = setTimeout(dojo.hitch(this, this.onMouseOutFollow), this.rollBackDelay);
    },

    // fired if window resizes. adjusting the left position
    windowResize: function(evt){
        var bounds = dojo.coords(this.connectNode, true);
        var contentBounds = dojo.coords(this.domNode, true);
        var leftPosition = Math.round(bounds.x + bounds.w - contentBounds.w);
        this.domNode.style.left = leftPosition + "px";
        dojo.byId("myCardShadow").style.left = (leftPosition + this.shadowMargin) + "px";
    }
});

