var page = 0;
var country = 'se';

$(document).ready(function() 
{
	splitURLs();
	fillURLs();
	fillQuestions();
	showChosenCampaigns();
		
	
	$('.target').bt(
	{
	width:400,
	padding:20,
	spikeLength: 40,
	spikeGirth: 20,
	fill: 'rgba(0, 0, 0, .9)',
	strokeWidth: 3,
	strokeStyle: '#cccccc',
	cssStyles: {color: '#FFF'},
	cornerRadius: 20,
	ajaxCache: false,
	btParentNode: 'body',
	ajaxPath: ["$(this).attr('href')"]
	});
	
	
	$('.target').click(function()
	{
		var id = $(this).attr('id').substring(5);	
		
		$('#film'+id).attr('title', id);
		$('#film'+id).click();
		return false;
	
	});


	$('.campaign_val').click(function()
	{
		toggleCampaign(this, this.value);
		return true;
	});
	
	$("#back_button").click(function()
	{
		document.location = 'step_' + (page-1) + '.php';
	});
	
	if(country == 'se')
	{
		$(".user_info[name='user[f4]']").blur(function()
		{
			getAndShowCity($(".user_info[name='user[f4]']").attr('value'), $(".user_info[name='user[f5]']"), $(".user_info[name='user[f6]']"));
		});
	}
	
	
	/*
	FOR QUESTIONS THAT SHOW UP WHEN YES IS CLICKED
	*/
	$('.show_next').click(function()
	{
		$(this).parent().next('.followup').slideDown('slow');
		$(this).parent().next('.followup').children('p:first').children('input:first').addClass('question');
		showChosenCampaigns();
		generateValidation();
	});
	
	$('.hide_next').click(function()
	{
		$(this).parent().next('.followup').hide('slow');
		$(this).parent().next('.followup').children('p:first').children('input:first').removeClass('question').removeAttr('validate');
		$(this).parent().next('.followup').children('p:first').children('.campaign_val:eq(1)').trigger('click');
		generateValidation();
	});
	
	$('.hide_next_he').click(function()
	{
		$(this).parent().next('.followup').hide('slow');
		$(this).parent().next('.followup').children('p:first').children('input:first').removeClass('question').removeAttr('validate');
		$(this).parent().next('.followup').children('p:first').children('input:last').trigger('click');
		generateValidation();
	});
	
	
	$('.hide_next_new').click(function()
	{
		$(this).parent().next('.followup').hide('slow');
		$(this).parent().next('.followup').children('p:first').children('input:first').removeClass('question').removeAttr('validate');
		emptyFollowUp(this);
	});
	
	$('.show_next').each(function()
	{
		if(this.checked)
			$(this).trigger('click');
	});
	
	
	$('.show_next').parent().next('.followup').each(function()
	{
		if($(this).is(':visible'))
			return true;
			
		$(this).children('p:first').children('.campaign_val:first').removeClass('question').removeAttr('validate');
	});
	
	$('h3').prepend('<span class="num">&nbsp;&nbsp;</span>');
	generateValidation();
});


function generateValidation()
{
	$('.question:visible').each(function(i)
	{
		if(this.type == 'radio')
			$(this).attr('validate', 'checked').attr('errormsg', country + '.answer_' + (i + 1));
		if(this.type == 'select' || this.type == 'select-one')
			$(this).attr('validate', 'notindexzero').attr('errormsg', country + '.answer_' + (i + 1));
		
		$(this).parent().prevAll('h3:first').children('.num').text((i + 1) + '. ');
		
	});
}


function getAndShowCity(ref, update, next)
{
	var city_url = '/proxies/postnr_proxy.php';
	$.get(city_url, {postnr: ref}, function(data)
	{
		info = data.split(",");
		if(!info[0])
			update.focus();
		else
		{
			update.attr('value', info[0]);
			next.focus();
		}
		return;
	});
}


function showChosenCampaigns()
{
	$('.campaign_val').each(function()
	{
		if(!this.checked)
			return true;
		
		toggleCampaign(this, this.value);

	});
}


function toggleCampaign(obj, value)
{
	if(value == 'nej')
	{
		$(obj).parent('p').next(".hidden").slideUp();
		$(obj).parent("p").next(".hidden").find("p").children().each(function()
		{
			$(this).removeAttr('validate').removeAttr('errormsg');
		});
	}
	else if(value == 'ja')
	{
		$(obj).parent('p').next(".hidden").slideDown();
		
		$(obj).parent("p").next(".hidden").find("p").children().each(function()
		{
			if(this.tagName != 'INPUT' && this.tagName != 'SELECT')
				return true;
				
			var name = this.name.match(/\[([^\]]+)\]$/);
			name = name[1];
			
			if(this.type == 'checkbox')
				$(this).attr('validate', 'checked').attr('errormsg', country + '.' + name);
			else if(this.type == 'select-one' || this.type == 'select')
				$(this).attr('validate', 'notindexzero').attr('errormsg', country + '.' + name);
			else if(name == 'pnr')
				$(this).attr('validate', 'pnr').attr('errormsg', country + '.birthdate');
			else if(this.type == 'text')
				$(this).attr('validate', 'notempty').attr('errormsg', country + '.' + name);
		});
	}
}


function fillQuestions()
{
	var name = '';
	var v = null;
	$("form[name='testform']").find('input,textarea,select').each(function()
	{
		name = this.name.replace(/^([^\[]*?)(\[)/, '$1["' + page + '"][');
		name = name.replace(/\[([^\"])/g, '["$1');
		name = name.replace(/([^\"]{1})\]/g, '$1"]');
		
		try
		{
			v = eval(arr_name + '.' + name);
		}
		catch(e)
		{
			return true;
		}

		//if(this.type == 'hidden')
			//return true;
		
		if(this.type == 'radio' || this.type == 'checkbox')
		{
			if(this.value == v)
				this.checked = 'checked';
			else
				this.checked = '';
		}
		else if(this.type == 'text' || this.type == 'hidden')
		{
			if(v)
				this.value = v;
		}
		else if(this.type == 'select-one' || this.type == 'select')
		{
			var sel = $("select[name='" + this.name + "']");
			sel.selectOptions(v);
		}
	});
}



function fillURLs()
{
	var $form = $("form");
	var form = $form.get(0);
	
	if(typeof(form) == 'undefined')
		return false;

	var act = form.action;
	
	if(act.match(/save/))
		form.action = 'step_' + (page+1) + '.php?save=true';
	else
		form.action = 'step_' + (page+1) + '.php';
	$("input[name='page']").attr('value', page);
}


function splitURLs()
{
	var loc = document.location.href;
	var fetch = /step_(.*)\.php/;
	var pages = loc.match(fetch);
	page = parseInt(pages[1]);
}


function debug(str)
{
	$("#debug").append('<br>' + str);
}

function popup(url,name,w,h)
 {
   
   popupwin = window.open(url,name,'height='+h+',width='+w+',left=100,top=100,resizable=no,scrollbars=no,toolbar=no,status=no');
 	popupwin.focus();
 } 
 
 function popup_scroll(url,name,w,h)
 {
   
   popupwin = window.open(url,name,'height='+h+',width='+w+',left=100,top=100,resizable=no,scrollbars=yes,toolbar=no,status=no');
 	popupwin.focus();
 }


function copyTitleToValue(el, to_id)
{
	
	var tmp_id = $(el).attr('name');
	var tmp_title = $(el).attr('title');
	//$('#debug').append(tmp_id);
	$('#' + to_id).val(tmp_title);
}


function emptyFollowUp(el)
{
	$(el).parent('p').next('.followup').find('input').each(function()
	{
		if(this.type == 'radio')
			$(this).attr('checked', '');
	});
	generateValidation();
}
