//
// RMSchedulerController
//
// Created by Alonso Villanueva

@import <Foundation/Foundation.j>
@import <AppKit/AppKit.j>
@import <MapKit/MKMapView.j>
@import <AppKit/CPTextField.j>
@import <AppKit/CPApplication.j>
@import <Foundation/CPURLRequest.j>
@import "AppController.j"
@import "JasperSoftReporter.j"



// var appCont; //comment 2017-03-03





@implementation RMSReportOrganizationController : RMControllerObject {



	CPPanel repoPane;

	id orgaPopu;
	id filtText;
	id orgaArra;
	id custArra;
	id custBackArra;
	id dateStarText;
	id dateEndText;
	id datePickStarPane;
	id datePickEndPane;
	id idenOrga;
	id nameOrga;
    id emaiOrga;
    id jasp;
    
   	CPPanel geneRepoPane;
   	id emaiText;
   	
   	CPTableView locaTabl;
   	CPArray locaArra;
   	id locaMenu;
   	
   	CPTableView persTabl;
   	CPArray persArra;
   	id persMenu;

   	CPTableView finaTabl;
   	id finaArra;
  	id finaMenu;
  	
  	id dictRepo;
  	id urlRepo;
  	
  	id emaiComm;
  	id repoComm;
  	
  	id ordePopu;

}



- (id) init:(id)paraAppCont {
	[super init];
 	
 	appCont = paraAppCont;
	dataBase = [appCont getDataBase];
	//alert("db init reports= " + [appCont getDataBase]);
	repoPane = geneRepoPane =  NULL;
	orgaPopu = NULL;
	filtText = NULL;
	orgaArra = NULL;
	dateStarText = emaiText = NULL;
	idenOrga = nameOrga = "";
	persTabl = persArra = NULL;
	ordePopu = NULL;
	finaArra = [CPArray array];
	//jasp = [[JasperSoftReporter alloc] init];
	jasp = [[JasperSoftReporter alloc] init:appCont];	
	[jasp organizationCodeSet:[appCont getOrgaCode] ];
	[jasp organizationIdSet:[appCont organizationId] ];
	[jasp cgiSetHost:[appCont getcgiHost] server:[appCont getcgiServ]];
	dictRepo = NULL;
	urlRepo = NULL;
	emaiComm = repoComm = "";
	
	return self;
}




- (void)  applicationQuit {

	if ( repoPane ) {
		[repoPane orderOut:0];
		[repoPane release];
	}	
	
	if (orgaPopu)     { [orgaPopu  release];}
	if (filtText)     { [filtText  release];}
	if (orgaArra)     { [orgaArra  release];}
	if (dateStarText) { [dateStarText  release];}
	if (dateEndText)  { [ dateEndText release];}
	if (datePickStarPane) { [datePickStarPane  release];}
	if (datePickEndPane)  { [datePickEndPane  release];}
	if (idenOrga) { [idenOrga  release];}
	if (nameOrga) { [ nameOrga release];}
	if (emaiOrga) { [emaiOrga  release];}
	
	if ( geneRepoPane ) {
		[geneRepoPane orderOut:0];
		[geneRepoPane release];
	}
	
	if (emaiText) { [emaiText  release];}
	if (locaTabl) { [locaTabl  release];}
	if (locaArra) { [locaArra  release];}
	if (persTabl) { [persTabl  release];}
	if (locaMenu) { [locaMenu  release];}
	if (persArra) { [persArra  release];}
	if (finaTabl) { [ finaTabl release];}
	if (persMenu) { [persMenu  release];}
	if (finaArra) { [finaArra  release];}
	if (finaMenu) { [ finaMenu release];}
	if (dictRepo) { [dictRepo  release];}
	if (urlRepo)  { [urlRepo  release]; }
	if (emaiComm) { [emaiComm  release];}
	if (repoComm) { [repoComm  release];}
	if (custBackArra) { [custBackArra  release];}
	if (custArra) { [custArra  release];}
	
	[jasp applicationQuit];
	if (jasp) { [jasp  release];}
}



- (void) addFromLocation:(id)sender {	

	var indeArra = [locaTabl selectedRowIndexes];
 	var coun     = [indeArra count];
		
	while ( coun >= 1 ){
			var firs = [indeArra firstIndex];
		    var valu = [ [locaArra objectAtIndex:firs] valueList];
		    var tempEmailoca = valu[1];
		    [finaArra addObject:@"" + tempEmailoca];
		    [indeArra removeIndex:firs];
		    coun --;
	}

	[finaTabl reloadData];
	
}

- (void) addFromPerson:(id)sender {	
	var indeArra = [persTabl selectedRowIndexes];
 	var coun     = [indeArra count];
		
	while ( coun >= 1 ){
			var firs = [indeArra firstIndex];
		    var valu = [ [persArra objectAtIndex:firs] valueList];
		    var tempEmailoca = valu[2];
		    [finaArra addObject:@"" + tempEmailoca];
		    [indeArra removeIndex:firs];
		    coun --;
	}

	[finaTabl reloadData];
}


- (void) fillOrganizations:(id)sender {

		var coun = [custBackArra count];
		[orgaPopu removeAllItems];
		[orgaPopu setTitle:"Organizaciones"];
		if(coun > 1){
			var popuArra = [[CPArray alloc] init];
			for ( var i=0; i<coun; i++ ) {
				var valuList = [custBackArra[i] valueList];
				var iden = valuList[0];
				var name = valuList[1];
				//var stri = [CPString :@"%@:%@",name,iden];
				if([[[name uppercaseString] rangeOfString:[orga uppercaseString]].length] != 0){
					var arraTemp = [[CPArray alloc] init];
					[arraTemp addObject:iden];
					[arraTemp addObject:name];
					[popuArra addObject:arraTemp];
					[orgaPopu addItemWithTitle:name];
				}
				//[custPopu addItemsWithTitle:popuArra];
			}
			 custArra = popuArra;
		}else{
			var quer = "select idPrimary,name from "+dataBase+".organizations where idPrimary!='"+orgaId+"' and active=1 order by name";
			custBackArra = [self query:quer];
			coun = [custBackArra count];
			var popuArra = [[CPArray alloc] init];
			for ( var i=0; i<coun; i++ ) {
				var arraTemp = [[CPArray alloc] init];
				var valuList = [custBackArra[i] valueList];
				var iden = valuList[0];
				var name = valuList[1];
				//var stri = [CPString stringWithFormat:@"%@:%@",name,iden];
					[arraTemp addObject:iden];
					[arraTemp addObject:name];
					[popuArra addObject:arraTemp];
					[orgaPopu addItemWithTitle:name];
				//[custPopu addItemsWithTitle:popuArra];
			}
			custArra = popuArra;
		}
		
}

- (void) fillState:(id)sender {
		[statePopu removeAllItems];
		[statePopu setTitle:"Estado"];
		var coun = [stateBackArra count];
		if(coun > 1){
			var popuArra = [[CPArray alloc] init];
			for ( var i=0; i<coun; i++ ) {
				var valuList = [stateBackArra[i] valueList];
				var name = valuList[0];
				//var stri = [CPString :@"%@:%@",name,iden];
				var arraTemp = [[CPArray alloc] init];
				//[arraTemp addObject:iden];
				[arraTemp addObject:name];
				[popuArra addObject:arraTemp];
				[statePopu addItemWithTitle:name];

				//[custPopu addItemsWithTitle:popuArra];
			}
			 stateArra = popuArra;
		}else{
			var quer = "select AddressState from "+dataBase+".organizationLocations where active=1 Group by AddressState order by AddressState Asc";
			stateBackArra = [self query:quer];
		
			coun = [stateBackArra count];
			var popuArra = [[CPArray alloc] init];
			for ( var i=0; i<coun; i++ ) {
				var arraTemp = [[CPArray alloc] init];
				var valuList = [stateBackArra[i] valueList];
				var name = valuList[0];
				//var stri = [CPString stringWithFormat:@"%@:%@",name,iden];
				if(![name isEqualToString:@""]){
					
					[arraTemp addObject:name];
					[popuArra addObject:arraTemp];
					[statePopu addItemWithTitle:name];
				}
				
				//[custPopu addItemsWithTitle:popuArra];
			}
			stateArra = popuArra;
		}
		
}

- (void) filterCustomer:(id)sender {
	 orga = [filtText stringValue];
	 [self fillOrganizations: self];
	
}




- (void) datePickerStartPanel:(id)sender {

	if ( datePickStarPane ) {
		[datePickStarPane orderFront:self];
	}else{
	
	var fram = CGRectMake(350,150,144,148);
	datePickStarPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; 
	[datePickStarPane setFloatingPanel:YES];
	[datePickStarPane setTitle:@"Fecha Inicio"];
	[datePickStarPane orderFront:self];

	var paneContView = [datePickStarPane contentView];

	fram = CGRectMake(0,0,144,148);
	var datePick = [[CPDatePicker alloc] initWithFrame:fram];
	[datePick setBackgroundColor:[CPColor whiteColor]];
	[datePick setTimeZone:[CPTimeZone defaultTimeZone]];
	[datePick setDatePickerElements:128];
	var dpe = [datePick datePickerElements];
	[datePick setDatePickerStyle:1];
	var dps = [datePick datePickerStyle];
	[datePick setDateValue:[CPDate date]];
	[datePick setObjectValue:[CPDate date]];
	[datePick setTarget:self];
	[datePick setAction:@selector(datePickerStartDateChange:)];
	//alert("dpe="+dpe+"  dps="+dps);
	
	[paneContView addSubview:datePick];
	}
}


- (void) datePickerStartDateChange:(id)sender {
	[dateStarText setStringValue:[[[sender dateValue] description] substringToIndex:10]];
	[datePickStarPane close];
}




- (void) datePickerEndPanel:(id)sender {

	if ( datePickEndPane ) {
		[datePickEndPane orderFront:self];
	}else{
	var fram = CGRectMake(350,150,144,148);
	datePickEndPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; 
	[datePickEndPane setFloatingPanel:YES];
	[datePickEndPane setTitle:@"Fecha Final"];
	[datePickEndPane orderFront:self];

	var paneContView = [datePickEndPane contentView];

	fram = CGRectMake(0,0,144,148);
	var datePick = [[CPDatePicker alloc] initWithFrame:fram];
	[datePick setBackgroundColor:[CPColor whiteColor]];
	[datePick setTimeZone:[CPTimeZone defaultTimeZone]];
	[datePick setDatePickerElements:128];
	var dpe = [datePick datePickerElements];
	[datePick setDatePickerStyle:1];
	var dps = [datePick datePickerStyle];
	[datePick setDateValue:[CPDate date]];
	[datePick setObjectValue:[CPDate date]];
	[datePick setTarget:self];
	[datePick setAction:@selector(datePickerEndDateChange:)];
	//alert("dpe="+dpe+"  dps="+dps);
	
	[paneContView addSubview:datePick];
	}
}


- (void) datePickerEndDateChange:(id)sender {
	[dateEndText setStringValue:[[[sender dateValue] description] substringToIndex:10]];
	[datePickEndPane close];
}

- (void) deleteFromFinal:(id)sender {	

	var inde = [finaTabl selectedRow];
 	if( inde >= 0 ){
 		[finaArra removeObjectAtIndex:inde];
 		[finaTabl reloadData];
 	}

}


- (void) generateReport:(id)sender {	

	var jaspTabl = "jsprFinalReport";
	var striStartDate = [[dateStarText stringValue] substringToIndex:10];
	var striEndDate = [[dateEndText stringValue] substringToIndex:10];
	var randCode =  [ [CPString UUID] substringToIndex:12];
	var custStr = "|" + nameOrga + ":" + idenOrga + "|";
	var indeOrdePopu = [ordePopu indexOfSelectedItem];
	urlRepo = NULL;

   
   var quer = "SELECT "; 
   quer +=   dataBase + ".eventsPermanent.text, ";
   quer +=  "SUBSTRING(" + dataBase + ".eventsPermanent.start_date,1,10) AS _date, ";
   quer +=  "SUBSTRING(" + dataBase + ".eventsPermanent.start_date,12) AS _hour ";
   quer +=  "FROM " + dataBase + ".eventsPermanent WHERE ";
   quer += " start_date >= (('" + striStartDate + " 00:00:00' - interval 1 day ) + interval 23 hour + interval 59 minute + interval 59 second ) "; 
   quer += " AND start_date <= '" + striEndDate + " 23:59:59' "
   quer +=  " AND customer = '" + idenOrga + "' ";

   if (indeOrdePopu == 0) {
   		quer +=  "ORDER BY _date";   	
   }else if (indeOrdePopu == 1) {
   		quer +=  "ORDER BY text";   	
   }

   
   //alert("query " + quer);
 //  var arraTempRepo = [self query:quer];
 	var arraAux = [self query:quer];
 	var arraTempRepo = [CPArray array];
 		
 	
 	for (var i = 0; i < [ arraAux count]; i++){
 		var valu = [ [arraAux objectAtIndex:i] valueList ];
 		var loca     = valu[0];
		var statDate = valu[1];		
		var hour     = valu[2];	
		var stri = " ('" + randCode + "','" + loca + "','" + statDate + "','" + hour + "')";
		[arraTempRepo addObject:stri];
		}
	 	
   var coun = [arraTempRepo count];
   
   if (coun == 0){
   		//alert("No se encontraron datos");
   		[glblAlerPane showWithMessage:@"Atencion" info:"No se encontraron datos"];
   		return;
   }
   
   var begiSql = "INSERT INTO " + dataBase + "." + jaspTabl + " (reportCode,FIELD01,FIELD02,FIELD03) VALUES " ;
   var middSql = "";
   
   if ( coun > 50 ){
   
  		while( coun > 50){
  		// alert("coun start while "+ coun);
   		   for (var i =0; i < 50; i++){  
   				var valu =  [arraTempRepo objectAtIndex:0];
   				//alert ("valu "+ valu);
				var temp  = i + 1;	
				if(temp == 50){
					middSql += valu;
				} else{
					middSql += valu + ",";
			    }
			    [arraTempRepo removeObjectAtIndex:0];
   				coun -=1;
   		   }

   	    quer =  begiSql + middSql ;
	    //[self query:quer];
	    [self query:quer];
    	//alert ("insert 1" + quer);	
    	middSql = "";
	   	//coun = [arraTempRepo count]; 

     }
   }
   
   
    coun = [arraTempRepo count];
    begiSql = "INSERT INTO " + dataBase + "." + jaspTabl + " (reportCode,FIELD01,FIELD02,FIELD03) VALUES " ;
    middSql = "";

    
    if (coun >= 1) {	   
   	for (var i =0; i < coun; i++){
   		var valu = [arraTempRepo objectAtIndex:i] ;
		var temp = i + 1;	
		if(temp == coun){
			middSql += valu; 
		} else{
			middSql += valu + ",";
		}
    }
    
     quer =  begiSql + middSql ;
    [self query:quer];
 }

	
	var repoCommTemp = [repoComm stringValue]; 
 	var titlRepo = "Programacion: "+ striStartDate + " - " + striEndDate + ":sc:" +  nameOrga; 
 	//Programación: startDate - EndDate:sc:Name  
    dictRepo = [[CPDictionary alloc] init];
    [dictRepo setObject:titlRepo  forKey:"title" ];
    [dictRepo setObject:"Locaciones:sc:Fecha:sc:Hora" forKey:"headList" ];
    [dictRepo setObject:randCode forKey:"repoCode" ];
    [dictRepo setObject:" " + repoCommTemp forKey:"comment" ];
    [dictRepo setObject:"ORKIN de Costa Rica is an independent franchise of Orkin Systems, LLC" forKey:"testFoot"];
	[dictRepo setObject:dataBase forKey:"sourceOfData" ];
	[dictRepo setObject:"OrganizationOrkinReport" forKey:"myModel" ];
	var jsprMsql = "b14_2"; 
	var myPathTemp = "/reports/Orkin";
	[dictRepo setObject:myPathTemp forKey:"myPath" ];
	
    urlRepo = [jasp  buildJasperURL:dictRepo];
    //alert("URL report " + urlRepo);
    //[jasp showPreviousView:urlRepo]; 
    //location.href = urlRepo;
    var uri =  encodeURI(urlRepo);
	window.open(uri);
	[geneRepoPane close];
}


- (void) nextReportPanel:(id)sender {
	
    
	if ([orgaPopu indexOfSelectedItem] == 0) {
	 	return;
	}


	urlRepo = NULL;

	
	if (geneRepoPane) {
		       
		[locaArra removeAllObjects];		
		[persArra removeAllObjects];	
		[finaArra removeAllObjects];		
		[finaArra addObject:@"" + emaiOrga ];
		[persTabl reloadData];
		[locaTabl reloadData];
		[finaTabl reloadData];
		[geneRepoPane orderFront:self];
	}else{
		
	var horiPos1 = 15;
	var horiPos2 = horiPos1 + 80;
	var horiPos3 = 310;
	var horiPos4 = horiPos3 + 100;

	var horiTextWidt = 200;
	var horiPosiOffs = -4;
	var horiPosi = 200;

	var vertPosi = 15;
	var vertPosiOffs = -4;
	var vertIncr = 26;
	var vertLineHeig = 30;

	var paneWidt = 900;
	var paneHeig = 610;
	var tablWidt = paneWidt - 20;
	var tablHeig = 150;
	
	var x = 450 + Math.random()*40;
	var y = 60 + Math.random()*40;
	var fram = CGRectMake(x,y, paneWidt,paneHeig);

	geneRepoPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[geneRepoPane setFloatingPanel:YES]; 
	[geneRepoPane orderFront:self];
	[geneRepoPane setTitle:@"Reporte"];
	
	var paneContView = [geneRepoPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:1. heightOrange:4.];

	var view = paneContView;

	
	//Tables
	
	//Location
	var labe = [self addTextField:@"Locaciones:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	horiPos3 += 150;
	labe = [self addTextField:@"Empleados:" TFPosX:horiPos3 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	
	vertPosi += 20;
	var fram= CGRectMake(horiPos1,vertPosi, 200,90);
	
	fram= CGRectMake(horiPos1,vertPosi, 400,300);
	var scroView= [[CPScrollView alloc] initWithFrame:fram];

	locaTabl = [[CPTableView alloc] initWithFrame:[scroView bounds]];
	[locaTabl setDataSource:self];
	[locaTabl setTarget:self];
	//[locaTabl setAction:@selector(eventTableSelection:)];
	[locaTabl setAllowsColumnReordering:YES];
	[locaTabl setUsesAlternatingRowBackgroundColors:YES];
	[locaTabl setAllowsMultipleSelection:YES];
	[locaTabl setDelegate:self];

	var colu= [[CPTableColumn alloc] initWithIdentifier:@"NameLoca"];
	[[colu headerView] setStringValue:@"Nombre Locación"];
	[colu setWidth:200];
	[locaTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"EmaiLoca"];
	[[colu headerView] setStringValue:@"Email"];
	[colu setWidth:200];
	[locaTabl addTableColumn:colu];
	
	[scroView setDocumentView:locaTabl];
	
	//Menu location table
	
	locaMenu = [[CPMenu alloc] initWithTitle:@"Opciones"];
	var seriCommOpti = [locaMenu insertItemWithTitle:@"Agregar Locación" 
							    action:@selector(addFromLocation:)
							     keyEquivalent:@""
							     atIndex:0];

	
	[scroView setMenu:locaMenu];
	[[CPArray arrayWithObjects:seriCommOpti] makeObjectsPerformSelector:@selector(setTarget:) withObject:self];
	//end
	
	[view addSubview:scroView];
	
	
	//Pesonnel

	var fram= CGRectMake(horiPos3,vertPosi, 200,90);
	
	fram= CGRectMake(horiPos3,vertPosi, 400,300);
	var scroView= [[CPScrollView alloc] initWithFrame:fram];

	persTabl = [[CPTableView alloc] initWithFrame:[scroView bounds]];
	[persTabl setDataSource:self];
	[persTabl setTarget:self];
	//[persTabl setAction:@selector(eventTableSelection:)];
	[persTabl setAllowsColumnReordering:YES];
	[persTabl setUsesAlternatingRowBackgroundColors:YES];
	[persTabl setAllowsMultipleSelection:YES];
	[persTabl setDelegate:self];

	var colu= [[CPTableColumn alloc] initWithIdentifier:@"NamePers"];
	[[colu headerView] setStringValue:@"Nombre Completo"];
	[colu setWidth:200];
	[persTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"EmaiPers"];
	[[colu headerView] setStringValue:@"Email"];
	[colu setWidth:200];
	[persTabl addTableColumn:colu];
	
	[scroView setDocumentView:persTabl];
	
	//Menu Person table
	
	persMenu = [[CPMenu alloc] initWithTitle:@"Opciones"];
	var seriCommOpti = [persMenu insertItemWithTitle:@"Agregar Empleado" 
							    action:@selector(addFromPerson:)
							     keyEquivalent:@""
							     atIndex:0];
	
	[scroView setMenu:persMenu];
	[[CPArray arrayWithObjects:seriCommOpti] makeObjectsPerformSelector:@selector(setTarget:) withObject:self];
	//end
	
	[view addSubview:scroView];
	
	
	//Final
	//horiPos3 += 450;
	vertPosi += 320;
	labe = [self addTextField:@"Destinatarios:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	vertPosi += 20;
	var fram= CGRectMake(horiPos1,vertPosi, 200,120);
	
	fram= CGRectMake(horiPos1,vertPosi, 400,130);
	var scroView= [[CPScrollView alloc] initWithFrame:fram];

	finaTabl = [[CPTableView alloc] initWithFrame:[scroView bounds]];
	[finaTabl setDataSource:self];
	[finaTabl setTarget:self];
	//[finaTabl setAction:@selector(eventTableSelection:)];
	[finaTabl setAllowsColumnReordering:YES];
	[finaTabl setUsesAlternatingRowBackgroundColors:YES];
	[finaTabl setAllowsMultipleSelection:YES];
	[finaTabl setDelegate:self];

	var colu= [[CPTableColumn alloc] initWithIdentifier:@"finaEmai"];
	[[colu headerView] setStringValue:@"Email"];
	[colu setWidth:400];
	[finaTabl addTableColumn:colu];

	//Menu Final table
	
	finaMenu = [[CPMenu alloc] initWithTitle:@"Opciones"];
	var seriCommOpti = [finaMenu insertItemWithTitle:@"Eliminar" 
							    action:@selector(deleteFromFinal:)
							     keyEquivalent:@""
							     atIndex:0];
							      

	
	[scroView setMenu:finaMenu];
	[[CPArray arrayWithObjects:seriCommOpti] makeObjectsPerformSelector:@selector(setTarget:) withObject:self];
	//end
	
	[scroView setDocumentView:finaTabl];
	
	[view addSubview:scroView];
	[finaArra addObject:@"" + emaiOrga ];
	[finaTabl reloadData];
	
	vertPosi -= 20;
	//Comment Email
	labe = [self addTextField:@"Comentario email:" TFPosX:horiPos3 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	vertPosi += 20;
	emaiComm = [self addTextField:@"" TFPosX:horiPos3 TFPosY:vertPosi-4 TFWidth:400 TFHeight:2*vertLineHeig VView:view Editable:YES];
    [emaiComm setLineBreakMode:CPLineBreakByWordWrapping];
    
	vertPosi += 60;
	//Comment Report
	labe = [self addTextField:@"Comentario Reporte:" TFPosX:horiPos3 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	vertPosi += 20;
	repoComm = [self addTextField:@" " TFPosX:horiPos3 TFPosY:vertPosi-4 TFWidth:400 TFHeight:2*vertLineHeig VView:view Editable:YES];
    [repoComm setLineBreakMode:CPLineBreakByWordWrapping];
    
    vertPosi += 60;
    [self addButton:@"Generar" TFPosX:horiPos1  TFPosY:vertPosi-2 TFWidth:65 TFHeight:24  VView:view sizeToFit:NO Action:@selector(generateReport:)];
	[self addButton:@"Enviar" TFPosX:horiPos2 TFPosY:vertPosi-2 TFWidth:65 TFHeight:24  VView:view sizeToFit:NO Action:@selector(sendReportByEmail:)];
	
	
	}
	

}




- (void) organizationSelectionPopUp:(id)sender {
	
	var inde = [orgaPopu indexOfSelectedItem];

	if (inde == 0) {
		 //alert("reload popu orga");
		[orgaPopu removeAllItems];
		[orgaPopu addItemWithTitle:@"Organizaciones"];
		[filtText setStringValue:@""];
		custBackArra = NULL;
		var quer = [CPString stringWithFormat:@"SELECT idPrimary,name,email FROM %@.organizations WHERE idPrimary!='%@' AND active=1 ORDER BY name",
		  dataBase,orgaId];
		custBackArra = [self query:quer];
		var popuArra = [[CPArray alloc] init];
		var coun = [custBackArra count];

		for ( var i=0; i<coun; i++ ) {
			var valuList = [custBackArra[i] valueList];
			idenOrga = valuList[0];
			nameOrga = valuList[1];
			emaiOrga = valuList[2];
			var arraTemp = [[CPArray alloc] init];
			[arraTemp addObject:idenOrga];
			[arraTemp addObject:nameOrga];
			[arraTemp addObject:emaiOrga];
			[popuArra addObject:arraTemp];
			[orgaPopu addItemWithTitle:nameOrga];
		}
		custArra = popuArra;

	}else{
		[orgaPopu selectItemAtIndex:inde];
		inde --;
		var valuList = custArra[inde];
		idenOrga = valuList[0];
		nameOrga = valuList[1];
		emaiOrga = valuList[2];

		
	}

}


- (void) reportsPanel {
	return repoPane;
}


- (void) reportsPanel:(id)sender {

	var horiPos1 = 10;
	var horiPos2 = horiPos1 + 100;
	var horiPos3 = 390;
	var horiPos4 = horiPos3 + 100;

	var horiTextWidt = 200;
	var horiPosiOffs = -4;
	var horiPosi = 200;

	var vertPosi = 20;
	var vertPosiOffs = -4;
	var vertIncr = 26;
	var vertLineHeig = 30;

	var paneWidt = 400;
	var paneHeig = 260;
	var tablWidt = paneWidt - 20;
	var tablHeig = 150;
	
	var x = 10 + Math.random()*40;
	var y = 60 + Math.random()*40;
	var fram = CGRectMake(x,y, paneWidt,paneHeig);

	repoPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[repoPane setFloatingPanel:YES]; 
	[repoPane orderFront:self];
	[repoPane setTitle:@"Panel Reportes Organización"];
	
	var paneContView = [repoPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:1. heightOrange:4.];

	var view = paneContView;
	
	
	
	var labe= [self addTextField:@"Filtro :" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	filtText = [self addTextField:@"" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:200 TFHeight:30 VView:view Editable:YES];
	[filtText setDelegate:self];
	[filtText setTarget:self];
	[filtText setAction:@selector(filterCustomer:)];

	vertPosi += 1.25*vertIncr;

	labe= [self addTextField:@"Organizaciones:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	
	orgaPopu = [self addPopupButton:@"Organizaciones" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[orgaPopu setTarget:self];
	[orgaPopu setAction:@selector(organizationSelectionPopUp:)];
	//[orgaPopu addItemWithTitle:"Organizaciones"];

	
	[self fillOrganizations:self];
		
	vertPosi += 40;
	labe= [self addTextField:@"Fecha Inicio:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	dateStarText = [self addTextField:[[[CPDate date] description] substringToIndex:10] TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:85 TFHeight:30 VView:view Editable:YES];
	[self addButton:@"DP" TFPosX:horiPos2 + 90 TFPosY:vertPosi-2 TFWidth:50 TFHeight:24  VView:view sizeToFit:NO Action:@selector(datePickerStartPanel:)];
	vertPosi += 40;
	labe= [self addTextField:@"Fecha Final:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	dateEndText = [self addTextField:[[[CPDate date] description] substringToIndex:10] TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:85 TFHeight:30 VView:view Editable:YES];
	[self addButton:@"DP" TFPosX:horiPos2 + 90 TFPosY:vertPosi-2 TFWidth:50 TFHeight:24  VView:view sizeToFit:NO Action:@selector(datePickerEndPanel:)];
	vertPosi += 40;
	
	
	//Ordenar por
	labe= [self addTextField:@"Ordenar por:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	
	ordePopu = [self addPopupButton:@"Fecha" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[ordePopu addItemWithTitle:"Nombre de locación"];
	[ordePopu setTarget:self];
	//[rolePopu setAction:@selector(roleSelectionPopUp:)];
	
	
	vertPosi += 40;
	[self addButton:@"Siguiente" TFPosX:horiPos2  TFPosY:vertPosi-2 TFWidth:80 TFHeight:24  VView:view sizeToFit:NO Action:@selector(nextReportPanel:)];
}



- (void) sendReportByEmail:(id)sender {	
	
	var coun = [finaArra count];
	
	if(coun > 0){	
	
	if (!urlRepo){
	    [self generateReport:sender];
	 }
	
	//addButton:@"Generar" TFPosX:horiPos1 
	if (urlRepo) {
		urlRepo = [urlRepo stringByReplacingOccurrencesOfString:@"192.168.2.252" withString:@"167.250.194.153"];
		var comm = [emaiComm stringValue]; 
		[jasp emailReportToList:finaArra :urlRepo :comm];

		}
	}
	[geneRepoPane close];
}







- (void) tableSelection:(id)sender {
}

- (void)controlTextDidChange:(CPNotification)notification   {
     [self filterCustomer:self];
}


//		TABLE SOURCE DELEGATE METHODS

- (int) numberOfRowsInTableView:(CPTableView)tablView {
	var coun= 0;
	var quer;

	if ( tablView == locaTabl ) {
		quer= [CPString stringWithFormat:@"SELECT name,email FROM %@.organizationLocations WHERE organizationId = '%@' ORDER BY name ASC",dataBase,idenOrga];
		locaArra = [self query:quer];	
		//alert("quer locations " + quer);
		coun = [locaArra count];
		//alert("count loca " +  coun);
	}
	
	if ( tablView == persTabl ) {
		quer = [CPString stringWithFormat:@"SELECT t2.NameFirst,t2.nameLast,t1.email FROM %@.organizationPersons t1, %@.persons t2  WHERE t1.personId = t2.id AND t1.organizationId = '%@' ORDER BY t2.NameFirst,t2.nameLast",
		dataBase,dataBase,idenOrga];
		persArra = [self query:quer];
		//alert("quer persons " + quer);	
		coun = [persArra count];
		//alert("count loca " +  coun);
	}
	
	if ( tablView == finaTabl ) {
		//quer= [CPString stringWithFormat:@"SELECT email FROM %@.organizations WHERE id = '%@' ",dataBase,idenOrga];
		//finaArra = [self query:quer];
		coun = [finaArra count];
	}

	return coun;
}


- (id) tableView:(CPTableView)tablView objectValueForTableColumn:(CPTableColumn)tablColu row:(int)rowInde {

	var headStri= [[tablColu headerView] stringValue];
	var headIden= [tablColu identifier];
	var valu = @"N/A";

	if ( tablView == locaTabl ) {
		valu = locaArra[rowInde];
	}
	if ( tablView == persTabl ) {
		valu = persArra[rowInde];
	}
	if ( tablView == finaTabl ) {
		valu = finaArra[rowInde];
	}
	
	if ( tablView == locaTabl ) {
		var arra = [[locaArra objectAtIndex:rowInde] valueList];	
		if ( [headIden isEqualToString:@"NameLoca"] ){
			valu =  arra[0] ;
		}
		else if ( [headIden isEqualToString:@"EmaiLoca"] ){
			valu =  arra[1];
		}
	}

	if ( tablView == persTabl ) {
		var arra= [[persArra objectAtIndex:rowInde] valueList];
		if ( [headIden isEqualToString:@"NamePers"] ){
			valu = arra[0] + " " + arra[1];
		}
		else if ( [headIden isEqualToString:@"EmaiPers"] ){
			valu = arra[2];
		}
	}
	
	 if ( tablView == finaTabl ) {
		var arra= [finaArra objectAtIndex:rowInde ];
		if ( [headIden isEqualToString:@"finaEmai"] ){
			valu = arra;        
		}
	}
		
	return valu;
}






@end
