$(function (){

    // Construct menu & excerpt
    constructMenu ();
    constructExcerpt();

	//Speed of the slideshow
	var intervalSpeed = 6000;
	var initializationDelay = 10;


	setTimeout("initializeHomeSlider("+intervalSpeed+")",initializationDelay);
});

/*****************/
/**  FUNCTIONS  **/
/*****************/

/* 1. Initializes the slider */
/* 2. Initializes the fader engine */
/* 3. Goto an element into the slider */
/* 4. Check the next element to activate into the slider and goes to it */
/* 5. Animate the li in menu for the incoming element */
/* 6. Animate the li in menu for the incoming element */
/* 7. Makes the initial animation of the menu */	
/* 8. Animate the correct menu for the incoming element */
/* 9. Adjust menu elements if they have no subtitle */
/* 10. Construct the necessary html for the slider menu */
/* 11. Construct the necessary html for the excerpt */
/* 12. Convert unscaped text into scaped one  */

/* 1. Initializes the slider */
function initializeHomeSlider (speed){

	//You have to specify width and height in #slider-container CSS properties
	//After that, the following script will set the width and height accordingly
	$('#mask-gallery, #fader a').width($('.rack-design').width());
	$('#gallery').width($('.rack-design').width() * $('#fader a').length);
	$('#mask-gallery, #fader a, #mask-excerpt, #excerpt li').height($('.rack-design').height());
	
	//Assign a timer, so it will run periodically
	var run = setInterval('gotoNext()', speed);	
	
	// Set First element of participant components as selected
	$('#fader > div a:first, #excerpt li:first','#controls_list li:first').addClass('selected');

	//Event handler for controls 
	$('#controls_list > li').hover(
	
	function () {
	
		// Restore first possible activated ones
		$('#controls_list > li').find('div').stop().animate({left:'0px'}, 500);
		$('#controls_list > li').stop().animate({opacity:'0.4'}, 500);

		var which = $(this).attr("rel");
		goto(which);


		$(this).find('div').stop().animate({left:'-10px'}, 500);
		$(this).stop().animate({opacity:'1.0'}, 500);
		
		return false;
	});
			
	//Mouse over, pause it, on mouse out, resume the slider show
	$('#fader a, #excerpt li,#controls_list > li').hover(
		function() {
			clearInterval(run);
			return false;
		}, 
		function() {
			run = setInterval('gotoNext()', speed);	
			return false;
		}
	);
	
	// Adjust menu elements if they have no subtitles
	adjustMenuElements();
	
	// Animate initially the right menu
	animateMenuFirstTime();

	// Initialize Fader engine
	initializeFader ();
}

/* 2. Initializes the fader engine */
function initializeFader () {

			// Muchos de los par‡metros que aparecen aqu’ no importan, ya que se ha modificado el funcionamiento
			// del slideshow desde dentro. Aœn as’, y para una correcta inicializaci—n, ah’ est‡n
            $("#fader").showcase({ 
				width: "937px",
				height: "85px",
                animation: { autoCycle: false, stopOnHover: true, interval: 3500,  speed: 1500,  easefunction: "swing",  type: "fade"},
                navigator: { item: { width: "20px", height: "20px" , orientation:"vertical", showNumber:true, showMiniature:false},
                             showMiniature: true,autoHide: false },
                titleBar: { autoHide: false, cssClass: null, css: { opacity: 0}}});
}


/* 3. Goto an element into the slider */
function goto(element) {

	//Get next sibling
	var next_image =  $('#fader div a:eq('+element+')');
	var next_excerpt = $('#excerpt li:eq('+element+')');
	var next_control = $('#controls_list li:eq('+element+')');
	
	//clear the selected class
	$('#excerpt li, #fader a, #controls_list li').removeClass('selected');
	$('#excerpt .content').fadeOut("fast");

	//reassign the selected class to current items
	$(next_image).addClass('selected');
	$(next_excerpt).addClass('selected');
	$(next_control).addClass('selected');

	//Scroll the items
	$('#mask-excerpt').stop(true,false);
	$('#mask-excerpt').scrollTo(next_excerpt, 800);
	setTimeout("changeFader("+element+")", 0);
}

/* 4. Check the next element to activate into the slider and goes to it */
function gotoNext() {
		
	//Get the current selected item (with selected class), if none was found, get the first item
	var currentElement = $('#controls_list li.selected').length ? $('#controls_list li.selected') : $('#controls_list li:first');
	var which = $(currentElement).attr("rel");
	
	var nextElement = new Number(which)+1;
	if (nextElement == $('#controls_list li').length) {
		nextElement = 0;
	} 
	goto(nextElement);	
	animateMenu(nextElement);
	return false;
}


/* 5. Animate the li in menu for the incoming element */
function changeFader (element) {
	$('#navigator a:eq(' + element + ')').click();
	$('#excerpt .content:eq(' + element + ')').stop(true,true).fadeIn(3000);
}


/* 6. Animate the li in menu for the incoming element */
function animateLi (i) {
	var oneLi = $('#controls_list li:eq('+ i +')');
	$(oneLi).find('div').stop().animate({left:'0px'}, 1000);
}


/* 7. Makes the initial animation of the menu */	
function animateMenuFirstTime() {
	
	// Move all menu elements into scene
	var list = $("#controls_list li");
	var elements = list.length;
	
	for (var i=0; i<=elements; i++) {
	    setTimeout("animateLi ("+ i + ")",300*i);
	}
	
	// Activate animation in first element
	setTimeout ("animateMenu(0)",2000);
	$('#excerpt .content').fadeIn(3000);
}

/* 8. Animate the correct menu for the incoming element */
function animateMenu (which) {

	// Restore first possible activated ones
	$('#controls_list > li').find('div').stop().animate({left:'0px'}, 200);
	$('#controls_list > li').animate({opacity:'0.4'}, 200);

	$('#controls_list > li:eq('+which+')').find('div').stop().animate({left:'-10px'}, 200);
	$('#controls_list > li:eq('+which+')').animate({opacity:'1.0'}, 200);

}

/* 9. Adjust menu elements if they have no subtitles */
function adjustMenuElements () {
	$('#controls_list li .title').each(
		function (intIndex) {
            // Take subtitle texts of menus
			var subtitleText = new String ($(this).find('.subtitle').html());

            // Checking if it's empty. If yes, repositionate menœ title
			if (subtitleText == "") {
				$(this).css("padding-top",'8px');
			}
		});
}

/* 10. Construct the necessary html for the slider menu */
function constructMenu () {

    // Searching containing menu data
    var ul ='<ul id="controls_list">'
    // Constructing list

    // Taking controls html root element
    var controls = $('#fader a');

    // Adding li's
    for (var i=0;i<controls.length; i++) {
        var content = $('#fader a:eq('+ i +') #for_title').html();
        li = '<li rel="'+ i+ '"><div><span class="title">' + content + '</span></div></li>';
        ul = ul + li;
    }
    ul = ul + '</ul>';
    // Adding to DOM
    $('.rack-design').append(ul);
}


/* 11. Construct the necessary html for the excerpt */
function constructExcerpt () {

    // Searching containing menu data
    var ul ='<div id="mask-excerpt"><ul id="excerpt">'
    // Constructing list

    // Taking controls html root element
    var controls = $('#fader a');

    // Adding li's
    for (var i=0;i<controls.length; i++) {
        var content = $('#fader a:eq('+ i +') #for_excerpt').html();
        li = '<li><span class="content">' + toHtml(content) + '</span></li>';
        ul = ul + li;
    }
    ul = ul + '</ul></div>';
    // Adding to DOM
    $('.rack-design').append(ul);
}


/* 12. Convert unscaped text into scaped one  */
function toHtml (myString) {
    
     var htmlString = "NO TEXT";
     if (myString != null) {
         htmlString = myString.split("&lt;").join("<");
        htmlString = htmlString.split("&gt;").join(">");
         htmlString = htmlString.split("&quot;").join("\"");
         htmlString = htmlString.split("&apos;").join("\'");
     }
     return htmlString;
     
}
