﻿//wfm JS, version 1.2.1
wfmInit();

function wfmInit() {
	//check if function prototype exists
	if (!Array.prototype.forEach)
	{
		Array.prototype.forEach = function (closure)
		{
			var context = arguments[1] || null;
			for (var i = 0; i < this.length; i ++)
			{
				arguments[0].call(context, this[i], i, this);
			}
		}
	}
}

// Checks a string to see if it in a valid date format
// of (D)D/(M)M/(YY)YY and returns true/false
function wfmIsValidDate(s) {
    // format D(D)/M(M)/(YY)YY
    var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;

    if (dateFormat.test(s)) {
        // remove any leading zeros from date values
        s = s.replace(/0*(\d*)/gi, "$1");
        var dateArray = s.split(/[\.|\/|-]/);

        // correct month value
        dateArray[1] = dateArray[1] - 1;

        // correct year value
        if (dateArray[2].length < 4) {
            // correct year value
            dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
        }

        var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
        if (testDate.getDate() != dateArray[0] || testDate.getMonth() != dateArray[1] || testDate.getFullYear() != dateArray[2]) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    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 s;
}

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 IsNewContractor(src, dest, hf, btn, nc, ic) {
    $(dest).val($(src).val());
    $(hf).val('t');
    $(btn).show();

    // postback if currency was change
    //return $(nc).wfmGetVal() != $(ic).text();
    // always postback
    return true;
}

function wfmFormatPrice(value) {
    return CommaFormatted(wfmTruncateToPrice(value).toFixed(2), ' ', ',');
}

function wfmFormatExchangeRate(value) {
    return CommaFormatted(wfmTruncateToExchangeRate(value).toFixed(4), ' ', ',');
}

function wfmTruncateToPrice(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);
}

function wfmTruncateToExchangeRate(i) {
    if (isNaN(i)) { i = 0.0000; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i * 10000) + 0.00001);
    i = i / 10000;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.0000'; }
    if (s.indexOf('.') == (s.length - 4)) { s += '0'; }
    s = minus + s;

    return parseFloat(s);
}

//bind money field
jQuery.fn.wfmBindMoney = function() {
	$(this).each(function() {
		$(this)
			.focus(function() { $(this).select(); })
			.focusout(function() {
				var valF = $(this).wfmGetPrice();
				if (valF > 99999999.99) valF = 99999999.99;

				$(this).val(wfmFormatPrice(valF));
				if (valF == 99999999.99) $(this).change();
			})
	});		
}

function wfmPreventKeyup(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;
}

//Gets value from html element
jQuery.fn.wfmGetVal = function() {
    if ($(this)[0].tagName == 'SPAN')
        return $(this).text(); //get value
    else if ($(this)[0].tagName == 'INPUT')
        return $(this).val(); //set value
    else if ($(this)[0].tagName == 'SELECT')
        return $(this).val(); //set value
    else return ''
};

//simply copy value
jQuery.fn.wfmSetVal = function(value) {
    if ($(this)[0].tagName == 'SPAN')
        $(this).text(value); //get value
    else if ($(this)[0].tagName == 'INPUT') {
        $(this).val(value); //set value
    }
};

//simply copy value
jQuery.fn.wfmGetPrice = function() {
    var val = $(this).wfmGetVal();
    val = val.replace(/ /g, '').replace(',', '.');

    var valF = parseFloat(val);
    if (isNaN(valF) == true) return parseFloat('0');

    //if (valF > 99999999.99) valF = 99999999.99;

    valF = wfmTruncateToPrice(valF);
    return valF;
};


//simply copy value
jQuery.fn.wfmGetExchangeRate = function() {
    var val = $(this).wfmGetVal();
    val = val.replace(/ /g, "").replace(',', '.');

    var valF = parseFloat(val);
    if (isNaN(valF) == true) return parseFloat('0');

    valF = wfmTruncateToExchangeRate(valF);
    return valF;
};


//simply copy value
jQuery.fn.wfmCopy = function() {
    var args = arguments[0] || {};
    var destination = args.destination;

    var sv = $(this).val();
    $(destination).text(sv); //set value
};


jQuery.fn.wfmUpdateVat = function() {
    var args = arguments[0] || {};
    var srcCtrl = args.srcCtrl;
    var destCtrl = args.destCtrl;
    var vatCtrl = args.vatCtrl;
	var vatRates = args.vatRates;
	
    //ignor
    if ($(vatCtrl).length == 0 || $(destCtrl).length == 0) return;

    var priceNet = $(srcCtrl).wfmGetPrice();

    //vat selection must contain '%' char
    var vatName = $(vatCtrl).find('option:selected').text()
    var vatName = vatName.substring(0, vatName.length - 1);

	var vatId = parseInt($(vatCtrl).find('option:selected').val());
	var vatRate = vatRates[vatId];
	
    //var vatRate = parseFloat(vatName, 10);
    if (isNaN(vatRate) == true) vatRate = 0;

    var vatValue = vatRate / 100.0;

    var priceGross = priceNet * vatValue;
    priceGross = Math.round(priceGross * 100) / 100; //round

    var $destObj = $(destCtrl);

    $(destCtrl).wfmSetVal(wfmFormatPrice(priceGross));

    if ($(this)[0].id == $(vatCtrl)[0].id) $(destCtrl).change();
};


jQuery.fn.wfmSum = function() {
    var args = arguments[0] || {};
    var src = args.src;
    var dest = args.dest;

    var priceSum = 0.0;

	if ($(dest).length == 0) return;

    $(src).each(function() {
        if ($(this).length == 1) {
            priceSum += $(this).wfmGetPrice();
        }
    });

    $(dest).wfmSetVal(wfmFormatPrice(priceSum));
};


jQuery.fn.wfmCalculateExcange = function() {
    var args = arguments[0] || {};
    var src = args.src;
    var dest = args.dest;

    var exchangeRate = $(args.exchangeRate).wfmGetExchangeRate();
    if (exchangeRate == undefined) exchangeRate = parseFloat('1');

    var direction = args.direction;

    if (direction == undefined) direction = 'c2pl';
    if ($(dest).length == 0) return;

    var prevVal = $(dest).wfmGetPrice();
    var priceEx = parseFloat('0');

    if (direction == 'c2pl')
        priceEx = $(src).wfmGetPrice() * exchangeRate;
    else
        priceEx = $(src).wfmGetPrice() / exchangeRate;

    priceEx = Math.round(priceEx * 100) / 100;

    $(dest).wfmSetVal(wfmFormatPrice(priceEx));
    //$(dest).change();
};


jQuery.fn.wfmBindInvoiceItemRow = function() {
    var args = arguments[0] || {};
    var exchangeRate = args.exchangeRate; //exchange Rate
    var documentType = args.documentType; //document type
	var vatRates = args.vatRates;

    var netPrice = $(this).find('td.net:first input');
    var netPricePL = $(this).find('td.net.PL input');
    var vatRate = $(this).find('td.vatRate select');
    var vatPrice = $(this).find('td.vat:first input');
    var vatPricePL = $(this).find('td.vat.PL input');
    var grossPrice = $(this).find('td.gross:first span');
    var grossPricePL = $(this).find('td.gross.PL span');

//    //hide vat if document type is receipt
//    if (documentType == 'Receipt') {
//        $(vatRate).parent().hide();
//        $(vatPrice).parent().hide();

//        if ($(netPricePL).length != 0) {
//            $(vatPricePL).parent().hide();
//        }
//    }

    $(netPrice).bind('keyup change', function(event) {
        //$(this).wfmInputPriceFormatCheck();
        if (wfmPreventKeyup(event) == true) { event.preventDefault(); return; }

        $(this).wfmUpdateVat({ srcCtrl: netPrice, destCtrl: vatPrice, vatCtrl: vatRate, vatRates: vatRates });
        $(this).wfmSum({ src: [netPrice, vatPrice], dest: grossPrice });

        //other currencies
        if ($(netPricePL).length != 0) {
            $(this).wfmCalculateExcange({ src: netPrice, dest: netPricePL, exchangeRate: exchangeRate });
            $(this).wfmUpdateVat({ srcCtrl: netPricePL, destCtrl: vatPricePL, vatCtrl: vatRate, vatRates: vatRates });
            $(this).wfmSum({ src: [netPricePL, vatPricePL], dest: grossPricePL });
        }
    });

    $(vatRate).bind('change', function(event) {
        $(this).wfmUpdateVat({ srcCtrl: netPrice, destCtrl: vatPrice, vatCtrl: vatRate, vatRates: vatRates });
        $(this).wfmSum({ src: [netPrice, vatPrice], dest: grossPrice });
    });

    $(vatPrice).bind('keyup change', function(event) {
        if (wfmPreventKeyup(event) == true) { event.preventDefault(); return; }

        $(this).wfmSum({ src: [netPrice, vatPrice], dest: grossPrice });
    });

    //bind when present
    if ($(netPricePL).length == 0) return;

    $(netPricePL).bind('keyup change', function(event) {
        if (wfmPreventKeyup(event) == true) { event.preventDefault(); return; }

        $(this).wfmUpdateVat({ srcCtrl: netPricePL, destCtrl: vatPricePL, vatCtrl: vatRate, vatRates: vatRates });
        $(this).wfmSum({ src: [netPricePL, vatPricePL], dest: grossPricePL });
    });

    $(vatRate).bind('change', function(event) {
        $(this).wfmUpdateVat({ srcCtrl: netPricePL, destCtrl: vatPricePL, vatCtrl: vatRate, vatRates: vatRates });
        $(this).wfmSum({ src: [netPricePL, vatPricePL], dest: grossPricePL });
    });

    $(vatPricePL).bind('keyup change', function(event) {
        if (wfmPreventKeyup(event) == true) { event.preventDefault(); return; }

        $(this).wfmSum({ src: [netPricePL, vatPricePL], dest: grossPricePL });
    });

};

var wfm_updateSummary = true;

jQuery.fn.wfmBindInvoiceItems = function() {
	var args = arguments[0] || {};
	var items = args.items; //invoice items
	var addItem = args.addItem; //invoice addrow
	var exchangeRate = args.exchangeRate; // alert(exchangeRate);
	var documentType = args.documentType;
	var vatRatesString = args.vatRates;
	
	//deserialize vat rates map
	vatRatesString = vatRatesString.substring(1, vatRatesString.length - 1);
	var vatRates=new Array();
	if(vatRatesString.length > 0){
		var vatList = vatRatesString.split(',');	
		vatList.forEach(function(element, index, array) {
		var temp = element.split(':');
			vatRates[parseInt(temp[0].replace('"', ''))] = parseFloat(temp[1].replace('"', ''));
		});
	}
	
	$(items).find("input.money").wfmBindMoney();

	//bind each invoice item row
	$(items).find('tr:not(.addItem)').each(function() {
		$(this).wfmBindInvoiceItemRow({ exchangeRate: exchangeRate, documentType: documentType, vatRates: vatRates });
	});

	//bind add row
	$(items).find('tr.addItem').each(function() {
		$(this).wfmBindInvoiceItemRow({ exchangeRate: exchangeRate, documentType: documentType, vatRates: vatRates}); //should be one
	});

	//$(this) is summary main container
	var rows = $(this).find('tr:not(:first)');

	// update summary
	$(items).find('tr:not(.addItem) td.net input, tr:not(.addItem) td.vat input').bind('change', function(event) {
		if (!wfm_updateSummary) return;

		//foreach row in summary
		rows.each(function() {
			var netPrice = $(this).find('.net:not(.PL) span');
			var netPricePL = $(this).find('.net.PL span');
			var vatPrice = $(this).find('.vat:not(.PL) span');
			var vatPricePL = $(this).find('.vat.PL span');
			var grossPrice = $(this).find('.gross:not(.PL) span');
			var grossPricePL = $(this).find('.gross.PL span');
			var vatCode = $(this).find('.vatRate span').text();

			//main summary row will contain all data
			var vatSelector = (vatCode == 'X') ? '' : "[text='" + vatCode + "']";

			var trs = $(items).find('tr:not(.addItem):has(option:selected' + vatSelector + ')');

			if (documentType == 'Receipt' && vatCode == '0%') {
				trs = $(items).find('tr:not(.addItem)'); //re-search, get all rows because they have 0% vat, but select isn't rendered to html
			}

			//X is used for summary header, other values will be ignored
			//there are invoice lines to calculate summary for given vatRate
			if ($(trs).length != 0) {
				netPrice.wfmSum({ src: $(trs).find('td.net:not(.PL) input'), dest: netPrice });
				vatPrice.wfmSum({ src: $(trs).find('td.vat:not(.PL) input'), dest: vatPrice });
				grossPrice.wfmSum({ src: [netPrice, vatPrice], dest: grossPrice });

				if ($(netPricePL).length != 0) {
					netPrice.wfmSum({ src: $(trs).find('td.net.PL input'), dest: netPricePL });
					vatPrice.wfmSum({ src: $(trs).find('td.vat.PL input'), dest: vatPricePL });
					grossPrice.wfmSum({ src: [netPricePL, vatPricePL], dest: grossPricePL });
				}

				if (vatCode == '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();
						$(netPrice).wfmSetVal('n/a');
						$(vatPrice).wfmSetVal('n/a');
						$(grossPrice).wfmSetVal('n/a');

						if ($(netPricePL).length != 0) {
							$(netPricePL).wfmSetVal('n/a');
							$(vatPricePL).wfmSetVal('n/a');
							$(grossPricePL).wfmSetVal('n/a');
						};
					});
				}
			}
		});
	});

	if (exchangeRate != '#') {
		$(exchangeRate).bind('change', function(event) {
			wfm_updateSummary = false;

			$(items).find('tr:not(.addItem)').each(function() {
				$(this).find('td.net:first input').change();
			});

			wfm_updateSummary = true;
			//update summary table
			$(items).find('tr:not(.addItem) td.vat input:first').change();
		});
	}

	//update summary table (on load)
	$(items).find('td.vat input:first').change();
};


jQuery.fn.wfmBindInvoice = function() {
	var args = arguments[0] || {};
	var grossPrice = args.grossPrice; //invoice gross price
	var netPrice = args.netPrice; //invoice net price

	var priceLeft = args.priceLeft;
	var priceSum = args.priceSum; //invoice price sum   

	var priceLeftPLN = args.priceLeftPLN;
	var priceSumPLN = args.priceSumPLN;

	$(grossPrice).wfmBindMoney();
	$(netPrice).wfmBindMoney();

	//	var lbShowContractor = args.lbShowContractor;
	//	var pnContractor = args.pnContractor;
	//	var lbShowAddContractor = args.lbShowAddContractor; // add contractor
	//	var lbShowEditContractor = args.lbShowEditContractor;
	//	var pnAddContractor = args.pnAddContractor;

	var exchangeRate = args.exchangeRate;

	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 priceGross = $(grossPrice).wfmGetPrice(); //price declared

			if ($(priceLeft).length != 0) {
				var sum = $(priceSum).wfmGetPrice();
				var pricel = (priceGross - sum);

				$(priceLeft).wfmSetVal(wfmFormatPrice(pricel));
			}

			if ($(exchangeRate).length != 0) {
				var exRate = $(exchangeRate).wfmGetExchangeRate();
				if (exRate == undefined) exRate = parseFloat('1');

				var priceGrossPLN = priceGross * exRate;
				priceGrossPLN = Math.round(priceGrossPLN * 100) / 100;

				var sumPLN = $(priceSumPLN).wfmGetPrice();
				var leftPLN = (priceGrossPLN - sumPLN);

				$(priceLeftPLN).wfmSetVal(wfmFormatPrice(leftPLN));
			}
		});
	});
};

jQuery.fn.wfmBindRWG = function() {
    var args = arguments[0] || {};
    var lSumValue = args.sumValue;
    var lAdvanceValue = args.advanceValue;
    var lPaymentValue = args.paymentValue;
    var iAdvanceAmount = args.advanceAmount;

    $(iAdvanceAmount).each(function() {
        $(this).bind('change keyup', function(event) {

            if ($(lAdvanceValue).get(0) == null) return;
            $(lAdvanceValue).wfmSetVal(wfmFormatPrice($(iAdvanceAmount).wfmGetPrice()));

            var sum = $(lSumValue).wfmGetPrice();
            var advance = $(lAdvanceValue).wfmGetPrice();
            var pricel = sum - advance;
            $(lPaymentValue).wfmSetVal(wfmFormatPrice(pricel));
        });
    });
    $(iAdvanceAmount).change();
};

jQuery.fn.wfmFixedBox = 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: 'auto',
				display: 'block'
			});
		}
		else
		{
			jQuery(this).css({
				position: 'fixed',
				zIndex: '101',
				top: y + 'px',
				left: x + 'px',
				width: w + 'px',
				height: h + 'px',
				overflow: 'auto',
				display: 'block'
			});
		}
	}));
};


jQuery.fn.wfmBindPicker = function() {
    var args = arguments[0] || {};
    var lbShow = args.lbShow;
    var pnPicker = args.pnPicker;

    var picker = $(pnPicker);

    //    var _checkExternalClick = function(event) {
    //        var $target = $(event.target);
    //        if ($target[0].id != $(picker)[0].id &&
    //			$target.parents('#' + $(picker)[0].id).length == 0
    //		) {
    //            $(picker).hide();
    //            $($(picker).find('input[type=hidden]')[0]).val("t");
    //        }
    //    };
	
	

    $(lbShow).bind('click', function(event) {
        $('.ContentPickerClose').click();
        //picker.slideDown('medium');
        picker.wfmShowModal({width: '950px'});
        $($(picker).find('input[type=hidden]')[0]).val("t");

        event.preventDefault();
    });

    $('.ContentPickerClose, .ContentPickerCloseB', $(picker)).click(function() {
        //$(picker).hide();
        $(picker).wfmHideModal();
        $($(picker).find('input[type=hidden]')[0]).val("f");		
    });

    //$(document).mousedown(_checkExternalClick);

};


jQuery.fn.wfmBindModal = 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).wfmHideModal();
			$($(picker).find('input[type=hidden]')[0]).val("f");
			
			//consume event
			event.preventDefault();
		}

		// var $target = $(event.target);
		// if ($target[0].id != $(picker)[0].id &&
			// $target.parents('#' + $(picker)[0].id).length == 0
		// ) 
		// {
			// $(picker).wfmHideModal();
			// $($(picker).find('input[type=hidden]')[0]).val("f");
		// }
	};

    var picker = $(container);
	var hfVisible = $(container).find('input[type=hidden]');
	
	//update panel modal set visible
	if ($(hfVisible[0]).val() == "t")
	{
		picker.wfmShowModal();
	}
	// else if ($(hfVisible[0]).val() == "f" && picker.is(':hidden') == false )
	// {
		// picker.wfmHideModal();
	// }
	

    $(this).bind('click', function(event) {
        $('.ContentPickerClose').click();
        
		picker.wfmShowModal();
        $($(picker).find('input[type=hidden]')[0]).val("t");

        if (preventDefault) event.preventDefault();
    });

	$(picker).find('.ContentPickerClose').bind('click', function() {
		$(picker).wfmHideModal();
        $($(picker).find('input[type=hidden]')[0]).val("f");
	});
	
    // $('.ContentPickerClose, .ContentPickerCloseB', $(picker)).click(function() {
        // $(picker).wfmHideModal();
        // $($(picker).find('input[type=hidden]')[0]).val("f");
    // });

    $(document).keyup(_checkExternalKeyDown);
};


jQuery.fn.wfmShowModal = 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>');	
	}

    // Get page sizes
    var arrPageSizes = ___getPageSize();
    // Style overlay and show it
    $('#jquery-overlay').css({
        backgroundColor: '#000',
        opacity: 0.8,
        width: arrPageSizes[0],
        height: arrPageSizes[1]
    }).fadeIn();

    //    // Assigning click events in elements to close overlay
    //    $('#jquery-overlay').click(function() {
    //        $('#jquery-overlay').remove();
    //        $('#' + divId).css("display", "none");
    //    });
	
	//static width    
    //$(this).css({ width: width });

	$(this).wfmFixedBox();
};

//hides modal displayed div and overlay
jQuery.fn.wfmHideModal = function() {
    
	$('#jquery-overlay').css({
        opacity: 0.0        
    }).fadeIn();
	
	$('#jquery-overlay').remove();

    $(this).css("display", "none");
};

jQuery.fn.wfmScrollToMessageBox = function() {
    $(window).scrollTo($(this), 1000, { offset: -10, easing: 'easeOutBounce' });
};

jQuery.fn.wfmBindPrint = function() {
    var args = arguments[0] || {};
    var container = args.container;
    var pageTitle = args.pageTitle;
    var additionalStyles = args.additionalStyles == null ? '' : args.additionalStyles;
    var classNameToAdd = args.classNameToAdd;

    $(this).bind('click', function(event) {
        $(container).printElement(
			{
			    printMode: 'popup',
			    //leaveOpen: true,
			    printBodyOptions:
				{
				    styleToAdd: 'padding:0px;margin:0px;' + additionalStyles,
				    classNameToAdd: classNameToAdd == null ? 'wfm wfmPrint' : classNameToAdd
				},
			    pageTitle: pageTitle
			})
        event.preventDefault();
    });
};

//hides modal displayed div and overlay
jQuery.fn.BindExchangeRate = function() {
    $(this).bind('change', function(event) {
        var dateVal = $(this).wfmGetVal();

        //check if date is valid
        if (wfmIsValidDate(dateVal) == false) return;
        event.preventDefault();
        //date is valid, do postback to get valid exchange rate
        setTimeout('__doPostBack(\'' + $(this)[0].id.replace(/_/g, '$') + '\',\'\')', 0)
    });
};


//example code
$(function() {
    //    $("#InvoiceItems1_invoiceItemAdd_txtPriceNet").click(function(event) {
    //        $(this).css("background", "orange");
    //    });
});


jQuery.fn.AddLog = function() {
    $(this).val($(this).val() + arguments[0] + "\n");
};


//auto update and bind function
$(function() {
    //$('.wfm input.date').datepicker();
    $('.wfm input.date').mask('99-99-9999');
//    $(".money").focus(function() { $(this).select(); });
//    $(".money").focusout(function() {
//        var valF = $(this).wfmGetPrice();
//        if (valF > 99999999.99) valF = 99999999.99;

//        $(this).val(wfmFormatPrice(valF));
//        if (valF == 99999999.99) $(this).change();
//    });

    $(".exchangeRate").focus(function() { $(this).select(); });
    $(".exchangeRate").focusout(function() {
        var result = $(this).wfmGetExchangeRate();
        $(this).val(wfmFormatExchangeRate(result))
    });

});

