// -----------------------
// --- jQuery settings ---
// -----------------------
jQuery.fx.interval = 33;
// -----------------------------
// --- Document ready events ---
// -----------------------------
$(document).ready(function(){
	// --- Google Maps API ---
	var gmtag = document.createElement("script");
	gmtag.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
	document.body.appendChild(gmtag);
	// --- jScrollPane ---
	// createScrollbars();
	// --- Supersize ---
	var randNum = randStart();
	$.supersized({
		slideshow			:	1,
		autoplay			:	1,
		start_slide			:	2,
		slide_interval      :   5000,
		slide_links			: 	0,
		transition			: 	1, 
		transition_speed	:	750,
		performance			:	2,
		random				:	0,
		slides 				:  	[
							{image : 'images/bg_img/1.jpg', title : ''},
							{image : 'images/bg_img/2.jpg', title : ''}, 
							{image : 'images/bg_img/3.jpg', title : ''},  
							{image : 'images/bg_img/4.jpg', title : ''},   
							{image : 'images/bg_img/5.jpg', title : ''}, 
							{image : 'images/bg_img/6.jpg', title : ''},  
							{image : 'images/bg_img/7.jpg', title : ''}, 
							{image : 'images/bg_img/8.jpg', title : ''}, 
							{image : 'images/bg_img/9.jpg', title : ''},
							{image : 'images/bg_img/10.jpg', title : ''},
							{image : 'images/bg_img/11.jpg', title : ''},
							{image : 'images/bg_img/12.jpg', title : ''}
								]					
	});
	// --- Switch mouseover ---
	$('#switch').mouseover(function() {
		$(this).animate({'width': 30}, 50, 'easeInOutExpo');
	}).mouseout(function(){
		$(this).animate({'width': 27}, 50, 'easeInOutExpo');
	});
});
// ----------------------------
// --- Window resize events ---
// ----------------------------
var wait = false;
$(window).resize(function(){
	$('.scrollReady').removeClass('scrollReady');
	if(wait !== false)
		clearTimeout(wait);
		wait = setTimeout(resizeFinished, 500);
});
function resizeFinished() {
	createScrollbars();
}
// -----------------
// --- Functions ---
// -----------------
// --- Body toggle ---
$('.switch').click(function() {
	// Body is closed and a detail panel is not open
	if ( $('#page-body.closed').length && (!$('.detail-panel.open').length) ) {
		openBody();
	// Body is open and a detail panel is closed OR body is closed and no detail panel exists...
	} else if ( $('#page-body.open').length && (!$('.detail-panel.open').length) ) {
		closeBody();
	// Body is open and a detail panel is open
	} else if ( $('#page-body.open').length && $('.detail-panel.open').length ) {
		destroyDyn();
		$('.detail-panel.open').animate({'left':'-340'}, 500, 'easeInOutExpo', function(){
			closeBody()	
		}).removeClass('open').addClass('closed');
		$('#switch').css({'width':'27'}).animate({'left':'330'}, 500, 'easeInOutExpo');
	}
});
// --- Detail toggle ---
$('.detail li').live('click', function(){
	var panel = $(this).attr('class');
	if($('.detail-panel.'+panel).hasClass('closed')) {
		openDetail(panel);
	} else {
		closeDetail();
	}
});
// ----------------------
// --- Ajax functions ---
// ----------------------
$('nav a').click(function() {
	var newPage = $(this).parent().attr('id');
	if(!($('body').hasClass(newPage))) {
		destroyDyn();
		$('.selected').removeClass('selected');
		$('#'+newPage).addClass('selected');
		$('body').removeClass().addClass(newPage);
		$.get(newPage+'.html', function(data) {
	    	var mainContent = $(data).filter('#page-body').find('.content'); 	
	    	var detailContent = $(data).filter('#page-detail').find('.detail-panel');
			var h1Title = $(data).find('#index a').text();
			if (h1Title != $('h1').text()) {
				$('h1, nav li:first-child a').animate({'opacity': 0}, 300, function() {
					$(this).text(h1Title).queue(function() {
						$(this).animate({'opacity': 1}, 300).dequeue();
					});
				});
			}		
			$('#page-body .content').wrap('<div class="tmp" />').queue(function() {
				$('#page-body .tmp').animate({'opacity': 0}, 300, function() {
					$('#page-body .tmp').html(mainContent);
				});
				loadCallback(newPage);		
				$('#page-body .tmp').animate({'opacity': 1}, 300, function() {
					$('#page-body .content').unwrap();
					if ($('#page-body').hasClass('closed')) {
						openBody();
					} else {
						bodyCallback();
					}
				});
				$(this).dequeue();
			});
			if ($('.detail-panel.open').length) {
				$('.detail-panel.open').animate({'left':'-340px'}, 500, 'easeInOutExpo', function() {
					$('#page-detail').html(detailContent);
				}).removeClass('open').addClass('closed');
				$('#switch').animate({'left':'330'}, 500, 'easeInOutExpo');	
			} else {
				$('#page-detail').html(detailContent);
			}
		}, 'html');
	} else if ($('#page-body').hasClass('closed')) {
		openBody();
	}
	return false;
});
// -----------------------
// --- Panel functions ---
// -----------------------
function openBody() {
	$('#page-body').animate({'left':'0'}, 500, 'easeInOutExpo', function() {
		bodyCallback();
	}).removeClass('closed').addClass('open');
	$('#page-aside').animate({'right':'0'}, 500, 'easeInOutExpo');
	$('#page-detail').animate({'left':'0'}, 500, 'easeInOutExpo');
	$('#super-nav').fadeOut(500, 'easeInOutExpo');
	$('#switch').css({'background-position':'right bottom', 'width':'27'});
	api.options.slideshow = 0;
}
function closeBody() {
	$('#page-body').animate({'left':'-330'}, 500, 'easeInOutExpo').removeClass('open').addClass('closed');
	$('#page-aside').animate({'right':'-230'}, 500, 'easeInOutExpo');	
	$('#page-detail').animate({'left':'-330'}, 500, 'easeInOutExpo');
	$('#super-nav').fadeIn(500, 'easeInOutExpo');
	$('#switch').css({'background-position':'right top', 'width':'27'});
	api.options.slideshow = 1;
}
function openDetail(panel) {
	if ($('.detail-panel.open').length) {
		$('.detail-panel.open').animate({'left':'-340'}, 500, 'easeInOutExpo', function() {
			$('.detail-panel.'+panel).animate({'left':'330'}, 500, 'easeInOutExpo', function() {
				panelCallback(panel);
			}).removeClass('closed').addClass('open');
			$('#switch').animate({'left':'1000'}, 500, 'easeInOutExpo');
		}).removeClass('open').addClass('closed');
		$('#switch').animate({'left':'330'}, 500, 'easeInOutExpo');
	} else {
		$('.detail-panel.'+panel).animate({'left':'330'}, 500, 'easeInOutExpo', function() {
			panelCallback(panel);
		}).removeClass('closed').addClass('open');
		$('#switch').animate({'left':'1000'}, 500, 'easeInOutExpo');
	}
}
function closeDetail() {
	destroyDyn();
	$('.detail-panel.open').animate({'left':'-340'}, 500, 'easeInOutExpo').removeClass('open').addClass('closed');
	$('#switch').animate({'left':'330'}, 500, 'easeInOutExpo');
}
// ---------------------------------
// --- Body load started actions ---
// ---------------------------------
// --- Runs after the ajax has
// --- completed but before the
// --- content has reappeared
// --- passes the name of the new
// --- page about to show
// ---------------------------------
function loadCallback(newPage) {
	switch(newPage) {
		case 'index':
			// --- var randNum = randStart();
			// --- getSupersized(randNum);
			getSupersized(2);
			break;
		case 'information':
			var randNum = randStart();
			getSupersized(randNum);
			break;
		case 'pricelist':
			var randNum = randStart();
			getSupersized(randNum);
			break;
		case 'editions':
			var randNum = randStart();
			getSupersized(randNum);
			break;
		case 'partners':
			var randNum = randStart();
			getSupersized(randNum);
			break;
		case 'contact':
			getSupersized(6);
			break;
	}
	_gaq.push(['_trackEvent', 'Page', 'Load', newPage]);
}
// ------------------------------------
// --- Body loaded complete actions ---
// ------------------------------------
// --- Runs after the ajax has
// --- completed and body has opened
// --- and if you open the body with
// --- the switch
// ------------------------------------
// --- 1. Page specific actions
// --- 2. Reinitialise the form
// ------------------------------------
function bodyCallback() {
	createScrollbars();
	// --- Page specific actions ---
	
	if ($('body').attr('class') == 'editions') {
		openDetail('092011');
	}
	
	if ($('body').attr('class') == 'partners') {
		openDetail('partners');		
	} 

	if ($('body').attr('class') == 'contact') {
		openDetail('contact');		
	} 

	else if ($('body').attr('class') == 'first') {
		_gaq.push(['_trackEvent', 'Body panel', 'Open', 'via switch']);
	}
	
	// --- Reinitialise the form ---
	if ($('#subForm').length) {
		// --- Autoclear fields ---
		$(".required").focus(function() {
			if( this.value == this.defaultValue ) {
				this.value = "";
			}
		}).blur(function() {
			if( !this.value.length ) {
				this.value = this.defaultValue;
			}
		});
	}
}
// --------------------------
// --- Load panel content ---
// --------------------------
// --- Runs after the detail 
// --- panel has opened
// --- passes the panel name
// --------------------------
function panelCallback(panel) {
	createScrollbars();
	embedMap();
	embedVideo();
	_gaq.push(['_trackEvent', 'Panel', 'Open', panel]);
}
// --------------------------
// --- Create jScrollPane ---
// --------------------------
function createScrollbars() {
	$('.open .scrollable:not(.scrollReady)').each(function() {
		$(this).jScrollPane({
			verticalGutter: 12,
			verticalDragMinHeight: 54
		}).data('jsp');
		$(this).addClass('scrollReady');
	});
}
// --------------------------
// --- Supersized api -------
// --------------------------
function getSupersized(slide) {
	api.options.slideshow = 1;
	api.options.transition = 1;
	api.options.transition_speed = 750;
	api.goTo(slide);
	api.options.transition_speed = 0;
	api.options.transition = 0;
	api.options.slideshow = 0;
}
// ------------------------------
// --- Random supersize image ---
// ------------------------------
function randStart(){
    var excluded = '7, 12';
    var total = 12;	
    var result = Math.floor(Math.random()*total);
    for(i=0; i <= total; i++) {
        if(excluded.search(result) != -1){
            return randStart({exclude: excluded, images: total});
        }
    }
    return result;
} 
// -------------------
// --- Google maps ---
// -------------------
function initialize() {
}
function embedMap() {
	if ( $('#mapbox').length ) {
		var latlng = new google.maps.LatLng(51.013921, 3.648484);
		var mapOptions = {
			backgroundColor: '#333333',
			zoom: 14,
			center: latlng,
			disableDefaultUI: false,
			panControl: false,
			mapTypeControl: false,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("mapbox"),mapOptions);
		var image = new google.maps.MarkerImage('images/map-marker.png',
			new google.maps.Size(25, 38),
			new google.maps.Point(0, 0));
		var shadow = new google.maps.MarkerImage('images/map-marker-shadow.png',
			new google.maps.Size(57, 34),
			new google.maps.Point(0, 0));
		setTimeout(function() {
			var marker = new google.maps.Marker({
				map: map,
				draggable: false,
				animation: google.maps.Animation.DROP,
				position: latlng,
				icon: image,
				shadow: shadow				
			});	
			google.maps.event.addListener(marker, 'click', getMap);	
		}, 1000);
		$('#mapbox').addClass('dynCont');
	}
}
function getMap() {
	var load = window.open('http://maps.google.com/maps?q=Carrera+Motors+nv,+Kortrijksesteenweg,+Sint-Martens-Latem,+Belgi%C3%AB&hl=en&ie=UTF8&ll=51.013505,3.649054&spn=0.002923,0.008234&sll=51.013147,3.652976&sspn=0.011691,0.032938&vpsrc=6&hq=Carrera+Motors+nv,&hnear=Kortrijksesteenweg,+9830+Sint-Martens-Latem,+Oost-Vlaanderen,+Vlaams+Gewest,+Belgium&t=h&z=18','','');
}

// ---------------------
// --- YouTube video ---
// ---------------------
function youtubeid(url) {	
	var ytid = url.match("[\\?&]v=([^&#]*)");
	ytid = ytid[1];
	return ytid;
};
function embedVideo() {
	if ( $('#ytbox').length ) {
		var thisHref = $('#ytbox').attr('title');
		if (thisHref.indexOf('http://www.youtube.com') >= 0) {
		    youtubeid(thisHref);
		} else if (thisHref.indexOf('http://youtu.be') >= 0) {
		    var ytid = thisHref.substr(thisHref.lastIndexOf("/") + 1);
		}
		player = new YT.Player('ytbox', {
		    height: '316',
			width: '510',
			videoId: ytid
		});
		$('#ytbox').addClass('dynCont');
	}
}

// ----------------------------
// --- Destroy maps/YouTube ---
// ----------------------------
function destroyDyn() {
	$('.ie8 .dynCont').css('opacity', 0);
	$('.dynCont').children().remove();
	if($('#ytbox.dynCont').length){
		player.destroy();
	}
}
