/*
 * Script from NETTUTS.com [by James Padolsey] V.2 (ENHANCED, WITH COOKIES!!!)
 * @requires jQuery($), jQuery UI & sortable/draggable UI modules & jQuery COOKIE plugin
 */

var iNettuts = {
    
    jQuery : $,
    
    settings : {
        columns :'.column',
        widgetSelector: '.widget',
        handleSelector: '.widget-head',
        contentSelector: '.widget-content',
        
        /* If you don't want preferences to be saved change this value to
            false, otherwise change it to the name of the cookie: */
       saveToCookie: 'inettuts-widget-preferences',
       //saveToCookie: false,
        
        widgetDefault : {
            movable: true,
            removable: true,
            collapsible: true,
            editable: false,
            colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green, color-ciano']
        },
        widgetIndividual : {}
    },
    
    
 			   items : {
				   'mefop-informa' : { 'type': 'content-fixed', 'title': 'Mefop Informa', 'subtitle': 'Leggi ed aggiornamenti normativi', 'icon':'mefop_informa.png', 'id': 'mefop-informa', 'color' : 'blue', 'column': '2', 'dataurl' : '/content/articoli.php?q=mefop-informa'
				   ,'removable': false, 'movable': false,  'collapsible': false
				    },
				   'eventi-mefop' : { 'type': 'content-fixed',  'title': 'Mefop FA',  'subtitle': 'Formazione e Attivit&agrave; Mefop', 'icon':'mefop_F-A.png', 'id': 'eventi-mefop', 'color' : 'blue', 'column': '3', 'dataurl' : '/content/eventi-mefop.php'
				   ,'removable': false, 'movable': false,  'collapsible': false
				   },

				   'notizie-dai-fondi' : { 'type': 'content-fixed',  'title': 'Mefop Evidenzia', 'subtitle': 'Notizie ed eventi dalla previdenza', 'icon':'mefop_evidenzia.png', 'id': 'notizie-dai-fondi', 'color' : 'blue', 'column': '1', 'dataurl' : '/content/articoli.php?q=notizie-dai-fondi' 
				   ,'removable': false, 'movable': false,  'collapsible': false
				   },
				    
				   'area-riservata' : { 'type': 'content', 'title': 'Area Riservata', 'id': 'area-riservata', 'color' : 'blue', 'column': '1', 'dataurl' : '/content/area-riservata.php' },			
				   'fondi-pensione' : { 'type': 'content',  'title': 'Fondi Pensione', 'id': 'fondi-pensione', 'color' : 'blue', 'column': '2', 'dataurl' : '/content/fondi-pensione.php?null=0' },			   		
				   'stampa' : { 'type': 'content',  'title': 'Dalla Stampa', 'id': 'stampa', 'color' : 'blue', 'column': '1', 'dataurl' : '/content/stampa.php' },
				   'stampa-abbonati' : { 'type': 'content',  'title': 'Dalla Stampa Abbonati', 'id': 'stampa-abbonati', 'color' : 'red', 'column': '1', 'dataurl' : '/content/stampa-abbonati.php' },
				   'normativa' : { 'type': 'content',  'title': 'Normativa', 'id': 'normativa', 'color' : 'blue', 'column': '2', 'dataurl' : '/content/normativa.php?null=0' },			   		
				   'autoregolazione' : { 'type': 'content',  'title': 'Autoregolazione Trasferimenti', 'id': 'autoregolazione', 'color' : 'blue', 'column': '2', 'dataurl' : '/content/autoregolazione.php?null=0' },			   		
				   'pubblicazioni' : { 'type': 'content',  'title': 'Pubblicazioni', 'id': 'pubblicazioni', 'color' : 'red', 'column': '2', 'dataurl' : '/content/pubblicazioni.php?null=0' },			   		
				   'studi-ricerche' : { 'type': 'content',  'title': 'Studi e Ricerche', 'id': 'studi-ricerche', 'color' : 'red', 'column': '2', 'dataurl' : '/content/studi-ricerche.php?null=0' },			 
				   
				   'rss-repubblica' : { 'type': 'rss',  'title': 'Rss Repubblica', 'id': 'rss-repubblica', 'color' : 'ciano', 'column': '1', 'dataurl' : '/content/rss-parser.php?feed=repubblica' },
				   'rss-repubblica-economia' : { 'type': 'rss',  'title': 'Rss Repubblica - Economia', 'id': 'rss-repubblica-economia', 'color' : 'ciano', 'column': '1', 'dataurl' : '/content/rss-parser.php?feed=repubblica-economia' },
				   'rss-corriere' : { 'type': 'rss',  'title': 'Rss Corsera', 'id': 'rss-corriere-della-sera', 'color' : 'ciano', 'column': '1', 'dataurl' : '/content/rss-parser.php?feed=corriere' },
				   'rss-corriere-economia' : { 'type': 'rss',  'title': 'Rss Corsera - Economia', 'id': 'rss-corriere-economia', 'color' : 'ciano', 'column': '1', 'dataurl' : '/content/rss-parser.php?feed=corriere-economia' },
				   'rss-sole' : { 'type': 'rss',  'title': 'Rss Il Sole 24 Ore', 'id': 'rss-sole', 'color' : 'ciano', 'column': '1', 'dataurl' : '/content/rss-parser.php?feed=sole' },
				   'rss-sole-economia' : { 'type': 'rss',  'title': 'Rss Il Sole 24 Ore - Economia', 'id': 'rss-sole-economia', 'color' : 'ciano', 'column': '1', 'dataurl' : '/content/rss-parser.php?feed=sole-economia' },
				   'rss-ministero-economia' : { 'type': 'rss',  'title': 'Rss Ministero dell\'Economia', 'id': 'rss-ministero-economia', 'color' : 'ciano', 'column': '1', 'dataurl' : '/content/rss-parser.php?feed=ministero-economia' },


				   'calendario' : { 'type': 'gadget',  'title': 'Calendario', 'id': 'calendario', 'color' : 'grey', 'column': '1', 'dataurl' : '/content/google-gadgets.php?gadget=calendario' },
				   'wikipedia' : { 'type': 'gadget',  'title': 'Cerca su Wikipedia', 'id': 'wikipedia', 'color' : 'grey', 'column': '1', 'dataurl' : '/content/google-gadgets.php?gadget=wikipedia' },
				   'attivita' : { 'type': 'gadget',  'title': 'Blocco Note', 'id': 'attivita', 'color' : 'grey', 'column': '1', 'dataurl' : '/content/google-gadgets.php?gadget=attivita' },
				   'mappe-google' : { 'type': 'gadget',  'title': 'Mappe Google', 'id': 'mappe-google', 'color' : 'grey', 'column': '1', 'dataurl' : '/content/google-gadgets.php?gadget=mappe-google' }

				 },

/*
				   'prossime-iniziative' : { 'type': 'content',  'title': 'Prossime Iniziative', 'id': 'prossime-iniziative', 'color' : 'red', 'column': '3', 'dataurl' : '/content/articoli.php?q=prossime-iniziative' },

				   'traduzioni' : { 'type': 'gadget',  'title': 'Traduzioni', 'id': 'traduzioni', 'color' : 'green', 'column': '1', 'dataurl' : '/content/google-gadgets.php?gadget=traduzioni' },
				   'convertitore' : { 'type': 'gadget',  'title': 'Convertitore Valute', 'id': 'convertitore', 'color' : 'green', 'column': '1', 'dataurl' : '/content/google-gadgets.php?gadget=convertitore' },
				   'calendario' : { 'type': 'gadget',  'title': 'Calendario', 'id': 'calendario', 'color' : 'green', 'column': '1', 'dataurl' : '/content/google-gadgets.php?gadget=calendario' },
*/
    init : function () {
    		jQuery( "#widgetlist").hide();
				this.loadWidgets();
        this.attachStylesheet('/css/interface.js.css');
        //this.sortWidgets();
        this.addWidgetControls();
        this.makeSortable();
        this.savePreferences();
        
    },

    addWidget : function (idWidget, idColumn) {
        var iNettuts = this,
        $ = this.jQuery,
        settings = this.settings,
        items = this.items;
	    	var loading = '<img src="/icone/loading.gif">';


		       jQuery.each(items, function(i,item){
							if ( item.id == idWidget ) {
								var html =  '<li class="widget color-'+ item.color + ' ombra_contenitore" id="' + item.id + '">';
										html += '<div class="ombra1"><div class="ombra2"><div class="ombra3">';
										if (item.type == 'content-fixed') {
											html += '<div class="widget-fixed-head">';
											html += '<div style="float:left;"><img src="/img/images/icone/' + item.icon + '" style="float:left;" />';
											html += '<h3>' + item.title + '</h3><div class="subtitle">' + item.subtitle + '</div></div></div>';
										} else {
											html += '<div class="widget-head"><h3>' + item.title + '</h3></div>';
										}
										html += '<div class="widget-content" id="' + item.id + '-content">' + loading + '</div>';
										html += '</div></div>';
										html += '</li>';
										jQuery( "#column" + idColumn ).append(html);
															
								if ( item.type == 'gadget' ) {
										jQuery( '#' +item.id + '-content' ).load(item.dataurl);
									 
								} else {
										jQuery( '#' +item.id + '-content' ).load(item.dataurl);
								}

							}
			      });
    },

    insertWidget : function (idWidget, idColumn) {
        var iNettuts = this,
        $ = this.jQuery,
        settings = this.settings,
        items = this.items;

				this.addWidget(idWidget, idColumn);
        this.savePreferences();					
				jQuery('#widgetlistitems #' + idWidget + ' a').replaceWith('<img src="/icone/accept.png"> Aggiunto');
    },

    loadWidgets : function () {
    	var iNettuts = this,
      $ = this.jQuery,
      settings = this.settings,
      items = this.items;
	    var loading = '<img src="/icone/loading.gif">';
      var cookie = jQuery.cookie(settings.saveToCookie);
      
        if(  settings.saveToCookie && cookie) {
					jQuery(settings.columns).each(function(i){
					    
					    var thisColumn = jQuery(this),
					    widgetData = cookie.split('|')[i].split(';');
					    jQuery(widgetData).each(function(){
					        if(!this.length) {return;}
					        var thisWidgetData = this.split(',');
					        iNettuts.addWidget(thisWidgetData[0], i + 1);
					       
					    });
					});			 
				} else {
					//alert ('COOKIE NON TROVATO');
					jQuery.each(items, function(i,item){
							iNettuts.addWidget(item.id , item.column );
					});     			
      	}
    },

    loadWidgetList : function () {
    	var iNettuts = this,
      $ = this.jQuery,
      settings = this.settings,
      items = this.items;
      itemsSelected = new Array();
      var listContent = '';
      var listRss = '';
      var listGadget = '';
      jQuery( "#columns").hide();
      jQuery( "#widgetlist").show();

      
	    var cookie = jQuery.cookie(settings.saveToCookie);
        if(  settings.saveToCookie && cookie) {
        		jQuery(settings.columns).each(function(i){
					    widgetData = cookie.split('|')[i].split(';');
					    jQuery(widgetData).each(function(){
					        if(!this.length) {return;}
					        var thisWidgetData = this.split(',');
					        itemsSelected.push(thisWidgetData[0]);
					    });
  				});
				} 

			jQuery.each(items, function(i,item){
			if (  jQuery.inArray( item.id , itemsSelected ) != -1 ) {

			} else {
				if ( item.type == 'content-fixed' ) {
					listContent +=  '<li id="' + item.id + '">' + item.title ;
					listContent += '<a href="#" onclick="iNettuts.insertWidget(\'' + item.id + '\',1);" class="addlink">';
					listContent += '<img src="/icone/add.png">' + '</a></li>';
				}

				if ( item.type == 'content' ) {
					listContent +=  '<li id="' + item.id + '">' + item.title ;
					listContent += '<a href="#" onclick="iNettuts.insertWidget(\'' + item.id + '\',1);" class="addlink">';
					listContent += '<img src="/icone/add.png">' + '</a></li>';
				}

				if ( item.type == 'rss' ) {
					listRss +=  '<li id="' + item.id + '">' + item.title ;
					listRss += '<a href="#" onclick="iNettuts.insertWidget(\'' + item.id + '\',1);" class="addlink">';
					listRss += '<img src="/icone/add.png">' + '</a></li>';
				}

				if ( item.type == 'gadget' ) {
					listGadget +=  '<li id="' + item.id + '">' + item.title ;
					listGadget += '<a href="#" onclick="iNettuts.insertWidget(\'' + item.id + '\',1);" class="addlink">';
					listGadget += '<img src="/icone/add.png">' + '</a></li>';
				}

			}
    });
      jQuery( "#widgetlistitems").html('<h1>Lista Widget</h1><ul id="list-content"></ul>');
      jQuery( "#widgetlistitems ul#list-content").append(listContent);
      jQuery( "#widgetlistitems").append('<h1>Lista RSS</h1><ul id="list-rss"></ul>');
      jQuery( "#widgetlistitems ul#list-rss").append(listRss);
      jQuery( "#widgetlistitems").append('<h1>Lista Gadget</h1><ul id="list-gadget"></ul>');
      jQuery( "#widgetlistitems ul#list-gadget").append(listGadget);
    },

    
    getWidgetSettings : function (id) {
        var $ = this.jQuery,
        settings = this.settings;
        return (id&&settings.widgetIndividual[id]) ? jQuery.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault;
    },

    
    addWidgetControls : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings;
            
        jQuery(settings.widgetSelector, jQuery(settings.columns)).each(function () {
            var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);
            //alert ( iNettuts.items[this.id].removable + ' -  -  ' +thisWidgetSettings.removable);
            if (thisWidgetSettings.removable && iNettuts.items[this.id].removable != false) {
            		
                jQuery('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).click(function () {
                    //if(confirm('Vuoi rimuovere questo widget ?')) {
                        jQuery(this).parents(settings.widgetSelector).animate({
                            opacity: 0    
                        },function () {
                            jQuery(this).wrap('<div/>').parent().slideUp(function () {
                                jQuery(this).remove();
                                iNettuts.savePreferences();
                            });
                        });

                    //} else {
                    //return false;
                  	//}
                }).appendTo(jQuery(settings.handleSelector, this));
            
            }
            
            if (thisWidgetSettings.editable) {
                jQuery('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).toggle(function () {
                    jQuery(this).css({backgroundPosition: '-66px 0', width: '55px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').show().find('input').focus();
                    return false;
                },function () {
                    jQuery(this).css({backgroundPosition: '', width: '24px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').hide();
                    return false;
                }).appendTo(jQuery(settings.handleSelector,this));
                jQuery('<div class="edit-box" style="display:none;"/>')
                    .append('<ul><li class="item"><label>Change the title?</label><input value="' + jQuery('h3',this).text() + '"/></li>')
                    .append((function(){
                        var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';
                        jQuery(thisWidgetSettings.colorClasses).each(function () {
                            colorList += '<li class="' + this + '"/>';
                        });
                        return colorList + '</ul>';
                    })())
                    .append('</ul>')
                    .insertAfter(jQuery(settings.handleSelector,this));
            }
            
            if (thisWidgetSettings.collapsible && iNettuts.items[this.id].collapsible != false ) {
                jQuery('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).click(function(){
                    jQuery(this).parents(settings.widgetSelector).toggleClass('collapsed');
                    /* Save prefs to cookie: */
                    iNettuts.savePreferences();
                    return false;    
                }).prependTo(jQuery(settings.handleSelector,this));
            }
        });
        
        jQuery('.edit-box').each(function () {
            jQuery('input',this).keyup(function () {
                jQuery(this).parents(settings.widgetSelector).find('h3').text( jQuery(this).val().length>20 ? jQuery(this).val().substr(0,20)+'...' : jQuery(this).val() );
                iNettuts.savePreferences();
            });
            jQuery('ul.colors li',this).click(function () {
                
                var colorStylePattern = /\bcolor-[\w]{1,}\b/,
                    thisWidgetColorClass = jQuery(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)
                if (thisWidgetColorClass) {
                    jQuery(this).parents(settings.widgetSelector)
                        .removeClass(thisWidgetColorClass[0])
                        .addClass(jQuery(this).attr('class').match(colorStylePattern)[0]);
                    /* Save prefs to cookie: */
                    iNettuts.savePreferences();
                }
                return false;
                
            });
        });
        
    },

   
    attachStylesheet : function (href) {
        var $ = this.jQuery;
        return jQuery('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
    },
    
    makeSortable : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            $sortableItems = (function () {
                var notSortable = '';
                //var notSortable = null;
                jQuery(settings.widgetSelector,jQuery(settings.columns)).each(function (i) {
                    //if (!iNettuts.getWidgetSettings(this.id).movable ) {
                    //alert (iNettuts.items[this.id].movable);
                     if (iNettuts.items[this.id].movable == false ) {
                        if(!this.id) {
                            this.id = 'widget-no-id-' + i;
                           
                        }
                        notSortable += '#' + this.id + ',';
                    }
                });
                return jQuery('> li:not(' + notSortable + ')', settings.columns);
            })();
        
        $sortableItems.find(settings.handleSelector).css({
            cursor: 'move'
        }).mousedown(function (e) {
            $sortableItems.css({width:''});
            jQuery(this).parent().css({
                width: jQuery(this).parent().width() + 'px'
            });
        }).mouseup(function () {
            if(!jQuery(this).parent().hasClass('dragging')) {
                jQuery(this).parent().css({width:''});
            } else {
                jQuery(settings.columns).sortable('disable');
            }
					//if(jQuery(this).parent().hasClass('dragging')) {
					//	jQuery(settings.columns).sortable('disable');
					//} else {
					//	jQuery(this).parent().css({width:''});
					//}
        });

        jQuery(settings.columns).sortable({
            items: $sortableItems,
            connectWith: jQuery(settings.columns),
            handle: settings.handleSelector,
            placeholder: 'widget-placeholder',
            forcePlaceholderSize: true,
            revert: 300,
            delay: 100,
            opacity: 0.8,
            containment: 'document',
            start: function (e,ui) {
                jQuery(ui.helper).addClass('dragging');
            },
            stop: function (e,ui) {
                jQuery(ui.item).css({width:''}).removeClass('dragging');
                jQuery(settings.columns).sortable('enable');
                /* Save prefs to cookie: */
                iNettuts.savePreferences();
            }
        });
    },
    
    savePreferences : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            cookieString = '';
            
        if(!settings.saveToCookie) {return;}
        
        /* Assemble the cookie string */
        jQuery(settings.columns).each(function(i){
            cookieString += (i===0) ? '' : '|';
            jQuery(settings.widgetSelector,this).each(function(i){
                cookieString += (i===0) ? '' : ';';
                cookieString += jQuery(this).attr('id') + ',';
                cookieString += jQuery(settings.contentSelector,this).css('display') === 'none' ? 'collapsed' : 'not-collapsed';
            });
        });
        	//alert (cookieString);
        	/*
					jQuery.cookie(settings.saveToCookie,cookieString,{
            expires: 10
            //path: '/'
 		       });
 		      */
 		      //alert (cookieString);
 		      //getData('preferences-save.php', 'myLayout=' + cookieString);
 		      jQuery.post("preferences-save.php", { myLayout: cookieString} );

    },

    delPreferences : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings,
            cookieString = '';
				jQuery.cookie(settings.saveToCookie,'',{ expires: -1 }); 
				location.reload(); 
    },

    viewWidgets : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings;

				jQuery( "#widgetlist").hide();
				jQuery( "#columns").show();
    },

   
    sortWidgets : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings;
        
        /* Read cookie: */
        var cookie = jQuery.cookie(settings.saveToCookie);
        if(!settings.saveToCookie||!cookie) {
            /* Get rid of loading gif and show columns: */
            jQuery('body').css({background:'#F3F4F6'});
            jQuery(settings.columns).css({visibility:'visible'});
            return;
        }
        
        /* For each column */
        jQuery(settings.columns).each(function(i){
            
            var thisColumn = jQuery(this),
                widgetData = cookie.split('|')[i].split(';');
                
            jQuery(widgetData).each(function(){
                if(!this.length) {return;}
                var thisWidgetData = this.split(','),
                    clonedWidget = jQuery('#' + thisWidgetData[0]),
                    colorStylePattern = /\bcolor-[\w]{1,}\b/,
                    thisWidgetColorClass = jQuery(clonedWidget).attr('class').match(colorStylePattern);
                
                /* Add/Replace new colour class: */
                if (thisWidgetColorClass) {
                    jQuery(clonedWidget).removeClass(thisWidgetColorClass[0]).addClass(thisWidgetData[1]);
                }
                
                /* Add/replace new title (Bring back reserved characters): */
                jQuery(clonedWidget).find('h3:eq(0)').html(thisWidgetData[2].replace(/\[-PIPE-\]/g,'|').replace(/\[-COMMA-\]/g,','));
                
                /* Modify collapsed state if needed: */
                if(thisWidgetData[3]==='collapsed') {
                    /* Set CSS styles so widget is in COLLAPSED state */
                    jQuery(clonedWidget).addClass('collapsed');
                }

                jQuery('#' + thisWidgetData[0]).remove();
                jQuery(thisColumn).append(clonedWidget);
            });
        });
        
        /* All done, remove loading gif and show columns: */
        jQuery('body').css({background:'#000'});
        jQuery(settings.columns).css({visibility:'visible'});
    }
  
};

iNettuts.init();


