/*
 * this function determines whether the event is the equivalent of the microsoft
 * mouseleave or mouseenter events.
 *
 * http://www.dynamic-tools.net/toolbox/isMouseLeaveOrEnter
 */
function isMouseLeaveOrEnter(e, handler) {
    if (e.type != 'mouseout' && e.type != 'mouseover')
    return false;

    var reltg = e.relatedTarget
                ? e.relatedTarget
                : e.type == 'mouseout'
                  ? e.toElement
                  : e.fromElement;

    while(reltg && reltg != handler)
    reltg = reltg.parentNode;

    return (reltg != handler);
}

/******************************************************************************/

var Collectbox = Class.create();
Collectbox.prototype = {

    instanceExists: false,

    initialize: function(doShow) {

        console.log('Collectbox.initialize()');

        if(Collectbox.instanceExists) {
            console.log('Collecbox instance already exists, doing nothing');
            return false;
        }
        Collectbox.instanceExists = true;

        console.log('open button');

        this.openButton = $('openCollectionButton');

        console.log('dummy button');

        this.openButtonSrc  = '/images/portfolio_button.gif';
        this.dummyButtonSrc = '/images/portfolio_button_dummy.gif';

        console.log('preload dummy');

        // Preload
        //console.log('make instance');
        //var fooImage = new Image();

        //console.log('load');
        //fooImage.src = dummyButtonSrc;

        //this.openButtonDimensions = new Array(this.openButton.width, this.openButton.height);

        console.log('OBSrc: ' + this.openButtonSrc);

        this.closeButton = $('closeCollectionButton');

        console.log('create spinner');

        this.spinner = new Image();
        this.spinner.src = '/images/spinner_collectbox.gif';
        this.spinner.width = this.spinner.height = 16;

        this.background = $('bgTransparent');
        //this.outerFrame = $('collectionOpen');
        this.innerFrame = $('collectionIMG');

        console.log('Binding events');
        Event.observe(this.openButton, 'click', function() {

            console.log('Click openbutton');

            this.background.show();
            //this.outerFrame.show();
            this.innerFrame.show();

            $$('#openCollectionButton img').first().src = this.dummyButtonSrc;
            //$('closeCollectionButton').show();

        }.bind(this));

        Event.observe(this.closeButton, 'click', function() {

            this.background.hide();
            this.innerFrame.hide();
            //this.outerFrame.hide();

            /*new Effect.Parallel([
                new Effect.Fade(this.outerFrame, { duration: 0.5 }),
                new Effect.Fade(this.innerFrame, { duration: 0.5 })
            ]);*/

            $$('#openCollectionButton img').first().src = this.openButtonSrc;
            //$('closeCollectionButton').hide();

        }.bind(this));

        this.reloadContent();

        if(doShow) {
            //alert('showme');
            this.show();
        }
    },

    show: function() {
        this.background.show();
        //this.outerFrame.show();
        this.innerFrame.show();

        $$('#openCollectionButton img').first().src = this.dummyButtonSrc;
    },

    addBookmark: function(areaId) {

        console.log('Collectbox.addBookmark()');

        //this.updateStart();

        var url = '/index.php?area=products&addBookmark&type=product&name='+areaId;
        new Ajax.Request(url, {
            onSuccess: function() {
                this.reloadContent();
            }.bind(this)
        });
    },

    removeBookmark: function(event) {

        console.log('Collectbox.removeBookmark()');

        if(!event)
        event = window.event;

        var link = Event.findElement(event, 'a');

        console.log('Element: ' + $(link).inspect());

        if(!link.id)
        return;

        var typeId = link.id.split('_');
        var type = typeId[0];
        var id   = typeId[1];

        this.updateStart();

        var url = '/index.php?area=products&removeBookmark&id='+id;

        if(type == 'p') {
            url += '&type=product';
        } else {
            url += '&type=variant';
        }

        new Ajax.Request(url, {
            onSuccess: function() {
                this.reloadContent();
            }.bind(this)
        });
    },

    reloadContent: function() {

        console.log('Collectbox.reloadContent()');

        this.updateStart();

        var container = $('collectboxContent');

        var url = '/products.php?getBookmarks';
        new Ajax.Request(url, {
            onSuccess: function(t, json) {

                console.log('got response');
                container.update(t.responseText);

                console.log('update content');
                $('collectbox_size').update(json.box_size);

                console.log('fade');
                if(json.box_size > 0) {
                    new Effect.Appear($('collection_sidebar'), { duration: 0.75 })
                } else {
                    new Effect.Fade($('collection_sidebar'), { duration: 0.75 })
                }

                console.log('hide spinner');
                this.updateFinish();

                //if(doShow)
                //this.show();

                $$('.quotebutton').each(function(link) {
                    var id = link.id.split('_')[1];

                    var url = new Template(
                        '/products.php?show=subprod&id=#{id}&addToBasket=#{id}'
                    ).evaluate({ id: id });

                    link.onclick = function() {
                        //this.updateStart();

                        new Ajax.Request(url, {
                            onSuccess: function() {

                                if(quoteBasket)
                                quoteBasket.update();

                                this.reloadContent();

                            }.bind(this)
                        });

                    }.bind(this);
                }.bind(this));

                $$('.collectbox_remove_button').each(function(link) {

                    if(!link.id)
                    return;

                    $(link).observe('click', this.removeBookmark.bindAsEventListener(this));

                }.bind(this));

                this.dirty = false;
            }.bind(this)
        });
    },

    updateStart: function() {

        console.log('Collectbox.updateStart()');

        try {

            var openImage = $$('#openCollectionButton img').first();

            openImage.width = this.spinner.width;
            openImage.height = this.spinner.height;
            openImage.src = this.spinner.src;

            /*this.openButton.width  = this.spinner.width;
            this.openButton.height = this.spinner.height;
            this.openButton.src    = this.spinner.src;*/

            console.log('Set openButton to ' + this.spinner.src);

            /*this.openButtonWasVisible = this.openButton.visible();
            this.openButton.show();*/

        } catch(e) {}
    },

    updateFinish: function() {

        console.log('Collectbox.updateFinish()');

        try {

            var openImage = $$('#openCollectionButton img').first();

            openImage.width = 17;
            openImage.height = 20;

            console.log('switch img src to ' + this.openButtonSrc);

            openImage.src = this.openButtonSrc;


            /*
            this.openButton.width  = this.openButtonDimensions[0];
            this.openButton.height = this.openButtonDimensions[1];
            this.openButton.src    = this.openButtonSrc;
            */

            console.log('updateFinish: Set openButton to ' + this.openButtonSrc);

            /*if(!this.openButtonWasVisible)
            this.openButton.hide();*/

        } catch(e) {}
    }

}

/******************************************************************************/

var collectboxFrame = null;
var collectboxImg   = null;
var basket          = null;

function initSlidebox(doShow) {

    console.log('initSlidebox()');

    // Only do this if elements exist (ie we're in devmode or bookmark feature is live)
    try { basket = new Collectbox(doShow); } catch(e) {  }
}

/******************************************************************************/

/*Event.observe(window, 'load', function() {
    initSlidebox();

    try { initDetailsPage(); } catch(e) {}
});*/
