﻿       
    /*
    This stores all procedures used by the "~/pages/orders.aspx" page
    Please note that it also uses scripts from the 
    "~/pages/scripts/ShopList.js" file. These are included in 
    the "~/pages/order.aspx" page before this script.
    */
    
    //Works out whether a user gets a discount or not
    //Depends on their country
    var giveDiscount = false;
    var discountPercent = 40;
    
    //An array of all books (IDs, prices, etc.)
    var bookIDArray;
    
    //A Book object : Default constructor
    function Book()
    {
        this.id = -1;
        this.title = "<unknown>";
        this.price = "0";
        this.category_id = "-1";
    }
    
    //A Book object : Alternative constructor
    function Book(id, title, price, category_id)
    {
        this.id = id;
        this.title = title;
        this.price = price;
        this.category_id = category_id;
    }
    
    
    // ---------------------------------------------- \\
    // -------------- PURCHASE METHODS -------------- \\
    
    //This deals with everything to do with purchases:
    //Includes doing checks, alerts, getting and
    //setting cookies, and redirecting to the Credit
    //Card facilities
    function purchase()
    {
        Update_Total_Cost()
        if (fieldCheck())
        {
            //An array of all ORDERED books
            var orderedBookArray = new Array();         
            for (var allBooks = 0; allBooks < bookIDArray.length; allBooks++)
            {
                var thisBook = bookIDArray[allBooks];
                
                //If the book has been ordered, add it to the array
                if (exists(thisBook.id))
                {
                    orderedBookArray[orderedBookArray.length] = thisBook;
                }
            }
            
            //Add every book and quantity to the confirm message
            var confirmMsg = "-- Order --\n\n";
            for (allBooks = 0; allBooks < orderedBookArray.length; allBooks++)
            {
                var thisBook = orderedBookArray[allBooks];
                var quantity = document.getElementById("txt_quantity_" + thisBook.id).value;
                confirmMsg += quantity + " x " + thisBook.title + "\n"
            }
            
            var totalCost;
            var USTotal;
            
            //Check for and accomodate discounts
            if (giveDiscount == false)
            {
                //No discount
                totalCost = Calculate_Total_Cost();
                USTotal = Math.round((totalCost / USExchangeRate) * 100) / 100; 
            }
            else
            {
                //Give discount
                totalCost = Calculate_Total_Cost_With_Discount()
                USTotal = Math.round((totalCost / USExchangeRate) * 100) / 100; 
            }
            
            confirmMsg += "\nTotal: R" + totalCost + " (± $" + USTotal + " US)\n\n";
            
            confirmMsg += "-- Client Details --\n\n";
            confirmMsg += "First Name:\t" + document.getElementById("txtFirstName").value + "\n";
            confirmMsg += "Last Name:\t" + document.getElementById("txtLastName").value + "\n";
            confirmMsg += "E-Mail Address:\t" + document.getElementById("txtEmail").value + "\n";
            if (document.getElementById("cboPaymentMethod").value == "credit_card")
            {
                confirmMsg += "Payment Method:\tCredit Card\n";
            }
            else
            {
                confirmMsg += "Payment Method:\tDirect Deposit\n";
            }
            
            confirmMsg += "\n-- Postal Address --\n\n";
            
            confirmMsg += document.getElementById("txtPostalAddress").value + "\n";
            var Country = document.getElementById("cboCountry").options[document.getElementById("cboCountry").selectedIndex].id;
            confirmMsg += Country + "\n";
            confirmMsg += document.getElementById("txtPostalCode").value + "\n";

            if (confirm("== Please confirm that the following is correct ==\n\n" + confirmMsg))
            {       
                //Store the total cost
                //Used to charge credit card, and as a check later.

                document.getElementById("totalCost").value = totalCost;
                
                
                //Determine if the client is paying via credit card or debit card
                if (document.getElementById("cboPaymentMethod").value == "credit_card")
                {
                    //Credit Card
                    document.getElementById("form1").submit();
                }
                else
                {
                    //Debit Card
                    document.getElementById("form1").action = "order/direct_deposits/direct_deposits.aspx";
                    document.getElementById("form1").submit();
                }
            }
        }
    }
    
    //Checks all input fields for valid input
    //Also makes sure at least one book is ordered
    //Called from function purchase() above
    //Returns true or false
    function fieldCheck()
    {
        var errors = "";
        var currentObj;
        
        if (Calculate_Total_Cost() < 1)
        {
            errors += "- Please order at least one book\n";
        }
        
        currentObj = document.getElementById("txtFirstName");
        if (currentObj.value == "" || currentObj.value == null)
        {
            errors += "- Please enter your first name\n";
        }
        
        currentObj = document.getElementById("txtLastName");
        if (currentObj.value == "" || currentObj.value == null)
        {
            errors += "- Please enter your last name\n";
        }
        
        currentObj = document.getElementById("txtEmail");
        if ((currentObj.value == "" || currentObj.value == null) || currentObj.value.indexOf('@') == -1)
        {
            errors += "- Please enter a valid e-mail address\n";
        }

        currentObj = document.getElementById("cboCountry");
        if (currentObj.selectedIndex == 0)
        {
            errors += "- Please select a country\n";
        }
        
        var currentObj = document.getElementById("cboPaymentMethod");
        if (currentObj.selectedIndex == 0)
        {
            errors += "- Please select a payment method\n";
        }

        currentObj = document.getElementById("txtPostalAddress");
        if (currentObj.value == "" || currentObj.value == null)
        {
            errors += "- Please enter your postal address\n";
        }
        
        currentObj = document.getElementById("txtPostalCode");
        if (currentObj.value == "" || currentObj.value == null)
        {
            errors += "- Please enter your postal code\n";
        }

        if (errors == "")
        {
            //All checks were passed
            return true;
        }
        else
        {
            //Some invalid data entries were found
            //Notify the user and DON'T proceed.
            alert("Insufficient Information to Proceed\n\n" + errors);
            return false;
        }
    }
    
    // --------------------------------------------------- \\
    // ---- CALCULATE LOCAL DISCOUNTS WHERE APPLICABLE --- \\
    
    function calculateLocalDiscount()
    {
        var selectedCountry;
        selectedCountry = document.getElementById("cboCountry").options[document.getElementById("cboCountry").selectedIndex].text;
        if (selectedCountry == "South Africa")
        {
            giveDiscount = true;
        }
        else
        {
            giveDiscount = false;
        }
        Update_Total_Cost();
    }
    
    
    // --------------------------------------------------- \\
    // -------------- DYNAMIC TABLE METHODS -------------- \\
    
    //Adds a book from the users shopping list
    //This adds it to the "Ordered" table 
    //And removes it from the "Unordered" table.
    //It does mess with cookies.
    function order_book(obj_button, thisBook)
    {
        //Add this book to the user's cookies
        //(The addBook method makes sure its not added twice)
        //See "~/pages/scripts/ShopList.js"
        addBook(thisBook.id)
        
        //Update the table
        add_book_to_OrderedTable(thisBook);
        remove_book_from_table(obj_button, 'tblUnorderedBooks');
        Update_Total_Cost();
    }
    
    //Removes a book from the users shopping list
    //This removes it from the "Ordered" table 
    //And adds it to the "Unordered" table.
    //It does mess with cookies.
    function unorder_book(obj_button, thisBook)
    {
        //Add this book to the user's cookies
        //(The removeBook method makes sure its not added twice)
        //See "~/pages/scripts/ShopList.js"
        removeBook(thisBook.id)
        
        //Update the table by removing only this row
        add_book_to_UnorderedTable(thisBook)
        remove_book_from_table(obj_button, 'tblOrderedBooks');
        Update_Total_Cost();
    }
    
    
    //This removes a book from the specified table
    //as defined by the button repressed.
    //For more information: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/IETechCol/dnwebgen/ie_leak_patterns.asp
    function remove_book_from_table(obj_button, table_id)
    {
        var table = document.getElementById(table_id);
	    var table_body = table.tBodies[0];
	
	    var delRow = obj_button.parentNode.parentNode;
	    var rIndex = delRow.sectionRowIndex;
	    
	    table.deleteRow(rIndex);
    }
    
    //Adds a book to the user's shopping list table only 
    //No cookies were used in this method!
    //Note: the thisBook is of object type Book (see above)
    function add_book_to_OrderedTable(thisBook)
    {
        var table = document.getElementById("tblOrderedBooks");
	    var docFragment = document.createDocumentFragment();
	    var trElem, tdElem, txtNode;
    	
	    trElem = document.createElement("tr");
	    trElem.setAttribute("align", "center");
		    tdElem = document.createElement("td");
			    txtNode = document.createTextNode(thisBook.title);
		    tdElem.appendChild(txtNode);
		    trElem.appendChild(tdElem);
    	
		    tdElem = document.createElement("td");
		        //For USExchangeRate, have a look in "~/pages/order.aspx" (C# to Java)
		        //and "~/pages/order.aspx.cs" (DB to C#)
		        var USPrice = Math.round((thisBook.price / USExchangeRate)*100)/100; //To 2 decimal places
			    txtNode = document.createTextNode("R" + thisBook.price + " (± $" + USPrice + " US)");
		    tdElem.appendChild(txtNode);
    	    trElem.appendChild(tdElem);
    		
		    tdElem = document.createElement("td");
			    var txt_quantity;
			    txt_quantity = document.createElement("input");
			    txt_quantity.setAttribute("type", "text");
			    txt_quantity.setAttribute("id", "txt_quantity_"+ thisBook.id);
			    txt_quantity.setAttribute("name", "txt_quantity_"+ thisBook.id);
			    txt_quantity.setAttribute("maxlength", "6");
			    txt_quantity.setAttribute("size", "6");
			    txt_quantity.setAttribute("value", "1");
			    txt_quantity.setAttribute("style", "text-align: center;");
			    txt_quantity.onchange = function() {Update_Total_Cost()}
		    tdElem.appendChild(txt_quantity);
    	    trElem.appendChild(tdElem);
    		
		    tdElem = document.createElement("td");
			    var btn_rem;
			    btn_rem = document.createElement("img");
			    btn_rem.setAttribute("src", "../images/buttons/order/remove/ButtonUp.gif");
			    btn_rem.setAttribute("id", "btn_rem" + thisBook.id);
			    btn_rem.setAttribute("style", "vertical-align: middle;");
			    btn_rem.onclick = function () {unorder_book(this, thisBook)};
			    btn_rem.onmouseover = function () {btnRemOver(this.id)};
			    btn_rem.onmousedown = function () {btnRemDown(this.id)};
			    btn_rem.onmouseout = function () {btnRemUp(this.id)};
		    tdElem.appendChild(btn_rem);
    	    trElem.appendChild(tdElem);
    	
	    docFragment.appendChild(trElem);
    	
	    table.tBodies[0].appendChild(docFragment);
    }
    
    //Adds a book to the user's Unordered Books table only 
    //No cookies were used in this method!
    //Note: the thisBook is of object type Book (see above)
    function add_book_to_UnorderedTable(thisBook)
    {
        var table = document.getElementById("tblUnorderedBooks");
	    var docFragment = document.createDocumentFragment();
	    var trElem, tdElem, txtNode;
    	
	    trElem = document.createElement("tr");
	    trElem.setAttribute("align", "center");
		    tdElem = document.createElement("td");
			    txtNode = document.createTextNode(thisBook.title);
		    tdElem.appendChild(txtNode);
		    trElem.appendChild(tdElem);
    	
		    tdElem = document.createElement("td");
			    //For USExchangeRate, have a look in "~/pages/order.aspx" (C# to Java)
		        //and "~/pages/order.aspx.cs" (DB to C#)
		        var USPrice = Math.round((thisBook.price / USExchangeRate)*100)/100; //To 2 decimal places
			    txtNode = document.createTextNode("R" + thisBook.price + " (± $" + USPrice + " US)");
		    tdElem.appendChild(txtNode);
    	    trElem.appendChild(tdElem);
    		
		    tdElem = document.createElement("td");
		        var nbsp = document.createTextNode('\xa0');
		    tdElem.appendChild(nbsp);
    	    trElem.appendChild(tdElem);
    		
		    tdElem = document.createElement("td");
			    var btn_add;
			    btn_add = document.createElement("img");
			    btn_add.setAttribute("src", "../images/buttons/order/order/ButtonUp.gif");
			    btn_add.setAttribute("id", "btn_add" + thisBook.id);
			    btn_add.setAttribute("style", "vertical-align: middle;");
			    btn_add.onclick = function () {order_book(this, thisBook)};
			    btn_add.onmouseover = function () {btnAddOver(this.id)};
			    btn_add.onmousedown = function () {btnAddDown(this.id)};
			    btn_add.onmouseout = function () {btnAddUp(this.id)};
		    tdElem.appendChild(btn_add);
    	    trElem.appendChild(tdElem);
    	
	    docFragment.appendChild(trElem);
    	
	    table.tBodies[0].appendChild(docFragment);
    }
    
    //Adds all the ordered books to the ordered books table
    //function drawUnorderedBooksTable(table_id)
    function drawUnorderedBooksTable()
    {
        //Go through the entire books array
        for(var allBooks = 0; allBooks < bookIDArray.length; allBooks++)
        {
            var thisBook = bookIDArray[allBooks];
            //If this book has *not* been ordered, add the Unordered Books Table
            if (!exists(thisBook.id))
            {
                add_book_to_UnorderedTable(thisBook);
            }
        }
    }
    
    //Adds all the ordered books to the ordered books table / Shopping List table
    function drawOrderedBooksTable()
    {
        //Go through the entire books array
        for(var allBooks = 0; allBooks < bookIDArray.length; allBooks++)
        {
            var thisBook = bookIDArray[allBooks];
            //If this book has been ordered, add the Ordered Books Table
            if (exists(thisBook.id))
            {
                add_book_to_OrderedTable(thisBook);
            }
        }
    }
    
    //This fixes as many memory leaks as possible
    //It should be called on page unload.
    function restoreMemory()
    {
        //This iterates though all document objects and removes 
        //all (dynamicly added) events from memory.
        //Only works with events like "element.onclick = function(){}"
        //Not "element.attachEvent()" or "element.addEventListener()"
        var clearElementProps = ['data', 'onmouseover', 'onmouseout', 'onmousedown', 'onmouseup', 'ondblclick', 'onclick', 'onselectstart', 'oncontextmenu'];
        var element;
        for(var doc = document.all.length; doc--;)
        {
            element = document.all[doc];
            for(var c = clearElementProps.length; c--;)
            {
                element[clearElementProps[c]] = null;
            }
        }
    }
    
    // ----------------------------------------------------------------- \\
    // -------------- Calculates the ESTIMATED Total Cost -------------- \\
    
    //Displays the total cost on the web page
    //Finds the total cost from the
    //Calculate_Total_Cost() function
    function Update_Total_Cost()
    {
        //Get the total in Rands
        var total = Calculate_Total_Cost();
        
        //To 2 decimal places
        var USTotal = Math.round((total / USExchangeRate)*100)/100; 
	    txtTotal = "R" + total + " (± $" + USTotal + " US)";

        var cell = document.getElementById("OrderedTotal");
        //Second "childNodes[0]." for the <b> tag thats in the cell already
        cell.childNodes[0].childNodes[0].nodeValue = txtTotal;
        
        //If there's a discount, take off 10%
        //Note! This gets double checked via server code upon approval 
        //of payment, so don't even think of fiddling with it!
        if (giveDiscount == true)
        {
            //All rounded to 2 decimal places
            var discountedTotal = Calculate_Total_Cost_With_Discount()
            var discountedUSTotal = Math.round((discountedTotal / USExchangeRate)*100)/100; 
	        var txtDiscountTotal = "R" + discountedTotal + " (± $" + discountedUSTotal + " US)";
            
            document.getElementById("DiscountedRow").style.display = '';
            //Second "childNodes[0]." for the <b> tag thats in the cell already
            document.getElementById("OrderedDiscountedTotal").childNodes[0].childNodes[0].nodeValue = txtDiscountTotal;
        }
        else
        {
            document.getElementById("DiscountedRow").style.display = 'none';
            //Second "childNodes[0]." for the <b> tag thats in the cell already
            document.getElementById("OrderedDiscountedTotal").childNodes[0].childNodes[0].nodeValue = "Not Applicable";
        }
    }
    
    //A discount percentage is applied to all
    //books EXCEPT e-books. This works out the final
    //price with regards to the discount.
    function Calculate_Total_Cost_With_Discount()
    {
        //Set the total to 0 initially
        var total = 0;
        
        //Go through the entire books array
        for(var allBooks = 0; allBooks < bookIDArray.length; allBooks++)
        {
            var thisBook = bookIDArray[allBooks];
            //If this book has been ordered, find out how many
            //have been ordered
            if (exists(thisBook.id))
            {
                var txtQuantity = document.getElementById("txt_quantity_" + thisBook.id);
                
                //Do some checks to make sure there is only valid input
                if (isNaN(txtQuantity.value))
                {
                    var newNumber = "";
                    var oldText = txtQuantity.value;
                    for(var x = 0; x < oldText.length; x++)
                    {
                        var thisChar = oldText.charAt(x);
                        if (!isNaN(thisChar))
                        {
                            newNumber += oldText.charAt(x);
                        }
                    }
                    txtQuantity.value = newNumber
                }    
                
                //We *do* want a value there (no blanks please!)
                if(txtQuantity.value == "")
                {
                    txtQuantity.value = "1";
                } 
                
                //We only want whole numbers
                if(txtQuantity.value.indexOf(".") != -1)
                {
                    var newNumber = txtQuantity.value
                    txtQuantity.value = newNumber.substring(0, newNumber.indexOf("."));
                } 
                
                //We don't want any negitive values either
                if (txtQuantity.value < 0)
                {
                    txtQuantity.value = txtQuantity.value * (-1);
                }
                
                var quantity = txtQuantity.value;
                var subtotal = quantity * thisBook.price;
                
                //If this is an e-book, do not discount it!
                if(thisBook.category_id != 5)
                {
                    //Rounded to two decimal places
                    subtotal = Math.round(subtotal * (1 - (discountPercent / 100)) * 100) / 100;
                }
                
                total += subtotal
            }
        }
        return total;
    }
    
    //Calculates the total cost of all ordered books in Rands
    //Called by the Update_Total_Cost() function above.
    function Calculate_Total_Cost()
    {
        //Set the total to 0 initially
        var total = 0;
        
        //Go through the entire books array
        for(var allBooks = 0; allBooks < bookIDArray.length; allBooks++)
        {
            var thisBook = bookIDArray[allBooks];
            //If this book has been ordered, find out how many
            //have been ordered
            if (exists(thisBook.id))
            {
                var txtQuantity = document.getElementById("txt_quantity_" + thisBook.id);
                
                //Do some checks to make sure there is only valid input
                if (isNaN(txtQuantity.value))
                {
                    var newNumber = "";
                    var oldText = txtQuantity.value;
                    for(var x = 0; x < oldText.length; x++)
                    {
                        var thisChar = oldText.charAt(x);
                        if (!isNaN(thisChar))
                        {
                            newNumber += oldText.charAt(x);
                        }
                    }
                    txtQuantity.value = newNumber
                }    
                
                //We *do* want a value there (no blanks please!)
                if(txtQuantity.value == "")
                {
                    txtQuantity.value = "1";
                } 
                
                //We only want whole numbers
                if(txtQuantity.value.indexOf(".") != -1)
                {
                    var newNumber = txtQuantity.value
                    txtQuantity.value = newNumber.substring(0, newNumber.indexOf("."));
                } 
                
                //We don't want any negitive values either
                if (txtQuantity.value < 0)
                {
                    txtQuantity.value = txtQuantity.value * (-1);
                }
                
                var quantity = txtQuantity.value;
                var subtotal = quantity * thisBook.price;
                total += subtotal
            }
        }
        return total;
    }
    
    // ------------------------------------------------------------------ \\
    // -------------- ADD / REMOVE BUTTONS (Image Changes) -------------- \\
    
    //Below: For the "Add"/"Remove"/"Purchase" buttons
    //Preload the images
    var mAddOver = new Image;
    var mAddDown = new Image;
    var mAddUp = new Image;
    var mRemOver = new Image;
    var mRemDown = new Image;
    var mRemUp = new Image;
    var mPurOver = new Image;
    var mPurDown = new Image;
    var mPurUp = new Image;
    var mRefreshOver = new Image;
    var mRefreshDown = new Image;
    var mRefreshUp = new Image;
    mAddOver.src = '../images/buttons/order/order/ButtonOver.gif';
    mAddDown.src = '../images/buttons/order/order/ButtonDown.gif';
    mAddUp.src = '../images/buttons/order/order/ButtonUp.gif';
    mRemOver.src = '../images/buttons/order/remove/ButtonOver.gif';
    mRemDown.src = '../images/buttons/order/remove/ButtonDown.gif';
    mRemUp.src = '../images/buttons/order/remove/ButtonUp.gif';
    mPurOver.src = '../images/buttons/order/purchase/ButtonOver.gif';
    mPurDown.src = '../images/buttons/order/purchase/ButtonDown.gif';
    mPurUp.src = '../images/buttons/order/purchase/ButtonUp.gif';
    mRefreshOver.src = '../images/buttons/order/refresh/ButtonOver.gif';
    mRefreshDown.src = '../images/buttons/order/refresh/ButtonDown.gif';
    mRefreshUp.src = '../images/buttons/order/refresh/ButtonUp.gif';
    
    //Mouse Over (add)
    function btnAddOver(imgID)
    {
        document.getElementById(imgID).src = mAddOver.src;
    }
    
    //Mouse Up (add)
    function btnAddUp(imgID)
    {
        document.getElementById(imgID).src = mAddUp.src;
    }
    
    //Mouse Down (add)
    function btnAddDown(imgID)
    {
        document.getElementById(imgID).src = mAddDown.src;
    }
    
    //Mouse Over (remove)
    function btnRemOver(imgID)
    {
        document.getElementById(imgID).src = mRemOver.src;
    }
    
    //Mouse Up (remove)
    function btnRemUp(imgID)
    {
        document.getElementById(imgID).src = mRemUp.src;
    }
    
    //Mouse Down (remove)
    function btnRemDown(imgID)
    {
        document.getElementById(imgID).src = mRemDown.src;
    }
    
    //Mouse Over (add)
    function btnPurOver(imgID)
    {
        document.getElementById(imgID).src = mPurOver.src;
    }
    
    //Mouse Up (add)
    function btnPurUp(imgID)
    {
        document.getElementById(imgID).src = mPurUp.src;
    }
    
    //Mouse Down (add)
    function btnPurDown(imgID)
    {
        document.getElementById(imgID).src = mPurDown.src;
    }
    
    //Mouse Over (add)
    function btnRefreshOver(imgID)
    {
        document.getElementById(imgID).src = mRefreshOver.src;
    }
    
    //Mouse Up (add)
    function btnRefreshUp(imgID)
    {
        document.getElementById(imgID).src = mRefreshUp.src;
    }
    
    //Mouse Down (add)
    function btnRefreshDown(imgID)
    {
        document.getElementById(imgID).src = mRefreshDown.src;
    }
    
    // --------------------------------------------- \\
    // -------------- EXPAND/COLLAPSE -------------- \\
            
    //Preload images
    var imgPlus = new Image();
    var imgMinus = new Image();
    imgPlus.src = "../images/buttons/plus.jpg";
    imgMinus.src = "../images/buttons/minus.jpg";
            
    //Expand/Collapse the book lists / tables
    function view(pmImg, span)
    {
        if (document.getElementById(pmImg).src != imgMinus.src)
        {
            document.getElementById(pmImg).src = imgMinus.src;
            document.getElementById(span).style.display='';
        }
        else
        {
            document.getElementById(pmImg).src = imgPlus.src;
            document.getElementById(span).style.display='none';
        }
    }