/*
 * 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: 'tir-widget-preferences',
        
        widgetDefault : {
            movable: true,
            removable: (userLoggedIn)?true:false,
            collapsible: true,
            editable: (userLoggedIn)?true:false,
            colorClasses : ['color-yellow', 'color-red', 'color-blue', 'color-white', 'color-orange', 'color-green']
        },
        widgetIndividual : {}
    },

    init : function () {
        this.attachStylesheet(siteUrl+'/view/css/widget.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);
            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).wrap('<div/>').parent().slideUp(function () {
                                $(this).remove();
                            });
                        });
						
						iNettuts.removePreferences($(this).parents(settings.widgetSelector).attr('id'));
                    }
                    return false;
                }).appendTo($(settings.handleSelector, this));
            }
            
			if($(this).find("h3").text() != 'News Letter' && $(this).find("h3").text() != 'Search' && $(this).find("h3").text() != 'Feature Inspiration' && $(this).find("h3").text() !=  'What is TIR?') // && $(this).find("h3").text() != 'Industry Feeds'
			{
            	if (thisWidgetSettings.editable) {	
				
				$(this).find('h3').text( $(this).find("h3").text().length>17 ? $(this).find("h3").text().substr(0,16)+'...' : $(this).find("h3").text() );
				
				
                $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).toggle(function () {
					if($(this).parents(settings.widgetSelector).find('.edit-box').is(":hidden"))
					{
						$(this).css({backgroundPosition: '', width: '56px'})
							.parents(settings.widgetSelector)
								.find('.edit-box').show().find('input').focus();
						return false;
					}else{
						$(this).css({backgroundPosition: '', width: '56px'})
							.parents(settings.widgetSelector)
								.find('.edit-box').hide();
						return false;
					}
                },function () {
                   if($(this).parents(settings.widgetSelector).find('.edit-box').is(":hidden"))
					{
						$(this).css({backgroundPosition: '', width: '56px'})
							.parents(settings.widgetSelector)
								.find('.edit-box').show().find('input').focus();
						return false;
					}else{
						$(this).css({backgroundPosition: '', width: '56px'})
							.parents(settings.widgetSelector)
								.find('.edit-box').hide();
						return false;
					}
                }).appendTo($(settings.handleSelector,this));
					
					if($(this).find("h6").text() == 'Weather') {
						$('<div class="edit-box" id="WeatherEditBoxId" style="display:none;"/>')
						.append('<form name="WeatherWidgetForm" method="POST"><ul><li class="item"><label>Country</label><select class="style13" name="WeatherCountryId" id="WeatherCountryId" style="width:200px;" onchange="GetWeatherCities(this.value);"><option value="">Select Country</option>'+countriesArray+'</select></li><li class="item"><label>City</label><select class="style13" name="WeatherCityName" id="WeatherCityNameId" style="width:200px;"><option value="">Select City</option>'+citiesArray+'</select></li><li class="item1"><table border="0" width="100%" align="center"><tr><td width="50%" align="right"><input type="radio" name="WeatherUnit" id="CelsiusId" value="C"'+((weatherUnit == 'C')?' checked':'')+'/>Celsius</td><td><input type="radio" name="WeatherUnit" id="FahrenheitId" value="F"'+((weatherUnit == 'F')?' checked':'')+'/>Fahrenheit</td></tr></table></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateWeatherWidgetForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#WeatherEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'News Feeds') {
						$('<div class="edit-box" id="NewsFeedsEditBoxId" style="display:none;"/>')
						.append('<form name="NewsFeedsWidgetForm" method="POST"><ul><li class="item"><label>Country</label><select class="style13" name="NewsFeedsCountryId" id="NewsFeedsCountryId" style="width:200px;">'+newsfeedsCountries+'</select></li><li class="item"><label>View</label><select class="style13" name="NewsFeedViewID" id="NewsFeedViewID" style="width:200px;">'+newsfeedsview+'</select></li><li class="item"><label>Number of items to display</label><select class="style13" name="NumOfItemsId" id="NumOfItemsId" style="width:200px;">'+NumOfItemsArray+'</select></li><li class="item"><label>Show Post Date</label><input type="checkbox" name="newsPostDate" id="newsPostDate" checked="checked"/></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateNewsFeedsForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#NewsFeedsEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'Industry Feeds') {
						$('<div class="edit-box" id="IndustryFeedsEditBoxId" style="display:none;"/>')
						.append('<form name="IndustryFeedsWidgetForm" method="POST"><ul><li class="item"><label>View</label><select class="style13" name="IndustryFeedViewID" id="IndustryFeedViewID" style="width:200px;">'+industryfeedsview+'</select></li><li class="item"><label>Number of items to display</label><select class="style13" name="IndustryNumOfItemsId" id="IndustryNumOfItemsId" style="width:200px;">'+IndustryNumOfItemsArray+'</select></li><li class="item"><label>Show Post Date</label><input type="checkbox" name="industryPostDate" id="industryPostDate" '+userIndustrySelectedShowPostDate+' /></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateIndustryFeedsForm(\'edit_industry\')">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#IndustryFeedsEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'Daily Inspiration') {
						$('<div class="edit-box" id="DailyBlogFeedsEditBoxId" style="display:none;"/>')
						.append('<form name="DailyBlogFeedsWidgetForm" method="POST"><ul><li class="item"><label>View</label><select class="style13" name="DailyBlogFeedViewID" id="DailyBlogFeedViewID" style="width:200px;">'+dailyblogfeedsview+'</select></li><li class="item"><label>Number of items to display</label><select class="style13" name="DailyBlogNumOfItemsId" id="DailyBlogNumOfItemsId" style="width:200px;">'+dailyblogNumOfItemsArray+'</select></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateDailyBlogFeedsForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#DailyBlogFeedsEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'Latest Uploads') {
						$('<div class="edit-box" id="LatestUploadsEditBoxId" style="display:none;"/>')
						.append('<form name="LatestUploadsWidgetForm" method="POST"><ul><li><label style="width: 100%;">Choose which categories to display</label></li>'+latestUploadsWidgetCategoriesArray+'<li class="item"><label style="width: 100%;">Display feeds by Country</label></li>'+latesUploadsWidgetCountriesArray+'<li class="item"><label style="width: 100%;">Display feeds by Popularity</label></li><li class="item1"><table border="0" width="100%"><tr><td width="50%"><input type="checkbox" name="MostViewed" id="LatestUploadMostViewedId" value="MostViewed"'+((latestUploadsMostViewed == '1')?' checked':'')+'/>Most Viewed</td><td><input type="checkbox" name="MostCommented" id="LatestUploadMostCommentedId" value="Most Commented"'+((latestUploadsMostCommented == '1')?' checked':'')+'/>Most Commented/Tagged</td></tr><tr><td width="50%"><input type="checkbox" name="MostEmailed" id="LatestUploadMostEmailedId" value="MostEmailed"'+((latestUploadsMostEmailed == '1')?' checked':'')+'/>Most Emailed/Forwarded</td><td>&nbsp;</td></tr></table></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateLatestUploadsForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#LatestUploadsEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'News Letter') {
						$('<div class="edit-box" id="NewsLetterEditBoxId" style="display:none;"/>')
						.append('<form name="NewsLetterWidgetForm" method="POST"><ul><li class="item"><label style="width: 100%;">Edit Frequency</label></li><li class="item1"><table border="0" width="100%"><tr><td width="50%"><input type="radio" name="Frequency" id="TwiceDailyId" value="TD"'+((frequency == 'TD')?' checked':'')+'/>Twice Daily</td><td><input type="radio" name="Frequency" id="DailyId" value="D"'+((frequency == 'D')?' checked':'')+'/>Daily</td></tr><tr><td width="50%"><input type="radio" name="Frequency" id="TwiceWeeklyId" value="TW"'+((frequency == 'TW')?' checked':'')+'/>Twice Weekly</td><td><input type="radio" name="Frequency" id="WeeklyId" value="W"'+((frequency == 'W')?' checked':'')+'/>Weekly</td></tr><tr><td width="50%"><input type="radio" name="Frequency" id="MonthlyId" value="M"'+((frequency == 'M')?' checked':'')+'/>Monthly</td><td>&nbsp;</td></tr></table></li><li class="item"><label style="width: 100%;">Delivery Format</label></li><li class="item1"><table border="0" width="100%"><tr><td width="50%"><input type="radio" name="DeliveryFormat" id="HtmlId" value="H"'+((deliveryFormat == 'H')?' checked':'')+'/>HTML</td><td><input type="radio" name="DeliveryFormat" id="TextId" value="T"'+((deliveryFormat == 'T')?' checked':'')+'/>Text</td></tr></table></li><li class="item1"><span><input type="checkbox" name="InviteFriendForNL" id="InviteFriendForNLId" value="1"'+((inviteFriendForNL == '1')?' checked':'')+'/>Invite a Friend</span></li><li class="item1"><span><input type="checkbox" name="SignUpForNL" id="SignUpForNLId" value="1"'+((signUpForNL == '1')?' checked':'')+'/>Sign Up</span></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateNewsLetterForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#NewsLetterEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'Podcast') {
						$('<div class="edit-box" id="PodcastEditBoxId" style="display:none;"/>')
						.append('<form name="PodcastWidgetForm" method="POST"><ul><li class="item1"><span><input type="checkbox" name="ListRecent" id="ListRecentId" value="1"'+((podcastListRecent == "1")?' checked':'')+'/>List recent</span></li><li class="item1"><span><input type="checkbox" name="InviteFriend" id="InviteFriendId" value="1"'+((podcastInviteFriend == "1")?' checked':'')+'/>Invite a Friend</span></li><li class="item1"><span><input type="checkbox" name="SignUp" id="SignUpId" value="1"'+((podcastSignUp == "1")?' checked':'')+'/>Sign Up</span></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidatePodcastForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#PodcastEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'Search') {
						$('<div class="edit-box" id="SiteSearchEditBoxId" style="display:none;"/>')
						.append('<form name="SiteSearchWidgetForm" method="POST"><ul><li class="item"><label>Filter by</label><select class="style13" name="FilterBy" id="FilterById" onChange="SiteSearchOptions(this.value)"><option value="">Select</option><option value="All">All</option><option value="Categories">Categories</option><option value="News">News</option><option value="Podcasts">Podcasts</option></select></li><li class="item" id="SiteSearchSearchTextOptionsId"></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateSiteSearchForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#SiteSearchEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'World Map mini-feed') {
						$('<div class="edit-box" id="WorldMapEditBoxId" style="display:none;"/>')
						.append('<form name="WorldMapWidgetForm" method="POST"><ul><li class="item"><label>Country</label><select class="style13" name="WorldMapCountryId" id="WorldMapCountryId" style="width:200px;" onchange="GetWorldMapCities(this.value);"><option value="">Select Country</option>'+countriesArray+'</select></li><li class="item"><label>City</label><select class="style13" name="WorldMapCityName" id="WorldMapCityNameId" size="10" multiple="multiple" style="width:200px;"><option value="">Select City</option>'+citiesArray+'</select></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateWorldMapWidgetForm(document.WorldMapWidgetForm.WorldMapCityName)">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#WorldMapEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'My Inspirations/Lightbox') {
						$('<div class="edit-box" id="MyInspirationsEditBoxId" style="display:none;"/>')
						.append('<form name="MyInspirationsWidgetForm" method="POST"><ul><li class="item"><label>Contributors</label><select class="style13" name="ContributorId" id="ContributorId" style="width:200px;"><option value="">Select</option></select></li><li class="item1"><label>Send to Friend</label><input type="text" name="SendToFriend" id="SendToFriendId" value=""/></li><li class="item1"><span><input type="checkbox" name="EmailMe" id="EmailMeId" value="1"/>Email me when this artist uploads new content</span></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateMyInspirationsWidgetForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#MyInspirationsEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'Email/SMS Notifications') {
						$('<div class="edit-box" id="EmailNotificationsEditBoxId" style="display:none;"/>')
						.append('<form name="EmailNotificationsWidgetForm" method="POST"><ul><li><label style="width: 100%;">New content upload in category</label></li>'+emailNotificationsWidgetCategoriesArray+'<li>&nbsp;</li><li class="item"><font color="#FFFFFF"><input type="checkbox" name="ContentUploadNotification" id="ContentUploadNotificationId" value="1"'+((contentUploadNotification == "1")?' checked':'')+'/>On content upload by favourite artist/studio/agency</font></li><li><label style="width: 100%;">Edit email address</label></li><li class="item1"><span><input type="text" name="Email" id="EmailId" class="textfield2" value="'+emailNotificationsEmail+'"></span></li><li><label style="width: 100%;">Edit mobile number for SMS</label></li><li class="item1"><span><input name="Mobile" id="MobileId" type="text" class="textfield2" value="'+emailNotificationsMobile+'"></span></li><li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateEmailNotificationsWidgetForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#EmailNotificationsEditBoxId\').slideToggle();"></li>')
						.append('</ul></form>')
						.insertAfter($(settings.handleSelector,this));
					}else if($(this).find("h6").text() == 'Inspirations') {
						$('<div class="edit-box" id="MyInspirationEditBoxId" style="display:none;"/>')
						.append('<form name="MyInspirationWidgetForm" method="POST"><ul><li><label style="width: 100%;">Change order from here</label></li>'+categoryListArray+'<li class="item" style="padding-left:10px;"><input type="submit" value="Submit" onclick="return ValidateMyInspirationWidgetForm()">&nbsp;<input type="button" value="Cancel" onclick="javascript: $(\'#MyInspirationEditBoxId\').slideToggle();"></li></ul></form>')

						.insertAfter($(settings.handleSelector,this));
					}else{
               			$('<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) {
                    /* STOP event bubbling */
                    e.stopPropagation();    
                }).click(function(){
                    $(this).parents(settings.widgetSelector).toggleClass('collapsed');
                    /* Save prefs to cookie: */
                    iNettuts.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>16 ? $(this).val().substr(0,16)+'...' : $(this).val() );
               // iNettuts.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: */
                    iNettuts.savePreferences();
                }
                return false;
                
            });
        });
        
    },
    
    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, // Vishal
            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: */
                iNettuts.savePreferences();
            }
        });
    },
    
    savePreferences : function () {
        var iNettuts = 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';
            });
        });
		
		if(userLoggedIn) {
			saveWidgetCookies(cookieString);
		}else{
			$.cookie(settings.saveToCookie,cookieString,{
				expires: 10
				//path: '/'
			});
		}
    },
	
	removePreferences : function (widgetId) {
        var iNettuts = 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){
				if($(this).attr('id') != widgetId)
				{
					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';
				}
            });
        });
		
		if(userLoggedIn) {
			saveWidgetCookies(cookieString);
			removeUserWidget(widgetId);
		}else{
			//$.cookie(settings.saveToCookie,cookieString,{
				//expires: 10
				//path: '/'
			//});
		}
    },
    
    sortWidgets : function () {
        var iNettuts = this,
            $ = this.jQuery,
            settings = this.settings;
        
        /* Read cookie: */
        //alert(userLoggedIn);
		if(userLoggedIn) {
			var cookie = cookieStrFromDb;
		}else{
			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 = $('#' + trim_new(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'});
    }
  
};

iNettuts.init();