$(document).ready(function(){
	
	// Loop through the widgets and hide them
	$('div.hs_widget').each(function(){ 
		// If the widget is a Gallery then hide it by positioning it off-screen
		// this is because slideshow.js cannot determine the dimensions (w, h) of elements that are hidden with display:none
		if ($(this).hasClass('hs_gallery')) {
			$(this).addClass('hs_offscreen');
		} else {
			$(this).addClass('hideContent');
		}
	});
	
	// Show the triggers
	$('.hs_trigger').show();
	
 	// Loop through all of the links which trigger a widget to appear
	$('A[rel="hs_trigger"]').each(function(i) {

		// Use the in-built loop counter variable (i) to locate the trigger's matching widget
		var $widget = $("div.hs_widget").eq(i);

		// Use the jQuery toggle method
		$(this).toggle( 
			function (){ 
				// Bring the gallery widget back on to the screen
				// but we still add hideContent to retain the transition effect
				if ($widget.hasClass('hs_offscreen')) {
					$widget.removeClass('hs_offscreen');
					$widget.addClass('hideContent');
				}
				// Reveal the widget with horizontal Blind effect
				if ($(this).hasClass('hs_horiz')) {
					$widget.show("blind", { direction: "horizontal" }, 500);
				// Reveal the widget with vertical Blind effect
				} else if ($(this).hasClass('hs_vert')) {
					$widget.show("blind", { direction: "vertical" }, 500);
				// A default backup transition
				} else {
					$widget.slideDown();
				}
				// Change the direction of the arrow next to the trigger link
				$(this).removeClass('closed');
				$(this).addClass('open');
				
				// Change the label of the trigger
				newLabel = changeLabel($(this).text(), 'Hide');
				if($(this).hasClass('nolabel')) {
					// do nothing
				} else {
					$(this).text(newLabel);
				}
			}, 
			function (){ 
				// Close the widget with horizontal Blind effect
				if($(this).hasClass('hs_horiz')) {
					$widget.hide("blind", { direction: "horizontal" }, 500);
				// Close the widget with vertical Blind effect
				} else if($(this).hasClass('hs_vert')) {
					$widget.hide("blind", { direction: "vertical" }, 500);
				// A default backup transition
				} else {
					$widget.slideUp();
				}
				// Change the direction of the arrow next to the trigger link
				$(this).removeClass('open');
				$(this).addClass('closed');

				// Change the label of the trigger
				newLabel = changeLabel($(this).text(), 'Show');
				if($(this).hasClass('nolabel')) {
					// do nothing
				} else {
					$(this).text(newLabel);
				}
			} 
		); 
	});
	
	// Takes two strings, strips 'Hide' or 'Show' off and returns the modified string with the new prefix at the front
	function changeLabel(text, prefix) {
		var $label = text;
		len = $label.length;
		$label = $label.substring(5, len);
		$label = prefix + ' ' + $label;
		return $label;
		console.log($label);
	}
});
