/*
##########################################################
				START CUSTOM HOMEPAGE FUNCTION
	Author: Stuart Elmore c/o e4education (http://www.e4eduation.co.uk/)
			(c) e4education & Stuart Elmore (October 2009).
		    DO NOT MAKE UNAUTHORISED COPIES OF THIS CODE
##########################################################
*/
	$.fn.e4eCustomHomepage = function() {
		var args = arguments[0] || {};
		var options = $.extend({}, $.e4eCustomHomepage.defaults, args);
		return $.e4eCustomHomepage.construct(options);
	};
	$.e4eCustomHomepage = {
		defaults: {
			columnRefs: ['#custcol1','#custcol2','#homeRightColumn'],
			defaultLayout:  [['cust_homepage','BBC_feed','testEvent'],['CustomBox','latestNews'],['testCalendar','testGallery','testMap','testAttachments']],
			sortable: true,
			boxClass: 'dynamicBox',
			loadingHTML:'<div style="height:32px; width:32px; margin:0 auto; background:url(/_includes/images/design/homepage.loading.gif) center;"><span style="display:none;">Loading...</span></div>',
			boxURL: '/_includes/code/custom.box.asp',
			resetButton: '#resetButton a',
			customiseButton: '#customiseButton a',
			handler: 'h2',
			placeholder: 'custom_ghost',
			debug: false,
			addNewBoxTo: 'last' // first / '#ref'
		},
		debug: function(options,msg,viewType){
			var msgType = viewType || 'log';
			if(options.debug === true){
				if(console){
					console[msgType]('e4eCustDebug: '+msg);
				}
			}
		},
		construct: function(options){
			$.e4eCustomHomepage.debug(options,'run construct');
			var layout;
			// has user already set up cookies?
			if($.cookie('customHomepage_layout') === null){
				// cookie doesn't exist so load defaults
				$.e4eCustomHomepage.debug(options,'cookie does not exist');
				layout = options.defaultLayout;
			}else{
				// cookie is set!
				var fullLayout = [];
				$.e4eCustomHomepage.debug(options,'cookie exists','info');
				$.e4eCustomHomepage.debug(options,'cookie: '+ $.cookie('customHomepage_layout'));
				layout = $.cookie('customHomepage_layout');
				layout = layout.replace(/\[/g,'');
				$.e4eCustomHomepage.debug(options,'layout = '+ layout);
				if(layout.indexOf('],') > -1){
					$.e4eCustomHomepage.debug(options,'layout has ],');
					layout = layout.split('],');
					for(var ix = 0; ix < layout.length; ix++){
						layout[ix] = layout[ix].replace(/\[/g,'');
						layout[ix] = layout[ix].replace(/\]/g,'');
						layout[ix] = layout[ix].replace(/"/g,'');
						$.e4eCustomHomepage.debug(options,'layout[ix] = '+layout[ix]);
						if(layout[ix].indexOf(',') > -1){
							layout[ix] = layout[ix].split(',');
							fullLayout.push(layout[ix]);
						}else{
							var tempLayout = [];
							tempLayout.push(layout[ix]);
							fullLayout.push(tempLayout);
						}
					}
					$.e4eCustomHomepage.debug(options,'fullLayout = '+fullLayout);
				}else{
					layout = layout.replace(/\[/g,'');
					layout = layout.replace(/\]/g,'');
					layout = layout.replace(/"/g,'');
					if(layout.indexOf(',') > -1){
						fullLayout = layout.split(',');
					}else{
						var tempLayout2 = [];
						tempLayout2.push(layout);
						fullLayout.push(tempLayout2);
					}
				}
			}
			// empty the columns and ready them for the new content.
			$.e4eCustomHomepage.debug(options,'Start emptying boxes','info');
			var i, ii;
			for(i=0; i<options.columnRefs.length; i++){
				$.e4eCustomHomepage.debug(options,'empty column '+i);
				$(options.columnRefs[i]).html(''); 
				$.e4eCustomHomepage.debug(options,'typeof(layout['+i+']) = '+typeof(layout[i]));
				if(typeof(layout[i]) != 'string'){
					for(ii=0; ii<layout[i].length; ii++){
						$.e4eCustomHomepage.debug(options,'load multiple box['+i+']['+ii+']: '+layout[i][ii]);
						$.e4eCustomHomepage.loadBox(options, $(options.columnRefs[i]), layout[i][ii], 'append');
					}
				}else if(layout[i].length > 0){
					$.e4eCustomHomepage.debug(options,'load single box: '+layout[i]);
					$.e4eCustomHomepage.loadBox(options, $(options.columnRefs[i]), layout[i], 'append');
				}else{
					$(options.columnRefs[i]).height(150);
				}
			}
			// set sortable handlers if allowed.
			$.e4eCustomHomepage.debug(options,'query sortables','info');
			if(options.sortable === true){
				$.e4eCustomHomepage.debug(options,'sortables === true');
				// check if sortables are available...
				for(i=0; i<options.columnRefs.length; i++){
					var connectWithVar = [];
					if(options.columnRefs.length>1){
						for(ii=0; ii<options.columnRefs.length; ii++){
							if(options.columnRefs[i] != options.columnRefs[ii]){
								connectWithVar.push('#'+$(options.columnRefs[ii]).attr('id'));
							}
						}
					}
					$.e4eCustomHomepage.debug(options,'connect with = '+connectWithVar);
					try{
						$(options.columnRefs[i]).sortable({
							connectWith: connectWithVar,
							handle: 'h2:first',
							items:'.'+options.boxClass,
							placeholder: options.placeholder,
							forcePlaceholderSize: true,
							stop: function(){
								for(var iii=0; iii<options.columnRefs.length; iii++){
									if($('.'+options.boxClass, options.columnRefs[iii]).length===0){
										$(options.columnRefs[iii]).height(150);
									}else{
										$(options.columnRefs[iii]).css('height', 'auto');
									}
								}
							},
							start: function(){
								$.e4eCustomHomepage.debug(options,'init Start Drag');
								$.e4eCustomHomepage.autoHeight(options);
							},
							update: function(){
								$.e4eCustomHomepage.save(options);
							}
						});
					}catch(ex){
						$.e4eCustomHomepage.debug(options,'<--- ERROR ---> Problem running sortable. Check ui.core, sortable and draggable is included.', 'error');
						$.e4eCustomHomepage.debug(options,'<--- ERROR ---> cont. Exception: "'+ex+'".', 'error');
					}
				}
			}
			//set up reset button
			$.e4eCustomHomepage.debug(options,'set up reset button','info');
			var resetLength = $(options.resetButton).length;
			if(resetLength>0){
				if($(options.resetButton).data('buttonSet') !== true){
					$(options.resetButton).click(function(evt){
						evt.preventDefault();
						$.e4eCustomHomepage.reset(options);
					});
					$(options.resetButton).data('buttonSet',true);
				}
			}else{
				$.e4eCustomHomepage.debug(options,'<--- ERROR ---> Unable to find reset button. Currently set to: "'+options.resetButton+'".', 'error');
			}
			//set up customise page
			$.e4eCustomHomepage.debug(options,'set up customise button','info');
			var customLength = $(options.customiseButton).length;
			if(customLength>0){
				if($(options.customiseButton).data('buttonSet') !== true){
					$(options.customiseButton).click(function(evt){
						evt.preventDefault();
						$.e4eCustomHomepage.customiseBoxes(options);
					});
					$(options.customiseButton).data('buttonSet',true);
				}
			}else{
				$.e4eCustomHomepage.debug(options,'<--- ERROR ---> Unable to find customise button. Currently set to: "'+options.customiseButton+'".', 'error');
			}
			// set the new cookie.
			$.e4eCustomHomepage.debug(options,'set cookie','info');
			$.e4eCustomHomepage.save(options);
		},
		save: function(options){
			$.e4eCustomHomepage.debug(options,'invoke save','info');
			var serialisedData = '[';
			for(var i=0; i<options.columnRefs.length; i++){
				var columnData = '[';
				$('.'+options.boxClass, $(options.columnRefs[i])).each(function(){
					$.e4eCustomHomepage.debug(options,'collect data for:'+$(this).attr('id'));
					columnData += (columnData == '[' ? '' : ',') + '"' + $(this).attr('id') + '"' ;
				});
				columnData += ']';
				$.e4eCustomHomepage.debug(options,'columnData = '+columnData);
				serialisedData += (serialisedData == '[' ? '' : ',') + columnData;
			}
			serialisedData += ']';
			$.e4eCustomHomepage.debug(options,'set cookie customHomepage_layout to: '+serialisedData);
			$.cookie('customHomepage_layout',serialisedData);
			$.e4eCustomHomepage.debug(options,'Cookie set', 'info');
		},
		reset: function(options){
			$.e4eCustomHomepage.debug(options,'invoke reset', 'info');
			$.e4eCustomHomepage.debug(options,'reset to: '+options.defaultLayout);
			// reset cookie
			var fullLayout = '[';
			var layout = options.defaultLayout;
			if(typeof(layout) != 'string'){
				for(var i=0; i<layout.length; i++){
					fullLayout += (fullLayout[fullLayout.length-1] == ']' ? ',[' : '[');
					if(typeof(layout[i]) != 'string'){
						for(var ii=0; ii<layout[i].length; ii++){
							fullLayout+= (fullLayout[fullLayout.length-1] == '[' ? '' : ',') + '"' + layout[i][ii] + '"';
						}
					}else{
						fullLayout += '"'+layout[i]+'"';
					}
					fullLayout += ']';
				}
			}else{
				fullLayout += layout;
			}
			fullLayout += ']';
			$.e4eCustomHomepage.debug(options,'new fullLayout = '+fullLayout);
			$.cookie('customHomepage_layout',fullLayout);
			$.e4eCustomHomepage.debug(options,'panels reset successfully', 'info');
			$.e4eCustomHomepage.debug(options,'call construct', 'info');
			// reset panels
			$.e4eCustomHomepage.construct(options);
		},
		loadBox: function(options, loadInto, objectRef, appendReplace){
			// set loading details...
			var boxesHolder = $.e4eCustomHomepageBoxes;
			var boxTitle = boxesHolder[objectRef].boxTitle || 'Loading';
			var boxHTML = 	'<div class="'+options.boxClass+'" id="'+objectRef+'">';
			boxHTML +=	'	<h2><span>'+boxTitle+'</span></h2>';
			boxHTML +=	'	<div class="dynamicContent">';
			boxHTML +=	'		'+options.loadingHTML;
			boxHTML +=	'	</div>';
			boxHTML +=	'</div>';
			if(appendReplace == 'append'){
				$(loadInto).append(boxHTML);
			}else{
				$(loadInto).replaceWith(boxHTML);
			}
			$.e4eCustomHomepage.debug(options,'AJAX call ajax request for: "'+objectRef+'"', 'info');
			// perform ajax request...
			$.ajax({
				url: options.boxURL + '?id=' + objectRef,
				data: $.e4eCustomHomepageBoxes[objectRef],
				dataType: 'json',
				type: 'POST',
				success:function(data){
					$.e4eCustomHomepage.debug(options,'AJAX success: Recieved data back for "'+objectRef+'"', 'info');
					var boxTitleObj = boxesHolder[objectRef].boxTitle || data.boxTitle;
					$('h2:first span', $('#'+objectRef)).text(boxTitleObj);
					$('.dynamicContent', $('#'+objectRef)).html(data.boxContent);
					if(data.boxScript !== undefined){
						$.e4eCustomHomepage.debug(options,'AJAX load script for "'+objectRef+'"', 'warn');
						$.e4eCustomHomepage.debug(options,data.boxScript,'warn');
						eval(data.boxScript);
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					$.e4eCustomHomepage.debug(options,'<--- ERROR ---> AJAX Recieved error back for "'+objectRef+'" ajax request.', 'error');
					$.e4eCustomHomepage.debug(options,'<--- ERROR ---> AJAX cont. textStatus:"'+textStatus+'", errorThrown: "'+errorThrown+'".', 'error');
					$('.dynamicContent',  $('#'+objectRef)).html('<h4>Error</h4><p>Sorry, there was a problem retrieving this content box.</p><p>Please click <a class="custom_reload">here</a> to try again.</p>');
					$('.custom_reload',  $('#'+objectRef)).click(function(){$.e4eCustomHomepage.loadBox(options, $(objectRef), objectRef, 'replace');});
				}
			});
		},
		addBox: function(options, boxID){
			var injectInto;
			if(typeof(options.columnRefs) != 'string'){
				if(options.addNewBoxTo == 'last'){
					injectInto = options.columnRefs[options.columnRefs.length-1];
				}else if(options.addNewBoxTo == 'first'){
					injectInto = options.columnRefs[1];
				}else{
					injectInto = options.addNewBoxTo;
				}
			}else{
				injectInto = options.columnRefs;
			}
			$.e4eCustomHomepage.loadBox(options, $(injectInto), boxID, 'append');
			$(injectInto).sortable('refresh');
			$.e4eCustomHomepage.save(options);
		},
		removeBox: function(options, boxID){
			$.e4eCustomHomepage.debug(options, 'remove: '+$(boxID));
			$(boxID).remove();
			$.e4eCustomHomepage.save(options);
		},
		customiseBoxes: function(options){
			// set up display window first
			var customiseHTML = 	'<div id="customiseHomepage_holder">';
			customiseHTML += 	'<div id="customiseHomepage_overlay"></div>';
			customiseHTML += 	'<div id="customiseHomepage"></div>';
			customiseHTML += 	'</div>';
			$('body').css('overflow','hidden').append(customiseHTML);
			var customiseHomepageContent ='<div id="custom_chooser">';
			customiseHomepageContent +=	'<h2>Customise this page</h2>';
			customiseHomepageContent +=	"<p>You can customise your own version of this website's homepage by selecting exactly what information you want to see. Choose from a wide range of options below and the homepage will be adjusted accordingly.</p><p><em>(Please note to use this feature you must have cookies enabled in your browser)</em></p>";
			customiseHomepageContent +=	'<div id="custom_box_choice_holder"><h2>Box Choices</h2><div id="custom_box_choice"></div></div>';
			customiseHomepageContent +=	'<div id="custom_box_preview_holder"><h2>Box Preview</h2><p><em>Click on a preview icon to see an example of each of the boxes</em></p><div id="custom_box_preview"></div></div>';
			customiseHomepageContent +=	'</div>';
			customiseHomepageContent +=	'<div title="Click here to close" id="custom_chooser_close">';
			customiseHomepageContent +=	'<span>Click here to close</span>';
			customiseHomepageContent +=	'</div>';
			$('#customiseHomepage').append(customiseHomepageContent);
			$.e4eCustomHomepage.customiseWindowResize();
			$(window).resize(function(){$.e4eCustomHomepage.customiseWindowResize();});
			$('#custom_chooser_close').click(function(){$.e4eCustomHomepage.customiseWindowRemove();});
			$('#customiseHomepage_overlay').click(function(){$.e4eCustomHomepage.customiseWindowRemove();});
			var boxHTML = 	'<ul id="custom_box_choices">';
			var addRemove = '';
			var item;
			for(item in $.e4eCustomHomepageBoxes){
				if($('#'+item).length >0){
					addRemove = '<span class="custom_remove" title="Click here to remove this box"><span>Click here to remove this box</span></span>';
				}else{
					addRemove = '<span class="custom_add" title="Click here to add this box"><span>Click here to add this box</span></span>';
				}
				boxHTML +=	'<li id="preview_'+item+'">'+addRemove+'<span class="custom_preview_icon" title="Click here to preview this box"><span>Click here to preview this box </span></span><span class="custom_preview_label">'+($.e4eCustomHomepageBoxes[item].boxTitle === undefined ? item : $.e4eCustomHomepageBoxes[item].boxTitle)+'</span></li>';
			}
			boxHTML +=	'</ul>';
			$('#custom_box_choice').append(boxHTML);
			$('#custom_box_choice .custom_remove').click(function(){
				$.e4eCustomHomepage.debug(options, 'Remove Icon Clicked');
				$.e4eCustomHomepage.clickRemove(options, ($(this).parent().attr('id').replace('preview_','')), $(this)); 
			});
			$('#custom_box_choice .custom_add').click(function(){
				$.e4eCustomHomepage.debug(options, 'Add Icon Clicked');
				$.e4eCustomHomepage.clickAdd(options, ($(this).parent().attr('id').replace('preview_','')), $(this)); 
			});
			$('#custom_box_choices .custom_preview_label').click(function(){
				$.e4eCustomHomepage.previewBox(options, ($(this).parent().attr('id').replace('preview_',''))); 
			});
			$('#custom_box_choices .custom_preview_icon').click(function(){
				$.e4eCustomHomepage.previewBox(options, ($(this).parent().attr('id').replace('preview_',''))); 
			});
		},
		clickAdd: function(options, boxID, element){
			$.e4eCustomHomepage.addBox(options, boxID); 
			$(element).replaceWith(
				$('<span class="custom_remove" title="Click here to remove this box"><span>Click here to remove this box</span></span>').click(function(){
					$.e4eCustomHomepage.clickRemove(options, ($(this).parent().attr('id').replace('preview_','')), $(this)); 
				})
			);
		},
		clickRemove: function(options, boxID, element){
			$.e4eCustomHomepage.debug(options, 'Remove function init');
			$.e4eCustomHomepage.removeBox(options, '#'+boxID); 
			$(element).replaceWith(
				$('<span class="custom_add" title="Click here to add this box"><span>Click here to add this box</span></span>').click(function(){
					$.e4eCustomHomepage.clickAdd(options, ($(this).parent().attr('id').replace('preview_','')), $(this)); 
				})
			);
		},
		customiseWindowResize: function(){
			$('#customiseHomepage_overlay').css({
				height:$(window).height(),
				width:$(window).width(),
				background: '#000',
				opacity: 0.4,
				position:'fixed',
				top:0,
				left:0
			});
			var windowHeight = $(window).height()-50;
			var windowTop = 0-(windowHeight/2);
			$('#customiseHomepage').css({
				border:'1px solid #333',
				height:windowHeight,
				width:650,
				position:'fixed',
				background:'#fff'
			}).stop().animate({
				top:windowTop,
				left:-325,
				marginTop:($(window).height())/2,
				marginLeft:($(window).width())/2
			},250);
			$('#custom_chooser').height(windowHeight-20);
		},
		customiseWindowRemove:function(){
			$('#customiseHomepage_holder').remove();
			$('body').css('overflow', 'auto');
		},
		previewBox: function(options, objectRef){
			// set loading details...
			var boxesHolder = $.e4eCustomHomepageBoxes;
			var boxTitle = boxesHolder[objectRef].boxTitle || 'Loading';
			var boxHTML =	'<div id="preview_description">';
			boxHTML +=	'	<h4>Description</h4>';
			boxHTML +=	'	<div id="preview_description_text">';
			boxHTML +=	'		<p>Please wait, description is loading.</p>';
			boxHTML +=	'	</div>';
			boxHTML +=	'</div>';
			boxHTML += 	'<div class="'+options.boxClass+'" id="box_preview_'+objectRef+'">';
			boxHTML +=	'	<h2><span>'+boxTitle+'</span></h2>';
			boxHTML +=	'	<div class="dynamicContent">';
			boxHTML +=	'		'+options.loadingHTML;
			boxHTML +=	'	</div>';
			boxHTML +=	'</div>';
			$('#custom_box_preview').html(boxHTML);
			$.e4eCustomHomepage.debug(options,'AJAX call ajax request for: "'+objectRef+'"', 'info');
			// perform ajax request...
			$.ajax({
				url: options.boxURL+'?preview=true',
				data: $.e4eCustomHomepageBoxes[objectRef],
				dataType: 'json',
				type: 'POST',
				success:function(data){
					$.e4eCustomHomepage.debug(options,'AJAX success: Recieved data back for "'+objectRef+'"', 'info');
					var boxTitleObj = boxesHolder[objectRef].boxTitle || data.boxTitle;
					var descriptionText = data.description || '<p><em>No description available</em></p>';
					if(descriptionText.indexOf('<p>') == -1){descriptionText = '<p>'+descriptionText +'</p>';}
					$('#preview_description_text').html(descriptionText);
					$('h2:first span', $('#box_preview_'+objectRef)).text(boxTitleObj);
					$('.dynamicContent', $('#box_preview_'+objectRef)).html(data.boxContent);
					if(data.boxScript !== undefined){
						$.e4eCustomHomepage.debug(options,'AJAX load script for "'+objectRef+'"', 'warn');
						$.e4eCustomHomepage.debug(options,data.boxScript,'warn');
						eval(data.boxScript);
					}
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					$.e4eCustomHomepage.debug(options,'<--- ERROR ---> AJAX Recieved error back for "'+objectRef+'" ajax request.', 'error');
					$.e4eCustomHomepage.debug(options,'<--- ERROR ---> AJAX cont. textStatus:"'+textStatus+'", errorThrown: "'+errorThrown+'".', 'error');
					$('.dynamicContent', $('#box_preview_'+objectRef)).html('<h4>Error</h4><p>Sorry, there was a problem retrieving this content box.</p><p>Please click <a class="custom_reload">here</a> to try again.</p>');
					$('.custom_reload', $('#box_preview_'+objectRef)).click(function(){$.e4eCustomHomepage.loadBox(options, $(objectRef), objectRef, 'replace');});
				}
			});
		},
		autoHeight: function(options){
			$.e4eCustomHomepage.debug(options,'autoHeight invoke');
			// get parent height and offset
			var parentHeight = 0;
			for(var i=0; i<options.columnRefs.length; i++){
				if(parentHeight<$(options.columnRefs[i]).parent().height()){
					parentHeight = $(options.columnRefs[i]).parent().height();
				}
			}
			// if parent offset is different to object offset then alter height
			var parentOffset, objOffset;
			for(i=0; i<options.columnRefs.length; i++){
				parentOffset = $(options.columnRefs[i]).parent().offset();
				objOffset = $(options.columnRefs[i]).offset();
				if(parentOffset.top != objOffset.top){
					$(options.columnRefs[i]).height(parentHeight - (objOffset.top - parentOffset.top));
				}else{
					$(options.columnRefs[i]).height(parentHeight);
				}
			}
		}
	};
/*
##########################################################
				END CUSTOM HOMEPAGE FUNCTION
##########################################################
*/