//aplication
var vote = 3;
var currentHash = 'start';
var stopAnimate = false;
var currentStep = 'step1';


$(function() {
	
	
	
	if($('.facebook').length > 0){
		$('body').css('overflow', 'hidden');
	}
	
	if(app_daysleft(_appVars.date) == 0){
		$('#app_wrapper').addClass('active');	
	}
	
	$('.play').click(function(){
		ga_track('play_video');
		var id = $(this).attr('id');
		$('iframe').hide();
		$('.popup').fadeIn('fast', function(){$(this).find('iframe').attr('src','http://www.youtube.com/embed/'+id).show()});
		return false;
	});
	
	$('.videoLink').click(function(){
		ga_track('play_video')
		var id = $(this).attr('id');
		$('iframe').hide();
		$('.popup').fadeIn('fast', function(){$(this).find('iframe').attr('src','http://www.youtube.com/embed/'+id).show()});
		return false;
	});
	
	$('.close_popup').click(function(){
		ga_track('close_popup')
		$(this).parent().parent().find('iframe').attr('src', '');
		$('.popup').hide();
		return false;
	});
	
	$('.close_overlay').click(function(){
		ga_track('close_popup')
		$('.overlay').hide();
		return false;
	});
	
	/*$('.left_side .share').click(function(){
		
		if($(this).attr('name') == 'facebook'){
			fb_post(_appVars.description, 'thumb');
		}else{
			app_share($(this).attr('name'), _appVars.description);	
		}
		return false;
	});*/
	
	$('#step3 .share').click(function(){
		voted = vote == 1 ? 'Indian Curry Style' : 'Bicky Crisp';
		thumb = vote == 1 ? 'thumb-i' : 'thumb-b';
		
		if($(this).attr('name') == 'facebook'){
			fb_post(_appVars.share.replace('%smaak%', voted), thumb)
		}else{
			app_share($(this).attr('name'), _appVars.share.replace('%smaak%', voted));	
		}
		return false;
	});
	
	
	
	$('#submit_vragen').click(function(){
		
			ga_track('questions_submit')	
		
		if($('#hguid').attr('value') == ''){
				$('.message').find('p').html(_appVars.error_voted);
				$('.overlay').show();
				return false;
			}else{
				if($('#q2').val() == '' || getRadioValue('q1') == ''){
					ga_track('question_error_required');
					$('.message').find('p').html(_appVars.error_question);
					$('.overlay').show();
					return false;
				}else if(isNaN($('#q2').val())){
					ga_track('question_error_number');
					$('.message').find('p').html(_appVars.error_number);
					$('.overlay').show();
					return false;
				}else{
					submitQuestions();	
				}	
			}		
	});
	
	$('.date').focus(function(){
		if($(this).attr('name') == $(this).val())$(this).val('');
	});
	
	$('.date').focusout(function(){
		if($(this).val() == '') $(this).val($(this).attr('name'));
	});
	
	
	
	
	$('#submit_gegevens').click(function(){
		
		ga_track('form_submit')
			var regemail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		
			if($('#hguid').attr('value') == ''){
				$('.message').find('p').html(_appVars.error_voted);
				$('.overlay').show();
				return false;
			}else if($("#gebdatumd").val() == "" || $("#gebdatumm").val() == "" || $("#gebdatumy").val() == "" || $("#voornaam").val() == "" ||  $("#email").val() == "" ||  $("#achternaam").val() == ""){
				ga_track('form_error_required');
				$('.message').find('p').html(_appVars.error_required);
				$('.overlay').show();
				return false;
			}else if (!regemail.test($("#email").val())){
				ga_track('form_error_email');
				$('.message').find('p').html(_appVars.error_email);
				$('.overlay').show();
				return false;
			}else if	(!checkDate($("#gebdatumd").val(), $("#gebdatumm").val(), $("#gebdatumy").val())){
				ga_track('form_error_date');
				$('.message').find('p').html(_appVars.error_date);
				$('.overlay').show();
				return false;
			}else if	(!$('#actievw').is(':checked')){
				ga_track('form_error_terms');
				$('.message').find('p').html(_appVars.error_voorwaarden);
				$('.overlay').show();
				return false;
			}else{
				 
				submitForm();
			}
	});
	
	
	app_loadflash();
	

	/*
	ga_trackLiked('check');
	ga_clickout();
	*/

});


$.History.bind(function(hash){
	
	ga_track(hash)
	
	stopAnimate = true;
	var id = "#"+hash;
	var page = $(id);
	
	//console.log($.cookie('smaak'+_appVars.template));
	
	if(id == '#' || page.length == 0)id = '#start';
	
	if($.cookie('smaak'+_appVars.template) != null && hash == 'vote_indian' && $('#hguid').val() == '' || $.cookie('smaak'+_appVars.template) != null && hash == 'vote_bicky' && $('#hguid').val() == ''){
					$('#start .message').find('p').html(_appVars.error_voted);
					$('#start .overlay').show();
					
					ga_track('already_voted');
						
					if(currentHash != 'start'){
						hash = 'start';
						id = '#start';
						page = $(id);
					}else{
						return false;	
					}
						
	}else if(vote == 1 && hash == 'start' || vote == 0 && hash == 'start'  ){
		
		hash = currentStep
		
		voted = vote == 1 ? 'vote_indian' : 'vote_bicky';
		
		if(currentStep == 'step2' || currentStep == 'step3'){
				switch(voted){
				case 'vote_indian':
						$('.nav .active').removeClass('active');
						$('.nav .a a').addClass('active');
						
						app_hide(['.page','#form .header h2','#step2','#step3','#bicky', '#klma','#klmb','#klmc']);
						app_show(['#klma','.car img','#title_indian','#step1','#indian']);
						app_fadeIn('#form');
				break;	
				case 'vote_bicky':
						$('.nav .active').removeClass('active');
						$('.nav .a a').addClass('active');
				
						app_hide(['.page','#form .header h2','#step2','#step3','#indian','#klma','#klmb','#klmc']);
						app_show(['#klma','.car img','#title_bicky','#step1','#bicky']);
						app_fadeIn('#form');
				break;
			}
		}else{
			hash = voted;
		}
		
		id = '#'+hash;
		page = $(id);
	}
	
	currentHash = hash;
	
	switch(hash){
		case 'vote_indian':
				$('.nav .active').removeClass('active');
				$('.nav .a a').addClass('active');
				if(vote == 3){
					submitSmaak(1)
				}
				$('#app_wrapper').addClass('voted');
				app_hide(['.page','#form .header h2','#step2','#step3','#bicky', '#klma','#klmb','#klmc']);
				app_show(['#klma','.car img','#title_indian','#step1','#indian']);
				app_fadeIn('#form');
		break;	
		case 'vote_bicky':
				$('.nav .active').removeClass('active');
				$('.nav .a a').addClass('active');
				
				if(vote == 3){
					submitSmaak(0)
				}
				$('#app_wrapper').addClass('voted');
				app_hide(['.page','#form .header h2','#step2','#step3','#indian','#klma','#klmb','#klmc']);
				app_show(['#klma','.car img','#title_bicky','#step1','#bicky']);
				app_fadeIn('#form');
		break;
		case 'prijzen':
				$('.nav .active').removeClass('active');
				$('.nav .b a').addClass('active');
				$('#app_wrapper').addClass('voted');
				app_hide(['.page','.car img','#klmd','#klme']);
				if($.cookie('smaak'+_appVars.template) != null){
					$('.active #prijzen .submit').hide();
					$('.active #klme').show()
				}else{
					$('.active #prijzen .submit').show();
					$('.active #klmd').show()
				}	
				app_fadeIn(id);
		break;
		case 'step2':
				currentStep = 'step2'
				$('.nav .active').removeClass('active');
				$('.nav .a a').addClass('active');
				app_hide(['#form .block .textblock', '#klma']);
				app_show(['#klmb'])
				app_fadeIn(id);
		break;
		case 'step3' :
				currentStep = 'step3'
				$('.nav .active').removeClass('active');
				$('.nav .a a').addClass('active');
				app_hide(['#form .block .textblock','#form .header h2', '#klmb']);
				app_show(['#title_bedankt', '#klmc'])
				app_fadeIn(id);
				
				if(_appVars.template == 'website' && _appVars.locale == 'nl_BE'){
					 var axel = Math.random() + "";
					var a = axel * 10000000000000;
					$('body').append('<iframe src="http://fls.doubleclick.net/activityi;src=2202441;type=11101952;cat=votin631;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');	 
				}else if(_appVars.template == 'website' && _appVars.locale == 'fr_BE'){
					var axel = Math.random() + "";
					var a = axel * 10000000000000;
					$('body').append('<iframe src="http://fls.doubleclick.net/activityi;src=2202441;type=11101952;cat=votin674;ord=' + a + '?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
				}
				
		break;
		case 'finalisten':
				$('.nav .active').removeClass('active');
				$('.nav .c a').addClass('active');
				$('#app_wrapper').addClass('voted');
				if($.cookie('smaak'+_appVars.template) != null ){
					$('.active #finalisten .vote').hide();
				}else{
					$('.active #finalisten .vote').show();
				}
				app_hide(['.page','.klembord']);
				app_show(['.car img']);
				app_fadeIn(id);
		break;
		case 'faq':
				$('.nav .active').removeClass('active');
				$('#app_wrapper').addClass('voted');
				app_hide(['.page','.klembord']);
				app_show(['.car img']);
				app_fadeIn(id);
		break;
		case 'voorwaarden':
				$('.nav .active').removeClass('active');
				$('#app_wrapper').addClass('voted');
				app_hide(['.page','.klembord']);
				app_show(['.car img']);
				app_fadeIn(id);
		break;
		default :
			if($.cookie('smaak'+_appVars.template) != null ){
					$('.active #timo .vote').hide();
					$('.active #stefanie .vote').hide();
				}else{
					$('.active #timo .vote').show();
					$('.active #stefanie .vote').show();
			}
		
				$('.nav .active').removeClass('active');
				$('.nav .a a').addClass('active');
			$('#app_wrapper').removeClass('voted');
			
			if($.flash.available && $('#flash_header').length > 0){
				app_hide(['.page','.klembord']);
				app_show(['.car img']);
			}else{
				app_hide(['.page']);
				app_show(['.car img','.klembord']);	
			}
			
			app_loadflash()
		
			app_fadeIn(id);
		break;
	}
});

function submitSmaak(value) {
						
		vote = value;
		
			
	
			$.ajax({
				url: "handlers/smaak.php?t=" + gt(),
				type: "POST",
				dataType: "json",
				data: {smaak: value, template : _appVars.template},
				success: smaakComplete
			});	
		
}
		
function smaakComplete(data) {
			voted = vote == 1 ? 'indian' : 'bicky';
			
			
			ga_track('vote_'+voted+'_complete')
			
			
				$("#hguid").val(data.guid);
			
}
		
function submitQuestions() {
			$.ajax({
				url: "handlers/questions.php?t=" + gt(),
				type: "POST",
				dataType: "json",
				data: (	{
						guid: $("#hguid").val(),
						q1: getRadioValue("q1"),
						q2: $("#q2").val()
					}),
				success: questionsComplete
			});
}
		

		
function submitForm() {
			
				$.ajax({
					url: "handlers/form.php?t=" + gt(),
					type: "POST",
					dataType: "json",
					data: (	{
							guid: $("#hguid").val(),
							voornaam: $("#voornaam").val(),
							achternaam: $("#achternaam").val(),
							email: $("#email").val(),
							telnr: $("#telnr").val(),
							geslacht: getRadioValue("geslacht"),
							gebdatum: $("#gebdatumy").val() + "-" + $("#gebdatumm").val() + "-" + $("#gebdatumd").val(),
							actievw: $("#actievw").prop("checked") ? 1 : 0,
							optin: $("#optin").prop("checked") ? 1 : 0,
							lang: $("#hlang").val()
						}),
					success: formComplete
				});
			
}
		
function questionsComplete() {
	ga_track('questions_complete')
}
function formComplete() {
	ga_track('form_complete')	
}
		
function getRadioValue(name) {
			var result = '';
			$("input[name='"+name+"']").each(function() {
				if ($(this).prop("checked"))
				{
					result = $(this).val();
					return;
				}
			});
			
			return result;
}
		
function checkDate(d, m, y) {
			
			
		
			if (d.length > 0 && m.length > 0 && y.length > 0) {
				d = parseInt(d);
				m = parseInt(m);
				y = parseInt(y);
				
				date = new Date(y, m-1, d);
				
		
				
				if(date == 'Invalid Date' || date == 'NaN' || m > 12 || d > 31){
					return false;
				}else{
					return true;
				}
			}
			
			return false;
}
		
function gt() {return new Date().getTime();}

function dump(v) {
			var r = "";
			
			if (v.constructor == Array)
				for (var i in v)
					r += i + ": " + v[i] + "\n";
			else
				r = v;
			
			//console.log(r);
}

function app_loadflash(){
	
	if($.flash.available && $('#flash_header .object').length > 0){	
		var flashMovie = $('#flash_header .object');
		$('#flash_header .object').html('');
		$('.active .klembord').hide();
		$('#start .klemcounter').hide();
		flashMovie.flash(
				{
					swf: 'flash/Header.swf',
					wmode : 'transparent',
					width: 1280,
					height: 477,
					play: false,
					flashvars: {
						language: _appVars.locale,
						date: _appVars.date,
						noanimation : stopAnimate,
						voted : $.cookie('smaak'+_appVars.template) != null? true : false
					}
				}
			);
			
	}else{
		$('#start .klemcounter').show();
		$('.active .klembord').show();
		$('#fallback').show();	
	}
}



function app_daysleft(number){
	
	var days = [
	'',
	'x',
	'xx',
	'xxx',
	'xxxx',
	'xxxxx',
	'xxxxxx',
	'xxxxxxx',
	'xxxxxxxx',
	'xxxxxxxxx'
	]

	var daysLeft = number;
		
	var splitNumber = (daysLeft + '').split('');
	
	if(daysLeft < 2)$('.days').attr('class', 'day')
	
	if((daysLeft+'').length < 2) splitNumber = [0+'',daysLeft+''];
	
	$('#number_a').attr('class', days[parseInt(splitNumber[0])]);
	$('#number_b').attr('class', days[parseInt(splitNumber[1])]);
	
}

function app_share(site, description){
	
	ga_track(site+"_share");
	
	msg = encodeURI(description);
	shareUrl = encodeURI(_appVars.baseUrl);
	title = encodeURI(_appVars.title);
	
	switch(site){
	case 'twitter':
		var url = "http://twitter.com/home?status="+msg+" "+shareUrl;
		var width = "600";
		var height = "300";
	break;
	case 'netlog':
		var url = "http://www.netlog.com/go/manage/links/view=save&origin=external&url="+shareUrl+"&description="+msg+"&title="+title;
		var width = "660";
		var height = "600";
	break;
	case 'facebook':
		var url = "http://www.facebook.com/sharer.php?u="+shareUrl+"&t="+msg;
		var width = "600";
		var height = "300";
	break;
		
	}
	
	popupLinkedIn = window.open(url, 'share', 'width='+width+',' +
									    'height='+height+',' +
									    'status=no,' +
									    'location=yes,' +
									    'menubar=no,' +
									    'directories=no,' +
									    'toolbar=no,' +
									    'resizable=no,' +
									    'scrollbars=no');
    popupLinkedIn.focus();
}



function app_show(ids){
		for(var id in ids){
			$(ids[id]).show();
		}
}

function app_hide(ids){
	for(var id in ids){
			$(ids[id]).css('display','none');
		}
}

function app_fadeIn(id){
	if(jQuery.browser.msie){
		$(id).show();	
	}else{
		$(id).fadeIn();
	}
}



//Track functions
function ga_track(action){
	_gaq.push(['_trackPageview', _appVars.locale+'/'+_appVars.template+'/'+action]);
}
function ga_clickout(){
		$('.links_wrapper a').click(function(){
				ga_track(_appVars.page+'/clickout/'+$(this).attr('name'));
		});
}
function ga_trackLiked(likeType){
	switch(likeType){
		case 'new':
				ga_track(_appVars.page+'/NewLike');	
		break;
		case 'check':
			if(_appVars.liked == '1'){
				ga_track(_appVars.page+'/AlreadyLiked');
			}else{
				ga_track(_appVars.page+'/NotLiked');
			}
		break;
	}
}



//Application functions
function app_popitup(url) {
	newwindow=window.open(url,'name','height=730,width=940');
	if (window.focus) {newwindow.focus()}
	return false;
}


//Facebook functions
function fb_post(description, thumb){
	ga_track('facebook_share')
	FB.ui(
  {
    method: 'feed',
    name: _appVars.title,
    link: _appVars.baseUrl,
    picture: _appVars.baseUrl+'/img/'+thumb+'.jpg',
    caption: '',
    description: description
  },
  function(response) {
    if (response && response.post_id) {
      //alert('Post was published.');
    } else {
      //alert('Post was not published.');
    }
  }
);
}

