/* *******************************************************************************************
 *                                                                                           *
 * Macros used for the Ctpress web site, in particualr for the order form                    *
 * Last updated 21 Dec 2011                                                                  *
 * *******************************************************************************************/

/* ***************************************************
*    Book titles and prices                         *
*****************************************************/
Products = new Array(6);
var SBA = false;
function CreateProducts()
{
    Products[1] = new Product("Steamboating Guide", 2.5, 1.5);
    Products[2] = new Product("Steam Engine Principles", 8, 5);
    Products[3] = new Product("Steam Tables", 3, 1);
    Products[4] = new Product("Windpower Principles", 10, 5);
    Products[5] = new Product("Windpower Principles Hardback", 25, 10);
}
function Product(Title, FullPrice, SBAPrice)
{
    this.Title = Title;
    this.FullPrice = FullPrice;
    this.SBAPrice = SBAPrice;
    this.Price = SBA ? SBAPrice : FullPrice;
}

/* ******************************************************
* Various generic utility functions                   *
********************************************************/
// Function to record last update
function lastup()
{
    revdate = new Date(document.lastModified);
    document.writeln("Last updated " + revdate.getDate() + "/" + (revdate.getMonth() + 1) + "/" + (revdate.getYear() + 1000).toString().substring(2, 4) + " ");
}

//-------------------------------------------------------------------------------
// function to check if a character is a digit
String.prototype.isDigit = function ()
{
    var val = this.charAt(0);
    return (val >= "0" && val <= "9");
}

//------------------------------------------------
// function to check if a character is an uppercase letter
String.prototype.isUpper = function ()
{
    var val = this.charAt(0);
    return (val >= "A" && val <= "Z");
}

//--------------------------------------------------------------------------------
String.prototype.trim = function ()
{
    return this.replace(/^\s+|\s+$/g, "");
}

//--------------------------------------------------------------
// function to emulate "_target" and similar attributes using onclick()
function targ(obj, t)
{
    obj.target = t;
    return true;
}

//--------------------------------------------------------------------------
// function to emulate an iframe
function iframe(file)
{
    document.getElementById("ctpmain").innerHTML = "<object type=\"text/html\" height=\"100%\" width=\"100%\"" + " data=\"" + file + "\" />";
}

//--------------------------------------------------------------
// format a number as a cash value (without currency symbol but with leading spaces)
function cash(val)
{
    var v = currency(val);
    var c = v.length;
    var d = "           " + v;
    return d.substring(c, c + 11);
}

//-------------------------------------------------------------------------------
// format a number as a cash value (without leading spaces)
function currency(val)
{
    var sign = 0;
    var i1 = 0;
    var i2 = 0;
    if (isNaN(val))
    {
        return "0.00";
    }
    if (val < 0) { sign = 1; val = -val; }
    var vs = val.toString(10);
    i1 = parseInt(vs);
    if (isNaN(i1)) { i1 = 0; }
    i2 = (val - i1) * 100 + 100.5;
    if (isNaN(i2)) { i2 = 0; }
    var v = (i1.toString(10) + "." + i2.toString(10).substring(1, 3));
    if (v == "0.00") { return v; }
    var v1 = v;
    if (sign == 1) { v1 = "-" + v; }
    return v1;
}

/* ***********************************************************************************
 *                                                                                   *
 *   (Re-)initialise the main form and set up the fixed data                         *
 *                                                                                   *
 *************************************************************************************/
function InitForm() // called from HTML after loading
{
    var d = new Date();                                //Create Date object.
    var s = d.getFullYear().toString(10).substr(2, 2); // create order number
    s += (d.getMonth() + 101).toString(10).substr(1, 2);
    s += (d.getDate() + 100).toString(10).substr(1, 2);
    s += "/";
    s += (d.getMinutes() + 100).toString(10).substr(1, 2);
    s += "w";
    document.getElementById('OrderNumber').innerHTML = s;
    resetform();
    return s;
}

//--------------------------------------------------------------------------------------------
// Process reset form button : Resets all data except the order number. Also called from Initform()
function resetform()
{
    document.forms['OrdFrm'].reset();
    // set the product titles and prices    
    document.getElementById('CheckboxSBA').checked = false;
    setSBA();
    UpdateTotal(1);
    UpdateTotal(2);
    UpdateTotal(3);
    UpdateTotal(4);
    // set the date
    setDate();
    // set various defaults
    document.getElementById('OrderNoID').value = document.getElementById("OrderNumber").innerHTML;
    document.getElementById('submitted').value = "No";
    document.getElementById('SubText').style.visibility = "hidden";
    document.getElementById('PayNow').disabled = true;
}
//-------------------------------------------------------------------------------------------------------------
// Set the date to today's date by default
function setDate()
{
    var s = "   ";
    var months = new Array(13);
    months[0] = "Jan";
    months[1] = "Feb";
    months[2] = "Mar";
    months[3] = "Apr";
    months[4] = "May";
    months[5] = "Jun";
    months[6] = "Jul";
    months[7] = "Aug";
    months[8] = "Sep";
    months[9] = "Oct";
    months[10] = "Nov";
    months[11] = "Dec";
    d = new Date();                           //Create Date object.
    s += d.getDate() + " ";                   //Get day
    s += months[d.getMonth()] + " ";          //Get month text
    s += d.getFullYear(); 			          //Get year
    document.forms['OrdFrm'].Date.value = s;
  //n.b. toDateString() can be used to get the month text, but doesn't work on Opera
}
//-------------------------------------------------------------------------------------
// Set the titles and prices of the various products
function setPrices()
{
    CreateProducts();
    var t = 0;
    for (t = 1; t < 5; t++)
    {
        document.getElementById('Price' + t).innerHTML = "Copies of " + Products[t].Title + " at &pound;" + cash(Products[t].Price);
        UpdateTotal(t);
    }
    document.getElementById('Price5').innerHTML = cash(Products[5].Price);
    UpdateTotal(4);

}

/* ************************************************************************************************
 *                                                                                                *
 * Process the Submit key, making sure that the enter key doesn't do it                           *
 *                                                                                                *
 **************************************************************************************************/
var button = false; // this will be true if the button is pressed, else false if it was the enter key

function bFoc() { button = true; }
function bBlur() { button = false; }

function ChkSubmit()
{
    if (!button) { return false; }
    button = false;
    var sub = document.getElementById('submitted');
    if (sub.value == "Yes")
    {
        var answer = confirm("This form has already been submitted.\n\n    Do you want to submit it again?\n\ ");
        if (!answer) { return false; }
    }
    sub.value = "Yes";
    document.getElementById('PayNow').disabled = false;
    document.getElementById('SubText').style.visibility = "visible";
    return true;
}

//----------------------------------------------------------------------------------------------------------
// Check that there is a sale, a name and an address, and enable submit button
// Called from UpdateDue and the OnChange of Name and Address
function chkDataEntered()
{
    var t = parseFloat(document.getElementById("TotalDue").innerHTML);
    var b1 = !isNaN(t);
    var b2 = (document.getElementById("NameID").value != null) && (document.getElementById("NameID").value.toString().trim() /*replace(/^\s+|\s+$/g, "")*/ != "");
    var b3 = (document.getElementById("AddressID").value != null) && (document.getElementById("AddressID").value.toString().trim() /*replace(/^\s+|\s+$/g, "")*/ != "");
    document.getElementById('SubmitButton').disabled = !(b1 && b2 && b3);
}

//------------------------------------------------------------------------------------------------------
// process the Paypal submit button
function submitPayPal()
{
    if (document.getElementById('submitted').value == "No")
    {
        alert("Please submit the order before going to PayPal\n\ ");
        return false;
    }
    return true;
}
/* *********************************************************************************************************
 *                                                                                                         *
 * A sequence of routines that updates the money fields when order numbers, prices or postage chages       *
 *                                                                                                         *
 ***********************************************************************************************************/

// update the total charge for a particular title
function UpdateTotal(titleNo)
{
    var items = document.forms['OrdFrm'].elements["Orders[]"];
    var item = items[titleNo - 1];
    var Count = document.getElementById("Count" + titleNo);
    var textarea = "T" + titleNo;
    if (isNaN(Count.value) || Count.value < 1 || Count.value > 99)
    {
        Count.value = "";
        item.value = "";
        document.getElementById("T" + titleNo).innerHTML = "&nbsp;"
        UpdateSum();
        return true;
    }
    if (titleNo == 4 && document.getElementById('Hardback').checked)
    {
        titleNo = 5;
    }
    Totalvalue = Products[titleNo].Price * Count.value;
    document.getElementById(textarea).innerHTML = (Totalvalue == 0) ? "&nbsp;" : cash(Totalvalue);
    Line = "&quot;" + Products[titleNo].Title + "&quot; Price &pound;" + currency(Products[titleNo].Price) + " Quantity " + Count.value.toString(10) + " Total &pound;" + currency(Totalvalue);
    item.value = Line;
    UpdateSum();
}

//-------------------------------------------------------------------------------
// Recalculates order form items total
var SaleSum;
function UpdateSum()
{
    SaleSum = 0;
    var a = parseFloat(document.getElementById("T1").innerHTML);
    if (!isNaN(a)) { SaleSum += a; }
    a = parseFloat(document.getElementById("T2").innerHTML);
    if (!isNaN(a)) { SaleSum += a; }
    a = parseFloat(document.getElementById("T3").innerHTML);
    if (!isNaN(a)) { SaleSum += a; }
    a = parseFloat(document.getElementById("T4").innerHTML);
    if (!isNaN(a)) { SaleSum += a; }

    document.getElementById("SaleSum").innerHTML = (SaleSum == 0) ? "&nbsp;" : cash(SaleSum);
    UpdateDisc();
}

//-------------------------------------------------------------------------------
// recalculates discount
function UpdateDisc()
{
    var discount = -0.25;
    var counts = new Array(4);
    var discash = 0;
    for (var i = 1; i < 5; i++)
    {
        if (document.getElementById("Count" + i).value > 9)
        {
            discash += discount * parseFloat(document.getElementById("T" + i).innerHTML);
        }
    }

    document.getElementById("Discount").innerHTML = (discash == 0) ? "&nbsp;" : cash(discash);
    UpdatePostage();
}

//---------------------------------------------------------------------------------------------------
// recalculates postage total
function UpdatePostage()
{
    var rate = 0;
    var postmin = 0;
    var postzone = "UK";
    if (document.getElementById('PostOS').checked) postzone = "OS";
    if (document.getElementById('PostAir').checked) postzone = "Air";

    document.getElementById("minc").style.visibility = "hidden";

    if (postzone == "UK") { rate = 0.15; postmin = 1; }
    if (postzone == "OS") { rate = 0.25; postmin = 2; }
    if (postzone == "Air") { rate = 0.50; postmin = 4; }
    if ((SBA == true) && (postzone == "UK"))
    {
        rate = 0;
        postmin = 0;
        document.getElementById("minc").innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;(free of charge)"
        document.getElementById("minc").style.visibility = "visible";
    } else
    {
        document.getElementById("minc").innerHTML = "&nbsp;(minimum charge)"
    }
    var sum = parseFloat(document.getElementById("SaleSum").innerHTML);
    if (isNaN(sum)) { sum = 0; }
    var disc = parseFloat(document.getElementById("Discount").innerHTML);
    if (isNaN(disc)) { disc = 0; }
    var postval = rate * (sum + disc);
    if (postval < postmin)
    {
        postval = postmin;
        document.getElementById("minc").style.visibility = "visible";
    }


    if (!isNaN(parseFloat(document.getElementById("SaleSum").innerHTML)))
    {
        document.getElementById("Postage").innerHTML = cash(postval);
    }
    else
    {
        document.getElementById("Postage").innerHTML = "&nbsp;";
        document.getElementById("minc").style.visibility = "hidden";
    }
    UpdateDue(postval, postzone);
}

//-------------------------------------------------------------------------------
// recalculates total amount to be paid
function UpdateDue(PostageValue, PostageZone)
{
    var post = parseFloat(document.getElementById("Postage").innerHTML);
    if (isNaN(post)) { post = 0; }
    var sum = parseFloat(document.getElementById("SaleSum").innerHTML);
    if (isNaN(sum)) { sum = 0; }
    var disc = parseFloat(document.getElementById("Discount").innerHTML);
    if (isNaN(disc)) { disc = 0; }
    var due0 = post + sum + disc;
    var due = currency(due0); //this value goes to PayPal
    document.getElementById("TotalDue").innerHTML = (due == 0) ? "&nbsp;" : cash(due);
    chkDataEntered();
    var Overll = "Sale: &pound;" + currency(SaleSum);
    Overll += " Discount: &pound;" + currency(disc);
    Overll += " Postage (" + PostageZone + "): &pound;" + currency(PostageValue)
    Overll += " Total Due: &pound;" + due;
    document.getElementById('OverallID').value = Overll;// this string goes to the acknowledge page

    //PayPal fields
    document.forms['_xclick'].amount.value = due;
    document.forms['_xclick'].item_name.value = "Order Number: " + document.forms['OrdFrm'].OrderNo.value + ", Books and Postage";
}

//------------------------------------ End of cash calculations -------------------------------------------------------------------
//Function to check the format of a UK postcode
var goodPC = "";
function PCstruct(pc)
{
    var ch = "";
    var singleCh = "BGELMNSW";
    var patt = /[ .]+/g; // remove any spaces or full stops
    var pc1 = pc.toUpperCase().replace(patt, "");

    if (pc1.length < 5 || pc1.length > 7) return false;
    goodPC = pc1;
    ch = pc1.charAt(0);
    if (!ch.isUpper()) return false; //first must be letter
    var pc2 = pc1.substring(1);
    pc1 = pc2;
    if (pc1.charAt(0).isUpper())
    {
        pc2 = pc1.substring(1); // may be 2 letters
        pc1 = pc2;
    } else
    {
        if (singleCh.indexOf(ch) == -1) return false; // if not, must be one of a small list
    }
    if (!pc1.charAt(0).isDigit()) return false; // then must have a digit
    pc2 = pc1.substring(1);
    pc1 = pc2;
    if (pc1.charAt(0).isUpper())
    {
        if (!pc1.charAt(1).isDigit()) return false; // London have letter-digit here
        pc2 = pc1.substring(2);
        pc1 = pc2;
    } else
    {
        if (!pc1.charAt(0).isDigit()) return false; // others must have a digit
        pc2 = pc1.substring(1);
        pc1 = pc2;
        if (pc1.charAt(0).isDigit())
        {
            pc2 = pc1.substring(1);  // may be another digit
            pc1 = pc2;
        }
    }

    if (!pc1.charAt(0).isUpper()) return false; //must end in 2 letters
    if (!pc1.charAt(1).isUpper()) return false;
    return true;
}

//-----------------------------------------------------
/* ************************************************************************************************************
 *                                                                                                            *
 * Checks whether there is a valid UK postcode and sets the postage zone to UK or Air, appropriately          *
 * (this can be overridden). Called from onBlur() of Postcode field.                                          *
 *                                                                                                            *
 **************************************************************************************************************/
function chkUKCode()
{
    var pc = document.getElementById("PostCodeID").value;
    if (pc.trim() == "") return;    
    var validPC = PCstruct(pc);
    
    if (validPC)
    {

        document.getElementById('PostUK').checked = true;
        UpdatePostage();
        document.getElementById("PostCodeID").value = goodPC.toString().substring(0, goodPC.length - 3) + " " + goodPC.substring(goodPC.length - 3);
    }
    else
    {
        document.getElementById('PostAir').checked = true;
        UpdatePostage();
    }
}
//-------------------------------------------------------------------------------------
/**********************************************************************************************************
 *                                                                                                        *
 * Routines to check SBA membership and set discounted prices approriately                                *
 *                                                                                                        *
 **********************************************************************************************************/
function setSBA()
{
    SBA = document.getElementById('CheckboxSBA').checked ? true : false;
    document.getElementById('SBAIDText').style.visibility = SBA ? "visible" : "hidden";
    document.getElementById("MemberID").style.visibility = SBA ? "visible" : "hidden";
    if (!(SBA == true))
    {
        document.getElementById('MemberID').value = "";
    }
    document.getElementById("invID").style.visibility = "hidden"
    setPrices();

    return true;
}
//-------------------------------------------------------------------------------------
function checkSBAID()
{
    var id = document.getElementById('MemberID').value;
    if (isNaN(id) || id < 1000 || id > 5000)
    {
        // temporarily disabled pending confirmation of structure of member ID
        //        document.getElementById("invID").style.visibility = "visible"
    } else
    {
        document.getElementById("invID").style.visibility = "hidden"
    }
}
