// Global functions
function replaceptags() {	
	//$("#tier3copy p").append("<br />");
	//$("#tier3copy p").contents().unwrap();
}
function transformimage() {
	if($("#tier3copy").length > 0){
	$("#tier3copy img").each(function() {
		//count = $(this).index()+1;
		var currentwidth = $(this).css("width");
		
		//var cleanwidth = currentwidth.substring(0, currentwidth.length-2);
		//var percentagewidth = ((cleanwidth/100)*80);

		if($(this).attr("alt").charAt(0)==" ") {
			$(this).wrap("<div class=imageholder />");
			$(".imageholder").css("width",currentwidth);
			$(this).before("<div class=imagecaption>"+$(this).attr("alt")+"</div>");
		}
	});		
	}	
}
function staffdownloadwarning() {
	if ($.browser.msie) {
		var message = "<p>If you are experiencing issues downloading this document, please right click on the file, and choose 'Save target as'.</p>";
		$("a[href$='doc']").parent("p").append(message);
		$("a[href$='docx']").parent("p").append(message);
		$("a[href$='xls']").parent("p").append(message);
		$("a[href$='xlsx']").parent("p").append(message);
		$("a[href$='ppt']").parent("p").append(message);
		$("a[href$='pptx']").parent("p").append(message);
	}
}
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
function newsStyle(choose) {
	var type = "";
	if(choose) {
	    type = choose;	
	}
	else {
		type = getUrlVars()["type"];
	}
	if(type) {
		if(type === 'external' || type === 'research' || type === 'business' || type === '') {
			$('#headerswitch').load('/header.htm');
			$('#footerswitch').load('/footer.htm');
			$('#newsarchiveurl').attr("href", "http://www.leedsmet.ac.uk/about/news.htm");
		}
		else if(type === 'staff') {
			$('#headerswitch').load('/staff/header.htm');
			$('#footerservices').load('/staff/footerservices.htm');
			$('#footerswitch').load('/staff/footer.htm');
			$('#newsarchiveurl').attr("href", "http://www.leedsmet.ac.uk/staff/latest-news.htm");
		}
		else if(type === 'student') {
			$('#headerswitch').load('/students/header.htm');
			$('#footerservices').load('/students/Service_finder_for_portal.htm');
			$('#footerswitch').load('/staff/footer.htm');
			$('#newsarchiveurl').attr("href", "http://www.leedsmet.ac.uk/students/news.htm");
		}
	}
	else {
		$('#headerswitch').load('/header.htm');
			$('#footerswitch').load('/footer.htm');	
	}
}
function hashaccordion() {
  //var hash = window.location.hash.substring( 1 );
//
//  if( hash ) {
//    var accordItem = $( '#accordion li a#' + hash );
//    if(accordItem) accordItem.next('div').slideToggle('fast');
//  }
//
//  $('#accordion ul').hide();
//  $('#accordion li a').click(
//    function() {
//        $(this).next().slideToggle('normal');	
//      }
//    );
  
 //var hash = window.location.hash;
// var thash = hash.substring(hash.lastIndexOf('#'), hash.length);
// $('#accordion').find('a[href*='+ thash + ']').closest('h3').trigger('click');
  
  
  }
function faqcheck() {
	if($(".faqlistitem").length > 0){
		$(".faqlisting").each(function() {
			$('<ul/>').appendTo($(this));							
		});
		$(".faqlistitem").each(function() {
			$("<li><a href='#"+$(this).children("a.faqid").attr('id')+"'>"+$(this).children('.faqquestion').text()+"</a></li>").appendTo($(this).parent().children(".faqlisting").children("ul"));
			
			$(this).append("<a href='#"+$(this).parent().children(".faqlisting").attr('id')+"'>Back to top</a><br /><br />");
		});
		}
}
function togglediv(clickdiv,showdiv,speed,scrollto) {
	$(clickdiv).click(function(){
		$(showdiv).slideToggle(speed);
		$(this).toggleClass("active"); 
		 if(scrollto == 'bottom') {
//			var offsettop = parseInt($("body").css("height"));

//			window.scrollTo(0,offsettop);
			$('html, body').animate({ scrollTop: 60000 }, 'slow');
		} 
		return false;
	});
}
function verticalhovermenu(ulid) {
	$(ulid+" li,"+ulid+" li").hover(
    function() { $(this).addClass("iehover"); },
    function() { $(this).removeClass("iehover"); }
  );	
}
function imageslider(divid) {
	$(divid).wrapInner("<div id='slides' />");
	$("#slides").wrapInner("<div class='slides_container' />");
	$(divid).slides({
		preload: true,
		preloadImage: 'imagescroll/loading.gif',
		play: 7000,
		pause: 5000,
		hoverPause: true
		});
}
function facultyscroller(divid,targetdivid) {
	
	$.localScroll.defaults.axis = 'xy';
	$(divid).localScroll({
		target: targetdivid,
		hash: true
	});
}

function carousel(divid) {
    $(divid+' li').each(function() {
         count = $(this).index()+1;
         $('.jcarousel-control').append("<a href='#'>"+count+"</a>");                                                                                   
    });
  $(divid).jcarousel({initCallback: carousel_initCallback, scroll: 1, auto: 0, wrap:'both' });
}
 
function carousel_initCallback(carousel) {
                jQuery('.jcarousel-control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });
 
 
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });
    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
 
}

function tabbedcontent(ulid) {
	$('#tabs > div').hide();
	if(window.location.hash) {
		var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
		$("#"+hash).show();
		$('#tabs ul#'+ulid+' li').removeClass('active');
		$('#tabs ul#'+ulid+' li#'+hash+"'").addClass('active');
      	//alert (hash);
	}
	else {
    	$('#tabs > div:first').show();
    	$('#tabs ul#'+ulid+' li:first').addClass('active');
	}
	$('#tabs ul#'+ulid+' li a').click(function(){ 
		$('#tabs ul#'+ulid+' li').removeClass('active');
		$(this).parent().addClass('active'); 
		var currentTab = $(this).attr('href');
		$('#tabs > div').hide();
		$(currentTab).show();
		return false;
    });
}
function cleardefaultinput(inputid) {
        var defaultmessage = $(inputid).val();
        $(inputid)
        .click(function() {
			if($(inputid).val() == defaultmessage) {
            	$(inputid).val("");
			}
        })
        .blur(function() {
			if($(inputid).val() == "") {
            	$(inputid).val(defaultmessage);
			}
        })
		.focus(function() {
			if($(inputid).val() == defaultmessage) {
            	$(inputid).val("");
			}
        })
		;
}
function sortlist(ulid) {
	var menu = $("#"+ulid).children('li').get(); 
	menu.sort(function(a, b) { 
	var val1 = $(a).text().toUpperCase(); 
	var val2 = $(b).text().toUpperCase(); 
	return (val1 < val2) ? -1 : (val1 > val2) ? 1 : 0; 
	}); 
	$.each(menu, function(index, row) { 
		$("#"+ulid).append(row); 
	}); 	
}

// Staff functions

function setCookie(element_id,cookiename) {
	$.cookie(cookiename, element_id, { path: '/', expires: 2920 });
}
function deleteCookie(cookiename) {
	$.cookie(cookiename, null, { path: '/'});
}


// Favourites
function populateFave() {
		var urlval = getPageURL();
		var titleval = getPageTitle();
		var pageidval = $("#pageid").val();
		var checkstring = escape(pageidval)+";"+escape(urlval)+";"+escape(titleval);
		var actualstring = "";
		var found = false;
		
		if($.cookie("stafffave")) {
			$("#favourites").show();
			$("#favelist").empty();
			$("#replacelist").empty();
			
			var favourites = new Array(6);
			for (favei=0; favei<=6; favei++) {
				favourites[favei]=new Array(3);
			}
			var favecookie = $.cookie("stafffave");
		
			if(favecookie.indexOf(",") != -1) {
			   
				var favesplit = favecookie.split(',');
				for (favespliti=0; favespliti<favesplit.length; favespliti++) {	
					var secondsplit = favesplit[favespliti].split(';');
					for (secondspliti=0; secondspliti<1; secondspliti++) {
						for (secondsplitj=0; secondsplitj<3; secondsplitj++) {
							favourites[favespliti][secondsplitj] = secondsplit[secondsplitj];
						}	
					}	
						//if (hasrightcol){
						actualstring = favourites[favespliti][0]+";"+favourites[favespliti][2]+";"+favourites[favespliti][1];
						if(actualstring == checkstring) {
							found = true;
						}
//							else {
//								$("#favebuttonimage").attr("src","http://www.leedsmet.ac.uk/assets/images/staff/buttons/addtofavouriteitem.gif");
//							}
//						}
					$("#favelist").append("<li><a title='"+unescape(favourites[favespliti][0])+"' class='removefavourite'></a><a title='"+unescape(favourites[favespliti][1])+"' href='"+unescape(favourites[favespliti][2])+"'>"+unescape(favourites[favespliti][1])+"</a></li>");	
					$("#replacelist").append("<input type='radio' name='radioreplace' value='"+favourites[favespliti][0]+";"+favourites[favespliti][1]+";"+favourites[favespliti][2]+"' id='radioreplace_"+favespliti+"' />&nbsp;"+unescape(favourites[favespliti][1])+"<br />");
//					sortlist("#favelist");
//					sortlist("#replacelist");
					$("#servicesList a[title="+unescape(favourites[favespliti][0])+"]").removeClass('addfavourite').addClass('removefavourite');
					
					//$("."+favourites[favespliti][0]).attr("title");
				}
			}
			else {
					var secondsplit = favecookie.split(';');
					for (secondspliti=0; secondspliti<1; secondspliti++) {		
						for (secondsplitj=0; secondsplitj<3; secondsplitj++) {
							favourites[0][secondsplitj] = secondsplit[secondsplitj];	
						}	
					}	
					actualstring = favourites[0][0]+";"+favourites[0][2]+";"+favourites[0][1];
					if(actualstring == checkstring) {
						found = true;
					}
					$("#favelist").append("<li><a title='"+unescape(favourites[0][0])+"' class='removefavourite'></a><a title='"+unescape(favourites[0][1])+"' href='"+unescape(favourites[0][2])+"'>"+unescape(favourites[0][1])+"</a></li>");
					//sortlist("#favelist");
					$("#servicesList a[title="+unescape(favourites[0][0])+"]").removeClass('addfavourite').addClass('removefavourite');
			}
			
			
			if($("#rightcolumn").length > 0){
				if($("#favebutton").length > 0){}
				else {
					$("#breadcrumb").append("<div id='favebutton'></div>");
				}

				if(found==true) {
					$("#favebutton").empty().prepend("<ul><li><a class='removefavourite' title='"+pageidval+"'><img id='favebuttonimage' src='http://www.leedsmet.ac.uk/assets/images/staff/buttons/removefromfavouriteitem.gif' /></a><a id='"+pageidval+"' title='"+titleval+"' href='"+urlval+"'></a></li></ul>");
				}
				else {
					$("#favebutton").empty().prepend("<ul><li><a class='addfavourite' title='"+pageidval+"'><img id='favebuttonimage' src='http://www.leedsmet.ac.uk/assets/images/staff/buttons/addtofavouriteitem.gif' /></a><a id='"+pageidval+"' title='"+titleval+"' href='"+urlval+"'></a></li></ul>");	
				}
			}
			
			//orderList();
		}
		else {
			//alert("has no cookie");
			if($("#rightcolumn").length > 0){
				/*if($("#righthandfave").length == 0){
					$("#rightimage").after("<div id='righthandfave'></div>");
				}*/
				if($("#favebutton").length > 0){}
				else {
					$("#breadcrumb").append("<div id='favebutton'></div>");
				}
				$("#favebutton").empty().prepend("<ul><li><a class='addfavourite' title='"+pageidval+"'><img id='favebuttonimage' src='http://www.leedsmet.ac.uk/assets/images/staff/buttons/addtofavouriteitem.gif' /></a><a id='"+pageidval+"' title='"+titleval+"' href='"+urlval+"'></a></li></ul>");
			}
		}
}	
function replaceFave(addstring) {
	$("#replace").show('slow');
	$('html, body').animate({ scrollTop: 0 }, 'slow');
}
function addToFave(id,name,url) {
	var addstring = escape(id)+";"+escape(name)+";"+escape(url);
	if($.cookie("stafffave")) {
		$("#replace").hide('slow');
		var favecookie = $.cookie("stafffave");	
		var favesplit = favecookie.split(',');
		if(favecookie.indexOf(addstring) != -1) {
			alert("You have already added this item to your favourites");
		}
		else {
			if(favesplit.length<6) {
				favesplit.push(addstring);
				setCookie(favesplit,"stafffave");
				populateFave();
			}
			else {
				$("#replacewith").val(addstring);
				replaceFave(addstring);
			}	
		}	
		
	}
	else {
		setCookie(addstring,"stafffave");
		//populateFave();
	}
	populateFave();
}
function removeFromFave(id,name,url) {
	var removestring = escape(id)+";"+escape(name)+";"+escape(url);
	if($.cookie("stafffave")) {
		var favecookie = $.cookie("stafffave");
		var favesplit = favecookie.split(',');

		for (favespliti=0; favespliti<=favesplit.length; favespliti++) {	
			if(favesplit[favespliti] == removestring) {
				favesplit.splice(favespliti,1);
			}
		}
		if(favesplit.length >=1) {
			favesplit = favesplit;
			setCookie(favesplit,"stafffave");
		}
		else {
			deleteCookie("stafffave");
			$("#favelist").empty();
			$("#favourites").hide();
		}
    $("#servicesList a[title="+id+"]").removeClass('removefavourite').addClass('addfavourite');
	populateFave();
	}
}
function getPageURL() {
	var url = $(location).attr('href');
	return url;
}
function getPageTitle() {
	var title = $(document).attr('title');
	return title;
}

function displayResourceCentre() {
	var currentKeywords = $("#servicekeywords").val();
	var resourcecentres = new Array();
	for (i=0; i <2; i++) {
		resourcecentres[i]=new Array(2);
	}
	var title = "";
	var sbcstrip = "";
	var sbc=new Array(21)
	for (i=0; i <21; i++) {
		sbc[i]=new Array(2);
	}
	sbc[0][0] = "AET"; sbc[0][1] = "faculty-of-arts-environment-and-technology.htm";
	sbc[1][0] = "CAF"; sbc[1][1] = "carnegie-faculty.htm";
	sbc[2][0] = "CAR"; sbc[2][1] = "campus-and-residential-services-cares.htm";
	sbc[3][0] = "DSE"; sbc[3][1] = "centre-for-learning-and-teaching.htm";
	sbc[4][0] = "ESC"; sbc[4][1] = "estate-services.htm";
	sbc[5][0] = "EXE"; sbc[5][1] = "vice-chancellors-group.htm";
	sbc[6][0] = "FBL"; sbc[6][1] = "faculty-of-business-and-law.htm";
	sbc[7][0] = "FIN"; sbc[7][1] = "financial-services.htm";
	sbc[8][0] = "HRD"; sbc[8][1] = "human-resources.htm";
	sbc[9][0] = "HSS"; sbc[9][1] = "faculty-of-health-and-social-sciences.htm";
	sbc[10][0] = "IMT"; sbc[10][1] = "information-media-and-technology-services-imts.htm";
	sbc[11][0] = "INO"; sbc[11][1] = "international-office.htm";
	sbc[12][0] = "LLI"; sbc[12][1] = "libraries-learning.htm";
	sbc[13][0] = "MAC"; sbc[13][1] = "marketing-and-communications.htm";
	sbc[14][0] = "RSO"; sbc[14][1] = "registrar-and-secretarys-office.htm";
	sbc[15][0] = "RUN"; sbc[15][1] = "regional-university-network-run.htm";
	sbc[16][0] = "SPT"; sbc[16][1] = "university-sport.htm";
	sbc[17][0] = "SSV"; sbc[17][1] = "student-services.htm";
	sbc[18][0] = "STB"; sbc[18][1] = "student-bursaries.htm";
	sbc[19][0] = "URE"; sbc[19][1] = "university-research-and-enterprise-office.htm";
	sbc[20][0] = "WDP"; sbc[20][1] = "widening-participation.htm";
	
	if($("#servicekeywords").val() !="") {
	
	var keywordsplit = currentKeywords.split(';');
	
	var tempintro = "";
	var address = "";
	
	for (spliti=0; spliti<keywordsplit.length; spliti++) {	
		tempintro = keywordsplit[spliti];
		if(tempintro.substr(0,44) == "Resource Centres - Services offered by Area:") {
			tempintro = tempintro.replace("Resource Centres - Services offered by Area:", "");
			resourcecentres[spliti][0] = tempintro.substr(0,3);
			
			//for (i=0; i <21; i++) {
//				alert(sbc[i][1]);
//				if (sbcstrip == sbc[i][0]) {
//					resourcecentres[i][1].push(sbc[i][1]);
//					alert("hooray");
//				}
//			}
			tempintro = tempintro.substr(6,tempintro.length);
			resourcecentres[spliti][1] = tempintro;
		}
		else {
				
		}
	}
	if(resourcecentres.length == 1) {
		title = "Service Area: "+resourcecentres[0][1];
	}
	else if(resourcecentres.length > 1) {

		for (resourcei=0; resourcei<resourcecentres.length-1; resourcei++) {
			if(resourcei == 0) {
				title = "Service provided by "+resourcecentres[resourcei][1];
			}
			else if(resourcei == resourcecentres.length-1) {
				title = title+" and "+resourcecentres[resourcei][1];
			}
			else {
				title = title+", "+resourcecentres[resourcei][1];	
			}
		}
	}
	$("#rightimage").prepend("<div id='rightimagetitle'>"+title+"</div>");
	}
}

function staffFaveSetup() {
if ($("#servicesList").length > 0){
	$("#servicesList li").prepend('<a class="addfavourite" />');
}

$("#header").after("<div id='favourites'><div id='favouriteslist'><ul id='favelist' class='to_order'></ul></div></div>");
$("#favourites").prepend("<input id='replacewith' name='replacewith' type='hidden' value='' /><input id='itemtoreplace' name='itemtoreplace' type='hidden' value='' /><div id='replace'>You have reached the maximum of 6 favourite links. Please choose which older link to replace below:<br /><ul id='replacelist' class='to_order'></ul><div align='center'><input name='btncancel' id='btncancel' type='button' value='Cancel replace' /><input name='btnreplace' id='btnreplace' type='button' value='Replace this item' /></div>");
//displayResourceCentre();
$('#btnreplace').click(function() {
			if($("input[name=radioreplace]").is(':checked') ) {
				$("#itemtoreplace").val($("input[name='radioreplace']:checked").val());	
				var favecookie = $.cookie("stafffave");
				var replacedstring = new String(favecookie.replace($("#itemtoreplace").val(),$("#replacewith").val()));
				setCookie(replacedstring,"stafffave");
				populateFave();
				$("#replace").hide('slow');
			}
			else {
				alert("Please choose an item to replace");	
			}
});
$('#btncancel').click(function() {
	$("#replace").hide('slow');
});
$(".addfavourite").each(function() {
	$(this).attr("title",$(this).siblings().attr("id"));
});

$('.addfavourite').live('click', function(ev){
	ev.preventDefault();
	var url = "";	
	if($(this).siblings().attr("href").charAt(0) === "/") {
		url = "http://www.leedsmet.ac.uk"+$(this).siblings().attr("href");
	}
	else {
		url = $(this).siblings().attr("href");
	}
	if(url.charAt(url.length-1) === "#") {
		url = url.substring(0, url.length-1); 
	}
	addToFave($(this).attr("title"),$(this).siblings().attr("title"),url);
	if($("#rightcolumn").length > 0){
		$("#favebuttonimage").attr("src","http://www.leedsmet.ac.uk/assets/images/staff/buttons/removefromfavouriteitem.gif");
		$("#favebuttonimage").parent().removeClass('addfavourite').addClass('removefavourite');
	}
});

$('.removefavourite').live('click', function(){
	
	if($(this).siblings().attr("href").charAt(0) === "/") {
		url = "http://www.leedsmet.ac.uk"+$(this).siblings().attr("href");
	}
	else {
		url = $(this).siblings().attr("href");
	}
	removeFromFave($(this).attr("title"),$(this).siblings().attr("title"),url);
	if($("#rightcolumn").length > 0){
			$("#favebuttonimage").attr("src","http://www.leedsmet.ac.uk/assets/images/staff/buttons/addtofavouriteitem.gif");
			$("#favebuttonimage").parent().removeClass('removefavourite').addClass('addfavourite');
	}
});

}


function outputNewsArchive(ulid) {
// Month number to string
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
        
// Sorting the <li> by year
$(ulid+" li").sort(function(a,b) {
    var yearA = $(a).attr('title').split("/")[0],
        yearB = $(b).attr('title').split("/")[0];
    return yearA < yearB;
}).appendTo($(ulid));

// Grouping the <li> by year
$(ulid+" li").each(function() {
    var year = $(this).attr('title').split("/")[0];
    // If the grouping <li> doesn't exist, create it
    if ($(ulid+" li.year." + year).length === 0) {
        $(ulid).append($('<li class="year ' + year + '"><h2>' + year + '</h2><ul></ul></li>'));
    }
    // Add the current <li> to the corresponding grouping <li>
    $(this).appendTo($(ulid+" li.year." + year + " ul"));
});

// Sorting the <li> by month inside each grouping <li>
$(ulid+" li.year ul").each(function() {
    $(this).children("li").sort(function(a,b) {
        var monthA = $(a).attr('title').split("/")[1],
            monthB = $(b).attr('title').split("/")[1];
        return monthA < monthB;
    }).appendTo($(this));
});

// Grouping the <li> by month inside each grouping <li>
$(ulid+" li.year ul").each(function() {
    $this = $(this);
    $this.children("li").each(function() {
        var month = $(this).attr('title').split("/")[1];
        // If the grouping <li> doesn't exist, create it
        if ($this.find("li.month." + month).length === 0) {
            $this.append($('<li class="month ' + month + '"><h3>' + months[month-1] + '</h3><ul></ul></li>'));
        }
        // Add the current <li> to the corresponding grouping <li>
        $(this).appendTo($this.find("li.month." + month + " ul")).addClass("item");
    });
});
}
function ucastariffcalc() {
$("#firststep").show();
$("#secondstep").hide();
$(".droppable").hide();
$("#draggedpoints").hide();
$("#draggedsubpoints").hide();
$("#prevstep").hide();
$("#nextstep a").click(function() {
	$("#firststep").hide();
	$("#secondstep").show();
	$(".droppable").show();
	$("#nextstep").hide();
	$("#prevstep").show();
});
$("#prevstep a").click(function() {
	$("#firststep").show();
	$(".droppable").hide();
	$("#secondstep").hide();
	$("#prevstep").hide();
	$("#nextstep").show();
});
var currentTitle="";
var currentParent="";
var previousParent="";
var count=0;
var secondoutput = "";

$(".qualification").each(function(){
	
	var currentTitle = $(this).attr('title');
	var currentParent = $(this).parent().attr('title');
	
	if(currentParent !="") {
		
		if(currentParent != previousParent) {
		$("#firststep").append("<input type='checkbox' name='groupchoice' title='"+currentParent+"' value='checkbox' id='groupchoice_"+count+"' />"+currentParent+"<br />");
		secondoutput +="<div class='category' title='"+currentParent+"' id='"+currentParent+"'><span class='title'>"+currentParent+"</span>";
		$(this).parent().children().each(function(){
			secondoutput +="<div class='draggable' title='"+$(this).attr('title')+"'>"+$(this).attr('title')+"</div>";
		});
		secondoutput += "</div>";
		}	
		
	}		
	else {
		$("#firststep").append("<input type='checkbox' name='groupchoice' title='"+currentTitle+"' value='checkbox' id='groupchoice_"+count+"' />"+currentTitle+"<br />");
		if($(this).children().attr('class') === 'subgroup') {
			secondoutput +="<div class='draggable' title='"+$(this).attr('title')+"'>"+$(this).attr('title')+"</div>";
		}
		else {
			secondoutput +="<div class='draggable' title='"+$(this).attr('title')+"'>"+$(this).attr('title')+"</div>";
		}
	}
	previousParent = currentParent;
	count++;
});
$("#secondstep").html(secondoutput);
$('input:checkbox').change(function ()
{	
	var elem = $("#secondstep div[id='"+$(this).attr('title')+"']");
	if (elem.is (".category")) {
		if ($(this).is(":checked")) {
			$("#secondstep div[title='"+$(this).attr('title')+"']").show();
			$("#secondstep div[title='"+$(this).attr('title')+"']").children().show();
		}
		else {
			$("#secondstep div[title='"+$(this).attr('title')+"']").hide();
			$("#secondstep div[title='"+$(this).attr('title')+"']").children().hide();
		}
	}
	else {
		if ($(this).is(":checked")) {
			$("#secondstep div[title='"+$(this).attr('title')+"']").show();
		}
		else {
			$("#secondstep div[title='"+$(this).attr('title')+"']").hide();
		}
	}
		
});

$("#draggedpoints").change(function() {
	var subpoints = $("#draggedsubpoints");
	subpoints.empty().append("<option value='#'>Please select...</option>").hide();
	$("#points").empty();
	if($("div[title='"+$("#draggedpoints").attr('title')+"'] "+"div[title='"+$("#draggedpoints").val()+"']").hasClass('subgroup')) {
		$("div[title='"+$("#draggedpoints").attr('title')+"'] "+"div[title='"+$("#draggedpoints").val()+"']").children().each(function(){
			subpoints.append("<option value='"+$(this).attr('title')+"'>"+$(this).text()+"</option>");
			subpoints.show();																													   
		});
	}
	else {
		$("#points").html($(this).val()+" points!");	
	}
});
$("#draggedsubpoints").change(function() {
	$("#points").html($(this).val()+" points!");							
});

$(".draggable" ).draggable({
		helper: 'clone'							
});

$( ".droppable" ).droppable({
		drop: handleDropEvent 
});
function handleDropEvent( event, ui ) {   
	var draggable = ui.draggable;  
	$("#droppedHeader").html(draggable.text());
	$("#points").empty();
	var selectlist = $("#draggedpoints");
	var selectsublist = $("#draggedsubpoints");
	selectlist.empty();
	selectsublist.empty().hide();
	selectlist.append("<option value=>Please select...</option>");
	
	selectlist.attr('title',draggable.text());
	var parentdiv = $("div[title='"+draggable.text()+"']").parent().attr('id');
	if(parentdiv != 'secondstep') {	
			$("div[title='" + parentdiv+"'] div[title='"+draggable.text()+"']").children().each(function() {
					
			if($(this).hasClass('subgroup')) {
				$(this).each(function(){
				selectlist.append("<option value='"+$(this).attr('title')+"'>"+$(this).attr('title')+"</option>");
			});
		}
		else {
			$(this).each(function(){
			selectlist.append("<option value='"+$(this).attr('title')+"'>"+$(this).text()+"</option>");
		});
	}
});
}
	else {
	$("div[title='"+draggable.text()+"']").children().each (function() { 
	selectlist.append("<option value='"+$(this).attr('title')+"'>"+$(this).text()+"</option>");
	});	
	}
		
	$("#draggedpoints").show();
	} 	
}


// OLD STYLE SWITCHER - USED ON SOME OLD PAGES - NOT working in safari or some versions firefox


	function switchStylestyle(styleName)
	{
		$('link[rel*=style][title]').each(function(i) 
		{
			this.disabled = true;
			if (this.getAttribute('title') == styleName) this.disabled = false;
		});
		createCookie('style', styleName, 365);
	}
	
// NEW TEXT STYLE SWITCHER - Glenns well hacked version... dynamic version replace default
	
//restore styles from cookies
 var strColSch = readCookie("colourScheme");
 if (strColSch !== null) {
    $('.theme').attr('href', 'http://www.leedsmet.ac.uk/assets/' + strColSch + '.css');
    $('body').attr('id', strColSch);
}
function styleswitcheroo () {

   $('#access span').each(function() {
      $(this).click(function() {
         var chosenColour = $(this).attr('class');
         $('body').attr('id', chosenColour);
         createCookie("colourScheme", chosenColour, 180);
         chosenColour = 'http://www.leedsmet.ac.uk/assets/' + chosenColour + '.css';
         $('.theme').attr('href', chosenColour);
      });
   });
};	
	

// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name,"",-1);
}
// /cookie functions


// Duncan amends

function carousel_lalm(divid) {
$(divid+' li').each(function() {
count = $(this).index()+1;
$('.jcarousel-control').append("<a href='#'>"+count+"</a>");                                                                                   
});
$(divid).jcarousel({initCallback: carousel_initCallback_lalm });
}

function carousel_initCallback_lalm(carousel) {
jQuery('.jcarousel-control a').bind('click',function() {
carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
return false;
           });
}
