/* //Copyright (c) 2009 Onkosh (http://www.onkosh.com) with James Padolsey */

var iNettuts = {
    
    jQuery : $,    
    settings : {
        columns : '.column',
        widgetSelector: '.widget',
        handleSelector: '.widget-head',
        contentSelector: '.widget-content',
        //saveToCookie: document.search.l.value== 'ar'? 'inettuts-widget-preferencesAR':'inettuts-widget-preferencesEN',
        saveToCookie: 'inettuts-widget-preferences',
		
        widgetDefault : {
            movable:true,
            collapsible:true,
			removable:true,
            editable: false, 
            colorClasses : ['color-green', 'color-green', 'color-green', 'color-green', 'color-green', 'color-green']
        },
        widgetIndividual : {}
    },

    init : function () {
	/* HANY!
	if (document.search.l.value== 'ar'){
	        this.attachStylesheet('/onn/js/inettuts.js.css');
	}else{
		this.attachStylesheet('/onn/js/inettuts2.js.css');
	}
	*/
        if (document.search.l.value== 'ar'){
                this.attachStylesheet('/onn/css/style.css');
        }else{
                this.attachStylesheet('/onn/en/css/style.css');
        }

		this.sortWidgets();
        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);            
            var mdSaveId = this.id; 			
			if (thisWidgetSettings.collapsible) {
                $('<a href="#" class="collapse"></a>').mousedown(function (e) {                    
                    e.stopPropagation();    
                }).click(function(){
                    $(this).parents(settings.widgetSelector).toggleClass('collapsed');
                    iNettuts.savePreferences();
                    return false;    
                }).prependTo($(settings.handleSelector,this));
            }
			
			 if (thisWidgetSettings.removable) {	
                $('<a href="#" class="remove" id="removebtn"></a>').mousedown(function (e) { 
                    e.stopPropagation();    
                }).click(function () {
                    if(confirm('This widget will be removed, ok?')) {
                        document.getElementById('c' + mdSaveId).checked = false;
						
	                    $(this).parents(settings.widgetSelector).animate({
                            opacity: 0    
                        },function () {
                             $(this).slideUp(function () {  
                                $(this).toggleClass('closed');
                                iNettuts.savePreferences(); 
                            });                            
                        });
                    }
                    return false;
                }).appendTo($(settings.handleSelector, this));
            }
        });              
    },
    
    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 = '';
                $(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) {
                $(ui.item).css({width:''}).removeClass('dragging');
                $(settings.columns).sortable('enable');                
                iNettuts.savePreferences();
            }
        });
    },
    
    savePreferences : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            cookieString = '';
        //alert(settings.saveToCookie);    
        if(!settings.saveToCookie) {return;}
        
        $(settings.columns).each(function(i){
            cookieString += (i===0) ? '' : '|';
            $(settings.widgetSelector,this).each(function(i){
                cookieString += (i===0) ? '' : ';';
                cookieString += $(this).attr('id') + ',';
                cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ',';
                cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ',';
                cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed,' : 'not-collapsed,';
                cookieString += $(settings.handleSelector,this).css('display') === 'none' ? 'closed' : 'not-closed';  /* added */
            });
        });
        $.cookie(settings.saveToCookie,cookieString,{
            expires: 10
            //path: '/'
        });		
    },
    
    sortWidgets : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings;
        
        var cookie = $.cookie(settings.saveToCookie);
        if(!settings.saveToCookie||!cookie) {
            $('body').css({background:'#fff'});
            $(settings.columns).css({visibility:'visible'});
            return;
        }
        
        $(settings.columns).each(function(i){
            
            var thisColumn = $(this),
                widgetData = cookie.split('|')[i].split(';');
                
            $(widgetData).each(function(){
                if(!this.length) {return;}
                var thisWidgetData = this.split(','),
                    clonedWidget = $('#' + thisWidgetData[0]),
                    colorStylePattern = /\bcolor-[\w]{1,}\b/,
                    thisWidgetColorClass = $(clonedWidget).attr('class').match(colorStylePattern);
                
                if (thisWidgetColorClass) {
                    $(clonedWidget).removeClass(thisWidgetColorClass[0]).addClass(thisWidgetData[1]);
                }
                
                $(clonedWidget).find('h3:eq(0)').html(thisWidgetData[2].replace(/\[-PIPE-\]/g,'|').replace(/\[-COMMA-\]/g,','));
                
                if(thisWidgetData[4]==='closed') {
                    $(clonedWidget).addClass('closed');
                    document.getElementById('c' + thisWidgetData[0]).checked = false;
                }
                
				if(thisWidgetData[3]==='collapsed') {
                    $(clonedWidget).addClass('collapsed');                
                }                
                /*else
				{
					document.getElementById('c' + thisWidgetData[0]).checked = true;					
				}*/
                
                $('#' + thisWidgetData[0]).remove();
                $(thisColumn).append(clonedWidget);
            });
        });
        
        $('body').css({background:'#fff'});
        $(settings.columns).css({visibility:'visible'});
    }  
};

iNettuts.init();
