/*
 * Help from NETTUTS.com [by James Padolsey]
 * @requires jQuery($), jQuery UI & sortable/draggable UI modules
 */

var cprWidgets = {
    
    settings : {
    	cookie_name : 'cprWidgetLayout',
    	cookie_options : {path: '/', expires: 10 },
        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']
        },
        widgetIndividual : {
        	CPR_FEATURE_MULTIWIDGET : {
        			movable: false,
		            removable: false,
		            collapsible: true
        		},
        		CPR_NOW_MULTIWIDGET : {
        			movable: false,
		            removable: false,
		            collapsible: true
        		} 
         }
        
    },
    
    layout: {},

    init : function () {
        this.attachStylesheet('/css/widgets.js.css');
        this.addWidgetControls();
        this.makeSortable();
    },
    //layout functions:
    setLayout: function(layout) {
    	$("#CPR_FEATURE_MULTIWIDGET-slides").cycle('pause');
    	$("#cpr-polling-multiwid-slides").cycle('pause');
    	$("#CPR_NOW_MULTIWIDGET-slides").cycle('pause');
    	$("#columns").empty();
    	$("#columns").load("/lib/uwa/widgetLoader.php?rnd="+ new Date().getTime(), {}, function() {
    		
    		$("#columnLoading").hide('scale', {percent: 0}, 500, function() {
				
			});
    		
    		
    		$("#CPR_FEATURE_MULTIWIDGET-slides").cycle({
				fx: 'fade',
				speed: 'slow',
				timeout:4000,
				next: '#CPR_FEATURE_MULTIWIDGET-slides .forward',
				prev: '#CPR_FEATURE_MULTIWIDGET-slides .reverse'
			});
			$("#CPR_FEATURE_MULTIWIDGET-slides .pause").click(function(){
				$("#CPR_FEATURE_MULTIWIDGET-slides").cycle('pause');
				return false;
			});
			$("#CPR_FEATURE_MULTIWIDGET-slides .play").click(function(){
				$("#CPR_FEATURE_MULTIWIDGET-slides").cycle('resume');
				return false;
			});
			
    		
			$("#CPR_NOW_MULTIWIDGET-slides").cycle({
				fx: 'fade',
				speed: 'slow',
				timeout:7000,
				next: '#CPR_NOW_MULTIWIDGET-slides .forward',
				prev: '#CPR_NOW_MULTIWIDGET-slides .reverse'
			});
			$("#CPR_NOW_MULTIWIDGET-slides .pause").click(function(){
				$("#CPR_NOW_MULTIWIDGET-slides").cycle('pause');
				return false;
			});
			$("#CPR_NOW_MULTIWIDGET-slides .play").click(function(){
				$("#CPR_NOW_MULTIWIDGET-slides").cycle('resume');
				return false;
			});
			
			
    		
    		$("#cpr-polling-multiwid-slides").cycle({
				fx: 'fade',
				speed: 'slow',
				timeout:7000,
				next: '#cpr-polling-multiwid-slides .forward',
				prev: '#cpr-polling-multiwid-slides .reverse'
			});
			$("#cpr-polling-multiwid-slides .pause").click(function(){
				$("#cpr-polling-multiwid-slides").cycle('pause');
				return false;
			});
			$("#cpr-polling-multiwid-slides .play").click(function(){
				$("#cpr-polling-multiwid-slides").cycle('resume');
				return false;
			});
			
				
			cprWidgets.init();
			
		}); 
    },
    
    getCurrentLayout: function() {
    	
    	var counter = 1;
    	$("#column1 > li:not(#CPR_FEATURE_MULTIWIDGET, .placeholder-image)").each( function () {
    		//grab the id of the iframe
    		var iframetemp = $(this).find("iframe").attr("id");
    		var widget_id_temp = iframetemp.split("_");
    		var widget_id = widget_id_temp[1];
    		var widget_code = this.id;
    		cprWidgets.layout[widget_code] = {
    			"x": 1,
    			"y": counter,
    			"widget_code": widget_code,
    			"id": widget_id
    		};
    		
    		counter++;
    	});
    	counter = 1;
    	$("#column2 > li:not(#CPR_NOW_MULTIWIDGET, .placeholder-image)").each( function () {
    		//grab the id of the iframe
    		var iframetemp = $(this).find("iframe").attr("id");
    		var widget_id_temp = iframetemp.split("_");
    		var widget_id = widget_id_temp[1];
    		var widget_code = this.id;
    		cprWidgets.layout[widget_code] = {
    			"x": 2,
    			"y": counter,
    			"widget_code": widget_code,
    			"id": widget_id
    		};
    		counter++;
    	});
    },
    
    saveLayoutToCookie : function() {
    	this.getCurrentLayout();
    	//alert('writing cookie with ' + this.cookie_name + ' and options: ' + this.cookie_options.path + 'exp: ' + this.cookie_options.expires);
    	var jsonencodedLayout = $.toJSON(cprWidgets.layout);
    	
    	$.cookie(settings.cookie_name, jsonencodedLayout, settings.cookie_options);
    	//console.dir(cprWidgets.layout);
    	//alert($(settings.columns).sortable('serialize'));
    },
    
    getWidgetInfo: function(widget_code) {
    	
    },
    
    getAvailableWidgets: function() {
    	
    },
    
    addWidget : function(widget_code) {
    	
    	$.post('/lib/uwa/widget_gateway.php?rnd=' + new Date().getTime(),
    		{
    			action : 'widget_added',
    			widget_code: widget_code
    		}, 
    		function(data, textStatus) {
    			if (textStatus != "success")
    			{
    				alert("Sorry there was an error communicating with the database. Please try again or contact the webmaster.");
    			}
    			else
    			{
    				var addedWidget = $(data);
    				var widgetHandle;
    				//figure out column height in pixels:
    				
    				($("#column1").height() > $("#column2").height()) ?  widgetHandle = addedWidget.appendTo("#column2") : widgetHandle = addedWidget.appendTo("#column1");
    				//reset this
    				cprWidgets.addWidgetControl(widgetHandle);
    				$(settings.columns).sortable('refresh');
    				$.fn.fancybox.close();
    				cprWidgets.saveLayoutToCookie();
    				//console.dir(cprWidgets.getCurrentLayout());
    			}
    		},
    		'html'
    	);
    	
    },
    
    removeWidget: function(widget_code) {
    	cprWidgets.saveLayoutToCookie();
    	$.post('/lib/uwa/widget_gateway.php?rand=' + new Date().getTime(),
    		{
    			action : 'widget_removed',
    			widget_code: widget_code
    		});
    },
    
    widgetMoved: function(thewidget_code){
    	
    	cprWidgets.saveLayoutToCookie();
    	$.post('/lib/uwa/widget_gateway.php?rand=' + new Date().getTime(),
    		{
    			action : 'widget_moved',
    			parameters : '',
    			widget_code: thewidget_code
    		});
    	
    },
    
    resetPlaceholders: function()
    {
    	$("#column1").append('<li class="placeholder-image"><img src="/images/column-placeholder.png" /></li>');
    	$("#column1 .placeholder-image:first").remove();
    	
    },
    
    getWidgetSettings : function (id) {
        //var $ = this.jQuery,
        settings = this.settings;
        return (id&&settings.widgetIndividual[id]) ? $.extend({},settings.widgetDefault,settings.widgetIndividual[id]) : settings.widgetDefault;
        
        return this.settings.widgetDefault;
    },
    
    addWidgetControl : function(widget) {
    	var thisWidgetSettings = cprWidgets.getWidgetSettings(widget.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?')) {
                        widget.animate({
                            opacity: 0    
                        },function () {
                            $(widget).wrap('<div/>').parent().slideUp(function () {
                            	var remove_id = widget.attr("id");
                                $(this).remove();
                                //insert code to call widgetGateway to put remove row in widgetHistory
                                cprWidgets.removeWidget(remove_id);
                            });
                        });
                    }
                    return false;
                }).appendTo($(settings.handleSelector, widget));
            }
            if (thisWidgetSettings.collapsible) {
                $('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {
                    e.stopPropagation();    
                }).toggle(function () {
                    $(this).css({backgroundPosition: '-38px 0'})
                        .parents(settings.widgetSelector)
                            .find(settings.contentSelector).hide();
                    return false;
                },function () {
                    $(this).css({backgroundPosition: ''})
                        .parents(settings.widgetSelector)
                            .find(settings.contentSelector).show();
                    return false;
                }).prependTo($(settings.handleSelector,widget));
            }
            
    },
    
    addWidgetControls : function () {
        var cprWidgets = this,
            settings = this.settings;
            
        $(settings.widgetSelector, $(settings.columns)).each(function () {
            var thisWidgetSettings = cprWidgets.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?')) {
                        $(this).parents(settings.widgetSelector).animate({
                            opacity: 0    
                        },function () {
                            $(this).wrap('<div/>').parent().slideUp(function () {
                            	var remove_id = this.id;
                                $(this).remove();
                                //insert code to call widgetGateway to put remove row in widgetHistory
                                cprWidgets.removeWidget(remove_id);
                            });
                        });
                    }
                    return false;
                }).appendTo($(settings.handleSelector, this));
            }
            
            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,this));
                $('<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="' + this + '"/>';
                        });
                        return colorList + '</ul>';
                    })())
                    .append('</ul>')
                    .insertAfter($(settings.handleSelector,this));
            }
            
            if (thisWidgetSettings.collapsible) {
                $('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {
                    e.stopPropagation();    
                }).toggle(function () {
                    $(this).css({backgroundPosition: '-38px 0'})
                        .parents(settings.widgetSelector)
                            .find(settings.contentSelector).hide();
                    return false;
                },function () {
                    $(this).css({backgroundPosition: ''})
                        .parents(settings.widgetSelector)
                            .find(settings.contentSelector).show();
                    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() );
            });
            $('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) {
        return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
    },
    
    makeSortable : function () {
            settings = this.settings;
            /*$sortableItems = function () {
                var notSortable = '';
                $(settings.widgetSelector,$(settings.columns)).each(function (i) {
                    if (!cprWidgets.getWidgetSettings(this.id).movable) {
                        if(!this.id) {
                            this.id = 'widget-no-id-' + i;
                        }
                        notSortable += '#' + this.id + ',';
                    }
                });
                //var test = $('> li:not(' + notSortable + ')', settings.columns);
                //return $('> li:not(' + notSortable + ')', settings.columns);
                return $(settings.columns);
            };
        */
        $(settings.columns).find(settings.handleSelector).css({
            cursor: 'move'
        }).mousedown(function (e) {
            $(settings.columns).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: 'li:not(#CPR_NOW_MULTIWIDGET, #CPR_FEATURE_MULTIWIDGET, .placeholder-image)',
            connectWith: $(settings.columns),
            handle: settings.handleSelector,
            placeholder: 'widget-placeholder',
            forcePlaceholderSize: true,
            revert: 30,
            delay: 30,
            opacity: 0.8,
            //cancel: '.multiwidget',
            containment: 'document',
            start: function (e,ui) {
                $(ui.helper).addClass('dragging');
            },
            stop: function (e,ui) {
                $(ui.item).css({width:''}).removeClass('dragging');
                $(settings.columns).sortable('enable');
                //here, we need to make a call to widgetGateway and write the move to the db.
                //cprWidgets.saveLayoutToCookie();
                cprWidgets.widgetMoved(ui.item.attr("id"));
                cprWidgets.resetPlaceholders();
            }
        });
    }
  
};

function addWidgetToHomepage()
{
	
}