/************************************************************************************************************
(C) www.dhtmlgoodies.com, March 2006

This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	

Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.

Version:
	1.0	Released	March. 3rd 2006

Thank you!

www.dhtmlgoodies.com
Alf Magne Kalleland

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

var flyingSpeed = 25;
var url = 'cart.php?';
var txt_totalPrice = (langName=='vi') ? 'Tổng cộng : ' : 'Total : ';
var txt_Product = (langName=='vi') ? 'sản phẩm' : 'product(s)';

var shopping_cart_div = false;
var flyingDiv = false;
var currentProductDiv = false;

var shopping_cart_x = false;
var shopping_cart_y = false;

var slide_xFactor = false;
var slide_yFactor = false;

var diffX = false;
var diffY = false;

var currentXPos = false;
var currentYPos = false;

var ajaxObjects = new Array();

function commify(Num){ 
	var newNum = "";
    var newNum2 = "";
    var count = 0;
	//this loop actually adds the commas   
    for (var k = Num.length-1; k >= 0; k--){
      var oneChar = Num.charAt(k);
      if (count == 3){
        newNum += ",";
        newNum += oneChar;
        count = 1;
        continue;
      } else {
        newNum += oneChar;
        count ++;
      }
   }
   
  // but now the string is reversed! = re-reverse the string
  for (var k = newNum.length-1; k >= 0; k--){
      var oneChar = newNum.charAt(k);
      newNum2 += oneChar;
  }
  return newNum2;
}

function shoppingCart_getTopPos(inputObj)
{		
  var returnValue = inputObj.offsetTop;
  while((inputObj = inputObj.offsetParent) != null){
  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetTop;
  }
  return returnValue;
}

function shoppingCart_getLeftPos(inputObj)
{
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null){
  	if(inputObj.tagName!='HTML')returnValue += inputObj.offsetLeft;
  }
  return returnValue;
}
	

function addToBasket(productId,quantity)
{
	if(!shopping_cart_div)shopping_cart_div = document.getElementById('shopping_cart');
	if(!flyingDiv){
		flyingDiv = document.createElement('DIV');
		flyingDiv.style.position = 'absolute';
		document.body.appendChild(flyingDiv);
	}
	
	shopping_cart_x = shoppingCart_getLeftPos(shopping_cart_div);
	shopping_cart_y = shoppingCart_getTopPos(shopping_cart_div);

	currentProductDiv = document.getElementById('slidingProduct' + productId);
	
	currentXPos = shoppingCart_getLeftPos(currentProductDiv);
	currentYPos = shoppingCart_getTopPos(currentProductDiv);
	
	diffX = shopping_cart_x - currentXPos;
	diffY = shopping_cart_y - currentYPos;
	

	
	var shoppingContentCopy = currentProductDiv.cloneNode(true);
	shoppingContentCopy.id='';
	flyingDiv.innerHTML = '';
	flyingDiv.style.left = currentXPos + 'px';
	flyingDiv.style.top = currentYPos + 'px';
	flyingDiv.appendChild(shoppingContentCopy);
	flyingDiv.style.display='block';
	flyingDiv.style.width = currentProductDiv.offsetWidth + 'px';
	flyToBasket(productId,quantity);
	
}


function flyToBasket(productId,quantity)
{
	var maxDiff = Math.max(Math.abs(diffX),Math.abs(diffY));
	var moveX = (diffX / maxDiff) * flyingSpeed;;
	var moveY = (diffY / maxDiff) * flyingSpeed;	
	
	currentXPos = currentXPos + moveX;
	currentYPos = currentYPos + moveY;
	
	flyingDiv.style.left = Math.round(currentXPos) + 'px';
	flyingDiv.style.top = Math.round(currentYPos) + 'px';	
	
	
	if(moveX>0 && currentXPos > shopping_cart_x){
		flyingDiv.style.display='none';		
	}
	if(moveX<0 && currentXPos < shopping_cart_x){
		flyingDiv.style.display='none';		
	}
		
	if(flyingDiv.style.display=='block'){
		setTimeout('flyToBasket(' + productId + ',' + quantity + ')',10);
	}else{
		ajaxAddProduct(productId,quantity);
	}
}

function showAjaxBasketContent(ajaxIndex)
{	
	// Getting a reference to the shopping cart items table
	var itemBox = document.getElementById('shopping_cart_items');
	
	var productItems = ajaxObjects[ajaxIndex].response.split('|||');	// Breaking response from Ajax into tokens
	var dbquan = parseInt(productItems[1]);
	
	productItems[3] = commify(productItems[3]);
	
	if(document.getElementById('shopping_cart_items_product' + productItems[0])){	// A product with this id is allready in the basket - just add number items
		var row = document.getElementById('shopping_cart_items_product' + productItems[0]);
		var items = row.cells[0].innerHTML /1;		
		//items = items + dbquan;
		items = dbquan;
		row.cells[0].innerHTML = items;
	}else{	// Product isn't allready in the basket - add a new row
		var tr = itemBox.insertRow(-1);
		tr.id = 'shopping_cart_items_product' + productItems[0]
		
		var td = tr.insertCell(-1);
		td.innerHTML = dbquan; 	// Number of items
		
		var td = tr.insertCell(-1);
		td.innerHTML = productItems[2]; 	// Description
		
		var td = tr.insertCell(-1);
		td.style.textAlign = 'right';
		td.innerHTML = productItems[3] + ' ' + productItems[4]; 	// Price	
		
		var td = tr.insertCell(-1);
		td.style.textAlign = 'center';
		var a = document.createElement('A');
		td.appendChild(a);
		a.href = 'javascript:void(0)';
		a.onclick = function(){ removeProductFromBasket(productItems[0]); };
		var img = document.createElement('IMG');
		img.src = 'images/del.gif';
		a.appendChild(img);
		//td.innerHTML = '<a href="#" onclick="removeProductFromBasket("' + productItems[0] + '");return false;"><img src="images/remove.gif"></a>';	
	} 
	

	updateTotalPrice();
	
	ajaxObjects[ajaxIndex] = false;
	
	//document.getElementById('cartActions').innerHTML = '<a href="javascript:void(0)" onclick="ajaxClearBasket()">Clear</a>';
	
}

function updateTotalPrice()
{
	var itemBox = document.getElementById('shopping_cart_items');
	// Calculating total price and showing it below the table with basket items
	var totalPrice = 0;	
	var totalPrice1 = 0;
	var p = '';	
	if(document.getElementById('shopping_cart_totalprice')){
		
		for(var no=1;no<itemBox.rows.length;no++){			
			p = itemBox.rows[no].cells[2].innerHTML.split(' ');			
			//pv[no] = p[no][0].replace(/[^0-9]/g,'');
			//pu[no] = p[no][1].replace(/[^0-9]/g,'');			
			totalPrice = totalPrice + (itemBox.rows[no].cells[0].innerHTML.replace(/[^0-9]/g,'') * p[0].replace(/[^0-9]/g,''));	
			totalPrice1 = totalPrice1 + (itemBox.rows[no].cells[0].innerHTML.replace(/[^0-9]/g,'') * p[1]);
		}		
		
		document.getElementById('shopping_cart_totalprice').innerHTML = txt_totalPrice + (itemBox.rows.length - 1) + ' ' + txt_Product + '<br>' + '&Sigma; ' + commify(totalPrice.toString()) + ' VND / ' + totalPrice1.toFixed(2) + ' USD';	//.toFixed(2)	
	}	
	
	// If there are no items in cart then remove the Clear and Checkout button
	if(itemBox.rows.length<2){
		document.getElementById('cartActions').style.display = 'none';
	}else{
		document.getElementById('cartActions').style.display = '';
	}
	
}

function removeProductFromBasket(productId)
{
	var productRow = document.getElementById('shopping_cart_items_product' + productId);
	
	var numberOfItemCell = productRow.cells[0];
	if(numberOfItemCell.innerHTML == '1'){
		productRow.parentNode.removeChild(productRow);	
	}else{
		numberOfItemCell.innerHTML = numberOfItemCell.innerHTML/1 - 1;
	}
	updateTotalPrice();
	ajaxRemoveProduct(productId);
	
}

function ajaxValidateRemovedProduct(ajaxIndex)
{
	if(ajaxObjects[ajaxIndex].response!='OK')alert('Error while removing product from the database');
	
}

function ajaxRemoveProduct(productId)
{
	var ajaxIndex = ajaxObjects.length;
	ajaxObjects[ajaxIndex] = new sack();
	ajaxObjects[ajaxIndex].requestFile = url + '&productIdToRemove=' + productId;	// Saving product in this file
	ajaxObjects[ajaxIndex].onCompletion = function(){ ajaxValidateRemovedProduct(ajaxIndex); };	// Specify function that will be executed after file has been found
	ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function		
}

function ajaxAddProduct(productId,quantity)
{
	var ajaxIndex = ajaxObjects.length;
	ajaxObjects[ajaxIndex] = new sack();
	ajaxObjects[ajaxIndex].requestFile = url + '&productId=' + productId + '&quantity=' + quantity;	// Saving product in this file
	ajaxObjects[ajaxIndex].onCompletion = function(){ showAjaxBasketContent(ajaxIndex); };	// Specify function that will be executed after file has been found
	ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function		
}
// This is Extra code
function ajaxClearBasket()
{
	var ajaxIndex = ajaxObjects.length;
	ajaxObjects[ajaxIndex] = new sack();
	ajaxObjects[ajaxIndex].requestFile = url + '&clear=1';	// Saving product in this file
	ajaxObjects[ajaxIndex].onCompletion = function(){ ClearBasket(); };	// Specify function that will be executed after file has been found
	ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function		
}
function ClearBasket()
{
	var itemBox = document.getElementById('shopping_cart_items');	
	for(i=itemBox.rows.length-1; i > 0; i--){
       itemBox.deleteRow(i); 
	}
	updateTotalPrice();
	//document.getElementById('cartActions').style.display = 'none';
}