Commits

jasonyeo committed 43da403 Draft

separated js from html

Comments (0)

Files changed (4)

         <!-- config java script -->
         <script src="js/mainConfig.js"></script>
 
-        <script>
-            
-            $(document).ready(function(){
-                
-                runAtStartUp();
-                 
-                var shoppingCartCookies = new Array();
-                shoppingCartCookies = $.parseJSON(readCookie('shoppingCart'));
-                if(shoppingCartCookies!=null)
-                {
-                    for(var i=0;i<shoppingCartCookies.length;i++)
-                    {        
-                        loadItemFromCookie(shoppingCartCookies[i].productId,+shoppingCartCookies[i].productQty,
-                        shoppingCartCookies[i].productName,shoppingCartCookies[i].productEach,shoppingCartCookies[i].productTotal);
-                        
-                    }
-                } 
-                     
-            var payBtn = $("#PayBtn");
-            var clearFormBtn = $("#clearFormBtn");
-		
-            //either product or payment page
-            var divProduct = $("#divMainProductCol");
-            var divPayment = $("#divPayment");
-		
-            //product info span
-            var productTitle = $("#productTitle");
-       	
-            clearFormBtn.click(function() {
-                $("#productTable > tbody").empty();
-                reUpdateGrandTotal();
-            });
-		
-            payBtn.click(function() {
-			
-                var allProducts = new Array();
-                    
-                var totalPrice = 0;
-                   
-                //store all the products in the table of item added into an array
-                $("#productTable tbody tr").each(function() {
-                    var object = new productBought;
-                    object.productId = $(this).find("#productId").attr('class');
-                    object.productQty = $(this).find("#productQty").html();
-                    object.productName= $(this).find("#productId").html();
-                    object.productTotal = $(this).find('#productTotal').html();
-                    object.productEach = $(this).find('#productEach').html();
-                    allProducts.push(object);
-                        
-                    var eachSubTotal = $(this).find('#productTotal').html().split("$");
-                    totalPrice = Number(eachSubTotal[1]) + Number(totalPrice);
-                        
-                });
-                    
-                //object for the earlier array
-                function productBought(productTitle,qty)
-                {
-                    this.productTitle = productTitle;
-                    this.qty = qty;
-                }
-		
-                //store the item added and grand total into cookies
-                createCookie('shoppingCart',JSON.stringify(allProducts),0);
-                createCookie('grandTotal',totalPrice,0);
-                    
-                /**
-                 *code segment for formatting the data and sending to ajax server
-                 */
-                var productArray = new Array();
-                var productQtyArray = new Array();
-                    
-                for(var i =0;i<allProducts.length;i++)
-                {
-                    productArray.push(allProducts[i].productId);
-                    productQtyArray.push(allProducts[i].productQty);
-                }
-                    
-                var branchId = readCookie('branchId');
-                var employeeId = readCookie('employeeId');
-                    
-                //order info to send 
-                var orderInfo = { "Branch_ID": branchId, "Employee_ID": employeeId, "Product_ID": productArray, "Quantity": productQtyArray};
-                $.ajax({
-                    type: "PUT",
-                    url: "http://lowe.jschua.com/DinoPos/api/orders",
-                    data: JSON.stringify(orderInfo),
-                    contentType: "application/json; charset=utf-8",
-                    success: function(data) {
-                        console.log("Success!!!");
-                        createCookie('orderId',data,0);
-                        window.location = "paymentForm.html";
-                    },
-                    dataType: "text",
-                    error: function (jqXHR, textStatus, errorThrown) {
-                        $('#result').text("The following error occured: " + textStatus, errorThrown);
-                    }
-                });
-                 
-                  
-            });
-		
-            //hide the payment at the start
-            divPayment.hide();
-		
-            //reinitialize the nice table that doesn't scroll the header.
-            reinitChromaTable();
-		
-        });
-            
-        /*
-         *Method checks if the search text field is blank before proceeding
-         *
-         *@return false if search text box is empty
-         */
-        function validateSearchField()
-        {
-            if($('#productSearchKey').val().length==0)
-            {   
-                $('#searchErrorMsg').text("Search field can't be blank!");
-                return false;
-            }
-            else{
-                $('#searchErrorMsg').text("");
-            }
-        }
-           
-        function searchProduct() {
-                
-            //checking if search field is not blank
-            var ifFieldValid = validateSearchField();
-            if(ifFieldValid == false)
-                return;
-                
-            var searchKeyword = $('#productSearchKey').val();
-                
-            //deciding which restful api to use depending on search keyword
-            var url; 
-            if(isNumber(searchKeyword))
-                url = "http://lowe.jschua.com/DinoPos/api/products/" +searchKeyword;
-            else
-                url = "http://lowe.jschua.com/DinoPos/api/products/?name=" +searchKeyword;
-                
-      
-            var totalProductFound = 0;
-                
-            $.ajax({
-                url: url,
-                dataType:'json',
-                async:false,
-                success:function(data){
-                    clearSearchResult();
-                    
-                    if(data!=null)
-                    {
-                        if(data instanceof Array)
-                        {
-                            // On success, 'data' contains a list of products.
-                            $.each(data, function (key, val) {
-                                displayProductInfo(val,totalProductFound);
-                                totalProductFound++;
-                            });
-                        }
-                        else //only one search result
-                        {
-                            displayProductInfo(data,totalProductFound);
-                            totalProductFound++;
-                        }
-                    }
-                }
-            }).done(createPagnation(totalProductFound));
-               
-        }
-            
-        //global var 
-        var currentPage=1; //edited in showPage
-        var totalPage=0; //set in createPagnation
-             
-        /**
-         * Method create the page numbering after a search result
-         */
-        function createPagnation(totalElement)
-        {
-            if(totalElement !=0) //no point running the code if there's no search result
-            {
-                totalPage = Math.ceil(totalElement/2);
-                
-                //creating the main list
-                var mainUl = document.createElement("ul");
-                    
-                //limit the search result to only 20 pages. [Just like amazon]
-                var pages = Math.ceil(totalElement/2);
-                if(pages > 20)
-                    pages = 20;
-                    
-                //adding the "Prev" button
-                if(pages > 1)
-                {
-                    var subUl = document.createElement("li");
-                    subUl.className ="prev disabled"
-                    subUl.innerHTML ="<a href=\"#\" onClick=\"showPage(-1)\">Prev</a>";
-                    mainUl.appendChild(subUl);
-                }
-                    
-                for(var x=1;x<=pages;x++)
-                {
-                    var subUl = document.createElement("li");
-                    subUl.className =x;
-                    if(x==1)
-                        subUl.className = subUl.className +" active";
-                    subUl.innerHTML ="<a href=\"#\" onClick=\"showPage("+x+")\">"+x+"</a>";
-                    mainUl.appendChild(subUl);
-                }
-                    
-                //Adding the next button
-                if(pages > 1)
-                {
-                    var subUl = document.createElement("li");
-                    subUl.innerHTML ="<a href=\"#\" onClick=\"showPage(0)\">Next</a>";
-                    subUl.className = "next";
-                    mainUl.appendChild(subUl);
-                }
-                var test = document.getElementById("productPagination");
-                test.appendChild(mainUl);
-            }
-        }
-            
-        /**
-         *Method is meant for the "enter" key listener for searching of product.
-         */
-        $("#productSearchKey").keyup(function(event){
-            if(event.keyCode == 13){
-                $("#btnProductSearch").click();
-            }
-        });
-
-            
-        /**
-         *Method take in the page number depending on what user selected.
-         *if pageNumber == 0, it means user clicked next button
-         *if pageNumber ==-1, it means user clicked previous button
-         */
-        function showPage(pageNumber)
-        {
-            //set the previously selected page as not active
-            $('#productPagination ul li.'+currentPage).removeClass('active');
-                
-            //-1 = prev, 0 = next
-            if(pageNumber!=-1 && pageNumber!=0){
-                currentPage = pageNumber;
-            }
-            else if(pageNumber==-1) //prev was selected
-            {
-                if(currentPage!=1)
-                {
-                    currentPage = currentPage-1;
-                    pageNumber = currentPage;
-                }else{
-                    pageNumber=1;
-                }
-            }
-            else if(pageNumber==0) //next was selected
-            {
-                if(currentPage!=totalPage){
-                    currentPage = currentPage+1;
-                    pageNumber = currentPage;
-                }else{
-                    pageNumber=totalPage;
-                }
-            }
-                
-            //hide the current page product
-            $('._current','#divSubProductCol').removeClass('_current').hide();
-                
-            var productNo1;
-            if(pageNumber==1){    
-                productNo1 = 0;
-            }
-            else{    
-                productNo1 = (pageNumber-1)*2;
-            }
-            var productNo2 = productNo1+1;
-               
-            //show the selected page product
-            $('#productNo_'+productNo1).addClass('_current').fadeIn();
-            $('#productNo_'+productNo2).addClass('_current').fadeIn();
-               
-            //below code to disable the pageNumber button
-            if(pageNumber!=0 && pageNumber!=-1){
-                $('#productPagination ul li.'+pageNumber).addClass('active');
-                $('#productPagination ul li.next').removeClass('disabled');
-                $('#productPagination ul li.prev').removeClass('disabled');
-            }
-            if(pageNumber ==totalPage){
-                $('#productPagination ul li.next').addClass('disabled');
-            }
-            if(pageNumber ==1){
-                $('#productPagination ul li.previous').addClass('disabled');
-            }   
-        }
-            
-            
-        /**
-         *function clear the pagnation and the searchresult
-         */
-        function clearSearchResult()
-        {
-            if($('#divSubProductCol').children().length >0) {
-                $('#divSubProductCol').empty();
-            }
-            if($('#productPagination').children().length >0) {
-                $('#productPagination').empty();
-            }
-        }
-            
-        /**
-         * Function role is to display the product information
-         * 
-         * @Param val = product object
-         * @Param product numbering = search result order #
-         */
-        function displayProductInfo(val,productNumbering)
-        {
-            var divInPlace =  document.getElementById("divSubProductCol");
-                  
-            var mainDiv = document.createElement("div");
-            mainDiv.id = "productNo_"+productNumbering;
-                
-            //hide product numbering 2 onwards. 
-            if(productNumbering >1)
-            {
-                mainDiv.setAttribute("style", "display:none")
-                mainDiv.className ="pagedemo";
-            }
-            else
-            {
-                mainDiv.className ="pagedemo _current";
-            }
-                
-            //creating the image layout
-            var divForImage = document.createElement("div");
-            divForImage.className ="span2";
-            divForImage.innerHTML ="<img src=\""+val.ImageUrl+"\" height=150 width=150>"
-                               
-            //creating the product brand, title, description and price layout
-            var divForProductInfo = document.createElement("div");
-            divForProductInfo.className ="span4";
-            divForProductInfo.setAttribute("id", "div_"+val.Product_ID);
-            var productBrand = "<h3> <span id=\"productBrand\">"+val.Brand+"</span></h4>";
-            var productTitle = "<h4> <span id=\"productTitle\">"+val.Name+"</span></h4>";
-            var productDescription ="<h6> <span id=\"productDescription\">"+val.Description+"</span></h6>";
-            var productPrice = "<h6> Price $<span id=\"productPrice\">"+val.Pricesell+"</span> </h6>";
-            divForProductInfo.innerHTML= productBrand+productTitle+productDescription+productPrice;
-                
-            //creating the form main div
-            var qtyForm = document.createElement("form");
-            qtyForm.className ="form-horizontal";   
-            var divForQtyForm = document.createElement("div");
-            divForQtyForm.className = "control-group";
-                
-            //creating the error message
-            var labelForErrorMsg = document.createElement("label");
-            labelForErrorMsg.className ="control-label text-error";
-            labelForErrorMsg.setAttribute("id","errorMsg_"+val.Product_ID);
-                
-            //creating the quantity input
-            var divForControl = document.createElement("div");
-            divForControl.className = "controls";
-            var inputForQty =document.createElement("input");
-            inputForQty.setAttribute("type", "text");
-            inputForQty.setAttribute("id","qty_"+val.Product_ID);
-            inputForQty.setAttribute("placeholder","Quantity");
-            inputForQty.className ="input-small";
-            divForControl.appendChild(inputForQty);
-            divForQtyForm.appendChild(labelForErrorMsg);
-            divForQtyForm.appendChild(divForControl);
-            qtyForm.appendChild(divForQtyForm);
-             
-            //creating the add to cart button
-            var addToCartButton = document.createElement("input");
-            addToCartButton.setAttribute("id",val.Product_ID);
-            addToCartButton.setAttribute("type","button");
-            var info = "addItemToTable("+val.Product_ID+")"
-            addToCartButton.setAttribute("onClick",info);
-            addToCartButton.setAttribute("value","Add this item to cart!");
-            addToCartButton.className ="btn btn-info span4";                
-                                
-            //adding the quantity text input and add to cart button into the product info page
-            divForProductInfo.appendChild(qtyForm);
-            divForProductInfo.appendChild(addToCartButton);
-                                
-            //adding the image and product info div into the main div
-            mainDiv.appendChild(divForImage);
-            mainDiv.appendChild(divForProductInfo); 
-               
-            //appending the div.
-            divInPlace.appendChild(mainDiv);
-        }
-            
-        /*
-         * Function activated when user clicked "Add to Cart" button
-         * @Param productId
-         */
-        function addItemToTable(productId)
-        {
-            //check if the user has keyed in qty
-            if($('#qty_'+productId).val().length==0) 
-            {
-                $('#errorMsg_'+productId).text("Qty can't be blank!");
-                return;
-            }
-                
-            var whetherExistProduct = false;
-            
-            //loop through the table to check if the exact product has been added before
-            //if added before, just update qty.
-            $('#productTable >tbody >tr').each(function(){
-                
-                var inTableProductId = $(this).find('#productId').attr('class') 
-                
-                if(inTableProductId == productId ) //item wanted to add already exist in table
-                {
-                    //update the qty and total instead
-                    var currentProductQty = $(this).find("#productQty").html();
-                    var currentProductEach = $(this).find('#productEach').html();
-                      
-                    //finding out the new quantity by adding old quantity + new quantity
-                    var oldProductQty = $('#div_'+productId).find('#qty_'+productId).val();
-                    var newProductQty = Number(currentProductQty) + Number(oldProductQty);
-                     
-                    //finding out the total by multiplying new qty and product price each
-                    var newTotal = (newProductQty * currentProductEach).toFixed(2);
-                     
-                    //update the qty field with new qty
-                    $(this).find('#productQty').html(newProductQty);
-                     
-                    //update the total with new total
-                    $(this).find('#productTotal').html('$'+newTotal);
-                     
-                    whetherExistProduct=true;
-                    return;
-                }
-                    
-            });
-                
-                
-            //product added is a new product - create a new row for it.
-            if(whetherExistProduct==false)
-            {
-                
-                var productName = $('#div_'+productId).find('#productTitle').text();
-                var productPrice = Number($('#div_'+productId).find('#productPrice').text());
-                var qtySelected = $('#div_'+productId).find('#qty_'+productId).val();
-                  
-                var totalPrice = qtySelected * productPrice;
-                
-                var tableDetailHeader ="<tr>";
-                var tableProductTitle ="<td class=\""+productId+"\" id=\"productId\">"+productName+"</td>";
-                var tableQty = "<td id=\"productQty\">"+qtySelected+"</td>";
-                var tableEach = "<td id=\"productEach\">"+(productPrice).toFixed(2)+"</td>";
-                var tableTotal = "<td id=\"productTotal\" >$"+(totalPrice).toFixed(2)+"</td>";
-                var tableRemoveItemBtn = "<td> <button class=\"btn btn-mini\" onclick=\"deleteRowItem(this)\"> x</button></td>"
-                var tableDetailFooter ="</tr>";
-                var entireTable = tableDetailHeader + tableProductTitle + tableQty + tableEach + tableTotal + tableRemoveItemBtn+tableDetailFooter;
-                
-                $("#productTable > tbody:last").append(entireTable);
-            }  
-            reUpdateGrandTotal();
-            reinitChromaTable();
-        }
-            
-            
-            
-        function loadItemFromCookie(productId,productQty,productName,productEach,productTotal)
-        {
-               
-            var tableDetailHeader ="<tr>";
-            var tableProductTitle ="<td class=\""+productId+"\" id=\"productId\">"+productName+"</td>";
-            var tableQty = "<td id=\"productQty\">"+productQty+"</td>";
-            var tableEach = "<td id=\"productEach\">"+productEach+"</td>";
-            var tableTotal = "<td id=\"productTotal\" >"+productTotal+"</td>";
-            var tableRemoveItemBtn = "<td> <button class=\"btn btn-mini\" onclick=\"deleteRowItem(this)\"> x</button></td>"
-            var tableDetailFooter ="</tr>";
-            var entireTable = tableDetailHeader + tableProductTitle + tableQty + tableEach + tableTotal + tableRemoveItemBtn+tableDetailFooter;
-                
-            $("#productTable > tbody:last").append(entireTable);
-                
-            reinitChromaTable();
-        }
-            
-        function isNumber (o){
-            return ! isNaN (o-0) && o != null;
-        }
-   
-   
-        function createCookie(name,value,days) {
-            if (days) {
-                var date = new Date();
-                date.setTime(date.getTime()+(days*24*60*60*1000));
-                var expires = "; expires="+date.toGMTString();
-            }
-            else var expires = "";
-            document.cookie = name+"="+value+expires+"; path=/";
-        }
-            
-        function readCookie(name) {
-            var nameEQ = name + "=";
-            var ca = document.cookie.split(';');
-            for(var i=0;i < ca.length;i++) {
-                var c = ca[i];
-                while (c.charAt(0)==' ') c = c.substring(1,c.length);
-                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
-            }
-            return null;
-        }
-  	
-        function reinitChromaTable()
-        {
-            $('#productTable').chromatable({
-                width: "100%",
-                //width: "450px",
-                height: "300px",
-                scrolling: "yes"
-	
-            });
-        }
-        function reUpdateGrandTotal()
-        {
-            var totalPrice = 0;
-            $('#productTable >tbody >tr').each(function(){
-                    
-                var eachSubTotal = $(this).find('#productTotal').html().split("$");
-                totalPrice = Number(eachSubTotal[1]) + Number(totalPrice);
-                    
-            });
-                
-            $('#totalAmt').text("Total: $"+totalPrice);
-        }
-        function deleteRowItem(o)
-        {
-            //o = button, parent = htmltablecell -> htmltablerow -> htmltablesection 
-            var p = o.parentNode.parentNode;
-            p.parentNode.removeChild(p);
-                
-            reUpdateGrandTotal();
-                
-        };
- 
-        </script>
-
+        <script src="js/index.js"> </script> 
     </body>
 
 </html>
+$(document).ready(function(){
+
+    runAtStartUp();
+
+    var shoppingCartCookies = new Array();
+    shoppingCartCookies = $.parseJSON(readCookie('shoppingCart'));
+    if(shoppingCartCookies!=null)
+{
+    for(var i=0;i<shoppingCartCookies.length;i++)
+{        
+    loadItemFromCookie(shoppingCartCookies[i].productId,+shoppingCartCookies[i].productQty,
+        shoppingCartCookies[i].productName,shoppingCartCookies[i].productEach,shoppingCartCookies[i].productTotal);
+
+}
+} 
+
+var payBtn = $("#PayBtn");
+var clearFormBtn = $("#clearFormBtn");
+
+//either product or payment page
+var divProduct = $("#divMainProductCol");
+var divPayment = $("#divPayment");
+
+//product info span
+var productTitle = $("#productTitle");
+
+clearFormBtn.click(function() {
+    $("#productTable > tbody").empty();
+    reUpdateGrandTotal();
+});
+
+payBtn.click(function() {
+
+    var allProducts = new Array();
+
+    var totalPrice = 0;
+
+    //store all the products in the table of item added into an array
+    $("#productTable tbody tr").each(function() {
+        var object = new productBought;
+        object.productId = $(this).find("#productId").attr('class');
+        object.productQty = $(this).find("#productQty").html();
+        object.productName= $(this).find("#productId").html();
+        object.productTotal = $(this).find('#productTotal').html();
+        object.productEach = $(this).find('#productEach').html();
+        allProducts.push(object);
+
+        var eachSubTotal = $(this).find('#productTotal').html().split("$");
+        totalPrice = Number(eachSubTotal[1]) + Number(totalPrice);
+
+    });
+
+    //object for the earlier array
+    function productBought(productTitle,qty)
+    {
+        this.productTitle = productTitle;
+        this.qty = qty;
+    }
+
+    //store the item added and grand total into cookies
+    createCookie('shoppingCart',JSON.stringify(allProducts),0);
+    createCookie('grandTotal',totalPrice,0);
+
+    /**
+     *code segment for formatting the data and sending to ajax server
+     */
+    var productArray = new Array();
+    var productQtyArray = new Array();
+
+    for(var i =0;i<allProducts.length;i++)
+    {
+        productArray.push(allProducts[i].productId);
+        productQtyArray.push(allProducts[i].productQty);
+    }
+
+    var branchId = readCookie('branchId');
+    var employeeId = readCookie('employeeId');
+
+    //order info to send 
+    var orderInfo = { "Branch_ID": branchId, "Employee_ID": employeeId, "Product_ID": productArray, "Quantity": productQtyArray};
+    $.ajax({
+        type: "PUT",
+        url: "http://lowe.jschua.com/DinoPos/api/orders",
+        data: JSON.stringify(orderInfo),
+        contentType: "application/json; charset=utf-8",
+        success: function(data) {
+            console.log("Success!!!");
+            createCookie('orderId',data,0);
+            window.location = "paymentForm.html";
+        },
+        dataType: "text",
+        error: function (jqXHR, textStatus, errorThrown) {
+            $('#result').text("The following error occured: " + textStatus, errorThrown);
+        }
+    });
+
+
+});
+
+//hide the payment at the start
+divPayment.hide();
+
+//reinitialize the nice table that doesn't scroll the header.
+reinitChromaTable();
+
+});
+
+/*
+ *Method checks if the search text field is blank before proceeding
+ *
+ *@return false if search text box is empty
+ */
+function validateSearchField()
+{
+    if($('#productSearchKey').val().length==0)
+    {   
+        $('#searchErrorMsg').text("Search field can't be blank!");
+        return false;
+    }
+    else{
+        $('#searchErrorMsg').text("");
+    }
+}
+
+function searchProduct() {
+
+    //checking if search field is not blank
+    var ifFieldValid = validateSearchField();
+    if(ifFieldValid == false)
+        return;
+
+    var searchKeyword = $('#productSearchKey').val();
+
+    //deciding which restful api to use depending on search keyword
+    var url; 
+    if(isNumber(searchKeyword))
+        url = "http://lowe.jschua.com/DinoPos/api/products/" +searchKeyword;
+    else
+        url = "http://lowe.jschua.com/DinoPos/api/products/?name=" +searchKeyword;
+
+
+    var totalProductFound = 0;
+
+    $.ajax({
+        url: url,
+        dataType:'json',
+        async:false,
+        success:function(data){
+            clearSearchResult();
+
+            if(data!=null)
+    {
+        if(data instanceof Array)
+    {
+        // On success, 'data' contains a list of products.
+        $.each(data, function (key, val) {
+            displayProductInfo(val,totalProductFound);
+            totalProductFound++;
+        });
+    }
+        else //only one search result
+    {
+        displayProductInfo(data,totalProductFound);
+        totalProductFound++;
+    }
+    }
+        }
+    }).done(createPagnation(totalProductFound));
+
+}
+
+//global var 
+var currentPage=1; //edited in showPage
+var totalPage=0; //set in createPagnation
+
+/**
+ * Method create the page numbering after a search result
+ */
+function createPagnation(totalElement)
+{
+    if(totalElement !=0) //no point running the code if there's no search result
+    {
+        totalPage = Math.ceil(totalElement/2);
+
+        //creating the main list
+        var mainUl = document.createElement("ul");
+
+        //limit the search result to only 20 pages. [Just like amazon]
+        var pages = Math.ceil(totalElement/2);
+        if(pages > 20)
+            pages = 20;
+
+        //adding the "Prev" button
+        if(pages > 1)
+        {
+            var subUl = document.createElement("li");
+            subUl.className ="prev disabled"
+                subUl.innerHTML ="<a href=\"#\" onClick=\"showPage(-1)\">Prev</a>";
+            mainUl.appendChild(subUl);
+        }
+
+        for(var x=1;x<=pages;x++)
+        {
+            var subUl = document.createElement("li");
+            subUl.className =x;
+            if(x==1)
+                subUl.className = subUl.className +" active";
+            subUl.innerHTML ="<a href=\"#\" onClick=\"showPage("+x+")\">"+x+"</a>";
+            mainUl.appendChild(subUl);
+        }
+
+        //Adding the next button
+        if(pages > 1)
+        {
+            var subUl = document.createElement("li");
+            subUl.innerHTML ="<a href=\"#\" onClick=\"showPage(0)\">Next</a>";
+            subUl.className = "next";
+            mainUl.appendChild(subUl);
+        }
+        var test = document.getElementById("productPagination");
+        test.appendChild(mainUl);
+    }
+}
+
+/**
+ *Method is meant for the "enter" key listener for searching of product.
+ */
+$("#productSearchKey").keyup(function(event){
+    if(event.keyCode == 13){
+        $("#btnProductSearch").click();
+    }
+});
+
+
+/**
+ *Method take in the page number depending on what user selected.
+ *if pageNumber == 0, it means user clicked next button
+ *if pageNumber ==-1, it means user clicked previous button
+ */
+function showPage(pageNumber)
+{
+    //set the previously selected page as not active
+    $('#productPagination ul li.'+currentPage).removeClass('active');
+
+    //-1 = prev, 0 = next
+    if(pageNumber!=-1 && pageNumber!=0){
+        currentPage = pageNumber;
+    }
+    else if(pageNumber==-1) //prev was selected
+    {
+        if(currentPage!=1)
+        {
+            currentPage = currentPage-1;
+            pageNumber = currentPage;
+        }else{
+            pageNumber=1;
+        }
+    }
+    else if(pageNumber==0) //next was selected
+    {
+        if(currentPage!=totalPage){
+            currentPage = currentPage+1;
+            pageNumber = currentPage;
+        }else{
+            pageNumber=totalPage;
+        }
+    }
+
+    //hide the current page product
+    $('._current','#divSubProductCol').removeClass('_current').hide();
+
+    var productNo1;
+    if(pageNumber==1){    
+        productNo1 = 0;
+    }
+    else{    
+        productNo1 = (pageNumber-1)*2;
+    }
+    var productNo2 = productNo1+1;
+
+    //show the selected page product
+    $('#productNo_'+productNo1).addClass('_current').fadeIn();
+    $('#productNo_'+productNo2).addClass('_current').fadeIn();
+
+    //below code to disable the pageNumber button
+    if(pageNumber!=0 && pageNumber!=-1){
+        $('#productPagination ul li.'+pageNumber).addClass('active');
+        $('#productPagination ul li.next').removeClass('disabled');
+        $('#productPagination ul li.prev').removeClass('disabled');
+    }
+    if(pageNumber ==totalPage){
+        $('#productPagination ul li.next').addClass('disabled');
+    }
+    if(pageNumber ==1){
+        $('#productPagination ul li.previous').addClass('disabled');
+    }   
+}
+
+
+/**
+ *function clear the pagnation and the searchresult
+ */
+function clearSearchResult()
+{
+    if($('#divSubProductCol').children().length >0) {
+        $('#divSubProductCol').empty();
+    }
+    if($('#productPagination').children().length >0) {
+        $('#productPagination').empty();
+    }
+}
+
+/**
+ * Function role is to display the product information
+ * 
+ * @Param val = product object
+ * @Param product numbering = search result order #
+ */
+function displayProductInfo(val,productNumbering)
+{
+    var divInPlace =  document.getElementById("divSubProductCol");
+
+    var mainDiv = document.createElement("div");
+    mainDiv.id = "productNo_"+productNumbering;
+
+    //hide product numbering 2 onwards. 
+    if(productNumbering >1)
+    {
+        mainDiv.setAttribute("style", "display:none")
+            mainDiv.className ="pagedemo";
+    }
+    else
+    {
+        mainDiv.className ="pagedemo _current";
+    }
+
+    //creating the image layout
+    var divForImage = document.createElement("div");
+    divForImage.className ="span2";
+    divForImage.innerHTML ="<img src=\""+val.ImageUrl+"\" height=150 width=150>"
+
+        //creating the product brand, title, description and price layout
+        var divForProductInfo = document.createElement("div");
+    divForProductInfo.className ="span4";
+    divForProductInfo.setAttribute("id", "div_"+val.Product_ID);
+    var productBrand = "<h3> <span id=\"productBrand\">"+val.Brand+"</span></h4>";
+    var productTitle = "<h4> <span id=\"productTitle\">"+val.Name+"</span></h4>";
+    var productDescription ="<h6> <span id=\"productDescription\">"+val.Description+"</span></h6>";
+    var productPrice = "<h6> Price $<span id=\"productPrice\">"+val.Pricesell+"</span> </h6>";
+    divForProductInfo.innerHTML= productBrand+productTitle+productDescription+productPrice;
+
+    //creating the form main div
+    var qtyForm = document.createElement("form");
+    qtyForm.className ="form-horizontal";   
+    var divForQtyForm = document.createElement("div");
+    divForQtyForm.className = "control-group";
+
+    //creating the error message
+    var labelForErrorMsg = document.createElement("label");
+    labelForErrorMsg.className ="control-label text-error";
+    labelForErrorMsg.setAttribute("id","errorMsg_"+val.Product_ID);
+
+    //creating the quantity input
+    var divForControl = document.createElement("div");
+    divForControl.className = "controls";
+    var inputForQty =document.createElement("input");
+    inputForQty.setAttribute("type", "text");
+    inputForQty.setAttribute("id","qty_"+val.Product_ID);
+    inputForQty.setAttribute("placeholder","Quantity");
+    inputForQty.className ="input-small";
+    divForControl.appendChild(inputForQty);
+    divForQtyForm.appendChild(labelForErrorMsg);
+    divForQtyForm.appendChild(divForControl);
+    qtyForm.appendChild(divForQtyForm);
+
+    //creating the add to cart button
+    var addToCartButton = document.createElement("input");
+    addToCartButton.setAttribute("id",val.Product_ID);
+    addToCartButton.setAttribute("type","button");
+    var info = "addItemToTable("+val.Product_ID+")"
+        addToCartButton.setAttribute("onClick",info);
+    addToCartButton.setAttribute("value","Add this item to cart!");
+    addToCartButton.className ="btn btn-info span4";                
+
+    //adding the quantity text input and add to cart button into the product info page
+    divForProductInfo.appendChild(qtyForm);
+    divForProductInfo.appendChild(addToCartButton);
+
+    //adding the image and product info div into the main div
+    mainDiv.appendChild(divForImage);
+    mainDiv.appendChild(divForProductInfo); 
+
+    //appending the div.
+    divInPlace.appendChild(mainDiv);
+}
+
+/*
+ * Function activated when user clicked "Add to Cart" button
+ * @Param productId
+ */
+function addItemToTable(productId)
+{
+    //check if the user has keyed in qty
+    if($('#qty_'+productId).val().length==0) 
+    {
+        $('#errorMsg_'+productId).text("Qty can't be blank!");
+        return;
+    }
+
+    var whetherExistProduct = false;
+
+    //loop through the table to check if the exact product has been added before
+    //if added before, just update qty.
+    $('#productTable >tbody >tr').each(function(){
+
+        var inTableProductId = $(this).find('#productId').attr('class') 
+
+        if(inTableProductId == productId ) //item wanted to add already exist in table
+    {
+        //update the qty and total instead
+        var currentProductQty = $(this).find("#productQty").html();
+        var currentProductEach = $(this).find('#productEach').html();
+
+        //finding out the new quantity by adding old quantity + new quantity
+        var oldProductQty = $('#div_'+productId).find('#qty_'+productId).val();
+        var newProductQty = Number(currentProductQty) + Number(oldProductQty);
+
+        //finding out the total by multiplying new qty and product price each
+        var newTotal = (newProductQty * currentProductEach).toFixed(2);
+
+        //update the qty field with new qty
+        $(this).find('#productQty').html(newProductQty);
+
+        //update the total with new total
+        $(this).find('#productTotal').html('$'+newTotal);
+
+        whetherExistProduct=true;
+        return;
+    }
+
+    });
+
+
+    //product added is a new product - create a new row for it.
+    if(whetherExistProduct==false)
+    {
+
+        var productName = $('#div_'+productId).find('#productTitle').text();
+        var productPrice = Number($('#div_'+productId).find('#productPrice').text());
+        var qtySelected = $('#div_'+productId).find('#qty_'+productId).val();
+
+        var totalPrice = qtySelected * productPrice;
+
+        var tableDetailHeader ="<tr>";
+        var tableProductTitle ="<td class=\""+productId+"\" id=\"productId\">"+productName+"</td>";
+        var tableQty = "<td id=\"productQty\">"+qtySelected+"</td>";
+        var tableEach = "<td id=\"productEach\">"+(productPrice).toFixed(2)+"</td>";
+        var tableTotal = "<td id=\"productTotal\" >$"+(totalPrice).toFixed(2)+"</td>";
+        var tableRemoveItemBtn = "<td> <button class=\"btn btn-mini\" onclick=\"deleteRowItem(this)\"> x</button></td>"
+            var tableDetailFooter ="</tr>";
+        var entireTable = tableDetailHeader + tableProductTitle + tableQty + tableEach + tableTotal + tableRemoveItemBtn+tableDetailFooter;
+
+        $("#productTable > tbody:last").append(entireTable);
+    }  
+    reUpdateGrandTotal();
+    reinitChromaTable();
+}
+
+
+
+function loadItemFromCookie(productId,productQty,productName,productEach,productTotal)
+{
+
+    var tableDetailHeader ="<tr>";
+    var tableProductTitle ="<td class=\""+productId+"\" id=\"productId\">"+productName+"</td>";
+    var tableQty = "<td id=\"productQty\">"+productQty+"</td>";
+    var tableEach = "<td id=\"productEach\">"+productEach+"</td>";
+    var tableTotal = "<td id=\"productTotal\" >"+productTotal+"</td>";
+    var tableRemoveItemBtn = "<td> <button class=\"btn btn-mini\" onclick=\"deleteRowItem(this)\"> x</button></td>"
+        var tableDetailFooter ="</tr>";
+    var entireTable = tableDetailHeader + tableProductTitle + tableQty + tableEach + tableTotal + tableRemoveItemBtn+tableDetailFooter;
+
+    $("#productTable > tbody:last").append(entireTable);
+
+    reinitChromaTable();
+}
+
+function isNumber (o){
+    return ! isNaN (o-0) && o != null;
+}
+
+
+function createCookie(name,value,days) {
+    if (days) {
+        var date = new Date();
+        date.setTime(date.getTime()+(days*24*60*60*1000));
+        var expires = "; expires="+date.toGMTString();
+    }
+    else var expires = "";
+    document.cookie = name+"="+value+expires+"; path=/";
+}
+
+function readCookie(name) {
+    var nameEQ = name + "=";
+    var ca = document.cookie.split(';');
+    for(var i=0;i < ca.length;i++) {
+        var c = ca[i];
+        while (c.charAt(0)==' ') c = c.substring(1,c.length);
+        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
+    }
+    return null;
+}
+
+function reinitChromaTable()
+{
+    $('#productTable').chromatable({
+        width: "100%",
+    //width: "450px",
+    height: "300px",
+    scrolling: "yes"
+
+    });
+}
+function reUpdateGrandTotal()
+{
+    var totalPrice = 0;
+    $('#productTable >tbody >tr').each(function(){
+
+        var eachSubTotal = $(this).find('#productTotal').html().split("$");
+        totalPrice = Number(eachSubTotal[1]) + Number(totalPrice);
+
+    });
+
+    $('#totalAmt').text("Total: $"+totalPrice);
+}
+function deleteRowItem(o)
+{
+    //o = button, parent = htmltablecell -> htmltablerow -> htmltablesection 
+    var p = o.parentNode.parentNode;
+    p.parentNode.removeChild(p);
+
+    reUpdateGrandTotal();
+
+};
+
+$(document).ready(function(){
+    runAtStartUp();
+
+    if(readCookie("rememberLogin")==="true") {
+        window.location = "index.html";
+    }
+
+    loadBranchDetails();
+});
+
+function loadBranchDetails() {
+
+    var divInPlace =  document.getElementById("listForBranchDetails");
+
+    $.getJSON("http://lowe.jschua.com/DinoPos/api/branches/", function (data) {
+
+        // On success, 'data' contains a list of branch.
+        $.each(data, function (key, val) {
+
+            // Format the text to display.
+            var branchOption = document.createElement("option");
+            branchOption.innerHTML = val.Name;
+            branchOption.id = val.Branch_ID;
+            branchOption.className = val.Tax_Percentage;
+            divInPlace.appendChild(branchOption);
+        });
+    })
+    .fail(
+            function (jqXHR, textStatus, err) {
+                $('#allbranch').text('Error: ' + err);
+            });
+}
+
+$('#loginBtn').click(function() {
+    console.log("came login!!");
+
+    numberOfLoop=0;
+
+    if(validateFieldNotEmpty())
+{
+    checkValidUserAndRedirect();
+    //create the progress bar animation
+    tid = setInterval(showProgress, 750);
+}
+});
+
+/*
+ *Method validate the login name and password field
+ *
+ *@return false if there are empty fields not filled in
+ */
+function validateFieldNotEmpty()
+{
+    //get the email and password
+    var userEmail = document.loginForm.userId.value;
+    var userPassword = document.loginForm.userPassword.value;
+
+    if(userEmail.length==0)
+    {
+        alert("Please fill in your userEmail");
+        return false;
+    }
+    if(userPassword.length==0)
+    {
+        alert("Please key in your password");
+        return false;
+    }
+
+    return true;
+}
+
+
+/**
+ * Method simulate a progress bar for the user to see when they clicked login.
+ */
+//global variable for the progress bars.
+var numberOfLoop = 0;
+var tid;     
+function showProgress()
+{
+    numberOfLoop++;
+    if(numberOfLoop ==6)
+    {    
+        clearTimeout(tid);
+        return;
+    }
+    var percentage = Number(numberOfLoop*20);
+    $('#progressBarDiv').attr('style', "");
+    $('#progressBar').attr('style',"width:"+percentage+"%");
+
+}
+
+
+
+function checkValidUserAndRedirect()
+{
+
+    var userName = document.loginForm.userId.value;
+    var userPassword = document.loginForm.userPassword.value;
+
+    console.log("username =="+userName);
+    console.log("userPassword=="+userPassword);
+
+
+    var userInfo = { "username": userName, "password": userPassword };
+    $.ajax({
+        type: "POST",
+        url: "http://lowe.jschua.com/DinoPos/api/users",
+        async: true,
+        data: JSON.stringify(userInfo),
+        contentType: "application/json; charset=utf-8",
+        statusCode: {
+            202: function () {
+            },
+        406: function () {
+            $('#errorMessage').text("Invalid login or password. Please try again.");
+            clearTimeout(tid);
+            $('#progressBar').attr('style',"width:100%");
+        }
+        },
+        success: function (data) {
+
+            var x = document.getElementById("listForBranchDetails").selectedIndex;
+            var branchId = document.getElementsByTagName("option")[x].id;
+            var taxPercentage = document.getElementsByTagName("option")[x].className;
+
+            var daysForCookie = 0;
+
+            if($('input[id=rememberCheckBox]').is(':checked'))
+            {
+                daysForCookie = 3;
+                createCookie('rememberLogin','true',3);
+            }
+
+            createCookie('employeeId',data,daysForCookie);
+            createCookie('branchId',branchId,daysForCookie);
+            createCookie('taxPercentage',taxPercentage,daysForCookie);
+
+            window.location = "index.html";
+        },
+        dataType: "text",
+        error: function (jqXHR, textStatus, errorThrown) {
+        }
+    });
+
+}
+
+function createCookie(name,value,days) {
+    if (days) {
+        var date = new Date();
+        date.setTime(date.getTime()+(days*24*60*60*1000));
+        var expires = "; expires="+date.toGMTString();
+    }
+    else var expires = "";
+    document.cookie = name+"="+value+expires+"; path=/";
+}
+
+function readCookie(name) {
+    var nameEQ = name + "=";
+    var ca = document.cookie.split(';');
+    for(var i=0;i < ca.length;i++) {
+        var c = ca[i];
+        while (c.charAt(0)==' ') c = c.substring(1,c.length);
+        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
+    }
+    return null;
+}
+
-
 <!DOCTYPE html>
 <html>
     <head>
         
 
         <script src="js/lib/jquery-1.8.2.min.js"></script>
-       <script src="js/lib/bootstrap.min.js"></script>
+        <script src="js/lib/bootstrap.min.js"></script>
         
-        <!-- config java script -->
-        <script src="js/loginTemplate.js"></script>
         <script src="js/mainConfig.js"></script>
-        
-        <script>
-   
-            $(document).ready(function(){
-                runAtStartUp();
-                
-                if(readCookie("rememberLogin")=="true")
-                {
-                    window.location = "index.html";
-                }
-                
-                loadBranchDetails();
-                
-            });
-            
-            function loadBranchDetails() {
-                
-                var divInPlace =  document.getElementById("listForBranchDetails");
-                
-                $.getJSON("http://lowe.jschua.com/DinoPos/api/branches/", function (data) {
-                
-                    // On success, 'data' contains a list of branch.
-                    $.each(data, function (key, val) {
-
-                        // Format the text to display.
-                        var branchOption = document.createElement("option");
-                        branchOption.innerHTML = val.Name;
-                        branchOption.id = val.Branch_ID;
-                        branchOption.className = val.Tax_Percentage;
-                        divInPlace.appendChild(branchOption);
-                    });
-                })
-                .fail(
-                function (jqXHR, textStatus, err) {
-                    $('#allbranch').text('Error: ' + err);
-                });
-            }
-           
-            $('#loginBtn').click(function() {
-                console.log("came login!!");
-                
-                numberOfLoop=0;
-		
-                if(validateFieldNotEmpty())
-                {
-                    checkValidUserAndRedirect();
-                    //create the progress bar animation
-                    tid = setInterval(showProgress, 750);
-                }
-            });
-            
-            /*
-             *Method validate the login name and password field
-             *
-             *@return false if there are empty fields not filled in
-             */
-            function validateFieldNotEmpty()
-            {
-                //get the email and password
-                var userEmail = document.loginForm.userId.value;
-                var userPassword = document.loginForm.userPassword.value;
-                
-                if(userEmail.length==0)
-                {
-                    alert("Please fill in your userEmail");
-                    return false;
-                }
-                if(userPassword.length==0)
-                {
-                    alert("Please key in your password");
-                    return false;
-                }
-                
-                return true;
-            }
-         
-         
-            /**
-             * Method simulate a progress bar for the user to see when they clicked login.
-             */
-            //global variable for the progress bars.
-            var numberOfLoop = 0;
-            var tid;     
-            function showProgress()
-            {
-                numberOfLoop++;
-                if(numberOfLoop ==6)
-                {    
-                    clearTimeout(tid);
-                    return;
-                }
-                var percentage = Number(numberOfLoop*20);
-                $('#progressBarDiv').attr('style', "");
-                $('#progressBar').attr('style',"width:"+percentage+"%");
-
-            }
-            
-          
-            
-            function checkValidUserAndRedirect()
-            {
-                
-                var userName = document.loginForm.userId.value;
-                var userPassword = document.loginForm.userPassword.value;
-                
-                console.log("username =="+userName);
-                console.log("userPassword=="+userPassword);
-                
-                
-                var userInfo = { "username": userName, "password": userPassword };
-                $.ajax({
-                    type: "POST",
-                    url: "http://lowe.jschua.com/DinoPos/api/users",
-                    async: true,
-                    data: JSON.stringify(userInfo),
-                    contentType: "application/json; charset=utf-8",
-                    statusCode: {
-                        202: function () {
-                        },
-                        406: function () {
-                            $('#errorMessage').text("Invalid login or password. Please try again.");
-                            clearTimeout(tid);
-                            $('#progressBar').attr('style',"width:100%");
-                        }
-                    },
-                    success: function (data) {
-                        
-                        var x = document.getElementById("listForBranchDetails").selectedIndex;
-                        var branchId = document.getElementsByTagName("option")[x].id;
-                        var taxPercentage = document.getElementsByTagName("option")[x].className;
-                        
-                        var daysForCookie = 0;
-                        
-                        if($('input[id=rememberCheckBox]').is(':checked'))
-                        {
-                            daysForCookie = 3;
-                            createCookie('rememberLogin','true',3);
-                        }
-                        
-                        createCookie('employeeId',data,daysForCookie);
-                        createCookie('branchId',branchId,daysForCookie);
-                        createCookie('taxPercentage',taxPercentage,daysForCookie);
-                        
-                        window.location = "index.html";
-                    },
-                    dataType: "text",
-                    error: function (jqXHR, textStatus, errorThrown) {
-                      }
-                });
-               
-            }
-            
-            function createCookie(name,value,days) {
-                if (days) {
-                    var date = new Date();
-                    date.setTime(date.getTime()+(days*24*60*60*1000));
-                    var expires = "; expires="+date.toGMTString();
-                }
-                else var expires = "";
-                document.cookie = name+"="+value+expires+"; path=/";
-            }
-            
-            function readCookie(name) {
-                var nameEQ = name + "=";
-                var ca = document.cookie.split(';');
-                for(var i=0;i < ca.length;i++) {
-                    var c = ca[i];
-                    while (c.charAt(0)==' ') c = c.substring(1,c.length);
-                    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
-                }
-                return null;
-            }
-
-            
-        </script>
-
+        <script src="js/login.js"></script>
     </body>
 
-</html>
+</html>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.