/*  Le Boutique for Joomla (c) 2006 Carlos Paz <steelgunner@chipzoo.com>
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  The Grid for Joomla is freely distributable under the terms of an MIT-style license.
 *  For details, see the The Grid for Joomla: http://www.chipzoo.com/main/index.php?option=com_the_grid&Itemid=26
 *	
/*--------------------------------------------------------------------------*/
if (checkout == 0) {
Event.observe(window, 'load', init, false);
//Event.observe(window, 'load', getCart, false);
//Event.observe(window, 'load', init_price, false);
} else {
init_qty();
}

var timeout; // for the timer dialog
var backend;
var alert_msg;
if (backend == 1) {
//alert("1");
var url =  "../components/com_the_grid/javascripts/editinplace.php";	
var url2 = "../components/com_the_grid/javascripts/editinplace_fieldtype.php";
var url3 = "../components/com_the_grid/javascripts/editinplace_form.php";
} else {
//alert("0");
var url =  "components/com_the_grid/javascripts/editinplace.php";	
var url2 = "components/com_leboutique/cart.php";
var url3 = "components/com_the_grid/javascripts/editinplace_form.php";
	
}
//location for the server response php files
// Initialize all div object that got the className of buyProduct and Cart
function init(){
var doc = document.getElementsByTagName('div');
for (var i = 0; i < doc.length; i++){
   if(doc[i].className == "buyProduct" )
   {
		buyProduct(doc[i]);
	}
}
	
}

// Initialize even observer to monitor the grid
function buyProduct(id){
	Event.observe(id, 'click', function(){addToCart($(id))}, false);
	//Event.observe(id, 'mouseover', function(){showAsEditable($(id))}, false);
	//Event.observe(id, 'mouseout', function(){showAsEditable($(id), true)}, false);
}

// Initialize even observer to monitor the buttons
function getCart(){
	Event.observe('theCart', 'click', function(){getCartDetails($('theCart'))}, false);
	//Event.observe(id, 'mouseover', function(){showAsEditable($(id))}, false);
	//Event.observe(id, 'mouseout', function(){showAsEditable($(id), true)}, false);
}






// add to cart 
function addToCart(obj){
	//Element.hide(obj);
	var productid = obj.getAttribute('productid');
	var task = obj.getAttribute('task');
	var userid = obj.getAttribute('userid');
	var qty = obj.getAttribute('qty');
	var new_content	=  escape(obj.innerHTML);
	var price	=  obj.getAttribute('price');
	var success	= function(t){printCartResponse(t, obj);}
	var failure	= function(t){operationFailed(t, obj);}
	var posts = 'productid='+productid+'&task='+task+'&userid='+userid+'&qty='+qty+'&price='+price;
	//alert(price);
	if (userid != 0 || login_required == 0) {
		openInfoDialog(add_product_msg);
		var myAjax = new Ajax.Request(url2, {method:'post', postBody:posts, onSuccess:success, onFailure:failure});	
	} else if (login_required == 1) {
		openInfoDialog(login_msg);
	}
}

function printCartResponse(t, obj){
	var theid = obj.getAttribute('eip_id');
	new Insertion.After(obj, t.responseText);
	//Event.observe(theid+'_save', 'click', function(){saveChanges(obj,url)}, false);
	//Event.observe(theid+'_cancel', 'click', function(){cleanUp(obj)}, false);
}

function operationFailed(t, obj){
	obj.innerHTML	= 'Sorry, the transaction failed.';
	cleanUp(obj);
}











// cart details
function getCartDetails(){
	var success	= function(t){printHtmlCart(t);}
	var failure	= function(t){operationFailed(t);}
	var pars = 'task=cartContent';
	var myAjax = new Ajax.Request(url2, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});
}

function printHtmlCart(t){
	winedit = new Window("thecart01", {className: "alphacube",  width:550, height:400, zIndex: 100, resizable:true, title: cart_title, draggable:true});
	winedit.getContent().innerHTML = t.responseText;
	winedit.setDestroyOnClose();
	winedit.showCenter();
	init_qty();
	//alert(t.responseText);
	//openInfoDialog();
}

function init_qty(){
	var doc = document.getElementsByTagName('div');
	for (var i = 0; i < doc.length; i++){
		if(doc[i].className == "theCartQty" )
		{
			init_qty_events(doc[i]);
		}
	}
}

function init_qty_events(id){
	Event.observe(id, 'click', function(){getHtmlFieldCart($(id))}, false);
	Event.observe(id, 'mouseover', function(){showAsEditable($(id))}, false);
	Event.observe(id, 'mouseout', function(){showAsEditable($(id), true)}, false);
}

function getHtmlFieldCart(obj){
	Element.hide(obj);
	var new_content	=  escape(obj.innerHTML);
	var success	= function(t){printHtmlCartField(t, obj);}
	var failure	= function(t){editFailed(t, obj);}
	var post = 'id='+obj.getAttribute('salesid')+'&value='+obj.getAttribute('qty')+'&task='+obj.getAttribute('task')+'&field='+obj.getAttribute('field');
	var myAjax = new Ajax.Request(url2, {method:'post', postBody:post, onSuccess:success, onFailure:failure});
}


function printHtmlCartField(t, obj){
	var theid = obj.getAttribute('salesid');
	new Insertion.After(obj, t.responseText);
	Event.observe(theid+'_save', 'click', function(){saveChanges(obj,url)}, false);
	Event.observe(theid+'_cancel', 'click', function(){cleanUp(obj)}, false);
}

function saveChanges(obj,url){
	var theid = obj.getAttribute('salesid');
	var new_content	=  escape($F(theid+'_edit'));
	obj.innerHTML = cart_saving;
	cleanUp(obj, true);
	var success	= function(t){editComplete(t, obj);}
	var failure	= function(t){operationFailed(t, obj);}
	var post = 'id='+theid+'&newvalue='+new_content+'&field='+obj.getAttribute('field')+'&task=theCartQtyUpdate';
	var myAjax = new Ajax.Request(url2, {method:'post', postBody:post, onSuccess:success, onFailure:failure});
}

function editComplete(t, obj){
	var theid = obj.getAttribute('salesid');
	obj.innerHTML	= t.responseText;
	obj.setAttribute('qty',t.responseText);
	showAsEditable(obj, true);
	resultadillo = t.responseText * parseFloat(document.getElementById('theCartPrice_'+theid).innerHTML); // update subtotal
	document.getElementById('theCartTotal_'+theid).innerHTML = resultadillo.toFixed(2);
	//alert(t.responseText);
	//alert(document.getElementById('theCartPrice_'+theid).innerHTML);
	var doc2 = document.getElementsByTagName('div');
	var grantotal = 0;
	var grantotalQty = 0;
	for (var z = 0; z < doc2.length; z++){
		if(doc2[z].className == "theCartTotal" )
		{
			grantotal = parseFloat(doc2[z].innerHTML) + grantotal;
		}
		if(doc2[z].className == "theCartQty" )
		{
			grantotalQty = parseFloat(doc2[z].innerHTML) + grantotalQty;
		}
	}
	document.getElementById('theCartGranTotal').innerHTML = grantotal.toFixed(2); //update gran total
	document.getElementById('theCartGranTotalQty').innerHTML = grantotalQty; //update gran total
	if (checkout == 1) {
		document.getElementById('gran_total_cart').value = grantotal; //update gran total
	}
	
	if ($('DE')) {
		update_product_details();	
	}
}


















// product_brochure

function product_brochure(obj){
	var productid = obj.getAttribute('productid');
	var success	= function(t){print_product_brochure(t);}
	var failure	= function(t){operationFailed(t);}
	var pars = 'task=product_brochure&productid='+productid;
	var myAjax = new Ajax.Request(url2, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});
}

function print_product_brochure(t){
	/*alert (t.responseText);*/
	probro = new Window('content_win', {className:"alphacube", width:550, height:350, zIndex: 100, resizable: false, hideEffect:Element.hide, showEffect:Element.show, minWidth: 10}) 
	probro.getContent().innerHTML= t.responseText;
	//contentWin.setContent('lost_password', true, true);
	probro.setDestroyOnClose(); 
	probro.toFront(); 
	probro.showCenter();
}











// save_user details

function save_user_details (){
	var success	= function(t){save_user_details_success(t);}
	var failure	= function(t){operationFailed(t);}
	document.leboutiquecheckout.task.value = "save_cookies";
	var pars = Form.serialize( 'leboutiquecheckout' );
	var myAjax = new Ajax.Request(url2, {method:'post', postBody:pars, onSuccess:success, onFailure:failure});
}

function save_user_details_success(t){
	alert ("SAVED");
	alert (t.responseText);
	//document.leboutiquecheckout.submit();
}













// just for the price field

function init_price(){
	var doc = document.getElementsByTagName('div');
	for (var i = 0; i < doc.length; i++){
		if(doc[i].className == "PriceProduct" )
		{
			init_price_events(doc[i]);
		}
	}
}

function init_price_events(id){
	Event.observe(id, 'click', function(){getHtmlPriceCatalogue($(id))}, false);
	Event.observe(id, 'mouseover', function(){showAsEditable($(id))}, false);
	Event.observe(id, 'mouseout', function(){showAsEditable($(id), true)}, false);
}

function getHtmlPriceCatalogue(obj){
	Element.hide(obj);
	var new_content	=  escape(obj.innerHTML);
	var success	= function(t){printHtmlPriceCatalogue(t, obj);}
	var failure	= function(t){editFailed(t, obj);}
	var post = 'id='+obj.getAttribute('productid')+'&value='+obj.getAttribute('price')+'&task='+obj.getAttribute('task')+'&field='+obj.getAttribute('field');
	var myAjax = new Ajax.Request(url2, {method:'post', postBody:post, onSuccess:success, onFailure:failure});
}


function printHtmlPriceCatalogue(t, obj){
	var theid = obj.getAttribute('productid');
	new Insertion.After(obj, t.responseText);
	Event.observe(theid+'_save_price', 'click', function(){saveChangesPriceCatalogue(obj,url)}, false);
	Event.observe(theid+'_cancel_price', 'click', function(){cleanUp2(obj)}, false);
}

function saveChangesPriceCatalogue(obj,url){
	var theid = obj.getAttribute('productid');
	var new_content	=  escape($F(theid+'_edit_price'));
	cleanUp2(obj, true);
	obj.innerHTML = "$ " + new_content;
	obj.setAttribute('price',new_content);
	document.getElementById(theid + '_buyProduct').setAttribute('price',new_content);
	showAsEditable(obj, true);
	
}





// change the price product

function change_price_product(obj){
	var theid = obj.getAttribute('productid');
	var new_content	=  escape($F(theid+'_edit_price_textbox'));
	document.getElementById(theid + '_buyProduct').setAttribute('price',new_content);
}








//auxiliar functions
function showAsEditable(obj, clear){
	if (!clear){
		Element.addClassName(obj, 'editable');
	}else{
		Element.removeClassName(obj, 'editable');
	}
}

function cleanUp(obj, keepEditable){
	var theid = obj.getAttribute('salesid');
	Element.remove(theid+'_editor');
	Element.show(obj);
	if (!keepEditable) showAsEditable(obj, true);
}

function cleanUp2(obj, keepEditable){
	var theid = obj.getAttribute('productid');
	Element.remove(theid+'_editor_price');
	Element.show(obj);
	if (!keepEditable) showAsEditable(obj, true);
}


function showCalendarParent(id) {
	var el = $(id);
	if (calendar != null) {
		calendar.hide();		// hide the existing calendar
		calendar.parseDate(el.value); // set it to a new date
		calendar.sel = el;
		calendar = null;
	} else {
		var parent = $("dateselector");		
		var cal = new Calendar(true, null, selected, closeHandler);
		calendar = cal;	
		cal.create(parent);
		cal.show();
		cal.parseDate($(id).value)
		calendar.sel = el;
	}
	return false;	
}

function checkAllGrid( n, form , fldName ) {
  if (!fldName) {
     fldName = 'cb';
  }
	//alert(n);
	var f = $(form+'_grid_form');
	var c = f.toggle.checked;
	var n2 = 0;
	for (i=0; i < n; i++) {
		cb = eval( 'f.' + fldName + '' + i );
		if (cb) {
			cb.checked = c;
			n2++;
		}
	}
	if (c) {
		f.boxchecked.value = n2;
	} else {
		f.boxchecked.value = 0;
	}
}
function checkOneGrid( n, form , fldName ) {
  if (!fldName) {
     fldName = 'cb';
  }
	var f = $(form+'_grid_form');
	var c = f.toggle.checked;
	cb = eval( 'f.' + fldName + '' + n );
	cb.checked = true;

}

function isCheckedGrid(isitchecked, form ){
	var f = $(form+'_grid_form');
	if (isitchecked == true){
		f.boxchecked.value++;
	}
	else {
		f.boxchecked.value--;
	}
}

function form_delete(form){
	var f = $(form+"_grid_form");
	var msg = '<br /><div align="center" class="contentheading">Are you sure you want to delete?</div><br />';
	Dialog.confirm(msg, {windowParameters: {className: "dialog", width:300, height:100}, okLabel: "Delete", cancel:function(win) {debug("cancel confirm panel")}, ok:function(win) {f.grid_task.value=form + "_delete";f.submit();} });
}

function form_publish(form,publish){
	var f = $(form+"_grid_form");
	f.grid_task.value = form + "_publish";
	f.published.value = publish;
	f.submit();
}






// popup picture script

function popupPic(img){
  foto1= new Image();
  foto1.src=(img);
  Controlla(img);
}
function Controlla(img){
  if((foto1.width!=0)&&(foto1.height!=0)){
    viewFoto(img);
  }
  else{
    funzione="Controlla('"+img+"')";
    intervallo=setTimeout(funzione,20);
  }
}
function viewFoto(img){
  largh=foto1.width+20;
  altez=foto1.height+20;
  stringa="width="+largh+",height="+altez;
  finestra=window.open(img,"",stringa);
}










// showhide options

function showhide(id){
	//id = 'details' + id;
	//alert(id);
	obj = document.getElementById(id);
	if (obj.style.display == "none"){
	obj.style.display = "";
	//alert("showing up");
	} else {
	obj.style.display = "none";
	//alert("showing down");
	}
}

function openInfoDialog(msg) {
	alert_msg = msg;
	Dialog.info(alert_msg, {windowParameters: {width:250, height:100}, showProgress: true}); 
	timeout=1; 
	setTimeout(infoTimeout, 1000) 
} 

function infoTimeout() { 
	timeout--; 
	if (timeout >0) { 
		Dialog.setInfoMessage(alert_msg + "<br />" + timeout + "s ...") 
		setTimeout(infoTimeout, 1000) 
	} 
	else 
		Dialog.closeInfo() 
} 

function remove_row(row) {
	Element.remove(row);
	var post = 'deleteid='+row+'&task=theCartDeleteRow';
	var success	= function(t){remove_row_complete();}
	var failure	= function(t){operationFailed();}
	var myAjax = new Ajax.Request(url2, {method:'post', postBody:post, onSuccess:success, onFailure:failure});
	return false;
}

function remove_row_complete () {
	recalculate_totals();
	if ($('DE')) {
		update_product_details();	
	}	
}

function update_product_details() {
	var success	= function(t){update_product_details_complete(t);}
	var failure	= function(t){operationFailed(t);}
	var post = 'task=update_product_details';
	var myAjax = new Ajax.Request(url2, {method:'post', postBody:post, onSuccess:success, onFailure:failure});
	return false;	
}

function update_product_details_complete(t) {
	$('DE').value = t.responseText;
}

function recalculate_totals () {
	
	var doc2 = document.getElementsByTagName('div');
	var grantotal = 0;
	var grantotalQty = 0;
	for (var z = 0; z < doc2.length; z++){
		if(doc2[z].className == "theCartTotal" )
		{
			grantotal = parseFloat(doc2[z].innerHTML) + grantotal;
		}
		if(doc2[z].className == "theCartQty" )
		{
			grantotalQty = parseFloat(doc2[z].innerHTML) + grantotalQty;
		}
	}
	document.getElementById('theCartGranTotal').innerHTML = grantotal; //update gran total
	document.getElementById('theCartGranTotalQty').innerHTML = grantotalQty; //update gran total
	if (checkout == 1) {
		document.getElementById('gran_total_cart').value = grantotal; //update gran total
	}	
	
}
