/// 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':'#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\/$/)){*/
  } 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(/\/archive/)){
      element = selectTab('nav5');
  } else if(urlPath.match(/\/politics/)){
      element = selectTab('nav6');
  } else if(urlPath.match(/\/arts/)){
      element = selectTab('nav7');
  } else if(urlPath.match(/\/life/)){
      element = selectTab('nav8');
  } else if(urlPath.match(/\/classifieds/)){
      element = selectTab('nav9');
  } else if(urlPath.match(/\/live/)){
      element = selectTab('nav10');
  } else if(urlPath.match(/\/events/)){
      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') ;

  // navigation for wine club
    } else if(urlPath == '/wine-club/') {
  	  element = selectTab('wnav1') ;
  } else if(urlPath.match(/\/wine-club\/offer-of-the-month/)){
  	element = selectTab('wnav2') ;
  } else if (urlPath.match(/\/wine-club\/discussion-board/)) {
  	element = selectTab('wnav3') ;
  } else if(urlPath.match(/\/wine-club\/features/)){
  	element = selectTab('wnav4') ;
	
// book club
} else if(urlPath == '/books/') {
  	  element = selectTab('bcnav1') ;
  } else if(urlPath.match(/^\/books\/forums/)){
  	element = selectTab('bcnav2') ;
  } else if (urlPath.match(/^\/books\/registration/)) {
  	element = selectTab('bcnav3') ;
  } else if(urlPath.match(/^\/books\/local-book-shop/)){
  	element = selectTab('bcnav4') ;
  
  
  
  // scoff
} else if(urlPath == '/scoff/') {
  	  element = selectTab('scoffnav1') ;
  } else if(urlPath.match(/^\/scoff\/blog/)){
  	element = selectTab('scoffnav2') ;
  } else if (urlPath.match(/^\/scoff\/registration/)) {
  	element = selectTab('scoffnav3') ;
  }
  
  


  // 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;
}



Event.observe(window, 'load',
  function() {
    toggleContainers();
  }
);

function initToggle() {
	var myDivsToToggle = $$('div.toggle');
	myDivsToToggle.each(
		function(divToToggle) {
			var links = divToToggle.select('a.togglelink' );
			links.each(
				function(link) {
					link.observe('click', toggleContent);
				}
			);
		}
	);
}

function toggleContent(event){

	var togglelink = Event.element(event);

	var ancestors = togglelink.ancestors();
	var divToToggle;

	ancestors.each(
		function(ancestor) {
			if (ancestor.hasClassName('toggle')) {
				divToToggle = ancestor;
			}
		}
	);

	var togglecontent = divToToggle.select('div.togglecontent')[0];
	var footer = divToToggle.select('div.togglebottom')[0];

	if (togglecontent.visible()) {
		rememberState(divToToggle, 'closed');
	} else {
		rememberState(divToToggle, 'open');
	}

	Effect.toggle(
		togglecontent,
		'slide',
		{
			duration: 0.2,
			afterFinish:function(){

				if (footer) {
					footer.toggle();
				}

				if (togglelink.hasClassName('open')) {
					togglelink.removeClassName('open');
					togglelink.addClassName('closed');
				} else {
					togglelink.removeClassName('closed');
					togglelink.addClassName('open');
				}

			}
		}
	);

	return true;

}

function rememberState(divElement, state) {

	var stateObj = new Object();

	var id = $(divElement).id;

	var stateString = readCookie('spectatorstate');

	if (stateString && stateString != '') {
		stateObj=stateString.evalJSON();
	}

	stateObj[id] = state;

	createCookie('spectatorstate', Object.toJSON(stateObj), 365);

}

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+"="+escape(value)+expires+"; path=/";
	// alert('createCookie '+value) ;
}

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) {
			// alert('readCookie '+name+ ' ' + ' cookie = ' + c + ' value = ' + c.substring(nameEQ.length,c.length)) ;
			return unescape(c.substring(nameEQ.length,c.length));
		}
	}
	return null;
}

function toggleContainers() {

	var stateString = readCookie('spectatorstate');
	var stateObj;

	if (stateString && stateString != '') {
		stateObj=stateString.evalJSON();
	}

	var keys = Object.keys(stateObj);

	keys.each(
		function(key) {
			divToToggle = $(key);
			if (divToToggle) {
				togglecontent = divToToggle.select('div.togglecontent')[0];
				togglelink = divToToggle.select('a.togglelink')[0];
				footer = divToToggle.select('div.togglebottom')[0];

				if (stateObj[key] == 'open') {
					if (togglelink) {
						togglelink.removeClassName('closed');
						togglelink.addClassName('open');
					}
					if (togglecontent) togglecontent.show();
					if (footer) footer.show();
				} else {
					if (togglelink) {
						togglelink.removeClassName('open');
						togglelink.addClassName('closed');
					}
					if (togglecontent) togglecontent.hide();
					if (footer) footer.hide();
				}
			}

		}

	);

}

var subscriberLogout = function() {
	eraseCookie('sitrk');
	eraseCookie('siact');
	eraseCookie('UID');
	eraseCookie('publicationCode');
	eraseCookie('ID');
	eraseCookie('CUID');
	document.location = document.location;
}
var spec_login_id = readCookie('spec_login_id'); 

document.observe("dom:loaded", function() {
										
		initToggle();
											
		// Highlight form fields on focus
		var highlightForm = $$('div.main input[type=text], div.main input[type=password], div.link-subscription input[type=text], div.link-subscription input[type=password]');
		highlightForm.each(
			function(highlightElement) {
				highlightElement.observe('focus',function(event) {
					event.element().addClassName("highlight");
				});
				highlightElement.observe('blur',function(event) {
					event.element().removeClassName("highlight");
				});
			}
		);
		
		/*
		//hide registration divs as necessary depending on whether the user is logged in (i.e. whether cookie spec_login_id is set)
		if($('pref-centre-notloggedin') || $('pref-centre-loggedin')) {
			var spec_login_id = readCookie('spec_login_id');
			if(spec_login_id == null) {
				//user is not logged in
				$('pref-centre-notloggedin').show() ;	
				$('pref-centre-loggedin').hide() ;				
			} else {
				//user is logged in
				$('pref-centre-notloggedin').hide() ;	
				$('pref-centre-loggedin').show() ;
				if($('my-spectator-box')) {
					$('my-spectator-box').hide() ;
				}		
			}
		}*/
		
		//hide registration divs as necessary depending on whether the user is logged in (i.e. whether cookie spec_login_id is set)
		var prefCentreNotLoggedInDivs = $$('.pref-centre-notloggedin') ;
		var prefCentreLoggedInDivs = $$('.pref-centre-loggedin') ;
	
		if(prefCentreNotLoggedInDivs || prefCentreLoggedInDivs) {
			// var spec_login_id = readCookie('spec_login_id'); now global!
			if(spec_login_id == null) {	
				//user is not logged in
				prefCentreNotLoggedInDivs.each(function(prefCentreDiv) {
					prefCentreDiv.show();				
				}) ;
				prefCentreLoggedInDivs.each(function(prefCentreDiv) {
					prefCentreDiv.hide();				
				}) ;				
			} else {
				//user is logged in
				prefCentreNotLoggedInDivs.each(function(prefCentreDiv) {
					prefCentreDiv.hide();				
				}) ;
				prefCentreLoggedInDivs.each(function(prefCentreDiv) {
					prefCentreDiv.show();				
				}) ;					
			}
		}		
		
//		if ($("button-pref-centre-reg")) {
//			$("button-pref-centre-reg").show();
//		}
		
		// Show the preference centre links when the dom is ready
		var prefLinks = $$('div#masthead div a');
		
		if (prefLinks) {
			prefLinks.each(
				function(prefLinksShow) {
					prefLinksShow.show();				
				}
			)
		}
		
		// if you are logged into preference centre and subscriber
		// then logout of both
		var subscriberCookie = readCookie('UID');
		if (subscriberCookie != null && spec_login_id != null) {
			var logoutButton = $('button-pref-logout');
			if (logoutButton) {
				logoutButton.observe('click',
					function(event) {
						event.stop();
						
						eraseCookie('sitrk');
						eraseCookie('siact');
						eraseCookie('UID');
						eraseCookie('publicationCode');
						eraseCookie('ID');
						eraseCookie('CUID');
						document.location = logoutButton.href;
					}
				);
		 	}
		}
		
		
		
});

function showCommentsBox(articleID) {
	if(spec_login_id == null) {
		href = "/comment/" + articleID + "/no-post-comment.thtml" ;
		fb.loadAnchor(href, 'width:675 height:370 scrolling:no overlayOpacity:25', 'Post a comment') ;
	} else {
		href = "/comment/" + articleID + "/post-comment.thtml" ;
		fb.loadAnchor(href, 'width:420 height:250 scrolling:no overlayOpacity:25', 'Post a comment now');
	}
	return false;
}



