
//-- Initialisation

/**
* Init
*/
$(document).ready(function(){ 
	initCompanySlider();
});


//-- Functions
//var companysliderVars = {animationStarted:false,idPrefix:'companySliderLogo',direction:'left',startMargin:0,logoWidth:0,current:0,logopages:Array(),loadedLogoData:Array(),nextHtml:''};
var sv = {bw:0,dir:'left',numLogos:0,logos:Array(),current:0,playing:false,slideTime:1000,startMargin:0,idPrefix:'companySliderLogo',currentHover:'',loadedLogoData:Array()}

function companySliderDebug(msg)
{
	if (window.console) {
		window.console.log(msg);
	}
}

/**
 * It is possible that we trigger an ajax-call by hovering a logo,
 * then when we move out of the slider the balloon pops up a little later
 * because the connection was slow.
 * It then won't hide automatically because we have already moved out of the slider.
 * That's why we check whether sv.currentHover is set and has the correct value before
 * actually showing the balloon.
 * So by unsetting it whenever we move out of the slider or hover a left/right-button
 * we fix the unwanted showing of balloons
 * @return
 */
function fixDelayedBalloonPopup()
{
	sv.currentHover = null;
}

function initCompanySlider()
{
	sv.bw = $('#companySlider .logos a').eq(0).css('width');
	companySliderDebug('bw: '+sv.bw);
	
	sv.startMargin = -(parseInt(sv.bw)*3)
	
	sv.numLogos = $('#companySlider .logos a').length;
	$('#companySlider .logos').css('margin-left',sv.startMargin);
	companySliderDebug('number of logoplaces: '+sv.numLogos);
	/**
	 * When leaving the belt DIV, hide the balloon,
	 * but only if we are not hovering the balloon
	 */
	$('.belt').bind('mouseout', function(e) {
		companySliderDebug('Mouse: '+e.pageX+','+e.pageY);

		if (mouseOverCompanySliderPopup(e)) {
			companySliderDebug('Mouse over popup');
		}else{
			fixDelayedBalloonPopup();
			$('#companySliderDetailsBalloon').hide();
		}
	});
	
	$('#companySlider .back').bind('click', function() {
		//companySliderRight();
	}).bind('mouseover', function(){
		companySliderDebug('hover button');
		fixDelayedBalloonPopup();
		$('#companySliderDetailsBalloon').hide();
		
		companySliderRight();
		
	}).bind('mouseout', function(){
		companySliderStop();
	});
		
	$('#companySlider .next').bind('click', function() {
		//companySliderLeft();
	}).bind('mouseover', function(){
		companySliderDebug('hover button');
		fixDelayedBalloonPopup();
		$('#companySliderDetailsBalloon').hide();
		
		companySliderLeft();
		
	}).bind('mouseout', function(){
		companySliderStop();
	});

	/**
	 * Call for logo-id's once
	 * This retuns an array with an array of id's for each page
	 */
	$.ajax({ 
		url: "/DCA/companies/getcompanysliderids",
		dataType: 'json',
		success: function(data){
			sv.logos = data;
			buildCompanySlider();
		}
	});
}

function buildCompanySlider()
{
	var i = 0;
	$('#companySlider .logos a').each(function(){
		if (i>=sv.numLogos){
			$(this).remove();
		}else{
			companySliderDebug('Logo with ID: '+sv.logos[i]);
			setLogoData(this,sv.logos[i]);
			i++;
		}
	});
}

function companySliderGetNext(logo)
{
	var current = 0;
		
	if (companysliderVars.direction=='right') {
		if (companysliderVars.current==undefined){
			companysliderVars.current = $('#companySlider .logos a').length-1;
		}else{
			companysliderVars.current--;
		}

		if (companysliderVars.current<=0) {
			companysliderVars.current = $('#companySlider .logos a').length-1;
		}
		
	}else{
		if (companysliderVars.current==undefined){
			companysliderVars.current = $('#companySlider .logos a').length-1;
		}else{
			companysliderVars.current++;
		}

		if (companysliderVars.current>=companysliderVars.logopages.length) {
			companysliderVars.current = 0;
		}
	}
	
	current = companysliderVars.logopages[ companysliderVars.current ];
	
	
}

function setLogoData(logoElm,logoId)
{
	companySliderDebug('Add logo: '+logoId);
	
	/**
	 * Add rollover callback and change ID
	 */
	//$(logoElm).attr('id','companySliderLogo'+logoId);
	
	/**
	 * If we have "cached" the logo HTML, we use that instead of doing an ajax-call
	 */
	if (sv.loadedLogoData[logoId]!=undefined) {
		$(logoElm).replaceWith(sv.loadedLogoData[logoId]);
		
	/**
	 * Otherwise we make an ajax-call to fetch the logo HTML
	 * and we put it in the cache
	 */
	}else{
		if (logoId!=undefined) {
			$.ajax({ 
				url: "/DCA/companies/getcompanysliderlogo",
				data: "id="+logoId,
				success: function(html){
					sv.loadedLogoData[logoId] = html;
					
					// We wait for the current scroll to finish untill we add the new html to the end (or beginning)
					$(logoElm).replaceWith(html);
				}
			});
		}
	}
}

function restartCompanySlide()
{
	if (sv.dir=='left') {
		$('#companySlider .logos').css('margin-left','0');
	}else{
		$('#companySlider .logos').css('margin-left',-parseInt(sv.bw));
	}
	
	startCompanySlide();
}

function startCompanySlide(difftime,reslideDir)
{
	/**
	 * If reslideDir is set, this means that we slide in direction reslideDir
	 * untill sv.playing is set to false,
	 * or the direction is being changed
	 * In each of those cases we simply return 
	 */
	if (reslideDir && (sv.stopped || reslideDir!=sv.dir)) return;
	
	/**
	 * If a slide is still playing, we do nothing
	 */
	if (sv.playing) return;
	
	sv.stopped = false;
	sv.playing = true;
	
	if (!difftime) difftime = sv.slideTime;
	
	if (sv.dir=='left') {
		$('#companySlider .logos').animate({marginLeft:(sv.startMargin-parseInt(sv.bw))},
		difftime,
		'linear',
		function(){
			var blck = $('#companySlider .logos a').eq(0).remove();
			$('#companySlider .logos').append(blck);
			$('#companySlider .logos').css('margin-left',sv.startMargin);
			companySliderUpdateCompany(blck,sv.dir);
			
			sv.playing = false;
			
			if (!sv.stopped && sv.dir=='left'){
				startCompanySlide(null,sv.dir);
			}
		})
		
	}else{
		$('#companySlider .logos').animate({marginLeft:(sv.startMargin+parseInt(sv.bw))},
		difftime,
		'linear',
		function(){
			var blck = $('#companySlider .logos a').eq($('#companySlider .logos a').length-1).remove();
			$('#companySlider .logos').prepend(blck);
			$('#companySlider .logos').css('margin-left',sv.startMargin);
			companySliderUpdateCompany(blck,sv.dir);

			sv.playing = false;
			
			if (!sv.stopped && sv.dir=='right'){
				startCompanySlide(null,sv.dir);
			}
		})
	}
}

/**
 * Find out what is the next companyID in our sv.logos-Array
 * This logic is based on whether we are scrolling left or right
 * The logic is:
 * - sv.current is the index-number of the leftmost logo
 * - the index-number for the element we want to know is either 
 * 		* sv.current-1 when we are scrolling left
 * 		* sv.current+sv.numLogos+1 when we are scrolling right
 * - If sv.current reaches -1 or sv.current+sv.numLogos reaches a higher number then the total amount of logos
 *   we loop around 
 * 
 * @param blck
 * @param dir
 * @return
 */
function companySliderUpdateCompany(blck, dir)
{
	index = 0;
	// Already add next page
	if (dir=='right') {
		sv.current--;
		if (sv.current<0) sv.current=sv.logos.length-1;
		
		index = sv.current;
	}else{
		sv.current++;
		if (sv.current>=sv.logos.length) sv.current=0;
		
		var index = sv.current + sv.numLogos;
		companySliderDebug('B: '+index);
		if (index>=sv.logos.length) index = index - sv.logos.length;
		companySliderDebug('I: '+index);
	}
		
	setLogoData(blck,sv.logos[index]);
}

function companySliderLeft()
{
	companySliderDebug('mouseclicked left');
	sv.dir = 'left';
	startCompanySlide();
}
function companySliderRight()
{
	companySliderDebug('mouseclicked right');
	sv.dir = 'right';
	startCompanySlide();
}
function companySliderStop()
{
	if (sv.playing) {
		sv.stopped = true;
		//$('#companySlider .logos').pauseAnimation();
	}
}
function companySliderResume()
{
}

function hoverCompanySliderLogo(elm)
{
	var id = $(elm).attr('id').substr(sv.idPrefix.length);
	if (id=='') return false;
	
	var balloon = $('#companySliderDetailsBalloon');
	
	//$('#companySlider .logos').pauseAnimation();
	
	//$('.js_content_data',balloon).hide();
	
	//$('#companySliderDetailsBalloon .js_content_data').html('<center><img src="/images/shared/loadingPopup.gif" width="32" height="32"></center>')
	
	var timestampId = new Date().getTime();
	sv.currentHover = timestampId;
	
	// Load page-data
	$.ajax({ 
		url: "/DCA/companies/getcompanysliderdetails",
		data: "id="+id,
		async: true,
		success: function(html){
			if (timestampId==sv.currentHover) {
				// Add the "page" to the end of the row
				$('#companySliderDetailsBalloon .js_content_data').html(html);
				//$('#companySliderDetailsBalloon .js_content_data').fadeIn();
				companySliderSetBalloonPos(elm);
			}else{
				companySliderDebug('ignored old ajax request data');
			}
		}
	});
}

function companySliderSetBalloonPos(elm)
{
	balloon = $('#companySliderDetailsBalloon').remove();
	$('body').append(balloon);
	
	var elmOffset = $(elm).offset();
	var containerOffset = $('#companySlider').offset();
	companySliderDebug('balloon pos x: '+($('#companySliderDetailsBalloon').outerWidth()/2)+' + '+elmOffset.left+' - '+containerOffset.left);
	companySliderDebug('balloon pos y: '+elmOffset.top+' + '+$(elm).outerHeight()/2 + ' + ' + $('#companySliderDetailsBalloon').outerHeight());
	
	var x = elmOffset.left - $('#companySliderDetailsBalloon').outerWidth()/2 + $(elm).outerWidth()/2; // + $('#companySliderDetailsBalloon').outerWidth()/2;
	var y = parseInt(elmOffset.top) - parseInt($('#companySliderDetailsBalloon').outerHeight());	
		
	$('#companySliderDetailsBalloon').show();
	
	$('#companySliderDetailsBalloon').css('left', x+'px');
	$('#companySliderDetailsBalloon').css('top', y+'px');
	
	$('#companySliderDetailsBalloon').bind('mouseleave', function() {
		companySliderDebug('Balloon left');
		
		companySliderResume();
		
		$('#companySliderDetailsBalloon').hide();
	});
}

function leaveCompanySliderLogo()
{
	$('#companySliderDetailsBalloon').hide();
}

function testMouseOverElement(e,elm)
{	
	if (!$(elm).length) return false;
	
	var elmPos = $(elm).offset();
	
	if (e.pageX > elmPos.left && e.pageY > elmPos.top && e.pageX < (elmPos.left + $(elm).outerWidth()) && e.pageY < (elmPos.top + $(elm).outerHeight())) {
		return true;
	}else{
		return false;
	}
}

function mouseOverCompanySliderPopup(e)
{
	companySliderDebug('Mouse: '+e.pageX+','+e.pageY);
	
	var balloon = $('#companySliderDetailsBalloon:visible');
	if (!$(balloon).length) return false;
	
	var balloonPos = $(balloon).offset();
	
	if (e.pageX > balloonPos.left && e.pageY > balloonPos.top && e.pageX < (balloonPos.left + $(balloon).outerWidth()) && e.pageY < (balloonPos.top + $(balloon).outerHeight())) {
		return true;
	}else{
		return false;
	}
}



/*
jQuery plugin : pause resume animation
Created by Joe Weitzel
BOX Creative LLC
http://plugins.jquery.com/project/Pause-Resume-animation
*/
jQuery.fn.startAnimation = function(  params, duration, easing, callback ) {
	jQuery(this).animate( params, duration, easing, callback );
	var data = { target:this.get(0), params: params, duration: duration, easing: easing, callback: callback,
				startTime: new Date().getTime(), timePlayed: 0, timeRemaining: 0 };
	if( !jQuery.pauseableAnimations ) {
		jQuery.extend({ pauseableAnimations: new Array( data ) });
	} else {
		for( var i in jQuery.pauseableAnimations ) {
			if( jQuery.pauseableAnimations[i].target == this.get(0) ) {
				jQuery.pauseableAnimations[i] = data;
			} else {
				jQuery.pauseableAnimations.push( data );
			};
		};
	};
};
jQuery.fn.pauseAnimation = function() {
	if( jQuery.pauseableAnimations ) {
		for(var i in jQuery.pauseableAnimations ) {
			if( jQuery.pauseableAnimations[i].target == this.get(0) ) {
				jQuery(this).stop();
				var now = new Date().getTime();
				var data = jQuery.pauseableAnimations[i];
				data.timePlayed += ( now - data.startTime );
				data.timeRemaining = data.duration - data.timePlayed;
				if( data.timePlayed > data.duration ) {
					var newArray = new Array();
					for( var p in jQuery.pauseableAnimations ) {
						if( jQuery.pauseableAnimations[p] != data ) newArray.push( jQuery.pauseableAnimations[p] );
					};
					jQuery.pauseableAnimations = newArray.length > 0 ? newArray : null;
					delete newArray;
					return this;
				};
				break;
			};
		};
	};
	return this;
};
jQuery.fn.resumeAnimation = function() {
	if( jQuery.pauseableAnimations ) {
		for(var i in jQuery.pauseableAnimations ) {
			var data = jQuery.pauseableAnimations[i];
			if( data.target == this.get(0) ) {
				this.animate( data.params, data.timeRemaining, data.easing, data.callback );
				data.startTime = new Date().getTime();
				return this;
			};
		};
	};
};

