/* Purpose: cart javascript-file */

// two hours before cookie expires
var EXPIRE = 2; 



// GLOBAL                         ----------------------------------------------


/**
 * crop number
 * @param {float} floatNum
 * @param {int} decimNum
 * @return int
 */
function cropNumber(floatNum, decimNum) {
	if (isNaN(floatNum))
		return false;
		
	var my = parseFloat(floatNum);
	var by = Math.pow(10, parseInt(decimNum));				
	var val = Math.round(my * by) / by;
	if (val.toFixed)
		val = val.toFixed(decimNum);
	
	return val;				
}





// COOKIES                        ----------------------------------------------


function checkCookie() {
	setCookie('COOKIE_TEST', 'OK');
	if (!(getCookie('COOKIE_TEST')))
		return false;

	eraseCookie('COOKIE_TEST');
	return true;	
}


/**
 * set cookie
 * @param {string} name Name of the cookie
 * @param {string} value Value of the cookie
 * @param {int} expires Hours before cookie expires
 * @param {string} path Path for the cookie
 * @param {string} secure Set "secure" if cookie for HTTPS
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function setCookie(name, value, expires, path, secure){
   var keks = name + "=" + escape(value);
	if (expires) {
		var date = new Date();
		date.setTime(date.getTime() + (expires * 60 * 60 * 1000));
		keks += "; expires=" + date.toGMTString();
	}
   // keks += "; domain=" + location.hostname;
   keks += (path) ? "; path=" + path : "; path=/";
   keks += (secure) ? "; secure" : "";
   document.cookie = keks;
	return false;
}


/**
 * get cookie
 * @param {string} name Name of the cookie
 * @return String
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function getCookie(name) {
   var i = 0;
   var search = name + "=";
	var end;
	var keks;
	var cookieSize = document.cookie.length;
	for (var i = 0; i < cookieSize; i++) {
      if (document.cookie.substring(i, i + search.length) == search) {
         end = document.cookie.indexOf(";", i + search.length);
			end = (end > -1) ? end : cookieSize;
         keks = document.cookie.substring(i + search.length, end);
         return unescape(keks);
      }
   }
   return "";
}


/**
 * erase cookie
 * @param {string} name Name of the cookie
 * @param {string} path Path for the cookie
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function eraseCookie(name, path) {
	var keks = name + "="; 
	keks += "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	// keks += "; domain=" + location.hostname;
	keks += (path) ? "; path=" + path : "; path=/";
	document.cookie = keks;
	return false;
}

/**
 * load collection
 * @param {string} collection Name of the cookie of the collection
 * @return Array
 */
function loadCollection(collection) {
   var str = unescape(getCookie(collection));
   var tmp = new Array();
	var cookieArray = new Array();
   // Daten aus dem Cookie in ein Array umwandeln
   if (str != "") {
      str = str.replace(/,/g, "\",\"");
      str = "\"" + str + "\""
      eval("tmp = [" + str + "]");
   }
   // assoziatives Array erstellen
   for (var i = 0; i < tmp.length; i += 2) {
     cookieArray[tmp[i]] = tmp[i+1];
   }
   // Array zur�ckgeben
   return cookieArray;
}


/**
 * load collection
 * @param {string} name Name of the key in the collection
 * @param {string} collection Name of the cookie of the collection
 * @return string
 */
function readCollection(name, collection) {
   return loadCollection(collection)[name];
   // return c[name];
}


/**
 * save collection
 * @param {Array} cookieArray Array of the 
 * @param {string} collection Name of the cookie of the collection
 * @return Boolean
 */
function saveCollection(cookieArray, collection) {
	
	
   var tmp = new Array();
   for (var e in cookieArray) {
		if (typeof cookieArray[e] != 'function') {
			tmp[tmp.length] = e;
			tmp[tmp.length] = cookieArray[e];
		}
   }
	setCookie(collection, tmp.toString(), EXPIRE);
	return true;
}	


/**
 * write collection
 * @param {string} name Name of the key in the collection
 * @param {string} value Value of the key in the collection
 * @param {string} collection Name of the cookie of the collection
 * @return Boolean
 */
function writeCollection(name, value, collection) {
	
	
   var c = loadCollection(collection);
   c[name] = value;
   saveCollection(c, collection);
	return false;
}



// SHOPPING CART COOKIES          ----------------------------------------------


/** add Item to Shopping Cart
 * @param {string} id ID of the item (numeric or literal)
 * @param {int} quantity Quantity of the item to add
 * @param {string} cat Name of the cookie collection
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function addItem(id, quantity, cat) {
	var count = parseInt(readCollection(id, cat));
	if (isNaN(count))
		count = 0;
	count += quantity;
	writeCollection(id, count, cat);	
	return false;
}


/** edit Item in Shopping Cart
 * @param {string} id ID of the item (numeric or literal)
 * @param {int} quantity Quantity of the item to set
 * @param {string} cat Name of the cookie collection
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function editItem(id, quantity, cat) {
	writeCollection(id, quantity, cat);
	if (!(quantity > 0))
	cambiarColorCarrito(id,0);	
	return false;
}


/** get Item in Shopping Cart
 * @param {string} id ID of the item (numeric or literal)
 * @param {string} cat Name of the cookie collection
 * @return int
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function getItem(id, cat) {
	return readCollection(id, cat);
}


/** remove Item from Shopping Cart
 * @param {string} id ID of the item (numeric or literal)
 * @param {string} cat Name of the cookie collection
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function removeItem(id, cat) {
	editItem(id, 0, cat);
	return false;
}




// SHOPPING CART                  ----------------------------------------------


/** Object of the Item
 * @param {int} id ID of the Item
 * @return Object this
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function cartItem(id) {
	this.id = id;
	this.name = $('#' + id + ' .itemName').html();
	this.quantity = parseInt($('#' + id + '/.itemQuantity/input').val());
	if (isNaN(this.quantity) || (this.quantity < 0))
		this.quantity = 0;
	this.price = $('#' + id + ' .itemPrice').html().toString().replace(/\./g, '').replace(',', '.');
	if (isNaN(this.price))
		alert('Price is not formated correctly');	
	this.tax = parseInt($('#' + id + ' .itemTAX').html()) * 0.01;
	this.unit = $('#' + id + ' .itemUnit').html();
	this.pack = $('#' + id + ' .itemPack').html();
	this.brand = $('#' + id + ' .itemBrand').html();
	if ($('#' + id + ' .itemImage img').size() > 0) {
		this.image = $('#' + id + ' .itemImage img').attr('src');
		if (!this.image.match('http'))
			this.image = "http://" + this.image;
	}
	if ($('#' + id).parent().attr('id') != '') {
		this.category_id = $('#' + id).parent().attr('id');
		if ($('#' + this.category_id + ' .itemCategoryName').size() > 0)
			this.category_name = $('#' + this.category_id + ' .itemCategoryName').html();
		//else
			//alert('Please define the name of the category with class="itemCategoryName" where the text refers to the name of the Category.');	
	}
	else
		alert('Please define the id of the category with setting id of the category in the "id"-attribute of the "tbody"-tag, which should be a parentNode of the item itself.');
	
	if ($('#storeName').attr("title") != '')
		this.store = $('#storeName').attr("title");
	else
		alert('Please define the name/id of the store with id="storeName" and set name/id of the store in the "title"-attribute.');
	
	return this;
}


/** Object of the Item (on onload)
 * @param {object} el JSON Element
 * @param {string} collection
 * @return Object this
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function loadItem(el, collection) {
	this.id = 'i' + el.id;
	this.name = el.name.replace(/\u00B6/g, "\"");
	this.quantity = parseInt(readCollection(this.id, collection));
	this.price = el.price.replace(/\./g, '').replace(',', '.');
	if (isNaN(this.price))
		alert("Price is not formated correctly");
	this.tax = el.tax * 0.01;
	this.unit = el.unit;
	this.pack = el.pack;
	this.brand = el.brand;
	if (el.image) {
		this.image = el.image;
		if (!this.image.match('http'))
			this.image = "http://" + this.image;
	}
	else if (el.extern) {
		this.image = "http://" + location.hostname + "/Images/iconaPDF.gif";
	}
	this.category_id = el.cat_id;
	this.category_name = el.cat_name;
	this.store = collection;

	return this;
}



/** Display the item
 * @param {object} item Item object of the Item
 * @param {Boolean} arguments[1] If true, the item will be set on first position
 *		and evtl. the className will be changed
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function displayItem(item) {


	cambiarColorCarrito(item.id, item.quantity);
	
	if ($('#' + item.id + '_uniqueID').size() > 0) {
		if (arguments[1] && arguments[1] == true)
			$('#' + item.id + '_uniqueID').remove();
		else {
			redisplayItem(item.id, item.quantity);
			return true;
		}
	}
	if (item.quantity <= 0) {
		if ($('#' + item.id + '_uniqueID').size() > 0)
			$('#' + item.id + '_uniqueID').remove();
		return false;
	}
	var dolly = $('#itemTemplate').clone(true).attr("id", function() { return item.id + '_uniqueID'; }).show();
	dolly.insertBefore($('#cartContent/*:first'));
	
	
	$('#' + item.id + '_uniqueID .itemID').html(item.id);
	$('#' + item.id + '_uniqueID .itemName').html(item.name);
	$('#' + item.id + '_uniqueID .itemQuantity').html(item.quantity);
	$('#' + item.id + '_uniqueID .itemQuantityInput').html('<input type="text" value="' + item.quantity + '" onchange="editInCart(\'' + item.id + '\', this.value, \'' + item.store + '\', \'' + item.pack + '\');" />');
	$('#' + item.id + '_uniqueID .itemStore').html(item.store);
	$('#' + item.id + '_uniqueID .itemCategoryID').html(item.category_id);
	$('#' + item.id + '_uniqueID .itemCategoryName').html(item.category_name);
	$('#' + item.id + '_uniqueID .itemPrice').html(item.price);
	$('#' + item.id + '_uniqueID .itemPriceSingle').html(cropNumber(item.price, 4).toString().replace('.', ','));
	$('#' + item.id + '_uniqueID .itemPriceMultiple').html(cropNumber((item.price * item.quantity), 4).toString().replace('.', ','));
	$('#' + item.id + '_uniqueID .itemPriceTAX').html(cropNumber((item.price * item.quantity * item.tax), 4).toString().replace('.', ','));
	$('#' + item.id + '_uniqueID .itemPriceInclusive').html(cropNumber((item.price * item.quantity * (1 + item.tax)), 4).toString().replace('.', ','));
	$('#' + item.id + '_uniqueID .itemTAX').html(Math.round(item.tax * 100));
	$('#' + item.id + '_uniqueID .itemUnit').html(item.unit);
	$('#' + item.id + '_uniqueID .itemPack').html(item.pack);
	$('#' + item.id + '_uniqueID .itemBrand').html(item.brand);
	if (!item.image || item.image.length < 1) {
		// $('#' + item.id + '_uniqueID .itemImage').hide();
	}
	else {
		$('#' + item.id + '_uniqueID .itemImage').html('<img src="' + item.image + '" alt="Image' + item.id + '" />');
	}
	// dolly.insertBefore($('#cartContent'));
	// $('#cartContent').insertBefore(dolly, $('#cartContent').firstChild);
		
	return true;
}


/** Redisplay already visible item
 * @param {string} id ID of the item
 * @param {int} quantity Quantity of the item
 * @param {Boolean} arguments[2] If true, the item will be set on first position
 *		and evtl. the className will be changed
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function redisplayItem(id, quantity) {
	
	if (arguments[2] && arguments[2] == true && $('#' + id + '_uniqueID').size() > 0 )
		$('#' + id + '_uniqueID').remove();

	if (quantity <= 0) {
		if ($('#' + id + '_uniqueID').size() > 0)
			$('#' + id + '_uniqueID').remove();
		return false;
	}
	
	if ($('#' + id + '_uniqueID').size() <= 0) {
		var item = new cartItem(id);
		item.quantity = readCollection(item.id, item.store);
		if (arguments[2] && arguments[2])
			displayItem(item, arguments[2]);
		else
			displayItem(item);
		return true;
	}
		
		
	var myQuantity = quantity;
	var myPack = $('#' + id + '_uniqueID .itemPack').html();
	var myStore = $('#' + id + '_uniqueID .itemStore').html();
	var myPrice = $('#' + id + '_uniqueID .itemPrice').html().toString().replace(',', '.');
	var myTax = parseInt($('#' + id + '_uniqueID .itemTAX').html()) * 0.01;
	
	$('#' + id + '_uniqueID .itemQuantity').html(myQuantity);
	$('#' + id + '_uniqueID .itemQuantityInput').html('<input type="text" value="' + myQuantity + '" onchange="editInCart(\'' + id + '\', this.value, \'' + myStore + '\', \'' + myPack + '\');" />');
	$('#' + id + '_uniqueID .itemPriceSingle').html(cropNumber(myPrice, 4).toString().replace('.', ','));
	$('#' + id + '_uniqueID .itemPriceMultiple').html(cropNumber((myPrice * myQuantity), 4).toString().replace('.', ','));
	$('#' + id + '_uniqueID .itemPriceTAX').html(cropNumber((myPrice * myQuantity * myTax), 4).toString().replace('.', ','));
	$('#' + id + '_uniqueID .itemPriceInclusive').html(cropNumber((myPrice * myQuantity * (1 + myTax)), 4).toString().replace('.', ','));
		
	return true;
}

/** Display total information in the cart
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function updateTotal() {
	var totalProducts = 0;
	var totalItems = 0;
	var totalReserve = 0;
	var totalReserveStatus = false;
	var totalPriceExclusive = 0.0;
	var totalPriceTax = 0.0;
	var totalPriceInclusive = 0.0;
	
	if ($('#cartFooter .cartTotalReserve').size() > 0) 
		totalReserve = parseInt($('#cartFooter .cartTotalReserve').html());
	if (isNaN(totalReserve) || (totalReserve < 0))
		totalReserve = 0;
		//a�ade producto al carrito
	$('#cartContent').children().each(function(i) {
		if (this.id.match("_uniqueID")) {
			var myPrice = $('#' + this.id + ' .itemPrice').html().toString().replace(',', '.');
			var myQuantity = parseInt($('#' + this.id + ' .itemQuantity').html());
			var myPack = parseInt($('#' + this.id + ' .itemPack').html());
			var myTax = parseInt($('#' + this.id + ' .itemTAX').html()) * 0.01;
			totalProducts++;
			totalItems += myQuantity;
			totalPriceExclusive += (myPrice * myQuantity);
			totalPriceTax += (myPrice * myQuantity * myTax);
			totalPriceInclusive += (myPrice * myQuantity * (1 + myTax));
			
		}
	});
	if (totalPriceExclusive >= totalReserve)
		totalReserveStatus = true;

	$('#cartFooter .cartTotalProducts').html(totalProducts);
	$('#cartFooter .cartTotalItems').html(totalItems);	
	$('#cartFooter .cartTotalReserveStatus').html('' + totalReserveStatus + '');
	$('#cartFooter .cartTotalReserve').parent().css({ color : (totalReserveStatus) ? '#23408F' : '#D2232A', fontWeight : (totalReserveStatus) ? 'normal' : 'bold' });
	$('#cartFooter .cartTotalPriceExclusive').html(cropNumber(totalPriceExclusive, 2).toString().replace('.', ','));
	$('#cartFooter .cartTotalPriceTax').html(cropNumber(totalPriceTax, 2).toString().replace('.', ','));
	$('#cartFooter .cartTotalPriceInclusive').html(cropNumber(totalPriceInclusive, 2).toString().replace('.', ','));

	// addOn by Mirta :-)
	mostraCesta(totalProducts);
	mostraCarrito(totalProducts);
		
	return true;
}


/** Add item to cart
 * @param {string} id ID of the item
 * @param {Boolean} arguments[1] If true, the item will be set on first position
 *		and evtl. the className will be changed
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function addToCart(id) {
	
	var item = new cartItem(id);
	addItem(item.id, item.quantity, item.store);
	if (isNaN(parseInt(item.quantity)))
		item.quantity = 0;
	item.quantity = checkPack(readCollection(item.id, item.store), item.pack);
	if (item.quantity < 0)
		readCollection(item.id, item.store);
	
	if (arguments[1])
		displayItem(item, arguments[1]);
	else
		displayItem(item);
	updateTotal();
	return false;
}




// quantity is arguments[1] just in case
// boolean for put on top is arguments[2] just in case
function updateInCart(id) {
	
	var pack = $("#" + id + " .itemPack").html();
	var quantity = (arguments[1] && arguments[1].length > 0) ? arguments[1] : $("#" + id + " .itemQuantity/input").val();
	
	if (isNaN(parseInt(quantity)))
		quantity = 0;	
	quantity = checkPack(quantity, pack);
	if (quantity < 0)
		quantity = 0;
	editItem(id, quantity, $('#storeName').attr("title"));
	// addOn by Mirta :-)
	cambiarColorCarrito(id, 0);	
	
	if (arguments[2]){
		redisplayItem(id, quantity, arguments[2]);
	}
	else{
		redisplayItem(id, quantity);
	}
	// addOn by Mirta :-)
	cambiarColorCarrito(id, quantity);	
	
	updateTotal();
	return false;
}


/** Edit item in cart
 * @param {string} id ID of the item
 * @param {string} quantity Quantity of the item
 * @param {string} store_id ID of the store of the item
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function editInCart(id, quantity, store_id, pack) {
	if (isNaN(parseInt(quantity)))
		quantity = 0;
	quantity = checkPack(quantity, pack);
	if (quantity < 0)
		quantity = $('#' + id + '_uniqueID .itemQuantity').html();
	
	//powered by mirta @:)))
	if (document.getElementById('productsTable')){
		if (document.getElementById(id)) {
			var mio = document.getElementById(id);
			var cantidad = mio.getElementsByTagName('input');
			cantidad[cantidad.length - 1].value = quantity;
		}
	}
		
	editItem(id, quantity, store_id);
	redisplayItem(id, quantity);
	updateTotal();
	return false;
}


/** Remove item from cart
 * @param {string} id ID of the item
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function removeFromCart(id) {
	id = id.replace('_uniqueID', '');
	var store_id = $('#' + id + '_uniqueID .itemStore').html();
	removeItem(id, store_id);
	redisplayItem(id, 0);	
	
	// addOn by Mirta :-)
	cambiarColorCarrito(id,0);	
		
	updateTotal();
	return false;
} 


/** Get only itemIDs out of cookie
 * @param {string} collection Cookie (or store-ID)
 * @param {string} separator Symbol for separating IDs
 * @return string
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function readItems(collection, separator) {
	var itemString = new String('');
	var items = loadCollection(collection);
	for (var key in items) {
		if (parseInt(items[key]) != 0) {
			itemString += (arguments[2] && !!arguments[2]) ? key.replace('i', '') + '|||' + items[key] + separator : key.replace('i', '') + separator;
		}
	}
	return itemString;
}


/** Load already existing items in cart (on onload Page)
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function loadCart() {
	if ($('#storeName').attr("title") == undefined && getCookie('CURRENT_ID') != '' && getCookie('CURRENT_NAME') != '')
		checkStoreInfo();

	if ($('#storeName').attr("title") != '' && numProducts() > 0) {
		var items = loadCollection($('#storeName').attr("title"));
		for (var key in items) {
			if (parseInt(items[key]) > 0){
				updateInCart(key, items[key]);
				
			}
			else
				removeFromCart(key);
		}
		return true;
	}
	
	if ($('#storeName').attr("title") != '') {
		var post = "PRODUCTLIST=" + readItems($('#storeName').attr("title"), '|') + "&STORE_ID=" + $('#storeName').attr("title");
		sendRequest("http://www.paramiclinica.com/listProducts.xsql", handleLoadCart, post);
		return false;
	}
	
	return false;
}


/** Handle Request
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function handleLoadCart(req) {
	if (req.responseText.substr(0, 1) != '{' && req.responseText.substr(0, 1) != '[') {
		// something went wrong, but we do not care
		updateTotal();
		return false;
	}
	// response should be an array
	// var response = eval ('(' + req.responseText + ')');
	var response = eval('(' + req.responseText + ')');
	var products = response.products;
	$('#cartFooter .cartTotalReserve').html(response.reservePrice);
	for (var i = 0; i < products.length; i++) {
		var item = new loadItem(products[i], $('#storeName').attr("title"));
		if (item.quantity && item.quantity > 0)
			displayItem(item);
	}
	updateTotal();
	return true;
}




function nextPage(form) {
	if (readItems($('#storeName').attr("title"), '|').length > 0) {
		form.PRODUCTLIST.value = readItems($('#storeName').attr("title"), '|');
	}
	if (form.RESERVE && $('#cartFooter .cartTotalReserveStatus').html() != "true") {
		alert("No has llegado al pedido minimo que tiene esta tienda!");
		return false;
	}
	
	form.submit();
	return false;
}


function finishPage(form) {
	if (getCookie('SES_ID').length > 0)
		form.action = "finalizar.xsql";
	if (readItems($('#storeName').attr("title"), '|').length > 0) {
		form.PRODUCTLIST.value = readItems($('#storeName').attr("title"), '|');
	}
	if (form.RESERVE && $('#cartFooter .cartTotalReserveStatus').html() != "true") {
		alert("No has llegado al pedido minimo que tiene esta tienda!");
		return false;
	}

	form.submit();
	return false;
}



function checkOut(form) {
	if (readItems($('#storeName').attr("title"), '|').length > 0) {
		form.PRODUCTLIST.value = readItems($('#storeName').attr("title"), '|');
		if ($('#cartFooter .cartTotalReserveStatus').html() == "true")
			form.submit();
		else
			alert('Reserve price not reached')
	}
	else
		alert('Nothing to checkout');
	return false;
}

function finishCart(form, id) {
	if (readItems($('#storeName').attr("title"), '|').length > 0) {
		var post = new String('');
		form.PRODUCTLIST.value = readItems($('#storeName').attr("title"), '|');
		form.ORDER.value = readItems($('#storeName').attr("title"), '#', true);
		post += 'ORDER=' + form.ORDER.value;
		post += '&COMMENT=' + form.COMMENT.value;
		
		$('#buttonFinal').hide();
		wait(id, "Please wait ...");
		
		sendRequest(form.action, handleFinishCart, post);
		return false;
	}
	return false;
}


function handleFinishCart(req) {
	var resp;
	var innerText = new String('');
	if (req.responseText.substr(0, 1) != '{' && req.responseText.substr(0, 1) != '[') {
		innerText += '<p>Se ha producido un error, si se repite por favor contacta con</p>';
		innerText += '<a href="mailto:tecnico@' + location.hostname.replace('www.','') + '?subject=JSON%20Error">tecnico@' + location.hostname.replace('www.','') + '</a>';
		
		pedidoMal(innerText);
	}
	else {
		
		resp = eval('(' + req.responseText + ')');
		innerText += '<p></p>';
		/*if (resp.confirm.length > 0) {
			innerText += '<p>' + resp.confirm + '</p>'; 
			innerText += '<p></p>'; 
		}*/
		if (resp.order && resp.order.global) {
			innerText += '<p></p>';
			innerText += '<pre class="rojo">Detalles del pedido</pre>';
			innerText += '<p></p>';
			innerText += '<pre>Numero referencia:       ' + resp.order.global.id + '</pre>';
			innerText += '<pre>Fecha de realizaci�n:    ' + resp.order.global.date + '</pre>';
			//innerText += '<pre>Status:   ' + resp.order.global.status + '</pre>';
			innerText += '<pre>Total del pedido:    ' + resp.order.global.total + '</pre>';
			//innerText += '<pre>eMail:    ' + resp.order.global.email + '</pre>';
			//innerText += '<p></p>';
		}
		//innerText += '<p></p>';
		//innerText += '<p>Por favor, si tiene una duda, contacte con nosotros</p>';
		
		pedidoBien(innerText);
		return false;
	}
		
	if (resp.order && resp.order.global && resp.order.global.status == 'P')
		cleanup();		
	
	return false;
	
	
}
// si el pedido va bien o no
function pedidoMal(testo) {
	if (testo.length > 0){
		viewMessage(testo);
	}
}

function pedidoBien(testo) {
	
	if (testo.length > 0){
		viewMessageOk(testo);
	} 
	$('#userFinal, #infoPedido, #userConfirmar, #buttonImprimir').show();
	$('#finalizarCompra, #carritoTitle, #userFinalizar').hide();
	$('#pedidoOK').show();
	cleanup();		
}
//funcion para visualizar los errores del usuarios cuando enserta sus datos un div
function viewMessageOk(message, where){
	var print = '<div><p>' + message + '</p></div>';
	$('#detalleOk').html(print);
	$('#detalleOk').show();
	return true;
}


function cleanup() {
	cleanupCookies();
	eraseCookie('SESSION');
	return false;
}


function cleanupCookies() {
	if (document.getElementById('storeName') && document.getElementById('storeName').title.length > 0)
		eraseCookie(document.getElementById('storeName').title);
	eraseCookie('CURRENT_ID');
	eraseCookie('CURRENT_NAME');
	eraseCookie('CURRENT_COMMENT');
	eraseCookie('SES_ID');
	return false;
}


// return int 
function numProducts() {
	
	var num = 0 ;
	if ($('#cartContent').size() > 0) {
		var childs = $('#cartContent').children();
		
		for (i = 0; i < childs.length; i++) {
			if (childs[i].id && childs[i].id.match("_uniqueID"))
				num++;
		}
	}
	if (num > 0)
		return num;
	else
		return -1;
}

function checkStoreInfo() {
	if ($('#storeName').attr("title") == undefined && getCookie('CURRENT_ID') != '' && getCookie('CURRENT_NAME') != '') {
		$('#storeName').attr("title", getCookie('CURRENT_ID')).html(getCookie('CURRENT_NAME'));
		if (document.forms['continueShopping']) {
			document.forms['continueShopping'].action = 'http://www.paramiclinica.com/tienda.xsql?TIENDA=' + $('#storeName').attr("title");
			$(document.forms['continueShopping']).find('a').attr('href', 'http://www.paramiclinica.com/tienda.xsql?TIENDA=' + $('#storeName').attr("title"));
		}
		var sIds = document.getElementsByName('STORE_ID');
		var sNames = document.getElementsByName('STORE_NAME');
		for (var i = 0; i < sIds.length; i++) {
			sIds[i].value = $('#storeName').attr("title");
			sNames[i].value = $('#storeName').html();
		}
	}
	return false;
}


function mostraCarrito(num) {
	if ($('#productsCesta').size() > 0) {
		num = parseInt(num);
		if (!isNaN(num) && num > 0) {
			$('#productsCesta').show();
			$('#googleTienda').hide();
			return true;
		}
		else {
			$('#productsCesta').hide(); 
			$('#googleTienda').show();
			return false;
		}
	}
	return false;
}



function cambiarColorCarrito(id, quantity) {
	if ($('#productsCesta').size() > 0 && document.getElementById(id)) {
		if (quantity > 0) {
			var mel = document.getElementById(id); 
			var images = mel.getElementsByTagName('img');
			var cantidad = mel.getElementsByTagName('input');
			cantidad[cantidad.length - 1].value = quantity;
			images[images.length - 1].src = "http://www.paramiclinica.com/Images/carrito-rojo25x15.gif";
		}
		if(quantity == 0 ) {
			var mel = document.getElementById(id);
			var mel = document.getElementById(id);
			
			var images = mel.getElementsByTagName('img');
			
			images[images.length - 1].src = "http://www.paramiclinica.com/Images/carrito-gris25x15.gif";
		}
	}
}

	
function mostraCesta(num) {
	if ($('#productsCesta').size() > 0) {
		num = parseInt(num);
				
		if (!isNaN(num) && num > 0) {
			$('#productsCesta').show();
			$('#googleTienda').hide();
			return true;
		}
		else {
			$('#productsCesta').hide(); 
			$('#googleTienda').show();
			return false;
			
		}
	}
	return false;
}


function mostraCarrito(num) {
	if ($('#productsCarrito').size() > 0) {
		//num = parseInt(num);
		if (!isNaN(num) && num > 0) {
			$('#productsCarrito, #button').show();
			$('#sinCarrito').hide();
			return true;
		}
		else {
			$('#productsCarrito, #button').hide(); 
			$('#sinCarrito').show();
			return false;
		}
	}
	return false;
}

/**
 * Change style of input field and display message if forgotten password
 * @param {object} form HTML form
 * @return undefined
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function forgotPassword(form) {
	//var msg = errorCheck(form);
	var msg = '';
	
	if (form.elements['USER'].value == '') {
		msg += 'La direcci�n de correo electr�nico es obligatoria.\n';
		form.elements['USER'].style.background = 'silver';
		
		//form.elements('inputEmailFake').style.background = 'silver';
		
		form.elements['USER'].style.border = '1px solid #C00';
		//$('inputEmailFake').style.border = '1px solid #C00';
	}
	else {
		if (!checkEmail(form.elements['USER'].value)) {
			msg += 'La direcci�n de correo electr�nico no tiene el formato correcto: direccion@dominio.ext.\n';
			form.elements['USER'].style.background = 'silver';
			//$('inputEmailFake').style.background = 'silver';
			form.elements['USER'].style.border = '1px solid #C00';
			//$('inputEmailFake').style.border = '1px solid #C00';
		}
	}

	if (msg == '') {
	//	form.action = "http://www.paramiclinica.com/olvidoLogin.xsql";
			form.action = "http://"+location.hostname+"/olvidoLogin.xsql";
		SubmitMyForm(form);
	}
	else
	viewMessage(msg);
	
	return undefined;
}


/**
 * Submit form
 * @param {object} form HTML form 
 * @return Boolean
 * @author Martin Gangkofer gangkofer@gmail.com
 */
function SubmitMyForm(form){
	for(var j = 0; j < form.elements.length; j++){
		if (form.elements[j].type == 'textarea')
			form.elements[j].value = seperatePoints(form.elements[j].value);
		if (form.elements[j].type != 'file')
			form.elements[j].value = reemplazaCaracteres(form.elements[j].value, "'", "`");
	}
	var buttons = document.getElementsByName("sendFormButton");
	if (buttons[0]) {
		for (var i = 0; i < buttons.length; i++) { 
		buttons[i].style.visibility  = 'hidden';
		}
	}
	
	form.submit();
}


function checkPack(quantity, pack) {
	quantity = parseInt(quantity);
	pack = parseInt(pack);
	if (!(isNaN(quantity)) && !(isNaN(pack))) {
		var remainder = quantity % pack;
		var roundUp = (pack - remainder) + quantity;
		var roundDown = quantity - remainder;
		if (remainder != 0) {
			if (confirm("La cantidad no es un numero proporcional al numero de unidades por lote.\nQuiere cambiar a " + roundUp + " ?"))
				quantity = roundUp;
			else
				quantity = -1;
		}
	}
	return quantity;
}
