function stripNonNumeric(str) {
	str += '';
	var rgx = /^\d|\.|-$/;
	var out = '';
	for(var i = 0; i < str.length; i++) {
		if(rgx.test(str.charAt(i))) {
			if(!((str.charAt(i) == '.' && out.indexOf('.') != -1) || (str.charAt(i) == '-' && out.length != 0))) {
				out += str.charAt(i);
			}
		}
	}
	return out;
}

jQuery.fn.nTip = function() {
	$(document.createElement('div')).attr('id', 'nTipWrapper').appendTo('body');
	$(this).each(function(){
		var tooltipEl=$(this);
		tooltipEl.data('title', tooltipEl.attr('title')).removeAttr('title');
		tooltipEl.hover(function(e){
			$('#nTipWrapper').empty().html(tooltipEl.data('title')).css({
				left:e.pageX+20,
				top:e.pageY+20
			}).show();
			tooltipEl.bind('mousemove.nTip', function(el){
				if( Math.round($(window).width()/2) > el.pageX ) {
					$('#nTipWrapper').css({
						marginLeft:0
					});
				} else {
					$('#nTipWrapper').css({
						marginLeft:-$('#nTipWrapper').outerWidth()-20
					})
				}
				$('#nTipWrapper').css({
					left:el.pageX+20,
					top:el.pageY+20
				})
			});
		}, function(){
			tooltipEl.unbind('mousemove.nTip');
			$('#nTipWrapper').empty().hide();
		});
	});
};

$(document).ready(function() {
	$('a.blank, ul.parteneri li a').attr('target', '_blank');
	
	$('.nTip').nTip();
	if($('.prodgallery').size()>0) $('a.galerie').lightBox();
	
	$('#cauta').submit(function() {
		var cauta = $('input[name="cauta_text"]').val();
		if(cauta.length < 3) alert('Va rugam introduceti minim 3 caractere pentru a continua cautarea.')
		else return true;
		return false;
	});
	
	$('a.te').each(function(){
		var th = $(this);
		e = th.attr('rel').replace('/','@');
		th.attr('href', 'mailto:'+e).removeAttr('rel');
		th.text(e);
	});
	
	$('.cat li a').click(function() {
		var th = $(this).next().next();
		var vstyle = th.attr('style');
		
		if(th.html() != null) {
			if(vstyle != undefined) vstyle = vstyle.toString().toLowerCase();
			
			if(vstyle == '' || vstyle == undefined || vstyle == 'display: none' || vstyle == 'display: none;') th.show();
			else th.hide();
			return false;
		}
	});
	
	
	
	
	
	$('.produs a.cumpprod, .detalii_produs a.cump').click(function() {
		var th = $(this);
		if(th.hasClass('stoc0')) {
			alert('Acest produs nu mai este pe stoc.');
		} else {
			var id = th.attr('href').split('/')[5];
			
			var produs = $('.produs_'+id);
			var cos_box = $('.cos_box');
			
			$('<div><img src="'+produs.find('img').attr('src')+'" alt="" /></div>').css({
						width:produs.find('img').width(),
						height:produs.find('img').height(),
						position:'absolute',
						top:produs.offset().top,
						left:produs.offset().left+15,
						opacity:0.5
					}).appendTo('body').animate({
						width:cos_box.innerWidth(),
						height:cos_box.innerHeight(),
						top:cos_box.offset().top,
						left:cos_box.offset().left+15 
					}, 'slow').animate({
							width:cos_box.innerWidth(),
							height:cos_box.innerHeight(),
							opacity:0},
					'fast', function() {
						var eq0 = cos_box.find('span').eq(0);
						var totaleq0 = parseInt(eq0.html().split(' ')[0])+1;
						eq0.html(totaleq0+' '+(totaleq0 == 1 ? 'produs' : 'produse')+' in cos');
						
						var eq1 = cos_box.find('span').eq(1);
						var totaleq1 = parseInt(eq1.html().split(' ')[0]);
						
						if(produs.find('.pretprod').size()>0) totaleq1 += parseInt(produs.find('.pretprod').html().split(' ')[1]);
						else totaleq1 += parseInt(produs.find('.pret').html().split(' ')[1]);
						eq1.html(totaleq1+' RON');
						
						$(this).remove();
						$.get('server.php?action=getCos&id='+id+'&do=adauga&personalizare='+($('textarea[name="cos_personalizare"]').size()>0 ? $('textarea[name="cos_personalizare"]').val() : ''));
					});
		}
		
		return false;
	});
	
	
	$('#cos tr').not(':first, :last').each(function() {
		var th = $(this);
		
		var id		= th.find('.sterge a').attr('href').split('sterge-')[1];
		var pretu	= parseInt(th.find('.pretu').text().split(' ')[0]);
		var prett	= parseInt(th.find('.total').text().split(' ')[0]);
		
		th.find('.inpcostxt').keyup(function() {
			var th2 = $(this);
			var cantitate = th2.val();
			var stoc = parseInt(th2.parent().prev().attr('class').split('stoc_')[1]);
			
			if(cantitate > stoc) {
				alert('Nu puteti comanda '+cantitate+' produse de acest tip deoarece\npe stoc mai sunt doar '+stoc+'.');
				th2.val(stoc);
				cantitate = stoc;
			}
			
			th.find('.total').html(cantitate*pretu+' RON');
			
			var total = cnt = 0;
			$('#cos tr').not(':first, :last').each(function() {
				cnt += parseInt($(this).find('.inpcostxt').val());
				total += parseInt($(this).find('.total').text().split(' ')[0]);
			});
			$('#cos tr:last td').html(total+' RON');
			
			var cos_box = $('.cos_box');
			cos_box.find('span').eq(0).html(cnt+' '+(cnt == 1 ? 'produs' : 'produse')+' in cos');
			cos_box.find('span').eq(1).html(total+' RON');
			
			if(cantitate != '' && cantitate != 0) $.get('server.php?action=getCos&id='+id+'&cantitate='+cantitate+'&do=update');
		});
	});
	
	
	$('.inpcostxt').keyup(function() {
		var _t = $(this);
		var val = _t.val();
		_t.val(val != '' ? (val.substr(0,1) == 0 ? '' : stripNonNumeric(val)) : '');
	});
	
	
	$('td.sterge a').click(function() {
		if(confirm('Esti sigur ca vrei sa stergi produsul din cos?')) {
			var th = $(this);
			th.parent().parent().fadeOut().remove();
			
			$('#cos tr').removeClass('striped');
			$('#cos tr:not(:first):not(:last):odd').addClass('striped');
			
			var total = 0;
			$('#cos tr').not(':first, :last').each(function() { total += parseInt($(this).find('.total').text().split(' ')[0]); });
			$('#cos tr:last td').html(total+' RON');
			
			var cos_box = $('.cos_box');
			var eq0 = cos_box.find('span').eq(0);
			var totaleq0 = parseInt(eq0.html().split(' ')[0]);
			var cantitate = th.parent().parent().find('input.inpcostxt').val();
			var totaleq0t = totaleq0-cantitate;
			eq0.html(totaleq0t+' '+(totaleq0t == 1 ? 'produs' : 'produse')+' in cos');
			
			var eq1 = cos_box.find('span').eq(1);
			var totaleq1 = parseInt(eq1.html().split(' ')[0]);
			var totala = parseInt(th.parent().parent().find('.pretu').text().split(' ')[0])*cantitate;
			eq1.html((totaleq1-totala)+' RON');
			
			$.get('server.php?action=getCos&id='+th.attr('href').split('sterge-')[1]+'&do=delete');
			if($('#cos td.sterge a').length == 0) window.location.href = $('#cos').attr('action').replace('/finalizeaza', '');
		}
		return false;
	});
	
	
	$('.listare_adrese .act').find('a:last').each(function() {
		$(this).click(function() {
			if($(this).attr('class') == 'doNotDelete') {
				alert('Nu puteti sterge aceasta adresa deoarece nu aveti alta configurata.\nAdaugati o adresa noua apoi apasati pe butonul sterge.');
			} else if(confirm('Esti sigur ca vrei sa stergi?')) return true;
			
			return false;
		});
	});
	
	$('#cos button').click(function() {
		var total = parseInt($('#cos tr:last td').text().split(' ')[0]);
		var min = parseInt($('#c_min').attr('class').split('c_')[1]);
		
		if(total < min) alert('Comanda minima este de '+min+' RON');
		else {
			if($('input[name="cos_modalitate_plata"]:checked').val() == undefined || $('input[name="cos_adresa_livrare[]"]:checked').val() == undefined || $('input[name="cos_modalitate_livrare"]:checked').val() == undefined || $('input[name="cos_adresa_facturare"]:checked').val() == undefined) {
				alert('Pentru a finaliza comanda, va rugam selectati\nModalitatea de plata, Adresa livrare si Modalitatea de livrare.');
			} else return true;
		}
		
		return false;
	});
	
	if($('.cosp').size()>0) {
		$('.cosp').click(function() {
			if(confirm('Aveti produse in cos!\nSunteti sigur ca nu doriti sa finalizati comanda?')) return true;
			return false;
		});
	}
	
	/*start salvare cos*/
	if($('textarea[name="cos_informatii"]').size()>0) {
		var th = $('textarea[name="cos_informatii"]');
		th.keyup(function(){$.get('/server.php?cos_informatii='+th.val()+'&action=updCosInformatii')});
	}
	
	if($('input[name="cos_modalitate_plata"]').size()>0) {
		$('input[name="cos_modalitate_plata"]').click(function() {
			$.get('/server.php?modalitate_plata='+$(this).val()+'&action=updCosModalitatePlata');
		});
	}
	
	if($('input[name="cos_adresa_livrare[]"]').size()>0) {
		$('input[name="cos_adresa_livrare[]"]').click(function() {
			var adr = new Array();
			$('input[name="cos_adresa_livrare[]"]:checked').each(function(i){adr[i] = $(this).val()});
			$.get('/server.php?adresa_livrare='+adr+'&action=updCosAdresaLivrare');
		});
	}
	
	if($('input[name="cos_modalitate_livrare"]').size()>0) {
		$('input[name="cos_modalitate_livrare"]').click(function() {
			$.get('/server.php?modalitate_livrare='+$(this).val()+'&action=updCosModalitateLivrare');
		});
	}
	
	if($('input[name="cos_adresa_facturare"]').size()>0) {
		$('input[name="cos_adresa_facturare"]').click(function() {
			$.get('/server.php?adresa_facturare='+$(this).val()+'&action=updCosAdresaFacturare');
		});
	}
	/*end salvare cos*/
	
	if($('#adrese_livrare').size()>0) {
		$('#adrese_livrare').tableDnD({
		    onDragClass: 'myDragClass',
		    onDrop: function(table, row) {
	            var rows = table.tBodies[0].rows;
	            var debugStr = '';
	            for (var i=0; i<rows.length; i++) debugStr += rows[i].id+'_';
		        $('#adrese_livrare tr').removeClass('even');
	            $('#adrese_livrare tr:not(:first):odd').addClass('even');
				$.get('/server.php?id='+debugStr.substring(0, debugStr.length-1)+'&db=adrese_livrare&action=orderAdrese');
		    }
		});
	}
	
	
	
});
