//@---->start cod cos
window.onload = function() {
	if($('cart'))
	{
		var draggables = $$("div.poza");
		draggables.each(function(currentDraggable) { 
			new Draggable(currentDraggable, {revert:true, ghosting:true});												 
		});
		
		Droppables.add("cart", {
			hoverclass: "cartOnHover",
			onDrop: function(element) {
				var itemId = element.id.split("_");
				addToCart(itemId[1], "msg_"+itemId[1]);
			}
		});
		
		startAjax();
	}
	
	if($('cos'))
	{
		Event.observe('cos', 'click', function(event) {
			var element = $(Event.element(event));		
			if(element.name=="tip_factura" || element.name=="metoda_plata")	{
				refreshTransport(element)
			}
			if(element.name=="transport") {
				recalculeazaCos(element.value);
			}
		});
	}
}

function startAjax()
{
	if($('r_comenzi'))
		return;
	
	Ajax.Responders.register({
		onCreate: function() {
		if (Ajax.activeRequestCount > 0)
		  Element.show($('indicator'));
	  },
		onComplete: function() {
		if (Ajax.activeRequestCount == 0)
		  Element.hide($('indicator'));
	  }
	});
}

function addToCart(id, msg_id)
{
	var cantitate=1;
	
	if($('cantitate_'+id))
	{
		cantitate=parseInt($('cantitate_'+id).value);
		
		if(isNaN(cantitate) || cantitate!=$('cantitate_'+id).value || cantitate<=0)
		{
			alert("Cantitatea trebuie sa fie valoare numerica!");
			return;
		}
	}

	new Ajax.Request(url_base+'server.php?action=addToCart&'+Math.random(9999), {
		parameters: 'id=' + id+'&cantitate='+cantitate,
		onSuccess: function(resp) {
			var cartUpdate = eval('(' + resp.responseText + ')');
			var isNew = cartUpdate['cartItemDetails'][0].isNew;
			
			Element.update($('nrItems'), cartUpdate['cartItemDetails'][0].nrItems);
			
			if(cartUpdate['cartItemDetails'][0].msg!="")
			{
				Element.update($('cartMsg'), cartUpdate['cartItemDetails'][0].msg);
				new Effect.Highlight('cartMsg', {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
			}
			
			if(cartUpdate['cartItemDetails'][0].discount!="")
			{
				$('cartTotalDiscount').show();
				Element.update($('cartTotalDiscount'), 'Reducere: -' + cartUpdate['cartItemDetails'][0].discount + ' RON');
				new Effect.Highlight('cartTotalDiscount', {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
			}
			
			$(msg_id).show();
			Effect.Fade(msg_id);
			
			if($('produs_in_cos_'+id))
			{
				$('produs_in_cos_'+id).show();
			}
			
			if (isNew == 1)
			{
				Element.update($('cant_in_cos_'+id), cantitate);//+' buc.'
	
				var newItem = '<div id="cartItem_' + id + '" style="display:none" class="row">';
				newItem += '<div class="cell1" id="cartItemQty_' + id + '" valign="top">'+cantitate+'</div>';
				newItem += '<div class="cell2">' + cartUpdate['cartItemDetails'][0].title + '</div>';
				newItem += '<div class="cell3" id="cartItemPrice_' + id + '">' + cartUpdate['cartItemDetails'][0].newPrice + ' RON</div>';
				newItem += '<div class="cell4"><a href="'+url_base+'server.php?action=removeFromCart&id=' + id + '" onclick="return removeFromCart(' + id + ')">';
				newItem += 'X</a></div><div class="clear"></div></div>';
				
				if($('cartIsEmpty'))
					Element.hide($('cartIsEmpty'));

				$('cartItems').insert({bottom: newItem});
                Element.update($('cartItemQty_' + id), cantitate);
				Element.update($('cartItemPrice_' + id), cartUpdate['cartItemDetails'][0].newPrice + ' RON');
				
				Effect.Appear('cartItem_' + id, { duration: 0.5 });
				Element.update($('cartTotalAmount'), '<b>TOTAL: ' + cartUpdate['cartItemDetails'][0].total + ' RON</b>');
				//new Effect.Highlight('cartTotalAmount', {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
			}
			else
			{
				Element.update($('cant_in_cos_'+id), cartUpdate['cartItemDetails'][0].newQty);//+' buc.'
				
				Element.update($('cartItemQty_' + id), cartUpdate['cartItemDetails'][0].newQty);
				Element.update($('cartItemPrice_' + id), cartUpdate['cartItemDetails'][0].newPrice + ' RON');
				Element.update($('cartTotalAmount'), '<b>TOTAL: ' + cartUpdate['cartItemDetails'][0].total + ' RON</b>');
				
				//new Effect.Highlight('cartTotalAmount', {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
				//new Effect.Highlight('cartItemPrice_' + id, {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
				//new Effect.Highlight('cartItemQty_' + id, {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
			} 
		}
	});

	return false;
}

function removeFromCart(id)
{
	Effect.Fade("cartItem_" + id);
	new Ajax.Request(url_base+"server.php?action=removeFromCart&"+Math.random(9999), {
		parameters: "id=" + id,
		onSuccess: function(resp) {
			var cartRemove = eval('(' + resp.responseText + ')');	
			var total = cartRemove['cartDetails'][0].total;
			var discount = cartRemove['cartDetails'][0].discount;
			
			//nr items
			Element.update($('nrItems'), cartRemove['cartDetails'][0].nrItems);
			
			if(cartRemove['cartDetails'][0].msg=="")
			{
				Element.update($('cartMsg'), '');				
			}
			
			if(total==0)
			{
				Element.update($('cartItems'), '<div id="cartIsEmpty">Cosul este gol.</div>');
				Element.update($('cartTotalAmount'), '<b>TOTAL: 0.00 RON</b>');
				//new Effect.Highlight('cartIsEmpty', {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
			}
			else
			{
				if(discount=="")
				{
					Element.update($('cartTotalDiscount'), '');
				}
				else
				{	
					Element.update($('cartTotalDiscount'), 'Reducere: -' + discount + ' RON');
					//new Effect.Highlight('cartTotalDiscount', {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
				}
				
				Element.update($('cartTotalAmount'), '<b>TOTAL: ' + total + ' RON</b>');
			}
			
			//new Effect.Highlight('cartTotalAmount', {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
			$('produs_in_cos_'+id).hide();
		}
	});
	return false;
}

function emptyCart()
{
	new Ajax.Request(url_base+'server.php?action=emptyCart&'+Math.random(9999), {
		onSuccess: function(resp) {
			if (resp.responseText == 1)
			{
				Element.update($('nrItems'), '0');
				Element.update($('cartItems'), '<div id="cartIsEmpty">Cosul este gol.</div>');
				Element.update($('cartTotalDiscount'), '');
				Element.update($('cartMsg'), '');
				Element.update($('cartTotalAmount'), '<b>TOTAL: 0.00 RON</b>');
				
				//new Effect.Highlight('cartIsEmpty', {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
				//new Effect.Highlight('cartTotalAmount', {startcolor:'#CCCCCC', endcolor:'#F7F7F7', restorecolor:'#F7F7F7'});
								
				var elements=$$("div.produs_in_cos");
				
				elements.each(function(s, index) { s.hide(); });
			}
		}
	});
	return false;
}
//<----end cod cos

//@functii comune
function NewWindow(mypage, myname, w, h, scroll)
{
	var win = null;
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings ='height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable';
	win = window.open(mypage, myname, settings)
}

function modCant(id, operatie)
{
	var cantitate=parseInt($(id).value);

	if(isNaN(cantitate))
	{
		alert("Cantitatea trebuie sa fie numerica!")
		$(id).value=1;
		return;
	}
	else
	{
		if(operatie=="+")
			$(id).value=cantitate+1;
		else
		{
			if(cantitate>=1)
				$(id).value=parseInt(cantitate)-1;	
		}
	}
}

function toggleContainer(id)
{	
	if($(id).style.display=="none")
		$(id).show();
	else $(id).hide();	
}

function valideazaComanda(total_comanda, comanda_minima, url, id_form, erori_cos, username)
{	
	if(username=="")
	{
		document.location.href=link_cont;	
	}
	else if(parseInt(total_comanda)==0)
	{
		alert("Nu aveti nici un produs in cos!");
		return false;
	}
	else if(parseInt(total_comanda)<parseInt(comanda_minima))
	{
		alert("Valoarea cosului este mai mica decat comanda minima!");
		return false;
	}
	else if(parseInt(erori_cos)>0)
	{
		alert("Pentru a finaliza comanda, trebuie sa stergeti produsele din cos care nu mai sunt pe stoc!");
	}
	else
	{
		$("finalizeaza_comanda").value="1";
		$(id_form).action=url;
		$(id_form).submit();
		
		return true;
	}
}

function toggleCampuri(id, arr_ids, arr_values)
{
	var checkbox=$(id);
	
	if(checkbox.checked)
	{
		for(var i=0;i<arr_ids.length;i++)
		{
			$(arr_ids[i]).value="";
			$(arr_ids[i]).disabled=false;
		}
	}
	else
	{
		for(var i=0;i<arr_ids.length;i++)
		{
			$(arr_ids[i]).value=arr_values[i];
			$(arr_ids[i]).disabled=true;
		}
	}
}

function checkForm(arr_ids, arr_err_msg)
{
	for(i=0;i<arr_ids.length;i++)
	{
		if($(arr_ids[i]).value=="")
		{
			alert(arr_err_msg[i]);
			return false;
		}
	}
}

function doSearch(id_form, id_camp)
{	
	var search_string=$(id_camp).value;
	
	//@trim
	search_string=trim(search_string)
	
	var search_form=$(id_form);

	if(search_string.length<3)
	{
		alert("Cautarea se face dupa minim 3 caractere!");
		return false;
	}
	else
	{
		var cuvinte_split=search_string.split(" ");

		for(var i=0;i<cuvinte_split.length;i++)
		{
			if(cuvinte_split[i].length<2)
			{
				alert("Cuvintele cautate trebuie sa aiba cel putin 2 caractere! \r\n Aveti unul sau mai multe cuvinte cu lungimea de 1 caracter.");
				return false;
			}
		}
		
		search_string=search_string.replace(/-/g, "_");
		search_string=search_string.replace(/[^A-Za-z0-9_.]/g, "-");
		search_form.action=url_base+"cautare/"+search_string;
		search_form.submit();
		return true;
	}
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function afiseazaCatSec(id)
{

	if($("toggle_cat_"+id).style.display=="none")
	{
		$("toggle_cat_"+id).style.display="block";
		$("actiune_"+id).innerHTML='<a href="#" onClick="afiseazaCatSec(\''+id+'\'); return false;" class="subcategorii_secundare" style="color:#E41F15"><b>x - inchide</u></b>';		
	}
	else
	{
		$("toggle_cat_"+id).style.display="none";
		$("actiune_"+id).innerHTML='<a href="#" onClick="afiseazaCatSec(\''+id+'\'); return false;" class="subcategorii_secundare"><b>&raquo; mai multe afectiuni</b></a>';
	}
}

function textCounter(field, cntfield, maxlimit) 
{
	if(field.value.length>maxlimit) 
		field.value = field.value.substring(0, maxlimit);
	else
		cntfield.value = maxlimit - field.value.length;
}

if(paginare_box==undefined)
{
	var paginare_box=new Array();	
}

function afiseazaJumpToPage(id_box, arrow)
{			
	if(paginare_box[id_box]=="hide")
	{  
		paginare_box[id_box]="show";
		$(arrow).src=url_img_dir+"arr_down.gif";
	}
	else
	{		
		paginare_box[id_box]="hide";
		$(arrow).src=url_img_dir+"arr_up.gif";
	}
	Effect.toggle(id_box, 'slide', { duration: 0.3 })
}

function cuponMesaj(container, cupon)
{
	if(cupon!="")
		$(container).innerHTML="<span style='line-height:18px'>&nbsp;Click pe <b>'ACTUALIZEAZA COS'</b> pt a valida discountul!";
	else
		$(container).innerHTML="";
}

function actualizeazaTransport()
{
	var tip_factura=Form.getInputs('cos','radio','tip_factura').find(function(radio) { return radio.checked; }).value;
	
	alert(tip_factura);
}

//@functie bazata pe prototype care afla valoarea selectata dintr-un grup de butoane radio
function $RF(el, radioGroup) 
{ 
    if($(el).type && $(el).type.toLowerCase() == 'radio') 
    { 
        var radioGroup = $(el).name; 
        var el = $(el).form; 
    }
    else if ($(el).tagName.toLowerCase() != 'form') 
    { 
        return false; 
    } 

    var checked = $(el).getInputs('radio', radioGroup).find( 
        function(re) {return re.checked;} 
    ); 

    return (checked) ? $F(checked) : null; 
}  


function refreshTransport()
{
	var url='server_transport.php';
	var rand=Math.random(9999);
		
	tip_factura=$RF('cos', 'tip_factura'); 
	metoda_plata=$RF('cos', 'metoda_plata'); 
	
	var param='tip_factura='+tip_factura+'&metoda_plata='+metoda_plata+'&rand='+rand;
	
	var options = {
					method : 'get',
					parameters : param,
					onLoading : function()
					{
						
					},
					onComplete : showTransport					
				  }
	
	var myAjax=new Ajax.Request(url, options);
}

function showTransport(originalRequest)
{
	
	Element.hide($('fisier_localitati'));
	Element.update($('lista_transporturi'), originalRequest.responseText);	
	new Effect.Highlight('lista_transporturi', {startcolor:'#CCCCCC', endcolor:'#FFFFFF', restorecolor:'#FFFFFF'});
}

function recalculeazaCos(transport_selectat)
{
	var url='server_transport.php';
	var rand=Math.random(9999);
	var param='id_transport='+transport_selectat+'&total_cos_fara_discount='+total_cos_fara_discount+'&discount='+discount+'&rand='+rand;
	
	var options = {
					method : 'get',
					parameters : param,
					onLoading : function() 	{ },
					onComplete : actualizeazaCos					
				  }
	
	var myAjax=new Ajax.Request(url, options);
}

function actualizeazaCos(originalRequest) 
{
	var info=originalRequest.responseText;	
	var pieces=info.split("|");	
	
	var cost_transport=pieces[0];
	var nume_transport=pieces[1];
	var total_de_plata=pieces[2];
	var fisier_localitati=pieces[3];
	
	if(fisier_localitati!="")
	{
		Element.show($('fisier_localitati'));
		Element.update($('fisier_localitati'), "<a href='"+url_base+fisier_localitati+"' target='_blank'>Va rugam sa verificati inainte de a trimite comanda daca adresa de livrare se afla in raza de acoperire a curierului selectat! <b><u>Vezi lista</u>.</b></a>");
		new Effect.Pulsate('fisier_localitati', {duration:3});
	}
	else
	{
		Element.hide($('fisier_localitati'));		
	}
	
	Element.update($('nume_transport'), nume_transport);
	Element.update($('total_de_plata'), total_de_plata);
	Element.update($('transport_cost'), cost_transport);
	
	new Effect.Highlight('nume_transport', {startcolor:'#CCCCCC', endcolor:'#FFFFFF', restorecolor:'#FFFFFF'});
	new Effect.Highlight('total_de_plata', {startcolor:'#CCCCCC', endcolor:'#FFFFFF', restorecolor:'#FFFFFF'});
	new Effect.Highlight('transport_cost', {startcolor:'#CCCCCC', endcolor:'#FFFFFF', restorecolor:'#FFFFFF'});
}

function finalizeazaComanda(nume_form) 
{
	
	metoda_plata=$RF(nume_form, 'transport');
	
	if(!metoda_plata)
	{
		alert("Nu ati selectat metoda de transport!");
		return;
	}
	
	document.forms[nume_form].submit();
}

function toggleSlide(id_elem)
{
	Effect.toggle(id_elem, 'slide', { duration: 0.3 });
}

function refreshProduseRetur(id_comanda_schimbat)
{
	var id_comanda=$("r_comenzi").value;
	var id_produs=$("r_produse").value;
	
	var combo_produse=$("r_produse");	
	var combo_cantitati=$("r_cantitati");
	var motiv_defect=$("motiv_defect");
	
	if(id_comanda=="0" || id_comanda=="")
	{
		//@reset combo produse
		combo_produse.disabled=true;					
		combo_produse.length=0;
		
		var opt = document.createElement("option");			
		combo_produse.options.add(opt);						        
	    opt.value="0";   
	    opt.text="--Alege comanda--";
	    
	    //@reset combo cantitati
	    combo_cantitati.disabled=true;					
		combo_cantitati.length=0;
		
		var opt=document.createElement("option");			
		combo_cantitati.options.add(opt);						        
	    opt.value="0";   
	    opt.text="--Alege cantitatea--";
	    
	    //@motiv defect
	    motiv_defect.disabled=true;
	    motiv_defect.value="Descriere defectiune";
	       
	    return "";    
	}
	
	if(id_comanda_schimbat)
		id_produs=0;
	
	if(id_produs==0 || id_produs=="")
	{
		combo_cantitati.disabled=true;					
		combo_cantitati.length=0;
		
		var opt = document.createElement("option");		
		combo_cantitati.options.add(opt);						        
	    opt.value = "0";   
	    opt.text = "--Alege cantitatea--";
	    
	    id_produs=0;
	}
	
	var url=url_base+'server_retur.php';
	var rand=Math.random(9999);
	
	var param='refresh_combos=1&id_comanda='+id_comanda+'&id_produs='+id_produs+'&rand='+rand;
	
	var options = {
					method : 'get',
					parameters : param,
					onCreate : function() { Element.show($('indicator_retur'));	},
					onComplete : function(resp)
					{
						produse = eval('(' + resp.responseText + ')');
						
						combo_produse.length=0;
						combo_cantitati.length=0;
						
						var nr_produse=parseInt(produse["nr_produse"][0].nr);
						var cantitate_ramasa=parseInt(produse["cantitate_ramasa"][0].nr);
						
						var opt = document.createElement("option");						
						combo_produse.options.add(opt);
						
						opt.value = "0";   
	    				opt.text = "--Alege produsul--";
	    						
						for(var i=0;i<nr_produse;i++)
						{							
							var opt = document.createElement("option");					       					        
							combo_produse.options.add(opt);					
					                                           
						    opt.value = produse["produse"][i].id_produs;   
						    opt.text = produse["produse"][i].nume;	        
						}	
											
						combo_produse.value=id_produs;
												
						if(cantitate_ramasa>0)
						{
							for(var i=1;i<=cantitate_ramasa;i++)
							{
								var opt = document.createElement("option");					       
					        	combo_cantitati.options.add(opt);					
					            
						    	opt.value = i;   
						    	opt.text = i;
							}
						}
						
						combo_produse.disabled=false;
						
						if(id_produs!="" && id_produs!="0")
							combo_cantitati.disabled=false;
						else
						{
							var opt = document.createElement("option");						
							combo_cantitati.options.add(opt);						
							opt.value = "0";   
	    					opt.text = "--Alege cantitatea--";
						}
						
						if(id_produs=="" || id_produs=="0" || id_comanda=="" || id_comanda=="0")
							motiv_defect.disabled=true;
						else motiv_defect.disabled=false;

						Element.hide($('indicator_retur'));
					}
				  }
	
	var myAjax=new Ajax.Request(url, options);
}

function adaugaProdusRetur()
{
	var url=url_base+'server_retur.php';
	var rand=Math.random(9999);
	
	var param=$('produs_retur').serialize()+'&rand='+rand;
	
	var options = {
					method : 'get',
					parameters : param,
					onCreate : function() { Element.show($('indicator_lista_retur'));	},
					onComplete : function(resp)
					{
						Element.hide($('indicator_lista_retur'));
						
						var info=resp.responseText;
						var pieces=info.split("--|x|--");

					    $('mesaj_avertizare').update(pieces[0]);	
						new Effect.Highlight($('mesaj_avertizare'), {startcolor:'#cccccc', endcolor:'#ffffff', restorecolor:'#ffffff'}); 						

						if(pieces[1]!="" && pieces[1]!=undefined)
						{
							$('tabel_produse_retur').update(pieces[1]);
							new Effect.Highlight('row_'+$('r_comenzi').value+'_'+$('r_produse').value, {startcolor:'#cccccc', endcolor:'#ffffff', restorecolor:'#ffffff'});							
							
							//reseteaza formularul de adaugare produs
							try { $("r_comenzi").selectedIndex=""; } 
							catch(e) { $("r_comenzi").selectedIndex=0 }
						
							refreshProduseRetur();
						}	
					}
				  }
	
	var myAjax=new Ajax.Request(url, options);
}

function stergeProdusRetur(id_comanda, id_produs)
{
	var url=url_base+'server_retur.php';
	var rand=Math.random(9999);
	
	var param='sterge=1&id_comanda='+id_comanda+'&id_produs='+id_produs+'&rand='+rand;
	var row='row_'+id_comanda+'_'+id_produs;
	var row_line='row_line_'+id_comanda+'_'+id_produs;
	
	var options = {
					method : 'get',
					parameters : param,	
					onCreate : function() { Element.show($('indicator_lista_retur')); },			
					onComplete : function(resp)
					{					
						Element.hide($('indicator_lista_retur'));
						
						var info=resp.responseText;
						
						if(info==1)
						{							
							new Effect.Highlight(row, {startcolor:'#ff7a77', endcolor:'#ffffff', restorecolor:'#ffffff'});						
							new Effect.toggle(row, 'slide', { delay: 0.5 });
							
							Element.hide($(row_line));
						}
						else alert(info);													
					}
				  }
	
	var myAjax=new Ajax.Request(url, options);
}

function modificaCantProdusRetur(id_comanda, id_produs)
{
	var cant=$('cant_'+id_comanda+'_'+id_produs).value;
	
	var url=url_base+'server_retur.php';
	var rand=Math.random(9999);
	
	var param='modifica_cant=1&id_comanda='+id_comanda+'&id_produs='+id_produs+'&cant='+cant+'&rand='+rand;
	
	var options = {
					method : 'get',
					parameters : param,	
					onCreate : function() { Element.show($('indicator_lista_retur')); },				
					onComplete : function(resp)
					{					
						Element.hide($('indicator_lista_retur'));	
						
						var info=resp.responseText;

						if(info==1)
							new Effect.Highlight('row_'+id_comanda+'_'+id_produs, {startcolor:'#cccccc', endcolor:'#ffffff', restorecolor:'#ffffff'});
						else alert(info)												
					}
				  }
	
	var myAjax=new Ajax.Request(url, options);
}