/*
 * @requires jQuery($), jQuery UI & sortable/draggable UI modules
 */

var iWidgets = {

	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: 'widget-preferences',
        widgetDefault : {
            movable: true,
            removable: false,
            collapsible: true,
            editable: false,
            modalable: false,
            colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green']
        },
        widgetIndividual : {
            quicklinks : {
                movable: false,
                collapsible: false
            },
            profile : {
                removable: false,
                modalable: true,
                modalableFunction: "loadModalProfileUpdate"
            },
            picture : {
                removable: false,
                editable: true
            },
            news : {
                removable: false
            },
            weather : {
                removable: false,
                colorClasses : ['yellow','red','white'] ,
                weatherOptions : [['1','Current Weather'],['4','next 4 days']]
            },
            competitionEntries : {
                removable: false
            },
            charts : {
                removable: false
            },
            referrals : {
                removable: false
            },
            privacy : {
                modalable: true,
                modalableFunction: "loadModalPrivacyUpdate",
                removable: false
            }
        }
    },

    init : function () {
        this.attachStylesheet('styles/widgets.js.css');
        this.sortWidgets();
        this.addWidgetControls();
        this.makeSortable();
    },
    cookie : function(name, value, options) {
        if (typeof value != 'undefined') {
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    },
    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 iWidgets = this,
            $ = this.jQuery,
            settings = this.settings;

        $(settings.widgetSelector, $(settings.columns)).each(function () {
            var thisWidgetSettings = iWidgets.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: */
                                iWidgets.savePreferences();
                            });
                        });
                    }
                    return false;
                }).appendTo($(settings.handleSelector, this));
            }



            if (thisWidgetSettings.editable) {
                  /* Standard Edit stuff */
                  $('<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();

                      /* CUSTOM START */
                      $('#pictureError').html("");
                      /* CUSTOM END */
                      return false;
                  },function () {
                      $(this).css({backgroundPosition: '', width: ''})
                          .parents(settings.widgetSelector)
                              .find('.edit-box').hide();
                      return false;
                  }).appendTo($(settings.handleSelector,this));

                /* CUSTOM START */
                  if(this.id == 'picture') {
                      $('<div class="edit-box" style="display:none;" id="pictureEdit"/>')
                          .append((function(){
                              var weatherList = '<ul>';
                              var weatherList2 = '<form id="picForm" method="post" action="file-upload.htm" enctype="multipart/form-data">';
                              var weatherList3 = '<li class="item"><label><input id="picture_input" type="file" name="file" /></label></li>';
                              var weatherList4 = '</form>';
                              var weatherList5 = '<li class="item"><label><span class="blk_link"><span><a id="uploadPic" href="" class="wht9">upload picture</a></span></span></label></li>';
                              return weatherList + weatherList2 + weatherList3 + weatherList4+ weatherList5;
                          })())
                          .append('</ul><div id="pictureError"></div>')
                          .insertAfter($(settings.handleSelector,this));
                  }
                  /* CUSTOM END */

            }



            if (thisWidgetSettings.modalable) {
                $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {
                    e.stopPropagation();
                }).click(function(){
                    if(thisWidgetSettings.modalableFunction == 'loadModalProfileUpdate'){
                        loadModalProfileUpdate();
                    }
                    if(thisWidgetSettings.modalableFunction == 'loadModalPrivacyUpdate'){
                        loadModalPrivacyUpdate();
                    }
                    return false;
                }).appendTo($(settings.handleSelector,this));
            }


            if (thisWidgetSettings.collapsible) {
                $('<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: */
                    iWidgets.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() );
                iWidgets.savePreferences();
            });
            $('#uploadPic').click(function() {
                var options = {
                    clearForm: true,
                    resetForm: true,
                    beforeSubmit: validatePicture,
                    target:'#pictureContent'
                }
                $('#picForm').ajaxSubmit(options);
                return false;
            });



            $('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: */
                    iWidgets.savePreferences();
                }
                return false;

            });
        });

    },
    attachStylesheet : function (href) {
        var $ = this.jQuery;
        return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
    },

    makeSortable : function () {
        var iWidgets = this,
            $ = this.jQuery,
            settings = this.settings,
            $sortableItems = (function () {
                // JONATHAN
                // Patch for jquery.1.3.2 is was
                // var notSortable = Ó;
                var notSortable = '#none,';
                $(settings.widgetSelector,$(settings.columns)).each(function (i) {
                    if (!iWidgets.getWidgetSettings(this.id).movable) {
                        if(!this.id) {
                            this.id = 'widget-no-id-' + i;
                        }
                        notSortable += '#' + this.id + ',';
                    }
                });

                // JONATHAN
                // BUG FIX
                //return $('> li:not(' + notSortable + ')', settings.columns);
                var selector = '> li';
                if(notSortable && notSortable != '')
                selector = '> li:not(' + notSortable + ')';
                return $(selector, 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')) {
                // JONATHAN
                // Patch for jquery.1.3.2
                //$(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');
                /* Save prefs to cookie: */
                iWidgets.savePreferences();
            }
        });
    },

    savePreferences : function () {
        var iWidgets = 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,';
                /* Closed/not closed widget? : */
                cookieString += $(settings.handleSelector,this).css('display') === 'none' ? 'closed' : 'not-closed';
            });
        });
        this.cookie(settings.saveToCookie,cookieString,{
            expires: 10
            //path: '/'
        });
    },

    sortWidgets : function () {
        var iWidgets = this,
            $ = this.jQuery,
            settings = this.settings;

        /* Read cookie: */
        var cookie = this.cookie(settings.saveToCookie);
        if(!settings.saveToCookie||!cookie) {
            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');
                }

                /* 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);
            });
        });

    }
};
$(document).ready(function(){
	iWidgets.init();
});