////////////////////// THE CYCLE OBJECT CLASS //////////////////////
// This is essentially a class which cycles through the div ids passed
// to it on creation
function CycleObject(ids, transType, onClass, offClass) {

  // Methods
  this.setVisible = function(index) {

    // Check if there is an indicator for the animation and set as appropriate
    if (this.indicators[this.currentlyVisible]) {
      this.indicators[this.currentlyVisible].removeClassName(this.onClass);
      this.indicators[this.currentlyVisible].addClassName(this.offClass);
    }

    if (this.indicators[index]) {
      this.indicators[index].removeClassName(this.offClass);
      this.indicators[index].addClassName(this.onClass);
    }

    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.showItem = function(index) {
  	// show a particular item in the list and stop the animation
	this.cycleObject.stop();
  	this.setVisible(index);
  }

  this.startCycle = function() {
    this.cycleObject = new PeriodicalExecuter(
      this.onUpdateCycle.bind(this), 8 // 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';

  this.onClass = typeof(onClass) != 'undefined' ? onClass : 'on';
  this.offClass = typeof(offClass) != 'undefined' ? offClass : 'off';

  // The index (of the array ids) of the currently visible div
  this.currentlyVisible = 0;

  // Initialisation
  this.cycleObject = null;

  // find if there are any indicators
  this.indicators = new Array(this.ids.length);

  for(i = 0; i < this.ids.length; i++){
    var indicatorLabel = this.ids[i]+'-indicator';
  	var indicator = $(indicatorLabel);
  	this.indicators[i] = indicator;
  }

  // Set the first one as visible and all the others as not
  for(i = 1; i < this.ids.length; i++){
    $(this.ids[i]).hide();
  }

  this.setVisible(0);

}

/////////// END OF CYCLEOBJECT CLASS //////////////////

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("information-age.com") == -1 &&
			 href.indexOf(hostname)==-1 )
			 return true ;
		else
			return false;
	};
	this.set = function(obj){
		obj.target = "_blank";
		obj.className = "external";
	};
	for (var i=0;i<a.length;i++){
		if(check(a[i])) set(a[i]);
	};
};

// 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);

Event.observe(window, 'load',
  function() {
	
	
		 
	



    toggleContainers();

  }
);

function initToggle() {

	toggleContainers();
	
	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 setDefaultFontSize() {

	textToResize = $('bodyText');
	var fs = textToResize.getStyle('fontSize');

	//alert(fs);

	if (fs.endsWith("px")) {
		myFontSize = parseFloat(fs);
		myFontSizeIncrement = 2;
		myFontSizeType = 'px';
	} else if (fs.endsWith("%")) {
		myFontSize = 100;
		myFontSizeIncrement = 10;
		myFontSizeType = '%';
	} else if (fs.endsWith("em")) {
		myFontSize = parseFloat(fs);
		myFontSizeIncrement = 0.1;
		myFontSizeType = 'em';
	} else {
		myFontSize = parseFloat(fs);
		myFontSizeIncrement = 2;
		myFontSizeType = 'px';
	}
}

function textSize(dir) {

	if (typeof myFontSize == 'undefined') {
		setDefaultFontSize();
		myNewFontSize = myFontSize;
	}

	if (dir == 'up') {
		myNewFontSize += myFontSizeIncrement;
	} else {
		myNewFontSize -= myFontSizeIncrement;
	}

	myNewFontSizeString = myNewFontSize + myFontSizeType;

	// alert(myNewFontSizeString);
	//alert('test1');
	textToResize.setStyle({ fontSize: myNewFontSizeString });
	//alert('test2');

	return;

}

function rememberState(divElement, state) {

	var stateObj = new Object();

	var id = $(divElement).id;

	var stateString = readCookie('iastate');

	if (stateString && stateString != '') {
		stateObj=stateString.evalJSON();
	}

	stateObj[id] = state;

	createCookie('iastate', 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;
}


document.observe("dom:loaded", function() {
	setLoginOptions();
});

function setLoginOptions() {	
		
		var signupDiv = $("signup-bar");
	//	if (signupDiv) {
	var signupBar = $("signup-bar");
	var commentsBox = $("show-comments-box");
	
		var login_id = readCookie('informationage_user');
			if(login_id == null) {	
				//user is not logged in
				if(signupBar){
					signupBar.show(); 				
				}
				if (commentsBox) {
					commentsBox.hide();
				}
				 
			} else {
				//user is logged in
				if(signupBar){
					signupBar.hide(); 				
				}
				if (commentsBox) {
					commentsBox.show();
				}
			}
		//}
		
	
	}

function toggleContainers() {

	var stateString = readCookie('iastate');
	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();
					}
				}
	
			}
	
		);
	}
}


