//@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()
{
	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)
{
	new Ajax.Request(url_base+'server.php?action=addToCart&'+Math.random(9999), {
		parameters: 'id=' + id,
		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'});
			}
			
			if (isNew == 1)
			{
				$(msg_id).show();
				Effect.Fade(msg_id);
				var newItem = '<div id="cartItem_' + id + '" style="display:none" class="row">';
				newItem += '<div class="cell1" id="cartItemQty_' + id + '" valign="top">1</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'));

				new Insertion.Bottom('cartItems', newItem);	
				
				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
			{
				$(msg_id).show();
				Effect.Fade(msg_id);
				
				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'});
		}
	});
	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'});
			}
		}
	});
	return false;
}
//end codul pt 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;
	var search_form=$(id_form);

	if(search_string.length<3)
	{
		alert("Cautarea se face dupa minim 3 caractere!");
		return false;
	}
	else
	{
		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 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($(nume_form).getInputs('radio', 'transport') == '')
    {
        document.forms[nume_form].submit();
        return false;
    }

	if(!metoda_plata)
	{
		alert("Nu ati selectat metoda de transport!");
		return false;
	}
	
	document.forms[nume_form].submit();
}

function toggleSlide(id_elem)
{
	Effect.toggle(id_elem, 'slide', { duration: 0.3 });
}