/*------------- [ DECLARATION OF VARIABLES: CONTENT ] -------------*/

	var showcase = [
						['showcase/camion1.jpg', 'Flota Transjamon', false, false],
						['showcase/camion2.jpg', 'Flota Transjamon', false, false],
						['showcase/camion3.jpg', 'Flota Transjamon', false, false],
						['showcase/camion4.jpg', 'Flota Transjamon', false, false]
				   ];

	var sections = [
						['content/productos.php', 'products_div'],
						['content/nosotros.php', 'nosotros_div'],
						['content/flota.php', 'flota_div']
				   ];


/*------------- [ DECLARATION OF VARIABLES: GLOBALS ] -------------*/
	
	var scrollOffset;
	
	var showcaseProcess;
	var showcaseStop = true;
	
	var animationFlag = false;
	
	var done = 0;
	var currentPosition = 0;
	var itemPosition = 0;
	
	var currentSection = 'products_div';
	var tabTag = '_link';
	var paneTag = '_div';
	
	var scrollanimation = [
								{ time: 0, begin: 0, change: 0.0, duration: 0.0, element: null, timer: null },
								{ time: 0, begin: 0, change: 0.0, duration: 0.0, element: null, timer: null }
						  ];


/*------------- [ LOADING ] -------------*/
	
	Event.observe(window, 'load', function() {
		initShowcase();
		initSections();
		initPortfolio();
		
		hivelogicEnkoder();
		fieldsHover();
		googleAnalytics();
	});


/*------------- [ SPECIFIC FUNCTIONS: SECTIONS ] -------------*/

	function initSections(){
		$(sections[0][1].split('_')[0] + tabTag).className = 'active';
		
		sections.each(function(section) {
			if( section[0] == false )
				$('content').insert('<div id="' + section[1] + '" class="section"></div>');
			else
				new Ajax.Request(section[0], {
					asynchronous: false,
					onComplete: function(content) {
	    				$('content').insert('<div id="' + section[1] + '" class="section">' + content.responseText + '</div>');
	  				}
				});
		});
		
		done = 2;
	}

	function displaySection(link){
		if (done == 2) {
			scrollSection(link, 'content', 'products_div', 'vertical');
			changeLink(link);
		}
		else 
			if (done == 0) {
				done = 1;
				
				new PeriodicalExecuter(function(process){
					if (done == 2) {
						process.stop();
						scrollSection(link, 'content', 'products_div', 'vertical');
						changeLink(link);
					}
				}, 0.015);
			}
	}
	
	function changeLink(link){
		if (currentSection == link)
			return;
		
		lastSection = currentSection;
		currentSection = link;
		
		Try.these(function(){
			$(currentSection.split('_')[0] + tabTag).className = 'active';
			
			if (lastSection)
				$(lastSection.split('_')[0] + tabTag).className = 'inactive';
		});
		
		adjustViewport();
	}

	function adjustViewport(){
		new PeriodicalExecuter(function(process){
			if (scrollanimation[0].timer == null) {
				if (scrollOffset != document.viewport.getScrollOffsets()[1]) {
					wide = -(document.viewport.getHeight() - 425);
					scrollEffect = new Effect.ScrollTo('menu_comment', {
						afterFinish: updateOffset,
						offset: wide,
						queue: {
							scope: 'scroll',
							position: 'end'
						}
					});
				}
				process.stop();
			}
		}, 0.25);
	}
	
	function updateOffset(){
		scrollOffset = document.viewport.getScrollOffsets()[1];
	}


/*------------- [ SPECIFIC FUNCTIONS: PORTFOLIO ] -------------*/

	function displayPortfolio(link){
		scrollSection(link, 'flota_div', 'flota_content_0', 'horizontal');
	}
	
	function hoverPortfolio(element, type){
		if(type == 'over')
			newOpacity = 1.0;
		else
			newOpacity = 0.6;
		
		queue = Effect.Queues.get( $(element).identify() );
		queue.each( function(effect){ effect.cancel(); } );
			
		oldOpacity = $(element).getStyle('opacity');
		
		if(oldOpacity!=newOpacity)
			new Effect.Opacity(element, { duration: 0.25, from: oldOpacity, to: newOpacity, queue: { scope: $(element).identify() } } );
	}
	
	function openPortfolio(element, cont, page){
		return hs.expand(element, {
			captionId: 'caption_' + cont,
			slideshowGroup: 'flota' + page
		} );
	}


/*------------- [ SPECIFIC FUNCTIONS: PRODUCTS ] -------------*/

	function displayProduct(link){
		scrollSection(link, 'products_div', 'products_back', 'horizontal');
	}


/*------------- [ SPECIFIC FUNCTIONS: CONTACT US ] -------------*/

	function scrollToDiv(link){
		new Effect.ScrollTo(link, { queue: { scope: 'scroll', position: 'end' } } );
	}


/*------------- [ SPECIFIC FUNCTIONS: SHOWCASE ] -------------*/

	function initShowcase(){
		$('back').setStyle( { opacity: 0.5, 'cursor': 'default' } );
		$('next').setStyle( { opacity: 1, 'cursor': 'pointer' } );
		
		for (cont = 0; cont < showcase.length; cont++)
			loadShowcase(cont);
		
		$('showcase_images').scrollLeft = 15;
		
		$('link').update(showcase[currentPosition][1]);
		
		if (showcase[currentPosition][2])
			$('link').writeAttribute('href', showcase[currentPosition][2]);
	}
	
	function timeShowcase(){
		if(showcaseProcess)
			showcaseProcess.stop();
		
		if(showcaseStop)
			showcaseProcess = new PeriodicalExecuter(function(process){
				changeShowcase('next', 'auto');
			}, 4);
	}

	function changeShowcase(orientation, type){
		lastPosition = currentPosition;
		
		if (orientation == 'next' && currentPosition < showcase.size() - 1) {
			currentPosition++;
			$('back').setStyle({ opacity: 1, 'cursor': 'pointer' });
		}
		else 
			if (orientation == 'back' && currentPosition != 0) {
				currentPosition--;
				$('next').setStyle({ opacity: 1, 'cursor': 'pointer' });
			}
			else 
				if (orientation == 'next' && currentPosition == showcase.size() - 1) {
					if(type == 'auto'){
						currentPosition = 0;
						$('next').setStyle({ opacity: 1, 'cursor': 'pointer' });
					}
					else
						return;
				}
		
		if(currentPosition == 0)
			$('back').setStyle( { opacity: 0.5, 'cursor': 'default' } );
		else
			if(currentPosition == showcase.size()-1)
				$('next').setStyle( { opacity: 0.5, 'cursor': 'default' } );
		
		if (!showcase[currentPosition][3])
			loadShowcase(currentPosition);
		
		if (lastPosition != currentPosition) {
			position = findElementPos($('image_' + currentPosition));
			position = position[0];
			
			offsetPos = findElementPos($('image_0'));
			position -= offsetPos[0];
			
			if (currentPosition > lastPosition) {
				first = position + 45;
				second = position + 15;
			}
			else {
				first = position - 15;
				second = position + 15;				
			}
			
			scrollStart($('showcase_images'), $('showcase_images').scrollLeft, first, 'horizontal', 25, 1);
			
			new PeriodicalExecuter(function(process){
				if( scrollanimation[1].timer == null ) {
					process.stop();
					scrollStart($('showcase_images'), $('showcase_images').scrollLeft, second, 'horizontal', 15, 1);
					
					$('link').update(showcase[currentPosition][1]);
					$('link').writeAttribute('href', showcase[currentPosition][2]);
				}
			}, 0.015);
		}
	}

	function loadShowcase(currentPosition){
		html = '';
		
		if(showcase[currentPosition][2])
			html += '<a href="' + showcase[currentPosition][2] + '">';
		
		html += '<div><img id="image_' + currentPosition + '" src="' + showcase[currentPosition][0] + '" alt="' + showcase[currentPosition][1] + '" title="' + showcase[currentPosition][1] + '" /></div>';
		
		if(showcase[currentPosition][2])
			html += '</a>';
		
		$('showcase_scroller').insert(html);
		
		showcase[currentPosition][3] = true;
	}


/*------------- [ SCROLLING FUNCIONS ] -------------*/

	function scrollSection(link, scrollArea, offset, direction){
		theScroll = $(scrollArea);
		
		position = findElementPos($(link));
		
		if( direction == 'horizontal' )
			position=position[0];
		else
			position=position[1];
		
		if ( offset != '' ) {
			offsetPos = findElementPos($(offset));
			
			if (direction == 'horizontal') {
				position -= offsetPos[0];
				start = theScroll.scrollLeft;
			}
			else {
				position -= offsetPos[1];
				start = theScroll.scrollTop;
			}
		}
	
		scrollStart(theScroll, start, position, direction, 25, 0);
	}
	
	function scrollStart(elem, start, end, direction, duration, position){
		if (scrollanimation[position].timer != null) {
			clearInterval(scrollanimation[position].timer);
			scrollanimation[position].timer = null;
		}
		
		scrollanimation[position].time = 0;
		scrollanimation[position].begin = start;
		scrollanimation[position].change = end - start;
		scrollanimation[position].duration = duration;
		scrollanimation[position].element = elem;
		
		scrollanimation[position].timer = setInterval('scrollAnimation(' + position  + ', \'' + direction + '\');', 15);
	}
	
	function scrollAnimation(position, direction){
		if (scrollanimation[position].time > scrollanimation[position].duration) {
			clearInterval(scrollanimation[position].timer);
			scrollanimation[position].timer = null;
		}
		else {
			move = sineInOut(scrollanimation[position].time, scrollanimation[position].begin, scrollanimation[position].change, scrollanimation[position].duration);
			
			if(direction == 'vertical')
				scrollanimation[position].element.scrollTop = move; 
			else
				scrollanimation[position].element.scrollLeft = move;
			
			scrollanimation[position].time++;
		}
	}

	function sineInOut(t, b, c, d){
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	}


/*------------- [ POSITIONING FUNCTIONS ] -------------*/
	
	function findElementPos(elemFind){
		var elemX = 0;
		var elemY = 0;
		
		do {
			elemX += elemFind.offsetLeft;
			elemY += elemFind.offsetTop;
		}
		while ( elemFind = elemFind.offsetParent )
	
		return Array(elemX, elemY);
	}
	
	function centerElement(element, parent) {
        elementDimensions = $(element).getDimensions();
        
		if (!parent) {
            viewportDimensions = document.viewport.getDimensions();
            parentWidth = viewportDimensions.width;
            parentHeight = viewportDimensions.height;
        }
		else {
            parentWidth = $(parent).offsetWidth;
            parentHeight = $(parent).offsetHeight;
        }
		
		viewportOffset = document.viewport.getScrollOffsets();
		
		$(element).absolutize();
		$(element).style.top = (parentHeight/2) - (elementDimensions.height/2) + viewportOffset.top + 'px';
        $(element).style.left = (parentWidth/2) - (elementDimensions.width/2) + viewportOffset.left + 'px';
	}
