
if (!Array.prototype.filter){
	Array.prototype.filter = function(fun /*, thisp*/) {
		var len = this.length;
		if (typeof fun != "function") throw new TypeError();
		var res = new Array();
		var thisp = arguments[1];
		for (var i = 0; i < len; i++) {
			if (i in this) {
				var val = this[i];
				// in case fun mutates this
				if (fun.call(thisp, val, i, this))
					res.push(val);
			}
		}
		return res;
	};
 }

ib_tools_methods = function() {
	this.forzeInteger = function(a) {
		if (a == "" || isNaN(a) || a == undefined) {
			return 0
		} else {
			return parseInt(a)
		}
	}
}
var ib_tools = new ib_tools_methods()

ib_customValidator_Methods = function() {
    /*Generic empty validation allways valid*/
    this.validateNone = function(a, b) {
        b.IsValid = true;
    }

    /*Validation Card Number*/
    var barcodeExpression = /^\d{13}$/
    this.validateBarcode = function(a, b) {
        b.IsValid = (b.Value.search(barcodeExpression) != -1)
    }

    /*Validation Card Number*/
    var cardExpression = /^\d{12,16}$/
    this.validateCard = function(a, b) {
        if (b.Value == "") {
            b.IsValid = true;
        } else {
            b.IsValid = (b.Value.search(cardExpression) != -1)
        }
    }

    /*Validation Zipcode*/
    var zipCodeExpression = /^\d{4,}$/
    this.validateZipCode = function(a, b) {
        if (b.Value == "") {
            b.IsValid = true;
        } else {
            b.IsValid = (b.Value.search(zipCodeExpression) != -1)
        }
    }

    var dateExpression = /^(0[1-9]|1\d|2\d|3[0-1])\/(0[1-9]|1[0-2])\/\d{4}$/
    this.validateDate = function(a, b) {
        if (b.Value == "") {
            b.IsValid = true;
        } else {
            b.IsValid = (b.Value.search(dateExpression) != -1)
        }
    }

    var timeExpression = /^(\d|0[0-9]|1\d|2[0-3])\:([0-5]\d)$/
    this.validateTime = function(a, b) {
        if (b.Value == "") {
            b.IsValid = true;
        } else {
            b.IsValid = (b.Value.search(timeExpression) != -1)
        }
    }

    this.validateInteger = function(a, b) {
        if (b.Value == "") {
            b.IsValid = true;
        } else {
            b.IsValid = (b.Value.search(/^(\d+)$/) != -1)
        }
    }

    var moneyExpression = /^\d*([\.|,]\d{1,2})?$/;
    this.validateMoney = function(a, b) {
        if (b.Value == "") {
            b.IsValid = true
        } else {
            b.IsValid = moneyExpression.test(b.Value)
        }
    }

    this.validateCodiceFiscale = function(a, b) {
        b.IsValid = true;
        if (b.Value != "") {
            var validi, i, s, set1, set2, setpari, setdisp;
            b.Value = b.Value.toUpperCase();
            if (b.Value.length == 16) {
                validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                for (i = 0; i < 16; i++) {
                    if (validi.indexOf(b.Value.charAt(i)) == -1) {
                        //"Il codice fiscale contiene un carattere non valido '" + b.Value.charAt(i) +"'.I caratteri validi sono le lettere e le cifre.";
                        b.IsValid = false;
                    }
                }
                set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
                setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
                s = 0;
                for (i = 1; i <= 13; i += 2)
                    s += setpari.indexOf(set2.charAt(set1.indexOf(b.Value.charAt(i))));
                for (i = 0; i <= 14; i += 2)
                    s += setdisp.indexOf(set2.charAt(set1.indexOf(b.Value.charAt(i))));
                if (s % 26 != b.Value.charCodeAt(15) - 'A'.charCodeAt(0)) {
                    //"Il codice fiscale non è corretto: il codice di controllo non corrisponde.";
                    b.IsValid = false;
                }
            } else if (b.Value.length == 11) {
                this.validatePartitaIVA(a, b)
            } else {
                b.IsValid = false;
            }
        }
    }

    this.validatePartitaIVA = function(a, b) {
        b.IsValid = true;
        if (b.Value != '') {
            if (b.Value.length != 11) {
                //"La lunghezza della partita IVA non è corretta: la partita IVA dovrebbe essere lunga esattamente 11 caratteri.";
                b.IsValid = false;
            }
            validi = "0123456789";
            for (i = 0; i < 11; i++) {
                if (validi.indexOf(b.Value.charAt(i)) == -1) {
                    //"La partita IVA contiene un carattere non valido '"+ b.value.charAt(i) + "'.I caratteri validi sono le cifre.";
                    b.IsValid = false;
                }
            }
            s = 0;
            for (i = 0; i <= 9; i += 2)
                s += b.Value.charCodeAt(i) - '0'.charCodeAt(0);
            for (i = 1; i <= 9; i += 2) {
                c = 2 * (b.Value.charCodeAt(i) - '0'.charCodeAt(0));
                if (c > 9) c = c - 9;
                s += c;
            }
            if ((10 - s % 10) % 10 != b.Value.charCodeAt(10) - '0'.charCodeAt(0)) {
                //"La partita IVA non è valida: il codice di controllo non corrisponde.";
                b.IsValid = false;
            }
        }
    }
}

var ib_validator = new ib_customValidator_Methods()


function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
	if (rnum == undefined) { 
		return 0
	} else {
		rnum = rnum.toString().replace(",", ".");
		if (rlength == undefined) {
			rlength = 2;
		}
		var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
		return parseFloat(newnumber); // Output the result to the form field
	}
}


function dropdown_menu_hack(el) {
	if (el.runtimeStyle.behavior.toLowerCase() == "none") { return; }
	el.runtimeStyle.behavior = "none";

	var ie5 = false;
	el.ondblclick = function(e) {
		window.event.returnValue = false;
		return false;
	}



	if (window.createPopup == null) {

		var fid = "dropdown_menu_hack_" + Date.parse(new Date());

		window.createPopup = function() {
			if (window.createPopup.frameWindow == null) {
				el.insertAdjacentHTML("AfterEnd", "<iframe   id='" + fid + "' name='" + fid + "' src='about:blank'  frameborder='1' scrolling='no'></></iframe>");
				var f = document.frames[fid];
				f.document.open();
				f.document.write("<html><body></body></html>");
				f.document.close();
				f.fid = fid;


				var fwin = document.getElementById(fid);
				fwin.style.cssText = "position:absolute;top:20px;left:0;display:none;z-index:99999;";


				f.show = function(px, py, pw, ph, baseElement) {
					py = py + baseElement.getBoundingClientRect().top + Math.max(document.body.scrollTop, document.documentElement.scrollTop);
					px = px + baseElement.getBoundingClientRect().left + Math.max(document.body.scrollLeft, document.documentElement.scrollLeft);
					fwin.style.width = pw + "px";
					fwin.style.height = ph + "px";
					fwin.style.posLeft = px;
					fwin.style.posTop = py;
					fwin.style.display = "block";
				}


				f_hide = function(e) {
					if (window.event && window.event.srcElement && window.event.srcElement.tagName && window.event.srcElement.tagName.toLowerCase() == "select") { return true; }
					fwin.style.display = "none";
				}
				f.hide = f_hide;
				//document.attachEvent("onclick", f_hide);
				document.attachEvent("onkeydown", f_hide);

			}
			return f;
		}
	}


	var _borderColor = "#a4b97f"
	var _panelBackground = "white"

	var _backColor_default = "white"
	var _foreColor_default = "black"
	var _backColor_hover = "#e0e6cc"
	var _foreColor_hover = "#3f4f08"
	var _itemsAlign = "left"


	function showMenu() {

		function selectMenu(obj) {
			var o = document.createElement("option");
			o.value = obj.value;
			o.innerHTML = obj.innerHTML;
			while (el.options.length > 0) { el.options[0].removeNode(true); }
			el.appendChild(o);
			el.title = o.innerHTML;
			el.contentIndex = obj.selectedIndex;
			el.menu.hide();
			var newEvt = document.createEventObject()
			document.all(el.id).fireEvent("onChange", newEvt)
		}


		el.menu.show(0, el.offsetHeight, 10, 10, el);
		var mb = el.menu.document.body;

		mb.style.cssText = "border:solid 1px " + _borderColor + ";margin:0;padding:0;overflow-y:auto;overflow-x:auto;background:" + _panelBackground + ";text-align:" + _itemsAlign + ";font-family:Verdana;font-size:12px;";
		var t = el.contentHTML;
		t = t.replace(/<select/gi, '<ul');
		t = t.replace(/<option/gi, '<li');
		t = t.replace(/<\/option/gi, '</li');
		t = t.replace(/<\/select/gi, '</ul');
		mb.innerHTML = t;


		el.select = mb.all.tags("ul")[0];
		el.select.style.cssText = "list-style:none;margin:0;padding:0;";
		mb.options = el.select.getElementsByTagName("li");

		for (var i = 0; i < mb.options.length; i++) {
			mb.options[i].selectedIndex = i;
			mb.options[i].style.cssText = "list-style:none;margin:0;padding:1px 2px;width/**/:100%;cursor:hand;cursor:pointer;white-space:nowrap;"
			mb.options[i].title = mb.options[i].innerHTML;
			mb.options[i].innerHTML = mb.options[i].innerHTML;
			mb.options[i].style.whiteSpace = "nowrap"
			mb.options[i].onmouseover = function() {
				if (mb.options.selected) { mb.options.selected.style.background = _backColor_default; mb.options.selected.style.color = _foreColor_default; }
				mb.options.selected = this;
				this.style.background = _backColor_hover; this.style.color = _foreColor_hover;
			}

			mb.options[i].onmouseout = function() { this.style.background = _backColor_default; this.style.color = _foreColor_default; }
			mb.options[i].onmousedown = function() { selectMenu(this); }
			mb.options[i].onkeydown = function() { selectMenu(this); }

			if (i == el.contentIndex) {
				mb.options[i].style.background = _backColor_hover;
				mb.options[i].style.color = _foreColor_hover;
				mb.options.selected = mb.options[i];
			}
		}


		var mw = Math.max((el.select.offsetWidth + 22), el.offsetWidth + 22);
		mw = Math.max(mw, (mb.scrollWidth + 22));
		var mh = mb.options.length * 15 + 8;

		var mx = (ie5) ? -3 : 0;
		var my = el.offsetHeight - 2;
		var docH = document.documentElement.offsetHeight;
		var bottomH = docH - el.getBoundingClientRect().bottom;

		mh = Math.min(mh, Math.max((docH - el.getBoundingClientRect().top - 50), 100));

		if ((bottomH < mh)) {
			mh = Math.max((bottomH - 12), 10);
			if (mh < 100) {
				my = -100;
			}
			mh = Math.max(mh, 100);
		}

		self.focus();

		el.menu.show(mx, my, mw, mh, el);
		sync = null;
		if (mb.options.selected) {
			mb.scrollTop = mb.options.selected.offsetTop;
		}

		window.onresize = function() { el.menu.hide() };
	}


	function switchMenu() {
		if (event.keyCode) {
			if (event.keyCode == 40) { el.contentIndex++; }
			else if (event.keyCode == 38) { el.contentIndex--; }
		} else if (event.wheelDelta) {
			if (event.wheelDelta >= 120)
				el.contentIndex++;
			else if (event.wheelDelta <= -120)
				el.contentIndex--;
		} else {
			return true;
		}

		if (el.contentIndex > (el.contentOptions.length - 1)) {
			el.contentIndex = 0;
		} else if (el.contentIndex < 0) {
			el.contentIndex = el.contentOptions.length - 1;
		}

		var o = document.createElement("option");
		o.value = el.contentOptions[el.contentIndex].value;
		o.innerHTML = el.contentOptions[el.contentIndex].text;
		while (el.options.length > 0) { el.options[0].removeNode(true); }
		el.appendChild(o);
		el.title = o.innerHTML;
	}

	if (dropdown_menu_hack.menu == null) {
		dropdown_menu_hack.menu = window.createPopup();
		document.attachEvent("onkeydown", dropdown_menu_hack.menu.hide);
	}
	el.menu = dropdown_menu_hack.menu;
	el.contentOptions = new Array();
	el.contentIndex = el.selectedIndex;
	el.contentHTML = el.outerHTML;

	for (var i = 0; i < el.options.length; i++) {
		el.contentOptions[el.contentOptions.length] = {
			"value": el.options[i].value,
			"text": el.options[i].innerHTML
		}

		if (!el.options[i].selected) { el.options[i].removeNode(true); i--; };
	}


	el.onkeydown = switchMenu;
	el.onclick = showMenu;
	el.onmousewheel = switchMenu;
}



function DocumentGetTotalProducts() {
	var total = 0;
	$(".TotalAmount").each(function() {
		var current = 0
		if ($(this)[0].nodeName == "SPAN") {
			current = $(this).text().replace(",", ".");
		} else {
			current = $(this).val().replace(",", ".");
		}

		if ((current != "") && (!isNaN(current))) {
			total += parseFloat(current);
		}
	})
	return roundNumber(total);
}

function DocumentGetTotalPayments() {
	var payed = 0;
	$(".PaymentAmount").each(function() {
		var current = $(this).find("input[type='text']").val().replace(",", ".");
		if ((current != "") && (!isNaN(current))) {
			payed += parseFloat(current);
		}
	})
	return roundNumber(payed);
}

function DocumentSetRemain(sender) {

	var total = DocumentGetTotalProducts();
	var payed = DocumentGetTotalPayments();
	var remain = total - payed;

	var target = $(sender).parent().parent().find("input[type='text']")
	if ((target.val() != "") && (!isNaN(target.val()))) {
		remain += parseFloat(target.val());
		payed -= parseFloat(target.val());
	}

	if (remain < 0) {
		remain = 0
	}
	target.val(remain)
	payed += remain;

	$(".Totals_Products").text(roundNumber(total))
	$(".Totals_Payments").text(roundNumber(payed))
	$(".Totals_Balance").text(roundNumber(total - payed))

}

function DocumentSetTotals() {
	
	var total = DocumentGetTotalProducts();
	var payed = DocumentGetTotalPayments();
	var balance = total - payed;

	$(".Totals_Products").text(roundNumber(total))
	$(".Totals_Payments").text(roundNumber(payed))
	$(".Totals_Balance").text(roundNumber(total - payed))
}

function validatePayments(a, b) {
	b.IsValid = (DocumentGetTotalProducts() == DocumentGetTotalPayments());
}



function ProductsRowMonitor(sender) {
	var className = sender.className;
	var rowClass = className.match(/row\d/)[0]  // row0 , row1, ...
	var colClass = jQuery.trim(className.match(/col\w+\s/)[0]); // colQty, colUnitAmount
	var value = sender.value
	
	if (!$(sender).is(".colTotal:input[type='text']")) {

		//Qty
		var qty = $("." + rowClass + ".colQty").val();
		//UnitAmount
		var unitAmount = roundNumber($("." + rowClass + ".colUnitAmount").text());
		//BaseAmount
		var baseAmount = (qty * unitAmount);
		//Discount

		var discount = $("." + rowClass + ".colDiscount").val();
		var simbol = $("." + rowClass + ".colDiscountSimbol").text();
		var discountAmount = 0;
		if (discount != undefined) {
			if (simbol == "%") {
				discountAmount = roundNumber((baseAmount * roundNumber(discount)) / 100)
			} else {
				discountAmount = roundNumber(discount)
			}
		} else {
			discount = 0
			discountAmount = 0
		}

		//TaxableAmount
		var taxableAmount = roundNumber(baseAmount - discountAmount)
		//VatAmount
		var vatPct = $("." + rowClass + ".colVat").text()
		var vatAmount = roundNumber((taxableAmount * roundNumber(vatPct)) / 100)
		//Total
		var totalAmount = roundNumber((taxableAmount + vatAmount))

		$("span." + rowClass + ".colBaseAmount").text(baseAmount.toString().replace(".", ","));
		$("." + rowClass + ".colBaseAmount:input").text(baseAmount.toString().replace(".", ","));

		$("span." + rowClass + ".colTaxableAmount").text(taxableAmount.toString().replace(".", ","));
		$("." + rowClass + ".colTaxableAmount:input").val(taxableAmount.toString().replace(".", ","));

		$("span." + rowClass + ".colTotal").text(totalAmount.toString().replace(".", ","));
		$("." + rowClass + ".colTotal:input").val(totalAmount.toString().replace(".", ","));


		var totalInput = $("." + rowClass + ".colTotal")[0]
		DocumentSetTotals(); totalMonitor(totalInput);
	} else {
		DocumentSetTotals(); totalMonitor(sender);
	}
}

function document_HasProducts(a,b) {
	b.IsValid = ($(".ProductDescription").length > 0);
}

function document_HasZero(a, b) {
	var total = DocumentGetTotalPayments()
	b.IsValid = (total > 0)
}

function validateApp(a, b) {
    b.IsValid = $("span.chk-app > input:checked").length > 0;
}

function validateRecharge(a, b) {
    b.IsValid = $("span.chk-gift > input:checked").length == 1;
}

function validateQty(a, b) {
    b.IsValid = $(".validate").length > 0;
}

function formatHour(val) {
    var hour, min;

    if (val == '')
        return '';
    else {
        val = val.replace(".", ":");
        arr = val.split(':');

        if (arr[0].length < 2) {
            hour = pad(arr[0], 2, "0", 1);
        } else {
            hour = arr[0];
        }

        if (arr[1] == undefined) {
            min = "00";
        } else if (arr[1].length < 2) {
            min = pad(arr[1], 2, "0", 2);
        } else {
            min = arr[1];
        }

        return hour + ":" + min;
    }
}

function pad(str, len, pad, dir) {
    if (len + 1 >= str.length) {
        switch (dir) {
            case 1:
                str = Array(len + 1 - str.length).join(pad) + str;
                break;
            case 2:
                str = str + Array(len + 1 - str.length).join(pad);
                break;
        }
       }
    return str;
}

function readCard(sender, target, div) {
	var _sender;
	var _target;
	
	if (typeof(target) == "string") {
		_target = "#" + target;
	} else {
		_target = target;
	}

	if (typeof (sender) == "string") {
		_sender = "#" + sender;
	} else {
		_sender = sender;
	}


	if ($(_target).val() == "") {
		$(_target).val(read(div))
	}
	var empty = ($(_target).val() == "");
	if (!empty) {
		var postBack = Sys.WebForms.PageRequestManager.getInstance();
		//debugger
		postBack._doPostBack($(_sender)[0].name, "");
	}
}

function read(div) {
	var divMsg = $("#" + div);
	divMsg.hide();

    try {
        reader.ChkInstallazione();
    } catch (e) {
        divMsg.html('Lettore SmartCard non disponibile per questo Browser!').show();

        return "";
    }

    var atr = reader.LeggiATR();

    if (reader.errCode == 0) {
        if (atr == "3B:4:A2:13:10:91") {
            reader.ChkInstallazione(reader.ChkVersione().selectNodes("/InstallFile/Cab[@name='DeDSyncCard.cab']"));
            reader.IMEL().IMELCardInit();
            //var number = reader.IMEL().IMELNumeroCarta();
            var number = reader.IMEL().IMELCodiceCarta();
            number = number.substr(3, 12);

            reader.IMEL().IMELCardClose();

            return number;
        } else {
            divMsg.html('Carta ICE-Beauty non valida.').show();
        }
    } else {
        if (reader.errCode == -2146434967) {
            divMsg.html('Carta ICE-Beauty non inserita.').show();
        } else {
            divMsg.html('Errore di lettura della Carta ICE-Beauty.').show();
        }
    }

    return "";
}

function showRowDetails(target, sender) {
	$("#" + target).slideToggle("slow", function() {
		if ($("#" + target).is(":visible")) {
			$(sender).addClass("Icon-MagnifierCollapse");
			$(sender).removeClass("Icon-MagnifierExpand");
		} else {
			$(sender).removeClass("Icon-MagnifierCollapse");
			$(sender).addClass("Icon-MagnifierExpand");
		}
	})
}

function toggleAllDetails(sender){
	if($(sender).is(".collapseAll")){
		$(".detailsCell > div").slideUp()
		$(sender).removeClass("collapseAll").removeClass("Icon-MagnifierCollapse").addClass("Icon-MagnifierExpand");
		$(".DetailsTrigger").removeClass("Icon-MagnifierCollapse").addClass("Icon-MagnifierExpand");
	}else{
		$(".detailsCell > div").slideDown()
		$(sender).addClass("collapseAll").removeClass("Icon-MagnifierExpand").addClass("Icon-MagnifierCollapse");
		$(".DetailsTrigger").removeClass("Icon-MagnifierExpand").addClass("Icon-MagnifierCollapse");
	}
	 
}

function filterKeys(e) {
    var chars = "1234567890,"
    var chr = String.fromCharCode(e.charCode == undefined ? e.keyCode : e.charCode);
    return e.ctrlKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
}

function cleanForm(type) {
    $("." + type + "-reset:input").each(function() {
        this.value = "";
    });
}

function showonlyone(thechosenone) {
      var newboxes = document.getElementsByTagName("div");
            for(var x=0; x<newboxes.length; x++) {
                  name = newboxes[x].getAttribute("name");
                  if (name == 'newboxes') {
                        if (newboxes[x].id == thechosenone) {
                        newboxes[x].style.display = 'block';
                  }
                  else {
                        newboxes[x].style.display = 'none';
                  }
            }
      }
}  

