//BUSQUEDA DE TABCATDIA
var formaTABCATDIA = null;
var panelTABCATDIA = null;
var intMode = 100;
var idTienda = null, idProveedor=null;
var GridStoreTABCATDIA = null;
var email = "";

function TABCATDIA_Constructor(){
	idTab = 'TABCATDIA';
	
	var txtBoton = "";
		
	panelTABCATDIA = new Ext.Panel({
						width:'100%',
						height: '80%',
						autoScroll:false,
						disabled: false
	});
	
	formaTABCATDIA = new Ext.FormPanel({
		labelAlign: 'top',
        labelWidth: 75,
        frame:true,
		bodyStyle:'padding:5px 5px 0',
        width: '100%',
		autoHeight: true,
        items: [
				panelTABCATDIA
			   ]
    });
	
	$("#divCatDiagnosticos").empty();
	formaTABCATDIA.render("divCatDiagnosticos");

	panelTABCATDIA.load({
		url: "vistas/tabCatDiagnosticos.php",
		params: {intMode:0, campo:'', order:''}, // or a URL encoded string
		callback: function(data){   
						
			$("#btnInsertar" + idTab).click(function() {
				AddEditTABCATDIA(1);
			});
			
			getDataTABCATDIA(1);
						
		},
		discardUrl: false,
		nocache: false,
		text: 'Loading...',
		timeout: 30,
		scripts: false
	});
}

function cargarTipoDiagnosticos(selObj){
	var strUrl1 = "data/comboboxes.php?method=tiposDiagnosticos&intEmpresa="+ objUsuario.empresa +"&rnd="+ Math.random();
	
	$.get(strUrl1, function(dataNew){
		var data = $.parseJSON(dataNew);
		var arrProductosCategorias = data.Items;
		
		selObj.empty();
		for (var i=0; i<arrProductosCategorias.length; i++) {
		  selObj.append('<option value="' + arrProductosCategorias[i].id + '">' + arrProductosCategorias[i].label + '</option>');
		}
		
	});
}

function getDataTABCATDIA(intCase, strLetra){
		
	if(objUsuario.empresa!=null){
		
		$( "#divDiagnosticosGrid" ).html("<div style='width:200px; margin-top:25px; margin-left:auto; margin-right:auto;'><img src='css/images/loading.gif'/></div>");
		
		var strUrl = "data/catDiagnosticos.php?intEmpresa="+ objUsuario.empresa +"&intCase="+ intCase +"&method=consultar&rnd="+ Math.random();
		if(strLetra!=null){
			strUrl += "&strLetra="+ strLetra;
		}

		// create the Data Store
		GridStoreTABCATDIA = new Ext.data.JsonStore({
			root: 'Items',
			totalProperty: 'totalCount',
			idProperty: 'intDiagnostico',
			remoteSort: true,
			/*fields: [
				'title', 'forumtitle', 'forumid', 'author',
				{name: 'replycount', type: 'int'},
				{name: 'lastpost', mapping: 'lastpost', type: 'date', dateFormat: 'timestamp'},
				'lastposter', 'excerpt'
			],*/
			fields: [ 'intDiagnostico', 'strDiagnostico', 'strClave', 'datFechaAlta', 'intFavorito' ],
			// load using script tags for cross domain, if the data in on the same domain as
			// this page, an HttpProxy would be better (ScriptTagProxy)
			proxy: new Ext.data.HttpProxy({
				url: strUrl
			})
		});
		//GridStoreTABCATDIA.setDefaultSort('intDiagnostico', 'asc');
	
		$( "#divDiagnosticosGrid" ).html("");

		var heightDoc = $(document).height();
		console.log("heightDoc: "+ heightDoc);
		heightDoc = heightDoc - 140;

		var grid = new Ext.grid.GridPanel({
		renderTo: document.getElementById("divDiagnosticosGrid"),
		frame: true,
		title: 'Diagnosticos',
		width:'100%',
		height: heightDoc,
		store: GridStoreTABCATDIA,
		trackMouseOver:false,
		disableSelection:true,
		loadMask: true,
		columns: [
		  {header: "Id", width: 60, dataIndex: 'intDiagnostico', sortable: true},
		  {header: "Diagnostico", width: 340, dataIndex: 'strDiagnostico', sortable: true, 
			renderer: function (value, metaDat, record) {
				//var newValue = "<a href='javascript: AddEditTABCATDIA(2,"+ record.data["intDiagnostico"] +");' target='_blank' style='color:#C60;'>"+ value +"</a>";
				var newValue =  value ;
				return newValue;
			} 
		  },
		  {header: "Clave", width: 90, dataIndex: 'strClave', sortable: true},
		  {header: "Favorito", width: 80, dataIndex: 'intFavorito', sortable: true, 
			renderer: function (value, metaDat, record) {
				if(value==0){
					var newValue = "<a href='javascript: setFavoritoDia("+ record.data["intDiagnostico"] +", 1);' target='_blank' style='color:#C60;'><img src='images/estrellitaOff.png'></a>";
				}else if(value==1){
					var newValue = "<a href='javascript: setFavoritoDia("+ record.data["intDiagnostico"] +", 0);' target='_blank' style='color:#C60;'><img src='images/estrellitaOn.png'></a>";
				}
				return newValue;
			}
		  }
		  /*,{header: "Fecha Alta", width: 120, dataIndex: 'datFechaAlta', sortable: true}*/
		],
		bbar: new Ext.PagingToolbar({
			pageSize: 20,
			store: GridStoreTABCATDIA,
			displayInfo: true,
			displayMsg: 'Mostrando {0} - {1} de {2}',
			emptyMsg: "0 Registros que mostrar"
			/*,items:[
				'-', {
				pressed: true,
				enableToggle:true,
				text: 'Ver Preview',
				cls: 'x-btn-text-icon details',
				toggleHandler: function(btn, pressed){
					var view = grid.getView();
					view.showPreview = pressed;
					view.refresh();
				}
			}]*/
		})
		});
		
		// trigger the data store load
		GridStoreTABCATDIA.load({params:{start:0, limit:20}});
	
		
	}else{
		alert("Todos los campos son requeridos");
	}
}

function limpiarTextboxesTABCATDIA(){
	$( "#dialog-diagnostico" ).find( "#txtIntDiagnostico" ).val('');
	$( "#dialog-diagnostico" ).find( "#txtDiagnostico" ).val('');
	$( "#dialog-diagnostico" ).find( "#txtClave" ).val('');
	//$( "#dialog-diagnostico" ).find( "#intFavorito" ).val('');

}

function AddEditTABCATDIA(intCase, id){
	$( "#divLoading" ).css({ "visibility":"visible", "display":"inherit" });
	var strUrl1 = "vistas/dialog-diagnostico.php?rnd="+ Math.random();
	
	$.get(strUrl1, function(data){
		
		$("#divCatDiagnosticos").html(data);					

		setTimeout(function(){ cargarDataDialogTABCATDIA(intCase, id); }, 1000);
	});
}

//function muestra_oculta(id){
//	var combo = $( "#dialog-diagnostico" ).find( "#selectTipoUsuario" ).val();
//		if(combo == 1 && document.getElementById){ //se obtiene el id
//		var el = document.getElementById(id); //se define la variable "el" igual a nuestro div
//		el.style.display = (el.style.display == 'none') ? 'block' : 'none'; //damos un atributo display:none que oculta el div
//		}
//		}
//		window.onload = function(){/*hace que se cargue la función lo que predetermina que div estará oculto hasta llamar a la función nuevamente*/
//		muestra_oculta('nombreConsul');/* "contenido_a_mostrar" es el nombre que le dimos al DIV */
//}

function cargarDataDialogTABCATDIA(intCase, id){
	
	$( "#btnGuardar" + idTab).unbind( "click" );
	$( "#btnCancelar" + idTab).unbind( "click" );
	$( "#btnEliminar" + idTab).unbind( "click" );
		
	if(intCase===1){
		
		limpiarTextboxesTABCATDIA();

		$( "#btnGuardar" + idTab ).click(function() {
			abcTABCATDIA(1);
		});
		
		$( "#btnCancelar" + idTab ).click(function() {
			TABCATDIA_Constructor();
		});
		
		$( "#btnEliminar" + idTab ).css({ visibility:"hidden" });
				
	}else{
		
		var record = null;

		GridStoreTABCATDIA.each(function(rd){  
			if( parseInt(id) == parseInt(rd.data["intDiagnostico"]) ){
				record = rd;
			}
		});
		
		if(record != null){

			$( "#dialog-diagnostico" ).find( "#txtIntDiagnostico" ).val(record.data["intDiagnostico"]);
			$( "#dialog-diagnostico" ).find( "#txtDiagnostico" ).val(record.data["strDiagnostico"]);
			$( "#dialog-diagnostico" ).find( "#txtClave" ).val(record.data["strClave"]);
			if( parseInt(record.data["intFavorito"])==0 ){
				$( "#dialog-diagnostico" ).find( "#imgFavorito" ).prop("src", "images/estrellitaOff.png");
				$( "#dialog-diagnostico" ).find( "#intFavorito" ).val(0);
			}else if( parseInt(record.data["intFavorito"])==1 ){
				$( "#dialog-diagnostico" ).find( "#imgFavorito" ).prop("src", "images/estrellitaOn.png");
				$( "#dialog-diagnostico" ).find( "#intFavorito" ).val(1);
			}

			$( "#btnGuardar"  + idTab).click(function() {
				abcTABCATDIA(2);
			});
			
			$( "#btnCancelar" + idTab ).click(function() {
				TABCATDIA_Constructor();
			});
			
			$( "#btnEliminar" + idTab).css({ visibility:"visible" });
			$( "#btnEliminar" + idTab).click(function() {
				abcTABCATDIA(3);
			});
				
		}
	}
	$( "#divLoading" ).css({ "visibility":"hidden", "display":"none" });
}

function abcTABCATDIA(intCase){

	if($( "#dialog-diagnostico" ).find( "#txtDiagnostico" ).val() != "" && $( "#dialog-diagnostico" ).find( "#txtClave" ).val() != "" ){
						
		var sQuery = "data/catDiagnosticos.php?method=modificar&intMode="+ intCase 
		+"&intDiagnostico="+ $( "#dialog-diagnostico" ).find( "#txtIntDiagnostico" ).val() 
		+"&txtDiagnostico="+ encodeURIComponent( $( "#dialog-diagnostico" ).find( "#txtDiagnostico" ).val() )
		+"&txtClave="+ encodeURIComponent( $( "#dialog-diagnostico" ).find( "#txtClave" ).val() )
		+"&intFavorito="+ $( "#dialog-diagnostico" ).find( "#intFavorito" ).val() 
		+"&intEmpresa="+ objUsuario.empresa +"&rnd="+ Math.random();
	
		console.log(sQuery);

		$.post(sQuery, function(dataNew){
			
			TABCATDIA_Constructor();
	
		});
		
	}else{
		alert("Todos los campos son requeridos.");
	}
}

function setFavoritoDia(intDiagnostico, intFavorito){
	var sQuery = "data/catDiagnosticos.php?method=modificar&intMode=4&intDiagnostico="+ intDiagnostico
	+"&intFavorito="+ intFavorito
	+"&intEmpresa="+ objUsuario.empresa +"&rnd="+ Math.random();

	$.post(sQuery, function(dataNew){
		
		TABCATDIA_Constructor();

	});
}

function changeFavoritoDia(){
	var intFavorito = $( "#dialog-diagnostico" ).find( "#intFavorito" ).val();
	if(intFavorito==0){
		$( "#dialog-diagnostico" ).find( "#imgFavorito" ).prop("src", "images/estrellitaOn.png");
		$( "#dialog-diagnostico" ).find( "#intFavorito" ).val(1);
	}else if(intFavorito==1){
		$( "#dialog-diagnostico" ).find( "#imgFavorito" ).prop("src", "images/estrellitaOff.png");
		$( "#dialog-diagnostico" ).find( "#intFavorito" ).val(0);
	}
}

function buscarPorDiagnostico(strTermino){
	if(strTermino==""){
		getDataTABCATDIA(1, 'A');
	}else{
		getDataTABCATDIA(2, strTermino);
	}
}

