﻿jQuery.fn.iwfBindModal = function() {
	var args = arguments[0] || {};
	var preventDefault = args.preventDefault == null ? false : args.preventDefault;
	var container = args.container;

	var _checkExternalKeyDown = function(event) {
		if (event.type != 'keyup') return false;

		if (event.keyCode == 27) //esc
		{
			$(picker).iwfHideModal();
			$($(picker).find('input[type=hidden]')[0]).val("f");

			//consume event
			event.preventDefault();
		}
	};

	var picker = $(container);
	var hfVisible = $(container).find('input[type=hidden]');

	//update panel modal set visible
	if ($(hfVisible[0]).val() == "t") {
		picker.iwfShowModal();
	}

	$(this).bind('click', function(event) {
		$('.ContentPickerClose').click();

		picker.iwfShowModal();
		$($(picker).find('input[type=hidden]')[0]).val("t");

		if (preventDefault) event.preventDefault();
	});

	$(picker).find('.ContentPickerClose').bind('click', function() {
		$(picker).iwfHideModal();
		$($(picker).find('input[type=hidden]')[0]).val("f");
	});

	$(document).keyup(_checkExternalKeyDown);
};

//shows div with given id as modal div
jQuery.fn.iwfShowModal = function() {
	var args = arguments[0] || {};
	var width = args.width == null ? $(this).width() : args.width;

	if ($('body').find('#jquery-overlay').length == 0) {
		// Apply the HTML markup into body tag
		$('body').append('<div id="jquery-overlay"></div>');
	}

	// Style overlay and show it
	$('#jquery-overlay').css({
		backgroundColor: '#000',
		opacity: 0.8,
		width: '100%',
		height: '100%',
		left: 0,
		top: 0,
		position:'fixed'
	}).fadeIn();

	$(this).iwfFixedBox();
};

//hides modal displayed div and overlay
jQuery.fn.iwfHideModal = function() {

	$('#jquery-overlay').css({
		opacity: 0.0
	}).fadeIn();

	$('#jquery-overlay').remove();

	$(this).css("display", "none");
};

//OLD VERSIONS:
//
//function iwfShowModal(divId,titleText) {
//	var dlg = $('#' + divId).dialog({ position: 'center', width: '740px', modal: true, resizable: false, draggable: false, zIndex: 100, title: titleText, dialogClass: 'repo relatedDocumentPicker', close: function(event, ui) { $('#' + divId).dialog("destroy"); } });
//	dlg.parent().appendTo($("form:first"));
//	$('#' + divId).parent().fixedBox();
//	$('#' + divId).parent().css("z-index", "102");
//}
//
//function iwfHideModal(divId) {
//	$('#' + divId).dialog("close");
//}

jQuery.fn.iwfFixedBox = function(options) {
	options = jQuery.extend({
		x: false,
		y: false
	}, options);

	//remove from parent container
	if (jQuery.browser.msie && jQuery.browser.version == '6.0') {
		$(this).css({ position: 'absolute' });
	}
	else {
		$(this).css({ position: 'fixed' });
	}

	return (this.each(function() {
		var x = y = 0;
		var w = h = 0;

		if (!options.x || !options.y) {
			//compute top and left positions
			var ww = document.documentElement.clientWidth
                     || document.body.clientWidth;
			var hh = document.documentElement.clientHeight
                     || document.body.clientHeight;

			//Opera
			//if (jQuery.browser.opera) hh = document.body.clientHeight;
			var w = jQuery(this).width();
			var h = jQuery(this).height();

			if (w > (0.9 * ww)) w = (0.9 * ww);
			if (h > (0.9 * hh)) h = (0.9 * hh);

			var padx = jQuery(this).css('padding-left');
			padx = parseInt(padx.substring(0, padx.length - 2));
			var pady = jQuery(this).css('padding-top');
			pady = parseInt(pady.substring(0, pady.length - 2));

			var borx = jQuery(this).css('border-left-width');
			borx = parseInt(borx.substring(0, borx.length - 2));
			if (!borx) borx = 0;
			var bory = jQuery(this).css('border-top-width');
			bory = parseInt(bory.substring(0, bory.length - 2));
			if (!bory) bory = 0;

			x = Math.round((ww - w - 2 * padx - 2 * borx) / 2);
			y = Math.round((hh - h - 2 * pady - 2 * bory) / 2);
		}

		if (options.x) x = parseInt(options.x);
		if (options.y) y = parseInt(options.y);

		//handle MSIE 6.0
		if (jQuery.browser.msie && jQuery.browser.version == '6.0') {
			//see http://www.howtocreate.co.uk/fixedPosition.html
			var expression = "( " + y + " + ( ignoreMe = "
                           + "document.documentElement.scrollTop ? "
                           + "document.documentElement.scrollTop : "
                           + "document.body.scrollTop ) ) + 'px'";

			jQuery(this).get(0).style.setExpression("top", expression);

			jQuery(this).css({
				position: 'absolute',
				zIndex: '101',
				left: x + 'px',
				width: w + 'px',
				height: h + 'px',
				overflow: 'hidden',
				display: 'block'
			});
		}
		else {
			jQuery(this).css({
				position: 'fixed',
				zIndex: '101',
				top: y + 'px',
				left: x + 'px',
				width: w + 'px',
				height: h + 'px',
				overflow: 'hidden',
				display: 'block'
			});
		}
	}));
};


jQuery.fn.iwfScrollToMessageBox = function() {
	$(window).scrollTo($(this), 1000, { offset: -10, easing: 'easeOutBounce' });
};

//Gets value from html element
jQuery.fn.iwfGetVal = function() {
	if ($(this)[0].tagName == 'SPAN')
		return $(this).text(); //get value
	else if ($(this)[0].tagName == 'INPUT')
		return $(this).val(); //get value
	else if ($(this)[0].tagName == 'SELECT')
		return $(this).val(); //get value
	else return ''
};

//simply copy value
jQuery.fn.iwfSetVal = function(value) {
	if ($(this)[0].tagName == 'SPAN')
		$(this).text(value); //set value
	else if ($(this)[0].tagName == 'INPUT') {
		$(this).val(value); //set value
	}
};

//simply copy value
jQuery.fn.iwfGetPrice = function() {
var val = $(this).iwfGetVal();
	val = val.replace(/ /g, '').replace(',', '.');

	var valF = parseFloat(val);
	if (isNaN(valF) == true) return parseFloat('0');

	//if (valF > 99999999.99) valF = 99999999.99;

	valF = iwfTruncateToPrice(valF);
	return valF;
};

function iwfPreventKeyup(event) {
	if (event.type != 'keyup') return false;

	if (event.keyCode >= 48 && event.keyCode <= 57) return false;
	if (event.keyCode == 8) return false; //bs
	if (event.keyCode == 32) return false; //spce
	if (event.keyCode == 46) return false; //del
	if (event.keyCode == 109) return false; //-
	if (event.keyCode == 188) return false; //,

	return true;
}


function CommaFormatted(amount, delimiter, coma) {
	//var delimiter = '.'; // replace comma if desired
	var minus = '';
	if (amount < 0) { minus = '-'; }
	var a = amount.split('.', 2)
	var d = a[1];
	var i = parseInt(a[0]);
	if (isNaN(i)) { return ''; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while (n.length > 3) {
		var nn = n.substr(n.length - 3);
		a.unshift(nn);
		n = n.substr(0, n.length - 3);
	}
	if (n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if (d.length < 1) { amount = n; }
	else { amount = n + coma + d; }
	amount = minus + amount;
	return amount;
}

function iwfFormatPrice(value) {
	return CommaFormatted(iwfTruncateToPrice(value).toFixed(2), ' ', ',');
}

function iwfTruncateToPrice(i) {
	if (isNaN(i)) { i = 0.00; }
	var minus = '';
	if (i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i * 100) + 0.001);
	i = i / 100;
	s = new String(i);
	if (s.indexOf('.') < 0) { s += '.00'; }
	if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;

	return parseFloat(s);
}

jQuery.fn.iwfUpdateVat = function() {
	var args = arguments[0] || {};
	var srcCtrl = args.srcCtrl;
	var destCtrl = args.destCtrl;
	var vatCtrl = args.vatCtrl;

	var netAmount = $(srcCtrl).iwfGetPrice();

	//vat selection must contain '%' char
	var vatName = $(vatCtrl).find('option:selected').text()
	var vatName = vatName.substring(0, vatName.length - 1);

	var vatRate = parseFloat(vatName, 10);
	if (isNaN(vatRate) == true) vatRate = 0;

	var vatValue = vatRate / 100.0;

	var grossAmount = netAmount * vatValue;
	grossAmount = Math.round(grossAmount * 100) / 100; //round
	
	var $destObj = $(destCtrl);

	$(destCtrl).iwfSetVal(iwfFormatPrice(grossAmount));

	if ($(this)[0].id == $(vatCtrl)[0].id) $(destCtrl).change();
};

jQuery.fn.iwfSum = function() {
	var args = arguments[0] || {};
	var src = args.src;
	var dest = args.dest;

	var priceSum = 0.0;

	$(src).each(function() {
		if ($(this).length == 1) {
			priceSum += $(this).iwfGetPrice();
		}
	});

	$(dest).iwfSetVal(iwfFormatPrice(priceSum));
};


jQuery.fn.iwfBindInvoiceItemRow = function() {
	var netAmount = $(this).find('td.net input');
	var vatRate = $(this).find('td.rate select');
	var vatAmount = $(this).find('td.vat input');
	var grossAmount = $(this).find('td.gross span');

	$(netAmount).bind('keyup change', function(event) {
		if (iwfPreventKeyup(event) == true) { event.preventDefault(); return; }
		$(this).iwfUpdateVat({ srcCtrl: netAmount, destCtrl: vatAmount, vatCtrl: vatRate });
		$(this).iwfSum({ src: [netAmount, vatAmount], dest: grossAmount });
	});

	$(vatRate).bind('change', function(event) {
		$(this).iwfUpdateVat({ srcCtrl: netAmount, destCtrl: vatAmount, vatCtrl: vatRate });
		$(this).iwfSum({ src: [netAmount, vatAmount], dest: grossAmount });
	});

	$(vatAmount).bind('keyup change', function(event) {
		if (iwfPreventKeyup(event) == true) { event.preventDefault(); return; }
		$(this).iwfSum({ src: [netAmount, vatAmount], dest: grossAmount });
	});
};




jQuery.fn.iwfBindInvoiceItems = function() {
	$(this).find('tr:not(.header)').each(function() { $(this).iwfBindInvoiceItemRow(); });

	var items = $(this);
	var rows = $('.invoiceSummary tr:not(.text)');

	// update summary
	$(this).find('td.net input, td.vat input').bind('change', function(event) {
		//foreach row in summary
		rows.each(function() {
			var netAmount = $(this).find('.net span');
			var vatAmount = $(this).find('.vat span');
			var grossAmount = $(this).find('.gross span');
			var vatRate = $(this).find('.rate span').text();

			//total summary row will contain all data
			var vatSelector = (vatRate == 'X') ? '' : '[text=' + vatRate + ']';

			var trs = $(items).find('tr:has(option:selected' + vatSelector + ')');

			//X is used for summary header, other values will be ignored
			if ($(trs).length != 0) {
				$(netAmount).iwfSum({ src: $(trs).find('td.net input'), dest: netAmount });
				$(vatAmount).iwfSum({ src: $(trs).find('td.vat input'), dest: vatAmount });
				$(grossAmount).iwfSum({ src: [netAmount, vatAmount], dest: grossAmount });

				if (vatRate == 'X') {
					$(this).find('input[type=hidden]').change();
				}

				if ($.browser.msie) {
					$(this).show();
				}

				if ($(this).is(':hidden') == true) {
					var spans = $(this).find('span');
					$(this).show();
					$(spans).animate({ height: 'show', opacity: 'show' }, 400);
				}
			}
			else {
				if ($(this).is(':hidden') == false) {
					var row = $(this);
					$(this).find('span').slideUp(400, function() {
						$(row).hide();
						$(netAmount).iwfSetVal('n/a');
						$(vatAmount).iwfSetVal('n/a');
						$(grossAmount).iwfSetVal('n/a');
					});
				}
			}
		});
	});

	//update summary table (on load)
	$(items).find('td.vat input:first').change();
};


jQuery.fn.iwfBindInvoice = function() {
	var args = arguments[0] || {};
	var grossPrice = args.grossPrice; //invoice items
	var priceLeft = args.priceLeft;
	var priceSum = args.priceSum; //invoice addrow

	var hidInput = $(priceSum).parent().find('input[type=hidden]');
	var grossPrice = $(grossPrice);
	var priceSum = $(priceSum);

	$([$(hidInput), $(grossPrice)]).each(function() {
		$(this).bind('change keyup', function(event) {

			var sum = $(priceSum).iwfGetPrice();
			var priceGross = $(grossPrice).iwfGetPrice();
			var pricel = (sum - priceGross) * -1;
			if ($(priceLeft).length != 0) { $(priceLeft).iwfSetVal(iwfFormatPrice(pricel)); }
		});
	});
};




jQuery(function($) {
	$.datepicker.regional['pl'] = {
		closeText: 'Zamknij',
		prevText: '&#x3c;Poprzedni',
		nextText: 'Następny&#x3e;',
		currentText: 'Dziś',
		monthNames: ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'],
		monthNamesShort: ['Sty', 'Lu', 'Mar', 'Kw', 'Maj', 'Cze', 'Lip', 'Sie', 'Wrz', 'Pa', 'Lis', 'Gru'],
		dayNames: ['Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'],
		dayNamesShort: ['Nie', 'Pn', 'Wt', 'Śr', 'Czw', 'Pt', 'So'],
		dayNamesMin: ['N', 'Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So'],
		weekHeader: 'Tydz',
		dateFormat: 'dd-mm-yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: '',
		showOn: 'both',
		buttonImage: '/images/calendar.gif',
		buttonImageOnly: true,
		buttonText: 'kalendarz',
		disabled: true,
		numberOfMonths: 1,
		defaultDate: 0
	};
	$.datepicker.setDefaults($.datepicker.regional['pl']);
});
