document.observe("dom:loaded", function() {
	searchText();
	featuresVideoImage();
	highlightForms();
	changeTextSize();
	formError();
	externalLink();
	startFeaturesCycle();
	startBlogsCycle();
	editProfile();
	showLoggedState();
	servicesDirectory();
	clickEvents();
});

// When search input is clicked on, remove the word search
// and put back if value is blank
function searchText() {
	var searchText = $("search-text");
	if (searchText) {
		searchText.observe('focus',
			function(event) {			
				if ($F(this) == 'Search') {
					this.value = '';
				}
			}
		).observe('blur',
			function(event) {
				if ($F(this) == '') {
					this.value = 'Search';
				}
			}
		);
	}
}

// If features module has video article
// set background position on the play arrow when you mouseover the image
function featuresVideoImage() {
	var featuresVideoImage = $$("a.features-video-image");
		featuresVideoImage.each (
			function (featuresVideoImageItem) {
				featuresVideoImageItem.observe('mouseover',
					function(event) {
						var imageMouseover = this.previous(0);
						if (imageMouseover && imageMouseover.hasClassName('arrow-play')) {
							imageMouseover.setStyle({
								backgroundPosition: '0 -54px'
							});
						}
					}
				).observe('mouseout',
					function(event) {
						var imageMouseout = this.previous(0);
						if (imageMouseout && imageMouseout.hasClassName('arrow-play')) {
							imageMouseout.setStyle({
								backgroundPosition: '0 0'
							});
						}
					}
				);
			}
		)
}


// Highlight form fields on focus
function highlightForms() {
	var highlightForm = $$('textarea, ol.form input[type=text], ol.form input[type=password], div#comments input[type=text]');
		highlightForm.invoke('observe','focus',
			function(event) {
				event.element().addClassName("highlight");
			}
		).invoke('observe','blur',
			function(event) {
				event.element().removeClassName("highlight");
				event.element().removeClassName("highlight-error");
			}
		);
}

// Highlight form fields with errors
function formError() {
	var formError = $$("ol.form li .error, div#comments span.error");
		formError.each (
			function(formErrorHighlight) {
				var error = formErrorHighlight.innerHTML;
				var errorHTML = error.substring(0,4);
				if (! (errorHTML == '<!--')) {
					var formErrorHighlightInput = formErrorHighlight.previous('input[type=text], input[type=password], textarea');
					if (typeof formErrorHighlightInput != 'undefined') {
						formErrorHighlightInput.addClassName("highlight-error");
					}
				}
			}
		);

}


// Increase/decrease text size in article
function setDefaultFontSize() {

	textToResize = $('bodyText');
	var fs = textToResize.getStyle('fontSize');

	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;
	textToResize.setStyle({ fontSize: myNewFontSizeString });

	return;

}

function changeTextSize() {
	var textIncrease = $("text-increase");
	if (textIncrease) {
		textIncrease.observe('click',
			function(event) {
				textSize('up');
				return false;
			}
		);
	}
	
	var textDecrease = $("text-decrease");
	if (textDecrease) {
		textDecrease.observe('click',
			function(event) {
				textSize('down');
				return false;
			}
		);
	}
}


////////////////////// 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);

}

// Start features cycle box
function startFeaturesCycle() {
	var featuresBox = $("features");
	if (featuresBox) {
		featuresCycleBox = new CycleObject(['headcyc-1', 'headcyc-2', 'headcyc-3', 'headcyc-4', 'headcyc-5']);
		featuresCycleBox.startCycle();
	
		var featuresLinks = $$('a.featurescyclelink');
		featuresLinks.each(function(link) {
			var itemNumber = link.id.replace('headline-rotate','')-1;
			link.observe('click',
				function() {
					featuresCycleBox.showItem(itemNumber);
				}
			)
		});
	}
}


// Start blogs cycle box
function startBlogsCycle() {
	var blogsBox = $("blogs-rotate");
	if (blogsBox) {
		blogsCycleBox = new CycleObject(['blogscyc-1', 'blogscyc-2', 'blogscyc-3', 'blogscyc-4']);
		blogsCycleBox.startCycle();
				
		var blogsLinks = $$('a.blogscyclelink');
		blogsLinks.each(function(link) {
			var itemNumber = link.id.replace('headline-blog-rotate','')-1;
			link.observe('click',
				function() {
					blogsCycleBox.showItem(itemNumber);
				}
			)
		});
	}
}

// Add target_blank to any external links
function externalLink() {
	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("hfmweek.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]);
	};
};






// Launch edit profile floatbox if users come from email link
function editProfile() {
	var url = window.location.search.substring(1);
	var getQuery = url.split('?');
	var loginCookie2 = readCookie('hfm_login_id');
	
	if (getQuery == 'editprofile' && loginCookie2) {
		$("header").insert ({
        	'bottom' : '<a href="/registration/editprofile.php" rel="floatbox" rev="autoStart:true width:780 height:480" style="display:none;"></a>'
  		});
	}

	// General floatbox options
	fbPageOptions = {
    	outsideClickCloses: false,
		hideFlash: true
	};

}

function showLoggedState() {
	var loginCookie = readCookie('hfm_login_id');
	
	if(loginCookie == null) {
		loggedOut();
	}
	else {
		loggedIn();
	}
}


// Hide/show registration options depending on whether the user is logged in or not
function loggedIn() {
	$$(".logged-out").invoke("hide");
	$$(".logged-in").invoke("show");
}

function loggedOut() {
	$$(".logged-in").invoke("hide");
	$$(".logged-out").invoke("show");
}

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 unescape(c.substring(nameEQ.length,c.length));
		}
	}
	return null;
}

function servicesDirectory() {
	if(!$('services-directory-country-filter')) {
		return false ;
	}

	var countrySelect = $('services-directory-country-filter').down('#country');
	if (countrySelect) {
		countrySelect.observe('change',
			function (event) {
				document.location = document.location.pathname + $F(this);
			}
		);
	
	}
}

function clickEvents() {
	var page = $('page');
	if (page) {
		page.observe('click',
			function(event) {
				var element = event.findElement('a[href$=".pdf"]');
				if (element) {
					event.stop();
					window.open(element.href);
				}
			}
		);
	}
}
