/* **
 * ** TOP ITEMS
 * ** */
 
var album = {
	items : new Array(),
	timer : null,
	currentItem : '0',
	additem : function(el, desc, link) {
		album.items.push( [el,desc,link] );
	},

	startup: function() {
		Element.addClassName('boxlink-' + album.currentItem, 'selected');
		album.timer = new PeriodicalExecuter(album.cycle, 5) // change image every 5 seconds
	},

	cycle: function() {
		new Effect.Fade(album.items[album.currentItem][0], { // the id of the <DIV> containing the photos
			from:1.0,
			to:0.0,
			duration: 1,
			fps: 50})
		album.currentItem++;
		if(album.currentItem >= album.items.length) album.currentItem = 0;
		new Effect.Appear(album.items[album.currentItem][0], { // the id of the <DIV> containing the photos
			from:0.0,
			to:1.0,
			duration: 1, 
			fps: 50,
			afterFinish: function() {
				$('slideshow_title').innerHTML = album.items[album.currentItem][1];
				$('slideshow_title').href = album.items[album.currentItem][2];
				$('slideshow_link').href = album.items[album.currentItem][2];
				album.clearSelected();
				Element.addClassName('boxlink-' + album.currentItem, 'selected');
			}
		})
	},

	show: function( number ){
		album.clearSelected();
		if ( album.timer != null )
			album.timer.stop();
		if ( number != album.currentItem ){
			Element.hide( album.items[album.currentItem][0] );
			album.currentItem = number;
			Element.show( album.items[album.currentItem][0] );
			
			$('slideshow_title').innerHTML = album.items[album.currentItem][1];
			$('slideshow_title').href = album.items[album.currentItem][2];
			$('slideshow_link').href = album.items[album.currentItem][2];
		}
	},
	
	clearSelected: function () {
		$A($('boxlinks').getElementsByClassName('selected')).each( function(el) { Element.removeClassName(el, 'selected'); } );
	}
}

/* **
 * ** SCREENSHOT SLIDESHOWS
 * ** */

var CustomGalleries = Class.create();
CustomGalleries.prototype = {

	initialize: function() {
		if (!document.getElementsByTagName){ return; }
		
		// Create the galleryArray property
		this.galleryArray = [];
		
		// List all the anchor tags on the page
		var anchors = document.getElementsByTagName('a');
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			// Check the REL="" attribute of the tag
			var relAttribute = String(anchor.getAttribute('rel'));
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('slide'))){
			
				// Discover the gallery and some other details
				var galleryId = this.extractGalleryId(relAttribute);
				var hrefAttribute = String(anchor.getAttribute('href'));
				var titleAttribute = String(anchor.getAttribute('title'));
				
				// Create a new gallery for each galleryId if it doesn't exist
				if( ! this.galleryArray[galleryId] ){
					this.galleryArray[galleryId] = new PhotoViewer();
					this.galleryArray[galleryId].disablePanning();
					this.galleryArray[galleryId].setSlideDuration(6000);
					this.galleryArray[galleryId].enableLoop();
					this.galleryArray[galleryId].setImageRoot('/images/photoviewer');
					this.galleryArray[galleryId].disableEmailLink();
					this.galleryArray[galleryId].disablePhotoLink();
					this.galleryArray[galleryId].setFontSize(12);
				}
				
				// Add a screenshot to the slideshow
				this.galleryArray[galleryId].add( 
					hrefAttribute,	// Full URL to the image
					titleAttribute ); /*,	// Descirption (= Game name)
					"platform" );	// Description2 (= Platform)	*/
				
				// Attach the onclick event to the anchor
				anchor.onclick = function () {mygalleries.start(this); return false;}
			}
		}
	},
	
	start: function(imageLink) {
		if (!document.getElementsByTagName){ return; }
		
		// Look up some of the variables we need
		var myRelAttribute = String(imageLink.getAttribute('rel'));
		var myGalleryId = this.extractGalleryId(myRelAttribute);
		var myGalleryAmount = 0;
		
		// List all the anchor tags on the page
		var anchors = document.getElementsByTagName('a');
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			// Check the REL="" attribute of the tag
			var relAttribute = String(anchor.getAttribute('rel'));
			if (anchor.getAttribute('href') && relAttribute == myRelAttribute ){
				
				// Is it the same anchor ?
				if( anchor == imageLink ){
					this.galleryArray[myGalleryId].show(myGalleryAmount);
					break;
				}
				
				// Couter++ and try next anchor
				myGalleryAmount++;
			}
		}
	},
	
	extractGalleryId: function(relAttribute) {
		// Used to extract the galleryId from the REL attribute
		if (relAttribute.length > 7){ return relAttribute.substring(6, relAttribute.length -1); }
		else {return "NO_GALLERY";}
	}
}

function initGalleries() { mygalleries = new CustomGalleries(); }
Event.observe(window, 'load', initGalleries, false);

Ajax.CustomAutocompleter = Class.create();
    Object.extend(Object.extend(Ajax.CustomAutocompleter.prototype, Autocompleter.Base.prototype), {
      initialize: function(element, update, url, options) {
        this.baseInitialize(element, update, options);
        this.options.asynchronous  = true;
	this.options.onComplete    = this.onComplete.bind(this);
        this.options.defaultParams = this.options.parameters || null;
        this.url                   = url;
      },
  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      if(this.update.firstChild && this.update.down().childNodes) {
        this.entryCount = 
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else { 
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.index = -1;
      
      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  },   
  markPrevious: function() {
    if(this.index > 0) this.index--
      else this.index = this.entryCount-1;
  },
  
  markNext: function() {
    if(this.index < this.entryCount-1) this.index++
      else this.index = 0;
  },
  getUpdatedChoices: function() {
    entry = encodeURIComponent(this.options.paramName) + '=' + 
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams) 
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
  }
    }); 

/* **
 * ** GENERAL
 * ** */

function ellipsis(root) {
//var start = new Date();
	if (!root)
		root = document;
	var items = document.getElementsByClassName( "ellipsis", root );
	
	if(Prototype.Browser && Prototype.Browser.IE) {
		// --- Internet Explorer uses auto-ellipsis through css
		for( var i = 0 ; i < items.length ; i++ ) {
			items[i].style.width = $(items[i].parentNode).getStyle('width');
			items[i].style.textOverflow = "ellipsis";
		}
	}
	else {
		// --- Other browsers, force via javascript
		for( var i = 0 ; i < items.length ; i++ ) 
			ellipsisText( items[i] );
	}
//alert( new Date() - start);
}

function ellipsisText( n ) {
	var w = n.clientWidth;
	if( w && n.scrollWidth > w ) {
		var org_t = n.innerHTML;
		var org_l = org_t.length;
		// var i = 1;
		var chop = Math.floor( (org_l * w) / n.scrollWidth ) - 1;
		if( chop > 0 ){
			while( n.scrollWidth > w ) {
				n.update(org_t.substring( 0, --chop )+"&hellip;");
			}
		}
	}
}

function addScoreLinks()
{
	var popupLinks = new Array();

	popupLinks = document.getElementsByClassName('popup');

	for(i = 0; i < popupLinks.length; i++)
	{
			popupId = getPopupId(popupLinks[i]);
			popupLinks[i].onmouseover = function() { showElement(this) };
			popupLinks[i].onmouseout = function() { hideElement(this) };
	}
}

function showElement(theHoverElement)
{
	theHoverElement.addClassName('hover');
}
function hideElement(theHoverElement)
{
	theHoverElement.removeClassName('hover');
}
function getPopupId(theElement)
{
	idFetcher = new RegExp('[0-9]');
	return idFetcher.exec(theElement.id);
}

function setActiveFeatures( number ){
	$("overview_menu").attributes['class'].nodeValue = 'overview_menu clearfix ' + number;

	var n = $('overview_menu').next(0);
	n.attributes["class"].nodeValue = (number == 'first') ? "first_content" : "first_content hide";
	n.next(0).attributes["class"].nodeValue= (number == 'second') ? "second_content" : "second_content hide";
	n.next(1).attributes["class"].nodeValue = (number == 'third') ? "third_content" : "third_content hide";
}
function emptyLogin() {
	if(document.form_action.login_name.value == 'username')
		document.form_action.login_name.value = '';
	if(document.form_action.login_pass.value == 'password')
		document.form_action.login_pass.value = '';
}
function mustSubmit(event) {
	if(event.keyCode == Event.KEY_RETURN)
	{
		$('form_action').onsubmit();
		
		return false;
	}
	else
	{
		return true;
	}
}
function quoteComment( el ) {
	Element.extend(el);
	Element.scrollTo('commentsubmit');
	Pvalue = el.up(0).up(0).down(0).down(0).innerHTML;
	Cvalue = el.up(0).previous(0).innerHTML;
	if( $('commenttext').value != "" )
		$('commenttext').value = $('commenttext').value + '\n\n';
	$('commenttext').value = $('commenttext').value + '[quote][b]' + Pvalue + ':[/b]\n' + Cvalue.stripScripts() + '[/quote]\n';
	$('commenttext').focus();
}
function editComment( el, cid, page ){
	if( confirm( "You are about to edit a comment. This action cannot be undone." ) ){
		Element.extend(el);
		Element.scrollTo('commentsubmit');
		Cvalue = el.up(0).previous(0).innerHTML;
		$('commenttext').value = Cvalue;
		$('cIdUpdate').value = cid;
		$('cPage').value = page;
		$('cIdUpdate').next(0).value = "Edit";
		$('commenttext').focus();
	}
}
function deleteComment()
{
	return confirm("Are you sure you want toggle the visibility of this comment?");
}
function validateForm()
{
	var t = new String ( document.commentform.text.value );
	if (t.trim()=="")
	{
		alert("Please provide a comment before posting.");
		return false;
	}
	else {
		document.commentform.postNewComment.value="Submitting...";
		document.commentform.postNewComment.disabled=true;
		return true;
	}
}

function submitOK()
{
	Effect.BlindUp('commentsubmit', { duration: 0.5 });
	$('commenttext').value = '';
	document.commentform.cIdUpdate.value="";
	document.commentform.cPage.value="";
	document.commentform.postNewComment.value="Send";
	document.commentform.postNewComment.disabled=false;

	new PeriodicalExecuter(function(pe) {
		Effect.BlindDown('commentsubmit', { duration: 0.5 });
		pe.stop();
	}, 3);
}

function sel(el)
{
	Element.extend(el);
	var alpha = $(el).up().up();
	alpha.getElementsBySelector('strong').each( function(els) { Element.removeClassName(els, 'selected'); } );
	Element.addClassName(el.firstDescendant(), 'selected');
}

/// Prototype trim function for strings
String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'') }

