(function($) {
    // Limit the amount of categories selected, does not return a jquery object
    $.fn.InstallationCategories = function(options) {
        var defaults = {
            alertmsg: 'Only one category can be selected.',
            maxSelected: 1,
            alert: true
        };
        var options = $.extend(defaults, options);

        var c = 0;
        this.each(function() {
            //for each div, now get the checkboxes that are checked
            if ($(this).children().children(':checkbox:checked').size() > 0) { c = c + 1; }
        });

        if (c > options.maxSelected) {
            if (options.alert) alert(options.alertmsg);
            return false;
        }
        else return true;
    };

    // Calculate the total price, does not return a jquery object
    $.fn.InstallationTotal = function(op) {

        var defaults = {         
            txtInstallationPriceID: '#InstallationPrice',
            txtSingleCostID: '#SingleCost',
            txtVAT1ID: '#TotalInclVAT1',
            txtVAT2ID: '#TotalInclVAT2',
            currency: ' Eur'
        };
        var op = $.extend(defaults, op);
	       

        var total = 0;
        this.each(function() {
            $(this).children().children(':checkbox:checked').each(function() {

		var obj = $(this).next().next();
		
		if (obj.next().next().next(':name').val() != '' &&  obj.next().next().next(':name').val() == "forEveryXPrice") {

			var discountUnit = obj.next().next().next().next(':name').val();
			var discountPrice = obj.next().next().next().next().next(':name').val();
			var amount = parseInt(obj.next(':text').val(), 10);
			var articlePrice = parseFloat(obj.text().replace(op.currency, ''), 10);

			var discountAmount = Math.floor(amount / discountUnit);
			var discountedPrice = discountPrice * discountAmount;
			var normalPrice = (amount - discountAmount) * articlePrice;

			total += normalPrice + discountedPrice;

		} else {                
                	var articlePrice = parseFloat(obj.text().replace(op.currency, ''), 10);
	                if (obj.next(':text').val() == '') obj.next(':text').val(1);
        	        var amount = parseInt(obj.next(':text').val(), 10);
                	total += articlePrice * amount;
		}
            });
        });

        var prices = $('input[rel=networkPrice]');       
        var prevMaxPrice = 0;
        var installationPrice = total;
        var singleCost = 0;

        for (var index = 0; index < prices.length; index = index + 1) {

            var arr_price = prices[index].name.split(",");
            var maxPrice = parseInt(arr_price[0], 10);
            var varSingleCost = parseInt(arr_price[1], 10);

            if (index == 0) {
                if (total > 0 && total <= maxPrice) {
                    total += varSingleCost;
                    singleCost = varSingleCost;
                }
            } else if (index < prices.length - 1) {
                if (total >= prevMaxPrice && total < maxPrice) {
                    total += varSingleCost;
                    singleCost = varSingleCost;
                }
            } else {
                if (total > prevMaxPrice) {
                    total += varSingleCost;
                    singleCost = varSingleCost;
                }
            }
            prevMaxPrice = maxPrice;
        }

        $('input[rel=InstallationPrice]').val(installationPrice.toFixed(2).toString() + op.currency);
        $('input[rel=SingleCost]').val(singleCost.toFixed(2).toString() + op.currency);
        $('input[rel=TotalInclVAT1]').val(total.toFixed(2).toString() + op.currency);

        var arr_VATS = $('input[rel=vat]');
        
        if (arr_VATS.length == 2) {
               var totalExclVAT = total - (total * (parseInt(arr_VATS[0].name) / 100));
               var totalInclVAT2 = totalExclVAT + (totalExclVAT * (parseInt(arr_VATS[1].name) / 100));
               $('input[rel=TotalInclVAT2]').val(totalInclVAT2.toFixed(2).toString() + op.currency);
           }
     };

})(jQuery);

jQuery.fn.numeric = function(decimal, callback) {
    decimal = decimal || ".";
    callback = typeof callback == "function" ? callback : function() { };
    this.keypress(
		function(e) {
		    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		    // allow enter/return key (only when in an input box)
		    if (key == 13 && this.nodeName.toLowerCase() == "input") {
		        return true;
		    }
		    else if (key == 13) {
		        return false;
		    }
		    var allow = false;
		    // allow Ctrl+A
		    if ((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return true;
		    // allow Ctrl+X (cut)
		    if ((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return true;
		    // allow Ctrl+C (copy)
		    if ((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return true;
		    // allow Ctrl+Z (undo)
		    if ((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return true;
		    // allow or deny Ctrl+V (paste), Shift+Ins
		    if ((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
			|| (e.shiftKey && key == 45)) return true;
		    // if a number was not pressed
		    if (key < 48 || key > 57) {
		        /* '-' only allowed at start */
		        // if (key == 45 && this.value.length == 0) return true;
		        /* only one decimal separator allowed */
//		        if (key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1) {
//		            allow = false;
//		        }
		        // check for other keys that have special purposes
		        if (
					key != 8 /* backspace */ &&
					key != 9 /* tab */ &&
					key != 13 /* enter */ &&
					key != 35 /* end */ &&
					key != 36 /* home */ &&
					key != 37 /* left */ &&
					key != 39 /* right */ &&
					key != 46 /* del */
				) {
		            allow = false;
		        }
		        else {
		            // for detecting special keys (listed above)
		            // IE does not support 'charCode' and ignores them in keypress anyway
		            if (typeof e.charCode != "undefined") {
		                // special keys have 'keyCode' and 'which' the same (e.g. backspace)
		                if (e.keyCode == e.which && e.which != 0) {
		                    allow = true;
		                }
		                // or keyCode != 0 and 'charCode'/'which' = 0
		                else if (e.keyCode != 0 && e.charCode == 0 && e.which == 0) {
		                    allow = true;
		                }
		            }
		        }
		        // if key pressed is the decimal and it is not already in the field
//		        if (key == decimal.charCodeAt(0) && this.value.indexOf(decimal) == -1) {
//		            allow = true;
//		        }
		    }
		    else {
		        allow = true;
		    }
		    return allow;
		}
	)
	.blur(
		function() {
		    var val = jQuery(this).val();
		    if (val != "") {
		        var re = new RegExp("^\\d+$|\\d*" + decimal + "\\d+");
		        if (!re.exec(val)) {
		            callback.apply(this);
		        }
		    }
		}
	);
    return this;
}