//BUSQUEDA DE TABCATHOS
var formaTABCATHOS = null;
var panelTABCATHOS = null;
var intMode = 100;
var idTienda = null, idProveedor=null;
var GridStoreTABCATHOS = null;
var email = "";

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

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

/*function cargarTipoHospitales(selObj){
	var strUrl1 = "data/comboboxes.php?method=tiposHospitales&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 getDataTABCATHOS(intCase, strLetra){
		
	if(objUsuario.empresa!=null){
		
		$( "#divHospitalesGrid" ).html("<div style='width:200px; margin-top:25px; margin-left:auto; margin-right:auto;'><img src='css/images/loading.gif'/></div>");
		
		var strUrl = "data/catHospitales.php?intEmpresa="+ objUsuario.empresa +"&intCase="+ intCase +"&method=consultar&rnd="+ Math.random();
		if(strLetra!=null){
			strUrl += "&strLetra="+ strLetra;
		}

		// create the Data Store
		GridStoreTABCATHOS = new Ext.data.JsonStore({
			root: 'Items',
			totalProperty: 'totalCount',
			idProperty: 'intHospital',
			remoteSort: true,
			/*fields: [
				'title', 'forumtitle', 'forumid', 'author',
				{name: 'replycount', type: 'int'},
				{name: 'lastpost', mapping: 'lastpost', type: 'date', dateFormat: 'timestamp'},
				'lastposter', 'excerpt'
			],*/
			fields: [ 'intHospital', 'strNombre', '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
			})
		});
		//GridStoreTABCATHOS.setDefaultSort('intHospital', 'asc');
	
		$( "#divHospitalesGrid" ).html("");

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

		var grid = new Ext.grid.GridPanel({
		renderTo: document.getElementById("divHospitalesGrid"),
		frame: true,
		title: 'Hospitales',
		width:'100%',
		height: heightDoc,
		store: GridStoreTABCATHOS,
		trackMouseOver:false,
		disableSelection:true,
		loadMask: true,
		columns: [
		  {header: "Id", width: 60, dataIndex: 'intHospital', sortable: true},
		  {header: "Hospital", width: 340, dataIndex: 'strNombre', sortable: true, 
			renderer: function (value, metaDat, record) {
				//var newValue = "<a href='javascript: AddEditTABCATHOS(2,"+ record.data["intHospital"] +");' 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["intHospital"] +", 1);' target='_blank' style='color:#C60;'><img src='images/estrellitaOff.png'></a>";
				}else if(value==1){
					var newValue = "<a href='javascript: setFavoritoDia("+ record.data["intHospital"] +", 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: GridStoreTABCATHOS,
			displayInfo: true,
			displayMsg: 'Mostrando {0} - {1} of {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
		GridStoreTABCATHOS.load({params:{start:0, limit:20}});
	
		
	}else{
		alert("Todos los campos son requeridos");
	}
}

function limpiarTextboxesTABCATHOS(){
	$( "#dialog-hospital" ).find( "#txtIntHospital" ).val('');
	$( "#dialog-hospital" ).find( "#txtHospital" ).val('');
	$( "#dialog-hospital" ).find( "#txtClave" ).val('');
	//$( "#dialog-hospital" ).find( "#intFavorito" ).val('');

}

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

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

//function muestra_oculta(id){
//	var combo = $( "#dialog-hospital" ).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 cargarDataDialogTABCATHOS(intCase, id){
	
	$( "#btnGuardar" + idTab).unbind( "click" );
	$( "#btnCancelar" + idTab).unbind( "click" );
	$( "#btnEliminar" + idTab).unbind( "click" );
		
	if(intCase===1){
		
		limpiarTextboxesTABCATHOS();

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

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

			$( "#dialog-hospital" ).find( "#txtIntHospital" ).val(record.data["intHospital"]);
			$( "#dialog-hospital" ).find( "#txtHospital" ).val(record.data["strNombre"]);
			/*$( "#dialog-hospital" ).find( "#txtClave" ).val(record.data["strClave"]);
			if( parseInt(record.data["intFavorito"])==0 ){
				$( "#dialog-hospital" ).find( "#imgFavorito" ).prop("src", "images/estrellitaOff.png");
				$( "#dialog-hospital" ).find( "#intFavorito" ).val(0);
			}else if( parseInt(record.data["intFavorito"])==1 ){
				$( "#dialog-hospital" ).find( "#imgFavorito" ).prop("src", "images/estrellitaOn.png");
				$( "#dialog-hospital" ).find( "#intFavorito" ).val(1);
			}*/

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

function abcTABCATHOS(intCase){

	if($( "#dialog-hospital" ).find( "#txtHospital" ).val() != ""  ){ /*&& $( "#dialog-hospital" ).find( "#txtClave" ).val() != ""*/
						
		var sQuery = "data/catHospitales.php?method=modificar&intMode="+ intCase 
		+"&intHospital="+ $( "#dialog-hospital" ).find( "#txtIntHospital" ).val() 
		+"&txtHospital="+ encodeURIComponent( $( "#dialog-hospital" ).find( "#txtHospital" ).val() )
		+"&selectPais="+ $( "#dialog-hospital" ).find( "#selectPais" ).val() 
		+"&selectEstado="+ $( "#dialog-hospital" ).find( "#selectEstado" ).val() 
		+"&selectMunicipio="+ $( "#dialog-hospital" ).find( "#selectMunicipio" ).val() 
		+"&txtColonia="+ $( "#dialog-hospital" ).find( "#txtColonia" ).val() 
		+"&txtCalle="+ $( "#dialog-hospital" ).find( "#txtCalle" ).val() 
		+"&txtNumExt="+ $( "#dialog-hospital" ).find( "#txtNumExt" ).val() 
		+"&txtNumInt="+ $( "#dialog-hospital" ).find( "#txtNumInt" ).val() 
		+"&txtCodigoPostal="+ $( "#dialog-hospital" ).find( "#txtCodigoPostal" ).val() 
		+"&txtTelefono="+ $( "#dialog-hospital" ).find( "#txtTelefono" ).val() 
		+"&intEmpresa="+ objUsuario.empresa +"&rnd="+ Math.random();
	
		/*+"&txtClave="+ encodeURIComponent( $( "#dialog-hospital" ).find( "#txtClave" ).val() )
		+"&intFavorito="+ $( "#dialog-hospital" ).find( "#intFavorito" ).val() 	console.log(sQuery);*/
		
		console.log(sQuery);
		
		$.post(sQuery, function(dataNew){
			
			TABCATHOS_Constructor();
	
		});
		
	}else{
		alert("Todos los campos son requeridos.");
	}
}

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

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

	});
}

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

function buscarPorHospital(strTermino){
	if(strTermino==""){
		//getDataTABCATHOS(1, 'A');
		getDataTABCATHOS(1, '');
	}else{
		getDataTABCATHOS(2, strTermino);
	}
}

