$(document).ready(function() {
	
	/* zebra tables */
	$('#data tr:nth-child(odd)').addClass("odd");
	
	/* submit data */
	$('.submit').click(function(){
		$(this).parent().trigger("submit");
		return false;
	});
	
	/* confirm logout */
	$('#logout').click(function(){
		if(!confirm("¿Está seguro que desea salir del sistema?")) {
			return false;
		}
	});
	
	/* change submenu */
	$('#menu li a').click(function(){
		$('#menu li a').removeClass("activelink");
		$(this).addClass("activelink");
		$('#submenu li').hide();
		$('.submenu_'+$(this).attr("href")).show();
		return false;
	});
	
	/* confirm status change */
	$('.status').click(function(){
		if(!confirm("¿Está seguro que desea cambiar el status del registro seleccionado?")) {
			return false;
		}
	});
	
	/* confirm deletion */
	$('.delete').click(function(){
		if(!confirm("¿Está seguro que desea borrar el registro seleccionado?")) {
			return false;
		}
	});
	
	/* change site */
	$('#id_site').change(function(){
		self.location.href = '/manager/start/home/site?id_site='+$(this).val();
	});
	
	/* create normalixed url */
	$('.url').change(function(){
		var url = "";
		$('.url').each(function() {
			url = url + $(this).val() + " ";
		});
		url = $.trim(url);
		url = url.toLowerCase();
		url = url.replace(/á/g, 'a');
		url = url.replace(/é/g, 'e');
		url = url.replace(/í/g, 'i');
		url = url.replace(/ó/g, 'o');
		url = url.replace(/ú/g, 'u');
		url = url.replace(/ñ/g, 'n');
		url = url.replace(/[^a-z0-9\ ]/g, '');
		url = url.replace(/\ +/g, '-');
		$('#url').val(url);
	});
	
	/* submit filters */
	$('#search').click(function(){
		$(this).parent().submit();
		return false;
	});
	
	/* enable rich text editor */
	$('.fckeditor').each(function(){
		var oFCKeditor = new FCKeditor($(this).attr("id"));
		oFCKeditor.BasePath = "/public/fckeditor/";
		oFCKeditor.ToolbarSet = 'Basic';
		oFCKeditor.Height = '300';
		oFCKeditor.ReplaceTextarea();
	});
		
	/* togle content levels */
	if($('#level_1').attr("checked")) {
		$('.level_1').show();
		$('.level_2').hide();
		$('#id_section').hide();
		$('#id_category').hide();
	}
	if($('#level_2').attr("checked")) {
		$('.level_1').hide();
		$('.level_2').show();
		$('#id_section').show();
		$('#id_category').hide();
	}
	if($('#level_3').attr("checked")) {
		$('.level_1').hide();
		$('.level_2').show();
		$('#id_section').show();
		$('#id_category').show();
	}
	$('#level_1').click(function(){
		$('.level_1').show();
		$('.level_2').hide();
		$('#id_section').hide();
		$('#id_category').hide();
	});
	$('#level_2').click(function(){
		$('.level_1').hide();
		$('.level_2').show();
		$('#id_section').show();
		$('#id_category').hide();
	});
	$('#level_3').click(function(){
		$('.level_1').hide();
		$('.level_2').show();
		$('#id_section').show();
		$('#id_category').show();
	});
	
	/* togle link */
	if($('#is_link_0').attr("checked")) {
		$('#link').hide();
	}
	if($('#is_link_1').attr("checked")) {
		$('#link').show();
	}
	$('#is_link_1').click(function(){
		$('#link').show();
	});
	$('#is_link_0').click(function(){
		$('#link').hide();
	});
	
	/* load categories */
	$('#id_section').change(function(){
		$('#id_category').children("option:gt(0)").remove();
		$.getJSON("/manager/site/contents/_categories", { id_section: $(this).val() }, function(data){
			$(data).each(function(i) { 
				$('#id_category').append('<option value="'+this.id_content+'">'+this.title+'</option>');
			});
		});
	});
	
	/* TODO: calendar */
	
	$('#cancel_quote').click(function(){
		if($('#id_reason').val()!="0") {
			$('#edit').attr("action", $(this).attr("href"));
			$('#edit').submit();
		} else {
			alert('Debe seleccionar un motivo para cancelar la cotización.');
		}
		return false;
	});
	
	$('#add_speaker a.add_speaker').click(function(){
		if($('#id_speaker').val()!="0") {
			$.getJSON($(this).attr("href"), { id_speaker: $('#id_speaker').val() }, function(data){
				if(data.id_speaker==0) {
					alert('El conferenciante ya existe en la lista.');
				} else {
					var html = '';
					var next_item = parseInt($('#items').val()) + 1;
					html = html + '<tr title="'+next_item+'">';
					html = html + '<td>'+data.full_name+'<input type="hidden" name="id_speaker_'+next_item+'" id="id_speaker_'+next_item+'" value="'+data.id_speaker+'" /></td>';
					html = html + '<td>$<input type="text" name="price_'+next_item+'" id="price_'+next_item+'" value="0.00" class="money" /></td>';
					html = html + '<td>$<input type="text" name="cost_'+next_item+'" id="cost_'+next_item+'" value="0.00" class="money" /></td>';
					html = html + '<td>$<input type="text" name="total_'+next_item+'" id="total_'+next_item+'" value="0.00" class="money" readonly="readonly" /></td>';
					html = html + '<td align="center"><input type="checkbox" name="is_confirmed_'+next_item+'" id="is_confirmed_'+next_item+'" value="1" /></td>';
					html = html + '<td align="center"><a href="/manager/orders/pending/delete_speaker" title="'+data.id_speaker+'" class="delete_speaker"><img src="public/images/delete.png" width="16" height="16" alt="" /></a></td>';
					html = html + '</tr>';
					$('#cart').append(html);
					$('#items').val(next_item);
				}
			});
		} else {
			alert('Debe seleccionar un conferenciante.');
		}
		return false;
	});
	
	$('.delete_speaker').livequery('click', function() { 
		var element = $(this);
		if(confirm("¿Está seguro que desea borrar el conferenciante seleccionado?")) {
			$.post($(this).attr("href"), { id_speaker: $(this).attr("title") }, function(){
				element.parent().parent().remove();
			});
		}
		return false;
	});
	
	$('.money').livequery('change', function() { 
		$(this).val(numeric_format(this));
		var item = $(this).parent().parent().attr("title");
		var total = parseFloat(clean_amount($('#price_'+item).val())) + parseFloat(clean_amount($('#cost_'+item).val()));
		$('#total_'+item).val(total);
		numeric_format(document.getElementById('total_'+item));
	});
	$('.money').livequery('focus', function() { 
		this.select();
	});
	
	$('.print_quote').click(function(){
		var w = window.open($(this).attr("href"), 'print', 'status=0, toolbar=0, location=0, menubar=0, resizable=0, scrollbars=1, width=670, height=480');
		if (w && !w.closed) {
			w.focus();
			w.moveTo(30,50);
			w.print();
		}
		return false;
	});
	
	$('.quote_details').click(function(){
		var w = window.open($(this).attr("href"), 'print', 'status=0, toolbar=0, location=0, menubar=0, resizable=0, scrollbars=1, width=670, height=480');
		if (w && !w.closed) {
			w.focus();
			w.moveTo(30,50);
		}
		return false;
	});
	
	$('.nosend').click(function(){
		alert('Debe llenar los costos de los conferenciantes para poder enviar la cotización por correo.');
		return false;
	});
	
});


/* replace all ocurrences of char */
function replace_all(str, from, to) {
	var idx = str.indexOf(from);
	while (idx > -1) {
		str = str.replace(from,to);
		idx = str.indexOf(from);
	}
	return str;
}

/* format number */
function format_number(amount) {
	var minus = '';
	var i = parseFloat(amount);
	
	if(isNaN(i)) 
		i = 0.00; 
	if(i < 0) 
		minus = '-';
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) 
		s += '.00';
	if(s.indexOf('.') == (s.length - 2)) 
		s += '0';
		
	s = minus + s;
	return s;
}

/* re-format number */
function re_format_number(amount) {
	var minus = '';
	var delimiter = ","; 
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	
	if(isNaN(i)) 
		return '';
	if(i < 0) 
		minus = '-';
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) 
		a.unshift(n); 
	n = a.join(delimiter);
	if(d.length < 1) 
		amount = n;
	else 
		amount = n + '.' + d;

	amount = minus + amount;
	return amount;
}

/* format as numeric (double) */
function numeric_format(el) {
	var output = '0.00';
	var num = el.value;
	var regexnum = /(^\d+$)|(^\d+\.\d+$)/;
	
	num = replace_all(num,",","");
	
	if (regexnum.test(num)){
		output = format_number(num);
		output = re_format_number(output);
	}
	el.value = output;
}

/* cleans an amount */
function clean_amount(val) {
	var num = val;
	num = num.replace("$","");
	num = num.replace("%","");
	num = replace_all(num,",","");
	return num;
}