
var currentItemId = 0;
var hideLoadingLogo = 0;
var ajaxURL = 'addProductAjax.php';
var ajaxRemoveURL = 'delProductAjax.php';
/* Drag And Drop Cart */
var currentXMLObj;

 var currentProductActive = false;
 var currentProduct = 0;
 var currentDelId = 0;
 var isActive = false;
 $(document).ready(function()        
  {  
		$(".draggable").draggable({
			revert : true,
			revertDuration : 500,
			distance : 5,
			helper : 'clone',
			opacity: 0.5,
			zIndex: 9999 
		});
		$(".droppable").droppable({
			hoverClass : 'droppableHover',
			tolerance : 'touch',
			drop: function(event, ui) {
				showLoading();
				currentProduct = ui.draggable.attr('id');
				addProductToCart(ui.draggable.attr('id'),1);
			}

		});
	 	$("span#fbox_img a").fancybox({
				'zoomSpeedIn':	0, 
				'zoomSpeedOut':	0, 
				'overlayShow':	true
			});
		addJscrollPane();

  });


function addJscrollPane() {
	$('.scroll-pane').jScrollPane({showArrows:true, scrollbarWidth: 17, reinitialiseOnImageLoad: true, maintainPosition : false});
}


function cancelAddProduct () {
	currentProductActive = false;
	hideLoading();
}
function addProductToCart(prodId,qty) {
	if (currentProductActive == false) {
		currentProductActive = true;
		setTimeout('allowDrop()',1000);
		$.get(ajaxURL + "?productId="+prodId+"&qty="+qty, function(data) {
			doAddProduct(data);
		},'xml');
	}
}
function addVariation(variationId,productId,qty,hideLoading) {
	hideLoadingLogo = hideLoading;
	if (qty <= 0) qty = 1;
	$.get(ajaxURL + "?productId="+productId+'&variationId='+variationId+'&qty='+qty, function(data) {	
		doAddVariation(data);
	},'xml');
}
function doAddProduct(data) {
	xml = parseXML(data);
	if (xml.getElementsByTagName("error")[0].childNodes[0].nodeValue!=0) {
		$.jGrowl("Error: " + xml.getElementsByTagName("error")[0].childNodes[0].nodeValue);
		hideLoading();
	} else {
		var htmlPopup = xml.getElementsByTagName("popupHTML")[0].childNodes[0].nodeValue;
		if (htmlPopup!=0) {
			$.facebox(xml.getElementsByTagName("popupHTML")[0].childNodes[0].nodeValue);
		} else {
			xml = parseXML(data);
			vid = xml.getElementsByTagName("vid")[0].childNodes[0].nodeValue;
			pid = xml.getElementsByTagName("pid")[0].childNodes[0].nodeValue;
			cid = xmlDoc.getElementsByTagName("cid")[0].childNodes[0].nodeValue;
			name = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
			price = xmlDoc.getElementsByTagName("price")[0].childNodes[0].nodeValue;
			qty = xmlDoc.getElementsByTagName("qty")[0].childNodes[0].nodeValue;
			totalcartqty = xmlDoc.getElementsByTagName("totalcart")[0].childNodes[0].nodeValue;
			totalCartAmt = xmlDoc.getElementsByTagName("cartamt")[0].childNodes[0].nodeValue;
			hideLoadingLogo = 1;
			addProductToDiv(pid,price,name,qty,totalcartqty,cid,totalCartAmt);			
		}
	}
}

function doAddVariation(data) {
	xml = parseXML(data);
	vid = xml.getElementsByTagName("vid")[0].childNodes[0].nodeValue;
	pid = xml.getElementsByTagName("pid")[0].childNodes[0].nodeValue;
	cid = xmlDoc.getElementsByTagName("cid")[0].childNodes[0].nodeValue;
	name = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
	price = xmlDoc.getElementsByTagName("price")[0].childNodes[0].nodeValue;
	qty = xmlDoc.getElementsByTagName("qty")[0].childNodes[0].nodeValue;
	totalcartqty = xmlDoc.getElementsByTagName("totalcart")[0].childNodes[0].nodeValue;
	cartTotalAmt = xmlDoc.getElementsByTagName("cartamt")[0].childNodes[0].nodeValue;
	addProductToDiv(pid,price,name,qty,totalcartqty,cid,cartTotalAmt);
	addJscrollPane();
}

function addProductToDiv(pid,price,name,qty,cart,cid,cartTotalAmt) {
	var tableDiv = document.getElementById('shoppingCart');
	if (document.getElementById('numcart').value==0) {
		document.getElementById('numcart').value=1;
		tableDiv.deleteRow(-1);
	}
	var tableDiv = document.getElementById('shoppingCart');
	var rows = tableDiv.rows.length;
	var row = tableDiv.insertRow(rows);
	row.id = 'row_'+cid;
	var cellImg = row.insertCell(0);
	var cellText = row.insertCell(1);
	cellText.className = 'basketText';
	cellImg.className = 'basketText';
	var textNode = document.createElement('span');
	var imgNode = document.createElement('span');
	var img = new Image();
	img.src = 'inc/prodOverlay.php?radius=0&inFile=uploads/prod/'+pid+'s.jpg&tX=50&tY=50&square=0&matte=FFFFFF&inOverlay=0&inPosition=top_left';
	cellImg.appendChild(img);
	textNode.innerHTML = qty+' x '+name+' (&pound;'+price+') <a style="cursor:default;" onClick="removeProduct('+cid+');return false;">X</a>';
	cellText.appendChild(textNode);
	document.getElementById('topCartItems').innerHTML = cart+' items';
	document.getElementById('cartTotalAmount').innerHTML = cartTotalAmt;
	if (hideLoadingLogo ==1 ) {
		hideLoading();
		hideLoadingLogo = 0;
		jQuery(document).trigger('close.facebox');
	}
	$.jGrowl("Added Product ("+name+")To Basket");
}

function addVariantFromPopup() {
	total = document.getElementById('popupVariants').value;
	pid = document.getElementById('popupPid').value;
	for (i=1;i<=total;i++) {
		qty = document.getElementById('qtyProd'+i).value;
		vid = document.getElementById('vid'+i).value;
		if (qty > 0) addVariation(vid, pid, qty, 0);
	}
	hideLoading();
	hideLoadingLogo = 0;
	jQuery(document).trigger('close.facebox');
}

function addProductFromDetail() {
	isSingle = document.getElementById('isSingleProd').value;
	productId = document.getElementById('productId').value;
	if (isSingle=='true') {
			qty = document.getElementById('qty0').value;
			showLoading();
			addProductToCart(productId,qty);
			hideLoading();
	} else {
		count = document.getElementById('numProducts').value;
		
		showLoading();
		for (i=0;i<count;i++) {
			variantId = document.getElementById('variantId'+i).value;
			qty = document.getElementById('qty'+i).value;
			if (qty > 0) {
				addVariation(variantId,productId,qty,0);
			}
		}
		hideLoading();
	}
}



function showLoading() {
	document.getElementById('loadingCart').innerHTML = '<img src="images/loading.gif" alt="Loading..." />';
}

function hideLoading() {
	addJscrollPane();
	document.getElementById('loadingCart').innerHTML = '';
	
}

function deleteProduct(id,cid) {
	document.getElementById('loadingCart').innerHTML = '<img src="images/loading.gif" alt="Loading..." />';
	currentDelId = id;
		$.get("delProductAjax.php?cid="+cid, function(data) {
			doDelProduct(data);
		},'xml');
}
function doDelProduct(data) {
	try //Internet Explorer
	  {
	  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  xmlDoc.async="false";
	  xmlDoc.loadXML(data);
	  }
	catch(e)
	  {
	  try //Firefox, Mozilla, Opera, etc.
	  {
	  parser=new DOMParser();
	  xmlDoc=parser.parseFromString(data,"text/xml");
	  }
	  catch(e)
	  {
	  alert(e.message);
	  return;
	  }
	}
	if (xmlDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue!=0) {
		alert('Error: '+xmlDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue);
	} else {
		document.getElementById('checkoutQty').innerHTML = xmlDoc.getElementsByTagName("qty")[0].childNodes[0].nodeValue;
		document.getElementById('checkoutTotal').innerHTML = '&pound;'+xmlDoc.getElementsByTagName("total")[0].childNodes[0].nodeValue;
		document.getElementById('loadingCart').innerHTML = '';
		var location = new String(document.location);
		var pos = location.lastIndexOf('/');
		var pageName = location.substr(pos);
		removeProductFromDiv(currentDelId);
		if (pageName=='/checkout.php#' || pageName=='/cart.php#') window.location.reload();
	}
}

function removeProduct(cid) {
	$.get(ajaxRemoveURL + "?cid="+cid, function(data) {
		doDelProduct(data);
	},'xml');	
}
function doDelProduct(data) {
	xmlDoc = parseXML(data);
	if (xmlDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue!=0) {
		$.jGrowl('Error: '+xmlDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue);
	} else {
		qty = xmlDoc.getElementsByTagName("qty")[0].childNodes[0].nodeValue;
		total = xmlDoc.getElementsByTagName("total")[0].childNodes[0].nodeValue;
		cid = xmlDoc.getElementsByTagName("cid")[0].childNodes[0].nodeValue;
		document.getElementById('topCartItems').innerHTML = qty+' items';
		document.getElementById('cartTotalAmount').innerHTML = total;
		removeProductFromDiv(cid);
		$.jGrowl('Removed Product From Cart');
	}
}
function removeProductFromDiv(id) {
	var tableDiv = document.getElementById('row_'+id).rowIndex;
	var cart = document.getElementById('shoppingCart');
	cart.deleteRow(tableDiv);
	addJscrollPane();
}
function allowDrop() {
	currentProductActive = false;
}

function changeLoc(url) {
	if (currentProductActive==false) window.location = url;
}

function parseXML(txt) {
	try {
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(txt);
		return(xmlDoc); 
	} catch(e) {
		try {//Firefox, Mozilla, Opera, etc.
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(txt,"text/xml");
			return(xmlDoc);
		} catch(e) {alert(e.message)}
	}
	return(null);
}
