/*
 * Script from NETTUTS.com [by James Padolsey]
 * @requires jQuery($), jQuery UI & sortable/draggable UI modules
 */

var iNettuts = {

    jQuery: $,

    settings: {
        columns: '.column',
        widgetSelector: '.widget',
        handleSelector: '.widget-head',
        contentSelector: '.widget-content',
        widgetDefault: {
            movable: true,
            collapsible: true,
            moreInformation: null,
            goToSite: null,
            customise: false,
            colorClasses: ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green', 'color-OxfordBlue'],
            colour: 'Platinum',
            initIsClosed: false,
            onInitOpen: null
        },
        widgetIndividual: null
    },

    init: function(settings) {
        this.settings.widgetIndividual = settings;
        this.addWidgetControls();
        this.makeSortable();
    },

    getWidgetSettings: function(id) {
        var $ = this.jQuery,
            settings = this.settings;
        return (id && settings.widgetIndividual[id]) ? $.extend({}, settings.widgetDefault, settings.widgetIndividual[id]) : settings.widgetDefault;
    },

    addWidgetControls: function() {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings;

        $(settings.widgetSelector, $(settings.columns)).each(function() {
            var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);


            if (thisWidgetSettings.collapsible) {
                if (thisWidgetSettings.initIsClosed == true) {
                    $('<a id="' + this.id + 'IsClosed" style="text-decoration:none;  background-position: -14px 0;" alt="Toggle Collapse" href="#" class="collapse' + thisWidgetSettings.colour + '">&nbsp;</a>').mousedown(function(e) {
                        e.stopPropagation();
                    }).toggle(function() {
                        $('.widget').css({ width: '483px' });
                        $(this).css({ backgroundPosition: '' })
                                .parents(settings.widgetSelector)
                                    .find(settings.contentSelector).show();
                        var thisWidgetSettings = iNettuts.getWidgetSettings(String(this.id).substr(0, (String(this.id).length - 8)));
                        eval(thisWidgetSettings.onInitOpen);
                        var date = new Date();
                        date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
                        $.cookie(this.id, "false", { path: '/', expires: date })
                        return false;
                    }, function() {
                        $('.widget').css({ width: '483px' }); // Added 11/3/2009
                        $(this).css({ backgroundPosition: '-14px 0' })
                            .parents(settings.widgetSelector)
                                .find(settings.contentSelector).hide();
                        var date = new Date();
                        date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
                        $.cookie(this.id, "true", { path: '/', expires: date })
                        return false;
                    }).appendTo($(settings.handleSelector, this));
                } else {
                    $('<a id="' + this.id + 'IsClosed" style="text-decoration:none" alt="Toggle Collapse" href="#" class="collapse' + thisWidgetSettings.colour + '">&nbsp;</a>').mousedown(function(e) {
                        e.stopPropagation();
                    }).toggle(function() {
                        $('.widget').css({ width: '483px' }); // Added 11/3/2009
                        $(this).css({ backgroundPosition: '-14px 0' })
                            .parents(settings.widgetSelector)
                                .find(settings.contentSelector).hide();
                        var date = new Date();
                        date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
                        $.cookie(this.id, "true", { path: '/', expires: date })
                        return false;
                    }, function() {
                        $('.widget').css({ width: '483px' });
                        $(this).css({ backgroundPosition: '' })
                            .parents(settings.widgetSelector)
                                .find(settings.contentSelector).show();
                        var date = new Date();
                        date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
                        $.cookie(this.id, "false", { path: '/', expires: date })
                        return false;
                    }).appendTo($(settings.handleSelector, this));


                }
            } else {
                $('<div style="float:right; width:31px; height:2px; overflow:hidden;"></div>').appendTo($(settings.handleSelector, this));
            }

            var customiseLink = "";
            if (thisWidgetSettings.customise) {
                customiseLink = '<a href="#" style=" float:right; text-decoration:none; color:white; font-size:0.75em;margin-right:5px; border:solid 0px white;">| Customise</a>';
            }

            if (thisWidgetSettings.barLinks != null) {
                for (var i = 0; i < thisWidgetSettings.barLinks.length; i++) {
                    $('<a href="' + thisWidgetSettings.barLinks[i][1] + '" alt="' + thisWidgetSettings.barLinks[i][3] + '" style="display:block; float:right; text-decoration:none; color:white; font-size:0.75em; margin-right:' + ((i == 0) ? 26 : 5) + 'px;">| ' + thisWidgetSettings.barLinks[i][0] + '</a>' + customiseLink).appendTo($(settings.handleSelector, this));
                }
            }
        });

        $('.edit-box').each(function() {
            $('input', this).keyup(function() {
                $(this).parents(settings.widgetSelector).find('h3').text($(this).val().length > 20 ? $(this).val().substr(0, 20) + '...' : $(this).val());
            });
            $('ul.colors li', this).click(function() {

                var colorStylePattern = /\bcolor-[\w]{1,}\b/,
                    thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)
                if (thisWidgetColorClass) {
                    $(this).parents(settings.widgetSelector)
                        .removeClass(thisWidgetColorClass[0])
                        .addClass($(this).attr('class').match(colorStylePattern)[0]);
                }
                return false;

            });
        });

    },


    saveStateToCookie: function() {
        var boxes = $("#column1 > .widget");
        var date = new Date();
        date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
        for (var i = 0; i < boxes.length; i++) {
            $.cookie(boxes[i].id + "PositionOrder", i + 1, { path: '/', expires: date });
            $.cookie(boxes[i].id + "PositionColumn", 1, { path: '/', expires: date });
        }
        boxes = $("#column2 > .widget");
        for (var i = 0; i < boxes.length; i++) {
            $.cookie(boxes[i].id + "PositionOrder", i + 1, { path: '/', expires: date });
            $.cookie(boxes[i].id + "PositionColumn", 2, { path: '/', expires: date });
        }
    },


    makeSortable: function() {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            $sortableItems = (function() {
                var notSortable = '';
                $(settings.widgetSelector, $(settings.columns)).each(function(i) {

                    if (!iNettuts.getWidgetSettings(this.id).movable) {
                        if (!this.id) {
                            this.id = 'widget-no-id-' + i;
                        }
                        notSortable += '#' + this.id + ',';
                    }
                });
                return $('> li:not(' + notSortable + ')', settings.columns);
            })();

        $sortableItems.find(settings.handleSelector).css({
            cursor: 'move'
        }).mousedown(function(e) {
            //$sortableItems.css({ width: '' });
            $('.widget').css({ width: '483px' });
            $(this).parent().css({
                width: '483px'
            });
        }).mouseup(function() {
            if (!$(this).parent().hasClass('dragging')) {
                $(this).parent().css({ width: '' });
            } else {
                $(settings.columns).sortable('disable');
            }
            $('.widget').css({ width: '483px' });

        });

        $(settings.columns).sortable({
            items: $sortableItems,
            connectWith: $(settings.columns),
            handle: settings.handleSelector,
            placeholder: 'widget-placeholder',
            forcePlaceholderSize: true,
            revert: 300,
            delay: 100,
            opacity: 0.8,
            containment: 'document',
            start: function(e, ui) {
                $(ui.helper).addClass('dragging');
                $('.widget-placeholder').attr('style', 'height:' + $(ui.helper).height() + 'px;');
            },
            stop: function(e, ui) {
                $(ui.item).css({ width: '' }).removeClass('dragging');
                $('.widget').css({ width: '483px' });
                $(settings.columns).sortable('enable');
                iNettuts.saveStateToCookie();
            }
        });
    }

};
