/**
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

// request status report layout
var imageURL = 'includes/templates/template_default/images/';
// request status report layout
document.write('<div id=\"loadStatus\" class=\"ajaxReqProgressdiv\" style=\"display:none;\"><img src=\"'+imageURL+'waiting.gif\"> Loading ... </div>');

function requestResource(url){

   requestResource(url, null);
}


//function requestResource(url, node, onCompleteCallback) {
function requestResource(url, parameters) {

	var httpRequest = false;

	//alert(url);

	if (window.XMLHttpRequest) {

	    httpRequest = new XMLHttpRequest();

	    if (httpRequest.overrideMimeType) {
		    httpRequest.overrideMimeType('text/xml');
	    }

	    browser = 'mozilla';

		//alert("firefox");

	} else if (window.ActiveXObject) {

	    browser = 'IE';

	    try {
		    httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
		   try {
		      httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		   } catch (e) {}
	    }

		//alert("ie");
	}

	if (httpRequest == null) {
	    alert('Giving up :( Cannot create an XMLHTTP instance');
	}

    // set handle time out
    //httpRequest.timeout = 20000;

    // defined when handle timeout alert information
	//httpRequest.ontimeout = function(){
    //  alert("Request has timed out. Please try again.")
    //};
    //alert('http://localhost/shop/'+url);

	if (parameters != null)
	{
		 url += parameters;
	}

	//alert( url);

    // parameter 1.var parameter 2.function
    //httpRequest.onreadystatechange = function() { processResponse(httpRequest, onCompleteCallback); };

	httpRequest.onreadystatechange = function() { processResponse(httpRequest); };

	httpRequest.open('GET', url, true);

    httpRequest.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );

	httpRequest.send(null);

}

/**
 * process response data
 */
function processResponse(httpRequest) {

	 //alert(httpRequest);

    // show load status on page
	if (httpRequest.readyState == 1) {

		var loadStatus = document.getElementById("loadStatus");

        var width      = document.body.clientWidth+"px";

		var height     = document.body.clientHeight+"px";

		loadStatus.style.width   = width+"px";

        loadStatus.style.height  = height+"px";

        // let layout middle
        loadStatus.style.left    = (document.body.offsetWidth-width)/2+"px";

        loadStatus.style.top     = (document.body.offsetHeight-height)/2+"px";

		loadStatus.style.display = "block";
	}

    else if (httpRequest.readyState == 4) {
       //alert('4 ok');
        document.getElementById("loadStatus").style.display="none";


	    if (httpRequest.status == 200) {

            /**/
			var xmldoc = null;
		    if (browser == 'IE') {

		        var xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");

		        xmldoc.loadXML(httpRequest.responseText);

		    } else {

		        var xmldoc = httpRequest.responseXML;
		    }
			parseXmlData(xmldoc);
			/**/
            /*
            var _xmlDom = null;

			alert('2222222222'+browser);

            switch(getOs()){

            case "MSIE":
                if (navigator.userAgent.toLowerCase().indexOf("msie 7.0")!=-1) {
                    if (xmlhttp.responseXML != null && xmlhttp.responseXML.xml.length > 0) {
                        _xmlDom = xmlhttp.responseXML;
                        break;
                    }
                }
                if (navigator.userAgent.toLowerCase().indexOf("msie 6.0")!=-1) {
                    var arrXmlDomTypes = ['MSXML2.DOMDocument.6.0',
                                          'MSXML2.DOMDocument.5.0',
                                          'MSXML2.DOMDocument.4.0',
                                          'MSXML2.DOMDocument.3.0',
                                          'MSXML2.DOMDocument',
                                           'Microsoft.XMLDOM'];
                    for(var i = 0; i < arrXmlDomTypes.length; i++) {
                       try{
                          _xmlDom = new ActiveXObject(arrXmlDomTypes[i]);
                          _xmlDom.loadXML(xmlhttp.responseText);
                          break;
                       }
                       catch(ex){}
                    }
                    if (null == _xmlDom){
                         alert("YOUR IE Browser can not support SXML.XMLDOM Object,please reintall microsoft ie explorer.");
                     }
                 }
                 break;
           case "Firefox":
                _xmlDom = xmlhttp.responseXML;
                 break;
           }

		   parseXmlData(_xmlDom);

	       */
	    }
		else if (httpRequest.status == 0)
		{
			alert(dump(httpRequest.responseText));

			//alert(httpRequest.responseXML);
		}
		else {
            alert(httpRequest.statusText);
		    alert('There was a problem with the request.');
	    }
	}
	else {
	   //alert('sssss');
	}
}

/**
 * xml dom parse
 *
 */
function parseXmlData(xmlData) {

	var root = xmlData.getElementsByTagName('root')[0]; // get xml document root node

    var list = root.childNodes;                         // get node list

	var currentPage = 1;

	//alert(list[0].nodeName);

	for (var i = 0; i < list.length; i++) {

	    //alert(list[i].nodeName);
        var nodeName = list[i].nodeName;

		//alert(nodeName);

        switch (nodeName) {

		case "action":
		    break;

		// ----------------------------------------------------------------- //
		// handle show product list                                          //
		// ----------------------------------------------------------------- //
        case "products": // handle pagination products list
		     processProduct(list[i], currentPage);
			 break;
	    case "pageStatus": // handle pagination pagebar status
             processPageStatus(list[i]);
		     break;
        case "varies": // handle pagin status attribute
             currentPage = processVaries(list[i]);
		     break;

		// ----------------------------------------------------------------- //
		// handle shopping action                                            //
		// ----------------------------------------------------------------- //

		case "mycart":
		    updateShoppingCart(list[i]); //flashing shopping cart
		    break;

	    case "customerID":
		     break;

		// ----------------------------------------------------------------- //
		// handle show product detail                                        //
		// ----------------------------------------------------------------- //
	    case "detail":
		     processProductDetail(list[i]);
		     break;
	    case "sql":
		     debugSearchSql(list[i]);
		     break;
	    default:
		     alert("can not parse data please check load_product.php file.");
			 break;
        }
	}
}

/**
 * handle product data
 */
function processProduct(products, currentPage) {

   //alert('processProduct');

   var list = products.childNodes;

   var productHtml = '';

   for (var i = 0; i < list.length ; i ++) {

       var product = list[i];

	   var items = product.childNodes;

       productHtml += "<div id=\"product_"+ i +"\" class=\"product\">"

	   var productID = "";

	   var productName = "";

	   var productPrice = "";

	   var productImage = "";

	   var productDescription = "";

	   var pattern = "";

	   var color = "";

	   var finish = "";

	   var collection = "";

	   for (var k = 0; k < items.length ; k ++) {

		   var nodeName = items[k].nodeName;

		   var node = items[k].firstChild;

		   switch (nodeName) {

		   case "id":

		   productID = ((node != null) ? node.data : "No Value");
		   break;

		   case "name":
		   productName = ((node != null) ? node.data : "No Value");
		   break;

		   case "price":
		   productPrice = ((node != null) ? node.data : "No Value");
		   break;

		   case "image":
		   productImage = ((node != null) ? node.data : "No Value");
		   break;

		   case "description":
		   productDescription = ((node != null) ? node.data : "No Value");
		   break;

		   case "pattern":
		   pattern = ((node != null) ? node.data : "NoValue");
		   break;

		   case "color":
		   color = ((node != null) ? node.data : "NoValue");
		   break;

		   case "finish":
		   finish = ((node != null) ? node.data : "NoValue");
		   break;

		   case "collection":
		   collection = ((node != null) ? node.data : "NoValue");
		   break;

		   default:
		   break;
		   }

	   }

       productHtml += "<table id=\"product_"+ productID +"\" style=\"width:100%;heigth:100px;\" class=\"item\" >";
	   productHtml += "<tr>";
       productHtml += "<td width=\"15%\" style=\"text-align:center\"><a href=\"javascript:showDetail('index.php?main_page=product_info&cPath=1&products_id="+productID+"&page="+currentPage+"')\"><img src=\"images/"+productImage+"\" alt=\""+productName+"\" title=\""+productName+"\"  class=\"listingProductImage\" /></a></td>";
	   productHtml += "<td width=\"15%\" style=\"text-align:center\"><a href=\"javascript:showDetail('index.php?main_page=product_info&cPath=1&products_id="+productID+"&page="+currentPage+"')\">"+productName+"</a></td>";
       productHtml += "<td width=\"15%\" style=\"text-align:center\">"+pattern+"</td>";
	   productHtml += "<td width=\"15%\" style=\"text-align:center\">"+color+"</td>";
       productHtml += "<td width=\"20%\" style=\"text-align:center\">"+finish+"</td>";
	   productHtml += "<td width=\"20%\" style=\"text-align:center\">"+collection+"</td>";
	   //productHtml += "<td width=\"20%\" style=\"text-align:center\">"+productPrice+"</td>";
	   //productHtml += "<span><a href=\"javascript:showDetail(\'product_"+ productID +"_detail\');\">show Detail</a></span>&nbsp;&nbsp;&nbsp;";
	   //productHtml += "<td><input type=\"text\" id=\""+ productID +"_qty\" size=\"1\" \>&nbsp;&nbsp;<a href=\"javascript:addToCart(\'"+ productID +"\');\">show Detail</a></td>";
	   productHtml += "</tr>";

	   //productHtml +="<div id=\"product_"+ productID +"_detail\" class=\"detail\" style=\"display:none;\">"+productDescription+"</div>";

	   productHtml += "</table>";

	   //alert('productHtml:'+productHtml);

	   //productHtml += "<hr>";
   }

   document.getElementById('listDiv').innerHTML = productHtml;

}

/**
 */
function processPageStatus(pageStatus) {

   document.getElementById('pageStatus').innerHTML = pageStatus.firstChild.data;

}


/**
 * handle pagination and data list attribute
 */
function processVaries(varies) {

   var list = varies.childNodes;

   var pageNavHtml = '';

   var currentPage = 1;

   var categoryID = 0;

   for (var i = 0; i < list.length ; i ++) {

       var item = list[i];

	   if (item.nodeName == "pageIndex") {

		   //alert(item.firstChild.data);

		   pageNavHtml += buildNumericPageNavigation(item.firstChild.data, categoryID, currentPage);
	   }

	   else if (item.nodeName == "hasPrev") {
		   var hasPrevPage = item.firstChild.data;
		   //alert(hasPrevPage);
		   if (hasPrevPage == "true") {
			   pageNavHtml += "<a href=\"javascript:goPage("+categoryID+","+ (parseInt(currentPage) - 1) +");\">Previous</a>&nbsp;&nbsp;";
		   }
	   }

	   else if (item.nodeName == "hasNext") {

		   var hasNextPage = item.firstChild.data;

		   if (hasNextPage == "true") {
			   pageNavHtml += "<a href=\"javascript:goPage("+categoryID+","+ (parseInt(currentPage) + 1) +");\">Next</a>";
		   }

	   }
	   else if (item.nodeName == "categoryID") {
		   categoryID = item.firstChild.data;
	   }

	   else if (item.nodeName == "currentPage") {
		   currentPage = item.firstChild.data;
	   }

   }


   document.getElementById('pageNav').innerHTML = pageNavHtml;

   return currentPage;

}

/**
 * show product detail
 */
function processProductDetail(detail) {


}

/**
 * create numeric navigate
 * @param pageIndex int
 * @param typeID int product type id
 * @param currentPage int request page number
 */
function buildNumericPageNavigation(pageIndex, typeID, currentPage) {

	var navStr = "";

	for (var i = 1; i <= pageIndex; i ++) {

		var link = ((i == currentPage) ? (i + "&nbsp;&nbsp;") :"<a href = \"javascript:goPage(" + typeID + "," + i + ");\">" + i + "</a>&nbsp;&nbsp;");

		navStr += link;

	}

	return navStr;
}

/**
 * list navigative operation
 *
 */
function goPage(categoryID, targetPage) {

	var url = "load_product.php?categoryID="+categoryID+"&page="+targetPage;

	requestResource(url);
}

/**
 * show product detail info
 */
function showDetail(productsDetail) {

	var detailDiv = document.getElementById(productsDetail);

	var display = detailDiv.style.display;

	if (display == "none")
	    detailDiv.style.display = "block";
	else
		detailDiv.style.display = "none";
}

function showProducts(value, key) {

   //alert(value + key);

   if (key == 1 || key == 2)
   {

	var url = "load_product.php?"+key+"="+value;

	requestResource(url, null);

   }

}


// ------------------------------------------------------------------------------------------------------ //
//
// ------------------------------------------------------------------------------------------------------ //
/**
 * onload show default product list
 */
function initProductList() {

	var url = "load_product.php";

	requestResource(url, null);

}

/**
 * onload show default product list
 */
function initProductList(page) {

	var url = "load_product.php";

	if (page != null)
	{
       url += "?page="+page;
	}

	//alert(url);

	requestResource(url);

}



/**
 * onload show default product list
 */
function initShoppingCart() {

	//alert('initShoppingCart');

	var url = "cart.php?op=load_product";

	requestResource(url);
}

/**
 *
 * update shopping cart data information
 */
function updateShoppingCart(mycart) {

    var quantity    = document.getElementById("cartQuantity"); // cart items quantity

	var weight      = document.getElementById("cartWeight");   // shopping weight total

    var total       = document.getElementById("cartTotal");    // shopping price total

	var cartItems   = document.getElementById("cartItems");

    //alert(mycart.nodeName);

    var list = mycart.childNodes;

	//alert(list.length);

    for (var i = 0; i < list.length; i ++) {

	    var element = list[i];

		//alert(element.nodeName);
        /**/
		if (element.nodeName == "products") {

		    var item = element.childNodes;

			var itemsText = "";

		    for (var k = 0; k < item.length ; k ++) {

				var product      = item[k].childNodes;

				//alert(product.nodeName);
                var productID    = product[0].firstChild.data;

				//alert(productID);
				var productName  = product[1].firstChild.data;

				//alert(productName);
				var productPrice = product[2].firstChild.data;

				//alert(productPrice);
				var productQty   = product[3].firstChild.data;

				//alert(productQty);
				var itemText = ("Item Name:"     + productName  + "&nbsp;&nbsp;");

                //itemText    += ("Item Quantity:" + productQty);

                itemText    += ("Item Price:"    + productPrice);

                itemText    += ("sub Price:"     + productPrice + " X " + productQty + " = " + (productPrice*productQty));

				itemsText   += (itemText);

				itemsText   += "&nbsp;<input type=\"text\" id=\"cartProductID_"+productID+"\" size=\"1\" value=\""+productQty+"\"/>";
                itemsText   += "<a href=\"javascript:removeCart(\'"+productID+"\')\">delete</a>"
				itemsText   += "| <a href=\"javascript:updateCart(\'"+productID+"\')\">update</a>"
                itemsText   += "<br>";


		    }

            cartItems.innerHTML = itemsText;

		}
		else if (element.nodeName == "quantity") {

		    quantity.innerHTML = element.firstChild.data;

		}
		else if (element.nodeName == "weight") {
            weight.innerHTML = element.firstChild.data;
		}
		else if (element.nodeName == "total") {
            total.innerHTML = element.firstChild.data;
		}
		else {

		}/**/
    }


}

/**
 *
 *
 */
function addToCart(productID) {

    var productQty = document.getElementById(productID+"_qty");

	var url;

	if (productQty != null)

         //if (productQty.value == '')  productQty.value = 1;

	     //alert(productQty.value);

	     url = "cart.php?op=add_product&product_id="+productID+"&cart_quantity="+(productQty.value == '' ? 1 : productQty.value);

	else
         url = "cart.php?op=add_product&product_id="+productID+"&cart_quantity=1";

	requestResource(url);


}
/**
 *
 *
 */
function updateCart(productID) {

	var productQty = document.getElementById("cartProductID_"+productID);

	if (productQty.value == '')  productQty.value = 1;

	var url = "cart.php?op=update_product&product_id="+productID+"&cart_quantity="+productQty.value;

	requestResource(url);
}
/**
 *
 *
 */
function removeCart(productID) {

	var url = "cart.php?op=remove_product&product_id="+productID;

	//alert(productID);

	requestResource(url);
}
/**
 *
 *
 */
function clearCart() {

	var url = "cart.php?op=destroy_cart";

	requestResource(url);
}
/**
 *
 *
 */
function goCheckout() {

}


function search(myform) {

  var getstr = "?";


  var length = myform.elements.length;

  var checkValue = '' ;

  //alert(length);

  for (i=0; i<length; i++) {

	  //alert(myform.elements[i].type);
      // select
      if (myform.elements[i].type == "select-one") {

          var sel = myform.elements[i];

		  var key = sel.name;

		  var value = sel.options[sel.selectedIndex].value;

		  //alert(value);

		  if (value == '$0')
			  continue;

          getstr += key + "=" + value + "&";

		  //alert(getstr);
      }
	  // checkbox
	  else if (myform.elements[i].type == "checkbox") {

		  var checkbox = myform.elements[i];

		  var key = checkbox.name;

		  if (checkbox.checked) {
              if (checkValue == "") {
                 checkValue = key + "=";
              }
			  checkValue += checkbox.value + ",";
          }
		  else continue;
	  }
	  // text
	  else if (myform.elements[i].type == "text") {

		  var key = myform.elements[i].name;

		  if (myform.elements[i].value.length > 0)

	         getstr += key + "=" + myform.elements[i].value + "&";
	  }



   }

   if (checkValue != '') {
       getstr += checkValue.substring(0, checkValue.length - 1) + "&";
   }

   if(getstr == "?") getstr = null;

   else
     getstr = getstr.substring(0, getstr.length - 1);



   //alert(getstr);
   requestResource('load_product.php', getstr);
}

function showDetail(url) {

   location.href=url;
}

function debugSearchSql(node) {

	//alert(node.nodeName);

	var sql = node.firstChild.data;

	//alert(sql);

	document.getElementById('showSqlDiv').innerHTML = base64decode(sql);
}

/**
 * onload show default product list
 */
function showCart() {

	//alert('initShoppingCart');
    var cartDiv = document.getElementById("cart");

	cartDiv.style.display="block";

	var cartLink = document.getElementById("cartLink");

    cartLink.innerHTML = "<a href=\"javascript:hiddenCart()\">hidden Cart</a>";

	var url = "cart.php?op=load_product";

	requestResource(url);
}

function hiddenCart() {

	//alert('initShoppingCart');
    var cartDiv = document.getElementById("cart");

	cartDiv.style.display="none";

	var cartLink = document.getElementById("cartLink");

    cartLink.innerHTML = "<a href=\"javascript:showCart()\">show Cart</a>";

}

var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var base64DecodeChars = new Array(
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

function base64encode(str) {
var out, i, len;
var c1, c2, c3;

len = str.length;
i = 0;
out = "";
while(i < len) {
c1 = str.charCodeAt(i++) & 0xff;
if(i == len)
{
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt((c1 & 0x3) << 4);
out += "==";
break;
}
c2 = str.charCodeAt(i++);
if(i == len)
{
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt((c2 & 0xF) << 2);
out += "=";
break;
}
c3 = str.charCodeAt(i++);
out += base64EncodeChars.charAt(c1 >> 2);
out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
out += base64EncodeChars.charAt(c3 & 0x3F);
}
return out;
}
//
function base64decode(str) {
var c1, c2, c3, c4;
var i, len, out;

len = str.length;
i = 0;
out = "";
while(i < len) {
/* c1 */
do {
c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while(i < len && c1 == -1);
if(c1 == -1)
break;

/* c2 */
do {
c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
} while(i < len && c2 == -1);
if(c2 == -1)
break;

out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

/* c3 */
do {
c3 = str.charCodeAt(i++) & 0xff;
if(c3 == 61)
return out;
c3 = base64DecodeChars[c3];
} while(i < len && c3 == -1);
if(c3 == -1)
break;

out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

/* c4 */
do {
c4 = str.charCodeAt(i++) & 0xff;
if(c4 == 61)
return out;
c4 = base64DecodeChars[c4];
} while(i < len && c4 == -1);
if(c4 == -1)
break;
out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
}
return out;
}

