
// 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 RMSReportAnnualController : RMControllerObject {



	CPPanel repoPane;
	id orgaPopu;
	id filtText;
	id orgaArra;
	id custArra;
	id custBackArra;
	id locaPopu;
	id locaArra;
	
	id prevIndeOrgaPopu;
	
	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 actiPopu;
  	id actiArra;
  	id actiListTabl;
  	id actiListArra;
  	//CPString        valuActivi               @accessors;
  	
  	
  	
  	id yearPopu;
  	
  	id eneroDict;
  	id febreroDict;
  	id marzoDict;
  	id abrilDict;
  	id mayoDict;
  	id junioDict;
  	id julioDict;
  	id agostoDict;
  	id setiembreDict;
  	id octubreDict;
  	id noviembreDict;
  	id diciembreDict;
  		
	
}



- (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]];
	
	 eneroDict     = [[CPDictionary alloc] init];
  	 febreroDict   = [[CPDictionary alloc] init];
  	 marzoDict     = [[CPDictionary alloc] init];
  	 abrilDict     = [[CPDictionary alloc] init];
  	 mayoDict      = [[CPDictionary alloc] init];
  	 junioDict     = [[CPDictionary alloc] init];
  	 julioDict     = [[CPDictionary alloc] init];
  	 agostoDict    = [[CPDictionary alloc] init];
  	 setiembreDict = [[CPDictionary alloc] init];
  	 octubreDict   = [[CPDictionary alloc] init];
  	 noviembreDict = [[CPDictionary alloc] init];
  	 diciembreDict = [[CPDictionary alloc] init];
  	 
  	 actiListArra = [[CPArray alloc] init];
  	 
	/*
	
	- (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)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 notes = "";
   var indeTempOrga = [orgaPopu indexOfSelectedItem];
   var indeTempLoca = [locaPopu indexOfSelectedItem];
   [self fillDictionariesDefaultValues];
    var coun1 = 0; var coun2 = 0; var coun3 = 0; var coun4 = 0;
    var coun5 = 0; var coun6 = 0; var coun7 = 0; var coun8 = 0;
   	var randCode = [ [CPString UUID] substringToIndex:12];
   	urlRepo = NULL;
   if(indeTempOrga == 0 ){
 	 [glblAlerPane showWithMessage:@"Atencion" info:"Debe indicar la organización."];
      return; 
   }
   
   if( indeTempLoca == 0){
 	 [glblAlerPane showWithMessage:@"Atencion" info:"Debe indicar la locación."];
      return; 
   }
   
   if( [actiListArra count] == 0){
 	 [glblAlerPane showWithMessage:@"Atencion" info:"Debe agregar al menos una actividad."];
      return; 
   }
  
   
   /*
   var nameOrga = "Aluap";
   var idenOrga = "alua_cr";
   
   var nameLoca = "Aluap";
   var idenLoca = "3259";
   */
   var actiDesc = [actiPopu titleOfSelectedItem];
   var year = [yearPopu titleOfSelectedItem];
   var colo  = "0";
   var colo1 = "B";
   var colo2 = "R";
   var colo3 = "G";
   var colo4 = "Y";
   var colo5 = "O";
   var colo6 = "GR";
   var colo7 = "C";
   var colo8 = "RR";
   

   
   
    var quer = "";
    var querStriActi = " AND ( ";
    var counActiLis = [actiListArra count];
    for (var k = 0; k < counActiLis; k++ ) {
    	var valuList =  actiListArra[k];
    	var tempK = k + 1;
    	if (tempK == counActiLis){
    		querStriActi += "oa2.description = '" + valuList + "' ";
    	}else{
    		querStriActi += "oa2.description = '" + valuList + "' OR ";
    	}
    }
    querStriActi += " )";
    
    quer = [CPString stringWithFormat:@"SELECT Distinct GROUP_CONCAT(distinct oa.description order by oa.description Separator '|') as calendario, GROUP_CONCAT(distinct oa.id order by oa.description Separator '|') as ids "];
    quer += "FROM " + dataBase + ".eventActivity as ea Inner Join " + dataBase + ".organizationActivities as oa on ea.idActivity = oa.id WHERE ";
    quer += "ea.idEvent in (SELECT ea2.idEvent FROM " + dataBase + ".eventActivity as ea2 Inner Join " + dataBase + ".organizationActivities as oa2 ";
    quer += "on ea2.idActivity = oa2.id inner join " + dataBase + ".eventsPermanent  as ep on ea2.idEvent = ep.Id Where  ";
    quer += "customer  = '"  + idenOrga +  "' ";
    quer += "AND location = '"  + idenLoca + "' ";
    quer +=  querStriActi + " ";
    quer += "AND start_date like '%" + year + "%' group by ea2.idEvent) ";
    quer += "group by ea.idEvent;";
    var arraAuxActi = [self query: quer];

    //quer = [CPString stringWithFormat:@"SELECT * "];
    //quer += "FROM " + dataBase + ".eventsPermanent WHERE " ;
    //quer += "customer = '"+idenOrga+"' ";
    //quer += "AND location = '" + idenLoca + "' ";
    //quer +=  querStriActi + " ";
    //quer += "AND start_date like '%" + year + "%' ";
    //quer += "ORDER BY id ASC limit 5";
       //console.log(quer);

    if ( [arraAuxActi count] == 0 ) {
    	[glblAlerPane showWithMessage:@"Atención" info:"No se encontraron datos."];
      	return; 
    }
    
  var counArraAuxActi = [arraAuxActi count];
  for (var j = 0; j < counArraAuxActi; j ++){
	  var valuList =  [[arraAuxActi objectAtIndex:j] valueList] ;
      var iteTemp = j + 1;
    //console.log(valuList);
    quer = [CPString stringWithFormat:@"SELECT "];
       quer += [CPString stringWithFormat:@"SUBSTRING(ep.start_date,6,2) AS _month, ",dataBase];
       quer += [CPString stringWithFormat:@"SUBSTRING(ep.start_date,9,2) AS _day ",dataBase];
       quer += " FROM " + dataBase + ".eventsPermanent " ;
       quer += " as ep inner join "+dataBase+".eventActivity as ea on ep.id = ea.idEvent " ;
       quer += " Inner Join "+dataBase+".organizationActivities as oa on ea.idActivity = oa.id Where";
       quer += " ep.customer  = '" + + idenOrga +  "' ";
       quer += "AND ep.location = '" + idenLoca + "' ";
       quer += "AND ep.start_date like '%" + year + "%' ";
       quer += "group by ep.id asc having GROUP_CONCAT(distinct oa.id order by oa.description Separator '|')  = '"+valuList[1]+"'";
       //console.log(quer);
       var tempArra = [self query: quer];
       var coun = [tempArra count];
       switch (iteTemp){			
				case 1:
				coun1 = coun;
				break;					
				case 2:
				coun2 = coun;
				break;		
				case 3:
				coun3 = coun;
				break;			
				case 4:
				coun4 = coun;
				break;			
				case 5:
				coun5 = coun;
				break;			
				case 6:
				coun6 = coun;
				break;			
				case 7:
				coun7 = coun;
				break;			
				case 8:
				coun8 = coun;
				break;			
				default:
				break;			
			}
       
       var stri = "";
       var iterTemp = 0;
       var myKeys;
       for (var i = 0; i < coun; i++ ) {
       		var arraTemp2 = [[tempArra objectAtIndex:i] valueList];
			var mont =  arraTemp2[0];
			var day  =  arraTemp2[1];
			stri += "\n" + mont + ", " + day ;
			
			switch (iteTemp){			
				case 1:
				colo = colo1;
				break;					
				case 2:
				colo = colo2;
				break;		
				case 3:
				colo = colo3;
				break;			
				case 4:
				colo = colo4;
				break;			
				case 5:
				colo = colo5;
				break;			
				case 6:
				colo = colo6;
				break;			
				case 7:
				colo = colo7;
				break;			
				case 8:
				colo = colo8;
				break;			
				default:
				break;			
			}
			

			myKeys = [eneroDict allKeys];
			 if ( mont == "1" || mont == "01" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [eneroDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [eneroDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[eneroDict setObject:"" + day + ":" + colo forKey: aKey ];	
         			}
				}
			}
			

			 myKeys = [febreroDict allKeys];
			 if ( mont == "2" || mont == "02" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [febreroDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [febreroDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[febreroDict setObject:"" + day + ":" +colo forKey: aKey ];	
         			}
				}
			}
			
			
			 myKeys = [marzoDict allKeys];
			 if ( mont == "3" || mont == "03" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [marzoDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [marzoDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[marzoDict setObject:"" + day + ":" + colo forKey: aKey ];	
         			}
				}
			}
			
			
			myKeys = [abrilDict allKeys];
			 if ( mont == "4" || mont == "04" ){
			
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				for (iterTemp = 0; iterTemp < [abrilDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [abrilDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			// alert(aObj + " == " + day + " key ->" + aKey);
         			if (aObj == day){
         				[abrilDict setObject:"" + day + ":" + colo forKey: aKey ];	
         				iterTemp = [abrilDict count];
         			}
				}
			}
			

			 myKeys = [mayoDict allKeys];
			 if ( mont == "5" || mont == "05" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [mayoDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [mayoDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[mayoDict setObject:"" + day + ":" + colo forKey: aKey ];	
         			}
				}
			}
			

			 myKeys = [junioDict allKeys];
			 if ( mont == "6" || mont == "06" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [junioDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [junioDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[junioDict setObject:"" + day + ":" + colo forKey: aKey ];	
         			}
				}
			}
			
			 myKeys = [julioDict allKeys];
			 if ( mont == "7" || mont == "07" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				for (iterTemp = 0; iterTemp < [julioDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [julioDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         			    console.log(aObj);
         			    console.log(randCode);
         				[julioDict setObject:"" + day + ":" + colo forKey: aKey ];	
         			}
				}
			}
			
			  myKeys = [agostoDict allKeys];
			 if ( mont == "8" || mont == "08" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [agostoDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [agostoDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[agostoDict setObject:"" + day + ":" + colo forKey: aKey ];	
         			}
				}
			}
			
			myKeys = [setiembreDict allKeys];
			 if ( mont == "9" || mont == "09" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [setiembreDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [setiembreDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[setiembreDict setObject:"" + day + ":" + colo forKey: aKey ];	
         			}
				}
			}
			

			 myKeys = [octubreDict allKeys];
			 if ( mont == "10"){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [octubreDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [octubreDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[octubreDict setObject:"" + day + ":" + colo forKey: aKey ];	
         			}
				}
			}
			

			 myKeys = [noviembreDict allKeys];
			 if ( mont == "11" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [noviembreDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [noviembreDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[noviembreDict setObject:"" + day + ":" +  colo forKey: aKey ];	
         			}
				}
			}
			
			
			myKeys = [diciembreDict allKeys];
			 if ( mont == "12" ){
			 if (day < 10  && day >= 1){
			 		day = [day stringByReplacingOccurrencesOfString:@"0" withString:@""];
				}
				
				for (iterTemp = 0; iterTemp < [diciembreDict count]; iterTemp ++ ){
					var aKey = [myKeys objectAtIndex:iterTemp];
         			var aObj = [diciembreDict objectForKey:aKey];
         			aObj = [aObj stringByReplacingOccurrencesOfString:@":0" withString:@""];
         			if (aObj == day){
         				[diciembreDict setObject:"" + day + ":" + colo forKey: aKey ];	
         			}
				}
			}
       }
  }
       

	var jaspTabl = "jsprCalendarReport";
	   


quer = [CPString stringWithFormat:@"INSERT INTO %@.%@ ",dataBase,jaspTabl];
	   quer += "(repoCode,MONTHS,";
	   quer += "sun1,mon1,tue1,wed1,thu1,fri1,sat1,";
	   quer += "sun2,mon2,tue2,wed2,thu2,fri2,sat2,";
	   quer += "sun3,mon3,tue3,wed3,thu3,fri3,sat3) ";
	   quer += "VALUES ";
	
	var striQuer = "";
	//Enero:Febreo:Marzo
	for (var i = 1; i <= 42; i ++){
			var aKey =  i;
			for (var j = 1; j <= 7; j ++ ){
				striQuer +=  "'" + [eneroDict objectForKey:"" + aKey + "" ] + "',";
				aKey ++;
			}
			
			aKey = i;
			for (var j = 1; j <= 7; j ++ ){
			    striQuer +=  "'" + [febreroDict objectForKey:"" + aKey + ""] + "',";
				aKey ++;
			}
			
			aKey = i;
			for (var j = 1; j <= 7; j ++ ){
				if (j == 7){
					striQuer += "'" + [marzoDict objectForKey:"" + aKey + ""] + "'";
				}else{
					striQuer +=  "'" + [marzoDict objectForKey:"" + aKey + ""] + "',";
				}
				aKey ++;
			}
			i += 6;
		quer += [CPString stringWithFormat:@"\n('%@','Enero:Febrero:Marzo',%@),",randCode,striQuer];
		striQuer = "";
		}
		
		//Abril:Mayo:Junio
	for (var i = 1; i <= 42; i ++){
			var aKey =  i;
			
			for (var j = 1; j <= 7; j ++ ){
				striQuer +=  "'" + [abrilDict objectForKey:"" + aKey + "" ] + "',";
				aKey ++;
			}
			
			aKey = i;
			for (var j = 1; j <= 7; j ++ ){
				striQuer +=  "'" + [mayoDict objectForKey:"" + aKey + "" ] + "',";
				aKey ++;
			}
			
			aKey = i;
			for (var j = 1; j <= 7; j ++ ){				
				if (j == 7){
					striQuer += "'" + [junioDict objectForKey:"" + aKey + ""] + "'";
				}else{
					striQuer +=  "'" + [junioDict objectForKey:"" + aKey + "" ] + "',";
				}
				aKey ++;
				
			}
			i += 6;
		quer += [CPString stringWithFormat:@"\n('%@','Abril:Mayo:Junio',%@),",randCode,striQuer];
		striQuer = "";
		}
	
	//Julio:Agosto:Septiembre
	for (var i = 1; i <= 42; i ++){
			var aKey =  i;
			for (var j = 1; j <= 7; j ++ ){
				striQuer +=  "'" + [julioDict objectForKey:"" + aKey + "" ] + "',";
				aKey ++;
			}
			
			aKey = i;
			for (var j = 1; j <= 7; j ++ ){
				striQuer +=  "'" + [agostoDict objectForKey:"" + aKey + "" ] + "',";
				aKey ++;
			}
			
			aKey = i;
			for (var j = 1; j <= 7; j ++ ){
				if (j == 7){
					striQuer += "'" + [setiembreDict objectForKey:"" + aKey + ""] + "'";
				}else{
					striQuer +=  "'" + [setiembreDict objectForKey:"" + aKey + ""] + "',";
				}
				aKey ++;
			}
			i += 6;
		quer += [CPString stringWithFormat:@"\n('%@','Julio:Agosto:Septiembre',%@),",randCode,striQuer];
		striQuer = "";
		}
		
		
	//Octubre:Noviembre:Diciembre
	for (var i = 1; i <= 42; i ++){
			var aKey =  i;
			for (var j = 1; j <= 7; j ++ ){
				striQuer +=  "'" + [octubreDict objectForKey:"" + aKey + ""] + "',";
				aKey ++;
			}
			
			aKey = i;
			for (var j = 1; j <= 7; j ++ ){
				striQuer +=  "'" + [noviembreDict objectForKey:"" + aKey + "" ] + "',";
				aKey ++;
			}
			
			aKey = i;
			for (var j = 1; j <= 7; j ++ ){
				if (j == 7){
					striQuer += "'" + [diciembreDict objectForKey: "" + aKey + ""] + "'";
				}else{
					striQuer +=  "'" + [diciembreDict objectForKey: "" + aKey + ""] + "',";
				}
				aKey ++;
			}
			i += 6;
			if (i == 42 ){
				quer += [CPString stringWithFormat:@"\n('%@','Octubre:Noviembre:Diciembre',%@)",randCode,striQuer];
			}else{
				quer += [CPString stringWithFormat:@"\n('%@','Octubre:Noviembre:Diciembre',%@),",randCode,striQuer];
			}
		
		striQuer = "";
		}
		quer = [quer stringByReplacingOccurrencesOfString:@"null" withString:@"0:0"];
		//alert(quer);
		[self query:quer];

 
   	
   var headYear = year;
   var userAlias = nameOrga + " - " + nameLoca;
 	
 	var task1,task2,task3,task4,task4,task5,task6,task7,task8;
 	if (coun1 > 0){
 		task1 = [[arraAuxActi objectAtIndex:0] valueList][0];
 		task1 = "- " +[task1 stringByReplacingOccurrencesOfString:@"|" withString:@" , "];
 	}
 	
 	if (coun2 > 0){
 		task2 = [[arraAuxActi objectAtIndex:1] valueList][0];
 		task2 = "- " +[task2 stringByReplacingOccurrencesOfString:@"|" withString:@" , "]; 		
 	}
 	
 	if (coun3 > 0){
 		task3 = [[arraAuxActi objectAtIndex:2] valueList][0];
  		task3 = "- " +[task3 stringByReplacingOccurrencesOfString:@"|" withString:@" , "];
 	}
 	
 	
 	if (coun4 > 0){
 		task4 = [[arraAuxActi objectAtIndex:3] valueList][0];
  		task4 = "- " +[task4 stringByReplacingOccurrencesOfString:@"|" withString:@" , "];
 	}
 	
 	if (coun5 > 0){
 		task5 = [[arraAuxActi objectAtIndex:4] valueList][0];
  		task5 = "- " +[task5 stringByReplacingOccurrencesOfString:@"|" withString:@" , "];
 	}
 	
 	if (coun6 > 0){
 		task6 = [[arraAuxActi objectAtIndex:5] valueList][0];
  		task6 = "- " +[task6 stringByReplacingOccurrencesOfString:@"|" withString:@" , "];
 	}
 	
 	if (coun7 > 0){
 		task7 = [[arraAuxActi objectAtIndex:6] valueList][0];
  		task7 = "- " +[task7 stringByReplacingOccurrencesOfString:@"|" withString:@" , "];
 	}
 	
 	if (coun8 > 0){
 		task8 = [[arraAuxActi objectAtIndex:7] valueList][0];
  		task8 = "- " +[task8 stringByReplacingOccurrencesOfString:@"|" withString:@" , "];
 	}

   if ( [repoComm stringValue] != "" ){
    notes = [repoComm stringValue];
   }
      

    dictRepo = [[CPDictionary alloc] init];
    [dictRepo setObject:headYear   forKey:"headYear" ];
    [dictRepo setObject:userAlias   forKey:"userAlias" ];
    [dictRepo setObject:task1 forKey:"Task_1" ];
    [dictRepo setObject:task2 forKey:"Task_2" ];
    [dictRepo setObject:task3 forKey:"Task_3" ];
    [dictRepo setObject:task4 forKey:"Task_4" ];
    [dictRepo setObject:task5 forKey:"Task_5" ];
    [dictRepo setObject:task6 forKey:"Task_6" ];
    [dictRepo setObject:task7 forKey:"Task_7" ];
    [dictRepo setObject:task8 forKey:"Task_8" ];
    [dictRepo setObject:notes forKey:"Notes"  ];
    [dictRepo setObject:randCode forKey:"repoCode" ];
	[dictRepo setObject:dataBase forKey:"sourceOfData" ];
	[dictRepo setObject:"ORKIN_VisitingProgram" forKey:"myModel" ];
	var jsprMsql = "b14_2"; 
	var myPathTemp = "/reports/Orkin";
	[dictRepo setObject:myPathTemp forKey:"myPath" ];
	
	
    //[jasp showPreviousView:urlRepo];  
    //Uncomment
    urlRepo = [jasp  buildJasperURL:dictRepo];
    var uri =  encodeURI(urlRepo);
	window.open(uri);


	
}


- (void)  fillDictionariesDefaultValues {

	 [eneroDict removeAllObjects] 
  	 [febreroDict removeAllObjects];
  	 [marzoDict removeAllObjects];
  	 [abrilDict removeAllObjects];
  	 [mayoDict removeAllObjects ];
  	 [junioDict removeAllObjects];
  	 [julioDict removeAllObjects];
  	 [agostoDict removeAllObjects];
  	 [setiembreDict removeAllObjects];
  	 [octubreDict removeAllObjects ];
  	 [noviembreDict removeAllObjects];
  	 [diciembreDict removeAllObjects];
	
	//Added 18/12/2017
	var year = [yearPopu titleOfSelectedItem];
	var dateStar = [[CPDate alloc] initWithString:year+"2016-01-01 00:00:00 -0600"];
	var dayStar = 5;
	var yearInt = [year intValue];
	var addDays = 0;
	var leapYear = 0;
	for(var i = 2016; i <= yearInt;i++){
		if((i % 4) == 0 && ((i % 100) != 0 || (i % 400) == 0)){
			if(i != yearInt){
				addDays += 31622400;
			}else{
				leapYear = 29;
			}
		}else{
			if(i != yearInt){
				addDays += 31536000;
			}else{
				leapYear = 28;
			}
		}
	}
	
	var dateEnd = [dateStar dateByAddingTimeInterval:addDays];
	var diffDays= [dateEnd timeIntervalSinceDate: dateStar];
	diffDays = (diffDays/86400);
	var diffDate = diffDays;
	diffDays = [(diffDays/7) intValue] * 7;
	diffDays = (diffDate - diffDays) + dayStar;
	diffDays = diffDays % 7;
	//End added

	//Enero
	var counDay = 0;
	
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 31){
			[eneroDict setObject: "0:0"   forKey:"" + i + "" ];
		}else{
			[eneroDict setObject: counDay + ":0"   forKey:"" + i + "" ];
		}
	}
	diffDays = (3+diffDays)%7;
	
	//Febrero
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > leapYear){
			[febreroDict setObject: "0:0"   forKey:"" + i + "" ];
		}else{
			[febreroDict setObject: counDay + ":0"   forKey:"" + i + "" ];
		}
	}
	diffDays = ((leapYear % 7) + diffDays) % 7;

	//Marzo
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 31){
			[marzoDict setObject: "0:0"   forKey:"" + i + "" ];
		}else{
			[marzoDict setObject: counDay + ":0"   forKey:"" + i + "" ];
		}
	}
	diffDays = (3+diffDays)%7;

	//Abril
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 30){
			[abrilDict setObject: "0:0"   forKey:"" + i + "" ];
		}else{
			[abrilDict setObject: counDay + ":0"   forKey:"" + i + "" ];
		}
	}
	diffDays = (2+diffDays)%7;
	
	//Mayo
	counDay = 0;
	[mayoDict setObject:"0:0"   forKey:"-1" ];
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 31){
			[mayoDict setObject: "0:0"   forKey:"" + i + "" ];
		}else{
			[mayoDict setObject: counDay + ":0"   forKey:"" + i + "" ];
		}
	}
	diffDays = (3+diffDays)%7;
	
	//Junio
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 30){
			[junioDict setObject: "0:0"   forKey:"" + i + "" ];
		}else{
			[junioDict setObject: counDay + ":0"   forKey:"" + i + "" ];
		}
	}
	diffDays = (2+diffDays)%7;
	
	//Julio
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 31){
			[julioDict setObject: "0:0"   forKey:"" + i + "" ];
		}else{
			[julioDict setObject: counDay + ":0"   forKey:"" + i + "" ];
		}
	}
	diffDays = (3+diffDays)%7;
	
	//Agosto
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 31){
			[agostoDict setObject: "0:0"   forKey:"" + i + "" ];
		}else{
			[agostoDict setObject: counDay + ":0"   forKey:"" + i + "" ];
		}
	}
	diffDays = (3+diffDays)%7;
	
	//Setiembre
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 30){
			[setiembreDict setObject: "0:0"   forKey: "" + i + "" ];
		}else{
			[setiembreDict setObject: counDay + ":0"   forKey: "" + i + "" ];
		}
	}
	diffDays = (2+diffDays)%7;
	
	//Octubre
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 31){
			[octubreDict setObject: "0:0"   forKey: "" + i + "" ];
		}else{
			[octubreDict setObject: counDay + ":0"   forKey: "" + i + "" ];
		}
	}
	diffDays = (3+diffDays)%7;
	
	//Noviembre
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 30){
			[noviembreDict setObject: "0:0"   forKey: "" + i + "" ];
		}else{
			[noviembreDict setObject: counDay + ":0"   forKey: "" + i + "" ];
		}
	}
	diffDays = (2+diffDays)%7;
	
	//Diciembre
	counDay = 0;
	for (var i = (diffDays + 1); i <= 42; i ++ ){
		counDay += 1;
		if (counDay > 31){
			[diciembreDict setObject: "0:0"   forKey: "" + i + "" ];
		}else{
			[diciembreDict setObject: counDay + ":0"   forKey: "" + i + "" ];
		}
	}
	
}


-(void) removeItemsPopUpLocationsContacts{
		[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) removeItemsPopUpActivities{
	[actiPopu removeAllItems];		
	[actiPopu addItemWithTitle:@"Actividades"];
}


-(void) removeItemsTableActivitiesList{
	[actiListArra removeAllObjects];
	[actiListTabl reloadData];
}




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

	if (inde ==0) {
		[self removeItemsPopUpLocationsContacts];
		[self removeItemsPopUpActivities];
		[self removeItemsTableActivitiesList];
		
	}else {
		[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.OrganizationId ='" + idenOrga + "'  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.OrganizationId ='" + idenOrga + "'  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.OrganizationId ='" + idenOrga + "'  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.OrganizationId ='" + idenOrga + "'  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.OrganizationId ='" + idenOrga + "'  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.OrganizationId ='" + idenOrga + "'  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.OrganizationId ='" + idenOrga + "'  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.OrganizationId ='" + idenOrga + "'  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];
		}
		
		quer = [CPString stringWithFormat:@"Select distinct  oa.description from %@.eventActivity as ea ",dataBase];
		quer += " Inner Join "+dataBase+".organizationActivities as oa on ea.idActivity = oa.id inner join ";
		quer += " "+dataBase+".eventsPermanent as ep on ep.id = ea.idEvent WHERE  ";
		quer += " customer  = '" + idenOrga + "'";
		quer += " AND location = '" + idenLoca + "' ";
		quer += " ORDER BY oa.description ASC ";
		//alert("quer = " +  quer );
		var tempArra1 = [self query:quer];
		var coun1 = [tempArra1 count];
		
		//var arraAux1 = [[CPArray alloc] init];
		//var arraAux2 = [[CPArray alloc] init];
		//alert("coun1 " + coun1);
		[self removeItemsPopUpActivities];
		for ( var j=0; j< coun1; j++ ) {
				var reco = [[tempArra1 objectAtIndex:j] valueList];
				var valuActivi = reco[0];
				//alert("valuActivi = " + valuActivi);
				var arraStri = [valuActivi componentsSeparatedByString:@"|"];
				var coun2 = [arraStri count];
				for ( var k=0; k < coun2; k++ ) {
					var objt = [arraStri objectAtIndex:k];
					if (objt != ""){ 	
						[self addItemWithTitleActivityPopUp:objt];
    				}

			}
		}	
	}
}


- (void) addItemWithTitleActivityPopUp:(var)objt {
	var numItem = [actiPopu numberOfItems];
	// alert("items acti popu = " + numItem);
	 if (numItem == 0){
	 	[actiPopu addItemWithTitle:objt];
	 	return ;
	 }
	 
	for (var i = 0; i < numItem ; i ++ ){
		var titl = [actiPopu itemTitleAtIndex:i];
		if(titl == objt){
			return;
		}
	}
	[actiPopu addItemWithTitle:objt];
}




- (void) organizationSelectionPopUp:(id)sender {
	
	var inde = [orgaPopu indexOfSelectedItem];
	  //Locations
		[locaPopu removeAllItems];
		[locaPopu addItemWithTitle:@"Locaciones"];
		locaArra = NULL;	
	if (inde == 0) {
		 //alert("reload popu orga");
		[filtText setStringValue:@""];
		[orgaPopu removeAllItems];
		[orgaPopu addItemWithTitle:@"Organizaciones"];
		orgaArra = NULL;
		[self removeItemsPopUpLocationsContacts];
		[self removeItemsPopUpActivities];
		[self removeItemsTableActivitiesList];
			
		
		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 --;	
		
		if (!prevIndeOrgaPopu){
			prevIndeOrgaPopu = inde;
		}else if (prevIndeOrgaPopu != inde){
			[self removeItemsPopUpLocationsContacts];
			[self removeItemsPopUpActivities];
			[self removeItemsTableActivitiesList];
		}
		prevIndeOrgaPopu = 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 = 360;
	var horiPos4 = horiPos3 + 80;

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

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

	var paneWidt = 680;
	var paneHeig = 660;
	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 Anual"];
	
	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];
	
		//Year
	labe= [self addTextField:@"Año :" TFPosX:horiPos3 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

/*
	var currDate = [CPDate date];
	var currYear = [[currDate description] substringToIndex:4];  
	yearPopu = [self addPopupButton:currYear TFPosX:horiPos4 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	for( var y=0;y<=2;y++){
		currYear = [currYear intValue] + 1;
		[yearPopu addItemWithTitle:(currYear+"") ];
	}
*/
	
	var currDate = [CPDate date];
	var currYear = [[currDate description] substringToIndex:4];
	// Esto es algo temporal que me solicitarion imagino que no sera definitivo
	// pues solo se trata de un usuario en especial que necesita la informacion de anos anteriores
	var anteriorYear = [currYear intValue] - 1; 
	anteriorYear += "";
	yearPopu = [self addPopupButton:anteriorYear TFPosX:horiPos4 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	for( var y=0;y<=3;y++){
		var aYear = [currYear intValue] + y;
		[yearPopu addItemWithTitle:(aYear+"") ];
	}


	[yearPopu setTarget: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:)];
	
	//Activity
	labe= [self addTextField:@"Actividad :" TFPosX:horiPos3 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	actiPopu = [self addPopupButton:@"Actividades" TFPosX:horiPos4 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[actiPopu setTarget:self];
	[actiPopu setAction:@selector(activityPopupSelection:)];
	/*
	quer = [CPString stringWithFormat:@"select description,duration,price from %@.organizationActivities order by description",dataBase];
	actiArra = [self query:quer];
	var coun = [actiArra count];
	for ( var i=0; i<coun; i++ ) {
		var valuList = [actiArra[i] valueList];
		[actiPopu addItemWithTitle:valuList[0]];
	}
	*/
	vertPosi += 40;
	var fram= CGRectMake(horiPos3,vertPosi, 300,90);
	var scroView= [[CPScrollView alloc] initWithFrame:fram];
	actiListTabl = [[CPTableView alloc] initWithFrame:[scroView bounds]];
	[actiListTabl setDataSource:self];
	[actiListTabl setTarget:self];
	[actiListTabl setAction:@selector(tableSelection:)];
	[actiListTabl setAllowsColumnReordering:YES];
	[actiListTabl setUsesAlternatingRowBackgroundColors:YES];
	[actiListTabl setAllowsMultipleSelection:YES];
	[actiListTabl setDelegate:self];

	var colu= [[CPTableColumn alloc] initWithIdentifier:@"Actividad"];
	[[colu headerView] setStringValue:@"Actividad"];
	[colu setWidth:350];
	[actiListTabl addTableColumn:colu];

	[scroView setDocumentView:actiListTabl];

	[view addSubview:scroView];
	

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


- (void) activityPopupSelection:(id)sender {
    //console.log("pop up selection");
	var acti = [actiPopu titleOfSelectedItem];
	if ( [acti isEqualToString:@"Actividades"] ) {
	    [self removeItemsTableActivitiesList];
		return;
	/*
		[actiPopu removeAllItems];
		[actiListArra removeAllObjects];
		[actiPopu addItemWithTitle:@"Actividades"];
		var quer = @"select description,duration,price from " + dataBase + ".organizationActivities where active=1 order by description";
		actiArra = [self query:quer];
		var coun = [actiArra count];
		for ( var i=0; i<coun; i++ ) {
			var valuList = [actiArra[i] valueList];
			[actiPopu addItemWithTitle:valuList[0]];
		}
		[actiListTabl reloadData];
		return;	
		*/
	}else{
		if ( ! acti || [self activityExists:acti] ){
		[glblAlerPane showWithMessage:@"Actividad existente" info:"Se eliminara de la lista"];
		}
		//alert("Actividad se encontró y se eliminó de la lista");
	else {
	    var coun = [actiListArra count];
		if (coun <= 20 ){
			[actiListArra addObject:acti];
		}else{
			[glblAlerPane showWithMessage:@"Actividad existente" info:"No se permiten más de 20 actividades"];
		}
		var inde = [actiPopu indexOfSelectedItem];
		inde--;
	   }
   }
	[actiListTabl reloadData];
 }


- (BOOL) activityExists:(CPString)acti {
	var coun = [actiListArra count];
	for ( var i=0; i<coun; i++ ) {
		if ( [actiListArra[i] isEqualToString:acti] ) {
			[actiListArra removeObjectAtIndex:i];
			
			var inde = [actiPopu indexOfSelectedItem];
			inde--;
			
			return YES;
		}
	}
	return NO;
}



- (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){	
	
	 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];
		}
	}else{
	[glblAlerPane showWithMessage:@"Atencion" info:"No hay contactos asignados."];
	}

}


- (int) numberOfRowsInTableView:(CPTableView)tablView {
	var coun = 0;
	if ( tablView == actiListTabl ) {
		coun = [actiListArra 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 == actiListTabl ) {
		valu = actiListArra[rowInde];
	}
	
		return valu;
}





@end
