/*
 * Original code from:
 * Script from NETTUTS.com [by James Padolsey] V.2 (ENHANCED, WITH COOKIES!!!)
 * @requires jQuery($), jQuery UI & sortable/draggable UI modules & jQuery COOKIE plugin
 */

var dashboard = {
    
    jQuery : $,
    
    settings : {
				columns : '.column1, .column2, .column3',
				widgetSelector: '.widget',
				handleSelector: '.widget-head',
				contentSelector: '.widget-content',
				
				baseurl: location.href.substring(0,location.href.lastIndexOf('/')+1), //put a "+1" if you want the last forward slash:
				
				/* If you don't want preferences to be saved change this value to
					false, otherwise change it to the name of the cookie: */
				saveToCookie: false,
				//saveToCookie: 'MsAuctionDashboardSettings',
				saveTitles: false, //Mewsoft added

				widgetDefault : {
					movable: true,
					removable: false,
					collapsible: true,
					editable: true,
					saveTitles: false,
					colorClasses : ['color-red', 'color-blue', 'color-green', 'color-purpple', 'color-white', 'color-orange', 'color-yellow', 'color-gray', 'color-pink',  'color-black' ]
				},

				widgetIndividual : {}
				/*
				widgetIndividual : {
					intro : {
						movable: false,
						removable: true,
						collapsible: true,
						editable: true,
						saveTitles: false
					}
				}
				*/

    }, // settings
	
	//-------------------------------------------------------------------------
	//-------------------------------------------------------------------------
	// added by Mewsoft
	options: function (opts) {
			//var opts = $.extend({}, $.fn.expander.defaults, options);
			var $ = this.jQuery;
			this.settings = $.extend({}, this.settings, opts);
	},

    init : function () {
        //this.attachStylesheet('inettuts.js.css');
        this.sortWidgets();
        this.addWidgetControls();
        this.makeSortable();
    },
    
    getWidgetSettings : function (id) {
        var $ = this.jQuery,
         settings = this.settings;
		return  (id && settings.widgetIndividual[id]) ? settings.widgetIndividual[id] : settings.widgetDefault;
    },
    
    addWidgetControls : function () {
        var dashboard = this,
            $ = this.jQuery,
            settings = this.settings;
            
        $(settings.widgetSelector, $(settings.columns)).each(function () {
            var thisWidgetSettings = dashboard.getWidgetSettings(this.id);
            if (thisWidgetSettings.removable) {
                $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).click(function () {
                    if(confirm('This widget will be removed, ok?')) {
                        $(this).parents(settings.widgetSelector).animate({
                            opacity: 0    
                        },function () {
                            $(this).slideUp(function () {
                                $(this).toggleClass('closed');
								/* Save prefs to cookie: */
                                dashboard.savePreferences();
                            });
                        });
                    }
                    return false;
                }).appendTo($(settings.handleSelector, this));
            }
            
            if (thisWidgetSettings.editable) {
                $('<a href="#" class="edit">Edit</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).toggle(function () {
					//original line
                    //$(this).css({backgroundPosition: '-66px 0', width: '55px'})
					//changed to this to show the close icon and hide the edit icon to save space
					$(this).css({backgroundPosition: '-66px 0', width: '31px'})
					//changed to this to hide the close icon to save space
					//$(this).css({backgroundPosition: '0px 0', width: '24px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').show().find('input').focus();
                    return false;
                },function () {
                    $(this).css({backgroundPosition: '', width: '24px'})
                        .parents(settings.widgetSelector)
                            .find('.edit-box').hide();
                    return false;
                }).appendTo($(settings.handleSelector,this));
                $('<div class="edit-box" style="display:none;"/>')
					// comment the line below to disable editing the widget titles. Added by Mewsoft
                    //.append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')
                    .append((function(){
                        var colorList = '<li class="item"><label>Select Color: &nbsp;</label><br><ul class="colors">';
                        $(thisWidgetSettings.colorClasses).each(function () {
                            colorList += '<li class="' + this + '"/>';
                        });
                        return colorList + '</ul>';
                    })())
                    .append('</ul>')
                    .insertAfter($(settings.handleSelector,this));
            }
            
            if (thisWidgetSettings.collapsible) {
				// added by Mewsoft, modifiy the line below as this:
				$('<a href="#" class="collapse"></a>').mousedown(function (e) {
                //$('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).click(function(){
                    $(this).parents(settings.widgetSelector).toggleClass('collapsed');
                    /* Save prefs to cookie: */
                    dashboard.savePreferences();
                    return false;    
                }).prependTo($(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() );
                dashboard.savePreferences();
            });
            $('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]);
                    /* Save prefs to cookie: */
                    dashboard.savePreferences();
                }
                return false;
                
            });
        });
        
    },
    
    attachStylesheet : function (href) {
        var $ = this.jQuery;
		//use full path, IE needs full URL to the script file
		return $('<link href="' +this.settings.baseurl+href + '" rel="stylesheet" type="text/css" />').appendTo('head');
    },
    
    makeSortable : function () {
        var dashboard = this,
            $ = this.jQuery,
            settings = this.settings,
            $sortableItems = (function () {
				var notSortable = '';
                $(settings.widgetSelector,$(settings.columns)).each(function (i) {
                    if (!dashboard.getWidgetSettings(this.id).movable) {
                        if(!this.id) {
                            this.id = 'widget-no-id-' + i;
                        }
                        notSortable += '#' + this.id + ',';
                    }
                });
                
				//original line
				// this line generates error in IE, do not uncomment
				//return $('> li:not(' + notSortable + ')', settings.columns);

				//fix for 1.3.x: http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/comment-page-4/#comments
				return $('> li', settings.columns).not(notSortable);
				
				// another fix: http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/comment-page-4/#comments
				//var selector = '> li';
				//if(notSortable && notSortable != '')selector = '> li:not(' + notSortable + ')';
				//return $(selector, settings.columns);

				//fix: http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/comment-page-4/#comments
				//return notSortable != "" ? $('> li:not("' + notSortable + '")', settings.columns) : $('> li', settings.columns);

				//fix for chrome : http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/comment-page-7/#comments
				//$sortableItems.find(settings.handleSelector).disableSelection().css({cursor: 'move'});

            })();
        
        $sortableItems.find(settings.handleSelector).css({
            cursor: 'move'
        }).mousedown(function (e) {
            $sortableItems.css({width:''});
            $(this).parent().css({
                width: $(this).parent().width() + 'px'
            });
        }).mouseup(function () {
			//fix: http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/comment-page-4/#comments
            //if(!$(this).parent().hasClass('dragging')) {
             //   $(this).parent().css({width:''});
            //} else {
			if($(this).parent().hasClass('dragging')) { //added this line
                $(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');
				//fix: http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/comment-page-6/#comments
				//—> For the resolution of place holder’s height issue which doesn’t come properly for IE6 & IE7
				//$(ui.placeholder).css({height:(ui.item).height()+'px', border: '2px dashed #ff6600'});
				$(ui.placeholder).css({height:(ui.item).height()+'px'});
				
				//disable text selection during move, for IE. added by Mewsoft
				$(settings.widgetSelector, settings.columns).disableSelection();

			},
            
			stop: function (e,ui) {
                $(ui.item).css({width:''}).removeClass('dragging');
                $(settings.columns).sortable('enable');
				
				//re-enable text selection during move, for IE. added by Mewsoft
				$(settings.widgetSelector, settings.columns).enableSelection();

                /* Save prefs to cookie: */
                dashboard.savePreferences();
            }
        });
    },
    
	// Call toggleEditable with the id of the widget you want to toggle editable property. For example: dashboard.toggleEditable(2);
	// http://jsabino.wordpress.com/2009/09/19/how-to-mimic-the-igoogle-interface-with-database/
	toggleEditable : function (id) {
        var $ = this.jQuery,
         settings = this.settings;
        dashboard.getWidgetSettings(this.id).editable=!dashboard.getWidgetSettings(this.id).editable;

        var w=$(settings.widgetSelector, $(settings.columns)).get(id);
        if (dashboard.getWidgetSettings(this.id).editable)
          $(".edit",w).css({visibility:'visible'});
        else
          $(".edit",w).css({visibility:'hidden'});

        return ;
    },

    savePreferences : function () {
        var dashboard = this,
            $ = this.jQuery,
            settings = this.settings,
            cookieString = '';
            
        if(!settings.saveToCookie) {return;}
        
        /* Assemble the cookie string */
        $(settings.columns).each(function(i){
            cookieString += (i===0) ? '' : '|';
            $(settings.widgetSelector,this).each(function(i){
                cookieString += (i===0) ? '' : ';';
                /* ID of widget: */
                cookieString += $(this).attr('id') + ',';
                /* Color of widget (color classes) */
                cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ',';
                
				//Mewsoft
				if (settings.saveTitles){
					/* Title of widget (replaced used characters) */
					cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ',';
				}
				else{
					cookieString += ',';
				}

                /* Collapsed/not collapsed widget? : */
                cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed,' : 'not-collapsed,';                
                /* Closed/not closed widget? : */
                cookieString += $(settings.handleSelector,this).css('display') === 'none' ? 'closed' : 'not-closed';
            });
        });
		
		// http://jsabino.wordpress.com/2009/09/19/how-to-mimic-the-igoogle-interface-with-database/
        /* AJAX call to store string on database */
        //$.post("dashboard_rpc.php","value="+cookieString); // ="+encodeURIComponent(cookieString));

        $.cookie(settings.saveToCookie, cookieString, {
            expires: 3650,
            path: '/'
        });
    },
    
    sortWidgets : function () {
        var dashboard = this,
            $ = this.jQuery,
            settings = this.settings;
        
        /* Read cookie: */
        var cookie = $.cookie(settings.saveToCookie);
        if(!settings.saveToCookie||!cookie) {
            /* Get rid of loading gif and show columns: */
            //$('body').css({background:'#000'});
            $(settings.columns).css({visibility:'visible'});
            return;
        }
        
        /* For each column */
        $(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);
                
                /* Add/Replace new colour class: */
                if (thisWidgetColorClass) {
                    $(clonedWidget).removeClass(thisWidgetColorClass[0]).addClass(thisWidgetData[1]);
                }
                
				if (settings.saveTitles){//Mewsoft added
					/* Add/replace new title (Bring back reserved characters): */
					$(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 */
                    $(clonedWidget).addClass('collapsed');
                }

                /* Modify closed state if needed: */                
                if(thisWidgetData[4]==='closed') {
                    /* Set CSS styles so widget is in CLOSED state */
                    $(clonedWidget).addClass('closed');
                }

                $('#' + thisWidgetData[0]).remove();
                $(thisColumn).append(clonedWidget);
            });
        });
        
        /* All done, remove loading gif and show columns: */
		/*removes background color black added by Mewsoft*/
        /* $('body').css({background:'url(images/background.gif) repeat-y top center'});*/
		/*original line: $('body').css({background:'#000'});*/
        $(settings.columns).css({visibility:'visible'});
    },
	
	//fix : http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/comment-page-6/#comments
	//so that the placeholder is shown with a dashed border and no text gets selected during dragging (tested only with IE7):
	disableTextSelection : function (targets) {
		$(targets).each(function(){
			if ('undefined' != typeof this.onselectstart) { // onselectstart is an IE-specific event
				this.onselectstart = function(){return false;};
			}
		});
	},
	enableTextSelection : function (targets) {
		$(targets).each(function(){
			if ('undefined' != typeof this.onselectstart) { // onselectstart is an IE-specific event
				this.onselectstart = function(){return true;};
			}
		});
	},
	//---------------------------------------------------------------------------------------------
	// code from http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/comment-page-2/#comments
	//---------------------------------------------------------------------------------------------
/*
function insertWidget(where, opt) {
	var selectorOld = dashboard.settings.widgetSelector;
	dashboard.settings.widgetSelector = '.new';
	salida = '<li class="new widget color-'+opt.color+'"><div class="widget-head"><h3>'+opt.title+'</h3></div><div class="widget-content"><p>'+opt.content+'</p></div></li>';
	$(where).append(salida);
	dashboard.addWidgetControls();
	dashboard.settings.widgetSelector = selectorOld;
}
insertWidget("#column1", {
color: "blue",
title: "Prueba",
content: "ESTO ES UNA PRUEBA"
});
*/

/*
function deletesettings()
{
    var d = new Date();
    document.cookie = "inettuts-widget-preferences=;v0=1;expires=" + d.toGMTString() + ";" + ";";
}
// or use jquer function
$.cookie('cookie-name',null));

*/

	//---------------------------------------------------------------------------------------------
	//				Saving to database
	//---------------------------------------------------------------------------------------------
	//These 2 functions for saving and loading settings from database on the server,
	// rename these to savePreferences, sortWidgets and rename the above 2 to anything.
    savePreferences1 : function () {
        var dashboard = this,
            $ = this.jQuery,
            settings = this.settings,
            cookieString = '';
            
        if(!settings.saveToCookie) {return;}
        
        /* Assemble the cookie string */
        $(settings.columns).each(function(i){
            cookieString += (i===0) ? '' : '|';
            $(settings.widgetSelector,this).each(function(i){
                cookieString += (i===0) ? '' : ';';
                /* ID of widget: */
                cookieString += $(this).attr('id') + ',';
                /* Color of widget (color classes) */
                cookieString += $(this).attr('class').match(/\bcolor-[\w]{1,}\b/) + ',';
                /* Title of widget (replaced used characters) */
                cookieString += $('h3:eq(0)',this).text().replace(/\|/g,'[-PIPE-]').replace(/,/g,'[-COMMA-]') + ',';
                /* Collapsed/not collapsed widget? : */
                cookieString += $(settings.contentSelector,this).css('display') === 'none' ? 'collapsed' : 'not-collapsed';
            });
        });
        
        /* AJAX call to store string on database */
        $.post("dashboard_rpc.php","value="+cookieString);
        
    },
    

    sortWidgets1 : function () {
        var dashboard = this,
            $ = this.jQuery,
            settings = this.settings;
        
        if(!settings.saveToCookie) {
            $('body').css({background:'#000'});
            $(settings.columns).css({visibility:'visible'});
            return;
        }
        
        $.post("dashboard_rpc.php", "",
            function(data){
        
              var cookie=data;
              
              if (cookie=="") {
                  //$('body').css({background:'#000'});
                  $(settings.columns).css({visibility:'visible'});
                  dashboard.addWidgetControls();
                  dashboard.makeSortable();
                  return;
              }
               
              /* For each column */
              $(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);
                      
                      /* Add/Replace new colour class: */
                      if (thisWidgetColorClass) {
                          $(clonedWidget).removeClass(thisWidgetColorClass[0]).addClass(thisWidgetData[1]);
                      }
                      
                      /* Add/replace new title (Bring back reserved characters): */
                      $(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 */
                          $(clonedWidget).addClass('collapsed');
                      }

                      $('#' + thisWidgetData[0]).remove();
                      $(thisColumn).append(clonedWidget);
                  });
              });
              
              
              /* All done, remove loading gif and show columns: */
              //$('body').css({background:'#000'});
              $(settings.columns).css({visibility:'visible'});
              
              dashboard.addWidgetControls();
			  //$(settings.columns).sortable(‘destroy’); // see http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/comment-page-2/#comments
              dashboard.makeSortable();
              
            });

    }
	//---------------------------------------------------------------------------------------------
	//				End of Saving to database
	//---------------------------------------------------------------------------------------------

};

//dashboard.init();
