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

@import "../AppController.j"
@import "../model/Model.j"


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




@implementation AutomaticOrganization : RMControllerObject {


	CPPanel repoPane;

	id orgaPopu;
	id prevOrgaPopu;
	id orgaArra;
	//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 finaDict;
  	id finaMenu;
  	
  	id dictRepo;
  	id urlRepo;
  	
  	id emaiComm;
  	id repoComm;
  	
  	id ordePopu;
  	id daysPopu;
  	
  	id dayMonthPopu;
  	
  	id checkActi;
  	id prevValuCheckActi;
  	id checkSendEmpt;
  	
  	id year;
  	id mont;
  	id day;
  	

}



- (id) init:(id)paraAppCont {
	[super init];
 	
 	appCont = paraAppCont;
	dataBase = [appCont getDataBase];
	//alert("db init reports= " + [appCont getDataBase]);
	prevValuCheckActi = "0";
	repoPane = geneRepoPane =  NULL;
	prevOrgaPopu = 0;
	orgaPopu = NULL;
	orgaArra = NULL;
	 emaiText = NULL;
	idenOrga = "";
	nameOrga = "";
	persTabl = persArra = NULL;
	ordePopu = NULL;
	finaDict =  [[CPDictionary alloc] init];
	//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 (orgaArra)     { [orgaArra  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 (finaDict) { [finaDict  release];}
	if (finaMenu) { [ finaMenu release];}
	if (dictRepo) { [dictRepo  release];}
	if (urlRepo)  { [urlRepo  release]; }
	if (emaiComm) { [emaiComm  release];}
	if (repoComm) { [repoComm  release];}
	
	[jasp applicationQuit];
	if (jasp) { [jasp  release];}
}



- (void) addEmailOrganization:(id)sender {

	var tempFinaObject = [[FinaObject alloc] init:idenOrga emai:emaiOrga type:1];
	[finaDict setObject:tempFinaObject  forKey:"" + emaiOrga + "" ];
	[finaTabl reloadData];		    
}



- (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 tempNameloca = valu[0];
		    var tempEmailoca = valu[1];
		    var tempIdenloca = valu[2];
		    var tempFinaObject = [[FinaObject alloc] init:tempIdenloca emai:tempEmailoca type:2];
		    [finaDict setObject:tempFinaObject  forKey:"" + 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 tempEmaiPers = valu[2];
		    var tempIdenpers = valu[3];
		    var tempFinaObject = [[FinaObject alloc] init:tempIdenpers emai:tempEmaiPers type:3];
		    [finaDict setObject:tempFinaObject  forKey:"" +  tempEmaiPers + "" ];
		    
		    [indeArra removeIndex:firs];
		    coun --;
	}

	[finaTabl reloadData];
}




- (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 ){
 		var finaDictKeys = [finaDict allKeys];
		var aKey = [finaDictKeys objectAtIndex:inde];
		[finaDict removeObjectForKey: aKey];
		[finaTabl reloadData];
 	}

}


- (void) updateChangesAutomaticReport:(id)sender {	

	var striStartDate = [ [ [CPDate date] description] substringToIndex:10 ] ;
	var tempStri = striStartDate;
	var quer = ""
	year = [tempStri substringToIndex:4];
	tempStri = [tempStri stringByReplacingOccurrencesOfString:@"" + year + "-" withString:@""];
	mont = [tempStri substringToIndex:2];
	tempStri = [tempStri stringByReplacingOccurrencesOfString:@"" + mont + "-" withString:@""];

	
	var tempDayInde   = [daysPopu indexOfSelectedItem];
	day = [daysPopu itemTitleAtIndex:tempDayInde];
	var auxDay = [day integerValue] - 1;

	if (mont == 2) {
		if (auxDay >= 28){
			auxDay = 27;	
		}
	}
	
	if ( (mont == 4) || (mont == 6) || (mont == 9)|| (mont == 11) ) {
		if (auxDay >= 30){
			auxDay = 29;	
		}
	}
	
	var nextDate = "";
	if (auxDay < 10){
	  	nextDate = [striStartDate substringToIndex:8] + "0" + auxDay  + " 20:15:00";
	}else{
		nextDate = [striStartDate substringToIndex:8] + auxDay  + " 20:15:00";
	}
	
	//console.log("nextDate = " + nextDate);
	var para = "";
	var acti = [checkActi state];
	var sendEmpt = [checkSendEmpt state];
	var comm1 = "" + [repoComm stringValue];
	var comm2 = ""  + [emaiComm stringValue];
	var emaiList = "";
	var indeOrdePopu = [ordePopu indexOfSelectedItem];	
	
	if (indeOrdePopu == 0) {
   		para = "order=date";  	
    }else if (indeOrdePopu == 1) {
   		para = "order=text";  	
    }	
	
	var finaDictKeys = [finaDict allKeys];	
	var coun =  [finaDict count];
	var tempI = 0;
	for (var i = 0 ; i < coun; i++) {
		var aKey = [finaDictKeys objectAtIndex:i];
		var objt = [finaDict objectForKey:aKey];
		 tempI = ( i + 1 );
		 if (tempI == coun){
		 	emaiList += "iden=" + [objt iden] + "|type=" + [objt type];
		 }else{
		 	emaiList += "iden=" + [objt iden] + "|type=" + [objt type] +  ":sc:";
		 }
	}
	
	//console.log("prevValuCheckActi = " + prevValuCheckActi +  "  acti = " + acti);
	if  ( (prevValuCheckActi == "0") && ( acti == "1") ) {
	quer = "UPDATE " + dataBase + ".automaticReportDefinitions SET ";
quer += [CPString stringWithFormat:@" dayMonth = '%@',contentParameters = '%@',active = %@, sendEmpty = %@, comment1 = '%@', comment2 = '%@', emailList = '%@', nextGeneDate = '%@' ", 
		  day,para,acti,sendEmpt,comm1,comm2,emaiList,nextDate];
   quer += [CPString stringWithFormat:@"WHERE typeReportId = 1 AND sendFrequencyId = 1 AND identifier = '%@' ",
         idenOrga];
    prevValuCheckActi = "1";
	}else{
		quer = "UPDATE " + dataBase + ".automaticReportDefinitions SET ";
quer += [CPString stringWithFormat:@" dayMonth = '%@',contentParameters = '%@',active = %@, sendEmpty = %@, comment1 = '%@', comment2 = '%@', emailList = '%@', nextGeneDate = '%@' ", 
		  day,para,acti,sendEmpt,comm1,comm2,emaiList,nextDate];
   quer += [CPString stringWithFormat:@"WHERE typeReportId = 1 AND sendFrequencyId = 1 AND identifier = '%@' ",
         idenOrga];     
   prevValuCheckActi = "0";    
	}	
	//console.log("quer = " + quer);
	[self query:quer];
	
	if ([finaDict count] == 0 && acti == 1) {
		[glblAlerPane showWithMessage:@"Advertencia" info:@"Se activó el envío de reportes automáticos sin destinatarios asignados"];
	}
	

}

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

	if (inde == 0) {
		 //alert("reload popu orga");
		prevOrgaPopu = 0;
		[finaDict removeAllObjects];
		[locaArra removeAllObjects];
		[persArra removeAllObjects];
		[orgaPopu removeAllItems];
		idenOrga = "";
		[locaTabl reloadData];
		[persTabl reloadData];	
		[finaTabl reloadData];
		[orgaPopu addItemWithTitle:@"Organizaciones"];
		orgaArra = NULL;		
		var quer = [CPString stringWithFormat:@"SELECT id,name,email,idPrimary FROM %@.organizations WHERE idPrimary !='%@' AND active=1 AND deletion = 0 ORDER BY name",
		  dataBase,orgaId];
		orgaArra= [self query:quer];
		var coun = [orgaArra count];
		for ( var i = 0; i < coun; i++ ) {
			var valuList = [orgaArra[i] valueList];
			idenOrga = valuList[3];
			nameOrga = valuList[1];
			emaiOrga = valuList[2];
		//var stri = [CPString stringWithFormat:@"%@:%@",name,iden];
			[orgaPopu addItemWithTitle:nameOrga];
		}	
		
	}else{
		[orgaPopu selectItemAtIndex:inde];
		inde --;
		
		if (prevOrgaPopu != inde) {
			[finaDict removeAllObjects];
		}
		
		var valuList = [orgaArra[inde] valueList];
		//console.log(valuList);
		idenOrga = valuList[3];
		nameOrga = valuList[1];
		emaiOrga = valuList[2];
		
quer = [CPString stringWithFormat:@"SELECT dayMonth,contentParameters,emailList,active,sendEmpty,comment1,comment2 FROM %@.automaticReportDefinitions WHERE identifier = '%@' AND typeReportId = 1 AND  sendFrequencyId = 1 LIMIT 1",
                                   dataBase,idenOrga];	
		
		var tempArra = [self query:quer];
		var coun = [tempArra count];
		for (var i = 0; i < coun; i++ ) {
			var valuList = [tempArra[i] valueList];
			var day   = valuList[0];
			var para  = valuList[1];
			var list  = valuList[2];
			var acti  = valuList[3];
			var send  = valuList[4];
			var comm1 = valuList[5];
			var comm2 = valuList[6];
		
//		[dateStarText setStringValue: init];
		var tempInde = [daysPopu indexOfItemWithTitle:day];
		//console.log(tempInde);
		if (tempInde == -1){
			[glblAlerPane showWithMessage:@"Advertencia" info:@"Debe cambiar el día de envio."];
		}else{
			[daysPopu selectItemAtIndex:tempInde];
		}
		//var tempStri = [[dateStarText stringValue] substringToIndex:10];
		//[dateStarText setStringValue: tempStri];

		if (para == "order=date"){
			[ordePopu setSelectedIndex:0];
		}else{
			[ordePopu setSelectedIndex:1];
		}
		//iden=numa_cr|type=0:sc:iden=3516|type=2:sc:iden=546|type=3
		//iden=numa_cr|type=0
		// iden=numa_cr   type=0
		if (list != "" ){
			var arra1 = [list componentsSeparatedByString:@":sc:"];
			for (var j = 0 ; j < [arra1 count]; j++) {
				var elem = arra1[j];
				var arra2 = [elem componentsSeparatedByString:@"|"];
				var typeArra = arra2[1];
				var idenArra = arra2[0] ;
				var idenAux = [idenArra componentsSeparatedByString:@"="]
				
				switch (typeArra) {								
					case "type=1":
					quer = [CPString stringWithFormat:@"SELECT email FROM %@.organizations WHERE idPrimary ='%@' LIMIT 1",
					dataBase,idenAux[1] ];
					var arraQuer = [self query: quer];
					if ([arraQuer count] > 0 ) {
						var valuListAux = [arraQuer[0] valueList];			
						var tempFinaObject = [[FinaObject alloc] init:idenAux[1] emai:valuListAux[0] type:1];
						[finaDict setObject:tempFinaObject  forKey:"" +  valuListAux[0] + "" ];	
					}
					break;
			
					case "type=2":			
					quer = [CPString stringWithFormat:@"SELECT email FROM %@.organizationLocations WHERE id = '%@' LIMIT 1",
					dataBase,idenAux[1] ];
					var arraQuer = [self query: quer];
					if ([arraQuer count] > 0 ) {
						var valuListAux = [arraQuer[0] valueList];			
						var tempFinaObject = [[FinaObject alloc] init:idenAux[1] emai:valuListAux[0] type:2];
						[finaDict setObject:tempFinaObject  forKey:"" +  valuListAux[0] + "" ];
					}
					break;
			
					case "type=3":			
					quer = [CPString stringWithFormat:@"SELECT email FROM %@.persons WHERE id = '%@' LIMIT 1",
					dataBase,idenAux[1] ];
					var arraQuer = [self query: quer];
					if ([arraQuer count] > 0 ) {
						var valuListAux = [arraQuer[0] valueList];			
						var tempFinaObject = [[FinaObject alloc] init:idenAux[1] emai:valuListAux[0] type:3];
						[finaDict setObject:tempFinaObject  forKey:"" +  valuListAux[0] + "" ];
					}
					break;
			
					default: 
					break;
				}
			 }
		}
		
		
		if (acti == 1) {
			[checkActi setStringValue:"1"];
			prevValuCheckActi = "1";
		}else{
			[checkActi setStringValue:"0"];
			prevValuCheckActi = "0";
		}
		
		if (send == 1) {
			[checkSendEmpt setStringValue:"1"];
		}else{
			[checkSendEmpt setStringValue:"0"];
		}
		//var tempComm1 = " " + comm1;
		[repoComm setStringValue:comm1];
		[emaiComm setStringValue:comm2];
		//[emaiComm setStringValue:[CPString stringWithFormat:@"%@",comm2] ];
		//[emaiComm setStringValue: [objt comm2]];  
		}
		
		 //[finaDict addObject:@"" + emaiOrga];
		//var tempFinaObject = [[FinaObject alloc] init:idenOrga emai:emaiOrga type:1];
		//[finaDict setObject:tempFinaObject  forKey:"" +  emaiOrga + "" ];
		[locaTabl reloadData];
		[persTabl reloadData];	
		[finaTabl reloadData];
	}
	
}


- (void) reportsPanel:(id)sender {
	
    
	if ([orgaPopu indexOfSelectedItem] == 0) {
	 	return;
	}
	
	if (geneRepoPane) {
		       
		[locaArra removeAllObjects];		
		[persArra removeAllObjects];	
		[finaDict removeAllObjects];		
		//[finaArra addObject:@"" + emaiOrga ];
		//var tempFinaObject = [[FinaObject alloc] init:idenOrga emai:emaiOrga type:1];
		//[finaDict setObject:tempFinaObject  forKey:"" + emaiOrga+ "" ];
		/*
		[persTabl reloadData];
		[locaTabl reloadData];
		[finaTabl reloadData];
		*/	
		[geneRepoPane orderFront:self];
		
	}else{
		
	var horiPos1 = 15;
	var horiPos2 = horiPos1 + 80;
	var horiPos3 = 310;
	var horiPos4 = horiPos3 + 480;

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

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

	var paneWidt = 890;
	var paneHeig = 650;
	var tablWidt = paneWidt - 20;
	var tablHeig = 150;
	
	var x = 50 + 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 Automático Organizaciones"];
	
	var paneContView = [geneRepoPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:1. heightOrange:4.];

	var view = paneContView;
	
	var 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 + 15) TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[orgaPopu setTarget:self];
	[orgaPopu setAction:@selector(organizationSelectionPopUp:)];
	//[orgaPopu addItemWithTitle:"Organizaciones"];

	
	var quer = [CPString stringWithFormat:@"SELECT id,name,email,idPrimary FROM %@.organizations WHERE idPrimary !='%@' AND active=1 AND deletion = 0 ORDER BY name",
			dataBase,orgaId];
		orgaArra= [self query:quer];
		var coun = [orgaArra count];
		for ( var i=0; i<coun; i++ ) {
			var valuList = [orgaArra[i] valueList];
			idenOrga = valuList[3];
			nameOrga = valuList[1];
			emaiOrga = valuList[2];
			[orgaPopu addItemWithTitle:nameOrga];
		}
	
	horiPos3 += 150;
	labe= [self addTextField:@"Fecha de envio:" TFPosX:horiPos3 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	
	daysPopu = [self addPopupButton:@"15" TFPosX:(horiPos3 + 95 )  TFPosY:vertPosi-4 TFWidth:70 TFHeight:24  VView:view pullsDown:NO];
	[daysPopu addItemWithTitle:"16"];   [daysPopu addItemWithTitle:"17"];
	[daysPopu addItemWithTitle:"18"];	[daysPopu addItemWithTitle:"19"]; 
	[daysPopu addItemWithTitle:"20"];	[daysPopu addItemWithTitle:"21"]; 
	[daysPopu addItemWithTitle:"22"];	[daysPopu addItemWithTitle:"23"]; 
	[daysPopu addItemWithTitle:"24"];	[daysPopu addItemWithTitle:"25"]; 
	[daysPopu addItemWithTitle:"26"];	[daysPopu addItemWithTitle:"27"];
	[daysPopu addItemWithTitle:"28"];	[daysPopu addItemWithTitle:"29"];
	[daysPopu addItemWithTitle:"30"];   [daysPopu addItemWithTitle:"31"];
	[daysPopu setTarget:self];
	
	labe= [self addTextField:@"del mes" TFPosX:(horiPos3 + 170 )  TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	
	
	//dateStarText = [self addTextField:[[[CPDate date] description] substringToIndex:10] TFPosX: (horiPos3 + 75 )  TFPosY:vertPosi-4 TFWidth:85 TFHeight:30 VView:view Editable:YES];
	//[self addButton:@"DP" TFPosX:(horiPos3 + 75 + 90 ) TFPosY:vertPosi-2 TFWidth:50 TFHeight:24  VView:view sizeToFit:NO Action:@selector(datePickerStartPanel:)];
		
    
    vertPosi += 30;
    checkActi = [[CPCheckBox alloc] initWithFrame:CGRectMake(horiPos3,vertPosi,120,25)];
	[checkActi setTitle:"Activar"];
    [checkActi setFont:[CPFont fontWithName:@"Arial" size:12]];
    [checkActi setTextColor:[CPColor whiteColor]];
	[view addSubview:checkActi];
	
	vertPosi += 20;
	checkSendEmpt = [[CPCheckBox alloc] initWithFrame:CGRectMake(horiPos3,vertPosi,280,25)];
	[checkSendEmpt setTitle:"Enviar aunque no tenga trabajos programados"];
    [checkSendEmpt setFont:[CPFont fontWithName:@"Arial" size:12]];
    [checkSendEmpt setTextColor:[CPColor whiteColor]];
	[view addSubview:checkSendEmpt];
	
	vertPosi -= 50;
	
	
	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 + 10 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[ordePopu addItemWithTitle:"Nombre de locación"];
	[ordePopu setTarget:self];
	
	vertPosi += 40;
	//Tables
	
	//Location
	labe = [self addTextField:@"Locaciones:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	
	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 addEmaiOrga = [finaMenu insertItemWithTitle:@"Agregar correo organización" 
							    action:@selector(addEmailOrganization:)
							     keyEquivalent:@""
							     atIndex:0];
	var seriCommOpti = [finaMenu insertItemWithTitle:@"Eliminar" 
							    action:@selector(deleteFromFinal:)
							     keyEquivalent:@""
							     atIndex:1];				      
	
	[scroView setMenu:finaMenu];
	[[CPArray arrayWithObjects:addEmaiOrga,seriCommOpti] makeObjectsPerformSelector:@selector(setTarget:) withObject:self];
	//end
	
	[scroView setDocumentView:finaTabl];
	
	[view addSubview:scroView];
	//[finaArra addObject:@"" + emaiOrga ];
	//[finaDict setObject:emaiOrga  forKey:"" + emaiOrga + "" ];
	//var tempFinaObject = [[FinaObject alloc] init:idenOrga emai:emaiOrga type:1];
	//[finaDict setObject:tempFinaObject  forKey:"" + 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:@"Guardar" TFPosX:horiPos4  TFPosY:vertPosi-2 TFWidth:65 TFHeight:24  VView:view sizeToFit:NO Action:@selector(updateChangesAutomaticReport:)];
//	[self addButton:@"Enviar" TFPosX:horiPos2 TFPosY:vertPosi-2 TFWidth:65 TFHeight:24  VView:view sizeToFit:NO Action:@selector(sendReportByEmail:)];
	
	//[locaTabl reloadData];
	//[persTabl reloadData];
	
	[orgaPopu selectItemAtIndex:1 ];
	[self organizationSelectionPopUp:sender];
	
	}

}




- (void) reportsPanel {
	return geneRepoPane;
}




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






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


//		TABLE SOURCE DELEGATE METHODS

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

	if ( tablView == locaTabl ) {
		quer= [CPString stringWithFormat:@"SELECT name,email,id FROM %@.organizationLocations WHERE organizationId = '%@' ORDER BY name ASC",dataBase,idenOrga];
		locaArra = [self query:quer];	
		//console.log("quer locations " + quer);
		coun = [locaArra count];
		//alert("count loca " +  coun);
	}
	
	if ( tablView == persTabl ) {
		quer = [CPString stringWithFormat:@"SELECT t2.NameFirst,t2.nameLast,t2.email,t1.personId 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];
		//console.log("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 = [finaDict 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";
	
	//console.log("rowInde " +  rowInde);
	

	if ( tablView == locaTabl ) {
		valu = locaArra[rowInde];
	}
	if ( tablView == persTabl ) {
		valu = persArra[rowInde];
	}
	if ( tablView == finaTabl ) {
		//valu = finaArra[rowInde];
		var finaDictKeys = [finaDict allKeys];
		var aKey = [finaDictKeys objectAtIndex:rowInde];
		//console.log("key " +  aKey);
		var objt = [finaDict objectForKey:aKey];
		//console.log("objt " +  objt);
		valu = [objt emai];
	}
	
	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;        
		}*/
		var finaDictKeys = [finaDict allKeys];
		var aKey = [finaDictKeys objectAtIndex:rowInde];
		var objt = [finaDict objectForKey:aKey];
		
		if ( [headIden isEqualToString:@"finaEmai"] ){
			valu = [objt emai];        
		}
	}
		
	return valu;
}


@end



@implementation FinaObject : RMControllerObject {
	
	id iden               @accessors(getter=iden, setter=iden:); 
	id emai				  @accessors(getter=emai, setter=emai:);
	id type				  @accessors(getter=type, setter=type:);

}

- (id) init:(id)paraIden emai:(id)paraEmai type:(id)paraType {
	[super init];
	iden = paraIden    
	emai = paraEmai    
	type = paraType    
	/*
	Types:
	1 -> Organization
	2 -> Location
	3 -> Person
	
	*/
	return self;
}




@end






















































