/*
 * 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,
            removable: true,
            collapsible: true,
            editable: true,
            colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green', 'color-grey']
        },
        widgetIndividual : {
            intro : {
                movable: false,
                removable: false,
                collapsible: false,
                editable: false
            }
        }
    },

    init : function () {
        this.attachStylesheet('inettuts.js.css');
        this.addWidgetControls();
        this.makeSortable();
    },
	
	initElement : function (element) {
		
	},
    
    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;
		var i = 0;	            
        $(settings.widgetSelector, $(settings.columns)).each(function () {
			
		//	$(this).resizable();
			
			var self = this;
			$(this).self = this;
			self.state = self.state || {};			
            var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);
			if (thisWidgetSettings.removable) {
                $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) {
                    e.stopPropagation();    
                }).click(function () {
                    if(confirm('This widget will be removed, ok?')) {
                    	self.state.removed = true;
                    	self.state.dirty = true;
                        $(this).parents(settings.widgetSelector).animate({
                            opacity: 0    
                        },function () {
                            $(this).wrap('<div/>').parent().slideUp(function () {
                                $(this).remove();
								if (self.parentNode.className.indexOf("floating column") != 1) {
									self.parentNode.style.left = "-100000px";
								}
                            });
                        });
						// update the changes
						saveWidget(self.state);
                    }
                    return false;
                }).appendTo($(settings.handleSelector, this));
            }				
			if (thisWidgetSettings.collapsible) {
                $('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {
                    e.stopPropagation();    
                }).toggle(function () {
                    $(this).css({backgroundPosition: '-42px 0'})
                        .parents(settings.widgetSelector)
                            .find(settings.contentSelector).hide();
					if (!self.state.min) {
                		self.state.min = true;
                		self.state.dirty = true;
						// update the changes
						saveWidget(self.state);
					}									
                    return false;
                },function () {
					self.state.min = false;
                	self.state.dirty = true;
                    $(this).css({backgroundPosition: ''})
                        .parents(settings.widgetSelector)
                            .find(settings.contentSelector).show();
					// update the changes
					saveWidget(self.state);
                    return false;
                }).appendTo($(settings.handleSelector,this));
				// load state 
				if (self.state.min) {
					// manually click the minimize button
					$(self).find(".collapse").triggerHandler("click");
				}
            }
            if (thisWidgetSettings.editable) {
                $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {
                    e.stopPropagation();    
                }).toggle(function () {		
                    $(this).css({backgroundPosition: '-56px 0', width: '14px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').show().find('input').focus();
                    return false;
                },function () {
					// update the changes
					saveWidget(self.state);
                    $(this).css({backgroundPosition: '', width: ''})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').hide();
                    return false;
                }).appendTo($(settings.handleSelector,this));
				var announcement = self.state && self.state.widgetID == 2;
				var cnt = parseInt(self.state.itemCount || 3);
				var itemCount = "";
				if (!announcement) {
					itemCount = '<li class="item"><label>Select number of articles to show:</label><select>';
					for (var i = 0; i < 12; ) {
						i++;
						itemCount += "<option value='" + i + "'";
						itemCount += (i == cnt) ? " selected='selected'>" : ">";
						itemCount += i + "</option>";  
					}
					itemCount += "</select>";
				}
                $('<div id="edit-box' + i + '" class="edit-box" style="display:none;"/>')
                    .append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')
					.append(itemCount)
                    .append((function(){
                        var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';
                        $(thisWidgetSettings.colorClasses).each(function () {
                            colorList += '<li class="' + this + '"/>';
                        });
                        return colorList + '</ul>';
                    })())
					.append(
						'<ul><li class="item"><label for="semitrans' + i + '">Semi Transparent:</label>' 
							+ '<input id="semitrans' + i + '" type="checkbox"/></li></ul>'
					)
                    .append('</ul>')
                    .insertAfter($(settings.handleSelector,this));
				// unselect semitrans	
				document.getElementById('semitrans' + i).checked = false;
				document.getElementById('edit-box' + i).state = self.state;	
            }    	
			i++;
        });        
        $('.edit-box').each(function () {		
		var self = this;
		var widget = this;
		var node = self;
		while (widget.parentNode) {
			if (widget.className && widget.className.indexOf('widget') >= 0) {
				node = widget;
				break;	
			}
			widget = widget.parentNode;
		}

            $('input',this).keyup(function () {				
            	node.state.title = $(this).val();
            	node.state.dirty = true;
                $(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() );
            });
			$('input', this).change (
				function () {
					node.state.alpha = this.checked ? 85 : 100;
					node.state.dirty = true;
					if (!this.checked) {
						$(this).parents(settings.widgetSelector)
							.css({opacity: 1, filter : "alpha(opacity=100)"});
					} else {
						$(this).parents(settings.widgetSelector)
							.css({opacity: 0.85, filter : "alpha(opacity=85)"});
					}					
				}
			);
			$('select', this).change (
				function () {
					node.state.itemCount = this.value;
					node.state.dirty = true;
					node.state.reload = true;
				}
			);			
            $('ul.colors li',this).click(function () {
                var colorStylePattern = /\bcolor-[\w]{1,}\b/,
                    thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)
                if (thisWidgetColorClass) {
					var newColorClass = $(this).attr('class').match(colorStylePattern)[0];
	            	node.state.color = newColorClass.replace(/color-/, "");
	                node.state.dirty = true;					
                    $(this).parents(settings.widgetSelector)
                        .removeClass(thisWidgetColorClass[0])
                        .addClass(newColorClass);
                }
                return false;
                
            });
        });
        
    },
    
    attachStylesheet : function (href) {
        var $ = this.jQuery;
        return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
    },
    
    makeSortable : function () {
		var self = this;		
        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:''});
            $(this).parent().css({
                width: $(this).parent().width() + 'px'
            });
        }).mouseup(function () {
            if(!$(this).parent().hasClass('dragging')) {
                $(this).parent().css({width:''});
            } 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',
            start: function (e,ui) {
                $(ui.helper).addClass('dragging');
            },
            stop: function (e,ui) {
				updateWidgetPositions();			
                $(ui.item).css({width:''}).removeClass('dragging');
                $(settings.columns).sortable('enable');				
            }
        });
    }
};

initDashboard();
setTimeout(function () {iNettuts.init();}, 750);

