////////////////////// 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("egrmagazine.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);


document.observe("dom:loaded", function() {
	highlightForm();
	initToggle();
	toggleContainers();
});


// Highlight form fields on focus
function highlightForm() {
	var highlightForm = $$('fieldset.form input[type=text], fieldset.form input[type=password], fieldset.form textarea');
	highlightForm.each(
		function(highlightElement) {
			highlightElement.observe('focus',function(event) {
				event.element().addClassName("highlight");
			});
			highlightElement.observe('blur',function(event) {
				event.element().removeClassName("highlight");
			});
		}
	);
}

// Directory expand close

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('smallbstate');

	if (stateString && stateString != '') {
		stateObj=stateString.evalJSON();
	}

	stateObj[id] = state;

	createCookie('smallbstate', 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('egrstate');
	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();
				}
			}

		}

	);

}

