var global_coupon = 0;
var global_pant = 0; 

function handleKeyPress(e,form){
    var key = e.keyCode || e.which;
    if (key == 13){
        checkEAN(form);
        form.quantity.value = 1;
        form.ean.value = "";
        form.ean.focus();
    }
}

function checkEAN(form){
    ean = form.ean.value;
    if(ean.length != 13){
        alert("Fungerar bara med EAN13");
        return;
    }
    checksum = getChecksum(ean);
    lastdigit = parseInt(ean.slice(12));
    if (checksum != lastdigit){
        alert("Felaktig checksiffra");
        return;
    }

    first_slice = ean.slice(8,11);
    last_slice = ean.slice(11,12);
    sum = parseFloat(first_slice.concat(".",last_slice));
    quantity = parseInt(form.quantity.value);
        if(quantity <= 0 || String(quantity) == "NaN"){
            alert("Antal ska vara ett heltal > 0");
            return;
        }
    total = sum * quantity;
    switch(ean.slice(0,3)){

        case "995":
            if (quantity == 1){
               text = "kupong värd ";
             }
             else{
               text = "kuponger värda ";
             } 
            global_coupon = round((global_coupon + total), 2);
            form.coupon.value = global_coupon;
            break;

        case "999":
            if (quantity == 1){
               text = "pantkvitto värt ";
            }
            else{
               text = "pantkvitton värda ";
            } 
            global_pant = round((global_pant + total), 2);
            form.pant.value = global_pant;
            break;

        default:alert("Inte giltig");
        return;
    }
    old = form.history.value;
    if (quantity == 1){
        textstring = quantity + " " + text+sum + " Kr." + "\n" + "EAN:" + ean + "\n\n" + old;
    }
    else{
        textstring = quantity + " " + text + sum + " Kr styck." + " Totalt " + total + " Kr." + "\n" + "EAN:" + ean + "\n\n" + old;
    }
    form.history.value = textstring;
}

function getChecksum(ean){
    i = 1;
    sum = 0;
    while (i < 12){
        sum = sum + parseInt(ean.slice(i,(i + 1)));
        i = i + 2;
    }
    sum = sum*3;
    i = 0;
    while (i < 11){
        sum = sum + parseInt(ean.slice(i,(i + 1)));
        i = i + 2;
    }
    check = 10 - (sum % 10);
    if(check == 10){
        check = 0;
    }
    return(check);
}

function round(number, X) {
   X = (!X ? 2 : X);
   return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
} 

function clearAll(form){
    global_coupon = 0;
    global_pant = 0;
    form.ean.value = "";
    form.quantity.value = 1;
    form.history.value = "";
    form.coupon.value = 0;
    form.pant.value = 0;
    form.ean.focus();
}
