function getMainAreaContent(html) {
  var startAfter = '<div id="main-long">';
  var endBefore = '</div><!-- end main -->';
	var start = html.indexOf(startAfter);
	if(start==-1) end = html.length; else start += startAfter.length;
	var end = html.indexOf(endBefore);
	if(end==-1) end = html.length;
	return html.substring(start, end);
}

function addPages(carousel, elms, index) {
  if(arguments.length<3) var index = 0;
	$.get('http://www.surecw.com/guernsey/page-'
	      +elms[index].href.substring(elms[index].href.indexOf('#')+1),
	      function(data) {
		index++;
		carousel.add(index, getMainAreaContent(data));
		if(index<elms.length) {
		  addPages(carousel, elms, index);
		} else {
      carousel.size(elms.length);
		}
	});
}

previousHash = location.hash;
function checkForHashChange() {
  if(location.hash!=previousHash) {
    var index = 0;
	  if(location.hash.length) {
	    var elms = $('.jcarousel-control a').get();
	    for(var i=0, j=elms.length; i<j; i++) {
	      if(elms[i].href.substring(elms[i].href.indexOf('#'))==location.hash) {
	        index = i+1;
	        break;
	      }
	    }
	  }
	  theCarousel.scroll(index);
	}
  previousHash = location.hash;
  window.setTimeout('checkForHashChange()', 200);
}

theCarousel = undefined;
$(document).ready(function() {
  if(!($.browser.msie && $.browser.version==6)) {
		var elms = $('.jcarousel-control a').get();
		for(var i=0, j=elms.length; i<j; i++) {
		  elms[i].href = '#'+elms[i].href.substring(elms[i].href.lastIndexOf('-')+1);
		};
	  var start = 1;
	  if(location.hash.length) {
	    var elms = $('.jcarousel-control a').get();
	    for(var i=0, j=elms.length; i<j; i++) {
	      if(elms[i].href.substring(elms[i].href.lastIndexOf('#')+1)
	         ==location.hash.substring(1)) {
	        start = i+1;
	        break;
	      }
	    }
	  }
	  $('#mycarousel').jcarousel({
	    scroll: 1,
	    visible: 1,
	    easing: 'swing',
	    wrap: 'both',
	    start: start,
	    initCallback: function(carousel) {
		    $('.jcarousel-control a').bind('click', function() {
	        carousel.scroll($.jcarousel.intval(this.parentNode.className));
	        return false;
		    });
		    $('.jcarousel-container').prepend('<div id="jcarousel-prev-fade"></div>'
	                                        +'<div id="jcarousel-next-fade"></div>');
	      theCarousel = carousel;
	      window.setTimeout('checkForHashChange()', 200);
	    },
	    itemLoadCallback: function(carousel, state) {
	      if(state!='init') return;
	      var elms = $('.jcarousel-control a').get();
	      addPages(carousel, elms);
	    },
	    itemFirstInCallback: {
	      onBeforeAnimation: function(carousel, elm, index, state) {
	        $('.jcarousel-control li.selected').removeClass('selected');
	        $('.jcarousel-control li.'+index).addClass('selected');
	        location.hash = $('.jcarousel-control li.selected a').attr('href');
	      }
	    }
	  });
	}
});

