
// AppController.j
// 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 RMSReportLocationController : RMControllerObject {



	CPPanel repoPane;
	id orgaPopu;
	id filtText;
	id orgaArra;
	id custArra;
	id custBackArra;
	id locaPopu;
	id locaArra;
	
	id dateStarText;
	id dateEndText;
	id datePickStarPane;
	id datePickEndPane;
	
	id nameOrga;
	id idenOrga;
	id nameLoca;
	id idenLoca;
	
	
	id cont1Popu;
	id cont2Popu;
	id cont3Popu;
	id cont4Popu;
	
	id contCorp1Popu;
	id contCorp2Popu;
	id contCorp3Popu;
	id contCorp4Popu;
	
	id jasp;
	id dictRepo;
  	id urlRepo;
  	
  	id emaiComm;
  	id repoComm;
  	
	
}



- (id) init:(id)paraAppCont {
	[super init];
 	
 	appCont = paraAppCont;
	dataBase = [appCont getDataBase];
	//alert("db init reports= " + [appCont getDataBase]);
	repoPane  = NULL;
	orgaPopu = NULL;
	 orgaArra = NULL;
	locaPopu = NULL;
	 dateStarText = NULL;
	dateStarText = NULL;
	nameOrga = "Organizaciones";
	idenOrga = 0;
	idenLoca =0;
	nameLoca = "Locaciones";
	
	cont1Popu = cont2Popu = cont3Popu = cont4Popu = NULL;
	
	contCorp1Popu = contCorp2Popu = contCorp3Popu = contCorp4Popu = NULL;
	
	dictRepo = urlRepo =  NULL;
	emaiComm = repoComm = "";
	//jasp = [[JasperSoftReporter alloc] init];
	jasp = [[JasperSoftReporter alloc] init:appCont];	
	[jasp organizationCodeSet:[appCont getOrgaCode] ];
	[jasp organizationIdSet:[appCont organizationId] ];
	[jasp cgiSetHost:[appCont getcgiHost] server:[appCont getcgiServ]];
	/*
	
	- (id) getcgiHost {
	return cgiHost;
}


- (id) getcgiServ {
	return cgiServ;
}
	cgiHost = @"199.102.237.34";
	cgiServ = @"rmws_scheduler.cgi";
	*/
	
	return self;
}


- (void)  applicationQuit {

	if ( repoPane ) {
		[repoPane orderOut:0];
		[repoPane release];
	}
	
	if (orgaPopu)     { [orgaPopu  release];}
	if (orgaArra)     { [orgaArra  release];}
	if (locaPopu)     { [locaPopu  release];}
	if (locaArra) 	  { [locaArra  release];}
	if (dateStarText) { [dateStarText  release];}
	if (dateEndText)  { [dateEndText  release];}
	if (datePickStarPane) { [datePickStarPane  release];}
	if (datePickEndPane)  { [datePickEndPane  release];}
	if (nameOrga) 	  { [nameOrga  release];}
	if (idenOrga)     { [idenOrga  release];}
	if (nameLoca)     { [nameLoca  release];}
	if (idenLoca)     { [idenLoca  release];}
	if (cont1Popu)    { [cont1Popu  release];}
	if (cont2Popu)    { [cont2Popu  release];}
	if (cont3Popu)    { [cont3Popu  release];}
	if (cont4Popu)    { [cont4Popu  release];}
	if (contCorp1Popu) { [contCorp1Popu  release];}
	if (contCorp2Popu) { [contCorp2Popu  release];}
	if (contCorp3Popu) { [contCorp3Popu  release];}
	if (contCorp4Popu) { [contCorp4Popu  release];}
	if (dictRepo) { [dictRepo  release];}
	if (urlRepo)  { [urlRepo  release];}
	if (emaiComm) {[emaiComm release];}
	if (repoComm) { [repoComm  release];}
	if (filtText)     { [filtText  release];}
	if (custBackArra) { [custBackArra  release];}
	if (custArra) { [custArra  release];}
	
	[jasp applicationQuit];
	if (jasp) { [jasp  release];}
}



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

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

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

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

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

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

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

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

- (void) clearFields:(id)sender {
		[cont1Popu removeAllItems];
		[cont2Popu removeAllItems];
		[cont3Popu removeAllItems];
		[cont4Popu removeAllItems];
		
		[contCorp1Popu removeAllItems];
		[contCorp2Popu removeAllItems];
		[contCorp3Popu removeAllItems];
		[contCorp4Popu removeAllItems];		
		
		[cont1Popu addItemWithTitle:@"Contacto"];
		[cont2Popu addItemWithTitle:@"Contacto"];
		[cont3Popu addItemWithTitle:@"Contacto"];
		[cont4Popu addItemWithTitle:@"Contacto"];
		
		[contCorp1Popu addItemWithTitle:@"Contacto"];
		[contCorp2Popu addItemWithTitle:@"Contacto"];
		[contCorp3Popu addItemWithTitle:@"Contacto"];
		[contCorp4Popu addItemWithTitle:@"Contacto"];

}

- (void)controlTextDidChange:(CPNotification)notification   {
     [self filterCustomer: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) filterCustomer:(id)sender {
	 orga = [filtText stringValue];
	 [self fillOrganizations: self];
	
}

- (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) generateReport:(id)sender {

   var indeTempOrga = [orgaPopu indexOfSelectedItem];
   var indeTempLoca = [locaPopu indexOfSelectedItem];
   	var randCode = [ [CPString UUID] substringToIndex:12];
   	urlRepo = NULL;
   if(indeTempOrga == 0 || indeTempLoca == 0){
 	 // alert("can't genereta report");
   		return;
   }

	var jaspTabl = "jsprFinalReport";
	var striStartDate = [[dateStarText stringValue] substringToIndex:10];
	var striEndDate = [[dateEndText stringValue] substringToIndex:10];
	var custStr = "|" + nameOrga + ":" + idenOrga + "|";
	var locaStr = "|" + nameLoca + ":" + idenLoca + "|";
	
	/*
   var quer =  "SELECT "; 
   quer +=  dataBase + ".eventsPermanent.calendar, ";
   quer +=  "SUBSTRING(" + dataBase + ".eventsPermanent.start_date,1,10), ";
   quer +=  "SUBSTRING(" + dataBase + ".eventsPermanent.start_date,11) ";
   quer +=  "FROM " + dataBase + ".eventsPermanent WHERE  start_date >= '" + striStartDate + " 00:01:01' AND end_date <= '" + striEndDate + " 23:59' AND customer LIKE '%" + idenOrga + "%'";
   quer += " AND location LIKE '%" + nameLoca + "%'";
   alert("quer selec " + quer);
   */
   
   /*

   //SE COMENTA ESTE BLOQUE PARA AER IMPLEMENTADO MAS ABAJO POR UNO MAS EFICIENTE
   var quer =  "SELECT "; 
   quer +=  "SUBSTR(" + dataBase + ".eventsPermanent.calendar, ";
   quer +=  " LOCATE('|'," + dataBase + ".eventsPermanent.calendar)+1, ";
   quer +=  "(CHAR_LENGTH(" + dataBase + ".eventsPermanent.calendar) - ";
   quer +=  "LOCATE('|',REVERSE(" + dataBase + ".eventsPermanent.calendar)) ";
   quer +=  "- LOCATE('|'," + dataBase + ".eventsPermanent.calendar))) AS acti, ";
   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 + "' ";
   quer += "AND location = '" + idenLoca + "' ";
   quer += "ORDER BY  start_date";
   // alert("quer selec " + 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];	
		loca = [loca stringByReplacingOccurrencesOfString:"|"  withString:@", "];
		var stri = " ('" + randCode + "','" + loca + "','" + statDate + "','" + hour + "')";
		[arraTempRepo addObject:stri];
	}

    */
    // ACA UNA VERSION MEJORADA CON FECHA 2022-10-18
    var quer =  "SELECT " + dataBase + ".eventsPermanent.calendar as acti, "; 
    //quer +=  "SUBSTR(" + dataBase + ".eventsPermanent.calendar, ";
    //quer +=  " LOCATE('|'," + dataBase + ".eventsPermanent.calendar)+1, ";
    //quer +=  "(CHAR_LENGTH(" + dataBase + ".eventsPermanent.calendar) - ";
    //quer +=  "LOCATE('|',REVERSE(" + dataBase + ".eventsPermanent.calendar)) ";
    //quer +=  "- LOCATE('|'," + dataBase + ".eventsPermanent.calendar))) AS acti, ";
    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 + "' ";
   	quer += "AND location = '" + idenLoca + "' ";
   	quer += "ORDER BY  start_date";
   	// alert("quer selec " + 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 elem     = valu[0];		
		var statDate = valu[1];		
		var hour     = valu[2];	
        loca         = [elem stringByReplacingOccurrencesOfString:@" |" withString:@"|"];
        loca         = [loca stringByReplacingOccurrencesOfString:@"| " withString:@"|"];
        loca         = [loca stringByReplacingOccurrencesOfString:@"|" withString:@", "];
        var pref     = [loca substringToIndex:2];
        if ( [[loca substringToIndex:2] isEqualToString:@", "]) {
            var rnge = CPMakeRange(2,[loca length] - 2);
            loca     = [loca substringWithRange:rnge];
        }
        var rnge = CPMakeRange([loca length] - 2,2);
        if ( [[loca substringWithRange:rnge] isEqualToString:@", "]) {
            loca = [loca substringToIndex:[loca length] - 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 = "";
   
    //Testing   
    if ( coun > 30 ){
   
  		while( coun > 30){
  		 //alert("coun start while "+ coun);
   		   for (var i =0; i < 30; i++){  
   				var valu =  [arraTempRepo objectAtIndex:0];
   				//alert ("valu "+ valu);
				var temp  = i + 1;	
				if(temp == 30){
					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];
    begiSql = "INSERT INTO " + dataBase + "." + jaspTabl + " (reportCode,FIELD01,FIELD02,FIELD03) VALUES " ;
    middSql = "";

    
    //end testing
   
    
      
   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 ;
    //alert("insert query " + quer);
    [self query:quer];
   }
    var repoCommTemp = [repoComm stringValue];
   //var titlRepo = nameLoca + " " + striStartDate + " - " + striEndDate;
    var titlRepo = "Programacion: "+ striStartDate + " - " + striEndDate + ":sc:" +  nameLoca; 
 	//Programación: startDate - EndDate:sc:Name
    dictRepo = [[CPDictionary alloc] init];
    [dictRepo setObject:titlRepo   forKey:"title" ];
    [dictRepo setObject:"Actividad: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];
    //[jasp showPreviousView:urlRepo];  
    var uri =  encodeURI(urlRepo);
	window.open(uri);

	
}




- (void) locationsSelectionPopUp:(id)sender {
	
	var inde = [locaPopu indexOfSelectedItem];



		[self clearFields:0];


		[locaPopu selectItemAtIndex:inde];
		inde --;
		var valuList = [locaArra[inde] valueList];
		idenLoca = valuList[0];
		nameLoca = valuList[1];	
		
		//Contacts
		var quer = "SELECT persons.email FROM " + dataBase + ".persons, " + dataBase + ".organizationLocations WHERE " + dataBase + ".persons.id = " + dataBase + ".organizationLocations.Contact0Id AND " + dataBase + ".organizationLocations.id = " + idenLoca + "  LIMIT 1";
		var arraTemp = [self query:quer];
		if( [arraTemp count] >= 1){
			var arraTemp2 = [[arraTemp objectAtIndex:0] valueList];
			var valu =  arraTemp2[0] ;
			[cont1Popu addItemWithTitle:@"" + valu];
			[cont1Popu selectItemAtIndex:1];
		}
		
		quer = "SELECT persons.email FROM " + dataBase + ".persons, " + dataBase + ".organizationLocations WHERE " + dataBase + ".persons.id = " + dataBase + ".organizationLocations.Contact1Id AND " + dataBase + ".organizationLocations.id = " + idenLoca + "  LIMIT 1";
		arraTemp = [self query:quer];
		if( [arraTemp count] >= 1){
			var arraTemp2 = [[arraTemp objectAtIndex:0] valueList];
			var valu =  arraTemp2[0] ;
			[cont2Popu addItemWithTitle:@"" + valu];
			[cont2Popu selectItemAtIndex:1];
		}
		
		quer = "SELECT persons.email FROM " + dataBase + ".persons, " + dataBase + ".organizationLocations WHERE " + dataBase + ".persons.id = " + dataBase + ".organizationLocations.Contact2Id AND " + dataBase + ".organizationLocations.id = " + idenLoca + "  LIMIT 1";
		arraTemp = [self query:quer];
		if( [arraTemp count] >= 1){
			var arraTemp2 = [[arraTemp objectAtIndex:0] valueList];
			var valu =  arraTemp2[0] ;
			[cont3Popu addItemWithTitle:@"" + valu];
			[cont3Popu selectItemAtIndex:1];
		}
		
		quer = "SELECT persons.email FROM " + dataBase + ".persons, " + dataBase + ".organizationLocations WHERE " + dataBase + ".persons.id = " + dataBase + ".organizationLocations.Contact3Id AND " + dataBase + ".organizationLocations.id = " + idenLoca + "  LIMIT 1";
		arraTemp = [self query:quer];
		if( [arraTemp count] >= 1){
			var arraTemp2 = [[arraTemp objectAtIndex:0] valueList];
			var valu =  arraTemp2[0] ;
			[cont4Popu addItemWithTitle:@"" + valu];
			[cont4Popu selectItemAtIndex:1];
		}
	
	 //Corpotatives
	 	quer = "SELECT persons.email FROM " + dataBase + ".persons, " + dataBase + ".organizationLocations WHERE " + dataBase + ".persons.id = " + dataBase + ".organizationLocations.ContactCorporate0Id AND " + dataBase + ".organizationLocations.id = " + idenLoca + "  LIMIT 1";
		arraTemp = [self query:quer];
		//alert("quer " + quer);
		if( [arraTemp count] >= 1){
			var arraTemp2 = [[arraTemp objectAtIndex:0] valueList];
			var valu =  arraTemp2[0] ;
			[contCorp1Popu addItemWithTitle:@"" + valu];
			[contCorp1Popu selectItemAtIndex:1];
		}
		
		quer = "SELECT persons.email FROM " + dataBase + ".persons, " + dataBase + ".organizationLocations WHERE " + dataBase + ".persons.id = " + dataBase + ".organizationLocations.ContactCorporate1Id AND " + dataBase + ".organizationLocations.id = " + idenLoca + "  LIMIT 1";
		arraTemp = [self query:quer];
		if( [arraTemp count] >= 1){
			var arraTemp2 = [[arraTemp objectAtIndex:0] valueList];
			var valu =  arraTemp2[0] ;
			[contCorp2Popu addItemWithTitle:@"" + valu];
			[contCorp2Popu selectItemAtIndex:1];
		}
		
		quer = "SELECT persons.email FROM " + dataBase + ".persons, " + dataBase + ".organizationLocations WHERE " + dataBase + ".persons.id = " + dataBase + ".organizationLocations.ContactCorporate2Id AND " + dataBase + ".organizationLocations.id = " + idenLoca + "  LIMIT 1";
		arraTemp = [self query:quer];
		if( [arraTemp count] >= 1){
			var arraTemp2 = [[arraTemp objectAtIndex:0] valueList];
			var valu =  arraTemp2[0] ;
			[contCorp3Popu addItemWithTitle:@"" + valu];
			[contCorp3Popu selectItemAtIndex:1];
		}
		
		quer = "SELECT persons.email FROM " + dataBase + ".persons, " + dataBase + ".organizationLocations WHERE " + dataBase + ".persons.id = " + dataBase + ".organizationLocations.ContactCorporate3Id AND " + dataBase + ".organizationLocations.id = " + idenLoca + "  LIMIT 1";
		arraTemp = [self query:quer];
		if( [arraTemp count] >= 1){
			var arraTemp2 = [[arraTemp objectAtIndex:0] valueList];
			var valu =  arraTemp2[0] ;
			[contCorp4Popu addItemWithTitle:@"" + valu];
			[contCorp4Popu selectItemAtIndex:1];
		}		
	
}


- (void) organizationSelectionPopUp:(id)sender {
	
	var inde = [orgaPopu indexOfSelectedItem];
	[self clearFields:0];
	  //Locations
		[locaPopu removeAllItems];
		[locaPopu addItemWithTitle:@"Locaciones"];
		locaArra = NULL;	
	if (inde == 0) {
		[filtText setStringValue:@""];
		 //alert("reload popu orga");
		[orgaPopu removeAllItems];
		[orgaPopu addItemWithTitle:@"Organizaciones"];
		custBackArra = NULL;
			
		
		var quer = [CPString stringWithFormat:@"SELECT idPrimary,name FROM %@.organizations WHERE idPrimary!='%@' AND active=1 ORDER BY name",
		  dataBase,orgaId];
		custBackArra = [self query:quer];
		var coun = [custBackArra count];
		var popuArra = [[CPArray alloc] init];
		for ( var i=0; i<coun; i++ ) {
			var valuList = [custBackArra[i] valueList];
			idenOrga = valuList[0];
			nameOrga = valuList[1];
			var arraTemp = [[CPArray alloc] init];
			[arraTemp addObject:idenOrga];
			[arraTemp addObject:nameOrga];
			[popuArra addObject:arraTemp];
			[orgaPopu addItemWithTitle:nameOrga];
		}
		custArra = popuArra;
	}else{
		[orgaPopu selectItemAtIndex:inde];
		inde --;		
		var valuList = custArra[inde];
		idenOrga = valuList[0];
		nameOrga = valuList[1];
	
		var quer = [CPString stringWithFormat:@"SELECT id,name FROM %@.organizationLocations WHERE organizationId='%@' AND active=1 ORDER BY name",
		  dataBase,idenOrga];
		locaArra= [self query:quer];
		var coun = [locaArra count];
		for ( var i=0; i<coun; i++ ) {
			var valuList = [locaArra[i] valueList];
			idenLoca = valuList[0];
			nameLoca = valuList[1];
			[locaPopu addItemWithTitle:nameLoca];
			}
		}
}










- (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 = 720;
	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 Locacion"];
	
	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;
	//Organizations
	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];
	
	//Locations
	vertPosi += 40;
	var labe= [self addTextField:@"Locaciones:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	
	locaPopu = [self addPopupButton:@"Locaciones" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[locaPopu setTarget:self];
	[locaPopu setAction:@selector(locationsSelectionPopUp:)];
			
	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:)];
	
	var widtPopu = 200;
	var heigPopu = 24;
	var spacePopu = 10;
	
	//Contacs
	vertPosi += 40;
	labe= [self addTextField:@"Contactos:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	cont1Popu = [self addPopupButton:@"Contacto" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:widtPopu TFHeight:heigPopu  VView:view pullsDown:NO];
	[cont1Popu setTarget:self];
	[cont1Popu setAction:@selector(cont1PopuSelectionPopUp:)];
	vertPosi +=  heigPopu +spacePopu;
	
	cont2Popu = [self addPopupButton:@"Contacto" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:widtPopu TFHeight:heigPopu  VView:view pullsDown:NO];
	[cont2Popu setTarget:self];
	[cont2Popu setAction:@selector(cont2PopuSelectionPopUp:)];
	vertPosi += heigPopu + spacePopu;
	
	cont3Popu = [self addPopupButton:@"Contacto" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:widtPopu TFHeight:heigPopu  VView:view pullsDown:NO];
	[cont3Popu setTarget:self];
	[cont3Popu setAction:@selector(cont3PopuSelectionPopUp:)];
	vertPosi +=  heigPopu + spacePopu;
	
	cont4Popu = [self addPopupButton:@"Contacto" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:widtPopu TFHeight:heigPopu  VView:view pullsDown:NO];
	[cont4Popu setTarget:self];
	[cont4Popu setAction:@selector(cont4PopuSelectionPopUp:)];
	vertPosi += heigPopu + spacePopu;
	
	//Contacs Corporatives
	vertPosi += 20;
	labe= [self addTextField:@"Coporativos:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	
	contCorp1Popu = [self addPopupButton:@"Contacto" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:widtPopu TFHeight:heigPopu  VView:view pullsDown:NO];
	[contCorp1Popu setTarget:self];
	[contCorp1Popu setAction:@selector(contCorp1PopuSelectionPopUp:)];
	vertPosi += heigPopu + spacePopu;
	
	contCorp2Popu = [self addPopupButton:@"Contacto" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:widtPopu TFHeight:heigPopu  VView:view pullsDown:NO];
	[contCorp2Popu setTarget:self];
	[contCorp2Popu setAction:@selector(contCorp2PopuSelectionPopUp:)];
	vertPosi += heigPopu + spacePopu;
	
	contCorp3Popu = [self addPopupButton:@"Contacto" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:widtPopu TFHeight:heigPopu  VView:view pullsDown:NO];
	[contCorp3Popu setTarget:self];
	[contCorp3Popu setAction:@selector(contCorp3PopuSelectionPopUp:)];
	vertPosi += heigPopu + spacePopu;
	
	contCorp4Popu = [self addPopupButton:@"Contacto" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:widtPopu TFHeight:heigPopu  VView:view pullsDown:NO];
	[contCorp4Popu setTarget:self];
	[contCorp4Popu setAction:@selector(contCorp4PopuSelectionPopUp:)];
	
	//Comment Email
	vertPosi += 50;
	labe = [self addTextField:@"Comentario\n email:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:15 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	vertPosi -= 10;
	emaiComm = [self addTextField:@"" TFPosX:horiPos2 TFPosY:vertPosi-4 TFWidth:200 TFHeight:2*vertLineHeig VView:view Editable:YES];
    [emaiComm setLineBreakMode:CPLineBreakByWordWrapping];
    
    //Comment Report
    vertPosi += 70;
	labe = [self addTextField:@"Comentario\n Reporte:" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	vertPosi -= 10;
	repoComm = [self addTextField:@" " TFPosX:horiPos2 TFPosY:vertPosi-4 TFWidth:200 TFHeight:2*vertLineHeig VView:view Editable:YES];
    [repoComm setLineBreakMode:CPLineBreakByWordWrapping];
	
	vertPosi += 65;
	[self addButton:@"Generar" TFPosX:horiPos2  TFPosY:vertPosi-2 TFWidth:80 TFHeight:24  VView:view sizeToFit:NO Action:@selector(generateReport:)];
	horiPos2 += 80 + 20
	[self addButton:@"Enviar" TFPosX:horiPos2  TFPosY:vertPosi-2 TFWidth:80 TFHeight:24  VView:view sizeToFit:NO Action:@selector(sendReportByEmail:)];
}

- (void) sendReportByEmail:(id)sender {	
	
	var inde1 = [cont1Popu titleOfSelectedItem];
	var inde2 = [cont2Popu titleOfSelectedItem];
	var inde3 = [cont3Popu titleOfSelectedItem];
	var inde4 = [cont4Popu titleOfSelectedItem];
	
	var inde5 = [contCorp1Popu titleOfSelectedItem];
	var inde6 = [contCorp2Popu titleOfSelectedItem];
	var inde7 = [contCorp3Popu titleOfSelectedItem];
	var inde8 = [contCorp4Popu titleOfSelectedItem];
	var arra =  [CPArray array];
	
	if ( inde1 && ! [inde1 isEqualToString:@"Contacto"] ){
		  // stri += inde1+ "\n";
		   [arra addObject:inde1];
		   //flag = 1;
	}
	
	if ( inde2 &&! [inde2 isEqualToString:@"Contacto"] ){
		    [arra addObject:inde2];
	}
	
	if ( inde3 && ! [inde3 isEqualToString:@"Contacto"] ){
		    [arra addObject:inde3];
	}
	
	if ( inde4 && ! [inde4 isEqualToString:@"Contacto"] ){
		    [arra addObject:inde4];
	}
	//Corporatives
	if ( inde5 && ! [inde5 isEqualToString:@"Contacto"] ){
		    [arra addObject:inde5];
	}
	
	if ( inde6 && ! [inde6 isEqualToString:@"Contacto"] ){
		   [arra addObject:inde6];
	}
	
	if ( inde7 && ! [inde7 isEqualToString:@"Contacto"] ){
		    [arra addObject:inde7];
	}






	if ( inde8 && ! [inde8 isEqualToString:@"Contacto"] ){
		    [arra addObject:inde8];
	}
	
	
	if([arra count] > 0){	
		urlRepo = NULL;
	    if (!urlRepo){
	        [self generateReport:sender];
	     }
	     
		if (urlRepo) {
			urlRepo = [urlRepo stringByReplacingOccurrencesOfString:@"192.168.2.252" withString:@"167.250.194.153"];
			var comm = [emaiComm stringValue]; 
			[jasp emailReportToList:arra :urlRepo :comm];
			urlRepo = NULL;
		}
	}
	
	
}



@end
