/**
 * 
 * Online invoice generator functionality
 * 
 * @version 30.07.2010
 * 
 * @author Janno Stern (www.janno.ee)
 * @author Innovatiivsed lahendused OÜ (www.innovatiivne.ee)
 * 
 * Tasklist:
 * - test, test and test
 * 
**/


/**
 * 
 * Set cookie value
 * 
**/

var setCookie = function(name, value){
	var date = new Date()
	date.setTime(date.getTime()+(1000*60*60*24*30*6));
	document.cookie = name+'='+value+'; expires='+date.toGMTString()+'; path=/';
}


/**
 * 
 * Get cookie value
 * 
**/

var getCookie = function(name){
	if(document.cookie.length>0){
		start=document.cookie.indexOf(name + '=');
		if(start!=-1){
			start = start + name.length+1;
			end = document.cookie.indexOf(';', start);

			if(end == -1) end = document.cookie.length;
			return unescape(document.cookie.substring(start, end));
		}
	}
	return '';
}


/**
 * 
 * Set heading h1
 * 
**/

var setHeader = function(){
	var tmp = $('#my-company-name').val();

	if(tmp == '' || tmp == '-') $('#header h1').text('ArveHai versioon 1.0')
	else $('#header h1').text(tmp);
}


/**
 * 
 * Set page title
 * 
**/

var setTitle = function(){
	var tmp = $('#invoice-nr').val();

	if(tmp == '' || tmp == '-') document.title = 'ArveHai versioon 1.0';
	else document.title = 'Arve '+tmp;
}


/**
 * 
 * Format sum
 * 
**/

var formatSum = function(sum){

	var val = sum.toString().split('.');
	var len = val[0].length;
	var result = '';

	while (len > 3){
		result = ' '+val[0].substr(len-3,3)+result;
		len -=3;
	}
	return val[0].substr(0,len)+result+'.'+val[1];
}


/**
 * 
 * Calculate invoice content prices
 * 
**/

var calculate = function(){

	var sum1 = parseFloat($('.row-amount input', $(this).parent().parent()).val().replace(',', '.').replace(' ', ''))*parseFloat($('.row-price input', $(this).parent().parent()).val().replace(',', '.').replace(' ', ''));
	var sum2 = 0;
	var vat = 0;

	if($('#my-company-vatnr').val() == '' || $('#my-company-vatnr').val() == '-') vat = 0;
	else vat = 0.2;

	$('#invoice-content tbody tr').each(function(){
		var tmp1 = parseFloat($('.row-amount input', this).val().replace(',', '.').replace(' ', ''));
		var tmp2 = parseFloat($('.row-price input', this).val().replace(',', '.').replace(' ', ''))

		if(isNaN(tmp1) || tmp1 < 0) tmp1 = 0;
		if(isNaN(tmp2) || tmp2 < 0) tmp2 = 0;

		sum2 += tmp1*tmp2;
		});

	if(isNaN(sum1) || sum1 < 0) sum1 = 0;
	if(isNaN(sum2) || sum2 < 0) sum2 = 0;

	//display the calculations
	if(sum1 != 0) $('.row-sum', $(this).parent().parent()).html(formatSum(sum1.toFixed(2)));
	else $('.row-sum', $(this).parent().parent()).html('');
	$('#sum-without-vat').html(formatSum(sum2.toFixed(2)));
	$('#sum-vat').html(formatSum((sum2*vat).toFixed(2)));
	$('#sum').html(formatSum((sum2*(1+vat)).toFixed(2)));
}


/**
 * 
 * $(document).ready()
 * 
 * The main code begins
 * 
**/

$(document).ready(function(){

	//define empty row for: #invoice-content table
	var emptyRow = '<tr><td class="row-name"><input type="text"></td><td class="row-amount"><input type="text"></td><td class="row-price"><input type="text"></td><td class="row-sum"></td></tr>';

	//generate date and display the invoice nr and invoice
	var date = new Date();
	$('#invoice-nr').val(date.getFullYear()+'-'+((date.getMonth()+1<10) ? '0'+(date.getMonth()+1) : (date.getMonth()+1))+'-'+((date.getDate()<10) ? '0'+date.getDate() : date.getDate())+'-1');
	$('#invoice-date').val(((date.getDate()<10) ? '0'+date.getDate() : date.getDate())+'.'+((date.getMonth()+1<10) ? '0'+(date.getMonth()+1) : (date.getMonth()+1))+'.'+date.getFullYear());

	//add 7 days to date and display due date
	date.setDate(date.getDate()+7);
	$('#invoice-due-date').val(((date.getDate()<10) ? '0'+date.getDate() : date.getDate())+'.'+((date.getMonth()+1<10) ? '0'+(date.getMonth()+1) : (date.getMonth()+1))+'.'+date.getFullYear());

	//read saved data from browser cookies
	$('.save').each(function(){var tmp = getCookie($(this).attr('name'));if(tmp) $(this).val(tmp);});

	//set page title
	setTitle();
	$('#invoice-nr').keyup(setTitle);
	$('#invoice-nr').change(setTitle);

	//set company name
	setHeader();
	$('#my-company-name').keyup(setHeader);
	$('#my-company-name').change(setHeader);

	//mouseover/mouseout functionality over input fields
	$('input').live('mouseover', function(){$(this).addClass('mouseFocus');});
	$('input').live('mouseout', function(){$(this).removeClass('mouseFocus');});

	//focus/blur functionality over input fields
	$('input').live('focus', function(){$(this).addClass('keyboardFocus');});
	$('input').live('blur', function(){$(this).removeClass('keyboardFocus');});

	//display default input in #invoice-info input
	$('#invoice-info input, #footer input').focus(function(){if($(this).val() == '-') $(this).val('');});
	$('#invoice-info input, #footer input').focusout(function(){if($(this).val() == '') $(this).val('-');});

	//change VAT number
	$('#my-company-vatnr').keyup(function(){$('#invoice-content .row-price input').trigger('keyup');});
	$('#my-company-vatnr').change(function(){$('#invoice-content .row-price input').trigger('keyup');});

	//save user input when it's changed
	$('.save').keyup(function(){$('.save').each(function(){setCookie($(this).attr('name'), $(this).val())});});
	$('.save').change(function(){$('.save').each(function(){setCookie($(this).attr('name'), $(this).val())});});

	//add new #invoice-content table row
	$('#invoice-content th').click(function(){$('#invoice-content tbody').append(emptyRow); $('#invoice-content tbody tr:last .row-name input').focus(); return false;});
	$('#invoice-content input').live('keyup', function(e){if(e.keyCode == 13){$(this).parent().parent().after(emptyRow); $('.row-name input', $(this).parent().parent().next()).focus(); return false;}});

	//delete #invoice-content table row
	$('#invoice-content .row-name input').live('keydown', function(e){if(e.keyCode == 8 && $(this).val() == ''){$('.row-name input', $(this).parent().parent().prev()).focus(); $(this).parent().parent().remove(); return false;}});

	//make the calculations
	$('#invoice-content .row-amount input, #invoice-content .row-price input').live('keyup', calculate);
	$('#invoice-content .row-amount input, #invoice-content .row-price input').live('change', calculate);

	//set focus on invoice-content input
	$('#invoice-content input:first').focus();

	//show and hide the toolbar
	$(document).mousemove(function(e){
		if(e.pageY <= 45 && $('#toolbar').is(':hidden')) $('#toolbar').slideDown(100);
		else if(e.pageY > 45 && $('#toolbar').is(':visible')) $('#toolbar').slideUp(100);
	});

	//print button functionality
	$('#print').click(function(){
		$('#toolbar').hide();
		window.print();
		return false;
	});

	//create new invoice
	$('#new').click(function(){
		window.location = window.location;
		return false;
	});

	//clear all saved data
	$('#clear').click(function(){
		$('input').val('');
		$('input').keyup();
		window.location = window.location;
		return false;
	});
});

