/* --------------------------------------------------------------------------------
* Knowsley Metropolitan Borough Council
* Homepage javascript
*
* Uses jQuery 1.2
* Created 072008
* Last edited 23072008 Tom Adams, Reading Room
-------------------- */

/* -----------------
* Sortable boxes
-------------------- */
	function rearrangeDummySpotlights(){
		if($("#spotlights .left .spotlight").length==0){
			$("#dummySpotLeft").height($("#spotlights .right").height());
		} else {
			$("#dummySpotLeft").height("100px").appendTo("#spotlights .left");
		}
		if($("#spotlights .right .spotlight").length==0){
			$("#dummySpotRight").height($("#spotlights .left").height());
		} else {
			$("#dummySpotRight").height("100px").appendTo("#spotlights .right");
		}
	}

	function getSpotlightsOrder() {
		// save custom order to cookie
		$.cookie("homeColOrderL", $("#spotlights .left").sortable("toArray"), { expires: 3650 });
		$.cookie("homeColOrderR", $("#spotlights .right").sortable("toArray"), { expires: 3650 });
		rearrangeDummySpotlights();
	}
	function moveSpotlights() {
		//onload, if cookies are set, rearrange the boxes
		if($.cookie("homeColOrderL")){
			//create arrays of box IDs from the two cookies
			colOrderL = $.cookie("homeColOrderL").split(",");
			colOrderR = $.cookie("homeColOrderR").split(","); 
			
			//move the original elements (remove then clone) to the bottom of their columns 
			for (i=0;i<colOrderL.length;i++){
				$("#"+colOrderL[i]).remove().clone().appendTo("#spotlights .left");	
			}
			for (i=0;i<colOrderR.length;i++){
				$("#"+colOrderR[i]).remove().clone().appendTo("#spotlights .right");	
			}			
		}
		//create dummy spotlights
		$("#spotlights .left").append("<div id=\"dummySpotLeft\"><!--//--></div>");
		$("#spotlights .right").append("<div id=\"dummySpotRight\"><!--//--></div>");
		rearrangeDummySpotlights();
		
		//make boxes sortable
		$("#spotlights .left").sortable({
			cancel: "ul",
		    connectWith: ["#spotlights .right"],
			/*containment: "#spotlights",*/
			handle: ".hdr",
			placeholder: "spotlightsDragPlaceholder", 
			zIndex:999,
			opacity:0.8,
			cursor:"move",
			tolerance:"tolerance",
			stop: function() { getSpotlightsOrder(); }
		});
		$("#spotlights .right").sortable({ 
			cancel: "ul",
		    connectWith: ["#spotlights .left"],
			/*containment: "#spotlights",*/
			handle: ".hdr",
			placeholder: "spotlightsDragPlaceholder", 
			zIndex:999,
			opacity:0.8,
			cursor:"move",
			tolerance:"tolerance",
			stop: function() { getSpotlightsOrder(); }
		});
	}

/* --------------------------------------------------------------------------------
* Do It Online customisation
-------------------- */
	//hide the section on page load to avoid all items flashing on-screen
	document.write('<style type="text/css">#doItOnline {display:none;}</style>');

	function writeDioCookie(){
		dioOff="";//create string for cookie
	 	$("#doItOnline li.off").each(function(){
			dioOff += $(this).find("a").text() + "^";//build up cookie string
		});
		//add dummy value to end of cookie to ensure that it's not empty - an empty value will delete the cookie
		dioOff+="*";
		//write the cookie
		$.cookie("homeDioOff", dioOff, { expires: 3650 });
	}	
	function hideEdit(){
		//hide all the editing feautures - used on save and cancel
	 	dioItems=$("#doItOnline").find("li");
		dioItems.each(function(){
			$(this).removeClass("dioEdit");
			$(this).find(":checkbox").hide();
			$(this).find("label").hide();
			$(this).find("a").show();
		});
		$("#doItOnline li.off").hide();//hide non-selected items
	}
	
	function doItOnline(){
	/* ---------------------------------------
	* run on load
	--------------------------------------- */
		//Create buttons and instructory text		
		$("#doItOnline .content")
		//'nothing selected' text
								.append("<p class=\"nothingSelected\" style=\"display:none;\">You don't have any Do It Online links in your list. Use the 'Edit/view full list' button to add items.</p>")
		//edit button
								.prepend("<p style=\"display:none;\" class=\"editList\" id=\"editList\"><a href=\"#\"><span><span><span>Edit</span></span></span></a></p>")
		//edit CTA
								.prepend("<p class=\"personalise\" style=\"display:none;\">You can also personalise which services you see by default. Just click the edit button.</p>")
		//save button
								.prepend("<p style=\"display:none;\" class=\"editList\" id=\"saveList\"><a href=\"#\"><span><span><span>Save Changes</span></span></span></a></p>")
		//edit instructions text
								.prepend("<p class=\"instructions\" style=\"display:none;\">Select the Do It Online links that you want to appear in your list. Click the 'Save changes' button when you're done.</p>");

		//In-header buttons
		$("#doItOnline h2")
		//view all button
								.append("<p class=\"editList\" id=\"viewAll\"><a href=\"#\"><span><span><span>View all</span></span></span></a></p>")
		//cancel button
								.append("<p style=\"display:none;\" class=\"editList\" id=\"cancel\"><a href=\"#\"><span><span><span>Cancel</span></span></span></a></p>");

		//Put 'more links' text in all headers
		moreLinksInner = "More links<span class=\"hide\"> - </span>";
		lessLinksInner = "Less links<span class=\"hide\"> - </span>";
		$("#doItOnline .content h3").prepend("<span class=\"moreLinks\">" + moreLinksInner + "</span>")
		$("#doItOnline .content h3").hover( 
			function () { 
				$(this).find(".moreLinks").addClass("moreLinksHover");
			},  
			function () { 
				$(this).find(".moreLinks").removeClass("moreLinksHover");
			} 
		); 
		
		//check for cookie
		dioCookie = ($.cookie("homeDioOff")) ? true : false;
		$("#doItOnline li").each(function(){
			//if no cookie, perform default behaviour - hide anything without 'on' class
			//but if cookie exists, ensure item is shown
			if (!dioCookie && !$(this).hasClass("on")){
				$(this).addClass("off");
			}
			//Create the editing elements and hide them
			itemId = $("#doItOnline li").index(this);
			$(this).prepend("<input id=\"dio"+itemId+"\" name=\"dio"+itemId+"\" type=\"checkbox\" checked=\"checked\" style=\"display:none;\"/>");
			$(this).append("<label for=\"dio" + itemId + "\" style=\"display:none;\">" + $(this).text() + "</label>")
		});
		
		//if cookie exists...
		if (dioCookie){
			//set all items to 'on' 
			$("#doItOnline li").addClass("on");
			
			//create aray of items from the cookie
			offItems = $.cookie("homeDioOff").split("^");
			for (i=0;i<offItems.length;i++){
				//for each item in the array, check whether there's an li with a matching name
				$("#doItOnline li:contains(" + offItems[i] + ")").each(function(){
					if($(this).find("a").text()==offItems[i]){
						//switch any matches to 'off' 
						$(this).addClass("off").removeClass("on");
					}
				});
			}
		};

		/*
		//check all headings and hide those without any active items
		$("#doItOnline h3").each(function(){
			numActive = 0;
			$(this).next().find("li").each(function(){
				if ($(this).hasClass("on")){
					numActive ++;
				}
			});
			if (numActive==0){
				$(this).addClass("off");
			}
		});
		
		//if no items are 'on', then show the 'nothing selected' message
		if($("#doItOnline li.on").length==0){
			$("#doItOnline .nothingSelected").show();
		}
		*/
		
		//show the completed section
		$("#doItOnline").show();

	/* ---------------------------------------
	* user clicks a section header
	--------------------------------------- */
		$("#doItOnline h3").click(function(){
			if($(this).find(".moreLinks").text().indexOf("More")!=-1){
				$(this).find(".moreLinks").html(lessLinksInner)
			} else {
				$(this).find(".moreLinks").html(moreLinksInner)
			}
			$(this).next().toggleClass("showAllItems");
		});
		
	/* ---------------------------------------
	* user clicks the 'View all' link
	--------------------------------------- */
		$("#doItOnline #viewAll a").click(function(){
			/*
			$("#doItOnline h3").addClass("expanded");
			$("#doItOnline h3.off").removeClass("off").addClass("offExpanded");
			*/

			$("#doItOnline ul").addClass("showAllItems");

			//show/hide buttons
			$(this).parent().hide(); //hide view all button
			$("#doItOnline #cancel").show();//show 'close' button
			$("#doItOnline #editList").show();//show edit list button
		 	$("#doItOnline .personalise").show();
			
			//add class to the first h3
			$("#doItOnline h3:first").addClass("first");
			
			//ensure all 'more links' are are changed to 'less'
			$("#doItOnline .moreLinks").html(lessLinksInner)

			return false;
		});

	/* ---------------------------------------
	* user clicks the 'Cancel' link (from either View All or Edit state)
	--------------------------------------- */
		$("#doItOnline #cancel a").click(function(){
			/*$("#doItOnline h3").removeClass("expanded");
			$("#doItOnline h3.offExpanded").removeClass("offExpanded").addClass("off");*/
			
			$("#doItOnline ul").removeClass("showAllItems");

			//track which items have been changed (in edit mode) and revert them
			$("#doItOnline .changed").toggleClass("off").toggleClass("on").removeClass("changed");

			//hide the editing features
			hideEdit();

			//show/hide buttons
			$(this).parent().hide(); //hide 'close' button
			$("#doItOnline #editList").hide();//show 'close' button
			$("#doItOnline #viewAll").show();//show view all button
			$("#doItOnline #saveList").hide();//show view all button
		 	$("#doItOnline .personalise").hide();
			$("#doItOnline .instructions").hide();//hide text

			//remove class on the first h3
			$("#doItOnline h3:first").removeClass("first");

			//ensure all 'less links' are are changed to 'more', and show them if hidden
			$("#doItOnline .moreLinks").html(moreLinksInner).show();

			return false;
		});

	/* ---------------------------------------
	* user clicks the 'edit list' link
	--------------------------------------- */
		$("#doItOnline #editList a").click(function(){
		 	$("#doItOnline ul").removeClass("showAllItems");
		 	$("#doItOnline li.off").show();
		 	$("#doItOnline .instructions").show();
		 	$("#doItOnline .nothingSelected").hide();
			/*
			$("#doItOnline h3").removeClass("off").removeClass("offExpanded");
			*/
		 	dioItems=$("#doItOnline li");
			dioItems.each(function(){
				$(this).addClass("dioEdit");
				$(this).find(":checkbox").show();
				$(this).find("label").show();
				$(this).find("a").hide();
				$(this).parent().find(".off :checkbox").removeAttr("checked");
			})
			$("#doItOnline #editList").hide();//show 'close' button
			$("#doItOnline #cancel").show();//show 'close' button
			$("#doItOnline #saveList").show();//show view all button
		 	$("#doItOnline .personalise").hide();//hide editing CTA

			//hide all the more/less links
			$("#doItOnline .moreLinks").hide();

			return false;
		});
		
	//user changes checkboxes
		$("#doItOnline :checkbox").change(function(){
			$(this).parent().toggleClass("off").toggleClass("on").addClass("changed");//track changes for the 'cancel' functionality
		})
		
	/* ---------------------------------------
	* user clicks the 'save changes' link
	--------------------------------------- */
		$("#doItOnline #saveList a").click(function(){
			//write cookie
			writeDioCookie()
			
			//hide the editing features
			hideEdit();
			
			//stop tracking changes
			$("#doItOnline .changed").removeClass("changed");//track which items have been changed (in edit mode) and revert them

			$("#doItOnline .instructions").hide();//hide instructions
			$("#doItOnline #editList").hide();//hide 'close' button
			$("#doItOnline #viewAll").show();//show 'close' button
			$("#doItOnline #saveList").hide();//hide view all button
			$("#doItOnline #cancel").hide();//hide close edit button
			
			//remove class on the first h3
			$("#doItOnline h3:first").removeClass("first");

			/*
			//check all headings and hide those without any active items
			//and check if zero items are being shown
			numItems = 0;
			$("#doItOnline").find("h3").each(function(){
				numActive = 0;
				$(this).next().find("li").each(function(){
					if ($(this).hasClass("on")){
						numActive ++;
					}
				});
				if (numActive==0){
					$(this).addClass("off").removeClass("on");
				} else {
					$(this).addClass("on").removeClass("off");
				}
				numItems+=numActive;
			});
			if(numItems==0){
				$("#doItOnline").find(".nothingSelected").show();
			}
			*/

			//ensure all 'less links' are are changed to 'more', and show them if hidden
			$("#doItOnline .moreLinks").html(moreLinksInner).show();

			return false;
		});
	}


/* --------------------------------------------------------------------------------
* Toggle homepage boxes
-------------------- */
	function toggleHomepageBoxes(){
		//run onload
		//check for subnav cookie
		if ($.cookie("homeNavOff")){
			offItems = $.cookie("homeNavOff").split("^");
			for (i=0;i<offItems.length;i++){
				//for each item in the array, check whether there's an h2 with a matching name
				$("#homepage #leftCol h2[class*='"+ offItems[i] +"']").each(function(){
					//switch any matches to 'off', change title, hide the next sibling (the content div)
					$(this).children().addClass("off");
					$(this).children().attr("title","Show Content");
					$(this).next().hide();
				});
			}
		}
		
		//subnav/tag clouds column
		$('#homepage #leftCol h2').click(function() {
			//animate the heading and create a cookie
			$(this).find('span:first').toggleClass('off');
			$(this).next().slideToggle("medium", function () { 
				// change 'title'
				if($(this).prev().find('span:first').attr("title")=="Hide Content"){
					$(this).prev().find('span:first').attr("title","Show Content");
				} else {
					$(this).prev().find('span:first').attr("title","Hide Content");
				}
				// create string for cookie
				navOff="";
				// create cookie of all 'off' items
				$(this).parent().find("div.content:hidden").each(function(){ //NOTE - .parent() might need amending when James chanegs the behaviour of these links????
					navOff+=$(this).prev().attr("class")+"^";
				});
				navOff+="*NULL*";//avoid empty final item
				$.cookie("homeNavOff", navOff, { expires: 3650 });
			});

		});
		
		//Spotlights
		$('#homepage #rightCol #spotlights .spotlight .hdr ul li a img.showHide').click(function() {
			$(this).parent().parent().parent().parent().parent().parent().find('.content').slideToggle();
			if($(this).attr("src")=="images/template/home-spot-hide.png"){
				$(this).attr("src","images/template/home-spot-show.png");
				$(this).attr("title","Show Content");
			} else {
				$(this).attr("src","images/template/home-spot-hide.png");
				$(this).attr("title","Hide Content");
			}
			return false;
		});
	}

/* --------------------------------------------------------------------------------
* Reset page
-------------------- */
	function resetPage(){
		$(".resetPage").click(function(){
			//Check that the user understands and is sure
			if (confirm('This will:\n\n- reset the order of boxes on this page\n- undo changes you have made to the Do It Online links\n\nAre you sure you want to do this?\n\n')) {
				//delete all the cookies		
				$.cookie("homeDioOff", "", { expires: -1 });
				$.cookie("homeColOrderL", "", { expires: -1 });
				$.cookie("homeColOrderR", "", { expires: -1 });
				$.cookie("homeNavOff", "", { expires: -1 });
				
				//reload the page
				window.location.reload()
	        }
			return false;

		});
	}
	
/* --------------------------------------------------------------------------------
* onload
-------------------- */
$(function () {
	moveSpotlights();
	toggleHomepageBoxes();
	doItOnline();
	resetPage();

/* --------------------------------------------------------------------------------
* Add spans to homepage H1
-------------------- */
	$('#homepage #rightCol h1').wrapInner('<span></span>');
});



		
		
		
