//---------------------------------------------------------------------||
// FUNCTION:    checkForm                                              ||
// PARAMETERS:  Form object, and true/false if we should check for     ||
//              a credit card number. You shouldn't accept credit cards||
//              via email.  Only use that when you are connected to a  ||
//              secure server.                                         ||
// RETURNS:     boolean (True form is correct, False form is in error) ||
// PURPOSE:     To check form elements                                 ||
//---------------------------------------------------------------------||
function checkForm(thisForm, checkForCreditCard)  {
        bFormError = false;   //Boolean variable to store form state
        bIsValidCard = false; //Boolean variable to store CC state
        strErrorList = "";    //String list of missing/errorsum fields

        if( thisForm.nome.value==''  ) {bFormError = true;  strErrorList += "Nome, ";}
        if( thisForm.cognome.value==''   ) {bFormError = true;  strErrorList += "Cognome, ";}
        if( thisForm.indirizzo.value=='') {bFormError = true;  strErrorList += "Indirizzo, ";}
        if( thisForm.citta.value==''   ) {bFormError = true;  strErrorList += "Citta', ";}        
        if( thisForm.cap.value==''    ) {bFormError = true;  strErrorList += "Cap, ";}
        if( thisForm.telefono.value==''  ) {bFormError = true;  strErrorList += "Telefono, ";}        
        if( bFormError == true ) {
                alert("Spiecenti, ma non tutti i campi sono stati competati.\n"
                     +"Controllare i seguenti campi: \n\n"
                     +strErrorList
                     +"\n\n");
                return false;
        }

        return true;
} //END function checkForm


//---------------------------------------------------------------------||
// FUNCTION:    CKquantity                                             ||
// PARAMETERS:  Quantity to                                            ||
// RETURNS:     Quantity as a number, and possible alert               ||
// PURPOSE:     Make sure quantity is represented as a number          ||
//---------------------------------------------------------------------||
function CKquantity(checkString) {

        strNewQuantity = "";    // String Adjusted Item Quantity
        count     = 0;          // Generic Loop Counter

        for (i = 0; i < checkString.length; i++) {
                ch = checkString.substring(i, i+1);

                if ((ch >= "0" && ch <= "9") || (ch == '.')) {
                        strNewQuantity += ch;
                }
        }

        if (strNewQuantity.length < 1)
                strNewQuantity = "1";

        return strNewQuantity;
}


//---------------------------------------------------------------------||
// FUNCTION:    AddToCart                                              ||
// PARAMETERS:  Form Object                                            ||
// RETURNS:     Cookie to user's browser, with prompt                  ||
// PURPOSE:     Adds a product to the user's shopping cart             ||
//---------------------------------------------------------------------||
function AddToCart(thisForm) {

        iNumberOrdered = 0;  //Integer number of products already ordered

        iNumberOrdered = GetCookie("NumberOrdered");
        iNumberOrdered++;

        if ( iNumberOrdered > 12 )
                alert("Spiacente, la tua lista è piena, procedere con la conferma.");
        else {
                dbUpdatedOrder = thisForm.quantity.value + "|"
                                 + thisForm.prezzo.value  + "|"
                                 + thisForm.prod_id.value + "|"
                                 + thisForm.name.value;

                NewOrder = "Order." + iNumberOrdered;
                SetCookie (NewOrder, dbUpdatedOrder, null, "/");
                SetCookie ("NumberOrdered", iNumberOrdered, null, "/");

                notice = thisForm.quantity.value + " "
                         + thisForm.name.value
                         + " aggiunta alla lista della prenotazione.";

                alert(notice);
        }
}


//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
        var endstr = document.cookie.indexOf (";", offset);
        if (endstr == -1)
                endstr = document.cookie.length;
        return unescape(document.cookie.substring(offset, endstr));
}


//---------------------------------------------------------------------||
// FUNCTION:    FixCookieDate                                          ||
// PARAMETERS:  date                                                   ||
// RETURNS:     date                                                   ||
// PURPOSE:     Fixes cookie date, stores back in date                 ||
//---------------------------------------------------------------------||
function FixCookieDate (date) {
        var base = new Date(0);
        var skew = base.getTime();
        date.setTime (date.getTime() - skew);
}


//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
function GetCookie (name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen)
                {
                var j = i + alen;
                if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
                i = document.cookie.indexOf(" ", i) + 1;
                if (i == 0) break;
                }

        return null;
}


//---------------------------------------------------------------------||
// FUNCTION:    SetCookie                                              ||
// PARAMETERS:  name, value, expiration date, path, domain, security   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,domain,secure) {
        document.cookie = name + "=" + escape (value) +
                        ((expires) ? "; expires=" + expires.toGMTString() : "") +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        ((secure) ? "; secure" : "");
}


//---------------------------------------------------------------------||
// FUNCTION:    DeleteCookie                                           ||
// PARAMETERS:  Cookie name, path, domain                              ||
// RETURNS:     null                                                   ||
// PURPOSE:     Removes a cookie from users browser.                   ||
//---------------------------------------------------------------------||
function DeleteCookie (name,path,domain) {
        if (GetCookie(name)) {
                document.cookie = name + "=" +
                                ((path) ? "; path=" + path : "") +
                                ((domain) ? "; domain=" + domain : "") +
                                "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
}


//---------------------------------------------------------------------||
// FUNCTION:    MoneyFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number                                       ||
// PURPOSE:     Reformats Dollar Amount to #.## format                 ||
//---------------------------------------------------------------------||
function moneyFormat(input) {
        var dollars = Math.floor(input)
        var tmp = new String(input)
        for (var decimalAt = 0; decimalAt < tmp.length; decimalAt++) {
                if (tmp.charAt(decimalAt)==".")
                        break;
        }

        var cents  = "" + Math.round(input * 100)
        cents = cents.substring(cents.length-2, cents.length)
        dollars += ((tmp.charAt(decimalAt+2)=="9")&&(cents=="00"))? 1 : 0;

        return dollars + "." + cents
}


//---------------------------------------------------------------------||
// FUNCTION:    RemoveFromCart                                         ||
// PARAMETERS:  Order Number to Remove                                 ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Removes an item from a users shopping cart             ||
//---------------------------------------------------------------------||
function RemoveFromCart(RemOrder) {
        if (confirm("Premi 'Ok' per rimuovere dalla prenotazione.")) {
                NumberOrdered = GetCookie("NumberOrdered");
                for(i=RemOrder; i <  NumberOrdered; i++) {
                        NewOrder1 = "Order." + (i+1);
                        NewOrder2 = "Order." + (i);
                        database = GetCookie(NewOrder1);
                        SetCookie (NewOrder2, database, null, "/");
                }
                NewOrder = "Order." + NumberOrdered;
                SetCookie ("NumberOrdered", NumberOrdered-1, null, "/");
                DeleteCookie(NewOrder, "/");
                location.href=location.href;
        }
}


//---------------------------------------------------------------------||
// FUNCTION:    GetFromCart                                            ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page          ||
//---------------------------------------------------------------------||
function GetFromCart() {
        NumberOrdered = 0;
        Total=0;
        TOTotal=0;
        TOquantity = " ";
        TOprice = " ";
        TOid_num = " ";
        TOname = " ";
        NumberOrdered = GetCookie("NumberOrdered");
        whattowrite = "";

        for (i = 1; i <= NumberOrdered; i++) {
                NewOrder = "Order." + i;
                database = "";
                database = GetCookie(NewOrder);

                Token0 = database.indexOf("|", 0);
                Token1 = database.indexOf("|", Token0+1);
                Token2 = database.indexOf("|", Token1+1);

                fields = new Array;
                fields[0] = database.substring( 0, Token0 );
                fields[1] = database.substring( Token0+1, Token1 );
                fields[2] = database.substring( Token1+1, Token2 );
                fields[3] = database.substring( Token2+1, database.length );

                Total = Total + (fields[1] * fields[0]);
                TOTotal = moneyFormat(Total);

                whattowrite += "<tr><td>" + fields[2] + "</td><td><font size=-1>"
                                + fields[3] + "</font></td><td>&euro:" + fields[1]
                                + "</td><td><input type=\"text\" size=\"2\" name=\"QUANTITY_"+ i +"\" value=\""
                                + fields[0] + "\"></td>"
                                + "<td><input type=\"button\" value=\"  Cancella  \" onclick=\"RemoveFromCart("+i+")\" class=\"cancella\"/></td>"
                                + "<input type=hidden name=\"ID_"+ i +"\" value=\"" + fields[2] + "\">"
                                + "<input type=hidden name=\"NAME_"+ i +"\" value=\"" + fields[3] + "\">"
                                + "<input type=hidden name=\"PRICE_"+ i +"\" value=\"" + fields[1] + "\">";
        }

        document.write(whattowrite);
        document.write("</td></tr><tr><td colspan=2><b>Totale</b></td><td>&euro;");
        document.write(TOTotal);
        document.write("</td><td></td>");
}


//---------------------------------------------------------------------||
// FUNCTION:    WriteToForm                                            ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product hidden fields Written to Document              ||
// PURPOSE:     Draws current cart product hidden fields on HTML form  ||
//---------------------------------------------------------------------||
function WriteToForm() {
        NumberOrdered = 0;
        Total=0;
        TOTotal=0;
        TOquantity = " ";
        TOprice = " ";
        TOid_num = " ";
        TOname = " ";
        NumberOrdered = GetCookie("NumberOrdered");
        whattowrite = "";

        for (i = 1; i <= NumberOrdered; i++) {
                NewOrder = "Order." + i;
                database = "";
                database = GetCookie(NewOrder);

                Token0 = database.indexOf("|", 0);
                Token1 = database.indexOf("|", Token0+1);
                Token2 = database.indexOf("|", Token1+1);

                fields = new Array;
                fields[0] = database.substring( 0, Token0 );
                fields[1] = database.substring( Token0+1, Token1 );
                fields[2] = database.substring( Token1+1, Token2 );
                fields[3] = database.substring( Token2+1, database.length );

                Total = Total + (fields[1] * fields[0]);
                TOTotal = moneyFormat(Total);

                document.write("<input type=hidden name=\"ID_"+ i +"\" value=\"" + fields[2] + "\">");
                document.write("<input type=hidden name=\"NAME_"+ i +"\" value=\"" + fields[3] + "\">");
                document.write("<input type=hidden name=\"PRICE_"+ i +"\" value=\"" + fields[1] + "\">");
                document.write("<input type=hidden name=\"QUANTITY_"+ i +"\" value=\"" + fields[0] + "\">");
        }
}
