var navigationTimer = $.timer();
var headingWidth = 590;
var loadingCount = 0;

$.widget( "custom.catcomplete", $.ui.autocomplete, {
	_renderMenu: function( ul, items ) {
		var self = this,
			currentCategory = "";
		$.each( items, function( index, item ) {
			/*if ( item.category != currentCategory ) {
				ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
				currentCategory = item.category;
			}*/
			
			self._renderItem( ul, item );
		});
	},
	_renderItem : function( ul, item ) {
		var li = $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( "<a>" + item.label+"</a>" )
			.appendTo( ul );
		if(item.subGroupCode) {
			//log("getting product details for: "+item.subGroupCode);
			getProductDetails(item.subGroupCode,item.catalogueIndex,updateSearchSubCategoryItem,li);	
		}else {
			//log(item.label);
		}
		return li;
	}
});

/**
 * Update an autocomplete result to show more information on this subcategory item
 * @param results
 * @param li
 */
function updateSearchSubCategoryItem(results,li) {
	if(results.categoryIndex == 1) {
		//log("FOR SALE");
	}
	var aTag = li.find('a');
	var div = $('<div class="ui-autocomplete-subcategory"></div>');
	aTag.empty();
	
	if(results.hasImage == "true") {
		// add an image
		div.append($('<img src="'+results.imageLocation+'/50x50/'+results.subGroupCode+'.jpg" width="50" height="50" />'));
	}else {
		div.append($('<img src="'+results.imageLocation+'/50x50/npa.png" width="50" height="50" />'));		
	}
	div.append($('<strong>'+$('<div></div>').html(results.name).text()+'</strong>'));
	div.append($('<em></em>').html(results.foundUnder));
	/*
	if(results.hasSpecs == true) {
		var specs = results.technicalSpecs.technicalSpec;
		var specification = $('<ul></ul>');
		if(specs.length == undefined) {
			var tempSpecs = specs;
			specs = [];
			specs[0] = tempSpecs;
		}
		for(var i=0; i < specs.length; i++) {
			var specName = specs[i].name;
			var specValue = new String(specs[i].value);
			var specValues = specValue.split('*');
					  
			var spec = $('<li>'+specName+' - </li>');
			for(var a=0; a < specValues.length; a++) {
				spec.append(specValues[a]);
				if(a < specValues.length-1) spec.append(', ');
			}
			specification.append(spec);
		}
		div.append(specification);
	}*/
	
	aTag.append(div);
	
	//log(results);
}

$.fn.equalHeights = function(px) {
	// work out what the tallest is
	var currentTallest = 0;
	$(this).each(function(){
		var objValue = $(this);
		if (objValue.height() > currentTallest) { currentTallest = objValue.height(); }
		//if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
		// for ie6, set height since min-height isn't supported
	});

	// set them all to the height of the tallest
	$(this).each(function(){
		var objValue = $(this);
		objValue.height(currentTallest);
	});
	return this;
};


/**
* Have this element stay in its position as the
* page is scrolling
**/
$.fn.followScroll = function() {
	var el = $(this);
	if(el.length > 0) {
		var elpos_original = el.offset().top;
		var elHeight = el.innerHeight();
		//log(elHeight);
		$(window).scroll(function(){
			elHeight = el.height();
			//log(elHeight);
			var elpos = el.offset().top;
			var windowpos = $(window).scrollTop();
			var difference = windowpos - elpos_original;
			var max = el.parents('div').height() - elHeight;
			
			//log("difference: "+difference+" ; max: "+max);
			// add some padding
			//difference += 5;
			
			if(windowpos > elpos_original) {
				if(difference < max) {
					el.css('position','absolute').stop().animate({'top': difference+'px'});
				}
			}else {
				el.stop().css('top','');
			}
		});
		
		$('.container',el.parents('div')).equalHeights();
	}
}

$(document).ready(function() {
	
	navigationTimer.set({
         action : navigationTick,
         time : 1
 	});
	
	//$('div.followScroll').followScroll();
	
	var belowIE8Test = ($.browser.msie && $.browser.version < 8);
	if ( belowIE8Test == undefined || belowIE8Test == false) {
	$('a[data-role="expandMenu"]').each(function() {
		var expandMenuLink = $(this);
		var expandedMenu = $('[data-role="expandedMenu"]',expandMenuLink.parent());
		var array = $([expandMenuLink,expandedMenu]);
		
		array.each(function() {
			$(this)
			.bind('mouseover', function() {
				//log("MOUSE OVER");
				expandedMenu.show();
				expandMenuLink.addClass('hoveredLink');
			})
			.bind('mouseleave', function() {
				expandedMenu.hide();
				expandMenuLink.removeClass('hoveredLink');
			});
		});
	});
	}
	
	/*
	$('a[data-role="expandMenu"], #subNavigation').bind('mouseover', function() {
		$('#subNavigation').show();
		$('#hireCatalogueLink').addClass('hoveredLink');
	});
	$('#hireCatalogueLink, #subNavigation').bind('mouseleave', function() {
		$('#subNavigation').hide();
		$('#hireCatalogueLink').removeClass('hoveredLink');
		//log("mouseout: subNavigation");
	});*/
		
	
	/*$('#subNavigation a[data-expand]').bind('mouseover', function() {
		changeNavigationItem($(this));	
	});
	*/
	
	$('span[data-linkedTo]').live('click', function() {
		pauseNav();
		moveHeadingTo($(this).attr('data-linkedTo'));
	});
	
	$('.tablesorter').tablesorter({widgets: ['zebra']}).each(function() {
		
		pager = $('<div id="pager_'+new Date().getTime()+'" class="tablesorterPager"><form><img src="/images/icons/control_start.png" class="first"/><img src="/images/icons/control_rewind.png" class="prev"/><input type="text" class="pagedisplay"/><img src="/images/icons/control_fastforward.png" class="next"/><img src="/images/icons/control_end.png" class="last"/><br /><label>Results Per Page</label><select class="pagesize"><option selected="selected"  value="10">10</option><option value="20">20</option><option value="30">30</option><option  value="40">40</option></select></form></div>');
		pager.insertAfter($(this));
		
		$(this).tablesorterPager({container: pager,positionFixed:false}); 
	});
	
	$(window).focus(function() {
    	navigationTimer.play();
	});

    $(window).blur(function() {
    	navigationTimer.pause();
    });
    

	$('a > img[alt], [data-bubbleAlt], [data-bubbleID]').live('mouseover',function() {
		//log("Caught mouseover event for a bubble display");
		var t = $(this);
		$('a img[alt], [data-bubbleAlt], [data-bubbleID]').HideAllBubblePopups();
		$('.jquerybubblepopup').remove();
		if(!t.HasBubblePopup()) {
			//log("Doesnt have bubble - creating it");
			var pos = 'top';
			var html = "";
			
			if(t.attr('data-bubblePosition')) pos = t.attr('data-bubblePosition');
			if(t.attr('data-bubbleID')) {
				html = $('#'+t.attr('data-bubbleID')).html();
			}else {
				html = t.attr('alt');
			}
			t.CreateBubblePopup({
	
				position : pos,
				align	 : 'center',
				themeMargins: {
					total: '5px',
					difference: '0px'
				},
				innerHtml: html,
				innerHtmlStyle: {
									color:'#000', 
									'text-align':'center'
								},
				themeName: 	'black',
				themePath: 	'/images/jquerybubblepopup-theme',
				openingDelay: 500
			});
		}else {
			// make sure its up to date
			if(t.attr('data-bubbleID')) {
				html = $('#'+t.attr('data-bubbleID')).html();
			}else {
				html = t.attr('alt');
			}
			t.SetBubblePopupInnerHtml(html,true);
		}
	});

	$('a img[alt], [data-bubbleAlt], [data-bubbleID]').live('mouseout',function() {
		$(this).HideBubblePopup();
	});
	
	changeNavigationItem($('#subNavigation li:first-child a[data-expand]'));
	if($('.scrollingWrapper section[data-active="true"]').length == 0) {
		var first = $('.scrollingWrapper section:first');
		first.attr('data-active',true);
		moveHeadingTo(first.attr('id'));
	}else {
		// make sure the active is actually selected
		var active = $('.scrollingWrapper section[data-active="true"]').removeAttr('data-active');
		var first = $('.scrollingWrapper section:first');
		first.attr('data-active',true);
		moveHeadingTo(active.attr('id'));
	}

	if($('#headerContainer').data('paused') == true) {
		playNav();
		pauseNav();
	}else {
		playNav();
	}

	$( "#query" ).catcomplete({
		source: "/webservice/search.php",
		minLength: 2,
		select: function( event, ui ) {
			window.location.href = ui.item.value;
		},
		search: function(event, ui) {
			$(this).addClass('searching');
		},
		open: function (event, ui) {
			$(this).removeClass('searching');
		},
		close: function (event, ui) {
			$(this).removeClass('searching');
		}
	});


	navigationTimer.play();
	
	if($('#depotLocator').length > 0) {
		// include the google maps API
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = "http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false&callback=setUpDepotMap";
		document.body.appendChild(script);
	}
	
	changeSizeOfTiles();
});



/**
 * Modifys the size of the tiles on the home page so
 * they are the same height
 */
function changeSizeOfTiles() {
	var count = 0;
	var tilesInRow = [];
	
	$('#body > div > section.tile').each(function() {
		var t = $(this);
		t.css('height','');

		// fix any images in this tile
		var images = $("img",t);
		var totalImages = images.length;
		var imageCount = 1;
		
		images.each(function() {
			var img = $(this);
			//if(img.width() == 0 || img.height() == 0) {
				img.load(function() {
					if(this.clientWidth > 0 && this.clientHeight > 0) {
						img.attr('width',this.clientWidth);
						img.attr('height',this.clientHeight);
					}
					
					if(imageCount++ == totalImages) {
						changeSizeOfTiles();
					}
				});
			//}
		});
		
		count += sizeOfTileAsNumber(t);
		if(count > 4) { 
			count = 0;
		}
		
		if(count == 0) {
			// start from a clean slate
			if(tilesInRow.length >= 1) {
				// the tiles in the previous row are still here, make them all the same size
				$(tilesInRow).equalHeights();
			}
			count = sizeOfTileAsNumber(t);
			tilesInRow = [];
		}
		
		// continuing on one row
		tilesInRow[tilesInRow.length] = t;
	});
	
	// get the last one
	if(tilesInRow.length >= 1) {
		// the tiles in the previous row are still here, make them all the same size
		$(tilesInRow).equalHeights();
	}
}

/**
 * Gets the size of a tile as a number
 */
function sizeOfTileAsNumber(tile) {
	var string = "";
	
	var sizes = ["one","two","three","four"];
	
	for(i in sizes) {
		if(tile.hasClass(sizes[i])) {
			string = sizes[i];
		}
	}
	
	switch(string) {
	case "one":
		return 1;
	break;
	case "two":
		return 2;
	break;
	case "three":
		return 3;
		break;
	case "four":
		return 4;
		break;
	default:
		return null;
		break;
	}
}

/**
 * Sets up a map with all the depot locations on it
 */
function setUpDepotMap() {
	
	// get the canvas for the map
	var mapCanvas = $('#depotLocator .mapCanvas');
	mapCanvas.attr('id','DepotMapCanvas');
	
	// clear the canvas to remove the current static image of the map
	mapCanvas.empty();

	// set up the map itself
	var myLatlng = new google.maps.LatLng(55.989991,-3.525423);
	var myOptions = {
		zoom: 6,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: false,
		streetViewControl: false
	}
	var map = new google.maps.Map(document.getElementById('DepotMapCanvas'), myOptions);
	var geocoder = new google.maps.Geocoder();
	
	// now, populate it with depot information
	$.ajax({
		  url: "/webservice/depotLocator.php",
		  data: { 'request': 'retrieve', 'response' : 'json' },
		  success: function(response){
			  //log(response);
			  // add each depot to the map

			  var image = new google.maps.MarkerImage('/images/layout/JP Logo-20x20.png',
			      // This marker is 20 pixels wide by 32 pixels tall.
			      new google.maps.Size(20, 20),
			      // The origin for this image is 0,0.
			      new google.maps.Point(0,0),
			      // The anchor for this image is the base of the flagpole at 0,32.
			      new google.maps.Point(0, 20));
			  
			  if(parseInt(response.resultCount) > 0) {
				for(var i=0; i < response.results.depot.length; i++) {
					var depot = response.results.depot[i];
					var title = depot.Name;
					if(depot.DepotTypeDescription1.Length > 0) {
						title += "("+depot.DepotTypeDescription1+")";
					}
					var address = depot.Addr1+','+depot.Addr2+','+depot.Addr3+','+depot.Addr4+','+depot.Postcode+',UK';

					addMarker(map, geocoder, title, address, "/depot/"+depot.Name.toLowerCase()+"/", image);
				}  
			  }
		  }
		});
	

	  
	  // set up autocomplete
	  var defaultBounds = new google.maps.LatLngBounds(
			  new google.maps.LatLng(49.2487, -7.8085),
			  new google.maps.LatLng(59.4190,  2.9581));
	  var input = document.getElementById('location');
	  var options = {
	    bounds: defaultBounds,
	    types: ['geocode']
	  };
	
	  var autocomplete = new google.maps.places.Autocomplete(input,options);
	  autocomplete.bindTo('bounds', map);
}

function addMarker(map, geocoder, name, address, link, image) {
	// get the lat, lng for this depot
	
	geocoder.geocode( { 'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			// TODO: Get proper depot.NAME
			var marker = new google.maps.Marker({
				map: map, 
				position: results[0].geometry.location,
			    animation: google.maps.Animation.DROP,
			    title: name,
			    icon: image
			});
			
			/*var infowindow = new google.maps.InfoWindow({
			    content: '<div style="width: 100px;">'+depot.Name+'</div>',
			    maxWidth: 150
			});*/
			
			google.maps.event.addListener(marker, 'click', function() {
				  window.location = link;
			});
		} else {
			// silently die
			//alert("Geocode was not successful for the following reason: " + status);
		}
	});
}

function navigationTick() {
	var progress = $('#headerContainer progress');
	if($('#headerContainer').data('paused') == true) {
		// its paused, so make sure its set to 0
		progress.attr('value',0);
	}else {
		// lets try and progress a bit
		var nextStep = parseInt(progress.attr('value')) + 1;
	
		if(nextStep > parseInt(progress.attr('max')) ) {
			nextNav();
			progress.attr('value',0);
		}else {
			progress.attr('value',nextStep);
		}
	}
}

function pauseNav() {
	var header = $('#headerContainer');
	
	$('#headerContainer').data('paused',true);
	
	$('[data-role="pausePlayControl"]').removeClass('sprite-control_pause').addClass('sprite-control_play').unbind("click").click(playNav);
	
	//log("Paused Navigation");
}

function playNav() {
	var header = $('#headerContainer');
	
	if(header.data('startedBy') == "") {
		// this has never been started before
	}
	
	$('#headerContainer').data('paused',false);

	$('[data-role="pausePlayControl"]').removeClass('sprite-control_play').addClass('sprite-control_pause').unbind("click").click(pauseNav);
	
	//$('#headerContainer').data('paused',false);
	//log('Playing navigation');
}

function changeNavigationItem(item,noCheck) {
	var noCheck = typeof(noCheck) != 'undefined' ? noCheck : false;
	var infoDiv = item.next();
	var backgroundPosition = infoDiv.data('background');
	var moreInfo = infoDiv.data('more');

	// add it to the navigation
	$('#subNavigation .active').removeClass('active').addClass('hidden').prev().removeClass('active');

	infoDiv.prev().addClass('active');
	infoDiv.removeClass('hidden').addClass('active').insertAfter(item);

	if(moreInfo && noCheck==false) {
		//moveHeadingTo(moreInfo)
	}

}

function moveHeadingTo(id) {
	//log("Attempting to move to: "+id);
	
	// get current position of more info
	var activeItem = $('.scrollingWrapper section[data-active="true"]');
	var scrollingWrapper = $('.scrollingWrapper');
	
	var position = 0;
	var activePosition = 0;
	var movingToPosition = 0;
	var movingToItem = null;
	var difference = 0;
	
	if(id == activeItem.attr('id')) {
		//log("active");
		$('span[data-linkedTo="'+activeItem.attr('id')+'"]').removeClass('sprite-bullet_black').addClass('sprite-bullet_orange');
	}else {
		// find out what position we want to get to, and what we are currently in
		$('#headerContainer .scrollingWrapper [data-id]').each(function() {
			var t = $(this);
			if(t.attr('data-active') == "true") {
				activePosition = position;
			}
			
			if(t.attr('id') == id) {
				movingToPosition = position;
				movingToItem = t;
			}
			position++;
		});
		
		if(activePosition > movingToPosition) {
			// left
			difference = movingToPosition - activePosition;
			scrollingWrapper.animate({
				left: '-='+(headingWidth * difference)
			});	
		}else {
			// right
			difference = activePosition - movingToPosition;
			scrollingWrapper.animate({
				left: '+='+(headingWidth * difference)
			});	
		}
		activeItem.removeAttr('data-active');
		if(movingToItem != null) {
			movingToItem.attr('data-active','true');
			
			$('span[data-linkedTo="'+activeItem.attr('id')+'"]').removeClass('sprite-bullet_orange').addClass('sprite-bullet_black');
			$('span[data-linkedTo="'+movingToItem.attr('id')+'"]').removeClass('sprite-bullet_black').addClass('sprite-bullet_orange');
			
			var sideLink = $('a[data-expand="'+movingToItem.attr('id').replace("More","Info")+'"]');
			if(sideLink.length > 0) {
				if(sideLink.has('div').length == 0) {
					changeNavigationItem(sideLink,true);
				}
			}
		}else {
			//log("Couldn't find heading: "+id);
		}
	}
}
function IsScrollAtStart() {
	if($('.scrollingWrapper section:first').attr('data-active') == "true") {
		return true;
	}
	return false;
}

function IsScrollAtEnd() {
	if($('.scrollingWrapper section:last').attr('data-active') == "true") {
		return true;
	}
	return false;
}
function scroll(position) {	
	var activeItem = $('.scrollingWrapper section[data-active="true"]');
	var newItem = null;
	var scrollingWrapper = $('.scrollingWrapper');

	$('span[data-linkedTo="'+activeItem.attr('id')+'"]').removeClass('sprite-bullet_orange').addClass('sprite-bullet_black');
	
	switch(position) {
		case "left":
			if(!IsScrollAtStart()) {
				scrollingWrapper.animate({
					left: '+='+headingWidth
				});	
				activeItem.removeAttr('data-active');
				newItem = activeItem.prev();
				newItem.attr('data-active','true');
			}
			break;
		case "right":
			if(!IsScrollAtEnd()) {
				scrollingWrapper.animate({
					left: '-='+headingWidth
				});
				
				activeItem.removeAttr('data-active');
				newItem = activeItem.next();
				newItem.attr('data-active','true');
			}
			break;
	}

	$('span[data-linkedTo="'+newItem.attr('id')+'"]').removeClass('sprite-bullet_black').addClass('sprite-bullet_orange')
	
	var sideLink = $('a[data-expand="'+newItem.attr('id').replace("More","Info")+'"]');
	if(sideLink.length > 0) {
		if(sideLink.has('div').length == 0) {
			//log("changing to "+newItem.attr('id'));
			changeNavigationItem(sideLink,true);
		}
	}
}

/**
 * Decides the next navigation item to display
 */
function nextNav() {
	var headerContainer = $('#headerContainer');
	if(headerContainer.data('paused') == false) {
		if(IsScrollAtEnd()) {
			// reset to start
			moveHeadingTo($('.scrollingWrapper section:first').attr('id'));
		}else {
			// continue through
			scroll("right");
		}
	}
}


/**
 * Returns a javascript object to the callback function provided with the product details of the subCategoryCode provided.
 * Callback function doesn't get called if no product was found
 * @param subCategoryCode
 */
function getProductDetails(subCategoryCode, catalogue, callback, param) {
	$.ajax({
		  url: "/webservice/subcategorys.php",
		  data: { 'request': 'retrieve', 'subCategoryCode' : subCategoryCode, 'catalogue' : catalogue, 'response' : 'json' },
		  success: function(response){
			  if(response.resultCount == 1) {
				  if (callback && typeof(callback) === "function") {
					    // execute the callback, passing parameters as necessary
					  	if(param == null) {
					  		callback(response.results.subcategory);
					  	}else {
					  		callback(response.results.subcategory,param);
					  	}
					}
			  }
		  },
		  error: function(response) {
			  log("Error getting product details for: "+subCategoryCode);
			  log(response);
		  }
		});
}

/**
 * Trys to add a new heading based on the pageID provided.
 * Makes an AJAX call and then alls addNewHeading if a result
 * is found.
 * @param pageIDSearch	Page ID to attempt to add
 */
function tryAddNewHeading(pageIDSearch, failCallback,dontUpdate) {
	log("Attempting to add a new heading for: "+pageIDSearch);
	$.ajax({
  		url: "/webservice/headings.php",
  		data: {request: 'retrieve', pageID: pageIDSearch, response: 'json'},
  		dataType: 'json',
  		success: function(data) {
  			// remove any page specific headings
  			$('#headerContainer .scrollingWrapper section[data-pageSpecific=true]').each(function() { removeHeading($(this).attr('data-id')); });
  			log(data.resultCount);
  			if(data.resultCount > 0) {
  				var headings = [];
  				if(data.resultCount == 1) {
	  				headings[0] = data.results.heading;
  				}else {
	  				headings = data.results.heading;
  				}
				for(i in headings) {
					var h = headings[i];
	  				addNewHeading(h.uniqueID, h.pageID, h.name, h.description, h.image, true, true, h.backgroundPositionHeight);
				}
  				pauseNav();
  			}else {
  				if(failCallback != null && typeof(failCallback) === "function") {
  					failCallback();
  				}
  			}
  		},
  		error: function(data) {
  			log("Error: trying to add new heading for: "+pageIDSearch);
  			log(data);
  		}
  	});	
	
	if(dontUpdate != null || dontUpdate != true) {
		$('#headerContainer').attr('data-activeID',pageIDSearch);
	}
}
/**
 * Sets the background to the specified height
 * @param height
 */
function setBackgroundHeight(section,height) {
	section.css('background-position','0px '+height+'px');
}

/**
 * Get the height of the background height
 */
function getBackgroundHeight(activeSection) {
	var currentPosition = activeSection.css('background-position');
	var currentHeight = currentPosition.split(' ')[1];
	
	if(currentHeight.substr(currentHeight.length-2) == "px") {
		currentHeight = currentHeight.substring(0,currentHeight.length-2);
	}else {
		currentHeight = 0;
	}
	
	return currentHeight;
}


/**
 * Adds a new heading to the page
 * @param id
 * @param name
 * @param description
 * @param background
 * @param activate
 */
function addNewHeading(id, pageID, name, description, background, activate, pageSpecific, backgroundPositionHeight) {
	if($('section[data-id="'+id+'"]').length == 0) {
		
		// it doesn't already exist, so lets add it!
		var section = innerShiv('<section id="'+id+'More"></section>',false);
		$('#headerContainer .scrollingWrapper').append(section);
		section = $('#'+id+'More');
		
		setBackgroundHeight(section,backgroundPositionHeight);
		
		if(description.length == 0) description = '<p></p>';
		//log(section);
		section.attr('data-id',id).attr('data-pageSpecific',pageSpecific).attr('data-pageID',pageID).css('background-image','url('+background+')');
		var div = $('<div></div>');
		var heading = $('<h2></h2>').html($('<div></div>').html(name).text());
		var body = $('<span></span>').html(description);
		
		var bullet = $('<span class="sprite-icons sprite-bullet_black" data-linkedTo="'+id+'More"></span>');
		
		div.append(heading).append(body);
		section.append(div);
		$('#headerContainer .scrollingControls').append(bullet);		
	}
	
	if(activate == true) {
		moveHeadingTo(id+'More');
	}
}

function removeHeading(id) {
	var isActive = false;
	if($('.scrollingWrapper section[data-id="'+id+'"][data-active="true"]').length == 1) {
		// this is the active item
		isActive = true;
	}
	$('#headerContainer .scrollingWrapper section[data-id="'+id+'"]').remove();
	$('span[data-linkedTo='+id+'More]').remove();
	
	if(isActive) {
		$('#headerContainer .scrollingWrapper').css('left','0px');
		var first = $('.scrollingWrapper section:first');
		first.attr('data-active',true);
		moveHeadingTo(first.attr('id'));
	}
	
}

function log(str) {
	if (this.console && typeof console.log != "undefined") {
		//console.log(str);
	}else {
		//alert(str);
	}
}

function nl2br(str) {
	var breakTag = "<br />";
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}

function loading() {
	//alert("Loading");
	var loader = $('#loading');
	if(loader.length == 0) {
		loader = $('<div id="loading" style="position: absolute; height: 100%;top: 0px; width: 100%; background: url(/images/layout/half-opacity.png);"><div class="centre" style="text-align: center;"><img src="/images/layout/ajax-loader_blue.gif"></div></div>');
		$('#body').append(loader);
	}
	
	loader.show();
	
	loadingCount++;
}

function finishedLoading() {
	//alert("Finished loading");
	loadingCount--;
	if(loadingCount < 1) {
	 $('#loading').hide();
	}
}

(function($) {
	  var cache = [];
	  // Arguments are image paths relative to the current page.
	  $.preLoadImages = function(arguments) {
	    var args_len = arguments.length;
	    for (var i = args_len; i--;) {
	      var cacheImage = document.createElement('img');
	      cacheImage.src = arguments[i];
	      cache.push(cacheImage);
	    }
	  }
	})(jQuery)

jQuery.ajaxSetup({
	  beforeSend: loading,
	  complete: finishedLoading
	});

