/* ----- TWITTER ----- */
$(function() {
	$.jTwitter('nedbase', 1, function(data) {
		var tweet = data[0].text;
		var timestr = data[0].created_at;

		$("#footer .twitter h3").html(linkify_plain(tweet));
		$("#footer .twitter .time").html(relative_time(timestr));

		Cufon.replace('#footer .twitter h3');
	});
});

/* ----- FONT ----- */
Cufon.replace('#nav a.lvl1', {
	hover: true
});
Cufon.replace('h1, h2, #footer .telnr');
Cufon.replace('.quote, .quoteBlue blockquote p, .flow h3');

lastLayer = 'ajaxSlideshow';
var heights = {
	'ajaxContact':541,
	'ajaxLogin':200,
	'ajaxSlideshow':280,
	'ajaxBigvideo':540
};



function fadeFromTo(lastLayer,objId){
	if(lastLayer !== objId) {

		//pause or resume flashslideshow
		if(objId == 'ajaxSlideshow') {
			resumeSlideshow();
		} else {
			pauseSlideshow();
		}

		tweenStart(lastLayer);

		velocity = 3;

		objHeight = heights[objId];
		lastHeight = heights[lastLayer];
		heightDiff = (objHeight - lastHeight) < 0 ? (objHeight - lastHeight) * -1 : (objHeight - lastHeight);
		speed = heightDiff * velocity;
		objHeight = heights[objId] + 'px';
		lastHeight = heights[lastLayer] + 'px';

//console.log('heightDiff ' + heightDiff + ', speed: ' + speed );
//console.log('Fade to ' + objId + ' from ' + lastLayer);

		if(objHeight > lastHeight) {
			fadeTween(objId,objHeight,lastLayer,speed,true);
		} else {
			resizeContainer(objId,objHeight,lastLayer,speed,true);
		}

	} else {
//console.log('Same layer, ignore');
	}

}


function fadeTween(objId,objHeight,lastLayer,speed,continueResize){
//console.log('fadein ' + objId);
	$('#'+lastLayer+'Html').css({'z-index':'99'});
	$('#'+objId+'Html').css({'z-index':'100'});

	// Fade-in objId
	$('#'+objId+'Html').css({'opacity':'0'});
	$('#'+objId+'Html').animate({'opacity':'1'}, 1000, 'swing', function(){
		if(continueResize) {
//console.log('callback: start resize: '+objId+' = '+objHeight);
			resizeContainer(objId,objHeight,lastLayer,speed,false);
		} else {
			tweenFinish(objId);
		}
		// Set lastObject to back
		$('#'+lastLayer+'Html').css({'opacity':'0'});
	});



}


function resizeContainer(objId,objHeight,lastLayer,speed,continueFade) {
//console.log('resize to ' + objId);
	// Resize container DIV
	$('#visualHolder')
		.stop().animate({'height':objHeight}, speed, 'swing', function(){

			if(continueFade) {
//console.log('callback: start fade');
				fadeTween(objId,objHeight,lastLayer,speed,false)
			} else {
				tweenFinish(objId);
			}
	});
}


function tweenFinish(objId){
	switch(objId){
		case 'ajaxContact':
			$('#ajaxContactHtml').css({'filter':'none'});
			if($("#directionsPanel").length) {
//console.log("ROUTE");
			}
			else {
//console.log("CONTACT");
				$('#formContact').animate({'height':'170px'});
				codeAddress('Molenwater 79, 4331SE, MIDDELBURG, NEDERLAND', "marker-nedbase");
			}
			break;
	}

}


function tweenStart(lastLayer){
	switch(lastLayer){
		case 'ajaxContact':
			$('#formContact').animate({'height':'49px'});
			break;
		case 'ajaxBigvideo':
			bvPlayer.sendEvent('STOP');
			break;
	}
}


/*initiate big video player -> called by flash*/
var bvPlayer = null;
function playerReady(thePlayer) {
	bvPlayer = window.document[thePlayer.id];

	bvPlayer.addModelListener("STATE","stateTracker");
}
	function stateTracker(obj) {
		switch(obj.newstate) {
			case 'COMPLETED':
				resumeSlideshow();
				break;
		}
	};

/* calculate relative time (for tweets) */
function relative_time(time_value) {
	var d = new Date(time_value.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/, "$1 $2 $4 $3 UTC"));
	var parsed_date = Date.parse(d);

	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);

	if(delta < 60) {
		return 'Minder dan een minuut geleden';
	} else if(delta < 120) {
		return 'Ongeveer een minuut geleden';
	} else if(delta < (45*60)) {
		return 'Ongeveer ' + (parseInt(delta / 60)).toString() + ' minuten geleden';
	} else if(delta < (90*60)) {
			return 'Ongeveer een uur geleden';
	} else if(delta < (24*60*60)) {
		return 'Ongeveer ' + (parseInt(delta / 3600)).toString() + ' uur geleden';
	} else if(delta < (48*60*60)) {
		return 'Ongeveer een dag geleden';
	} else {
		return 'Ongeveer ' + (parseInt(delta / 86400)).toString() + ' dagen geleden';
	}
}


function init() {

	/* ----- ADD ".js" CLASS TO BODY ----- */
	$('body').addClass('js');

	/*
	$('.quoteBlue blockquote').each(function(){
		$(this).css({'opacity':'0.1'});
		$(this).animate({'opacity':'1.0'}, 1000);
	});
	*/

	////////// GOOGLEMAPS
	initGoogleMap('ajaxContactHtml');
	//$('#ajaxContactHtml').css({'opacity':'0', 'z-index':'0'});
//console.log('GMAP: '+$('#ajaxContactHtml').css('opacity'));
//console.log("----- INIT -----");

	/* ----- LOAD CONTENT AND ANIMATE TO REPLACE VISUAL ----- */
	$('#meta a.ajax').each(function(){

//console.log("A ID: "+$(this).attr('id'));

		var objId = $(this).attr('id');

		var aniHeight = heights[objId];

		if (objId != 'ajaxSlideshow'){
			$('#'+objId+'Html').css({'opacity':'0'});
		}
		// Bind onCLICK to links
		$(this).bind('click', function() {

//console.log(this);

			// Href
			var href = $(this).attr('href');

			// Active class
			$('#meta a').removeClass('active');
			$(this).addClass('active');

			// Check if DIV exists
			if (!$('#'+objId+'Html').length) {
				// Create new DIV
				$('<div id="'+objId+'Html" class="ajaxAdded2"></div>').appendTo('#visualHolder');
				if (objId == 'ajaxLogin') {
					$.ajax({url: href,
						success: function(data){
							$('#'+objId+'Html').html(data);
							Cufon.replace('h1, h2');
						}
					});
				}
			}

			// Add the GoogleMaps content
			if (objId == 'ajaxContact' && !$('#formContact').length) {
				// Add Contact form
//console.log('create div subcontactform');
				$('<div id="formContact"></div>').css('height','49px').appendTo('#ajaxContactHtml');
				$.get(href, {'ajax':'1'}, function(data){
					$('#formContact').html(data);
			   		Cufon.replace('h1, h2');
			 	});
			}


			// fade in and out
			fadeFromTo(lastLayer,objId,aniHeight);

			lastLayer = objId;

			// Prevent browser from following links
			return false;
		});
	});

	initModal();


	/* ---- FORM SUBMIT DISABLE ---- */
	$('#offerte-aanvraag').bind('submit', function(){
		//$('#FB_Send_Loader').attr("disabled", true);
		$('#FB_Send_Loader').parent().append('<p><br>Bezig met verzenden...<img src="/image/loading.gif"></p>');
	});

	/* ----- LOAD FLASH ------ */
	/* see website.php	*/


	/* ----- SLIDE DOWN NAVIGATION ----- */
	$('#navigation').css('height', '34px');
	$('#nav > li').hover(
		function(){
			var ulHeight = 34;
			ulHeight = ulHeight + 10; // Extra padding bottom
			var ulHeight = ulHeight + $(this).find('ul').height();
			if (ulHeight < 34) {ulHeight = 34;}
			$('#navigation')
				.stop()
				.animate({'height':ulHeight+'px'}, 500, 'swing');
			// IE 6 only
			if (jQuery.browser.msie && jQuery.browser.version == "6.0") {
				$(this).height(ulHeight+'px');
			}
		},
		function(){
			$('#navigation')
				.stop()
				.animate({'height':'34px'}, 500, 'swing');
			// IE 6 only
			if (jQuery.browser.msie && jQuery.browser.version == "6.0") {
				$(this).height('auto');
			}
		}
	);

	/** ----- CONTENT SLIDER ----- */

	function initBannerSlideshow() {
	    $('.contentBanner .slides').each(function(){
		    $navId = '#' + $(this).attr('id') + 'Nav';
		    $(this).cycle({
			    fx: 'fade',
			    timeout: 3000,
			    pager: $navId
		    });
	    });
	}
	initBannerSlideshow();

	/* ----- PORTFOLIO SELECTION ----- */

	// Hide submit button
	$('#formPortfolio button').hide();

	// Loop all checkboxes
	$('#formPortfolio input:checkbox').each(function(){
		// Pretty Checkboxes
		//$(this).css('width', '0px');
		$('<span class="fakecheckbox"></span>').insertAfter($(this));
		// Add onChange event
		$(this).bind('change', function(){
			var uri = '/portfolio.htm?';
			var uriParam = '';
			var showAll = false;
			// Uncheck "Show all" or all others
			if ($(this).attr('id') == 'branches_0') {
				$('#formPortfolio input:checkbox').attr('checked', false).parent().removeClass('active');
				$(this).attr('checked', true);
			}
			else {
				$('#branches_0').attr('checked', false).parent().removeClass('active');
			}
			// Loop checked items
			$('#formPortfolio input:checked').each(function(){
				if ($(this).attr('id') == 'branches_0') {
					var showAll = true;
				}
				else {
					if(uriParam != ''){
						uriParam += '&';
					}
					uriParam += $(this).attr('name') + '=1';
				}
			});
			// Toggle CSS class "active"
			$(this).parent().toggleClass('active');
			// AJAX - Load data of checkboxes
			if (showAll === false) {uri = uri + uriParam;}

			$.ajax({
				beforeSend: function() {
					$('<div class="ajaxLoader"><p><span></span><img src="/image/colorbox/loading.gif" alt="Laden..." style="display:block;margin:10px auto;"></p></div>').appendTo('#portfolio');
				},
				url: uri,
				success: function(data) {
					$('#portfolio').html(data);
					$('.item a').colorbox({
						current: "",
						previous: "<span></span>Vorige project",
						next: "Volgende project<span></span>",
						onComplete: function(){
//console.log("onComplete 310");
						    initBannerSlideshow();
							Cufon.replace("h1");
						},
						onLoad: function(){
//console.log("onLoad 310");
							$('.contentBanner .slides').each(function(){
								$navId = '#' + $(this).attr('id') + 'Nav';
								$(this).cycle('destroy');
							});
						},
						onCleanup: function(){
//console.log("onCleanup 198");
							$('.contentBanner .slides').each(function(){
//console.log($(this));
								$navId = '#' + $(this).attr('id') + 'Nav';
								$(this).cycle('destroy');
							});
						}
					});
				}
			});
		});
	});


	// AJAX - Load data of text links
	$('#formPortfolio a').click(function(){
		var uri = $(this).attr('href');

		// Uncheck all items
		$('#formPortfolio input:checkbox').attr('checked', false).parent().removeClass('active');
		if ($(this).attr('id') == 'branchesAll') {
			$('#branches_0').attr('checked', true).parent().addClass('active');
		}
		// AJAX - Load data of link
		$.ajax({
			beforeSend: function() {
				$('<div class="ajaxLoader"><p><span></span><img src="/image/colorbox/loading.gif" alt="Laden..." style="display:block;margin:10px auto;"></p></div>').appendTo('#portfolio');
			},
			url: uri,
			success: function(data) {
				$('#portfolio').html(data);
				Cufon.replace("h2");
				$('.lightbox').colorbox({
					current: "",
					previous: "<span></span>Vorige project",
					next: "Volgende project<span></span>",
					onComplete: function(){
//console.log("onComplete 349");
						initBannerSlideshow();
						Cufon.replace("h1");
					},
					onLoad: function(){
//console.log("onLoad 349");
						$('.contentBanner .slides').each(function(){
							$navId = '#' + $(this).attr('id') + 'Nav';
							$(this).cycle('destroy');
						});
					},
					onCleanup: function(){
//console.log("onCleanup 198");
						$('.contentBanner .slides').each(function(){
//console.log($(this));
							$navId = '#' + $(this).attr('id') + 'Nav';
							$(this).cycle('destroy');
						});
					}
				});
			}
		});
		return false;
	});


	/* ----- ACCORDION ----- */

	$('ul.accordion').each(function(){
		$(this).find('.content').wrapInner('<div class="text" />');
		$(this).find('p.title').bind('click', function(){
			var obj = $(this).nextAll('.content');
			var h = obj.find('.text').height();
			if (obj.height() == 0) {
				$(this).parent().addClass('open');
				obj.animate({'height':h+'px'});
			}
			else {
				$(this).parent().removeClass('open');
				obj.animate({'height':'0px'});
			}
		});
		//$(this).find('.content').css('height', '0px');
		var objOpen = $(this).find('li').first();
		var nh = objOpen.find('.text').height();
		objOpen.addClass('open');
		objOpen.find('.content').animate({'height':nh+'px'});
	});

	$('#contactHeader, #routeHeader').live('click', function(){
		if ($('#formContact').height() != 170) {
			$('#formContact').animate({'height':'170px'});
			$('#buttonUpDown').removeClass('up');
			$('#buttonUpDown').fadeIn(300).addClass('down');
		}
		else {
			$('#formContact').animate({'height':'49px'});
			$('#buttonUpDown').removeClass('down');
			$('#buttonUpDown').fadeIn(300).addClass('up');
		}
		return false;
	});


	/* NEDBASE MOVIE POPUP*/

	$('#sidebarbanner12 a, body:not(.ios) .coll .play-movie a').colorbox({
		width: 702,
		height: 535
	});

	/* SOCIALSHARE */
	if ($(window).width() <= 1024) { $('#socialSharing').css('display', 'none'); }
	$(window).resize(function() {
		var resized = false;
		if($(window).width() <= 1024) {
			resized = true;
			$('#socialSharing').hide('slow');
			console.log(resized);
		} else if ($(window).width() > 1024){
			$('#socialSharing').show('slow');
			resized = false;
		}
	});

	 $('#socialSharing a').bind("mouseenter",function() {
		var element = $(this);
		$(this).removeAttr('isOpen');
		setTimeout(function(){
			if($(element).attr('isOpen')){
				return;
			}
			$(this).attr('isOpen', true);
			switch($(element).attr('id')){
				case 'sFacebook':
					$(element).stop().animate({backgroundColor:"#5267b4"},50);
					$(element).css("background-image", "url('/image/social/fg-hover.png')");
					setTimeout(function() { $(element).text('Facebook'); }, 100);
					break;

				case 'sTwitter':
					$(element).stop().animate({backgroundColor:"#00b4df"},50);
					$(element).css("background-image", "url('/image/social/twitter-hover.png')");
					setTimeout(function() { $(element).text('Twitter'); }, 100);
					break;

				case 'sGoogle':
					$(element).stop().animate({backgroundColor:"#4fb73c"},50);
					$(element).css("background-image", "url('/image/social/gp-hover.png')");
					setTimeout(function() { $(element).text('Google+'); }, 100);
					break;
			}
//			$(element).css("padding-left", "45px");
			$(element).animate({width:"150px"},75);
		}, 95);
	 });
	 $('#socialSharing li').bind("mouseout",function() {
		var element = $(this).find(">:first-child");
		$(element).attr('isOpen', true);
		$(element).stop().animate({width:"32px"},150, function() {
			$(this).text('');
			switch($(this).attr('id')){
				case 'sFacebook':
					$(this).css("background-image", "url('/image/social/fg.png')");
					break;

				case 'sTwitter':
					$(this).css("background-image", "url('/image/social/twitter.png')");
					break;

				case 'sGoogle':
					$(this).css("background-image", "url('/image/social/gp.png')");
					break;
			}
			$(element).animate({backgroundColor:"#cecece"},50, function() {$(this).find(">:first-child").removeAttr('isOpen');});
		});
	 });

}


var isIE = false;

/* ----- ON DOCUMENT READY ----- */
$(document).ready(function(){

	if (!isIE) {
		init();
	}

});
