/* jquery easing */
if (typeof jQuery != "undefined") { 
    jQuery.extend(jQuery.easing, {
	    "easeOutQuad": function (x, t, b, c, d) {
	        return -c *(t/=d)*(t-2) + b;
        }
	});
}

/* 
====================
WEATHER 
====================
*/
/*
tanto.namespace("ndm.newscomau.weather");

  ndm.newscomau.weather.weatherclass = function(defaultWeather, callback) {
  
     var weatherURL = 'http://www.riminibeach.it/';
  
     if(!defaultWeather) {
	    /* find the default weather code*/
		defaultWeather = "n00";
/*	 }
     if(!callback) {
	    callback = function(city,distCode) { userprefs.saveWeather(city,distCode); };
	 } 
     var weatherDrop = jQuery("#weather-drop");
	 var defaultWeatherHash = "#" + defaultWeather;
	  weatherDrop.each(function() {
	     jQuery(weatherDrop).find(".tab").hide();		 
	     jQuery(this).hover(
			 function() {
			    jQuery(weatherDrop).find(".tab").show();
			 }, 
			 function() {
			    jQuery(weatherDrop).find(".tab").hide();			    
			 }
		 );
	  });
	  jQuery("#news-weather div.module-content").hide();
	  jQuery("#news-weather dd.tab a").click(function() {
	      var currentCityHash = jQuery(this).attr('href');
		  var currentCityText = jQuery(this).html();
	      jQuery("#news-weather div.module-content").hide();
		  jQuery(currentCityHash).show();
		  weatherDrop.find(".tab").hide();
		  weatherDrop.find("dt").html("<span>" + currentCityText + "</span>");
          jQuery("#weather-city a").attr("href",weatherURL + currentCityHash.replace("#",""));
	 	  jQuery("#weather-city a").html("<span>" + currentCityText + "</span>");
		  callback(currentCityText,currentCityHash.replace("#",""));
		  return false;
	  });
	 jQuery(defaultWeatherHash).show();
     jQuery("#weather-city a").attr("href",weatherURL + defaultWeather);
	 jQuery("#weather-city a").html("<span>" + weatherDrop.find('a[href="' + defaultWeatherHash +'"]').html() + "</span>");	  
	  jQuery("#news-weather").show();
  };
*/

/* 
===============================
light box for sortables
===============================
*/

ndm.newscomau.newshome.sortableLightbox = {
	lightboxElement : null,
	create : function() {
		this.lightboxElement = document.createElement('div');
		this.lightboxElement.id = "accordionLightbox";
		jQuery(this.lightboxElement).height(jQuery(document).height());

		jQuery("div.ad-header:first").prepend(this.lightboxElement); 
		jQuery(this.lightboxElement).css("width","100%");
		jQuery(this.lightboxElement).css("opacity",0.2);	
		jQuery(this.lightboxElement).css("position","absolute");		
		jQuery(this.lightboxElement).css("background-color","#000000");		
		jQuery(this.lightboxElement).css("top",0);
		jQuery(this.lightboxElement).css("left",0);	
		jQuery(this.lightboxElement).css("z-index",200);			
   	
	},
	
	destroy : function() {
		var lightbox = this.lightboxElement
		jQuery(lightbox).animate( { "opacity" : 0 },300,"linear",function() {
		jQuery(lightbox).remove();																					  
		});
	}
}

/* 
===============================
lightbox confirm 
===============================
*/
ndm.newscomau.newshome.lightboxConfirm = function(options) {

	var settings = jQuery.extend({
	   msg : "<h2>Are you sure?</h2><p>When you reset your homepage it goes back to its original settings and any changes you've made will be lost</p>",
	   yes : "Yes",
	   no : "No",
	   yescallback : function() { },
	   nocallback : function() { },
	   cancelcallback : function() {}

	},options||{});

	var lightboxElement = null;
	
	var create = function(msg) {
		this.lightboxElement = document.createElement('div');
		this.lightboxElement.id = "lighbox-confirm";
		jQuery("div.ad-header:first").append(this.lightboxElement);   
	
		createBG();
		createDialog(settings.msg);		
		jQuery("object,iframe,embed").css("visibility","hidden");
		
	};
	
	var createBG = function() {
		var lightboxBG = document.createElement('div');
		lightboxBG.className = "dialog-bg";
		jQuery(lightboxBG).height(jQuery(document).height());
		jQuery(lightboxBG).width(jQuery(document).width());
		jQuery(lightboxBG).css("opacity",0.6);
		jQuery(this.lightboxElement).append(lightboxBG);

	};
	
	var createDialog = function(msg) {
		var diablogBox = document.createElement('div');
		diablogBox.className = "dialog-box";
		
		/* close */
		var diablogBoxClose = document.createElement('a');
		diablogBoxClose.className = "close";
		diablogBoxClose.innerHTML = "Close";
		diablogBoxClose.href = "#";	
		diablogBox.appendChild(diablogBoxClose);		
	   diablogBoxClose.onclick = function() {
		   destroy();	
		   return false;			   
	   };
	   

		/* message text */
		var diablogBoxMessage = document.createElement('div');
		diablogBoxMessage.className = "message";
		diablogBoxMessage.innerHTML = msg;
		diablogBox.appendChild(diablogBoxMessage);		
		
		/* yes / no controls */
		var diablogBoxControls = document.createElement('div');
		diablogBoxControls.className = "controls";
		var diablogBoxControlsYes = document.createElement('a');
		   diablogBoxControlsYes.className = "yes";
		   diablogBoxControlsYes.innerHTML = settings.yes;
		   diablogBoxControlsYes.href ="#";
		var diablogBoxControlsNo = document.createElement('a');		
		   diablogBoxControlsNo.className = "no";		
		   diablogBoxControlsNo.innerHTML = settings.no;
		   diablogBoxControlsNo.href ="#";		   

		diablogBoxControls.appendChild(diablogBoxControlsNo);
		diablogBoxControls.appendChild(diablogBoxControlsYes);

		diablogBox.appendChild(diablogBoxControls);

		jQuery(this.lightboxElement).append(diablogBox);

	   diablogBoxControlsYes.onclick = function() {
		   settings.yescallback();
		   destroy();
		   return false;
	   };
	   diablogBoxControlsNo.onclick = function() {
		   settings.nocallback();		   
		   destroy();	
		   return false;		   
	   };
	};
	var destroy = function() {
		jQuery(this.lightboxElement).remove();																					  
		//jQuery("object,iframe,embed").css("visibility","visible");	
	
	}
	create();
}

/*
=========================
POSITION SAVED
=========================
*/
var positionSaved = function(opts) {
   var thisobj = this;
   this.positionSavedNode;
   
	this.settings = jQuery.extend({
	   message : "Position saved",
	   appendTo : "div.ad-header:first",
	   top: 0,
	   left: 0,
	   timer: 1000
	},opts||{});
   
	this.create = function() {
	   var savedNode = document.createElement('div');
	   savedNode.className = "userprefs-feedback";
	   savedNode.innerHTML = this.settings.message;
	   this.positionSavedNode = savedNode;
	   jQuery(this.settings.appendTo).append(this.positionSavedNode);
	}
	
	this.destroy = function() {
		var currentNode = jQuery(thisobj.positionSavedNode)
		//currentNode.fadeOut('fast', function() { currentNode.remove(); });
		currentNode.remove();
	} 
	
	this.init = function() {
		this.create();
		var timeout = setTimeout(this.destroy,this.settings.timer);
	}
	this.init();
} // end position saved

/*
=========================
MAP TAB
=========================
*/
jQuery.fn.mapTab = function(options) {
	var settings = jQuery.extend({
	   defaultMapPanel : ".map-panel:eq(0)",
	   mapNav : ".map-nav",
	   mapFooter : ".map-footer",	   
	   mapPanel : ".map-panel",
	   mapImage : "img.map",
	   userPrefsName : "newsloc",
	   userPrefs : false,
	   stop : function(state) { }
	},options||{});
	var currentMapTab = this;
	var selectTab = function(mapTabContainer,targetHash,ignoreStop) {
		var selectedTab = jQuery(targetHash);
		/* hide all the map panels */
		mapTabContainer.find(settings.mapPanel).each(function() {
			jQuery(this).hide();
		});
		updateActiveNav(targetHash);
		mapTabContainer.attr("class","around-australia map-tab activepanel-" + targetHash.replace("#",""));
		selectedTab.show();
		// this function can be run without the user interacting... if that happens then we will tell it to ignore the stop function
		if(ignoreStop !== true) {
		   settings.stop(targetHash.replace("#around-australia-",""));				
		}
		return false;
	}
	var updateActiveNav = function(targetHash) {
		jQuery(currentMapTab).find(settings.mapNav + ' a').each(function() {																	 
		   if(jQuery(this).attr("href") == targetHash) {
			 //  console.log(jQuery(this).attr("href") + " " + targetHash + "adding class");
		      jQuery(this).parent().addClass("active");		
		   } else {
			  // console.log(jQuery(this).attr("href") + " " + targetHash + "removing class");			   
		      jQuery(this).parent().removeClass("active");		   
		   }
		});
	}
	return this.each(function() {
		/* hide all the map panels */
		jQuery(this).find(settings.mapPanel).each(function() {
			jQuery(this).hide();
		});		
		/* 
		if there is a default map panel set via the settings then make that visible
		else make the nav visible and assign the behaviours to the click events
		 */
		if(settings.defaultMapPanel) {
			var selectedTab = jQuery(settings.defaultMapPanel);
			selectTab(jQuery(this),"#" + selectedTab.attr("id"),true);
		}
			/* asign the behaviours to the image map */
			jQuery(this).find(settings.mapNav + " area").each(function() {
				jQuery(this).click(function() {
					selectTab(jQuery(this).parent().parent().parent(), jQuery(this).attr("href"));
					return false;		
				});
				jQuery(this).mouseover(function() {
					var tabContainer = jQuery(this).parent().parent();
					var panelID = jQuery(this).attr("href");
					var mapClass = panelID.replace("#","");
					tabContainer.find(settings.mapImage).attr("class","map " + mapClass);
				});
				jQuery(this).mouseout(function() {
					var tabContainer = jQuery(this).parent().parent();
					var panelID = jQuery(this).attr("href");
					var mapClass = panelID.replace("#","");
					tabContainer.find(settings.mapImage).attr("class","map");
				});		
			}); // end map bevaiours
			/* asign the behaviours to the nav links */			
			jQuery(this).find(settings.mapNav + " li a").each(function() {
				jQuery(this).click(function() {
					selectTab(jQuery(this).parent().parent().parent().parent(),jQuery(this).attr("href"));
					return false;				
				});
			}); // end nav behaviours			
	});
}


/*
=============================
User functionality 
incorporates user tips and user prefs
=============================
*/



tanto.namespace("ndm.newscomau.hometipsclass");
tanto.namespace("ndm.newscomau.hometips");

ndm.newscomau.hometipsclass = function() {
	
	var thistips = this;
	this.hasDragged = false;
	this.hasOpened = false;

	var Usertip = function(options) {
		var thisobj = this;
		var mouseX;
		var mouseY;
		var animTimeout;
		
		this.settings = jQuery.extend({
		   trigger: function() {},
		   fixtomouse: false,
		   offsettop: 20,
		   offsetleft: 20,
		   timeout: 50,
		   show: "fadeIn",
		   hide: "hide",
		   close: "fadeOut",
		   kill: null,
		   initialState: "show",
		   secondState: "hide",
		   HTML: "tip",
		   closeHTML: null,
		   className: "tip",
		   id: null,
		   callback: function() {},
		   closecallback: function() {}
		},options||{});	
		
		this.killed = false;
		
		this.create = function() {
		   var tipNode = document.createElement('div');	
		   tipNode.className = thisobj.settings.className;
		   tipNode.id = thisobj.settings.id;		   
		   tipNodeHTML = document.createElement('div');
		   tipNodeHTML.className = "tipbody";
		   tipNodeHTML.innerHTML = thisobj.settings.HTML;
  		   tipNode.appendChild(tipNodeHTML);
		   
		   if(thisobj.settings.closeHTML != null) {
			   tipNodeClose = document.createElement('div');
			   tipNodeClose.className = "close";
			   tipNodeClose.innerHTML = thisobj.settings.closeHTML;
			   tipNode.appendChild(tipNodeClose);	
			   tipNodeClose.onclick = thisobj.close;			   
		   }

		   return tipNode;
		};
		
		this.getNode = function() {
			return this.tipNode;
		};
		
		this.initialState = function() {
			if(thisobj.killed === true) { return; } 		
			thisobj.animate(thisobj.settings.initialState);			
		}
		
	
		this.show = function() {

			thisobj.animTimeout = setTimeout(thisobj.showTip,thisobj.settings.timeout);
		};
		
		this.showTip = function() {
			if(thisobj.killed === true) { return; } 
			if(thisobj.settings.fixtomouse == true) {
				jQuery(thisobj.tipNode).css("position","absolute");
				jQuery(thisobj.tipNode).css("z-index",2000);				
				jQuery(thisobj.tipNode).css("top",mouseY - (jQuery(thisobj.tipNode).height() + thisobj.settings.offsettop));
				jQuery(thisobj.tipNode).css("left",mouseX);
			}
			thisobj.animate(thisobj.settings.show,"fast");		
		}
		
		this.hide = function() {
			if(thisobj.killed === true) { return; } 		
			clearTimeout(thisobj.animTimeout);
			thisobj.animate(thisobj.settings.hide);		
		}
	
		this.close = function() {
			if(thisobj.killed === true) { return; } 			
			thisobj.animate(thisobj.settings.close,null,thisobj.closecallback);
		};
		
		this.closecallback = function() {
			thisobj.settings.closecallback();
            userprefs.saveAccordionGroups('undefined');
			thisobj.kill();
		};
		
		this.kill = function() {
			thisobj.killed = true;
			jQuery(thisobj.tipNode).addClass("disabletip");
           
			if(thisobj.settings.kill != null) {

			   thisobj.animate(thisobj.settings.kill,null,thisobj.settings.callback);				
			} else {
			   thisobj.settings.callback();
			}
		};
		
		this.animate = function(transition,speed,callback) {

			jQuery(thisobj.tipNode)[transition](speed,callback);
		}
		
		if(this.settings.fixtomouse != null) {
			jQuery(document).mousemove(function(e) {
				mouseX = e.pageX;
				mouseY = e.pageY;
			});
		}

		this.tipNode = this.create();
		this.initialState();
		return this;
	};
	
	
	/**/
	this.useDrag = function() {
		this.hasDragged = true;
	}
	
	this.useOpen = function() {
		this.hasOpened = true;			
	}
	
	/* control closing them */
	this.userDragAndOpen = function() {
		if(thistips.hasDragged === true && thistips.hasOpened === true) {
			thistips.tipHeader.close();
			thistips.tipFooter.close();
		}		
	};
	
	this.userDragOrOpen = function() {
		if(thistips.hasDragged === true || thistips.hasOpened === true) {
			//thistips.tipHeader.close();
			//thistips.tipFooter.close();
		}
		thistips.userDragAndOpen();
	};
	
	this.userDrag = function() {
		thistips.tipTools.kill();
		thistips.useDrag();
		thistips.tipSideDrag.kill();        
		thistips.tipDrag.kill();	
	};
	
	this.userOpen = function() {
		thistips.tipTools.kill();
		thistips.useOpen();
		thistips.tipSideOpen.kill();
		thistips.tipOpen.kill();
		thistips.userDragOrOpen();
	};
	
	
	this.userKillAll = function() {
		thistips.tipHeader.kill();
		thistips.tipFooter.kill();
		thistips.tipDrag.kill();
		thistips.tipOpen.kill();		
		thistips.tipTools.kill();
		thistips.tipSideOpen.kill();
		thistips.tipSideDrag.kill();
	};
	
	/* 
	create tips 
	*/
	this.tipOpen = new Usertip({
		id: "tip-open", 
		HTML: "<p>This is the open tip</p>", 
		initialState: "hide", 
		fixtomouse: true,
		kill: "hide"
	});
	
	this.tipDrag = new Usertip({
		id: "tip-drag", 
		HTML: "<p>This is the drag tip</p>",
		initialState: "hide", 
		fixtomouse: true,
		kill: "hide"
	});	
	
	this.tipHeader = new Usertip({
		id: "tip-header", 
		HTML: '<h2>Personalizza questa pagina</h2>',
		closeHTML: "chiudi questo messaggio",		
		kill: "hide",
		close: "fadeOut"		
		//closecallback: thistips.userKillAll
	});
	
	this.tipFooter = new Usertip({
		id: "tip-footer", 
		HTML: "", 
		closeHTML: "",
		kill: "hide",
		//closecallback: thistips.userKillAll,
		kill: "fadeOut"
	});

	this.tipSideDrag = new Usertip({
		id: "tip-sidedrag", 
		HTML: "<p>This is a second tip</p>",
		closeHTML: "Close tips",
        closecallback: thistips.userDrag,	
		kill: "hide"		
	});	
	
	this.tipSideOpen = new Usertip({
		id: "tip-sideopen", 
		HTML: "<p>This is a second tip</p>",
		closeHTML: "Close tips",
        closecallback: thistips.userOpen,	
		kill: "hide"
	});	

	this.tipTools = new Usertip({
		id: "tip-tools",
		className: "tip-tools",		
		HTML: '' 
		//closecallback: thistips.userKillAll
	});

return this;
}
	ndm.newscomau.hometips = ndm.newscomau.hometipsclass();

/* 
===========================================
USER PREFS SETUP
===========================================
*/
var userprefs = {
	
	prefsMap : ["accgroup","state","accbus","accent","accspo","acctec","accmon","acctra","weatherdist","weathercity"],
	accGroupXREF : ["nat","wor","spo","bus","mon","ent","tra","tec"],
	accGroupOrder : "",
	defaultAccGroupOrder : "012345678",//[0,1,2,3,4,5,6,7,8]; // the numbers match the keys of the above names...
	userDefaultAccGroupOrder : "",
	user_accgroup : "",
	user_accbus : "",
	user_accent : "",
	user_accspo : "",
	user_accmon : "",	
	user_acctec : "",	
	user_state : "",
	user_weatherdist : "",
	user_weathercity : "",
	usedbefore: false,
	init : function() {
		ndm.user.prefs.map(this.prefsMap);	
		ndm.user.prefs.load();
		ndm.user.prefs.setVersion(1);
		this.user_accgroup = this.setPreferenceDefault(ndm.user.prefs.get("accgroup"),"012345678");	
		this.user_accbus = this.setPreferenceDefault(ndm.user.prefs.get("accbus"),"100");
		this.user_accent = this.setPreferenceDefault(ndm.user.prefs.get("accent"),"100");
		this.user_accspo = this.setPreferenceDefault(ndm.user.prefs.get("accspo"),"100");
		this.user_accmon = this.setPreferenceDefault(ndm.user.prefs.get("accmon"),"100");
		this.user_acctec = this.setPreferenceDefault(ndm.user.prefs.get("acctec"),"100");
		this.user_acctra = this.setPreferenceDefault(ndm.user.prefs.get("acctra"),"100");		
		this.user_state = this.setPreferenceDefault(ndm.user.prefs.get("state"),"all");	
		this.user_weatherdist = this.setPreferenceDefault(ndm.user.prefs.get("weatherdist"),"n00");
		this.user_weathercity = this.setPreferenceDefault(ndm.user.prefs.get("weathercity"),"Sydney");		
		this.accGroupOrder = this.user_accgroup;
		this.userDefaultAccGroupOrder = this.user_accgroup;
		jQuery(window).unload( userprefs.unload );
	}, 

	getUsedbefore: function() {
		return this.usedbefore;
	},
		unload: function() {
	
	},

	setPreferenceDefault : function(prefValue,defaultValue) {
		if(parseFloat(prefValue) < 0) {
			return defaultValue;
		} else {
			this.usedbefore = true;
			return prefValue;
		}
	},
	
	setupAccordionGroups : function(groupOrder) {

		/* convert the string to an array (thought JS did this anyway...) */
		groupOrder = groupOrder.match(/.{1}/g);
		/* loop through and place inorder
		I've reversed the order, as IE seems to tolerate HTML flaws more easily... the content is then prepended rather than appended
		*/

		groupOrder.reverse();
		for(var i=0; i<this.defaultAccGroupOrder.length;i++) {
			jQuery("#content-accordions").prepend(jQuery("#group-accordions-" + this.accGroupXREF[groupOrder[i]]));	
		} 
	},
	/* needs to be replaced with something that will initialise the accordion element directly */
	closeAccordions : function() {
		jQuery("div.module-accordion.open").each(function() {
			jQuery(this).find(".module-content").hide();
			jQuery(this).removeClass("open");
		 });
	}
	,
	resetAccordions : function() {
		this.setupAccordionGroups(this.defaultAccGroupOrder);
		this.closeAccordions();
		
		ndm.user.prefs.set("accbus", "100");
		ndm.user.prefs.set("accent", "100");
		ndm.user.prefs.set("accspo", "100");
		ndm.user.prefs.set("accmon", "100");
		ndm.user.prefs.set("acctec", "100");
		ndm.user.prefs.set("acctra", "100");	
	},
	userResetAccordions : function() {
		this.setupAccordionGroups(this.userDefaultAccGroupOrder);
	},
	
	/* this has become a bit mixed up... the function is now getting called directly by the 
	accordion object... so the references have got out of whack... must clean up...
	*/
	saveAccordionGroups : function(e) {
		userprefs.accGroupOrder = "";
		var index = 0;
		jQuery("#content-3 .group").each(function() {
		   var id = $(this).attr("id");
		   id = id.replace(/group-accordions-/,"");
		   userprefs.accGroupOrder += userprefs.getArrayKey(userprefs.accGroupXREF,id);				  
		   index++;
		});		
		/* set preferences */
		ndm.user.prefs.set("accgroup",userprefs.accGroupOrder,true,null,false,userprefs.positionSaved(e));
		//ndm.user.prefs.showUrlInInput("shareURL");		

	},
	positionSaved: function(e) {
        if(typeof e === 'undefined') { return }
		var left = e.pageX; 
		var top = e.pageY;

		var message = new positionSaved({ left: left, top: top });
	},
	saveWeather: function(city,dist) {

		ndm.user.prefs.set("weatherdist",dist);		
		ndm.user.prefs.set("weathercity",city);
	},
	getWeather : function() {

		return [this.user_weathercity,this.user_weatherdist];
	},	
	/* save accordion state
	this method is called by the stop in the accordion plugin, and is applied in this file, when the accordions are initialised
	accordionStates : string eg 1001 (1 = open 0 = closed)
	userPrefsName : string eg accbus 
	*/
	saveAccordionState : function(accordionStates,userPrefsName){
		ndm.user.prefs.set(userPrefsName,accordionStates);
	//	ndm.user.prefs.showUrlInInput("shareURL");
	},
	/*
	saveState
	state : string eg NSW 
	*/
	saveState : function(state) {
	   ndm.user.prefs.set("state",state);
	},
	
	// called by the maptab for around australia to determine which state should be shown...
	getDefaultMapPanel : function() {
		return "#around-australia-" + this.user_state;
	},
	getArrayKey : function(haystack,needle) {
		for(var i = 0; i < haystack.length; i++) {
			if(needle == haystack[i]) {
				return i;
			} // check needle to haystack
		} // end for loop
	} // end function
}

/* 
=============================
incorporates Accordions and Dragging 
====================================
*/
jQuery.fn.homeAccordions = function(options) {
	
	var settings = jQuery.extend({
	   defaultState : "10",
	   accordionContainer : ".module",
	   accordionHandle : "div.module-header",	   
	   accordionContent : "div.module-content",
	   ajaxurlPrefix : "pagelets/",
	   ajaxurlSuffix : ".php",
	   userPrefsName : "accNA",
	   stop : function(accordionState,userPrefsName) { },
	   afterload : function(currentAccordionContent) { },       
	   kill : false
	},options||{});
	
	
	if(settings.kill === true) {
		return;
	}
	
	
	/*
	when running through this script we need to have a few ways of setting the defaults
	takes settings to decide which are open
	defaults to all closed
	*/

	/* convert default state to an array */
	
	var accordionIndex = 0;
	var accordionGroup = this;
	
	/* =========================================
	accordion object, to handle all the stages of updating the elements
	========================================= */
	
	var accordions = {
		/* =========================================
		initialise accordion
		currentAccordion = jQuery object 
		state = string as a bool (1 or 0)
		========================================= */
		initialiseAccordion : function(currentAccordion,state) {
		
			var currentAccordionContent = currentAccordion.find(settings.accordionContent);				
			/* 
			treat the default  
			the default is a string of 1s and 0s, that represent the order of the accordions. 1 = open, 2 = closed	
			*/
			
			this.handleHover(currentAccordion.find(settings.accordionHandle));
		
			if(state == "1") {

				if(currentAccordionContent.html()) {
				  //currentAccordionContent.slideDown();
				    currentAccordionContent.animate({
					   height: "show"
				    }, {"duration": 600, "easing" : "easeOutQuad"});
				} else {
					currentAccordionContent.parent().addClass("loading");
		   			var ajaxurl = this.getAJAXURL(jQuery(currentAccordion).attr("id"));	 
                    jQuery.get(ajaxurl,{},function(data) {
						currentAccordionContent.parent().removeClass("loading");
                        currentAccordionContent.text(" ");// this is for all your safari 2 kids out there
						currentAccordionContent.prepend(data);
						 currentAccordionContent.animate({
			                 height: "show"
			             }, 600, "easeOutQuad");
						 settings.afterload(currentAccordionContent);                         
					});                   
                   
				} // end if/else
				currentAccordion.find(settings.accordionContent).show();
				currentAccordion.addClass("open");
			} else {
				currentAccordion.find(settings.accordionContent).hide();
				currentAccordion.removeClass("open");			
			} // end if/else


		},	// end initialise method
		
		handleHover : function(moduleHeader) {
 		    moduleHeader.hover( 
			   function() { moduleHeader.addClass("hover"); },
			   function() { moduleHeader.removeClass("hover"); }
			);			
		},
		
		/* =========================================
		toggleAccordion
		currentAccordionHandle = jQuery object 
		========================================= */
		toggleAccordion : function(currentAccordionHandle) {
			
			this.returnAllStates();
	
		   var currentAccordion = currentAccordionHandle.parent();	
		   var currentAccordionContent = currentAccordion.find(settings.accordionContent);
		   
		   /* construct the AJAX url from the prefix, ID and suffix */
		   var ajaxurl = this.getAJAXURL(jQuery(currentAccordion).attr("id"));
		   
		   /* check whether the accordion is already open, if it is then close it */
		   if(currentAccordion.hasClass("open")) {
			  /* slide it up */
			  
			  currentAccordionContent.animate({
			      height: "hide"
			  }, 600, "easeOutQuad");
			  
			  /* it's no longer open, so lets remove the class*/
			  currentAccordion.removeClass("open");
		   } else {
			  currentAccordionContent = currentAccordion.find(settings.accordionContent);
			  
			  currentAccordion.addClass("open");
			  /* 
			  if the accordion already contains HTML content the just slide it open, 
			  else...  
			  make an ajax call to fill it up, then open it once done
			  */
			  if(!!currentAccordionContent.html()) {
				  
				  currentAccordionContent.animate({
			          height: "show"
			      }, 600, "easeOutQuad");
				  
			  } else {
				  /* set a loading class so you can do something nice while we get the content */				  
				  currentAccordionContent.parent().addClass("loading");             
                    jQuery.get(ajaxurl,{},function(data) {
						currentAccordionContent.parent().removeClass("loading");
                        currentAccordionContent.text(" "); // this is for all your safari 2 kids out there
						currentAccordionContent.prepend(data);
						 currentAccordionContent.animate({
			                 height: "show"
			             }, 600, "easeOutQuad");
						 settings.afterload(currentAccordionContent);                         
					});
                     			   
			  } // end if/else
			  
		   }

		   settings.stop(this.returnAllStates(),settings.userPrefsName);
		   
		}, // end toggleAccordion method
		getAJAXURL : function(id) {
			return settings.ajaxurlPrefix + id + settings.ajaxurlSuffix; 
		},
		returnAllStates : function() {
			var allStates = "";
			jQuery(accordionGroup).find(settings.accordionContainer).each(function() {
					/* get the module content for this accordion */
					if(jQuery(this).hasClass("open")) {
						allStates += "1";
					} else {
						allStates += "0";						
					}
			});
			
			return allStates;
		}

	};
	
	


	/* =========================================
	manage the interface 
	pl - changed click to mousedown
	========================================= */
	jQuery(this).find(settings.accordionContainer).each(function() {

	    if(accordionIndex > 0) {
			var currentAccordion = jQuery(this);
	
			/*
			attach a click behaviour the module handle
			*/
			currentAccordion.find(settings.accordionHandle).each(function() {
			   jQuery(this).mousedown(function() {
			   accordions.toggleAccordion(jQuery(this));
			   
				});
				jQuery(this).find("h3.heading a").each(function() {

					jQuery(this).mousedown(function() {
					    jQuery(this).parent().parent().mousedown();
						return false;
					});
					/* and destroy the click */		
					jQuery(this).click(function() {
					    return false;
					});	
				});	  
			});
			/*
			initialise the accordion
			*/
			if(typeof settings.defaultState == "string") {
				var arrDefaultState = settings.defaultState.match(/.{1}/g);
				var currentAccordionState = arrDefaultState[accordionIndex];
			} else {
				var currentAccordionState = "0";
			}
			accordions.initialiseAccordion(currentAccordion,currentAccordionState);

			/* increment the counter... this is used to check on the default states */
		}
		accordionIndex++;
	});

};


/*
============================
SEND TO TOP / SEND TO BOTTOM
============================
*/
jQuery.fn.homeSortableSendTo = function(options) {

	var animating = false;
	
	var settings = jQuery.extend({
	   stop : function() { }
	},options||{});

	   var createSendTo = function(hashID) {
		   var sendtoContainer = document.createElement('div');
		       sendtoContainer.className = "sendTo";

		   var sendToTools = document.createElement('div');
		       sendToTools.className = "sendToTools";

		   var sendtoLabel = document.createElement('em');	
			   sendtoLabel.innerHTML = "Sposta:";
		   var sendtoTop = document.createElement('a');
			   sendtoTop.href = "#" + hashID;
			   sendtoTop.className = "top";
			   sendtoTop.innerHTML = "Sopra";
		   var sendtoBottom = document.createElement('a');  				   
			   sendtoBottom.href = "#" + hashID;
			   sendtoBottom.className = "bottom";				   
			   sendtoBottom.innerHTML = "Sotto";
			   
		   sendToTools.appendChild(sendtoLabel);
		   sendToTools.appendChild(sendtoTop);
		   sendToTools.appendChild(sendtoBottom);
		   

		   sendtoContainer.appendChild(sendToTools);	
		   
		   /* behaviours */
		   jQuery(sendtoTop).click(function() { return false; });

		   jQuery(sendtoTop).mousedown(function(e) {
				if(animating === false) {
					animating = true;
					elementToMove = jQuery(this.hash)
					var container = elementToMove.parent();	
						elementToMove.animate({ opacity: 0.0 }, 300, "linear", function() {
								container.prepend(elementToMove);
								elementToMove.attr("style","");
								animating = false;
								settings.stop(e,elementToMove);
						} );
				}
			  return false;			   
		   });
		   
		   jQuery(sendtoBottom).click(function() { return false; });
		   jQuery(sendtoBottom).mousedown(function(e) {											   
				if(animating === false) {
					animating = true;									
					elementToMove = jQuery(this.hash);
					var container = elementToMove.parent();	
						elementToMove.animate({ opacity: 0.0 }, 300, "linear", function() {
							container.append(elementToMove);
							elementToMove.attr("style","");
								animating = false;	
								settings.stop(e,elementToMove);
					} );		
				} 
				return false;
		   });
		   
		   return sendtoContainer;
		   
	   }
		
	   jQuery(this).each(function() {
		  // get the id of the accordion set we're dealing with, and send that through to be used later...
		  var currentGroupID = jQuery(this).attr("id");
		  jQuery(this).find("div.group-header").append(createSendTo(currentGroupID));
	   });			
};

/*
============================
dragsortscroll
============================

how it works:

> user clicks on a handle
> a helper is created
> the heights for each item are caculated and cached as an attribute 
> the position of the helper is set via the mouse position and the offset of the scroll bar
> if the helper crosses a threshold set in relation to the cached heights, and the direction of the mouse, the the original item is moved to a new position along with the placeholder
> if the user moves to an area of the viewport that is defined by the first or second sense then the auto scroll starts functioning

The drag functionality updates the helper position via setTimeout, allowing for calculation based on mouse and scroll position

*/

// ouch!
ndm.newscomau.sendToTopOneShot = true;

jQuery.fn.dragsortscroll = function(options) {
	return this.each(function() {
		var thisobj = this;
		var currentContainer = this;	
	
		this.settings = jQuery.extend({
			firstSense: 25, // area to detect auto scroll - moves faster
			secondSense: 50, // area to detect auto scroll 
			scrollSpeedFast: 50, // fast
			scrollSpeedSlow: 25, // pixels to be moved by when scrolling slowly			
			margin: 10, // distance away from the browser's edge
			helperTimeout: 10, // refresh period for helper
			placeholder : "placeholder", // name of placholder used when dragging things
			readyClass : "draggable", 
			opacity : 0.8,	
			handle: "h2",
			items: "div.group",
			stop : function(e) { },
			start : function(e) { },
			aftersort : function(e) {},
			kill : false
		},options||{});	

		if(this.settings.kill === true) {
			return;
		}	
		
		this.dragging = false; // bool to tell whether the drag is currently in use		

		this.dragObject = null; // will be a dom element that is being moved
		this.helper = null; // will be a dom element, probably a clone of the element moved
		this.placeholder = null; // will be a dom element to show the user where things will drop	
		this.mouseX; // set via mouse move 
		this.mouseY; // set via mouse move
		this.mouseScrollPos = 0; // set at mouse move
		this.mouseDirection; // up or down	
		this.direction;	// up or down, determines which way to auto scroll
		this.scrollPos; // set at scroll
		this.relPos; // this is an array with the top and left pos of the mouse in the target object	
		this.allowsort = true; // if true, the sorter is allowed to fire
		this.viewportwidth; // set via calculate view port method
		this.viewportheight; // set via calculate view port method
		this.pos; // mouse relative position in the browser view port
		this.canScroll = false;	// bool, determines whether we can scroll... duh
		this.scrollKill = true;
		this.scrollTopVal = 0; // storage for jQuery().scrollTop();... gets used in many places...
		this.scrollSpeed; // set via mouse move, and used by the scroll timeout
		this.timeoutCall = null; // timeout for auto scrolling
		
		this.itemIndexPos; // when picking up a dragger, this saves the position it was in the list
	
		this.currentDragger = null;
		this.offset;
		this.containerOffset;
		
		 this.scrolling = false;
		 this.counter = 0;


		// cache some info for the sorting
		this.itemTops = [];
		this.itemBottoms = [];
		this.itemCounter = 0;	
	

	this.setScrollTop = function() {
		thisobj.scrollTopVal = parseInt(jQuery(document).scrollTop());
	}
	
	this.getScrollTop = function() {
	   return thisobj.scrollTopVal;	
	}
	
	this.setMousePos = function(e){
		thisobj.mouseY = parseInt(e.pageY);
		thisobj.mouseX = parseInt(e.pageX);		
	}
	
	this.setPos = function() {
		thisobj.pos = thisobj.mouseY - thisobj.getScrollTop();		 
	}
	
	this.killScroll = function() {
		thisobj.canScroll = false;
		thisobj.scrollKill = true;		
	}
	this.allowScroll = function() {
		thisobj.scrollKill = false;			
	}
	
	this.killDragging = function() {
	    thisobj.dragging = false;	
	}
	
	this.allowDragging = function() {
	    thisobj.dragging = true;		
	}


	 /*
	 calculateViewport 
	 sets values for the view port size, and sets them into the object
	 */
	 this.calculateViewport = function() {
		 if (typeof window.innerWidth != 'undefined') {
			  thisobj.viewportwidth = window.innerWidth,
			  thisobj.viewportheight = window.innerHeight
		 } else if (typeof document.documentElement != 'undefined'
			 && typeof document.documentElement.clientWidth !=
			 'undefined' && document.documentElement.clientWidth != 0) {
			   thisobj.viewportwidth = document.documentElement.clientWidth,
			   thisobj.viewportheight = document.documentElement.clientHeight
		 }	
	 } // end calculate viewport

     this.scrollStart = function() {
		 
	 }
	 
	 this.scrollStop = function() {
		 
	 }
	 /*
	 mouse move
	 determines where the mouse is in relation to the view port, and the areas set as scrollable areas
	 */

/* addition for ie7 dragging problem */

	 var mousemovediv = document.createElement("div");
	 
	 
	 jQuery("#network-bar").append(mousemovediv);
	 
	 jQuery(mousemovediv).width("100%");
	 jQuery(mousemovediv).height("100%");	
	 jQuery(mousemovediv).css("position", "absolute");	
	 jQuery(mousemovediv).css("left", "0px");
	 jQuery(mousemovediv).css("top", "0px");
	 jQuery(mousemovediv).css("z-index", "5000");
	 jQuery(mousemovediv).css("background-color", "#ffffff");
	 jQuery(mousemovediv).css("opacity", 0.0);	 
	 jQuery(mousemovediv).height(jQuery(document).height());
	 jQuery(mousemovediv).width(jQuery(document).width());	
     jQuery(mousemovediv).hide();
     
	 jQuery(document).mousemove(function(e){
										 
		var oldMouseY = thisobj.mouseY;										 
		thisobj.setMousePos(e);
		thisobj.setPos(e);			
		thisobj.mouseScrollPos = thisobj.getScrollTop(); // cache the scrollTop for this mouse specific event



		// determine the direction the mouse is moving in... 
		if(oldMouseY > thisobj.mouseY) {
			thisobj.mouseDirection = "up";
		} else if(oldMouseY < thisobj.mouseY)  {
			thisobj.mouseDirection = "down";	  
		}
		// determine the position in relation to scroll areas 
		if(thisobj.scrollKill === false) {
			if(thisobj.pos > thisobj.viewportheight - (thisobj.settings.firstSense + thisobj.settings.secondSense) - thisobj.settings.margin && thisobj.pos < thisobj.viewportheight - thisobj.settings.margin) {
			   if(thisobj.pos > thisobj.viewportheight - thisobj.settings.firstSense) {
				   thisobj.scrollSpeed = thisobj.settings.scrollSpeedFast;
			   } else {
				   thisobj.scrollSpeed = thisobj.settings.scrollSpeedSlow;		   
			   }
			   if(thisobj.canScroll === false) {
				   thisobj.canScroll = true;
				   thisobj.direction = "down";
			   }
			   
			} else if(thisobj.pos < thisobj.settings.margin + (thisobj.settings.firstSense + thisobj.settings.secondSense) && thisobj.pos > thisobj.settings.margin) {
			   if(thisobj.pos < thisobj.settings.margin + thisobj.settings.firstSense) {
				  thisobj.scrollSpeed = thisobj.settings.scrollSpeedFast;
			   } else {
				  thisobj.scrollSpeed = thisobj.settings.scrollSpeedSlow;		   
			   }
			   if(thisobj.canScroll === false) {
				   thisobj.canScroll = true;
				   thisobj.direction = "up";		   

			   }
			} else {
			   thisobj.direction = null;
			   thisobj.canScroll = false;
			}
		} // end if test on scroll kill
	 }); // end mouse move


	/* 
	onScroll 
	*/
	jQuery(window).bind('scroll',function(e) {
		thisobj.setScrollTop();
		thisobj.calculateViewport();
	});		 
	
	 /* 
	 scroll page
	 calls on it's self to animte the scrolling
	 */
	 this.scrollpage = function() {

	 }
	 
	/*
	===========================
	drag and sort functions....
	===========================	
	*/

	/* 
	placeholder - this is the dotted line when the user can put the item being dragged
	*/
	this.createPlaceholder = function() {
		var srcHeight = jQuery(thisobj.dragObject).height();
		var srcWidth = jQuery(thisobj.dragObject).width();			
		thisobj.placeholder = document.createElement('div');		
		thisobj.placeholder.className = thisobj.settings.placeholder;
		jQuery(thisobj.placeholder).width(srcWidth);
		jQuery(thisobj.placeholder).height(srcHeight);
		jQuery(thisobj.placeholder).css("position","absolute");
		jQuery("div.ad-header:first").append(thisobj.placeholder);
		thisobj.movePlaceholder();
	}

	  jQuery(document).mouseup(function(e) {		
		 if(thisobj.dragging === true) {
		   thisobj.endDrag(e);
		 }
	  });
		
		
		/* functions that fire when the user starts using and stops using the functionality */
		this.stop = function(e) { 
	       jQuery(mousemovediv).hide();
		   thisobj.killScroll();
		   thisobj.settings.stop(e); 
		};
		this.start = function(e) { 
		   thisobj.allowScroll();	
		   thisobj.settings.start(e); 
	       jQuery(mousemovediv).show();
		};
		



		this.setContainerOffset = function() { containerOffset = jQuery(thisobj).offset(); }
		this.setDrag = function(val) { thisobj.drag = val; }
		this.getDrag = function() {  return thisobj.drag; }
		

		/*
		start drag
		element - element to drag
		top - original top value for the selected element
		left -  ofiginal left value for the selected element
		*/
		this.startDrag = function(e,element,top,left) {
			/* use a clone for the acutal thing that the user "holds" */
			thisobj.helper = jQuery(element).clone();
            thisobj.helper.addClass("draghelper");
			
			thisobj.allowDragging();		 
			thisobj.setContainerOffset();
			thisobj.cacheHeights();
			thisobj.dragObject = element;
			thisobj.setPosIndexes();
			thisobj.calculateViewport();			
			thisobj.itemIndexPos = jQuery(element).attr("posindex"); 

			thisobj.createPlaceholder();
			/* prepent the helper to the body so we can see it, and move it about */
			jQuery("div.ad-header:first").prepend(thisobj.helper);
			thisobj.helper.css("top",top);
			thisobj.helper.css("left",left);

			// make the original object hide
			jQuery(element).css("visibility","hidden"); 
			/* fireup the move helper timer */
			thisobj.moveHelper();
			/* fire call back */
			thisobj.start(e);
		}

		this.endDrag = function(e) {
			thisobj.killDragging();	
			// make the drag object hide
			jQuery(thisobj.dragObject).css("visibility","visible");	 
			thisobj.dragObject = null;
			jQuery(thisobj.helper).remove();
			thisobj.stop(e);
			thisobj.destroyPlaceholder();	
			
			// and switchola the send to top
			if (ndm.newscomau.sendToTopOneShot) { 
			    jQuery("#content-accordions div.group-header .sendTo").remove();
			    jQuery("#content-accordions div.group-accordions").homeSortableSendTo({ stop: function(e,elementToMove) { elementToMove.removeClass("hover"); userprefs.saveAccordionGroups(e); } });
			    ndm.newscomau.sendToTopOneShot = false;
			} 
		}

		this.destroyPlaceholder = function() {
			jQuery(thisobj.placeholder).remove();
		}

		/* sets an attribute to the item with the current height - this means we don't have to calculate it on the fly later */
		this.cacheHeights = function() {
			jQuery(thisobj).find(">" + thisobj.settings.items).each(function() {	  
			   jQuery(this).attr("cachedheight",jQuery(this).height());	
			});
		}

	/*
	move helper
	top - int 
	left - int 
	*/
	this.moveHelper = function() {
		if(thisobj.dragging === true) {
			thisobj.moveHelperExecute();
			thisobj.helperTimeout = setTimeout(thisobj.moveHelper, thisobj.settings.helperTimeout);
			//thisobj.helperTimeout = setInterval(thisobj.moveHelperExecute, thisobj.settings.helperTimeout);
		} else {
			clearTimeout(thisobj.helperTimeout);
			//clearInterval(thisobj.helperTimeout);
		}
	}
	
	this.moveHelperExecute = function() {	

			var element = thisobj.helper;
			var currentScrollTop = thisobj.getScrollTop();			
			var top;
			var left;
			
			top = thisobj.mouseY - parseInt(thisobj.mouseScrollPos - currentScrollTop);

			left = thisobj.mouseX;		
			element.css("left",left - relPos[0]);
			element.css("top",top - relPos[1]);
			
			if(thisobj.canScroll === true) {
				if(thisobj.direction == "down") {
					jQuery(document).scrollTop(thisobj.getScrollTop() + thisobj.scrollSpeed);						
				} else if(thisobj.direction == "up") {
					jQuery(document).scrollTop(thisobj.getScrollTop() - thisobj.scrollSpeed);			
				}	
			} // end if
			
			if(thisobj.allowsort === true) { 
				thisobj.sortItems(top, top + parseInt(element.attr("cachedheight")));
			}		

			top = thisobj.mouseY - parseInt(thisobj.mouseScrollPos - currentScrollTop);
			left = thisobj.mouseX;		
			element.css("left",left - relPos[0]);
			element.css("top",top - relPos[1]);
	}

  

	/*
	Sorting functionality
	
	*/


	this.sortItems = function(top,bottom) {

		// Here be dragons!
		var threshold = [ Math.floor((thisobj.itemBottoms[thisobj.itemIndexPos*1 - 1] + thisobj.itemTops[thisobj.itemTops.length - thisobj.itemIndexPos*1])/2) || 0,
						 Math.floor((thisobj.itemBottoms[thisobj.itemIndexPos] + thisobj.itemBottoms[thisobj.itemIndexPos*1 + 1])/2) || Infinity ];
	    
		
		if (top < threshold[0]) {
			itemPosition = thisobj.itemIndexPos*1 - 1;
			thisobj.itemIndexPos = itemPosition;
			thisobj.moveDraggableBefore(thisobj.settings.items + ":eq(" + itemPosition + ")");	   
		} else if (bottom > threshold[1]) {
			itemPosition = thisobj.itemIndexPos*1 + 1;
			thisobj.itemIndexPos = itemPosition;
			thisobj.moveDraggableAfter(thisobj.settings.items + ":eq(" + itemPosition + ")");	   
		}
	 
	
	} // end sortItems

	this.moveDraggableBefore = function(element) {
		jQuery(thisobj).find(element).before(thisobj.dragObject);
		thisobj.setupItems();
		thisobj.movePlaceholder();
		thisobj.aftersort();	
	}
	
	this.moveDraggableAfter = function(element) {
		jQuery(thisobj).find(element).after(thisobj.dragObject);
		thisobj.setupItems();
		thisobj.movePlaceholder();	  
		thisobj.aftersort();		
	} 
	
	this.aftersort = function(e) { thisobj.settings.aftersort(e); };	

	this.movePlaceholder = function() {
		var srcOffset = jQuery(thisobj.dragObject).offset();
		var currentLeft = parseInt(jQuery(thisobj.placeholder).css("left"));
		var currentTop = parseInt(jQuery(thisobj.placeholder).css("top"));	
		jQuery(thisobj.placeholder).css("left",srcOffset.left);
		jQuery(thisobj.placeholder).css("top",srcOffset.top);			
	}



	/*
	Loops through items and cache some information. Eg the height value
	*/
	this.setupItems = function() {
		var itemCounter = 0;
		var startPoint = parseInt(containerOffset.top);
		var incrementalHeight = 0;
		jQuery(thisobj).find(">" + thisobj.settings.items).each(function() {
			var currentDragger = jQuery(this);
			var currentHeight = parseInt(currentDragger.attr("cachedheight"));
			thisobj.itemTops[itemCounter] = startPoint + incrementalHeight + 20;
			thisobj.itemBottoms[itemCounter] = startPoint + (incrementalHeight + currentHeight);
			itemCounter++;
			incrementalHeight += currentHeight + 20;
		});
		thisobj.itemTops.reverse();/**/
	}

	this.setPosIndexes = function() {
		var positionIndex = 0;
		jQuery(this).find(" > " + thisobj.settings.items).each(function() {
		   jQuery(this).attr("posindex",positionIndex);
		   positionIndex++;
		});
	}

  /* 
  initialise all the functionality
  */
		thisobj.setContainerOffset();
		thisobj.cacheHeights();
		thisobj.setupItems();
		thisobj.setPosIndexes();
		
		/* loop through items */
		jQuery(this).find(" > " + thisobj.settings.items).each(function() {
		  /* jQuery object of current dragger */
		  var currentDragger = jQuery(this);
		  currentDragger.addClass(thisobj.settings.readyClass);

		  
		  currentDragger.find(thisobj.settings.handle).hover(function() {
				currentDragger.addClass("hover");							
		  },function(){
				currentDragger.removeClass("hover");							

		  });		  

		  /* set offset values for this dragger, the offset is the x / y pos */
		  var currentOffset = currentDragger.offset();
		  /* asign the mouse down behaviour to the handle */
		  jQuery(this).find(thisobj.settings.handle).mousedown(function(e) {
			  offset = jQuery(currentDragger).offset();
			  relPos = [e.pageX - offset.left, e.pageY - offset.top];
			  thisobj.startDrag(e,currentDragger,offset.top,offset.left);
			  /* stop any kind of text selection nonsense */
			  document.body.focus();
			  document.onselectstart = function () { return false; };		  
			  return false;
		  });
		  thisobj.itemCounter++;
		});
	});
   /*
   end initialising
   */
};
