//dummy console
if(typeof(console) === 'undefined' || console == null) {
	console = {};
	console.log = function() { }
}

/***************
	namespace
****************/
var ec = {};
ec.webi = {};

/***************
	init defaults
****************/

$(document).ready(function() {
	setButtons($('input.button'), $('a.cancel'));

	//Selectit dropdowneiksi
	setSelectmenu($('select:not(.nodropdown)'));

	//Toolbar
	$.each($('div.toolbar a,td.toolbar a'), function(key, element) {
		if ($(element).hasClass('righticon')) {
			$(element).button({
				icons: {secondary: $(element).attr('rel')}
			});
		}
		else if ($(element).hasClass('icononly')) {
			$(element).button({
				icons: {primary: $(element).attr('rel')},
				text: false
			});
		}
		else {
			$(element).button({
				icons: {primary: $(element).attr('rel')}
			});
		}
	});

	$('div.toolbar-buttonset,td.toolbar-buttonset').buttonset();

	$('ul.ui-tabs-nav > li').hover(
		function() {
			$(this).addClass('ui-state-hover');
		},function() {
			$(this).removeClass('ui-state-hover');
		}
	);

	//Textareat resizable
	$('textarea:not(.noresizable)').resizable();
	$('textarea.resize_vertical_only').each(function() {
		$(this).resizable('option', 'maxWidth', $(this).outerWidth()).resizable('option', 'minWidth', $(this).outerWidth());
	});

	//focus
	$('(input,textarea).focus:not(.protected):first').focus();

	
	//Help-dialogit
	$('div.helpbutton').position({
		my: 'right top',
		at: 'right top',
		of: $('#content'),
		offset: '-10 10'
	});
	$('div.helpbutton img').tipTip({
		attribute: 'title',
		defaultPosition: 'left',
		delay: 0
	});
	$('a.help').click(function() {
		if ($('#help-dialog')) {
			removeDialog($('#help-dialog'));
		}
		$('#content').append($('<div />').attr('id', 'help-dialog'));
		$('#help-dialog').addClass('ajax-loading');
		$.ajax({
			url: $(this).attr('href'),
			success: function(response) {
				$('#help-dialog').removeClass('ajax-loading');
				$('#help-dialog').html(response);
			},
			error: function() {
				$('#help-dialog').removeClass('ajax-loading');
				$('#help-dialog').text('Ohjeen lataaminen epäonnistui');
			}
		});
		$('#help-dialog').dialog({
			width: 600,
			height: 400,
			title: 'Ohje',
			close: function() {
				removeDialog($(this));
			}
		});
		return false;
	});
	$('input.validator_time').ecTimeValidator();
	
	/* FlashMessages */
	$('#notifycontainer').notify();
	$(document).ajaxSuccess(function(event, request, ajaxOptions) {
		if (ajaxOptions.dataType == 'json') {
			var jsonData = $.parseJSON(request.responseText);
			if (jsonData != undefined && jsonData.flashmessages != undefined) {
				$.each(jsonData.flashmessages, function(key, obj) {
					var className = 'notify-normal';
					if (obj.severity == 1) {
						className = 'notify-warning';
					}
					$('#notifycontainer').notify('create', className, {
						message: obj.message
					}, {
						custom: true
					});
				});
			}
		}
	});
});

function removeDialog(element) {
	element.dialog('destroy');
	element.remove();
}

function setSelectmenu(elements) {
	elements.each(function(key, element) {
		if ($(element).find('option').length > 0) {
			$(element).selectmenu({
				style: 'dropdown'/*,
				maxHeight: $(document).height() - $(element).offset().top - $(element).height() -20*/
			});
		}
	});
}

function setButtons(button, cancel) {
	//Submitit Buttoneiksi
	$.each(button, function(key, element) {
		$(element).removeClass('button');
		$(element).button();
		if (!$(element).hasClass('ui-priority-primary') || $(element).hasClass('ui-priority-secondary')) {
			$(element).addClass('ui-priority-primary');
		}
	});

	//Cancelit buttoneiksi
	$.each(cancel, function(key, element) {
		$(element).removeClass('cancel');
		$(element).button();
		if (!$(element).hasClass('ui-priority-primary') || $(element).hasClass('ui-priority-secondary')) {
			$(element).addClass('ui-priority-secondary');
		}
	});
}

/************
  validators
**************/

(function($) {
	$.fn.extend({
		ecTimeValidator: function(options) {
			var defaults = {}
			var options = $.extend(defaults, options);

			return this.each(function() {
				var $this = $(this);
				$this.change(function() {
					var success = true;
					var inputValue = $this.val();
					//Normalisoi lukema
					var parts = inputValue.split(/[:.]/);
					var hours;
					var minutes;
					if (parts.length == 2) {
						hours = parseInt(parts[0], 10);
						minutes = parseInt(parts[1], 10);
					}
					else if (inputValue.length == 2 || inputValue.length == 1) {
						hours = parseInt(inputValue, 10);
						minutes = 0;
					}
					else if (inputValue.length == 4) {
						hours = parseInt(inputValue.substring(0, 2), 10);
						minutes = parseInt(inputValue.substring(2,4), 10);
					}
					else {
						success = false;
					}
					//Validoi
					success = success && hours !== NaN && minutes !== NaN;
					success = success && hours >= 0 && hours <= 24;
					success = success && minutes >=0 && minutes <60;

					if (success) {
						$this.removeClass('error');
						//Formatoi output
						inputValue = ec.formatTime(hours, minutes);
						$this.val(inputValue);
					}
					else {
						$this.addClass('error');
					}
				});
			});
		}
	});
})(jQuery);

function parseDoubleFromFinnishFormat(string) {
	var parts = string.split(',');
	var stringDouble = parts[0] + "." + parts[1];
	return parseFloat(stringDouble);
}

function formatNumber(num) {
	var a = Math.floor(num);
	var b = Math.floor((num-a)*100).toString();
	while (b.length < 2) {
		if (parseInt(b, 10) != 0)
			b = '0' + b;
		else
			b += '0';
	}
	if (!isNaN(a) && !isNaN(b)) {
		return a + ',' + b;
	}
	return '';
}

function timeToMinutes(timeStr) {
	var parts = timeStr.split(':');
	return parseInt(parts[0], 10) * 60 + parseInt(parts[1], 10);
}

/********************
	Collapsible
 ********************/

(function($) {
	$.fn.extend({
		ecCollapsible: function(options) {
			var defaults = {
				handle: '.collapsible-handle',
				content: '.collapsible-content',
				icon1: 'ui-icon-carat-1-e',
				icon2: 'ui-icon-carat-1-s'
			};

			var options = $.extend(defaults, options);

			return this.each(function() {
				var $this = $(this);
				var handle = $this.find(options.handle);
				var content = $this.find(options.content);

				if (options.icon1) {
					handle.prepend('<span class="ui-icon lefticon '+ options.icon1+ '"></span>');
				}

				handle.click(function() {
					content.toggle('blind', 300);
					if (options.icon1) {
						$(this).find('span.ui-icon').toggleClass(options.icon1).toggleClass(options.icon2);
					}
					$(this).data('isOpen', !$(this).data('isOpen'));
				});

				content.hide();
				handle.data('isOpen', false);
			});

		}
	});
})(jQuery);

ec.toggleAllCollapsible = function(handleClass, readyCallback) {
	var target = false;
	$(handleClass).each(function(index) {

		if (index == 0) {
			target = !$(this).data('isOpen'); // kaikki sektiot samaan tilaan, kuin eka
		}

		if ($(this).data('isOpen') != target) {
			$(this).click();
		}

	});
	
	if (readyCallback) {
		readyCallback(target);
	}
};

ec.parseDateTime = function(input) {
	if (input == null) {
		return null;
	}
	if (input instanceof Date) {
		return input;
	}
	var year = input.substring(0, 4);
	var month = input.substring(5, 7) - 1;
	var day = input.substring(8, 10);
	var hours = 0;
	var minutes = 0;
	var seconds = 0;
	if (input.length > 8) {
		hours = input.substring(11, 13);
		minutes = input.substring(14,16);
		seconds = input.substring(17,19);
	}
	return new Date(year,month,day, hours, minutes, seconds);
};

ec.formatTime = function(hours, minutes) {
	var inputValue;
	if (hours < 10)
		inputValue = '0' + hours;
	else
		inputValue = '' + hours;
	inputValue += ':';
	if (minutes < 10)
		inputValue += '0' + minutes;
	else
		inputValue += minutes;
	return inputValue;
};

ec.formatDate = function(date) {
	if (date == null) {
		return null;
	}
	var month = date.getMonth() + 1;
	if (month < 10)
		month = '0' + month;
	var ret = date.getFullYear() + '-' + month + '-' + date.getDate();
	return ret;
};
ec.webi.getCoveringnoteLink = function(ecomid, covid) {
	var ret = 'lahetteet/'
	if (ecomid) {
		ret += ecomid;
	}
	if (covid) {
		ret += ';' + covid;
	}
	return ret;
};
