
/* Sliders' bar width */
function setBarWidth(bar) {
	var handle = $(bar+" .ui-slider-handle");
	if(handle.length != 0) {
		var progressBarWidth = handle.offset().left - $(bar).offset().left + 12;
		$(bar+" .ui-slider-progress").width(Math.round(progressBarWidth));
	}
}

/* Slider needs a bit different function */
function setBarWidthSlider(bar,index, maxBarWidth, maxIndex){
	/* maxBarWidth / maxIndex = 215/70 */
	var progressBarWidth = index * maxBarWidth/maxIndex;
	$(bar+" .ui-slider-progress").width(Math.round(progressBarWidth));
}

/* Buys should not exceed the amount of monthly income */
function getDiff(){
	// Diff = Income - Buys
	return parseInt($("#amountTransfer").val()) - ( parseInt($("#amountBuys").val()) +  parseInt($("#amountOther").val()) );
}

function incomeToSmall(){
	if ( getDiff() < 0 ) return true;
	else return false;
}

function adjustSlider(scale,adjSlider){
	var allBuys = parseInt($("#amountBuys").val()) + parseInt($("#amountOther").val());
	var curIndex = getIndex(scale,allBuys);
	$(adjSlider).slider('option','value',curIndex);
	setBarWidth(adjSlider);
	//$("#amountTransfer").val(scale[curIndex]);
}

function adjustBuySlider(scale,adjSlider){
	var allowedTransfer = parseInt($("#amountTransfer").val()) - parseInt($("#amountOther").val());
	var curIndex = Math.round(getIndex(scale,allowedTransfer)/2);
	$(adjSlider).slider('option','value',curIndex);
	setBarWidth(adjSlider);
	$("#otherEvents").slider('option','value',curIndex);
	setBarWidth("#otherEvents");
	//$("#amountTransfer").val(scale[curIndex]);
}

function showError(sliderError) {
	$(sliderError).fadeIn("slow");
}
function hideError(sliderError) {
	// Hide all errors at once
	$(".sliderError").fadeOut("slow");
}

/* Get nearest index */
function getIndex(scale,value){
	for(i=0;scale[i] <= value;i++)
	{
		if((value - scale[i]) < (scale[i+1] - value)) var index = i;
		else var index = i+1;
	}
	return index;
}

// Choose suitable cards, accounts and services
function checkValue(q,a){
	$("#poll"+q+" li").hide();
	$("#poll"+q+" span").hide();
	$("#card"+q+a+" li").show();
	$("#text"+q+a).show();
	var test = $.cookie('poll');
	var cookies = {};
	if(test != null) {
	 var split1 = test.split("|");
	 for(x in split1) {
	   if(split1[x].length > 0) {
		var split2 = split1[x].split("=");
		cookies[split2[0]] = split2[1];	  
	   }
	 }
		}
	cookies[q] = a;
	var cookieString = "";
	for(x in cookies) {
	  cookieString += x+"="+cookies[x]+"|";
	}
	$.cookie('poll', cookieString,{ path: '/'});
}



// Test your knowledge
function checkTestValue(q,a){
		if(a != "0") {
//          $(".test"+q+" input").attr("disabled","disabled");
		  $(".test"+q+" .result.incorrect").hide();
		  $(".test"+q+" .result.correct").show();
		  $(".test"+q+" .answer").show();
		} else {
//          $(".test"+q+" input").attr("disabled","disabled");
		  $(".test"+q+" .result.correct").hide();
		  $(".test"+q+" .result.incorrect").show();
		  $(".test"+q+" .answer").show();
		}

	var test = $.cookie('test');
	var cookies = {};
	if(test != null) {
	 var split1 = test.split("|");
	 for(x in split1) {
	   if(split1[x].length > 0) {
		var split2 = split1[x].split("=");
		cookies[split2[0]] = split2[1];	  
	   }
	 }
		}
	cookies[q] = a;
	var cookieString = "";
	for(x in cookies) {
	  cookieString += x+"="+cookies[x]+"|";
	}
	$.cookie('test', cookieString,{ path: '/'});

}

function correct(q) {
	$("#result"+q).html('<span class="correct">Hyvä! Vastasit oikein.</span>');
}
function incorrect(q) {
	$("#result"+q).html('<span class="incorrect">Hups! Vastasit väärin.</span>');
}
function showCorrectAnswer(q) {
	$("#answer"+q).show();
}



/* Layer functions */
/*
function createLayerBG(){
	var docHeight = $(document).height();
	$('body').append('<div id="layerBackground" style="opacity:0.5;filter:alpha(opacity=50);height:'+docHeight+'px;"></div>');
}

function createLayer(layer){
	$(layer).show();
}
*/


// create common error layer
// Call: createError("creditAmount");
function createError(elemId, errorText){

	var errorHTML =	"<div class=\"errorContainer\"><div id=\""+elemId+"-error\" class=\"errorDialog\">";
	errorHTML +=	"<div class=\"inner\">";
	errorHTML +=	"<p>"+errorText+"</p>";
	errorHTML +=	"</div></div></div>";
	
	$("#"+elemId).before(errorHTML);
	$("#"+elemId+"-error").fadeIn("slow");
	
	// Fixed some styling issues. If the element is not indented then will be indented.
	if ( !$("#"+elemId+"-error").parent().parent().hasClass("indent") ){
		$("#"+elemId+"-error").addClass("indent");
	}
	
}

function removeError(elemId){
	$("#"+elemId+"-error").parent().remove();
}

function clearFormGeneral(){
	$('.counter input[type="radio"]').removeAttr('checked');
	$('.counter input[type="text"]').val('').removeClass("error");
	$('.counter input[type="checkbox"]').removeAttr('checked').removeAttr('disabled');
	$('.errorDialog').parent().remove();
}

function showInfoBox(elemId, text){
	var tooltipHTML =	"<div class=\"tooltip\" id=\""+elemId+"-tooltip\"><span class=\"tooltip_close\"></span>";
	tooltipHTML +=		"<p>"+text+"</p>";
	tooltipHTML +=		"</div>";
	
	$("#"+elemId).before(tooltipHTML);
}
function removeInfoBox(){
	$(".tooltip").remove();
}


$(document).ready(function() {
	/* Checkbox replacement */
	$('.navigo-tests-multi input:radio').checkbox();
	
	$('.infoBtn').hover(function(){
			$(this).find('.infoContainer').show();
		}, 
		function () {
			$(this).find('.infoContainer').hide();
		}
	);
	
	/* Handle layers */
	$('#showSCard').click(function(){
		createLayerBG();
		createLayer('#layerSCard');
		//return false;
	});
	$('#showMap').click(function(){
		createLayerBG();
		createLayer('#layerMap');
		//return false;
	});
	
	$('#showExample1').click(function(){
		createLayerBG();
		createLayer('#layerExample1');
		//return false;
	});
	$('#showExample2').click(function(){
		createLayerBG();
		createLayer('#layerExample2');
		//return false;
	});
	$('#showExample3').click(function(){
		createLayerBG();
		createLayer('#layerExample3');
		//return false;
	});
	
	$('#layer a.layerClose').click(function(){
		$('.layer').hide();
		$('#layerBackground').remove();
		return false;
	});
	
	
	/* Sliders */
	/*	Steps:
		0-1000: 50
		1000-5000: 100
		5000-100000: 10000 */
	//var scale = [0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1200, 1400, 1600, 1800, 2000, 10000, 20000, 30000, 40000, 50000];
	var max_amount = 100000;
	var scale = new Array();
	scale[0] = 0;
	var i=0;

	while (i<=19)
	{
		i++;
		scale[i] = scale[i-1] + 50;
	}
	while (i<=59)
	{
		i++;
		scale[i] = scale[i-1] + 100;
	}
	while (i<=69)
	{
		i++;
		if (i == 61) scale[i] = 10000;
		else scale[i] = scale[i-1] + 10000;
	}

	var scale_max = scale.length - 1;
	var stepper = 1;
	
	
	/* MONTHLY TRANSFER */
	$("#monthlyTransfer").slider({
		value:0,
		min: 0,
		max: scale_max,
		step: stepper,
		slide: function(event, ui) {
			$("#amountTransfer").val(scale[ui.value]);
			setBarWidthSlider("#monthlyTransfer",ui.value, 215, 70);
			if( incomeToSmall() ){
				//adjustBuySlider(scale,"#buysFromS");
				showError("#sliderErrorTransfer");
			}
			else hideError("#sliderErrorTransfer");
		}
	});
	
	$("#amountTransfer").blur(function () {
		if( incomeToSmall() ){
			showError("#sliderErrorTransfer");
		}
		else {
			var typedVal = parseInt($(this).val());
			if (typedVal > max_amount) typedVal = max_amount;
			var curIndex = getIndex(scale,typedVal);
			
			$("#monthlyTransfer").slider('option','value',curIndex);
			$(this).val(scale[curIndex]);
			setBarWidth("#monthlyTransfer");
			hideError("#sliderErrorTransfer");
		}
	});
	
	/* BUYS FROM S-GROUP */
	$("#buysFromS").slider({
		value:0,
		min: 0,
		max: scale_max,
		step: stepper,
		slide: function(event, ui) {
			$("#amountBuys").val(scale[ui.value]);
			setBarWidthSlider("#buysFromS",ui.value, 215, 70);
			if( incomeToSmall() ){
				//adjustSlider(scale,"#monthlyTransfer");
				showError("#sliderErrorBuys");
			}
			else hideError("#sliderErrorBuys");
			
		}
	});
	
	$("#amountBuys").blur(function () {
		if( incomeToSmall() ){
			showError("#sliderErrorBuys");
		}
		else{
			var typedVal = $(this).val();
			if (typedVal > max_amount) typedVal = max_amount;
			var curIndex = getIndex(scale,typedVal)
			
			$("#buysFromS").slider('option','value',curIndex);
			$(this).val(scale[curIndex]);
			setBarWidth("#buysFromS");
			hideError("#sliderErrorBuys");
		}
	});
	
	/* OTHER EVENTS */
	$("#otherEvents").slider({
		value:0,
		min: 0,
		max: scale_max,
		step: stepper,
		slide: function(event, ui) {
			$("#amountOther").val(scale[ui.value]);
			setBarWidthSlider("#otherEvents",ui.value, 215, 70);
			if( incomeToSmall() ){
				showError("#sliderErrorOther");
				//adjustSlider(scale,"#monthlyTransfer");
			}
			else hideError("#sliderErrorOther");
			
		}
	});
	
	$("#amountOther").blur(function () {
		if( incomeToSmall() ){
			showError("#sliderErrorOther");
		}
		else{
			var typedVal = $(this).val();
			if (typedVal > max_amount) typedVal = max_amount;
			var curIndex = getIndex(scale,typedVal)
			
			$("#otherEvents").slider('option','value',curIndex);
			$(this).val(scale[curIndex]);
			setBarWidth("#otherEvents");
			hideError("#sliderErrorOther");
		}
	});
	
	/* Slider for joustoluottolaskuri */
	/* Slider steps */
	var max_amount_credit = 10000;
	var min_amount_credit = 2000;
	var scale_credit = new Array();
	scale_credit[0] = min_amount_credit;
	var i=0;
	while (i<=79)
	{
		i++;
		scale_credit[i] = scale_credit[i-1] + 100;
	}
	
	var scale_max_credit = scale_credit.length - 1;
	var stepper = 1;
	
	$("#creditAmount").slider({
		value:min_amount_credit,
		min: 0,
		max: scale_max_credit,
		step: stepper,
		slide: function(event, ui) {
			$(".amount-holder input").removeClass("error");
			removeError("creditAmount");
			
			$("#counter3_textbox1").val(scale_credit[ui.value]); // set value for input field
			$("#creditAmount .ui-slider-handle span").text(scale_credit[ui.value]+" €"); // set value for tooltip
			setBarWidthSlider("#creditAmount",ui.value, 497, 80);
			removeInfoBox();
		}
	});
	
	$("#counter3_textbox1").blur(function () {
		var typedVal = $(this).val();
		if (typedVal > max_amount_credit) {
			typedVal = max_amount_credit;
			var curIndex = getIndex(scale_credit,typedVal) - 1;
			
			$(this).addClass("error");
			createError("creditAmount",virhe3+" 2000-10000 €");
			
		} else if (typedVal < min_amount_credit) {
			typedVal = min_amount_credit;
			var curIndex = getIndex(scale_credit,typedVal);
			
			$(this).addClass("error");
			createError("creditAmount",virhe3+" 2000-10000 €");
			
		} else if ((typedVal % 100) !=0) {
			var curIndex = getIndex(scale_credit,typedVal);
			
			$(this).addClass("error");
			createError("creditAmount",virhe4);
			
		} else {
			var curIndex = getIndex(scale_credit,typedVal);
			$(this).removeClass("error");
			removeError("creditAmount");
		}
		
		$("#creditAmount").slider('option','value',curIndex);
		//$(this).val(scale_credit[curIndex]);
		$("#creditAmount .ui-slider-handle span").text(scale_credit[curIndex]+" €");
		setBarWidth("#creditAmount");
		hideError("#sliderErrorOther");
	});
	$('#counter3_textbox1').keyup(function(event) {
		if ($(this).hasClass("error")){
			$(this).removeClass("error");
			removeError("creditAmount");
		}
	});

	$('#counter2_textbox1,#counter1_textbox1').blur(function() {
		if ($(this).hasClass("error")){
			$(this).removeClass("error");
			removeError("counter2_textbox1");
			removeError("counter1_textbox1");
		}
	});
	$('#counter2_textbox1,#counter1_textbox1').keyup(function(event) {
		if ($(this).hasClass("error")){
			$(this).removeClass("error");
			removeError("counter2_textbox1");
			removeError("counter1_textbox1");
		}
	});
	if (!(typeof useCounter === 'undefined') && useCounter != "counter2-staff" ){
		$("#counter2_textbox1").blur(function () {
			
			var typedVal = $(this).val();
			
			if ( isNaN( parseInt(typedVal) ) ){
				createError("counter2_textbox1",virhe2);
			} else if (typedVal > 5000) {
				typedVal = max_amount_credit;
				$(this).addClass("error");
				createError("counter2_textbox1",virhe3+" 200-5000 €");
				
			} else if (typedVal < 200) {
				typedVal = min_amount_credit;
				
				$("#counter2_textbox1").addClass("error");
				createError("counter2_textbox1",virhe3+" 200-5000 €");
				
			} else if ((typedVal % 100) !=0) {
				$(this).addClass("error");
				createError("counter2_textbox1",virhe4);
				
			} else {
				$(this).removeClass("error");
				removeError("counter2_textbox1");
			}
			
			//hideError("#sliderErrorOther");
		});
	}
	
	
	

	/* Set the sliders after the document is loaded */
	$("#monthlyTransfer").slider('option','value',getIndex(scale,$("#amountTransfer").val()));
	setBarWidth("#monthlyTransfer");
	$("#buysFromS").slider('option','value',getIndex(scale,$("#amountBuys").val()));
	setBarWidth("#buysFromS");
	$("#otherEvents").slider('option','value',getIndex(scale,$("#amountOther").val()));
	setBarWidth("#otherEvents");
	// Credit counter
	$("#creditAmount").slider('option','value',getIndex(scale_credit,$("#counter3_textbox1").val()));
	setBarWidth("#creditAmount");
	
	// Tooltip for Credit counter's amount
	$("#creditAmount .ui-slider-handle").html("<span style=\"display:none;\" />");
	$("#creditAmount .ui-slider-handle span").text($("#counter3_textbox1").val()+" €"); // set value for tooltip
	
	var isMouseDown = false;
	var isMouseOver = false;
	$('body').mousedown(function() {
        isMouseDown = true;
    })
    .mouseup(function() {
        isMouseDown = false;
		
		if (!isMouseOver){
			$("#creditAmount .ui-slider-handle span").css('display','none');
		}
    });

	$("#creditAmount .ui-slider-handle").mouseover( function(){
		$(this).find("span").css('display','block');
		isMouseOver = true;
		
	}).mouseout( function(){
		if( !isMouseDown ){
			$(this).find("span").css('display','none');
		}
		isMouseOver = false;
	});
	
	/* Joustoluottolaskuri - Maksuvapaat kuukaudet */
	/* Validate checkboxes:
		- max 2 selections
		- selection cannot have a neighbour
		- check also if months are 6th and 7th or 1st and 12th.
	*/
	var cb = $('.months input');
	
	// Check selection amount
	if ( $('.months input:checked').length > 1 ){
		cb.each( function(){
			if ( !$(this).attr('checked') ){
				$(this).attr('disabled','disabled');
			}
		});
	}
	
	
	
	var errorOn = false;
	function callError(){
		createError("months",virhe19);
		errorOn = true;
	}	
	// Bind different action for IE and others
	cb.bind($.support.opacity ? 'change': 'click', function(e) {
  
		// Check if neighbours
		var prev = $(this).parent().prev('.month').find('input');
		var next = $(this).parent().next('.month').find('input');
		// use either counter3 or counter1
		var months = $("input[name='counter3_menuD']");
		if ($("input[name='counter1_menuD']").length > 0){
			months = $("input[name='counter1_menuD']");
		}
		var thisMonth = months.index($(this)); // index starts from 0
		
		if ( $(this).attr('checked') && (prev.attr('checked') || next.attr('checked')) ){			
			callError();
		}
		else if( !errorOn && (((thisMonth == 0) && months.eq(11).attr('checked')) || ((thisMonth == 11) && months.eq(0).attr('checked'))) ){
			callError();
		
		}
		else if( !errorOn && (((thisMonth == 5) && months.eq(6).attr('checked')) || ((thisMonth == 6) && months.eq(5).attr('checked'))) ){
			callError();
		}
		else {
			$('.months .sliderError').hide();
			cb.removeAttr('disabled');
			errorOn = false;
			removeError("months");
		}
				
		// Check selection amount
		if ( $('.months input:checked').length > 1 ){
			cb.each( function(){
				if ( !$(this).attr('checked') ){
					$(this).attr('disabled','disabled');
				}
			});
		}
		
		//e.preventDefault();
	});
	
	/* Clear errors */
	// Bind different action for IE and others
	$("#paymentSet input").bind($.support.opacity ? 'change': 'propertychange', function(e) {
		removeError("paymentSet");
		
		e.preventDefault();
	});
	$('#counter2_name').keyup(function(event) {
		removeError("counter2_name");
	});

	
	/* Reset Joustoluottolaskuri */
	$('#counter3_reset').click( function(){
		$('#creditAmount').slider('option','value',getIndex(scale_credit,min_amount_credit));
		setBarWidth('#creditAmount');
		$('#counter3_textbox1').val(min_amount_credit);
		
		clearFormGeneral();
		$('.counter input[type="text"]').val('2000');
		$("#creditAmount .ui-slider-handle span").text("2000 €");
	});
	
	// Reset Kertaluottolskuri and Tuoteluottolaskuri
	$('#counter1_reset,#counter2_reset').click( function(){
		clearFormGeneral();
	});
	
	/* Info tooltip */
	var mouseOver=false; 
	$('.tooltip_clicker').click(function(){
		// Info button toggles infobox visibility
		if ($('.tooltip').length > 0){
			removeInfoBox();
		} else {
			if ($(this).attr('id') == "counter3_picture_link") {
				showInfoBox($(this).attr('id'), infotext1_jousto);
			}
			if ($(this).attr('id') == "counter2_picture_link") {
				showInfoBox($(this).attr('id'), infotext1_tuote);
			}
			
			
			
			$('.tooltip').hover(function(){ 
				mouseOver=true; 
			}, function(){ 
				mouseOver=false; 
			});
			
			// remove tooltip when clicked outside of it.
			$('html').live('click', function (e) {
				if (!mouseOver) {
					removeInfoBox();
				}
			});
		}
		
		return false;
	});
	
	$('.tooltip_close').live('click', function (e) {
		removeInfoBox();
	});
	

	
});


