// JavaScript Document
// Based script for using dojo in this site
// =========================================

    dojo.require("dojo.parser");
    dojo.require("dojo.regexp");
    dojo.require("dijit.form.Form");
    dojo.require("dijit.form.ValidationTextBox");
    dojo.require("dijit.form.TextBox");
	dojo.require("dijit.Dialog");
	
  	var historyArray = new Array();

    dojo.addOnLoad(function() {
        dojo.connect(dijit.byId("searchInput"), "onFocus", 
                function() {
                    if(this.value == "Enter keyword")
                        this.attr("value", ""); }
            );
    });

    function validateEmail(){
		var email = null;
		var path = "";
		
		if(dojo.byId("indexEmailText") != null){
        	email = dojo.byId("indexEmailText").value;//document.getElementById("emailText").value;
		}
		if(dojo.byId("emailText") != null){
        	email = dojo.byId("emailText").value;//document.getElementById("emailText").value;
			var path = "../";
		}
		
        //email = email.trim();
		
        if(email != "Enter email"){
            if(echeck(email)){
                subscribe(email, path);
                //document.getElementById("emailText").value = "";
            }else{
                dojo.byId("result").innerHTML = "<div class=normal_text><font color=red>Invalid email address</font></div>";
            }
        }
    }

    function subscribe(email, path) {
      //alert("sending : " + document.getElementById("emailText").value);
      dojo.xhrGet( {
        // The following URL must match that used to test the server.
        url: path + "php_func/subscribeNewsLetter.php?email=" + email,
        handleAs: "text",
        timeout: 10000, // Time in milliseconds
        preventCache: true,
        
        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) {
            dojo.byId("result").innerHTML = "Processing plz wait";
            dojo.byId("result").style.display = "block";
			dojo.byId("subscribeNewsLetterDiv").innerHTML = response;
            dojo.byId("result").style.display = "none";
            return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }
        });
      }

      function updateResult(response){
        //alert("U date result");
        if(response == "ERR_DUPLICATE"){
            //dojo.byId("subscribeNewsLetter").innerHTML = response;
            dojo.byId("result").innerHTML = "This email was already subscribed";
        }else{
            dojo.byId("subscribeNewsLetterDiv").innerHTML = response;
            dojo.byId("result").style.display = "none";
            dojo.byId("result").innerHTML = "";
        }
      }

      function listByGrape(type,page) {
          var pageStr = "";
          if(page != null){
            pageStr = "&page=" + page;
          }
          var url = "../shopping/listProduct.php";
          url = url + "?query=true&get_sel_wineGrape=" + type + pageStr;

          dojo.xhrGet( {
            url: url,
            preventCache: true,
            //timeout: 5000, // Time in milliseconds

            // The LOAD function will be called on a successful response.
            load: function(response/*, ioArgs*/) {
              //dojo.byId("signupForm").innerHTML = "";
			  dojo.byId("productInfoDiv").innerHTML = " ";
			  dojo.byId("productInfoDiv").style.display = "none";
			  dojo.byId("productDiv").innerHTML = response;
			  dojo.byId("productDiv").style.display = "block";
              return response;
            },

            // The ERROR function will be called in an error case.
            error: function(response, ioArgs) {
              console.error("HTTP status code: ", ioArgs.xhr.status);
              return response;
              }
            });
      }

      function listByRegion(reg,page) {
          var pageStr = "";
          if(page != null){
            pageStr = "&page=" + page;
          }
          var url = "../shopping/listProduct.php";
          url = url + "?query=true&get_sel_wineRegion=" + reg + pageStr;

          dojo.xhrGet( {
            url: url,
            preventCache: true,
            //timeout: 5000, // Time in milliseconds

            // The LOAD function will be called on a successful response.
            load: function(response/*, ioArgs*/) {
              //dojo.byId("signupForm").innerHTML = "";
			  dojo.byId("productInfoDiv").innerHTML = " ";
			  dojo.byId("productInfoDiv").style.display = "none";
			  dojo.byId("productDiv").innerHTML = response;
			  dojo.byId("productDiv").style.display = "block";
              return response;
            },

            // The ERROR function will be called in an error case.
            error: function(response, ioArgs) {
              console.error("HTTP status code: ", ioArgs.xhr.status);
              return response;
              }
            });
      }
	  
      function searchTextResult(j) {
      var url = "../shopping/listProduct.php";

      if(j > 1)
        url = url + "?page=" + j;
    
      dojo.xhrPost( {
        // The following URL must match that used to test the server.
        // "php_func/signupNewUser.php",
        url: url,
        form: 'searchTextForm',
        preventCache: true,
        //timeout: 5000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response/*, ioArgs*/) {
		  dojo.byId("productInfoDiv").innerHTML = " ";
		  dojo.byId("productInfoDiv").style.display = "none";
		  dojo.byId("productDiv").innerHTML = response;
		  dojo.byId("productDiv").style.display = "block";
		  
          return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }
        });
      }

      function searchResult(j) {
      var url = "../shopping/listProduct.php";

      if(j != null)
        url = url + "?page=" + j;
		
      dojo.xhrPost( {
        // The following URL must match that used to test the server.
        // "php_func/signupNewUser.php",
        url: url,
        form: 'searchForm',
        preventCache: true,
        timeout: 5000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response/*, ioArgs*/) {
		  dojo.byId("productInfoDiv").innerHTML = " ";
		  dojo.byId("productInfoDiv").style.display = "none";
		  dojo.byId("productDiv").innerHTML = response;
		  dojo.byId("productDiv").style.display = "block";

          return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }
        });
      }
	  
	  function orderBy(j,order) {
      var url = "../shopping/listProduct.php";
	  
      if(j > 1)
        url = url + "?page=" + j + "&order=" + order;
	  else
	    url = url + "?order=" + order;

      dojo.xhrPost( {
        url: url,
        form: 'searchForm',
        preventCache: true,
        // The LOAD function will be called on a successful response.
        load: function(response/*, ioArgs*/) {
		  dojo.byId("productInfoDiv").innerHTML = " ";
		  dojo.byId("productInfoDiv").style.display = "none";
		  dojo.byId("productDiv").innerHTML = response;
		  dojo.byId("productDiv").style.display = "block";

          //getFooter("productList");
          return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }
        });
      }

      function addReview() {
      dojo.xhrPost( {
        // The following URL must match that used to test the server.
        // "php_func/signupNewUser.php",
        url: "../php_func/addReview.php",
        form: 'reviewForm',
        preventCache: true,
        //timeout: 5000, // Time in milliseconds

        // The LOAD function will be called on a successful response.
        load: function(response/*, ioArgs*/) {
          dojo.byId("reviewResult").innerHTML = response;
          return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }
        });
      }

      function getProductDetail(id){
        var idStr = "";
		
        if(id != null)
            idStr = idStr + id;
        dojo.xhrGet( {
        url: "../shopping/product_info.php?barcode=" + idStr,
        handleAs: "text",
        timeout: 5000, // Time in milliseconds
        preventCache: true,

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) {
			dojo.byId("productDiv").style.display = "none";
            dojo.byId("productInfoDiv").innerHTML = response;
			dojo.byId("productInfoDiv").style.display = "block";
			//putStack(response);
            //getFooter("productList");
            return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }
        });
      }
	  
	  // Add to the latest node 
	  function addToHistoryArray(page){
	  	if(page != historyArray[historyArray.length]){
			historyArray[historyArray.length] = page;
			alert(historyArray);
		}else{
			alert("DUPLICATE PAGE, Dont add");
		}
	  }
	  
	  // Remove the top of list
	  function removeFromHistoryArray(){
	  	//historyArray[historyArray.length] = null;
		alert(historyArrray);
	  }
	  
      function backFromBufferredPage(){
	  	popStack();
	  }
	  
	  function backFromInfoPage(){
		dojo.byId("productInfoDiv").style.display = "none";
    	dojo.byId("productInfoDiv").innerHTML = " ";
		dojo.byId("productDiv").style.display = "block";
	  }

      function _backFromBufferredPage(){
	  	if(dojo.byId("displayPanel_2").style.display == "block"){
			dojo.byId("displayPanel_2").style.display = "none";
    	    dojo.byId("displayPanel_1").style.display = "block";
		}else{
	        dojo.byId("displayPanel_2").style.display = "block";
    	    dojo.byId("displayPanel_1").style.display = "none";
		}
        
        getFooter("productList");
      }

      function getFooter(page){
        dojo.xhrGet( {
        url: "php_func/getFooter.php?page=" + page,
        handleAs: "text",
        timeout: 5000, // Time in milliseconds
        preventCache: true,

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) {
            dojo.byId("footBox").innerHTML = response;
            return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }
        });
      }

      function addToCart(barcode, quantity, mode){
          var statusStr = "Adding to basket";
		  var isDetailedPage = "";
		  if(barcode!= null && barcode[0] == 'd'){
		  	barcode = barcode.substring(1,barcode.length);
			isDetailedPage = "d";
		  }
          switch(mode){
              case 'a':   dojo.byId(isDetailedPage + barcode).innerHTML 
			  					= "<img src=../images/ajax-loader.gif>&nbsp;<font class=text_account color=RED>Adding to basket</font>";
			  			  statusStr = "<b class=text_account><font color=white>Adding to basket</font></b>";
                          mode = "add";
                          break;
              case 'u':   statusStr = "<b class=text_account>Updating basket</b>";
                          mode = "upd";
                          break;
              case 'd':   dojo.byId(isDetailedPage + barcode).innerHTML = "<img src=../images/ajax-loader.gif>&nbsp;<font class=text_account color=RED>Removing from basket</font>";
			  			  statusStr = "<b class=text_account>Removing from basket</b>";
                          mode = "del";
                          break;
          }

          //alert("after sw");

          if(quantity == null){
              if(barcode == null){
                  barcode = "-";
                  quantity = 0;
              }else{
                  quantity = dojo.byId("quantity").value;
              }
          }

        dojo.xhrGet( {
        url: "../php_func/shoppingCart.php?func=" + mode + "&bc=" + barcode + "&qt=" + quantity,
        handleAs: "text",
        timeout: 3000, // Time in milliseconds
        preventCache: true,

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) {
			//alert(statusStr + dojo.byId("basketDiv").innerHTML);
            dojo.byId("basketDiv").innerHTML = statusStr;
			if(isDetailedPage == "d")
				dojo.byId("dbasketDiv").innerHTML = statusStr;

			//updateBasket(response);
			//alert(isDetailedPage + barcode);
			updateEachProduct(isDetailedPage + barcode);
            setTimeout(function(){updateBasket(response); response = null}, 500);
			
            return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }
        });
      }

      function updateBasket(response){
          dojo.byId("basketDiv").innerHTML = response;
		  dojo.byId("dbasketDiv").innerHTML = response;
      }
	  
	  function updateEachProduct(barcode){
		  //alert("update each prd");
		  var isDetailedPage = "";
		  var noButton = "false";
		  if(barcode[0] == 'd'){
		  	barcode = barcode.substring(1,barcode.length);
			isDetailedPage = "d";

			noButton = "true";
		  }
		dojo.xhrGet( {
        url: "../php_func/shoppingCart.php?func=viewEachPrd&bc=" + barcode + "&noButton=" + noButton,
        handleAs: "text",
        timeout: 3000, // Time in milliseconds
        preventCache: true,

        // The LOAD function will be called on a successful response.
        load: function(response, ioArgs) {
			dojo.byId(isDetailedPage + barcode).innerHTML = response;
//            setTimeout(function(){updateBasket(response); response = null}, 500);
//			updateEachProduct();
            return response;
        },

        // The ERROR function will be called in an error case.
        error: function(response, ioArgs) {
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }
        });
	  }

    function execPage(page, isSamePage) {
		
        dojo.xhrGet( {
            // The following URL must match that used to test the server.
            url: "php_func/" + page + ".php",
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            preventCache: true,
            
            // The LOAD function will be called on a successful response.
            load: function(response, ioArgs) {
				putStack(response);
                return response;
            },

            // The ERROR function will be called in an error case.
            error: function(response, ioArgs) {
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
        });
    }

    function _execPage(page, isSamePage) {
		
        dojo.xhrGet( {
            // The following URL must match that used to test the server.
            url: "php_func/" + page + ".php",
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            preventCache: true,
            
            // The LOAD function will be called on a successful response.
            load: function(response, ioArgs) {
                //alert("done");
				if(isSamePage == false){
                	dojo.byId("displayPanel_1").style.display = "none";
                	dojo.byId("displayPanel_1").innerHTML = dojo.byId("displayPanel_2").innerHTML;
				}
                dojo.byId("displayPanel_2").innerHTML = response;
				dojo.byId("displayPanel_2").style.display = "block";
                
                //setTimeout(function(){updateResult(response); response = null}, 500);
                return response;
            },

            // The ERROR function will be called in an error case.
            error: function(response, ioArgs) {
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
        });
    }
	
	function backFromExecPage(page){
		removeFromHistoryArray(page);
	}

    function updateResult(response){
        dojo.byId("displayPanel_1").innerHTML = response;
    }

    function removeItemFromBasket(){
        //alert("remove item");
	  dojo.byId("totalQuan").innerHTML = "<img src=../images/ajax-loader_7E7E7E.gif>";
	  dojo.byId("totalPrice").innerHTML = "<img src=../images/ajax-loader_7E7E7E.gif>";
        dojo.xhrPost( {
          // The following URL must match that used to test the server.
          url: "../php_func/removeItemFromBasket.php",
          handleAs: "text",
          form: "removeItemForm",
          timeout: 5000, // Time in milliseconds
          preventCache: true,

          // The LOAD function will be called on a successful response.
          load: function(response, ioArgs) {
              //addToCart(null,null,'u');
              //execPage("basket", true);
			  //updateTotal(response);
			  reloadBasketContent();
              return response;
          },

          // The ERROR function will be called in an error case.
          error: function(response, ioArgs) {
              console.error("HTTP status code: ", ioArgs.xhr.status);
              return response;
          }
        });
      }

      function updateBasketItem(){
      //alert("updateBasketItem");
	  dojo.byId("totalQuan").innerHTML = "<img src=../images/ajax-loader.gif>";
	  dojo.byId("totalPrice").innerHTML = "<img src=../images/ajax-loader.gif>";
      dojo.xhrPost( {
          // The following URL must match that used to test the server.
          url: "../php_func/updateBasketItem.php",
          handleAs: "text",
          form: "removeItemForm",
          timeout: 5000, // Time in milliseconds
          preventCache: true,

          // The LOAD function will be called on a successful response.
          load: function(response, ioArgs) {
              addToCart(null,null,'u');
              //execPage("basket", true);
			  
			  //==========================
			  // totalQuantity:totalPrice
			  updateTotal(response);

              return response;
          },

          // The ERROR function will be called in an error case.
          error: function(response, ioArgs) {
              console.error("HTTP status code: ", ioArgs.xhr.status);
              return response;
          }
        });
      }
	  
	  function updateTotal(response){

		  // total quan : total price
		  var i = response.indexOf(':');
		  //alert("i=" + i + " " + response);
		  var totalQuan = response.substring(0,i);
		  var totalPrice = response.substring(i+1,response.length);


		  dojo.byId("totalQuan").innerHTML = totalQuan;
		  dojo.byId("totalPrice").innerHTML = totalPrice;

	  }
	  
	  // To update total proce for each product
	  function updateTotalPrice(barcode, quantity, price){
 	      //alert("total_"+barcode+" Price="+ price + " ,Quantity=" + quantity);
		  dojo.byId("total_"+barcode).innerHTML = addCommas(price*quantity);
	  }
	  
	  function addCommas(nStr)
 	  {
		  nStr += '';
		  x = nStr.split('.');
  		  x1 = x[0];
		  x2 = x.length > 1 ? '.' + x[1] : '';
		  var rgx = /(\d+)(\d{3})/;
		  while (rgx.test(x1)) {
		    x1 = x1.replace(rgx, '$1' + ',' + '$2');
		  }
		  return x1 + x2;
	  }

	  
	  function reloadBasketContent(){
        dojo.xhrGet( {
            // The following URL must match that used to test the server.
            url: "../shopping/basketContent.php",
            handleAs: "text",
            timeout: 5000, // Time in milliseconds
            preventCache: true,
            
            // The LOAD function will be called on a successful response.
            load: function(response, ioArgs) {
                dojo.byId("basketContentDiv").innerHTML = response;
                return response;
            },

            // The ERROR function will be called in an error case.
            error: function(response, ioArgs) {
                console.error("HTTP status code: ", ioArgs.xhr.status);
                return response;
            }
        });
	  }

      function submitFormPost(formName, nextPage){
          dojo.xhrPost( {
          // The following URL must match that used to test the server.
          url: "../php_func/" + formName + ".php",
          handleAs: "text",
          form: formName,
          timeout: 5000, // Time in milliseconds
          preventCache: true,

          // The LOAD function will be called on a successful response.
          load: function(response, ioArgs) {
              //execPage(nextPage,false);
			  alert("../shopping/"+nextPage+".php");
			  window.location("../shopping/"+nextPage+".php");
              return response;
          },

          // The ERROR function will be called in an error case.
          error: function(response, ioArgs) {
              console.error("HTTP status code: ", ioArgs.xhr.status);
              return response;
          }
        });
      }
	  
	  function changeButtonLocation(){
			dojo.byId("buttonLocation1").style.display = "none";  
			dojo.byId("buttonLocation2").style.display = "block";  
	  }
	  
	  function loginAlert(){
		dijit.byId('alertDialog').show();
	  }
	  
	  // ==================
	  function putStack(response){
		//alert("putStack called");
	  	if(dojo.byId("displayPanel_1").innerHTML == "" || dojo.byId("displayPanel_1").innerHTML.length <= 10){
			//alert("Pane 1 == null");
			dojo.byId("displayPanel_1").innerHTML = response;
			dojo.byId("displayPanel_1").style.display = "block";
			dojo.byId("displayPanel_2").innerHTML = "";
			dojo.byId("displayPanel_3").innerHTML = "";
		}else if(dojo.byId("displayPanel_2").innerHTML == "" || dojo.byId("displayPanel_2").innerHTML.length <= 10){
			//alert("Pane 2 == null");
			dojo.byId("displayPanel_2").innerHTML = response;
			dojo.byId("displayPanel_2").style.display = "block";
			dojo.byId("displayPanel_1").style.display = "none";
			dojo.byId("displayPanel_3").innerHTML = "";
		}else if(dojo.byId("displayPanel_3").innerHTML == "" || dojo.byId("displayPanel_3").innerHTML.length <= 10){
			//alert("Pane 3 == null");
			dojo.byId("displayPanel_3").innerHTML = response;
			dojo.byId("displayPanel_3").style.display = "block";
			dojo.byId("displayPanel_1").style.display = "none";
			dojo.byId("displayPanel_2").style.display = "none";
		}else{
			//alert("Falling into the last condition");
			//alert(response);
			dojo.byId("displayPanel_3").innerHTML = response;
			dojo.byId("displayPanel_3").style.display = "block";
			dojo.byId("displayPanel_1").style.display = "none";
			dojo.byId("displayPanel_2").style.display = "none";
		}
	  }
	  
	  function popStack(){
	  	if(dojo.byId("displayPanel_3").innerHTML != ""){
			//alert("Pane 3 != null");
			dojo.byId("displayPanel_3").innerHTML = "";
			dojo.byId("displayPanel_3").style.display = "none";
			dojo.byId("displayPanel_2").style.display = "block";
		}else if(dojo.byId("displayPanel_2").innerHTML != ""){
			//alert("Pane 2 != null");
			dojo.byId("displayPanel_2").innerHTML = "";
			dojo.byId("displayPanel_2").style.display = "none";
			dojo.byId("displayPanel_1").style.display = "block";
		}else if(dojo.byId("displayPanel_1").innerHTML != ""){
			// Do nothing, not allow to empty the stack pane
		}
	  }