/* Checks whether we have cookies enabled by
 * setting and reading a temporary cookie.
 * Returns true or false.
 */
function cookiesEnabled() {
	// First find a cookie name that's not in use
	var basename = 'tmp', counter = -1, name, cookie;
	do {
	  name = basename+((++counter)?counter:'');
	  cookie = new Cookie(document, name);
	} while(cookie.load());
	// Then store some data in it
	cookie.testdata = 1;
	cookie.store();
	// Finally try to read the data back again
	cookie = new Cookie(document, name);
	if(cookie.load() && cookie.testdata) {
	  // we have cookies enabled
	  // - delete the temporary cookie
	  cookie.remove();
	  return true;
	}  // else cookies are not enabled, so there's no point deleting the
	   // temporary cookie since it was never set in the first place
	return false;
}



/* Gets an identifier corresponding to the site we're curerently on.
 * Returns 'g', 'i' or 'j'.
 */
function getSite() {
  var sites = {
    'Guernsey':    ['g', 'guernsey' ],
    'Isle of Man': ['i', 'isleofman'],
    'Jersey':      ['j', 'jersey'   ]
  };

  var siteNameStart = document.title.indexOf(',');
  if(siteNameStart==-1) return undefined;
  siteNameStart += 2;

  var siteNameEnd = document.title.indexOf(':');
  if(siteNameEnd==-1) return undefined;

  return sites[document.title.substring(siteNameStart, siteNameEnd)];
}



$(document).ready(function(){
	// List of top-level pages from each island's site
	var pages = [
	  {g:305, i:303 ,j:304},
	  {g:307, i:296 ,j:306},
	  {g:309, i:298 ,j:308},
	  {g:311, i:300 ,j:310}
	];
	pages.get = function(src, id) {
	  for(var i=0, j=this.length; i<j; i++) {
	    if(this[i][src]==id) return this[i];
	  }
	  return undefined;
	};
	
	
	// Check whether we have cookies enabled
	if(cookiesEnabled()) {
	  // Check whether the cookie we're interested in is set
	  cookie = new Cookie(document, 'locn');
	  if(!cookie.load()) {
	    // it's not set - check with the user that
	    // this is the site they want to be on
	    var site = getSite();
	    var pageId = parseInt(window.location.href.substring(
	                            window.location.href.indexOf('-')+1
	                          ));
	    var ids = pages.get(site[0], pageId);
	    if(ids) {
	      var url = 'http://www.sureskate.com/?guernsey='
	                +encodeURIComponent('http://www.sureskate.com/ice/page-'+ids.g)
	                +'&jersey='
	                +encodeURIComponent('http://www.sureskate.com/ice/page-'+ids.j)
	                +'&isleofman='
	                +encodeURIComponent('http://www.sureskate.com/ice/page-'+ids.i);
	    } else {
	      var url = 'http://www.sureskate.com/?'+site[1]+'='
	                +encodeURIComponent('http://www.sureskate.com/ice/page-'+pageId);
	    }
	    window.location = url;
	  }
	}
});

