/*
 * Script based on NETTUTS.com [by James Padolsey]
 * @requires jQuery($), jQuery UI & sortable/draggable UI modules
 */

function update_old_content(id){
	$("#"+id).load("get.php?action=old&id="+id, function(){$("#"+id).slideDown();});
}

function addWidgetsControlsToId(object, iNettuts){

	var settings = iNettuts.settings;
        
        var thisWidgetSettings = iNettuts.getWidgetSettings(object.id);
        if (thisWidgetSettings.removable) {
            $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) {
                e.stopPropagation();    
            }).click(function () {
            	$(this).parents(settings.widgetSelector).find(settings.contentSelector).slideUp("normal", function(){
            		$(this).parents(settings.widgetSelector).slideUp("slow", function(){
            			$(this).remove();
            			update_order();
            		});
            		$(this).remove();
            	});
				//change_to_category(0);
				
                return false;
            }).appendTo($(settings.handleSelector, object));
        }
        
        if (thisWidgetSettings.editable) {
            $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {
                e.stopPropagation();    
            }).toggle(function () {
                $(this).css({backgroundPosition: '-66px 0', width: '55px'})
                    .parents(settings.widgetSelector)
                        .find('.edit-box').show().find('input').focus();
                return false;
            },function () {
                $(this).css({backgroundPosition: '', width: ''})
                    .parents(settings.widgetSelector)
                        .find('.edit-box').hide();
                return false;
            }).appendTo($(settings.handleSelector,object));
            $('<div class="edit-box" style="display:none;"/>')
                .append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')
                .append((function(){
                    var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';
                    $(thisWidgetSettings.colorClasses).each(function () {
                        colorList += '<li class="' + object + '"/>';
                    });
                    return colorList + '</ul>';
                })())
                .append('</ul>')
                .insertAfter($(settings.handleSelector,object));
        }
        
        if (thisWidgetSettings.collapsible) {
            $('<a href="#" class="collapse">(Vis gamle program)</a>').mousedown(function (e) {
                e.stopPropagation();    
            }).toggle(function () {
            	
                var box_id = $(this).css({backgroundPosition: '-52px 0'})
                    .parents(settings.widgetSelector)
                    	.find(settings.contentSelector).find(".old").get(0).id;
                	update_old_content(box_id);
                return false;
            },function () {
                $(this).css({backgroundPosition: '-38px 0'})
                    .parents(settings.widgetSelector)
                        .find(settings.contentSelector).find(".old").slideUp();
                return false;
            }).prependTo($(settings.handleSelector,object));
        }

}

var iNettuts = {
    
    jQuery : $,
    
    settings : {
        columns : '.column',
        widgetSelector: '.widget',
        handleSelector: '.widget-head',
        contentSelector: '.widget-content',
        widgetDefault : {
            movable: true,
            removable: true,
            collapsible: true,
            editable: false,
            colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green', 'color-brown']
        },
        widgetIndividual : {
            solid : {
                movable: false,
                removable: false,
                collapsible: false,
                editable: false
            }
        }
    },

    init : function () {
        this.attachStylesheet('css/inettuts.js.css');
        this.addWidgetControls(this.settings.columns);
        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 (columns) {
    	var iNettuts = this,
	    	$ = this.jQuery,
		    settings = this.settings;
        
	    $(settings.widgetSelector, $(columns)).each(function () {
	    	addWidgetsControlsToId(this, iNettuts);
	    });
	    
	    $('.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;
	            
	        });
	    });
    },
    
    attachStylesheet : function (href) {
        var $ = this.jQuery;
        return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
    },
    
    makeSortable : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            $sortableItems = (function () {
                var notSortable = '#solid,';
                $(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:''});
			$(this).parents(settings.widgetSelector)
						.find(settings.contentSelector).hide();
			
			if($(this).parent().parent().attr("id") == 'row'){
				reload_content($(this).parent().attr("id"));
			} else {
				$(this).parent().css({
					width: $(this).parent().width() + 'px'
				});
			}
			
        }).mouseup(function () {
            if(!$(this).parent().hasClass('dragging')) {
                $(this).parent().css({width:''});
				if($(this).parent().parent().attr('id') != 'row'){
					$(this).parents(settings.widgetSelector)
							.find(settings.contentSelector).show();
				}
            } else {
                $(settings.columns).sortable('disable');
            }
        });

        $(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',
			update : function () {
        		update_order();
			},
            start: function (e,ui) {
                $(ui.helper).addClass('dragging');
				if($(ui.item).parent().attr('id') == 'row'){
					$(ui.item).css({width:'20%'});
				}
            },
            stop: function (e,ui) {
				$(ui.item).css({width:''}).removeClass('dragging');
                $(settings.columns).sortable('enable');
				
				if($(ui.item).parent().attr('id') == 'row'){
					$(ui.item).parent().find(settings.contentSelector).hide();
				} else {
					$(ui.item).parent().find(settings.contentSelector).show();
				}
            }
        });
    }
  
};

iNettuts.init();
