/* Author:
 * marek
 */

// namespacing to keep the global scope clean
var ml = ml || {};

$( function() {

    ml.contentLoader = {
        _leftmargin: 0,
        _defaultTopMargin: 70,
        _lastposy: 0, // startscrolltop
        _lastposx: 0, // startscrollleft
        _linkarray: [],

        breadcrumb: function ( position, elementId ) {
            this._linkarray.splice( position, this._linkarray.length );
            out(this._linkarray.join(' > '));
            this.load_content( elementId );
        },

        load_content: function ( url, position, width ) {
            // remove special characters to use it as an id
            var breadcrumbName,
                urlIds = url.split('/');

            // if there's a GET parameter behind the last slash, i don't want this to be the name
            if ( urlIds[urlIds.length-1][0] === '?' ) {
                breadcrumbName = urlIds[urlIds.length-2];
            } else {
                breadcrumbName = urlIds[urlIds.length-1];
            }
            breadcrumbName = breadcrumbName.split('.')[0];

            urlIds = urlIds.join("")
                           .split('.').join("")
                           .split('?').join("")
                           .split('=').join("");

            this._linkarray.push(
                '<span onclick="ml.contentLoader.breadcrumb('
                +this._linkarray.length+', \''
                +url+'\' );">'
                +breadcrumbName+'</span>'
            );
            out(this._linkarray.join(' > '));

            // if it's not yet here
            if ( $('#'+urlIds).length == 0 ) {
                var positionX,
                    positionY;

                if (position) {
                    position = position.split(' ');
                    console.log(position);
                    positionX = position[0];
                    positionY = position[1];
                } else {
                    positionX = (Math.random()-0.5)*3500;
                    positionY = (Math.random()-0.5)*3500;
                }

                if (width) {
                    width = width+'px';
                } else {
                    width = '460px';
                }
                // create it
                $('#dragContainer').append(
                    '<div class="contentContainer" id="'
                    + urlIds + '" style="left:'
                    + positionX + 'px;top:'
                    + positionY + 'px;width:'
                    + width + '"></div>'
                );
                // and load content
                $('#'+urlIds).load( url , function() {
                    $(this)
                        .fadeIn( 'slow' )
                        .hover(
                            // i only wanna drag, when mouse is over the Background
                            function() { ml.contentLoader.hoverDraggableChild(); },
                            function() { ml.contentLoader.outDraggableChild(); }
                        );

                    // alter the content if it's from this superno softlink
                    $(this)
                        .find( 'a.extern' )
                        .attr( 'target', '_blank' );
                    $(this)
                        .find( 'a' ).not('.extern')
                        .each(function() {
                            $(this)
                                .bind( 'click', function() {
                                    ml.contentLoader.load_content(
                                        $(this).attr('href')+'?baseUrl='+$(this).attr('baseUrl'),
                                        $(this).attr('position'),
                                        $(this).attr('breite')
                                        );
                                    // preventing the href from working
                                    return false;
                                });
                        });

                    $(this)
                        .find( 'a.thumbnail' )
                        .lightBox({
                            'saveButton': true // my own addition to ligtbox
                        }); // Select all links in object with gallery ID
                    ml.contentLoader.jumpToElement('#'+urlIds);
                    // console.log(this);
                });
            } else {
                this.jumpToElement('#'+urlIds);
            }

        }, // load_content()

        jumpHome: function () {
            this._lastposx = this._leftmargin;
            this._lastposy = this._defaultTopMargin;
            this._linkarray = [];
            out('');
            $('#dragContainer').animate({
                top:  this._defaultTopMargin + 'px',
                left: this._leftmargin + 'px'
            }, 500);
        },

        jumpToElement: function ( selector ) {
            $('#dragContainer').animate({
                left: this.jumpToLeft(selector) + 'px',
                top:  this.jumpToTop(selector) + 'px'
            }, 500);
        },

        // why don't these two work inside the animate-properties-list?!?
        jumpToTop: function ( selector ) {
            this._lastposy = -$(selector).position().top + this._defaultTopMargin;
            return this._lastposy;
        },

        jumpToLeft: function ( selector ) {
            this._lastposx = -$(selector).position().left + this._leftmargin;
            return this._lastposx;
        },

        setLeftmargin: function () {
            this._leftmargin = ($('#viewContainer').width() / 2) - (($('#home').width()+40) / 2) -1;
            if (this._leftmargin < 0) { // if window.width < 500
                this._leftmargin = 0;   // then dock to the left
            }
        },

        hoverDraggableChild: function () {
            $( "#dragContainer" )
                .draggable( "option", "disabled", true )
                .removeClass( 'cursorMove' );
        },
        outDraggableChild: function () {
            $( "#dragContainer" )
                .draggable( "option", "disabled", false )
                .addClass( 'cursorMove' );
        },

        init: function () {

            // replacing the href functionality with my ajax call
            $('a').each(function() {
                $(this).bind(
                    'click', function() {
                        ml.contentLoader.load_content( $(this).attr('href'), $(this).attr('position') );
                        // preventing the href from working
                        return false;
                    }
                );
            });

            $( "#dragContainer" )
                .draggable({
                    handle: "#dragContainer",
                    stop: function(event, ui) {
                        ml.contentLoader._lastposx = ui.position.left;
                        ml.contentLoader._lastposy = ui.position.top; // scroll
                    }
                })
                .bind('mousewheel', function(event, delta) {
                    ml.contentLoader._lastposy += delta*30;
                    $('#dragContainer').css({ top: ml.contentLoader._lastposy+'px' });
                });

            $(window).bind('resize', function () {
                ml.contentLoader.setLeftmargin();
            });

            $( "#dragContainer" ).children().hover(
                // i only wanna drag, when mouse is over the Background
                function() { ml.contentLoader.hoverDraggableChild(); },
                function() { ml.contentLoader.outDraggableChild(); }
            );

            this.setLeftmargin();
            this.jumpHome();

        } // init()

    }; // ml.containerLoader

    ml.contentLoader.init();

});