/// COOKIE JS ///

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);
}

/// TOGGLE JS ///


function toggleElementUsingCookie( myDivId , toggle) {

	var elem ;
	var cookieName = 'hide'+myDivId ;

	if (document.getElementById) // this is the way the standards work
		elem = document.getElementById( myDivId ) ;
	else if (document.all) // this is the way old msie versions work
		elem = document.all[myDivId] ;
	else if (document.layers) // this is the way nn4 works
		elem = document.layers[myDivId] ;

  	if (elem.style.display =='' && elem.offsetWidth!=undefined && elem.offsetHeight!=undefined) {
    	elem.style.display= (elem.offsetWidth!=0 && elem.offsetHeight!=0)?'block':'none';
    }

	//if the display is currently block and we want to toggle set cookie to true
	if (elem.style.display == 'block' && toggle == true) {
		createCookie(cookieName, 'true', 5) ;
	} else if (elem.style.display == 'none' && toggle == true) {
		createCookie(cookieName, 'false', 5) ;
	}

	if (readCookie(cookieName) == 'true') {
		elem.style.display = 'none' ;
	} else {
		elem.style.display = 'block' ;
	}

}


////////////////////// THE CYCLE OBJECT CLASS //////////////////////
// This is essentially a class which cycles through the div ids passed
// to it on creation
function CycleObject(ids, transType) {

  // Methods
  this.setVisible = function(index) {

    switch(this.transType) {

      case 'normal':
        $(this.ids[this.currentlyVisible]).hide();
        $(this.ids[index]).show();
        this.currentlyVisible = index;
        break;

      case 'fade':
        new Effect.Fade(
          this.ids[this.currentlyVisible],
      		{
      			from: 1.0,
      			to: 0.0,
      			duration: 0.3,
      			queue: 'end'
      		}
      	);

      	new Effect.Appear(
          this.ids[index],
      		{
      			from: 0.0,
      			to: 1.0,
      			duration: 0.3,
      			queue: 'end'
      		}
      	);
        this.currentlyVisible = index;
        break;
    }
  }

  this.nextItem = function() {
    // If we're at the end of the list...
    if( this.currentlyVisible == this.ids.length - 1 ) {
      return false;
    } else {
      this.setVisible(this.currentlyVisible + 1);
      return true;
    }
  }

  this.prevItem = function() {
    // If we're at the beginning of the list...
    if( this.currentlyVisible == 0 ) {
      ;// do nothing
    } else {
      this.setVisible(this.currentlyVisible - 1);
    }
  }

  this.startCycle = function() {
    this.cycleObject = new PeriodicalExecuter(
      this.onUpdateCycle.bind(this), 5 // this is the number of seconds between each interval
    );
  }

  this.stopCycle = function() {
    this.cycleObject.stop();
    this.cycleObject = null;
  }

  this.toggleCycle = function() {
    if (this.cycleObject == null) {
      this.startCycle();
    } else {
      this.stopCycle();
    }
  }

  this.onUpdateCycle = function (pe) {
    if (this.nextItem() == false) {
      this.setVisible(0);
    }
  }

  // Properties

  // An array of ids over which the object will cycle
  // First check that the id exists, if not, discard it
  this.ids = [];
  for(i = 0; i < ids.length; i++) {
    if($(ids[i]) != null) {
      this.ids.push(ids[i]);
    }
  }

  // Transition is 'fade' by default
  this.transType = typeof(transType) != 'undefined' ? transType : 'fade';

  // The index (of the array ids) of the currently visible div
  this.currentlyVisible = 0;

  // Initialisation
  this.cycleObject = null;
  // Set the first one as visible and all the others as not
  $(this.ids[0]).show();
  for(i = 1; i < this.ids.length; i++){
    $(this.ids[i]).hide();
  }

}

/////////// END OF CYCLEOBJECT CLASS //////////////////

function selectTabWithImage (elementID, imageName) {
  $(elementID).getElementsBySelector('a')[0].setStyle({background:'url("/images/'+imageName+'") left center no-repeat #666',
                                                       color:'#fff'});
  return $(elementID);
}

function selectTab (elementID) {
  $(elementID).getElementsBySelector('a')[0].setStyle( { 'background-color':'#666', color:'#fff' } );
  return $(elementID);
}


function setRememberedNavTab() {
  // Get the first subdir from the url
  var urlPath = window.location.pathname.replace(/[^\/]*$/, "");

  element = null;
  // alert(urlPath) ;
  // First select the tab
  if(urlPath == '/'){
      element = selectTab('nav1');
  } else if(urlPath.match(/^\/coffeehouse/)){
      element = selectTabWithImage('nav2','coffee_on.png');
  } else if(urlPath.match(/^\/the-magazine\/$/)){
      element = selectTabWithImage('nav3','mag_on.png');
  } else if(urlPath.match(/^\/(clivedavis)|(melaniephillips)|(stephenpollard)/)){
      element = selectTab('nav4');
  } else if(urlPath.match(/\/blogs/)){
      element = selectTab('nav4');
  } else if(urlPath.match(/\/politics/)){
      element = selectTab('nav5');
  } else if(urlPath.match(/\/the-magazine\/books/)){
      element = selectTab('nav6');
  } else if(urlPath.match(/\/archive/)){
      element = selectTab('nav7');
  } else if(urlPath.match(/\/life/)){
      element = selectTab('nav8');
  } else if(urlPath.match(/\/style-and-travel/)){
      element = selectTab('nav9');
  } else if(urlPath.match(/\/classifieds/)){
      element = selectTab('nav10');
  } else if(urlPath.match(/\/live/)){
      element = selectTab('nav11');

  } else if(urlPath == '/business/') {
  	  element = selectTab('bnav1') ;
  } else if(urlPath.match(/^\/business\/trading-floor/)){
  	element = selectTab('bnav2') ;
  } else if (urlPath.match(/^\/business\/the-magazine/)) {
  	element = selectTab('bnav3') ;
  } else if(urlPath.match(/^\/business\/breaking-news/)){
  	element = selectTab('bnav4') ;
  }

  // If we're in an article page...
  if (urlPath.match(/\/\d+\/.*/) && !urlPath.match(/\/archive\/.*/) ) {
    removeLink = false;
  // ...or an individual blog listing ...
  } else if(urlPath.match(/\/(clivedavis)|(melaniephillips)|(stephenpollard)/)) {
    removeLink = false;
  // ...or archive ...
  } else if(urlPath.match(/\/archive/)) {
    removeLink = false;
  // ...or classifieds subsection ...
  } else if(urlPath.match(/\/classifieds\/.+/)) {
    removeLink = false;
  } else {
    removeLink = true;
  }

  if(element != null && removeLink) {
    element.getElementsBySelector('a')[0].removeAttribute('href');
  }

}

function setSelected (id,requestedValue) {

  selectList = $(id);

  if(selectList != null && selectList.options){
    for( i in selectList.options){
      if(selectList.options[i].value == requestedValue){
        selectList.selectedIndex = i;
      }
    }
  }
}


this.blankwin = function(){
	var hostname = window.location.hostname;
	hostname = hostname.replace("www.","").toLowerCase();
	var a = document.getElementsByTagName("a");

	this.check = function(obj){
		var href = obj.href.toLowerCase();
		if ( href.indexOf("http://") != -1 &&
			 href.indexOf("spectator.co.uk") == -1 &&
			 href.indexOf(hostname)==-1 )
			 return true ;
		else
			return false;
	};
	this.set = function(obj){
		obj.target = "_blank";
		obj.className = "external";
	};

	this.remember = function(obj, ida) {
		pattern = /\/[0-9]+\// ;
		matches = obj.href.toLowerCase().match(pattern) ;
		if (matches != null)
			ida.push(matches[0].replace('/', '')) ;
	} ;
	var ida = new Array() ;

	for (var i=0;i<a.length;i++){
		if (check(a[i])) {
			set(a[i]);
		} else {
			remember(a[i], ida) ;
		}
	};

	var idb = [], i, len = ida.length;
    for(i=0; i<len; i++ ) {
        if( idb.indexOf( ida[i]) < 0 ) {
            idb.push(ida[i]);
        }
    }

/*
	alert('SHB says ' + window.location.href  + "=" + idb.join('') + ":" +
			readCookie('Spectator-User') + "+" +
			readCookie('Spectator-Session')) ;
*/
};


// script initiates on page load.

this.addEvent = function(obj,type,fn){
	if(obj.attachEvent){
		obj['e'+type+fn] = fn;
		obj[type+fn] = function(){obj['e'+type+fn](window.event );}
		obj.attachEvent('on'+type, obj[type+fn]);
	} else {
		obj.addEventListener(type,fn,false);
	};
};

addEvent(window,"load",blankwin);


// Toggle between two classes

// Use html in this way:
// <a onclick="changeClass(this,'class2','class1');" class="class1">Some Message</a>

function changeClass(elem, className1,className2) {
	elem.className = (elem.className == className1)?className2:className1;
}

