// AppController.j
// RMSchedulerController
//
// Created by Robert T. Beck

@import <Foundation/Foundation.j>
@import <AppKit/AppKit.j>
@import <MapKit/MKMapView.j>
@import <MapKit/MKLocation.j>
//@import "DatePicker.j"
@import "RMControllerObject.j"
@import "RMSchedulerView.j"
@import "RMSchedulerCPView.j"
@import "ServerConnector.j"
//add 2017-03-03
@import "AppController.j"


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





@implementation RMSchedulerController : RMControllerObject {

	id actiArra;
	id actiListArra;
	id actiListTabl;
	id actiPopu;

	id coloText;
	id pricEXCText;
	id pricFCUText;
	id pricUSDText;

	id coorLngdText;
	id coorLatiText;

	id custArra;
	id custBackArra;
	CPArray stateArra;
	id stateBackArra;
	id custHoliArra;
	id custPopu;
	id custStri;

	id custLocaAddrText;
	id custLocaLngd;
	id custLocaLati;
	id custLocaStri;	
	CPArray custLocaArra;
	CPPopUpButton custLocaPopu;

	CPPopUpButton statePopu;

	id dateStarText;
	id dateEndTextReProg;
	id dateStarTextPntr;
	id duraText;

	CPArray emplArra;
	CPPopUpButton emplPopu;
	CPArray emplListArra;
	CPArray emplListRepeArra;
	CPTableView emplListTabl;
	
	CPArray equiArra;
	CPPopUpButton equiPopu;
	CPArray equiListArra;
	CPArray equiListRepeArra;
	CPTableView equiListTabl;
	
	int evenOpti;
	CPTextField evenIdenText;
	CPPanel evenNotePane;
	CPTextField evenBillText;
	CPTextField evenFreqText;
	id evenMenu; 	//add 2017-02-27
	CPTextField evenNoteText;
	CPTextField evenNumbText;
	CPArray evenArra;
	CPTableView evenTabl;
	
	CPPanel evenDeleSeriFutuPane;
	CPTextField evenSeriFutuText;
	CPTextField evenDateFutuText;

	id freqPopu;

	id holiArra;
	id hourStarText;
	
	id isNew;

	id	idenText;
	int incoOpti;
	id incoArra;
	id incoTabl;
	id incoEmplWorkDayOverChec;
	id incoEmplWorkHourOverChec;
	id incoEvenOverChec;
	id incoOtheOverChec;
	id incoPersOverChec;
	id incoVehiOverChec;

	id locaLngd;
	id locaLati;

	id minuStarText;

	id persArra;

	id schePane;
	id scheView;
	id scheWind;
	id	seriText;

	id titlText;
	
	id filtText;
	

	id lettArra;
	id lettHexaArra;
	
	int paraFlag;

	id  sltdEvenDefi;     // *******
	id  btnIngr;
	id  btnLimp;
	id  btnBorrID;
	id  btnBorrSr;
	id  btnExtrID;
	id  btnExtrSr;
	id  btnNoFltr;
	id  btnReProg;

	id  btnFltrID;
	id  btnFltrSr;
	id  btnFltrOr;
	id  btnFltrLc;
	id  btnFltrSt;

	id  btnFltrPe;
	id  btnFltrEq;
	id  btnSear;
	id  btnFltrCm;
	id  btnFltrSch;
	id  btnFltrSp;
	id  btnFltrRo;
        id  btnUpdt;
        id  btnExit; 

	id  updtSubj;
	id  updtNumb;
	id  blckView1;
	id  blckView2;
	id  creaTabl;
	
	 id orga;
}



- (id) init:(id)paraAppCont {
	[super init];
 	creaTabl = 0;
 	appCont = paraAppCont;
	dataBase = [appCont getDataBase];
	//alert("db init resources= " + [appCont getDataBase]);
    //appCont= self;
	actiListArra = [[CPArray alloc] init];

	custStri = 0;
	custLocaStri = 0;
	isNew = true;
	emplListArra = [[CPArray alloc] init];
	emplListRepeArra = [[CPArray alloc] init];
	equiListArra = [[CPArray alloc] init];
	equiListRepeArra = [[CPArray alloc] init];
	evenNotePane = 0;
	evenOpti = 0;
	evenDeleSeriFutuPane = 0;
	orga = "";
	incoOpti = 0;
	sltdEvenDefi = nil;       // *******
    	updtSubj     = nil;
    	updtNumb     = -1;

//	mapMarkArra = [[CPArray alloc] init];

	persArra = [CPArray array];

	schePane = nil;
//	schePlotHoriNumb = 2;
	//scheViewWidt = 300;
	// scheViewHeig = 200;


	lettArra= [CPArray array];
	[lettArra addObject:@"A"];
	[lettArra addObject:@"B"];
	[lettArra addObject:@"C"];
	[lettArra addObject:@"D"];
	[lettArra addObject:@"E"];
	[lettArra addObject:@"F"];
	[lettArra addObject:@"G"];
	[lettArra addObject:@"H"];
	[lettArra addObject:@"I"];
	[lettArra addObject:@"J"];
	[lettArra addObject:@"K"];
	[lettArra addObject:@"L"];
	[lettArra addObject:@"M"];
	[lettArra addObject:@"N"];
	[lettArra addObject:@"O"];
	[lettArra addObject:@"P"];
	[lettArra addObject:@"Q"];
	[lettArra addObject:@"R"];
	[lettArra addObject:@"S"];
	[lettArra addObject:@"T"];
	[lettArra addObject:@"U"];
	[lettArra addObject:@"V"];
	[lettArra addObject:@"X"];
	[lettArra addObject:@"Y"];
	[lettArra addObject:@"Z"];
	[lettArra addObject:@"0"];
	[lettArra addObject:@"1"];
	[lettArra addObject:@"2"];
	[lettArra addObject:@"3"];
	[lettArra addObject:@"4"];
	[lettArra addObject:@"5"];
	[lettArra addObject:@"6"];
	[lettArra addObject:@"7"];
	[lettArra addObject:@"8"];
	[lettArra addObject:@"9"];

	lettHexaArra= [CPArray array];
	[lettHexaArra addObject:@"0"];
	[lettHexaArra addObject:@"1"];
	[lettHexaArra addObject:@"2"];
	[lettHexaArra addObject:@"3"];
	[lettHexaArra addObject:@"4"];
	[lettHexaArra addObject:@"5"];
	[lettHexaArra addObject:@"6"];
	[lettHexaArra addObject:@"7"];
	[lettHexaArra addObject:@"8"];
	[lettHexaArra addObject:@"9"];
	[lettHexaArra addObject:@"A"];
	[lettHexaArra addObject:@"B"];
	[lettHexaArra addObject:@"C"];
	[lettHexaArra addObject:@"D"];
	[lettHexaArra addObject:@"E"];
	[lettHexaArra addObject:@"F"];
	


	return self;
}





- (void) activityPopupSelection:(id)sender {
	var acti = [actiPopu titleOfSelectedItem];
	if ( [acti isEqualToString:@"Actividades"] ) {
		[actiListArra removeAllObjects];
		[actiListTabl reloadData];
		[duraText setIntValue:0];
		[pricFCUText setIntValue:0];
		[pricUSDText setIntValue:0];
		[actiPopu removeAllItems];
		[actiPopu addItemWithTitle:@"Actividades"];
		var quer = @"select description,duration,price,id 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]];
		}
		return;
	}

	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 {
		[actiListArra addObject:acti];

		var inde = [actiPopu indexOfSelectedItem];
		inde--;
		var valuList = [actiArra[inde] valueList];
		var dura = valuList[1];
		var pric = valuList[2];

		var duraTemp = prompt("Duración estimada: "+dura+" minutos");
		if ( [duraTemp length] > 0 )
			dura = duraTemp;

		dura = [duraText floatValue] + [dura floatValue];
		[duraText setStringValue:[CPString stringWithFormat:@"%.2f",dura]];

		pric = [pricUSDText floatValue] + [pric floatValue];
		[pricUSDText setStringValue:[CPString stringWithFormat:@"%.2f",pric]];
	}
	[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--;
			var valuList = [actiArra[inde] valueList];
			var dura = [valuList[1] floatValue];
			var pric = [valuList[2] floatValue];

			dura = [duraText floatValue] - [dura floatValue];
			[duraText setStringValue:[CPString stringWithFormat:@"%.2f",dura]];

			pric = [pricUSDText floatValue] - [pric floatValue];
			[pricUSDText setStringValue:[CPString stringWithFormat:@"%.2f",pric]];

			return YES;
		}
	}
	return NO;
}



- (void)  applicationQuit {
	if ( schePane ) {
		[schePane orderOut:0];
		[schePane release];
	}
	
	if(scheWind) { 
		[scheWind orderOut:0];
		[scheWind release];
	}
	
	
}




- (void) clearFields:(id)sender {
	[custPopu selectItemAtIndex:0];
	custStri = 0;
	[custLocaPopu removeAllItems];
	[custLocaPopu addItemWithTitle:@"Locaciones"];
	[custPopu selectItemAtIndex:0];
	[custLocaArra removeAllObjects];
	[custLocaAddrText setStringValue:@""];
	custLocaStri = 0;
	[actiPopu selectItemAtIndex:0];
	[actiListArra removeAllObjects];
	[actiListTabl reloadData];
	[duraText setStringValue:@""];
	[pricFCUText setStringValue:@""];
	[pricUSDText setStringValue:@""];
	[equiPopu selectItemAtIndex:0];
	[equiListArra removeAllObjects];
	[equiListTabl reloadData];
	[emplPopu selectItemAtIndex:0];
	[emplListArra removeAllObjects];
	[emplListTabl reloadData];
	[coloText setStringValue:@""];
 	[idenText setStringValue:@""];
 	[seriText setStringValue:@""];
	[titlText setStringValue:@""];

	//[filtText setStringValue:@""];
}

- (void) clearFieldsUpdate:(id)sender {
	[actiPopu selectItemAtIndex:0];
	[actiListArra removeAllObjects];
	[actiListTabl reloadData];
	[duraText setStringValue:@""];
	[pricFCUText setStringValue:@""];
	[pricUSDText setStringValue:@""];
	[equiPopu selectItemAtIndex:0];
	[equiListArra removeAllObjects];
	[equiListTabl reloadData];
	[emplPopu selectItemAtIndex:0];
	[emplListArra removeAllObjects];
	[emplListTabl reloadData];
	[coloText setStringValue:@""];
 	[idenText setStringValue:@""];
 	[seriText setStringValue:@""];
	[titlText setStringValue:@""];

	//[filtText setStringValue:@""];
}




- (void) commentSerieOption:(id)sender {
 
	var inde = [evenTabl selectedRow];
 	if( inde >= 0 ){
 		var valuList = [evenArra[inde] valueList];
 		var evenIden = valuList[0];
 		var seriIden = valuList[1];
 		paraFlag = 1;
 		[ self commentPanel :evenIden :seriIden :0 ];
 	}else{ 
 		[glblAlerPane showWithMessage:@"Atencion" info:"No se ha seleccionado ningun evento"];
 		//alert("Ningún evento seleccionado"); 
 	}
}



- (void) commentEventOption:(id)sender {

	var indeArra = [evenTabl selectedRowIndexes];
 	var coun     = [indeArra count];
 		
 	if( coun > 0 ){
 		
 		var firs = [indeArra firstIndex];
		var valu = [ [evenArra objectAtIndex:firs] valueList ];
		var evenIden = valu[0];
		var seriIden = valu[1];
		paraFlag = 2;
 		if (coun == 1){ 		
		    [self commentPanel :evenIden :seriIden :coun ];		    
 		}else{
 			[self commentPanel :evenIden :seriIden :3 ];	
 		}
 	}else{  
        [glblAlerPane showWithMessage:@"Atencion" info:"No se ha seleccionado ningun evento"];
 	//	alert("Ningún evento seleccionado"); 	
 	}

}


- (void) commentPanel:(int)paraIden :(int)paraSeri :(int)paraCoun {
	
	[evenNoteText setStringValue:""];
	var iden = paraIden;
	if ( evenNotePane ) {
		[evenNotePane orderFront:self];
	}
	else {
		var x = 300;
		var y = 200;
		var fram = CGRectMake(x,y, 460,170);
		evenNotePane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
		[evenNotePane setFloatingPanel:YES]; 
		[evenNotePane setDelegate:self];
		[evenNotePane orderFront:self];
		[evenNotePane setTitle:@"Comentarios"];
		var view = [evenNotePane contentView];
		[view setBackgroundColor:coloDefaBrig];
		[self addBanners:view heightBlue:2. heightOrange:4.];
		var horiPos1 = 10;
		var horiPos2 = horiPos1 + 100;
		var vertPosi = 20;
		var vertIncr = 25;
		var labe= [self addTextField:@"Comentarios :" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
		[labe setTextColor:[CPColor whiteColor]];
		evenNoteText = [self addTextField:@"" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:300 TFHeight:4*vertIncr VView:view Editable:YES];
		[evenNoteText setLineBreakMode:CPLineBreakByWordWrapping];			
		vertPosi += 4.5*vertIncr;	
		var butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2,vertPosi, 80,24)];
		[butt setTitle:"Actualizar"];
		[butt setTarget:self];
		[butt setAction:@selector(commentUpdate:)];                
		[view addSubview:butt];
	}

	    var querSQL = "";
	    if (paraFlag == 1){
			querSQL = [CPString stringWithFormat:@"SELECT serieComm FROM %@.eventsPermanent WHERE id=%@ LIMIT 1",dataBase,iden];
			//alert("query= " + querSQL);
			var arra = [self query:querSQL]; 
	        if ( [arra count] > 0 ) {
				var valuList = [arra[0] valueList];
				[evenNoteText setStringValue:[valuList objectAtIndex:0]];
	  		}
	    } 
	    
	   if (paraFlag == 2 && paraCoun == 1){
			querSQL =  [CPString stringWithFormat:@"SELECT eventComm FROM %@.eventsPermanent WHERE id=%@ LIMIT 1",dataBase,iden];
			//alert("query= " + querSQL);
			var arra = [self query:querSQL];
	        if ( [arra count] > 0 ) {
				var valuList = [arra[0] valueList];
				[evenNoteText setStringValue:[valuList objectAtIndex:0]];
	  		}	
	   }
	   
}



- (void) commentUpdate:(id)sender {
	var text = [evenNoteText stringValue];
	text = [text stringByReplacingOccurrencesOfString:@"'" withString:@""];	
	text = [text stringByReplacingOccurrencesOfString:@"\"" withString:@""];	
	
	if (paraFlag == 1) {
			var inde = [evenTabl selectedRow];
 			if( inde >= 0 ){
 				var valuList = [evenArra[inde] valueList];
 				var seriIden = valuList[1];		
				var seriComm = text;
				var quer = [CPString stringWithFormat:@"UPDATE %@.eventsPermanent SET serieComm='%@' WHERE seriesId=%@",dataBase,seriComm,seriIden];
				//alert(quer);
				[self query:quer];			
 	        }
 	        
	}else if(paraFlag == 2) {
	//alert("update events");
		var indeArra = [evenTabl selectedRowIndexes];
 		var coun     = [indeArra count];
	 	var begiSql  = "INSERT INTO " + dataBase + ".eventsPermanent (id,eventComm) VALUES";
 		var middSql  = "";
	 	var endSql   = " ON DUPLICATE KEY UPDATE eventComm = VALUES (eventComm)";
 		var evenComm = text;
 		
		while ( coun >= 1 ){
			var firs = [indeArra firstIndex];
		    var valu = [ [evenArra objectAtIndex:firs] valueList ];
		    var evenIden = valu[0];
		    [indeArra removeIndex:firs];
		    	coun -=  1; 
				if(coun == 0){ 
					middSql += " (" + evenIden + ",'" + evenComm + "')";
				}else{
					middSql += " (" + evenIden + ",'" + evenComm + "'),";
				}
		  }
		  
		  var totaSql =  begiSql + middSql + endSql;
		  var quer = [CPString stringWithFormat:totaSql];
				[self query:quer];	     
	}
	//[scheView reloadData]
	[evenNotePane close];
}


- (void) priceFCUToUSD:(id)sender {
	var pricUSD = [pricFCUText floatValue]/[pricEXCText floatValue];
	var pricUSDStri = [CPString stringWithFormat:@"%.0f",pricUSD];
	[pricUSDText setStringValue:pricUSDStri];
}



- (void) priceUSDToFCU:(id)sender {
	var pricFCU = [pricUSDText floatValue]*[pricEXCText floatValue];
	var pricFCUStri = [CPString stringWithFormat:@"%.0f",pricFCU];
	[pricFCUText setStringValue:pricFCUStri];
}


- (void) customerPopupSelection:(id)sender {

	var inde = [custPopu indexOfSelectedItem];
	var quer = 0;
	//Change
	if ( inde == 0 ) {
		[self clearFields:0];
		[filtText setStringValue:@""];
		[custPopu removeAllItems];
		[custPopu addItemWithTitle:@"Organizaciones"];
		quer = [CPString stringWithFormat:@"select id,name,idPrimary 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 arraTemp = [[CPArray alloc] init];
			var valuList = [custBackArra[i] valueList];
			var iden = valuList[0];
			var name = valuList[1];
			var idPrimary = valuList[2];
			[arraTemp addObject:iden];
			[arraTemp addObject:name];
			[arraTemp addObject:idPrimary];
			[popuArra addObject:arraTemp];
			[custPopu addItemWithTitle:name];
		}
		custArra = popuArra;
		custStri = 0;

		quer = @"select id,name,addressStreet,addressCity,addressState,locationLongitude,locationLatitude,color from " + dataBase + ".organizationLocations where active=1 order by name";
		//alert("locations " + quer)
		custLocaArra = [self query:quer];
		var coun = [custLocaArra count];
		for ( var i=0; i<coun; i++ ) {
			var valuList = [custLocaArra[i] valueList];
			var locaIden = valuList[0];
			var name = valuList[1];
			var stri = [CPString stringWithFormat:@"%@:%@",name,locaIden];
			[custLocaPopu addItemWithTitle:stri];
			var lngd = [valuList[5] floatValue];
			var lati = [valuList[6] floatValue];
			if ( mapCont )
				[mapCont radiusCenteredAtPoint:lngd :lati erase:NO draw:YES radius:0.0005 color:[CPColor greenColor]];
		}
        
		return;
	}
	[self clearFields:0];
	[custPopu selectItemAtIndex:inde];

	inde--;

	[titlText setStringValue:@""];

	var valuList = custArra[inde];
	
	var custIden = valuList[2];
	var name = valuList[1];
	custStri = valuList[2];//[CPString stringWithFormat:@"%@:%@",name,custIden];
	if ( mapCont )
		[mapCont radiusCenteredAtPoint:0 :0 erase:YES draw:NO radius:0. color:[CPColor greenColor]];

	quer = [CPString stringWithFormat:@"select id,name,addressStreet,addressCity,addressState,locationLongitude,locationLatitude,color from %@.organizationLocations where organizationId='%@' and active=1 order by name",
		dataBase,custIden];
	custLocaArra = [self query:quer];
	var coun = [custLocaArra count];
	for ( var i=0; i<coun; i++ ) {
		var valuList = [custLocaArra[i] valueList];
		var locaIden = valuList[0];
		var name = valuList[1];
		var stri = [CPString stringWithFormat:@"%@:%@",name,locaIden];
		[custLocaPopu addItemWithTitle:stri];
		var lngd = valuList[5];
		var lati = valuList[6];
		if ( mapCont )
			[mapCont radiusCenteredAtPoint:lngd :lati erase:NO draw:YES radius:0.0004 color:[CPColor greenColor]];
	}

	[emplPopu removeAllItems];
	[emplPopu addItemWithTitle:@"Personal"];
	
	quer = [CPString stringWithFormat:@"select abbreviation from %@.organizationTraining where organizationId='%@' order by abbreviation",dataBase,custIden];
	//alert("OrgaTraining " + quer );
	var orgaAbbrArra = [self query:quer];
	var orgaAbbrCoun = [orgaAbbrArra count];
	var orgaAbbrStri = @"";
	for ( var i=0; i<orgaAbbrCoun; i++ )
		orgaAbbrStri = [CPString stringWithFormat:@"%@ %@",orgaAbbrStri,[[orgaAbbrArra[i] valueList] objectAtIndex:0]];
//Change
	quer = [CPString stringWithFormat:@"select distinct t1.id,t1.nameLast,t1.nameFirst,t1.phone1,t1.email,t2.position,t1.color from %@.persons t1, %@.organizationPersons t2 where t2.organizationId='%@' and t2.personId=t1.id and t2.active = 1 order by t1.nameLast,t1.nameFirst",
		dataBase,dataBase,orgaId];
	//alert("query emp " + quer);
	emplArra = [self query:quer];
	var emplCoun = [emplArra count];
	//alert(orgaAbbrCoun);
	if ( orgaAbbrCoun > 0 ) {
		for ( var j=emplCoun-1; j>=0; j-- ) {
			var valuList = [emplArra[j] valueList];
			var emplIden = valuList[0];
			var nameLast = valuList[1];
			var nameFirs = valuList[2];
			var posi     = [valuList[5] substringToIndex:1];
			var stri = [CPString stringWithFormat:@"%@, %@ [%@]:%@",nameLast,nameFirs,posi,emplIden];

			quer = [CPString stringWithFormat:@"select abbreviation from %@.employeeTraining where personId=%@ and organizationId='%@' order by abbreviation",dataBase,emplIden,custIden];
			var emplAbbrArra = [self query:quer];
			var emplAbbrCoun = [emplAbbrArra count];
		
			if ( emplAbbrCoun != orgaAbbrCoun ) {
				[emplArra removeObject:emplArra[j]];
				//alert("Removing1 "+emplAbbrCoun+" vs "+orgaAbbrCoun+"  eliminating:"+j);
				continue;
			}

			var emplAbbrStri = @"";
			for ( var i=0; i<emplAbbrCoun; i++ )
				emplAbbrStri = [CPString stringWithFormat:@"%@ %@",emplAbbrStri,[[orgaAbbrArra[i] valueList] objectAtIndex:0]];

			if ( ! [emplAbbrStri isEqualToString:orgaAbbrStri] ) {
				[emplArra removeObject:emplArra[j]];
				//alert("Removing2  *"+emplAbbrStri+"* vs *"+orgaAbbrStri+"*  eliminating:"+j);
			}
		}
	}

	emplCoun = [emplArra count];
	//alert(emplCoun);
	//alert("RMSchedulerController 434, "+ emplCoun);
	for ( var j=0; j<emplCoun; j++ ) {
		var valuList = [emplArra[j] valueList];
		var emplIden = valuList[0];
		var nameLast = valuList[1];
		var nameFirs = valuList[2];
		var posi     = [valuList[5] substringToIndex:1];
		var stri = [CPString stringWithFormat:@"%@, %@ [%@]:%@",nameLast,nameFirs,posi,emplIden];
		[emplPopu addItemWithTitle:stri];
	}

/*	quer = [CPString stringWithFormat:@"select id,organizationId,dateStart,dateFinish,description from %@.organizationHolidays where organizationId='%@' order by dateStart",
		dataBase,custIden];
	custHoliArra = [self query:quer];
*/
	quer = [CPString stringWithFormat:@"select id,CountryId,dateStart,dateFinish,description from %@.countryHolidays where CountryId='%@' order by dateStart",
		dataBase,countryCode];
	holiArra = [self query:quer];

	[evenTabl reloadData];
}



- (void) customerLocationPopupSelection:(id)sender {
	[titlText setStringValue:@""];
	[custLocaAddrText setStringValue:@""];
	[actiPopu selectItemAtIndex:0];
	[actiListArra removeAllObjects];
	[actiListTabl reloadData];
	[duraText setStringValue:@""];
	[pricFCUText setStringValue:@""];
	[pricUSDText setStringValue:@""];
	[equiPopu selectItemAtIndex:0];
	[equiListArra removeAllObjects];
	[equiListTabl reloadData];
	[emplPopu selectItemAtIndex:0];
	[emplListArra removeAllObjects];
	[emplListTabl reloadData];
  	[idenText setStringValue:@""];
	[seriText setStringValue:@""];

	var orgaInde = [custPopu indexOfSelectedItem];
	if ( orgaInde == 0 ) {
		custStri = 0;
		return;
	}
	orgaInde--;

	var orgaName = custArra[orgaInde][1];
	var locaInde = [custLocaPopu indexOfSelectedItem];
	if ( locaInde == 0 ) {
		custLocaStri = 0;
		return;
	}
	locaInde--;

	valuList = [custLocaArra[locaInde] valueList];
	var locaName = valuList[1];
	
	//[titlText setStringValue:[CPString stringWithFormat:@"%@ - %@",orgaName,locaName]];
	[titlText setStringValue:[CPString stringWithFormat:@"%@",locaName]];
	var locaIden = valuList[0];
	custLocaStri = locaIden;//[CPString stringWithFormat:@"%@:%@",locaName,locaIden];
	custLocaLngd = valuList[5];
	custLocaLati = valuList[6];
	if ( [custLocaLngd isEqualToString:@"NA"] )
		custLocaLngd = @"0";
	if ( [custLocaLati isEqualToString:@"NA"] )
		custLocaLati = @"0";

	[custLocaAddrText setStringValue:[CPString stringWithFormat:@"%@; %@; %@",valuList[2],valuList[3],valuList[4]]];
	locaLngd = valuList[5];
	locaLati = valuList[6];
	
	if ( mapCont )
		[mapCont radiusCenteredAtPoint:locaLngd :locaLati erase:NO draw:YES radius:0.0004 color:[CPColor blueColor]];
		
	var colo = valuList[7];
	if ( [colo length] != 7 ) {
		/*colo = [CPString stringWithFormat:@"#%x%x%x",
    		Math.floor(Math.random()*15.99),Math.floor(Math.random()*15.99),Math.floor(Math.random()*15.99)];
    		*/
    		//colo = [CPString stringWithFormat:@"#%x%x%x",   
    		//( Math.floor(Math.random() * 5.99 ) + 10 ) , (Math.floor(Math.random() *  5.99 ) + 10 ), (Math.floor(Math.random( )* 5.99 ) + 10)];	
    	colo = [self getRandomColor];	
    	var quer = [CPString stringWithFormat:@"update %@.organizationLocations set color='%@' where id=%@",dataBase,colo,locaIden];
    		
    	//[self query:quer];
	}
	[coloText setStringValue:colo];
}




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


- (void) datePickerPanel:(id)sender {

	var fram = CGRectMake(350,200,144,148);
	var datePickPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; 
	[datePickPane setFloatingPanel:YES];
	[datePickPane setTitle:@"DatePicker"];
	[datePickPane orderFront:self];

	var paneContView = [datePickPane 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(datePickerDateChange:)];
	//alert("dpe="+dpe+"  dps="+dps);
	
	[paneContView addSubview:datePick];
}

/**
- (void) datePickerDateChangeReProg:(id)sender {
	[dateEndTextReProg setStringValue:[[[sender dateValue] description] substringToIndex:10]];
}


- (void) datePickerPanelReProg:(id)sender {

	var fram = CGRectMake(350,200,144,148);
	var datePickPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; 
	[datePickPane setFloatingPanel:YES];
	[datePickPane setTitle:@"DatePicker"];
	[datePickPane orderFront:self];

	var paneContView = [datePickPane 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(datePickerDateChangeReProg:)];
	//alert("dpe="+dpe+"  dps="+dps);
	
	[paneContView addSubview:datePick];
}
**/
- (void) employeePopupRepeat:(id)sender {
	emplListArra = emplListRepeArra;
	[emplListTabl reloadData];
}



- (void) employeePopupSelection:(id)sender {
	var empl = [emplPopu titleOfSelectedItem];
	if ( [empl isEqualToString:@"Personal"] ) {
		[emplListArra removeAllObjects];
		[emplListTabl reloadData];
		return;
	}
	if ( ! empl || [self employeeExists:empl] )
		[glblAlerPane showWithMessage:@"Empleado ya registrado" info:"Se eliminara de la lista"];
		//alert("Empleado se eliminó de la lista");
	else {
		[emplListArra addObject:empl];
		if ( [emplListArra count] > 4 )
			[glblAlerPane showWithMessage:@"Atencion" info:"Numero del personal en este servicio es mayor que 4"];
			//alert("Numero del personal en este servicio es mayor que 4");
	}
	[emplListTabl reloadData];
}



- (BOOL) employeeExists:(CPString)empl {
	var coun = [emplListArra count];
	for ( var i=0; i<coun; i++ ) {
		if ( [emplListArra[i] isEqualToString:empl] ) {
			[emplListArra removeObjectAtIndex:i];
			return YES;
		}
	}
	return NO;
}



- (void) equipmentAssociated:(id)sender {

	var emplListArraCoun = [emplListArra count];

	for ( var i=0; i<emplListArraCoun; i++ ) {	
		var emplIdenArra = [emplListArra[i] componentsSeparatedByString:@":"];
		var emplIden = emplIdenArra[1];
		var quer = [CPString stringWithFormat:@"select equipmentId from %@.personEquipment where personId=%@",dataBase,emplIden];
		var emplEquiArra = [self query:quer];
		var emplEquiCoun= [emplEquiArra count];

		var equiArraCoun = [equiArra count];

		for ( var j=0; j<emplEquiCoun; j++ ) {
			var emplEquiValuList = [emplEquiArra[j] valueList];
			var equiIden = [emplEquiValuList[0] intValue];
			if ( equiIden == typeof "undefined" || equiIden == 'NaN' || equiIden == NaN )
				continue;

			alert("Employee equipment j="+j+" : "+equiIden);

			for ( var k=0; k<equiArraCoun; k++ ) {
				var equiArraValuList = [equiArra[k] valueList];
				var equiIden0 = [equiArraValuList[0] intValue];

				if ( equiIden == equiIden0 ) {
					//console.log("Found equipment at k="+k+"  *"+equiIden+"*   *"+equiIden0+"*");

					var iden1 = equiArraValuList[1];
					var make = equiArraValuList[2];
					var mode = equiArraValuList[3];
					var year = equiArraValuList[4];
					var stri = [CPString stringWithFormat:@"%@_%@_%@_%@:%@",make,mode,year,iden1,equiIden0];
					//alert("Equipment found : "+stri);

					var equiListArraCoun = [equiListArra count];
					var exis = NO;
					for ( var l=0; l<equiListArraCoun; l++ ) {
						//console.log("*"+equiListArra[l]+"*   *"+stri+"*");
						if ( [equiListArra[l] isEqualToString:stri] ) {
							exis = YES;
							alert("Found at l="+l);
							break;
						}
					}
					if ( exis == NO )
						[equiListArra addObject:stri];

					break;
				}
			}
		}
	}

	[equiListTabl reloadData];
}



- (void) equipmentPopupRepeat:(id)sender {
	equiListArra = equiListRepeArra;
	[equiListTabl reloadData];
}



- (void) equipmentPopupSelection:(id)sender {
	var equi = [equiPopu titleOfSelectedItem];
	if ( [equi isEqualToString:@"Equipo"] ) {
		[equiListArra removeAllObjects];
		[equiListTabl reloadData];
		return;
	}
	if ( equi && [self equipmentExists:equi] )
		[glblAlerPane showWithMessage:@"Equipo ya registrado" info:"Se eliminara de la lista"];
		//alert("Equipo se encontró y se eliminó de la lista");
	else
		[equiListArra addObject:equi];
	[equiListTabl reloadData];
}



- (BOOL) equipmentExists:(CPString)equi {
	var coun = [equiListArra count];
	for ( var i=0; i<coun; i++ ) {
		if ( [equiListArra[i] isEqualToString:equi] ) {
			[equiListArra removeObjectAtIndex:i];
			return YES;
		}
	}
	return NO;
}

- (void) fillOrganizations:(id)sender {
		[self clearFields:nil];
		[custLocaPopu removeAllItems];
		[custLocaPopu setTitle:"Locaciones"];
		var coun = [custBackArra count];
		[custPopu removeAllItems];
		[custPopu 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 idPrimary = valuList[2];
				//var stri = [CPString :@"%@:%@",name,iden];
				if([[[name uppercaseString] rangeOfString:[orga uppercaseString]].length] != 0){
					var arraTemp = [[CPArray alloc] init];
					[arraTemp addObject:iden];
					[arraTemp addObject:name];
					[arraTemp addObject:idPrimary];
					[popuArra addObject:arraTemp];
					[custPopu addItemWithTitle:name];
				}
				//[custPopu addItemsWithTitle:popuArra];
			}
			 custArra = popuArra;
		}else{
			var quer = "select id,name,idPrimary 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 idPrimary = valuList[2];
				//var stri = [CPString stringWithFormat:@"%@:%@",name,iden];
					[arraTemp addObject:iden];
					[arraTemp addObject:name];
					[arraTemp addObject:idPrimary];
					[popuArra addObject:arraTemp];
					[custPopu addItemWithTitle:name];
				//[custPopu addItemsWithTitle:popuArra];
			}
			custArra = popuArra;
		}
		
}

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

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

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

- (void) eventTableSelection:(id)sender {
	
	var inde = [evenTabl selectedRow];
	var valuList = [evenArra[inde] valueList];
	var evenIden = valuList[0];
 	[idenText setStringValue:evenIden];
	var evenSeri = valuList[1];
	[seriText setStringValue:evenSeri];

	if ( evenNotePane && [evenNotePane isVisible] )
		[self scheduleEventBillingNotes:0];
}



- (void) inconsistenciesTableSelection:(id)sender {
	var inde = [incoTabl selectedRow];
	var valuList = [incoArra[inde] valueList];
	if ( incoOpti == 1 && [valuList[5] intValue]>0 ) {
		[idenText setStringValue:valuList[5]];
		incoOpti = 0;
	}
	else {
		[idenText setStringValue:valuList[2]];
		incoOpti = 1;
	}
	[seriText setStringValue:@""];
	[self scheduleIdentityEvents:0];
}

	
- (void) reProgramSeries:(id)sender	{
	isNew = false;
	[self scheduleEventInsert:self];



}
	

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



- (void) scheduleEvents:(id)sender {
	evenOpti = 0;
	[evenTabl reloadData];
}



- (void) scheduleIdentityEvents:(id)sender {
	evenOpti = 1;
	[evenTabl reloadData];
}



- (void) scheduleSeriesEvents:(id)sender {
	evenOpti = 2;
	[evenTabl reloadData];
}


/*
	var arraAux = [self query:quer];
 	var arraTempRepo = [CPArray array];
 		
 	
 	for (var i = 0; i < [ arraAux count]; i++){
 		var valu = [ [arraAux objectAtIndex:i] valueList ];
 		var loca     = valu[0];
		var statDate = valu[1];		
		var hour     = valu[2];	
		var stri = " ('" + randCode + "','" + loca + "','" + statDate + "','" + hour + "')";
		[arraTempRepo addObject:stri];
		}
*/


/*
- (void) scheduleEventFilterEmployees:(id)sender {

	var quer = @"truncate " + dataBase + ".events";
	[self query:quer];
	
	var finaQuer = [CPString stringWithFormat:@"select id,seriesId,eventIdentifier,start_date,end_date,text,source,calendar,personnel,location,customer,lat,lng,vehicle,eventComm,serieComm from %@.eventsPermanent where  ",dataBase];
	
	var emplListCoun = [emplListArra count];
	var emplListStri = @"";
	var arraValu = [CPArray array];
	
	
	for ( var i = 0; i<emplListCoun; i++ ) {
		var titl = emplListArra[i];
		var titlCompArra = [titl componentsSeparatedByString:@":"];	
		var iden = titlCompArra[1];
		
		var temp2 = i + 1;
	    if (temp2 == emplListCoun) {
	   		 finaQuer +=  [CPString stringWithFormat:@" personnel like '%%:%@|%%'",iden];
	    }else{
	     	 finaQuer +=  [CPString stringWithFormat:@" personnel like '%%:%@|%%' or ",iden];
	    }
	    
	    
		quer = [CPString stringWithFormat:@"select id,seriesId,eventIdentifier,start_date,end_date,text,source,calendar,personnel,location,customer,lat,lng,vehicle,eventComm,serieComm from %@.eventsPermanent where  personnel like '%%:%@|%%'",
		dataBase,iden];
		[self query:quer];
		
		var arraEvenPerm = [self query: quer];
		var counArraEvenPerm = [arraEvenPerm count];
		
		console.log("rows " + iden + " -> " + counArraEvenPerm );
		for (var j = 0; j < counArraEvenPerm; j++) {
			var valu = [ [arraEvenPerm objectAtIndex:j] valueList ];
			var idd = valu[0];
			var seriesId = valu[1];
			var  eventIdentifier = valu[2];
			var  start_date = valu[3];
			var  end_date = valu[4];
			var  text = valu[5];
			var  source = valu[6];
			var  calendar = valu[7];
			var personnel = valu[8];
			var  location = valu[9];
			var  customer = valu[10];
			var  lat = valu[11];
			var  lng = valu[12];
			var  vehicle = valu[13];
			var  eventComm = valu[14];
			var  serieComm = valu[15];
			var colo = [self getRandomColor];
		    var stri = [CPString stringWithFormat:@" (%@,%@,'%@','%@','%@','%@','%@','%@','%@','%@','%@',%@,%@,'%@','%@','%@','%@') ",
				idd,seriesId,eventIdentifier,start_date,end_date,text,source,calendar,personnel,location,customer,lat,lng,vehicle,eventComm,serieComm,colo];
			[arraValu addObject:stri];
			//console.log("creating tuple " + j);
	    }
	    
	    var counInse = [arraValu count];
	    var begiSql = [CPString stringWithFormat:@"INSERT INTO %@.events (id,seriesId,eventIdentifier,start_date,end_date,text,source,calendar,personnel,location,customer,lat,lng,vehicle,eventComm,serieComm,color) VALUES ",dataBase];
	    var middSql = "";
	    var maxTupl = 25;
	    
	    while(counInse > maxTupl){
	    	for (var l = 0; l < maxTupl; l++){
	    	console.log("while in for");
	    		var valu = [arraValu objectAtIndex:0];
	    		var temp = l + 1;
	    		if (temp == maxTupl){
	    			middSql += valu;
	    		}else{
	    			middSql += valu + ",";
	    		}
	    		[arraValu removeObjectAtIndex:0];
	    		counInse -=1;
	    	}
	    	quer = begiSql + middSql;
	    	console.log("insert tuple " + quer );
	    	[self query:quer];
	    	console.log("pass insert")
	    	middSql = "";
	    }
	    
	counInse = [arraValu count];
	begiSql = [CPString stringWithFormat:@"INSERT INTO %@.events (id,seriesId,eventIdentifier,start_date,end_date,text,source,calendar,personnel,location,customer,lat,lng,vehicle,eventComm,serieComm,color) VALUES ",dataBase];
	middSql = "";
	
	if (counInse > 0) {
		for (var i =0; i < counInse; i++){
		console.log("rest tuples" + i )
			var valu = [arraValu objectAtIndex:i]; 
			var temp = i + 1;
			if (temp == counInse){
				middSql += valu; 
			} else{
				middSql += valu + ",";
			}
		}
		quer =  begiSql + middSql ;
		[self query:quer];
	}
   }//end for

	alert("3 fina select " + finaQuer);
	var finaArra = [self query: finaQuer];
	var counFinaArra = [finaArra count];
	alert ("fina count " + counFinaArra );
	
	quer = [CPString stringWithFormat:@"INSERT INTO %@.events (id,seriesId,eventIdentifier,start_date,end_date,text,source,calendar,personnel,location,customer,lat,lng,vehicle,eventComm,serieComm,color) VALUES ",dataBase];

		for (var k = 0; k < counFinaArra; k++) {
		console.log("run final insert")
			var valu = [ [counFinaArra objectAtIndex:k] valueList];
			var  idd = valu[0];
			var  seriesId = valu[1];
			var  eventIdentifier = valu[2];
			var  start_date = valu[3];
			var  end_date = valu[4];
			var  text = valu[5];
			var  source = valu[6];
			var  calendar = valu[7];
			var  personnel = valu[8];
			var  location = valu[9];
			var  customer = valu[10];
			var  lat = valu[11];
			var  lng = valu[12];
			var  vehicle = valu[13];
			var  eventComm = valu[14];
			var  serieComm = valu[15];   
			var  colo = [self getRandomColor];
			var  temp = k + 1;
			if ( temp == counArraEvenPerm){
				quer += [CPString stringWithFormat:@" (%@,%@,'%@','%@','%@','%@','%@','%@','%@','%@','%@',%@,%@,'%@','%@','%@','%@') ",
				idd,seriesId,eventIdentifier,start_date,end_date,text,source,calendar,personnel,location,customer,lat,lng,vehicle,eventComm,serieComm,colo];
			}else{
			quer += [CPString stringWithFormat:@" (%@,%@,'%@','%@','%@','%@','%@','%@','%@','%@','%@',%@,%@,'%@','%@','%@','%@'),",
     			idd,seriesId,eventIdentifier,start_date,end_date,text,source,calendar,personnel,location,customer,lat,lng,vehicle,eventComm,serieComm,colo];
			}
	    }
		
	alert("insert fina quer" + quer);
	//console.log("insert fina quer" + quer);
	//[self query:quer];
	
	[self scheduleNew:nil];
}
*/

	/*
	
	var emplListCoun = [emplListArra count];
	var emplListStri = @"";
	for ( var i=0; i<emplListCoun; i++ ) {
		var titl = emplListArra[i];
		var titlCompArra = [titl componentsSeparatedByString:@":"];	
		var iden = titlCompArra[1];
		quer = [CPString stringWithFormat:@"select id,seriesId,eventIdentifier,start_date,end_date,text,source,calendar,personnel,location,customer,lat,lng,vehicle,eventComm,serieComm from %@.eventsPermanent where  personnel like '%%:%@|%%'",dataBase,iden];
		alert ("query 1" +  quer);
		[self query:quer];
		
		
		
		
		//alert(quer);
		//var colo = [CPString stringWithFormat:@"#%x%x%x",
		//		2+Math.floor(Math.random()*4.99),4+Math.floor(Math.random()*11.99),4+Math.floor(Math.random()*4.99)];
		var colo = [self getRandomColor];	
		quer = [CPString stringWithFormat:@"update %@.events set color='%@' where  personnel like '%%:%@|%%'",
			dataBase,colo,iden];
		//alert ("query 2" +  quer);
		[self query:quer];		
		if ( i>0 )
			emplListStri = [CPString stringWithFormat:@"%@ and",emplListStri];
		emplListStri = [CPString stringWithFormat:@"%@ personnel like '%%:%@|%%'",emplListStri,iden];
	}
	if ( emplListCoun > 1 ) {
		quer = [CPString stringWithFormat:@"update %@.events set color='#F00' where %@",dataBase,emplListStri];
		//alert ("query 3" +  quer);
		[self query:quer];
	}
	//quer = "CALL " + dataBase + ".setFlagTrigger(1)";
	//[self query:quer];
    //alert("pass procedure " + quer);
	
	[self scheduleNew:nil];
	
	*/
//}



//Change
//New up 2017-05-25
- (void) scheduleEventFilterEmployees:(id)sender {

	var quer = @"truncate " + dataBase + "." + appCont.useTabl;
	[self query:quer];
	var quer = @"truncate " + dataBase + ".eventsAux";
	[self query:quer];

	var emplListCoun = [emplListArra count];
	var emplListStri = @"";
	console.log(emplListCoun);
	for ( var i=0; i<emplListCoun; i++ ) {
		var titl = emplListArra[i];
		var titlCompArra = [titl componentsSeparatedByString:@":"];	
		var iden = titlCompArra[1];
		quer = [CPString stringWithFormat:@"replace into %@.eventsAux SELECT e.* FROM %@.eventsPermanent as e Inner Join  %@.eventPerson as ep on  e.id = ep.idEvent inner join %@.persons as p on ep.idPerson = p.id where p.id = %@;",
			dataBase,dataBase,dataBase,dataBase,iden];

		[self query:quer];

		var colo = [self getRandomColor];	
		quer = [CPString stringWithFormat:@"update %@.eventsAux set color='%@' where  personnel like '%%:%@|%%'",
			dataBase,colo,iden];
		//alert ("query 2" +  quer);
		//[self query:quer];		
		if ( i>0 )
			emplListStri = [CPString stringWithFormat:@"%@ and",emplListStri];
		emplListStri = [CPString stringWithFormat:@"%@ personnel like '%%:%@|%%'",emplListStri,iden];
	}
	if ( emplListCoun > 1 ) {
		quer = [CPString stringWithFormat:@"update %@.eventsAux set color='#F00' where %@",dataBase,emplListStri];
		//[self query:quer];
	}
	
	quer  = [CPString stringWithFormat:@"insert into %@.%@ (select * from %@.eventsAux)",dataBase,appCont.useTabl,dataBase];
	[self query:quer];
	[self scheduleNew:nil];
}



- (void) scheduleEventFilterEquipment:(id)sender {

	var quer = @"truncate " + dataBase + "." + appCont.useTabl;
	[self query:quer];

	var equiListCoun = [equiListArra count];
	var equiListStri = @"";
	for ( var i=0; i<equiListCoun; i++ ) {
		var titl = equiListArra[i];
		var titlCompArra = [titl componentsSeparatedByString:@":"];	
		var iden = titlCompArra[1];
		quer = [CPString stringWithFormat:@"replace into %@.%@ SELECT e.* FROM %@.eventsPermanent as e Inner Join  %@.eventEquipment as ee on  e.id = ee.idEvent inner join  %@.equipment as eq on ee.idEquipment = eq.id0 where eq.id0 = %@;",
			dataBase,appCont.useTabl,dataBase,dataBase,dataBase,iden];
		[self query:quer];
		//var colo = [CPString stringWithFormat:@"#%x%x%x",
		//		2+Math.floor(Math.random()*4.99),4+Math.floor(Math.random()*4.99),4+Math.floor(Math.random()*11.99)];
		var colo = [self getRandomColor];	
		quer = [CPString stringWithFormat:@"update %@.%@ set color='%@' where vehicle like '%%:%@|%%'",
			dataBase,appCont.useTabl,colo,iden];
		//[self query:quer];
		if ( i>0 )
			equiListStri = [CPString stringWithFormat:@"%@ and",equiListStri];
		equiListStri = [CPString stringWithFormat:@"%@ vehicle like '%%:%@|%%'",equiListStri,iden];
	}
	if ( equiListCoun > 1 ) {
		quer = [CPString stringWithFormat:@"update %@.%@ set color='#F00' where %@",
			dataBase,appCont.useTabl,equiListStri];
	    //[self query:quer];
	}

	//alert(quer);
	[self scheduleNew:nil];
}



- (void) scheduleEventFilterFields:(id)sender {

	var quer = @"truncate " + dataBase + "." + appCont.useTabl;
	[self query:quer];

	quer = @"replace into " + dataBase + "."+ appCont.useTabl+" select * from " + dataBase + ".eventsPermanent where";
	var stat = NO;

	var inde;
	console.log("0. Equi" + quer);
	var cust = [custPopu titleOfSelectedItem];
	if ( cust && ! [cust isEqualToString:@"Organizaciones"] ) {
		inde = [custPopu indexOfSelectedItem] - 1;
		
		var iden = custArra[inde][2];
		quer = [CPString stringWithFormat:@"%@ customer = %@",quer,iden];
		stat = YES;
	}
console.log("1 Org" + quer);
	var loca = [custLocaPopu titleOfSelectedItem];
	if ( loca && ! [loca isEqualToString:@"Locaciones"] ) {
		inde = [custLocaPopu indexOfSelectedItem] - 1;

		var valuList = [custLocaArra[inde] valueList]

		if ( stat )
			quer = [CPString stringWithFormat:@"%@ and location = %@",quer,valuList[0]];
		else
			quer = [CPString stringWithFormat:@"%@ location = %@",quer,valuList[0]];
		stat = YES;
	}

	var state = [statePopu titleOfSelectedItem];
	if ( state && ! [state isEqualToString:@"Estado"] ) {
		if ( stat )
			quer = [CPString stringWithFormat:@"%@ and location in (select id from %@.organizationLocations where AddressState = '%@' )",quer,dataBase,state];
		else
			quer = [CPString stringWithFormat:@"%@ location in (select id from %@.organizationLocations where AddressState = '%@' )",quer,dataBase,state];
		stat = YES;
	}

    var counActi = [actiListArra count];
    var  clau = @"";
    var  sepa = @"";
    if ( counActi > 0 ) {
        for ( var h = 0; h < [actiListArra count]; h++ ) {
        	if ( h > 0 )
        		sepa = @",";
        	var inde = [actiPopu indexOfItemWithTitle:actiListArra[h]] - 1; 
        	var valuList = [actiArra[inde] valueList];
        	clau = [CPString stringWithFormat:@"%@%@%@",clau,sepa,valuList[3]];
        } 
        if ( [clau length] > 0 ) {
			if ( stat )
				quer = [CPString stringWithFormat:@"%@ and id in (Select idEvent from %@.eventActivity where idActivity IN (%@))",quer,dataBase,clau];
			else
				quer = [CPString stringWithFormat:@"%@ id in (Select idEvent from %@.eventActivity where idActivity IN (%@))",quer,dataBase,clau];
			stat = YES;        	
        }
    }
    
    /*
	var acti = [actiPopu titleOfSelectedItem];
	if ( acti && ! [acti isEqualToString:@"Actividades"] ) {
		inde = [actiPopu indexOfSelectedItem] - 1;
		var valuList = [actiArra[inde] valueList];
		if ( stat )
			quer = [CPString stringWithFormat:@"%@ and id in (Select idEvent from %@.eventActivity where idActivity = %@)",quer,dataBase,valuList[3]];
		else
			quer = [CPString stringWithFormat:@"%@ id in (Select idEvent from %@.eventActivity where idActivity = %@)",quer,dataBase,valuList[3]];
		stat = YES;
	}
	*/

	var equi = [equiPopu titleOfSelectedItem];
	var empl = [emplPopu titleOfSelectedItem];
	if ( empl && ! [empl isEqualToString:@"Personal"] ) {
		inde = [emplPopu indexOfSelectedItem] - 1;
		var valuList = [emplArra[inde] valueList];
		if ( stat )
			quer = [CPString stringWithFormat:@"%@ and id in (Select idEvent from %@.eventPerson where idPerson = %@)",quer,dataBase,valuList[0]];
		else
			quer = [CPString stringWithFormat:@"%@ id in (Select idEvent from %@.eventPerson where idPerson = %@)",quer,dataBase,valuList[0]];
		stat = YES;
	}
	if ( equi && ! [equi isEqualToString:@"Equipo"] ) {
		inde = [equiPopu indexOfSelectedItem] - 1;
		var valuList = [equiArra[inde] valueList];
		if ( stat )
			quer = [CPString stringWithFormat:@"%@ and id in (Select idEvent from %@.eventEquipment where idEquipment = %@)",quer,dataBase,valuList[0]];
		else
			quer = [CPString stringWithFormat:@"%@ id in (Select idEvent from %@.eventEquipment where idEquipment = %@)",quer,dataBase,valuList[0]];
		stat = YES;
	}

	if ( stat ) {
		//quer = [CPString stringWithFormat:@"%@ and start_date > (last_day(now()) + interval 1 day - interval 4 month) ",quer];
		[self query:quer];
		
		//console.log(quer);
		//var colo = [CPString stringWithFormat:@"#%x%x%x",
		//		8+Math.floor(Math.random()*7.99),8+Math.floor(Math.random()*7.99),8+Math.floor(Math.random()*7.99)];
		var colo = [self getRandomColor];	
		quer = [CPString stringWithFormat:@"update %@.%@ set color='%@'",dataBase,appCont.useTabl,colo];
		//[self query:quer];
		//console.log(quer);
	    [coloText setStringValue:colo];
	}
	else
		[glblAlerPane showWithMessage:@"Atencion" info:"No se filtraron los datos, Por favor seleccione campos"];
		//alert("No se filtraron los datos. Por favor selecciones campos.");

	[self scheduleNew:nil];
}



- (void) scheduleEventFilterIdentification:(id)sender {

	
	var iden = [idenText stringValue];
	if ( [iden length] == 0 ) {
		[glblAlerPane showWithMessage:@"Informacion" info:"Seleccione un evento de la tabla de eventos con el número de identificación deseado o introduzca éste en la casilla"];
		//alert("Seleccione un evento de la tabla de eventos con el número de identificación deseado o introduzca éste en la casilla");
		return;
	}

	var quer = @"truncate " + dataBase + "." + appCont.useTabl ;
	[self query:quer];

	quer = [CPString stringWithFormat:@"replace into %@.%@ select * from %@.eventsPermanent where id=%@",
		dataBase,appCont.useTabl,dataBase,iden];
	[self query:quer];

	//var colo = [CPString stringWithFormat:@"#%x%x%x",
    //		8+Math.floor(Math.random()*7.99),8+Math.floor(Math.random()*7.99),8+Math.floor(Math.random()*7.99)];
	var colo = [self getRandomColor];	
	var quer = [CPString stringWithFormat:@"update %@.%@ set color='%@'",dataBase,appCont.useTabl,colo];
	//[self query:quer];

    [coloText setStringValue:colo];

    [self scheduleNew:nil];
}



- (void) scheduleEventFilterLocation:(id)sender {

	var inde = [custLocaPopu indexOfSelectedItem];
	if ( inde < 0 ) {
		[glblAlerPane showWithMessage:@"Operacion fallida" info:"No hay locacion seleccionada, re intentelo"];
		//alert("No hay locación seleccionada");
		return;
	}

	var quer = @"truncate " + dataBase + "." + appCont.useTabl;
	[self query:quer];

	inde--;
	var valuList = [custLocaArra[inde] valueList];
	var iden = valuList[0];

	quer = [CPString stringWithFormat:@"replace into %@.%@ select * from %@.eventsPermanent where location = %@ ",
		dataBase,appCont.useTabl,dataBase,iden];
	[self query:quer];
	
	var colo = valuList[7];
	if ( [colo length] != 7 )
		 colo = [self getRandomColor];	
	//var quer = [CPString stringWithFormat:@"update %@.%@ set color='%@'",dataBase,appCont.useTabl,colo];
	//[self query:quer];

	[self scheduleNew:nil];
}

- (void) scheduleEventFilterState:(id)sender {

	var inde = [statePopu indexOfSelectedItem];
	if ( inde < 1 ) {
		[glblAlerPane showWithMessage:@"Operacion fallida" info:"No hay estado seleccionado, re intentelo"];
		//alert("No hay locación seleccionada");
		return;
	}

	var quer = @"truncate " + dataBase + "." + appCont.useTabl;
	[self query:quer];

	var iden = [statePopu titleOfSelectedItem];
	quer = [CPString stringWithFormat:@"replace into %@.%@ select e.* from %@.eventsPermanent as e inner join %@.organizationLocations as o on e.location = o.id where o.AddressState = '%@' ",
		dataBase,appCont.useTabl,dataBase,dataBase,iden];
	[self query:quer];

	[self scheduleNew:nil];
}


		
- (void) scheduleEventFilterOrganizations:(id)sender {

	var quer = @"truncate " + dataBase + "." + appCont.useTabl;
	[self query:quer];

	var iden = [custPopu titleOfSelectedItem];
	var coun = [custArra count];
	var orgaId = 0;
	for ( var i=0; i<coun; i++ ) {
		var arraTemp = custArra[i];
		if(iden == arraTemp[1]){
			orgaId = arraTemp[2];
		}

	}

    quer = [CPString stringWithFormat:@"replace into %@.%@ select * from %@.eventsPermanent where customer = '%@' order by location",
				dataBase,appCont.useTabl,dataBase,orgaId];
	[self query:quer];

	[self scheduleNew:nil];
	/*
	var coun = [custLocaArra count];
	for ( var i=0; i<coun; i++ ) {
		var valuList = [custLocaArra[i] valueList];
		var iden = valuList[0];

		quer = [CPString stringWithFormat:@"replace into %@.events select * from %@.eventsPermanent where location like '%%:%@|'",
			dataBase,dataBase,iden];
		[self query:quer];

		var colo = valuList[7];
		quer = [CPString stringWithFormat:@"update %@.events set color='%@' where location like '%%:%@|'",
			dataBase,colo,iden];
		[self query:quer];
	}
	*/
}



- (void) scheduleEventFilterNone:(id)sender {

	var quer = @"truncate " + dataBase + "." +appCont.useTabl;
	[self query:quer];

	var quer = "Select attributeValue from riglobal.userAttributes where objectName = '"+appCont.accoUser+"' and attributeName = 'scheduleRange' limit 1;"
	var arraAux = [self query:quer];
	var befoM   = "2";
	var afteM   = "4";
	if( [arraAux count] == 1 ){
		var comp = [[arraAux[0] valueList][0] componentsSeparatedByString:@"#SC#"];
		befoM = [comp[0] intValue];
		afteM = [comp[1] intValue];		
	}

	quer = @"replace into " + dataBase + "."+ appCont.useTabl +" select * from " + dataBase + ".eventsPermanent where start_date between ";
	quer +=" (last_day(now()) + interval 1 day - interval " + befoM + " month) AND (last_day(now()) + interval 1 day + interval " + afteM + " month);";
	[self query:quer];
   /*
	quer = @"select id,color from " + dataBase + ".organizationLocations";
	var arra = [self query:quer];
	var arraCoun = [arra count];
	for ( var i=0; i<arraCoun; i++ ) {
		var valuList = [arra[i] valueList];
		var iden = valuList[0];
		var colo = valuList[1];
		if ( [colo isEqualToString:@"0"] )
			colo = [CPString stringWithFormat:@"#%x%x%x",
				8+Math.floor(Math.random()*7.99),8+Math.floor(Math.random()*7.99),8+Math.floor(Math.random()*7.99)];
		var quer = [CPString stringWithFormat:@"update %@.events set color='%@' where location like '%%:%@|'",dataBase,colo,iden];
		[self query:quer];
		var quer = [CPString stringWithFormat:@"update %@.organizationLocations set color='%@' where id=%@",dataBase,colo,iden];
		[self query:quer];
	}
	*/
	[self scheduleNew:nil];
}



- (void) scheduleEventFilterSeries:(id)sender {

	var seri = [seriText stringValue];
	if ( [seri length] == 0 ) {
		[glblAlerPane showWithMessage:@"Informacion" info:"Seleccione un evento de la tabla de eventos con el número de serie deseado o introduzca éste en la casilla"];
		//alert("Seleccione un evento de la tabla de eventos con el número de serie deseado o introduzca éste en la casilla");
		return;
	}

	var quer = @"truncate " + dataBase + "." + appCont.useTabl;
	[self query:quer];

	quer = [CPString stringWithFormat:@"replace into %@.%@ select * from %@.eventsPermanent where seriesId=%@",
		dataBase,appCont.useTabl,dataBase,seri];
	[self query:quer];

	var colo = [coloText stringValue];
	quer = [CPString stringWithFormat:@"update %@.%@ set color='%@' ",
		dataBase,appCont.useTabl,colo];
	//[self query:quer];

	[self scheduleNew:nil];
}



- (void) scheduleEventFreeBlockedSpots:(id)sender {
	var fact1 = 4;
	var fact2 = 3600./fact1;
	var xd = 4;
	var yd = 4;

	var numb = fact1*24*7*52;
	var spotArra = [];
	for ( var i=0; i<numb; i++ )
		spotArra[i] = 0;

	var dateNow = [CPDate date];
	var stri = [CPString stringWithFormat:@"%@ 00:00:00 -0600",[[dateNow description] substringToIndex:10]];
	var dateRefe = [[CPDate alloc] initWithString:stri];
	var day = dateRefe.getDay();
	if ( day )
		dateRefe = [[CPDate alloc] initWithTimeInterval:-day*24*3600. sinceDate:dateRefe];
	var dateRefeDesc = [dateRefe description];
	//alert("dateRefeDesc = "+dateRefeDesc);


	// Customer's location
	
	var orgaLoca = [custLocaPopu titleOfSelectedItem];
	//alert("Considering orgaLoca="+orgaLoca);
	var orgaLocaComp = [orgaLoca componentsSeparatedByString:@":"];
	var orgaLocaCode = orgaLocaComp[1];
	if ( ! [orgaLoca isEqualToString:@"Locaciones"] ) {
		var quer = [CPString stringWithFormat:@"select start_date,end_date from %@.eventsPermanent where location = '|%@|'",dataBase,orgaLoca];
		var orgaLocaDayArra = [self query:quer];
		var orgaLocaDayCoun = [orgaLocaDayArra count];
		for ( var i=0; i<orgaLocaDayCoun; i++ ) {
			var valuList = [orgaLocaDayArra[i] valueList];
			var stri = [CPString stringWithFormat:@"%@:00 -0600",valuList[0]];
			var dateStar = [[CPDate alloc] initWithString:stri];
			var timeStar = [dateStar timeIntervalSinceDate:dateRefe];
			stri = [CPString stringWithFormat:@"%@:00 -0600",valuList[1]];
			var dateFini = [[CPDate alloc] initWithString:stri];
			var timeFini = [dateFini timeIntervalSinceDate:dateRefe];

			if ( timeStar < 0. && timeFini > 0. ) {
				var spotIndeStar = 0;
				var spotIndeFini = timeFini / fact2;
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 7;
			}
			else if ( timeStar > 0. && timeFini > 0. ) {
				var spotIndeStar = Math.floor(timeStar/fact2);
				var spotIndeFini = Math.floor(timeFini/fact2 + 0.99);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 7;
			}
		}

	}


	// Equipment available time

	var equi = [equiPopu titleOfSelectedItem];
	//alert("Considering equipment="+equi);
	var equiComp = [equi componentsSeparatedByString:@":"];
	var equiCode = equiComp[1];
	if ( ! [equi isEqualToString:@"Equipo"] ) {
		var quer = [CPString stringWithFormat:@"select start_date,end_date from %@.eventsPermanent where vehicle like '%%|%@|%%'",dataBase,equi];
		var equiDayArra = [self query:quer];
		var equiDayCoun = [equiDayArra count];
		for ( var i=0; i<equiDayCoun; i++ ) {
			var valuList = [equiDayArra[i] valueList];
			var stri = [CPString stringWithFormat:@"%@:00 -0600",valuList[0]];
			var dateStar = [[CPDate alloc] initWithString:stri];
			var timeStar = [dateStar timeIntervalSinceDate:dateRefe];
			stri = [CPString stringWithFormat:@"%@:00 -0600",valuList[1]];
			var dateFini = [[CPDate alloc] initWithString:stri];
			var timeFini = [dateFini timeIntervalSinceDate:dateRefe];

			if ( timeStar < 0. && timeFini > 0. ) {
				var spotIndeStar = 0;
				var spotIndeFini = timeFini / fact2;
				//alert("i="+i+"   dateStart="+stri+"  spotIndeStar="+spotIndeStar+"   spotIndeFini="+spotIndeFini);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 6;
			}
			else if ( timeStar > 0. && timeFini > 0. ) {
				var spotIndeStar = Math.floor(timeStar/fact2);
				var spotIndeFini = Math.floor(timeFini/fact2 + 0.99);
				//alert("i="+i+"   dateStart="+stri+"  spotIndeStar="+spotIndeStar+"   spotIndeFini="+spotIndeFini);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 6;
			}
		}

	}


	// Company's holidays

	/*
	if ( holiArra && [holiArra count]>0 ) {
		var coun = [holiArra count];
		for ( var i=0; i<coun; i++ ) {
			var valuList = [holiArra[i] valueList];
			var stri = [CPString stringWithFormat:@"%@ -0600",valuList[2]];
			var dateStar = [[CPDate alloc] initWithString:stri];
			var timeStar = [dateStar timeIntervalSinceDate:dateRefe];
			stri = [CPString stringWithFormat:@"%@ -0600",valuList[3]];
			var dateFini = [[CPDate alloc] initWithString:stri];
			var timeFini = [dateFini timeIntervalSinceDate:dateRefe];

			if ( timeStar < 0. && timeFini > 0. ) {
				var spotIndeStar = 0;
				var spotIndeFini = timeFini / fact2;
				//alert("i="+i+"   dateStart="+stri+"  spotIndeStar="+spotIndeStar+"   spotIndeFini="+spotIndeFini);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 2;
			}
			else if ( timeStar > 0. && timeFini > 0. ) {
				var spotIndeStar = Math.floor(timeStar/fact2);
				var spotIndeFini = Math.floor(timeFini/fact2 + 0.99);
				//alert("i="+i+"   dateStart="+stri+"  spotIndeStar="+spotIndeStar+"   spotIndeFini="+spotIndeFini);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 2;
			}
		}
		var spot = @"";
	}
	else
		alert("La organizacion no tiene días feriados!");
	*/


	// Employee available time

	var empl = [emplPopu titleOfSelectedItem];
	//alert("Considering empl="+empl);
	var emplComp = [empl componentsSeparatedByString:@":"];
	var emplCode = emplComp[1];
	if ( ! [empl isEqualToString:@"Personal"] ) {
		var emplDay = [];
		var emplTimeStar = [];
		var emplTimeFini = [];
		for ( var i=0; i<7; i++ ) {
			emplDay[i] = 1;
			emplTimeStar[i] = @"00:00";
			emplTimeFini[i] = @"23:59";
		}

		var quer = [CPString stringWithFormat:@"select day,timeStart,timeFinish from %@.personSchedule where personId=%@",dataBase,emplCode];
		var emplDayArra = [self query:quer];
		var emplDayCoun = [emplDayArra count];
		for ( var i=0; i<emplDayCoun; i++ ) {
			var valuList = [emplDayArra[i] valueList];
			var day = [[valuList objectAtIndex:0] intValue];
			emplDay[day] = 0;
			emplTimeStar[day] = [[valuList[1] substringToIndex:2] intValue];
			emplTimeFini[day] = [[valuList[2] substringToIndex:2] intValue];
			//alert("day="+day+"  start="+emplTimeStar[day]+"   finish="+emplTimeFini[day]);
		}

		for ( var i=0; i<numb; i++ ) {
			var timeInte = i*fact2;
			var dateNext = [[CPDate alloc] initWithTimeInterval:timeInte sinceDate:dateRefe];
			var day = dateNext.getDay();
			if ( emplDay[day] == 1 ) {
				spotArra[i] = 4;
			}
			else {
				var hour = dateNext.getHours();
				if ( hour<emplTimeStar[day] || hour>=emplTimeFini[day] )
					spotArra[i] = 4;
			}
		}

		quer = [CPString stringWithFormat:@"select start_date,end_date from %@.eventsPermanent where personnel like '%%|%@|%%'",dataBase,empl];
		emplDayArra = [self query:quer];
		emplDayCoun = [emplDayArra count];
		//alert(quer+"  count="+emplDayCoun);
		for ( var i=0; i<emplDayCoun; i++ ) {
			var valuList = [emplDayArra[i] valueList];
			var stri = [CPString stringWithFormat:@"%@:00 -0600",valuList[0]];
			var dateStar = [[CPDate alloc] initWithString:stri];
			var timeStar = [dateStar timeIntervalSinceDate:dateRefe];
			stri = [CPString stringWithFormat:@"%@:00 -0600",valuList[1]];
			var dateFini = [[CPDate alloc] initWithString:stri];
			var timeFini = [dateFini timeIntervalSinceDate:dateRefe];

			if ( timeStar < 0. && timeFini > 0. ) {
				var spotIndeStar = 0;
				var spotIndeFini = timeFini / fact2;
				//alert("i="+i+"   dateStart="+stri+"  spotIndeStar="+spotIndeStar+"   spotIndeFini="+spotIndeFini);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 4;
			}
			else if ( timeStar > 0. && timeFini > 0. ) {
				var spotIndeStar = Math.floor(timeStar/fact2);
				var spotIndeFini = Math.floor(timeFini/fact2 + 0.99);
				//alert("i="+i+"   dateStart="+stri+"  spotIndeStar="+spotIndeStar+"   spotIndeFini="+spotIndeFini);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 4;
			}
		}

		quer = [CPString stringWithFormat:@"select dateStart,dateFinish from %@.personVacations where personId='%@'",dataBase,emplCode];
		emplDayArra = [self query:quer];
		emplDayCoun = [emplDayArra count];
		//alert(quer+"  personVacations count="+emplDayCoun);
		for ( var i=0; i<emplDayCoun; i++ ) {
			var valuList = [emplDayArra[i] valueList];
			var stri = [CPString stringWithFormat:@"%@ -0600",valuList[0]];
			var dateStar = [[CPDate alloc] initWithString:stri];
			var timeStar = [dateStar timeIntervalSinceDate:dateRefe];
			stri = [CPString stringWithFormat:@"%@ -0600",valuList[1]];
			var dateFini = [[CPDate alloc] initWithString:stri];
			var timeFini = [dateFini timeIntervalSinceDate:dateRefe];

			if ( timeStar < 0. && timeFini > 0. ) {
				var spotIndeStar = 0;
				var spotIndeFini = timeFini / fact2;
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 4;
			}
			else if ( timeStar > 0. && timeFini > 0. ) {
				var spotIndeStar = Math.floor(timeStar/fact2);
				var spotIndeFini = Math.floor(timeFini/fact2 + 0.99);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 4;
			}
		}

	}


	// Customer's working hours

	if ( ! [orgaLoca isEqualToString:@"Locaciones"] ) {
		var orgaLocaDay = [];
		var orgaLocaTimeStar = [];
		var orgaLocaTimeFini = [];
		for ( var i=0; i<7; i++ ) {
			orgaLocaDay[i] = 1;
			orgaLocaTimeStar[i] = @"00:00";
			orgaLocaTimeFini[i] = @"23:59";
		}

		var quer = [CPString stringWithFormat:@"select day,timeStart,timeFinish from %@.locationSchedule where organizationLocationId=%@",dataBase,orgaLocaCode];
		var orgaLocaDayArra = [self query:quer];
		var orgaLocaDayCoun = [orgaLocaDayArra count];
		for ( var i=0; i<orgaLocaDayCoun; i++ ) {
			var valuList = [orgaLocaDayArra[i] valueList];
			var day = [[valuList objectAtIndex:0] intValue];
			orgaLocaDay[day] = 0;
			orgaLocaTimeStar[day] = [[valuList[1] substringToIndex:2] intValue];
			orgaLocaTimeFini[day] = [[valuList[2] substringToIndex:2] intValue];
			//alert("day="+day+"  start="+orgaLocaTimeStar[day]+"   finish="+orgaLocaTimeFini[day]);
		}
		for ( var i=0; i<numb; i++ ) {
			var timeInte = i*fact2;
			var dateNext = [[CPDate alloc] initWithTimeInterval:timeInte sinceDate:dateRefe];
			var day = dateNext.getDay();
			if ( orgaLocaDay[day] == 1 ) {
				spotArra[i] = 5;
			}
			else {
				var hour = dateNext.getHours();
				if ( hour<orgaLocaTimeStar[day] || hour>=orgaLocaTimeFini[day] )
					spotArra[i] = 5;
			}
		}

	}


	// Customer's holidays

	if ( custHoliArra && [custHoliArra count]>0 ) {
		var coun = [custHoliArra count];
		for ( var i=0; i<coun; i++ ) {
			var valuList = [custHoliArra[i] valueList];
			var stri = [CPString stringWithFormat:@"%@ -0600",valuList[2]];
			var dateStar = [[CPDate alloc] initWithString:stri];
			var timeStar = [dateStar timeIntervalSinceDate:dateRefe];
			stri = [CPString stringWithFormat:@"%@ -0600",valuList[3]];
			var dateFini = [[CPDate alloc] initWithString:stri];
			var timeFini = [dateFini timeIntervalSinceDate:dateRefe];

			if ( timeStar < 0. && timeFini > 0. ) {
				var spotIndeStar = 0;
				var spotIndeFini = timeFini / fact2;
				//alert("i="+i+"   dateStart="+stri+"  spotIndeStar="+spotIndeStar+"   spotIndeFini="+spotIndeFini);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 3;
			}
			else if ( timeStar > 0. && timeFini > 0. ) {
				var spotIndeStar = Math.floor(timeStar/fact2);
				var spotIndeFini = Math.floor(timeFini/fact2 + 0.99);
				//alert("i="+i+"   dateStart="+stri+"  spotIndeStar="+spotIndeStar+"   spotIndeFini="+spotIndeFini);
				for ( var j=spotIndeStar; j<spotIndeFini; j++ )
					spotArra[j] = 3;
			}
		}
		var spot = @"";
	}


	// Past is gray

	for ( var i=0; i<numb; i++ ) {
		var timeInte = i*fact2;
		var dateNext = [[CPDate alloc] initWithTimeInterval:timeInte sinceDate:dateRefe];
		var timeNext = [dateNext timeIntervalSinceDate:dateRefe];
		var timeInte = [dateNext timeIntervalSinceDate:dateNow];
		if ( timeInte < 0. ) {
			var spotInde = Math.floor(timeNext/fact2);
			spotArra[spotInde] = 8;
		}
		else {
			break;
		}
	}


	// First hour of month

	var year = [[stri substringToIndex:4] intValue];
	for ( var y=0; y<2; y++ ) {
		for ( var m=0; m<12; m++ ) {
			stri = [CPString stringWithFormat:@"%04d-%02d-01 00:00:00 -0600",year+y,m];
			var dateStar = [[CPDate alloc] initWithString:stri];
			var timeStar = [dateStar timeIntervalSinceDate:dateRefe];
			if ( timeStar > 0. ) {
				var spotIndeStar = Math.floor(timeStar/fact2);
				spotArra[spotIndeStar] = 1;
				//alert("First of month = "+stri+"   spotIndeStar="+spotIndeStar);
			}
		}
	}


	// 1 Year - 52 Week

	var x = 60;
	var y = 60;
	var w = 26*8*xd + 40;
	var h = 2*24*fact1*yd + 40;
	var fram = CGRectMake(x,y, w,h);

    var	spotPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[spotPane setFloatingPanel:YES]; 
	[spotPane setDelegate:self];
	[spotPane orderFront:self];
	[spotPane setTitle:orgaLoca+"   "+empl+"   "+equi];
	
	var paneContView = [spotPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:2. heightOrange:4.];

	var x;
	var y0;
	for ( var k=0; k<52; k++ ) {
		if ( k < 26 ) {
			x = (2+k*8)*xd;
			y0 = 4*yd;
		}
		else {
			x = (2+(k-26)*8)*xd;
			y0 = (24*fact1+6)*yd;
		}
		for ( var j=0; j<7; j++ ) {
			x += xd;
			for ( var i=0; i<12*fact1; i++ ) {
				var y = y0 + i*yd;
				var fram = CGRectMake(x,y, xd-1,yd-1);
				var view = [[RMSchedulerCPView alloc] initWithFrame:fram];
				var ijk = (k*7+j)*24*fact1 + i;
				if ( spotArra[ijk] == 0 )
					[view setBackgroundColor:[CPColor greenColor]];
				else if ( spotArra[ijk] == 1 )
					[view setBackgroundColor:[CPColor whiteColor]];
				else if ( spotArra[ijk] == 2 )
					[view setBackgroundColor:[CPColor magentaColor]];
				else if ( spotArra[ijk] == 3 )
					[view setBackgroundColor:[CPColor redColor]];
				else if ( spotArra[ijk] == 4 )
					[view setBackgroundColor:[CPColor orangeColor]];
				else if ( spotArra[ijk] == 5 )
					[view setBackgroundColor:[CPColor brownColor]];
				else if ( spotArra[ijk] == 6 )
					[view setBackgroundColor:[CPColor blueColor]];
				else if ( spotArra[ijk] == 7 )
					[view setBackgroundColor:[CPColor yellowColor]];
				else if ( spotArra[ijk] == 8 )
					[view setBackgroundColor:[CPColor grayColor]];
				[paneContView addSubview:view];
			}
			for ( var i=12*fact1+1; i<24*fact1; i++ ) {
				var y = y0 + i*yd;
				var fram = CGRectMake(x,y, xd-1,yd-1);
				var view = [[RMSchedulerCPView alloc] initWithFrame:fram];
				var ijk = (k*7+j)*24*fact1 + i;
				if ( spotArra[ijk] == 0 )
					[view setBackgroundColor:[CPColor greenColor]];
				else if ( spotArra[ijk] == 1 )
					[view setBackgroundColor:[CPColor whiteColor]];
				else if ( spotArra[ijk] == 2 )
					[view setBackgroundColor:[CPColor magentaColor]];
				else if ( spotArra[ijk] == 3 )
					[view setBackgroundColor:[CPColor redColor]];
				else if ( spotArra[ijk] == 4 )
					[view setBackgroundColor:[CPColor orangeColor]];
				else if ( spotArra[ijk] == 5 )
					[view setBackgroundColor:[CPColor brownColor]];
				else if ( spotArra[ijk] == 6 )
					[view setBackgroundColor:[CPColor blueColor]];
				else if ( spotArra[ijk] == 7 )
					[view setBackgroundColor:[CPColor yellowColor]];
				else if ( spotArra[ijk] == 8 )
					[view setBackgroundColor:[CPColor grayColor]];
				[paneContView addSubview:view];
			}
		}
	}


	// 30-Day Month

	var numbMont = fact1*24*30;
	var spotMontArra = [];
	for ( var i=0; i<numbMont; i++ )
		spotMontArra[i] = 0;

	var ii = 0;
	for ( var m=0; m<11; m++ ) {
		for ( var d=0; d<numbMont; d++ ) {
			if ( spotArra[ii] == 1 )
				break;
			ii++;
		}
		for ( var i=0; i<numbMont; i++ ) {
			if ( spotArra[ii] == 1 && i > 0 )
				break;
			spotMontArra[i] += spotArra[ii];
			ii++;
		}
	}

	x = 950;
	y = 60;
	w = 30*xd + 20;
	h = 24*fact1*yd + 40;
	fram = CGRectMake(x,y, w,h);

	var spotMontPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[spotMontPane setFloatingPanel:YES]; 
	[spotMontPane setDelegate:self];
	[spotMontPane orderFront:self];
	[spotMontPane setTitle:"Summary 30-day month: "+orgaLoca+"   "+empl+"   "+equi];
	
	paneContView = [spotMontPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:2. heightOrange:4.];

	for ( var d=0; d<30; d++ ) {
		x = (4+d)*xd;
		y0 = 4*yd;

		for ( var i=0; i<12*fact1; i++ ) {
			var y = y0 + i*yd;
			var fram = CGRectMake(x,y, xd-1,yd-1);

			var view = [[RMSchedulerCPView alloc] initWithFrame:fram];
			var ijk = d*24*fact1 + i;

			var red  = spotMontArra[ijk] / 11.;
			var gree = 1. - spotMontArra[ijk] / 11.;
			var blue = spotMontArra[ijk]/11.*(1.-spotMontArra[ijk]/11.)*4.;
			var colo = [CPColor colorWithCalibratedRed:red green:gree blue:blue alpha:1.];
			[view setBackgroundColor:colo];
			
			//console.log("d="+d+"   i="+i+"   x="+x+"   y="+y+"   ["+red+","+gree+","+blue+"]  fram="+fram);

			[paneContView addSubview:view];
		}
		for ( var i=12*fact1+1; i<24*fact1; i++ ) {
			var y = y0 + i*yd;
			var fram = CGRectMake(x,y, xd-1,yd-1);
			var view = [[RMSchedulerCPView alloc] initWithFrame:fram];
			var ijk = d*24*fact1 + i;

			var red  = spotMontArra[ijk] / 11.;
			var gree = 1. - spotMontArra[ijk] / 11.;
			var blue = spotMontArra[ijk]/11.*(1.-spotMontArra[ijk]/11.)*4.;
			var colo = [CPColor colorWithCalibratedRed:red green:gree blue:blue alpha:1.];
			[view setBackgroundColor:colo];

			[paneContView addSubview:view];
		}

	}


	// 4-Week

	var numb4Week = fact1*24*7*4;
	var spot4WeekArra = [];
	for ( var i=0; i<numb4Week; i++ )
		spot4WeekArra[i] = 0;

	for ( var w=0; w<13; w++ ) {
		var wi= numb4Week*w;
		for ( var i=0; i<numb4Week; i++ )
			spot4WeekArra[i] += spotArra[wi+i];
	}

	x = 1100;
	y = 60;
	w = 28*xd + 40;
	h = 24*fact1*yd + 40;
	fram = CGRectMake(x,y, w,h);

    var	spot4WeekPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[spot4WeekPane setFloatingPanel:YES]; 
	[spot4WeekPane setDelegate:self];
	[spot4WeekPane orderFront:self];
	[spot4WeekPane setTitle:"Summary 4-Week: "+orgaLoca+"   "+empl+"   "+equi];
	
	paneContView = [spot4WeekPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:2. heightOrange:4.];

	for ( var k=0; k<4; k++ ) {
		x = (2+k*8)*xd;
		y0 = 4*yd;
		for ( var j=0; j<7; j++ ) {
			x += xd;
			for ( var i=0; i<12*fact1; i++ ) {
				var y = y0 + i*yd;
				var fram = CGRectMake(x,y, xd-1,yd-1);
				var view = [[RMSchedulerCPView alloc] initWithFrame:fram];
				var ijk = (k*7+j)*24*fact1 + i;

				var red  = spot4WeekArra[ijk] / 52.;
				var gree = 1. - spot4WeekArra[ijk] / 52.;
				var blue = spot4WeekArra[ijk]/52.*(1.-spot4WeekArra[ijk]/52.)*4.;
				var colo = [CPColor colorWithCalibratedRed:red green:gree blue:blue alpha:1.];
				[view setBackgroundColor:colo];

				[paneContView addSubview:view];
			}
			for ( var i=12*fact1+1; i<24*fact1; i++ ) {
				var y = y0 + i*yd;
				var fram = CGRectMake(x,y, xd-1,yd-1);
				var view = [[RMSchedulerCPView alloc] initWithFrame:fram];
				var ijk = (k*7+j)*24*fact1 + i;

				var red  = spot4WeekArra[ijk] / 52.;
				var gree = 1. - spot4WeekArra[ijk] / 52.;
				var blue = spot4WeekArra[ijk]/52.*(1.-spot4WeekArra[ijk]/52.)*4.;
				var colo = [CPColor colorWithCalibratedRed:red green:gree blue:blue alpha:1.];
				[view setBackgroundColor:colo];

				[paneContView addSubview:view];
			}
		}
	}
	

	// Week

	var numbWeek = fact1*24*7;
	var spotWeekArra = [];
	for ( var i=0; i<numbWeek; i++ )
		spotWeekArra[i] = 0;


	for ( var w=0; w<52; w++ ) {
		var wi= numbWeek*w;
		for ( var i=0; i<numbWeek; i++ )
			spotWeekArra[i] += spotArra[wi+i];
	}

	x = 1250;
	y = 60;
	w = 7*xd + 60;
	h = 24*fact1*yd + 40;
	fram = CGRectMake(x,y, w,h);

	var spotWeekPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[spotWeekPane setFloatingPanel:YES]; 
	[spotWeekPane setDelegate:self];
	[spotWeekPane orderFront:self];
	[spotWeekPane setTitle:"Summary Week: "+orgaLoca+"   "+empl+"   "+equi];
	
	paneContView = [spotWeekPane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:2. heightOrange:4.];

	x = 6*xd;
	y0 = 4*yd;
	for ( var j=0; j<7; j++ ) {
		x += xd;
		for ( var i=0; i<12*fact1; i++ ) {
			var y = y0 + i*yd;
			var fram = CGRectMake(x,y, xd-1,yd-1);
			var view = [[RMSchedulerCPView alloc] initWithFrame:fram];
			var ijk = j*24*fact1 + i;

			var red  = spotWeekArra[ijk] / 52.;
			var gree = 1. - spotWeekArra[ijk] / 52.;
			var blue = spotWeekArra[ijk]/52.*(1.-spotWeekArra[ijk]/52.)*4.;
			var colo = [CPColor colorWithCalibratedRed:red green:gree blue:blue alpha:1.];
			[view setBackgroundColor:colo];

			[paneContView addSubview:view];
		}
		for ( var i=12*fact1+1; i<24*fact1; i++ ) {
			var y = y0 + i*yd;
			var fram = CGRectMake(x,y, xd-1,yd-1);
			var view = [[RMSchedulerCPView alloc] initWithFrame:fram];
			var ijk = j*24*fact1 + i;

			var red  = spotWeekArra[ijk] / 52.;
			var gree = 1. - spotWeekArra[ijk] / 52.;
			var blue = spotWeekArra[ijk]/52.*(1.-spotWeekArra[ijk]/52.)*4.;
			var colo = [CPColor colorWithCalibratedRed:red green:gree blue:blue alpha:1.];
			[view setBackgroundColor:colo];

			[paneContView addSubview:view];
		}
	}


}



- (void) scheduleEventNumber:(id)sender {
	//var freqInde = [freqPopu indexOfSelectedItem];
}



- (void) scheduleEventCancelModify:(id)sender {
	[self setControllers_ON_OFF:1];
	[self clearFieldsUpdate:nil];
	//[filtText setStringValue:@""];

	if ( ![updtSubj isEqualToString:@"Serie"] ) {
		[blckView1 setHidden:YES];
    	[blckView2 setHidden:YES];
	}
    updtSubj = nil;
    updtNumb = -1;
    isNew = true;
}



- (void) scheduleEventDeleteID:(id)sender {
	var iden = [idenText stringValue];
	var conf = confirm("Desear eliminar el evento con ID= "+iden+" ?");
	if ( conf ) {
		var quer = [CPString stringWithFormat:@"delete from %@.eventsPermanent where id=%@",dataBase,iden];
		[self query:quer];
		quer = [CPString stringWithFormat:@"delete from %@.events where id=%@",dataBase,iden];
		[self query:quer];
		[evenTabl reloadData];
		[idenText setStringValue:@""];
	}
}



- (void) scheduleEventDeleteSeries:(id)sender {
	var seri = [evenSeriFutuText stringValue];
	var date = [evenDateFutuText stringValue];
	var conf = confirm("Desear eliminar los eventos de la serie * " + seri + " * a partir de la fecha * "+date+" * ?");
	if ( conf ) {
		var quer = [CPString stringWithFormat:@"delete from %@.eventsPermanent where seriesId=%@ and start_date>='%@'",dataBase,seri,date];
		[self query:quer];
		//quer = [CPString stringWithFormat:@"delete from %@.events where seriesId=%@ and start_date>='%@'",dataBase,seri,date];
		//[self query:quer];
		[evenTabl reloadData];
		[evenDeleSeriFutuPane close];
		
	}
	
}



- (void) scheduleEventDeleteSeriesFuture:(id)sender {

	if ( !evenDeleSeriFutuPane ) {
		var x = 300;
		var y = 200;
		var fram = CGRectMake(x,y, 400,120);
		evenDeleSeriFutuPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
		[evenDeleSeriFutuPane setFloatingPanel:YES]; 
		[evenDeleSeriFutuPane setDelegate:self];
		[evenDeleSeriFutuPane orderFront:self];
		[evenDeleSeriFutuPane setTitle:@"Eliminacion Serie en Futuro"];

		var view = [evenDeleSeriFutuPane contentView];
		[view setBackgroundColor:coloDefaBrig];
		[self addBanners:view heightBlue:2. heightOrange:4.];

		var horiPos1 = 10;
		var horiPos2 = horiPos1 + 100;
		var vertPosi = 20;
		var vertIncr = 25;

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

		evenSeriFutuText = [self addTextField:@"" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:80 TFHeight:30 VView:view Editable:YES];
		[evenSeriFutuText setTarget:self];
		[evenSeriFutuText setAction:@selector(someTableSelection:)];
		[evenSeriFutuText setTextColor:[CPColor grayColor]];

		vertPosi += vertIncr;

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

		evenDateFutuText = [self addTextField:@"" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:140 TFHeight:vertIncr VView:view Editable:YES];

		[self addButton:@"C" TFPosX:horiPos2+150 TFPosY:vertPosi-2 TFWidth:25 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventDeleteSeriesDatePickerPanel:)];

		vertPosi += 1.25*vertIncr;

		var butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2,vertPosi, 80,24)];
		[butt setTitle:"Eliminar"];
		[butt setTarget:self];
		[butt setAction:@selector(scheduleEventDeleteSeries:)];                
		[view addSubview:butt];
	}else{
		[evenDeleSeriFutuPane orderFront:self];
	}

	var seriIden = [seriText stringValue];
	[evenSeriFutuText setStringValue:seriIden];
	[evenDateFutuText setStringValue:@""];
}



- (void) scheduleEventDeleteSeriesDatePickerDateChange:(id)sender {
	[evenDateFutuText setStringValue:[[[sender dateValue] description] substringToIndex:16]];
}



- (void) scheduleEventDeleteSeriesDatePickerPanel:(id)sender {

	var fram = CGRectMake(450,300,144,148);
	var datePickPane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask]; 
	[datePickPane setFloatingPanel:YES];
	[datePickPane setTitle:@"DatePicker"];
	[datePickPane orderFront:self];

	var paneContView = [datePickPane 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(scheduleEventDeleteSeriesDatePickerDateChange:)];
	
	[paneContView addSubview:datePick];
}



- (void) scheduleEventExtractID:(id)sender {
	evenOpti = 1;
	[evenTabl reloadData];
        
    [self setControllers_ON_OFF:0]; 
	//id,seriesId,location,start_date,end_date,text,personnel,vehicle,customer,calendar
    
    var indeOrga = [custPopu indexOfSelectedItem];
	var indeLoca = [custLocaPopu indexOfSelectedItem];
	var valuList = [evenArra[0] valueList];
	var evenId   = valuList[0];
    sltdEvenDefi = [[model_eventsDefinitions alloc] init:appCont eventId:[evenId intValue]];
	[self clearFields:nil];
	var orga = [sltdEvenDefi orga];
	//[titlText setStringValue:[sltdEvenDefi titl]];

	[custPopu selectItemAtIndex:indeOrga];

	[self customerPopupSelection:nil];
	[custLocaPopu selectItemAtIndex:indeLoca];
	[self customerLocationPopupSelection:nil];

	actiListArra = [sltdEvenDefi getActivities];
	[actiListTabl reloadData];
	[dateStarText setStringValue:[sltdEvenDefi starDate]];
	[hourStarText setStringValue:[sltdEvenDefi starHour]];
	[minuStarText setStringValue:[sltdEvenDefi starMinu]];
	//[evenFreqText setStringValue:[seriModl freq]];
	//[freqPopu selectItemAtIndex:[[seriModl cale] intValue]];
	//[freqPopu selectItemAtIndex:-1];
	//[evenNumbText setStringValue:[seriModl evnts]];

	emplListArra = [sltdEvenDefi getPersons];
	[emplListTabl reloadData];
	equiListArra = [sltdEvenDefi getEquipments];
	[equiListTabl reloadData];
	[seriText setStringValue:[sltdEvenDefi seriId]];
	[idenText setStringValue:[sltdEvenDefi recoId]];    	
	var _strtDate = [sltdEvenDefi starDate];
	[dateStarText setStringValue:_strtDate];

	//var dateArra  = [_strtDate componentsSeparatedByString:@" "];
	//var dateScnd  = [[dateArra objectAtIndex:1] componentsSeparatedByString:@":"];
	[hourStarText setStringValue:[sltdEvenDefi starHour]];
	[minuStarText setStringValue:[sltdEvenDefi starMinu]];
	[duraText setStringValue:[sltdEvenDefi dura]];

	[self scheduleIdentityEvents:nil];
	[blckView1 setHidden:NO];
	[blckView2 setHidden:NO];
}



- (void) scheduleEventExtractSeries:(id)sender {
	[self updateOriginalSerieParameters];
	evenOpti = 2;
	[evenTabl reloadData];
}



- (void) scheduleEventInsert:(id)sender {

	var inseCoun = 0;
 	var evenNumb = [evenNumbText intValue];
 	if ( evenNumb < 1 ) {
 		[glblAlerPane showWithMessage:@"Atencion" info:"Por favor ingresar el numero de eventos"];
 		//alert("Por favor ingresar numero de eventos");
 		return;
 	}
        if ( [freqPopu indexOfSelectedItem] == -1 ) {
        	[glblAlerPane showWithMessage:@"Atencion" info:"Por favor declare una calendarizacion"];
               // alert("Por favor declare una Calendarizacion");
                return;
        }
 	var acti = [actiListArra componentsJoinedByString:@"|"];
 	var titl = [titlText stringValue];
 	var evenFreq = [evenFreqText intValue];
 	if ( evenFreq < 1 ) {
 		evenFreq = 1;
 		[evenFreqText setIntValue:1];
 	}
 	var starPoin =0;
 	if(isNew){
 		var starPoin =0;
 		var dateStarStri = [[dateStarText stringValue] substringToIndex:10];
 	}else{
 		var quer= [CPString stringWithFormat:@"select start_date from %@.eventsPermanent where seriesId=%@ order by start_date desc limit 1",dataBase,[seriText intValue]];
 		var arraTemp = [self query:quer];
 		var arra = [[arraTemp objectAtIndex:0] valueList];
 		var dateStarStri = [arra[0] substringToIndex:10];
 		evenNumb = evenNumb+1;
 		//var starPoin =1;
 	}

 	var hourStarStri = [CPString stringWithFormat:@"%02d",[hourStarText intValue]];
 	var minuStarStri = [CPString stringWithFormat:@"%02d",[minuStarText intValue]];
 	//var seri = Math.floor(1000000*Math.random());
 	var seri = Date.now();
 	if ( updtNumb != -1 )
 		seri = updtNumb;
	var evenIden = [CPString stringWithFormat:@"%@%@%@%@",custStri,dateStarStri,hourStarStri,minuStarStri];
 	evenIden = [evenIden stringByReplacingOccurrencesOfString:@" " withString:@""];
 	evenIden = [evenIden stringByReplacingOccurrencesOfString:@"-" withString:@""];
 	evenIden = [evenIden stringByReplacingOccurrencesOfString:@"_" withString:@""];
 	evenIden = [evenIden stringByReplacingOccurrencesOfString:@":" withString:@""];
 	var dura = [duraText intValue];
 	var pric = [pricFCUText floatValue];
 	var freqType = [freqPopu titleOfSelectedItem];
 	var freqInde = [freqPopu indexOfSelectedItem];
 	var empl = [emplListArra componentsJoinedByString:@"|"];
 	emplListRepeArra = [emplListArra copy];
 	var equi = [equiListArra componentsJoinedByString:@"|"];
 	equiListRepeArra = [equiListArra copy];
 	var colo = [coloText stringValue];
 	if ( [colo length] != 7 )
 		colo = [self getRandomColor];  //colo = @"#79B";
 
 	if ( custStri == 0 || custLocaStri == 0 || evenNumb == 0 ) {
 		[glblAlerPane showWithMessage:@"Atencion" info:"Cliente no está definido o la locación no está definida o el número de eventos = 0. Por favor verifique los datos."];
 		//alert("Cliente no está definido o la locación no está definida o el número de eventos = 0. Por favor verifique los datos.");
 		return;
 	}
    var custOnly = [[custStri componentsSeparatedByString:@":"] objectAtIndex:0];
	dateStarFull = [CPString stringWithFormat:@"%@ %@:%@:00 -0600",dateStarStri,hourStarStri,minuStarStri];
 	var dateStar = [[CPDate alloc] initWithString:dateStarFull];
 	if ( [updtSubj isEqualToString:@"Serie"] && isNew ) {
         //var updtQuer = [CPString stringWithFormat:@"UPDATE %@.eventsPermanent SET seriesId=%d WHERE seriesId=%d",dataBase,seri*-1,seri];
         var updtQuer = [CPString stringWithFormat:@"DELETE FROM %@.eventsPermanent WHERE start_date >= '%@' AND seriesId=%d  ",dataBase,[dateStarFull substringToIndex:16],seri];
         [self query:updtQuer];
         //updtQuer = [CPString stringWithFormat:@"UPDATE %@.scheduleSeriesDefinitions SET serieId=%d WHERE serieId=%d",dataBase,seri*-1,seri];
         updtQuer = [CPString stringWithFormat:@"DELETE FROM %@.scheduleSeriesDefinitions WHERE id=%d ",dataBase,seri];
         [self query:updtQuer];
 	}

 	if ( [freqType isEqualToString:@"Una vez"] ) {
 		var seriId = [seriText stringValue]+"";
 		if(isNew){
			var quer = [CPString stringWithFormat:@"insert into %@.scheduleSeriesDefinitions (type,title,organization,location,activities,eventIdentifier,serieId,startDate,startHour,startMinute,duration,price,calendarization,frequency,events,personnel,equipments) values('0','%@','%@','%@','%@','%@','%d','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",dataBase,
		       	titl,custOnly,custLocaStri,acti,evenIden,seri,dateStarStri,hourStarStri,minuStarStri,dura,pric,freqInde,[evenFreqText stringValue],[evenNumbText stringValue],empl,equi];
        	var resuS = [self query:quer];
        	var coun = [resuS count];
			
			for ( var i=0; i<coun; i++ ) {
				var valuList = [resuS[i] valueList];
				var idS = valuList[0];
				seriId = idS;
			}

			coun = [emplListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
				var valuList = [emplArra[inde-1] valueList];
				var emplIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.seriePerson (idPerson,idSerie) values(%@,%@)",dataBase,emplIden,seriId];
				[self query:quer];
			}

			coun = [equiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
				var valuList = [equiArra[inde-1] valueList];
				var equiIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.serieEquipment (idEquipment,idSerie) values(%@,%@)",dataBase,equiIden,seriId];
			[self query:quer];
			}

			coun = [actiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
				var valuList = [actiArra[inde-1] valueList];
				var actIden = valuList[3];
				var quer = [CPString stringWithFormat:@"insert into %@.serieActivity (idActivity,idSerie) values(%@,%@)",dataBase,actIden,seriId];
				[self query:quer];
			}
        }

			var dateSegmEnd  = [[CPDate alloc] initWithTimeInterval:dura*60. sinceDate:dateStar];
            var resu = [dateStarFull compare : dateStar]
		    if (resu != 1){
		 
		    	var idEvent = "";
				var quer = [CPString stringWithFormat:@"insert into %@.eventsPermanent (start_date,end_date,text,source,calendar,personnel,customer,location,lng,lat,vehicle,color,seriesId,eventIdentifier,billing) values('%@','%@','%@','Orkin','%@','%@','%@','%@',%@,%@,'%@','%@',%d,'%@',%@)",dataBase,
					[[dateStar description] substringToIndex:16],[[dateSegmEnd description] substringToIndex:16],titl,acti,empl,custStri,custLocaStri,custLocaLngd,custLocaLati,equi,colo,seriId,evenIden,pric];
				var resuE = [self query:quer];
	        	var coun = [resuE count];
				
				for ( var j=0; j<coun; j++ ) {
					var valuList = [resuE[j] valueList];
					var idE = valuList[0];
					idEvent = idE;
				}
				inseCoun++;

				coun = [emplListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
					var valuList = [emplArra[inde-1] valueList];
					var emplIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventPerson (idPerson,idEvent) values(%@,%@)",dataBase,emplIden,idEvent];
					[self query:quer];
				}

				coun = [equiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
					var valuList = [equiArra[inde-1] valueList];
					var equiIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventEquipment (idEquipment,idEvent) values(%@,%@)",dataBase,equiIden,idEvent];
				[self query:quer];
				}

				coun = [actiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
					var valuList = [actiArra[inde-1] valueList];
					var actIden = valuList[3];
					var quer = [CPString stringWithFormat:@"insert into %@.eventActivity (idActivity,idEvent) values(%@,%@)",dataBase,actIden,idEvent];
				[self query:quer];
				}
		}
	}

 	else if ( [freqType isEqualToString:@"Diario"] ) {
 		var seriId = [seriText stringValue]+"";
 		if(isNew){
			var quer = [CPString stringWithFormat:@"insert into %@.scheduleSeriesDefinitions (type,title,organization,location,activities,eventIdentifier,serieId,startDate,startHour,startMinute,duration,price,calendarization,frequency,events,personnel,equipments) values('0','%@','%@','%@','%@','%@','%d','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",dataBase,
		       	titl,custOnly,custLocaStri,acti,evenIden,seri,dateStarStri,hourStarStri,minuStarStri,dura,pric,freqInde,[evenFreqText stringValue],[evenNumbText stringValue],empl,equi];
        	var resuS = [self query:quer];
        	var coun = [resuS count];
			
			for ( var i=0; i<coun; i++ ) {
				var valuList = [resuS[i] valueList];
				var idS = valuList[0];
				seriId = idS;
			}

			coun = [emplListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
				var valuList = [emplArra[inde-1] valueList];
				var emplIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.seriePerson (idPerson,idSerie) values(%@,%@)",dataBase,emplIden,seriId];
				[self query:quer];
			}

			coun = [equiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
				var valuList = [equiArra[inde-1] valueList];
				var equiIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.serieEquipment (idEquipment,idSerie) values(%@,%@)",dataBase,equiIden,seriId];
			[self query:quer];
			}

			coun = [actiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
				var valuList = [actiArra[inde-1] valueList];
				var actIden = valuList[3];
				var quer = [CPString stringWithFormat:@"insert into %@.serieActivity (idActivity,idSerie) values(%@,%@)",dataBase,actIden,seriId];
				[self query:quer];
			}

        }

		for ( var i=starPoin; i<evenNumb; i++ ) {
			var jump = i*evenFreq;
			var jumpSecs = jump*3600.*24;
			var dateSegmStar = [[CPDate alloc] initWithTimeInterval:jumpSecs sinceDate:dateStar];
			var dateSegmEnd  = [[CPDate alloc] initWithTimeInterval:jumpSecs+dura*60. sinceDate:dateStar];
            var resu = [dateStarFull compare : dateSegmStar]
		    if (resu != 1){
		    	var idEvent = "";
				var quer = [CPString stringWithFormat:@"insert into %@.eventsPermanent (start_date,end_date,text,source,calendar,personnel,customer,location,lng,lat,vehicle,color,seriesId,eventIdentifier,billing) values('%@','%@','%@','Orkin','%@','%@','%@','%@',%@,%@,'%@','%@',%d,'%@',%@)",dataBase,
						[[dateSegmStar description] substringToIndex:16],[[dateSegmEnd description] substringToIndex:16],titl,acti,empl,custStri,custLocaStri,custLocaLngd,custLocaLati,equi,colo,seriId,evenIden,pric];
				var resuE = [self query:quer];
	        	var coun = [resuE count];
				
				for ( var j=0; j<coun; j++ ) {
					var valuList = [resuE[j] valueList];
					var idE = valuList[0];
					idEvent = idE;
				}
				inseCoun++;

				coun = [emplListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
					var valuList = [emplArra[inde-1] valueList];
					var emplIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventPerson (idPerson,idEvent) values(%@,%@)",dataBase,emplIden,idEvent];
					[self query:quer];
				}

				coun = [equiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
					var valuList = [equiArra[inde-1] valueList];
					var equiIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventEquipment (idEquipment,idEvent) values(%@,%@)",dataBase,equiIden,idEvent];
				[self query:quer];
				}

				coun = [actiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
					var valuList = [actiArra[inde-1] valueList];
					var actIden = valuList[3];
					var quer = [CPString stringWithFormat:@"insert into %@.eventActivity (idActivity,idEvent) values(%@,%@)",dataBase,actIden,idEvent];
				[self query:quer];
				}
			}
		}
 	}
 	else if ( [freqType isEqualToString:@"Semanal"] ) {
 		var seriId = [seriText stringValue]+"";
 		if(isNew){
			var quer = [CPString stringWithFormat:@"insert into %@.scheduleSeriesDefinitions (type,title,organization,location,activities,eventIdentifier,serieId,startDate,startHour,startMinute,duration,price,calendarization,frequency,events,personnel,equipments) values('0','%@','%@','%@','%@','%@','%d','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",dataBase,
		       	titl,custOnly,custLocaStri,acti,evenIden,seri,dateStarStri,hourStarStri,minuStarStri,dura,pric,freqInde,[evenFreqText stringValue],[evenNumbText stringValue],empl,equi];
        	var resuS = [self query:quer];
        	var coun = [resuS count];
			
			for ( var i=0; i<coun; i++ ) {
				var valuList = [resuS[i] valueList];
				var idS = valuList[0];
				seriId = idS;
			}

			coun = [emplListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
				var valuList = [emplArra[inde-1] valueList];
				var emplIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.seriePerson (idPerson,idSerie) values(%@,%@)",dataBase,emplIden,seriId];
				[self query:quer];
			}

			coun = [equiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
				var valuList = [equiArra[inde-1] valueList];
				var equiIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.serieEquipment (idEquipment,idSerie) values(%@,%@)",dataBase,equiIden,seriId];
			[self query:quer];
			}

			coun = [actiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
				var valuList = [actiArra[inde-1] valueList];
				var actIden = valuList[3];
				var quer = [CPString stringWithFormat:@"insert into %@.serieActivity (idActivity,idSerie) values(%@,%@)",dataBase,actIden,seriId];
				[self query:quer];
			}


        }
		for ( var i=starPoin; i<evenNumb; i++ ) {
			var jump = i*evenFreq;
			var jumpSecs = jump*3600.*24*7;
			var dateSegmStar = [[CPDate alloc] initWithTimeInterval:jumpSecs sinceDate:dateStar];
			var dateSegmEnd  = [[CPDate alloc] initWithTimeInterval:jumpSecs+dura*60. sinceDate:dateStar];
            var resu = [dateStarFull compare : dateSegmStar]
		    if (resu != 1){
		    	var idEvent = "";
			   var quer = [CPString stringWithFormat:@"insert into %@.eventsPermanent (start_date,end_date,text,source,calendar,personnel,customer,location,lng,lat,vehicle,color,seriesId,eventIdentifier,billing) values('%@','%@','%@','Orkin','%@','%@','%@','%@',%@,%@,'%@','%@',%d,'%@',%@)",dataBase,
						[[dateSegmStar description] substringToIndex:16],[[dateSegmEnd description] substringToIndex:16],titl,acti,empl,custStri,custLocaStri,custLocaLngd,custLocaLati,equi,colo,seriId,evenIden,pric];
			   	var resuE = [self query:quer];
	        	var coun = [resuE count];
				
				for ( var j=0; j<coun; j++ ) {
					var valuList = [resuE[j] valueList];
					var idE = valuList[0];
					idEvent = idE;
				}
			   inseCoun++;

			   	coun = [emplListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
					var valuList = [emplArra[inde-1] valueList];
					var emplIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventPerson (idPerson,idEvent) values(%@,%@)",dataBase,emplIden,idEvent];
					[self query:quer];
				}

				coun = [equiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
					var valuList = [equiArra[inde-1] valueList];
					var equiIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventEquipment (idEquipment,idEvent) values(%@,%@)",dataBase,equiIden,idEvent];
				[self query:quer];
				}

				coun = [actiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
					var valuList = [actiArra[inde-1] valueList];
					var actIden = valuList[3];
					var quer = [CPString stringWithFormat:@"insert into %@.eventActivity (idActivity,idEvent) values(%@,%@)",dataBase,actIden,idEvent];
				[self query:quer];
				}
		    }
		}
 	}
 	else if ( [freqType isEqualToString:@"Mensual"] ) {
		var seriId = [seriText stringValue]+"";
 		if(isNew){
			var quer = [CPString stringWithFormat:@"insert into %@.scheduleSeriesDefinitions (type,title,organization,location,activities,eventIdentifier,serieId,startDate,startHour,startMinute,duration,price,calendarization,frequency,events,personnel,equipments) values('0','%@','%@','%@','%@','%@','%d','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",dataBase,
		       	titl,custOnly,custLocaStri,acti,evenIden,seri,dateStarStri,hourStarStri,minuStarStri,dura,pric,freqInde,[evenFreqText stringValue],[evenNumbText stringValue],empl,equi];
        	var resuS = [self query:quer];
        	var coun = [resuS count];
			
			for ( var i=0; i<coun; i++ ) {
				var valuList = [resuS[i] valueList];
				var idS = valuList[0];
				seriId = idS;
			}

			coun = [emplListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
				var valuList = [emplArra[inde-1] valueList];
				var emplIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.seriePerson (idPerson,idSerie) values(%@,%@)",dataBase,emplIden,seriId];
				[self query:quer];
			}

			coun = [equiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
				var valuList = [equiArra[inde-1] valueList];
				var equiIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.serieEquipment (idEquipment,idSerie) values(%@,%@)",dataBase,equiIden,seriId];
			[self query:quer];
			}

			coun = [actiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
				var valuList = [actiArra[inde-1] valueList];
				var actIden = valuList[3];
				var quer = [CPString stringWithFormat:@"insert into %@.serieActivity (idActivity,idSerie) values(%@,%@)",dataBase,actIden,seriId];
				[self query:quer];
			}

        }
 		var dateStarDesc = [dateStar description];
 		var rang = CPMakeRange(0,4);
 		var year = [[dateStarDesc substringWithRange:rang] intValue];
 		rang = CPMakeRange(5,2);
 		var mont = [[dateStarDesc substringWithRange:rang] intValue];
 		rang = CPMakeRange(8,2);
 		var day = [[dateStarDesc substringWithRange:rang] intValue];
 		rang = CPMakeRange(11,8);
 		var rest = [dateStarDesc substringWithRange:rang];
		for ( var i=starPoin; i<evenNumb; i++ ) {
			var montNew = mont + i*evenFreq;
			var yearNumb = 0;
			if ( montNew > 12 ) {
				yearNumb = Math.floor(montNew/12.);
				montNew -= yearNumb*12;
			}
			var dateSegmStarDesc = [CPString stringWithFormat:@"%04d-%02d-%02d %@ -0600",year+yearNumb,montNew,day,rest];
			var dateSegmStar = [[CPDate alloc] initWithString:dateSegmStarDesc];
			var dateSegmEnd  = [[CPDate alloc] initWithTimeInterval:dura*60. sinceDate:dateSegmStar];
			var resu = [dateStarFull compare : dateSegmStar]
		    if (resu != 1){
		    	var idEvent = "";
				var quer = [CPString stringWithFormat:@"insert into %@.eventsPermanent (start_date,end_date,text,source,calendar,personnel,customer,location,lng,lat,vehicle,color,seriesId,eventIdentifier,billing) values('%@','%@','%@','Orkin','%@','%@','%@','%@',%@,%@,'%@','%@',%d,'%@',%@)",dataBase,
						[[dateSegmStar description] substringToIndex:16],[[dateSegmEnd description] substringToIndex:16],titl,acti,empl,custStri,custLocaStri,custLocaLngd,custLocaLati,equi,colo,seriId,evenIden,pric];
				var resuE = [self query:quer];
	        	var coun = [resuE count];
				
				for ( var j=0; j<coun; j++ ) {
					var valuList = [resuE[j] valueList];
					var idE = valuList[0];
					idEvent = idE;
				}
				inseCoun++;

				coun = [emplListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
					var valuList = [emplArra[inde-1] valueList];
					var emplIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventPerson (idPerson,idEvent) values(%@,%@)",dataBase,emplIden,idEvent];
					[self query:quer];
				}

				coun = [equiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
					var valuList = [equiArra[inde-1] valueList];
					var equiIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventEquipment (idEquipment,idEvent) values(%@,%@)",dataBase,equiIden,idEvent];
				[self query:quer];
				}

				coun = [actiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
					var valuList = [actiArra[inde-1] valueList];
					var actIden = valuList[3];
					var quer = [CPString stringWithFormat:@"insert into %@.eventActivity (idActivity,idEvent) values(%@,%@)",dataBase,actIden,idEvent];
				[self query:quer];
				}
			}
		}
 	}
 
 	/*
 	else if ( [freqType isEqualToString:@"Cada 7 dias"] ) {
		for ( var i=0; i<evenNumb; i++ ) {
			var dateSegmStar = [[CPDate alloc] initWithTimeInterval:i*7*24*3600. sinceDate:dateStar];
			var dateSegmEnd  = [[CPDate alloc] initWithTimeInterval:i*7*24*3600.+dura*60. sinceDate:dateStar];
			var quer = [CPString stringWithFormat:@"insert into test.eventsPermanent (start_date,end_date,text,source,calendar,personnel,customer,location,lng,lat,vehicle,color,seriesId,eventIdentifier,billing) values('%@','%@','%@','Orkin','|%@|','|%@|','|%@|','|%@|',%@,%@,'|%@|','%@',%d,'%@',%@)",
						[[dateSegmStar description] substringToIndex:16],[[dateSegmEnd description] substringToIndex:16],titl,acti,empl,custStri,custLocaStri,custLocaLngd,custLocaLati,equi,colo,seri,evenIden,pric];
			[self query:quer];
		}
 	}
 	else if ( [freqType isEqualToString:@"Cada 14 dias"] ) {
		for ( var i=0; i<evenNumb; i++ ) {
			var dateSegmStar = [[CPDate alloc] initWithTimeInterval:i*14*24*3600. sinceDate:dateStar];
			var dateSegmEnd  = [[CPDate alloc] initWithTimeInterval:i*14*24*3600.+dura*60. sinceDate:dateStar];
			var quer = [CPString stringWithFormat:@"insert into test.eventsPermanent (start_date,end_date,text,source,calendar,personnel,customer,location,lng,lat,vehicle,color,seriesId,eventIdentifier,billing) values('%@','%@','%@','Orkin','|%@|','|%@|','|%@|','|%@|',%@,%@,'|%@|','%@',%d,'%@',%@)",
						[[dateSegmStar description] substringToIndex:16],[[dateSegmEnd description] substringToIndex:16],titl,acti,empl,custStri,custLocaStri,custLocaLngd,custLocaLati,equi,colo,seri,evenIden,pric];
			[self query:quer];
		}
 	}
 	else if ( [freqType isEqualToString:@"Cada 21 dias"] ) {
		for ( var i=0; i<evenNumb; i++ ) {
			var dateSegmStar = [[CPDate alloc] initWithTimeInterval:i*21*24*3600. sinceDate:dateStar];
			var dateSegmEnd  = [[CPDate alloc] initWithTimeInterval:i*21*24*3600.+dura*60. sinceDate:dateStar];
			var quer = [CPString stringWithFormat:@"insert into test.eventsPermanent (start_date,end_date,text,source,calendar,personnel,customer,location,lng,lat,vehicle,color,seriesId,eventIdentifier,billing) values('%@','%@','%@','Orkin','|%@|','|%@|','|%@|','|%@|',%@,%@,'|%@|','%@',%d,'%@',%@)",
						[[dateSegmStar description] substringToIndex:16],[[dateSegmEnd description] substringToIndex:16],titl,acti,empl,custStri,custLocaStri,custLocaLngd,custLocaLati,equi,colo,seri,evenIden,pric];
			[self query:quer];
		}
 	}
 	else if ( [freqType isEqualToString:@"Cada 28 dias"] ) {
		for ( var i=0; i<evenNumb; i++ ) {
			var dateSegmStar = [[CPDate alloc] initWithTimeInterval:i*28*24*3600. sinceDate:dateStar];
			var dateSegmEnd  = [[CPDate alloc] initWithTimeInterval:i*28*24*3600.+dura*60. sinceDate:dateStar];
			var quer = [CPString stringWithFormat:@"insert into test.eventsPermanent (start_date,end_date,text,source,calendar,personnel,customer,location,lng,lat,vehicle,color,seriesId,eventIdentifier,billing) values('%@','%@','%@','Orkin','|%@|','|%@|','|%@|','|%@|',%@,%@,'|%@|','%@',%d,'%@',%@)",
						[[dateSegmStar description] substringToIndex:16],[[dateSegmEnd description] substringToIndex:16],titl,acti,empl,custStri,custLocaStri,custLocaLngd,custLocaLati,equi,colo,seri,evenIden,pric];
			[self query:quer];
		}
 	}
 	*/
 	
	else {

		var seriId = [seriText stringValue]+"";
 		if(isNew){
			var quer = [CPString stringWithFormat:@"insert into %@.scheduleSeriesDefinitions (type,title,organization,location,activities,eventIdentifier,serieId,startDate,startHour,startMinute,duration,price,calendarization,frequency,events,personnel,equipments) values('0','%@','%@','%@','%@','%@','%d','%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')",dataBase,
		       	titl,custOnly,custLocaStri,acti,evenIden,seri,dateStarStri,hourStarStri,minuStarStri,dura,pric,freqInde,[evenFreqText stringValue],[evenNumbText stringValue],empl,equi];
        	var resuS = [self query:quer];
        	var coun = [resuS count];
			
			for ( var i=0; i<coun; i++ ) {
				var valuList = [resuS[i] valueList];
				var idS = valuList[0];
				seriId = idS;
			}

			coun = [emplListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
				var valuList = [emplArra[inde-1] valueList];
				var emplIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.seriePerson (idPerson,idSerie) values(%@,%@)",dataBase,emplIden,seriId];
				[self query:quer];
			}

			coun = [equiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
				var valuList = [equiArra[inde-1] valueList];
				var equiIden = valuList[0];
				var quer = [CPString stringWithFormat:@"insert into %@.serieEquipment (idEquipment,idSerie) values(%@,%@)",dataBase,equiIden,seriId];
			[self query:quer];
			}

			coun = [actiListArra count];
			for ( var j=0; j<coun; j++ ) {
				var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
				var valuList = [actiArra[inde-1] valueList];
				var actIden = valuList[3];
				var quer = [CPString stringWithFormat:@"insert into %@.serieActivity (idActivity,idSerie) values(%@,%@)",dataBase,actIden,seriId];
				[self query:quer];
			}

        }

		var freqArra = [freqType componentsSeparatedByString:@" "];
		
		var freq = -1;
		if ( [freqArra[0] isEqualToString:@"Primer"] )
			freq = 1;
		else if ( [freqArra[0] isEqualToString:@"Segundo"] )
			freq = 2;
		else if ( [freqArra[0] isEqualToString:@"Tercer"] )
			freq = 3;
		else if ( [freqArra[0] isEqualToString:@"Cuarto"] )
			freq = 4;
		//add 2017-03-15
		else if ( [freqArra[0] isEqualToString:@"Quinto"] )
			freq = 5;
			//end

		var dow = -1;
		if ( [freqArra[1] isEqualToString:@"domingo"] )
			dow = 0;
		else if ( [freqArra[1] isEqualToString:@"lunes"] )
			dow = 1;
		else if ( [freqArra[1] isEqualToString:@"martes"] )
			dow = 2;
		else if ( [freqArra[1] isEqualToString:@"miércoles"] )
			dow = 3;
		else if ( [freqArra[1] isEqualToString:@"jueves"] )
			dow = 4;
		else if ( [freqArra[1] isEqualToString:@"viernes"] )
			dow = 5;
		else if ( [freqArra[1] isEqualToString:@"sábado"] )
			dow = 6;
			
		if ( freq < 0 || dow < 0 ) {
			alert("Aborting");
			return;
		}

 		var dateStarDesc = [dateStar description];
 		var rang = CPMakeRange(0,4);
 		var year = [[dateStarDesc substringWithRange:rang] intValue];
 		rang = CPMakeRange(5,2);
 		var mont = [[dateStarDesc substringWithRange:rang] intValue];
 		rang = CPMakeRange(8,2);
 		var day = [[dateStarDesc substringWithRange:rang] intValue];
 		rang = CPMakeRange(11,8);
 		var rest = [dateStarDesc substringWithRange:rang];
 		//return;
		for ( var i=starPoin; i<evenNumb; i++ ) {

			var montNew = mont + i *evenFreq;
			var yearNumb = 0;
			if ( montNew > 12 ) {
				yearNumb = Math.floor(montNew/12.);
				montNew -= yearNumb*12;
			}
			var day = 1;
			var dateSegmStar;
			var dowLoca = 0;
			var freqLoca = 0;
			do {
				var dateSegmStarDesc = [CPString stringWithFormat:@"%04d-%02d-%02d %@ -0600",year+yearNumb,montNew,day,rest];
				dateSegmStar = [[CPDate alloc] initWithString:dateSegmStarDesc];
				dowLoca = dateSegmStar.getDay();
				if ( dowLoca == dow )
					freqLoca++;
				//alert("dateSegmStarDesc="+dateSegmStarDesc+"  dow="+dow+"  dowLoca="+dowLoca+"  day="+day+"  freq="+freq+"  freqLoca="+freqLoca);
				day++;
			} while ( freqLoca != freq );
			var dateSegmEnd  = [[CPDate alloc] initWithTimeInterval:dura*60. sinceDate:dateSegmStar];
			var resu = [dateStarFull compare : dateSegmStar]
		    if (resu != 1){
		    	var idEvent = "";
				var quer = [CPString stringWithFormat:@"insert into %@.eventsPermanent (start_date,end_date,text,source,calendar,personnel,customer,location,lng,lat,vehicle,color,seriesId,eventIdentifier,billing) values('%@','%@','%@','Orkin','%@','%@','%@','%@',%@,%@,'%@','%@',%d,'%@',%@)",dataBase,
						[[dateSegmStar description] substringToIndex:16],[[dateSegmEnd description] substringToIndex:16],titl,acti,empl,custStri,custLocaStri,custLocaLngd,custLocaLati,equi,colo,seriId,evenIden,pric];
				var resuE = [self query:quer];
	        	var coun = [resuE count];
				
				for ( var j=0; j<coun; j++ ) {
					var valuList = [resuE[j] valueList];
					var idE = valuList[0];
					idEvent = idE;
				}
				inseCoun++;

				coun = [emplListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
					var valuList = [emplArra[inde-1] valueList];
					var emplIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventPerson (idPerson,idEvent) values(%@,%@)",dataBase,emplIden,idEvent];
					[self query:quer];
				}

				coun = [equiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
					var valuList = [equiArra[inde-1] valueList];
					var equiIden = valuList[0];
					var quer = [CPString stringWithFormat:@"insert into %@.eventEquipment (idEquipment,idEvent) values(%@,%@)",dataBase,equiIden,idEvent];
				[self query:quer];
				}

				coun = [actiListArra count];
				for ( var j=0; j<coun; j++ ) {
					var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
					var valuList = [actiArra[inde-1] valueList];
					var actIden = valuList[3];
					var quer = [CPString stringWithFormat:@"insert into %@.eventActivity (idActivity,idEvent) values(%@,%@)",dataBase,actIden,idEvent];
				[self query:quer];
				}
			}
		}
 	}

 	if ( [updtSubj isEqualToString:@"Serie"] && isNew ) {
         //var updtQuer = [CPString stringWithFormat:@"UPDATE %@.eventsPermanent SET seriesId=%d WHERE seriesId=%d",dataBase,seri*-1,seri];
         
 		 var updtQuer = [CPString stringWithFormat:@"Select serieComm from %@.eventsPermanent WHERE  seriesId=%d Limit 1 ",dataBase,seri];
         var commentTemp = [self query:updtQuer];

         updtQuer = [CPString stringWithFormat:@"UPDATE %@.eventsPermanent set seriesId=%d WHERE  seriesId=%d  ",dataBase,seriId,seri];
         [self query:updtQuer];


        var coun = [commentTemp count];
		if(coun > 0){
			var commentSeri = "";
			for ( var i=0; i<coun; i++ ) {
				var valuList = [commentTemp[i] valueList];
				var com = valuList[0];
				commentSeri = com;
			}

         updtQuer = [CPString stringWithFormat:@"UPDATE %@.eventsPermanent set serieComm='%@' WHERE seriesId=%d  ",dataBase,commentSeri,seriId];
         [self query:updtQuer];
     	}
         //updtQuer = [CPString stringWithFormat:@"UPDATE %@.scheduleSeriesDefinitions SET serieId=%d WHERE serieId=%d",dataBase,seri*-1,seri];
 	}
 
 	[seriText setIntValue:seriId];
 	var acci = @"ingresaron";
 	if ( [updtSubj isEqualToString:@"Serie"] ) {
 		[self scheduleEventCancelModify:nil];
 		acci = "actualizaron";
 	} 
 	[seriText setIntValue:seriId];
 	[self scheduleSeriesEvents:nil];
 	[glblAlerPane showWithMessage:@"Operacion exitosa" info:[CPString stringWithFormat:@"Se %@  ( %d ) eventos.",acci,inseCoun]];
 	if(!isNew){
 		[self scheduleEventCancelModify:nil];
 	}
 	
 	evenOpti = 2;
	[evenTabl reloadData];
 	//alert([CPString stringWithFormat:@"Se %@  ( %d ) eventos.",acci,inseCoun]);
}



- (void) scheduleEventModify:(id)seder {
	 isNew = true;
	 if ( [updtSubj isEqualToString:@"Serie"] ) {
         [self scheduleEventInsert:nil];
     }
     else {
     	 [self scheduleOnlyEventUpdate:nil];
     }
}


- (void) scheduleOnlyEventUpdate:(id)sender {

	

 	var acti = [actiListArra componentsJoinedByString:@"|"];
 	if ( [actiListArra count] > 0)
 	     acti = "|" + acti;
	var empl = [emplListArra componentsJoinedByString:@"|"];
 	if ( [emplListArra count] > 0)
 	     empl = "|" + empl;	
	var equi = [equiListArra componentsJoinedByString:@"|"];
 	if ( [equiListArra count] > 0)
 	     equi = "|" + equi;

    var dayS = [dateStarText stringValue];
    var houS = [hourStarText stringValue];
    var minS = [minuStarText stringValue];
    var ddur = [duraText stringValue];
    var dtSt = [self dateConvertion:dayS hours:houS minutes:minS offSet:@"0"];
    var dtEn = [self dateConvertion:dayS hours:houS minutes:minS offSet:ddur];
    var eCmm = [sltdEvenDefi evntComm];
    var sCmm = [sltdEvenDefi seriComm];


    var quer = [CPString stringWithFormat:@"UPDATE %@.%@ SET calendar='%@|',personnel='%@|',vehicle='%@|',start_date='%@',end_date='%@',eventComm='%@',serieComm='%@' WHERE id= %@",
               dataBase,appCont.useTabl,acti,empl,equi,[[dtSt description] substringToIndex:16],[[dtEn description] substringToIndex:16],eCmm,sCmm,[sltdEvenDefi recoId]];
//alert("query " + quer);
//    var quer = [CPString stringWithFormat:@"UPDATE %@.eventsPermanent SET calendar='%@',personnel='%@',vehicle='%@' WHERE id='%@'",dataBase,acti,empl,equi,[sltdEvenDefi recoId]];
    [self query:quer];
    var quer = [CPString stringWithFormat:@"UPDATE %@.eventsPermanent SET calendar='%@|',personnel='%@|',vehicle='%@|',start_date='%@',end_date='%@' WHERE id= %@",
               dataBase,acti,empl,equi,[[dtSt description] substringToIndex:16],[[dtEn description] substringToIndex:16],[sltdEvenDefi recoId]];
    [self query:quer];


    var quer = [CPString stringWithFormat:@"delete from %@.eventPerson where idEvent = %@",
               dataBase,[sltdEvenDefi recoId]];
    [self query:quer];

    var coun = [emplListArra count];
	for ( var j=0; j<coun; j++ ) {
			var inde = [emplPopu indexOfItemWithTitle:emplListArra[j]];  
			var valuList = [emplArra[inde-1] valueList];
			var emplIden = valuList[0];
			var quer = [CPString stringWithFormat:@"insert into %@.eventPerson (idPerson,idEvent) values(%@,%@)",dataBase,emplIden,[sltdEvenDefi recoId]];
			[self query:quer];
	}

    var quer = [CPString stringWithFormat:@"delete from %@.eventEquipment where idEvent = %@",
               dataBase,[sltdEvenDefi recoId]];
    [self query:quer];

	coun = [equiListArra count];
	for ( var j=0; j<coun; j++ ) {
			var inde = [equiPopu indexOfItemWithTitle:equiListArra[j]];  
			var valuList = [equiArra[inde-1] valueList];
			var equiIden = valuList[0];
			var quer = [CPString stringWithFormat:@"insert into %@.eventEquipment (idEquipment,idEvent) values(%@,%@)",dataBase,equiIden,[sltdEvenDefi recoId]];
			[self query:quer];
	}

    var quer = [CPString stringWithFormat:@"delete from %@.eventActivity where idEvent = %@",
               dataBase,[sltdEvenDefi recoId]];
    [self query:quer];

	coun = [actiListArra count];
	for ( var j=0; j<coun; j++ ) {
			var inde = [actiPopu indexOfItemWithTitle:actiListArra[j]];  
			var valuList = [actiArra[inde-1] valueList];
			var actIden = valuList[3];
			var quer = [CPString stringWithFormat:@"insert into %@.eventActivity (idActivity,idEvent) values(%@,%@)",dataBase,actIden,[sltdEvenDefi recoId]];
			[self query:quer];
	}

    [self scheduleIdentityEvents:nil];
    [self scheduleEventCancelModify:nil];
    
 }



- (void) scheduleEventBillingNotes:(id)sender {
	var inde = [evenTabl selectedRow];
	if ( inde < 0 ) {
		[glblAlerPane showWithMessage:@"Atencion" info:"Por favor seleccionar evento"];
		//alert("Por favor seleccionar evento.");
		return;
	}
	var valuList = [evenArra[inde] valueList];
	var evenIden = valuList[0];

	if ( evenNotePane ) {
		[evenNotePane orderFront:self];
	}
	else {
		var x = 300;
		var y = 200;
		var fram = CGRectMake(x,y, 460,260);
		evenNotePane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
		[evenNotePane setFloatingPanel:YES]; 
		[evenNotePane setDelegate:self];
		[evenNotePane orderFront:self];
		[evenNotePane setTitle:@"Comentarios"];

		var view = [evenNotePane contentView];
		[view setBackgroundColor:coloDefaBrig];
		[self addBanners:view heightBlue:2. heightOrange:4.];

		var horiPos1 = 10;
		var horiPos2 = horiPos1 + 100;
		var vertPosi = 20;
		var vertIncr = 25;

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

		evenIdenText = [self addTextField:@"" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:60 TFHeight:30 VView:view Editable:YES];
		[evenIdenText setTarget:self];
		[evenIdenText setAction:@selector(someTableSelection:)];
		[evenIdenText setTextColor:[CPColor grayColor]];

		vertPosi += vertIncr;

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

		evenBillText = [self addTextField:@"" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:300 TFHeight:vertIncr VView:view Editable:YES];

		vertPosi += vertIncr;

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

		evenNoteText = [self addTextField:@"" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:300 TFHeight:4*vertIncr VView:view Editable:YES];
		[evenNoteText setLineBreakMode:CPLineBreakByWordWrapping];

		vertPosi += 4.5*vertIncr;
	
		var butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2,vertPosi, 80,24)];
		[butt setTitle:"Actualizar"];
		[butt setTarget:self];
		[butt setAction:@selector(scheduleEventBillingNotesUpdate:)];                
		[view addSubview:butt];

		butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2+80,vertPosi, 80,24)];
		[butt setTitle:"Eliminar"];
		[butt setTarget:self];
		[butt setAction:@selector(scheduleEventBillingNotesDelete:)];                
		[view addSubview:butt];

		butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2+160,vertPosi, 80,24)];
		[butt setTitle:"Limpiar"];
		[butt setTarget:self];
		[butt setAction:@selector(scheduleEventBillingNotesClearFields:)];                
		[view addSubview:butt];
	}
	/* 2017-03-01
	[evenIdenText setStringValue:evenIden];
	var quer = [CPString stringWithFormat:@"select billing,notes from test.eventsPermanent where id=%@",evenIden];
	var arra = [self query:quer];
	if ( [arra count] > 0 ) {
		var valuList = [arra[0] valueList];
		[evenBillText setStringValue:[valuList objectAtIndex:0]];
		[evenNoteText setStringValue:[valuList objectAtIndex:1]];
	}*/
}



- (void) scheduleEventBillingNotesClearFields:(id)sender {
	[evenBillText setStringValue:@""];
	[evenNoteText setStringValue:@""];
}



- (void) scheduleEventBillingNotesDelete:(id)sender {
	var inde = [evenTabl selectedRow];
	if ( inde < 0 ) {
		[glblAlerPane showWithMessage:@"Atencion" info:"Por favor seleccionar evento"];
		//alert("Por favor seleccionar evento.");
		return;
	}
	
	
	var valuList = [evenArra[inde] valueList];
	var evenIden = valuList[0];
	var quer = [CPString stringWithFormat:@"delete from %@.eventsPermanent where id=%@",dataBase,evenIden];
	[self query:quer];
	quer = [CPString stringWithFormat:@"delete from %@.%@ where id=%@",dataBase,appCont.useTabl,evenIden];
	[self query:quer];
}



- (void) scheduleEventBillingNotesUpdate:(id)sender {
	var inde = [evenTabl selectedRow];
	if ( inde < 0 ) {
		[glblAlerPane showWithMessage:@"Atencion" info:"Por favor seleccionar evento"];
		//alert("Por favor seleccionar evento.");
		return;
	}
	var valuList = [evenArra[inde] valueList];
	var evenIden = valuList[0];
	var evenBill = [evenBillText stringValue];
	var evenNote = [evenNoteText stringValue];
	var quer = [CPString stringWithFormat:@"update %@.eventsPermanent set billing='%@', notes='%@' where id=%@",dataBase,evenBill,evenNote,evenIden];
	[self query:quer];
}



- (void) scheduleEventRoutes:(id)sender {
	if ( ! mapCont ) {
		[glblAlerPane showWithMessage:@"Atencion" info:"Por favor active el mapa"];
		//alert("Por favor active el mapa.");
		return;
	}
	var coorLngd = [coorLngdText stringValue];
	var coorLati = [coorLatiText stringValue];
	if ( [coorLngd length] < 2 )
		coorLngd = @"-84.035";
	if ( [coorLati length] < 2 )
		coorLati = @"9.906";
	coorLngd = [coorLngd floatValue];
	coorLati = [coorLati floatValue];
	[coorLngdText setFloatValue:coorLngd];
	[coorLatiText setFloatValue:coorLati];

	[mapCont radiusCenteredAtPoint:0 :0 erase:YES draw:NO radius:0. color:[CPColor greenColor]];

	var dateNow = [dateStarText stringValue];

	var equiCoun = [equiArra count];
	for ( var e=0; e<equiCoun; e++ ) {
		var valuList = [equiArra[e] valueList];
		var equiIden = valuList[0];
		var equiType = [valuList[4] intValue];
		if ( equiType != 0 )
			continue;

		var red  = Math.random();
		var gree = Math.random();
		var blue = Math.random();
		var colo = [CPColor colorWithCalibratedRed:red green:gree blue:blue alpha:1.];
		var coloHexa = [colo hexString];
		//console.log(coloHexa);

		// (SUBSTRING(t1.start_date,0,11)

		var quer = [CPString stringWithFormat:@"select lng,lat,start_date,end_date,location from %@.eventsPermanent where start_date like '%@%%' and vehicle like '%%:%@|%%' order by start_date",dataBase,dateNow,equiIden];
		var equiEvenArra = [self query:quer];
		var equiEvenCoun = [equiEvenArra count];

		var mapLocaArra = [[CPArray alloc] init];

		var mapLoca = [[MKLocation alloc] initWithLatitude:coorLati andLongitude:coorLngd];
		[mapLocaArra addObject:mapLoca];
		for ( var i=0; i<equiEvenCoun; i++ ) {
			var valuList2 = [equiEvenArra[i] valueList];
			var lngd = [valuList2[0] floatValue];
			var lati = [valuList2[1] floatValue];
			if ( !lngd || lngd == 0. || lngd == "NA" )
				lngd = coorLngd;
			if ( !lati || lati == 0. || lati == "NA" )
				lati = coorLati;
			mapLoca = [[MKLocation alloc] initWithLatitude:lati andLongitude:lngd];
			[mapLocaArra addObject:mapLoca];
		}
		[mapCont locationArrayDraw:mapLocaArra color:coloHexa];

		blue = e/equiCoun;
		colo = [CPColor colorWithCalibratedRed:red green:gree blue:blue alpha:1.];

		[mapCont radiusCenteredAtPoint:coorLngd :coorLati erase:NO draw:YES radius:0.0004 color:[CPColor blueColor]];
		for ( var i=0; i<equiEvenCoun; i++ ) {
			var valuList2 = [equiEvenArra[i] valueList];
			var lngd = [valuList2[0] floatValue];
			var lati = [valuList2[1] floatValue];
			if ( !lngd || lngd == 0. || lngd == "NA" )
				lngd = coorLngd;
			if ( !lati || lati == 0. || lati == "NA" )
				lati = coorLati;
			[mapCont radiusCenteredAtPoint:lngd :lati erase:NO draw:YES radius:0.0004 color:colo];
		}

		var lngdPrev = coorLngd;
		var latiPrev = coorLati;
		var dateStarPrev = 0;
		var dateFiniPrev = 0;
		var locaPrev = @"";
		for ( var i=0; i<equiEvenCoun; i++ ) {
			var valuList2 = [equiEvenArra[i] valueList];
			var lngd = [valuList2[0] floatValue];
			var lati = [valuList2[1] floatValue];
			var loca = valuList2[4];
			if ( !lngd || lngd == 0. || lngd == "NA" )
				lngd = coorLngd;
			if ( !lati || lati == 0. || lati == "NA" )
				lati = coorLati;
			var dateStarStri = [CPString stringWithFormat:@"%@:00 -0600",valuList2[2]];
			var dateFiniStri = [CPString stringWithFormat:@"%@:00 -0600",valuList2[3]];
			if ( i == 0 ) {
				lngdPrev = lngd;
				latiPrev = lati;
				dateStarPrev = [[CPDate alloc] initWithString:dateStarStri];
				dateFiniPrev = [[CPDate alloc] initWithString:dateFiniStri];
			}
			else {
				var lngdDiff = lngd - lngdPrev;
				var latiDiff = lati - latiPrev;
				var dist = Math.sqrt(lngdDiff*lngdDiff+latiDiff*latiDiff)*111.45*1.35;
				var timeInte = dist/30. * 3600.;
				var dateStarPred = [[CPDate alloc] initWithTimeInterval:timeInte sinceDate:dateFiniPrev];
				var dateStar = [[CPDate alloc] initWithString:dateStarStri];
				var dateFini = [[CPDate alloc] initWithString:dateFiniStri];
				var timeComp = [dateStar timeIntervalSinceDate:dateStarPred] / 60.;
				var resu = @"OK";
				if ( timeComp < 0. )
					resu = @"ERROR";

				alert("Equipment: "+equiIden+"\nSegment: "+i+"\nFrom: "+locaPrev+"\nDatePrevious: "+[dateFiniPrev description]+"\nTo: "+loca+"\nDistance= "+dist+"\nTimeInterval= "+timeInte+"\nDateStartPred: "+[dateStarPred description]+"\nDateStart: "+[dateStar description]+"\nTimeCompleted= "+timeComp+"\nResult: "+resu);

				lngdPrev = lngd;
				latiPrev = lati;
				dateStarPrev = dateStar;
				dateFiniPrev = dateFini;
				locaPrev = loca;
			}
		}

	}

}



- (void) scheduleFrequency:(id)sender {
	[evenNumbText setIntValue:0];
}


- (void) scheduleInconsistencies:(id)sender {
	[self scheduleInconsistenciesWithMode:0];
}



- (void) scheduleInconsistenciesForLocation:(id)sender {
	[self scheduleInconsistenciesWithMode:1];
}



- (void) scheduleInconsistenciesWithMode:(int)mode {
	var quer = @"truncate " + dataBase + ".scheduleInconsistencies";
	[self query:quer];
	
	var locaInde = 0;
	if ( mode == 1) {
		var inde = [custLocaPopu indexOfSelectedItem];
		inde--;
		var titl = [custLocaPopu itemTitleAtIndex:0];
		if ( inde == 'undefined' || inde<0 ) {
			[glblAlerPane showWithMessage:@"Atencion" info:"Por favor seleccione una locacion"];
			//alert("Por favor seleccione una locación");
			return;
		}
		var loca = [custLocaPopu titleOfSelectedItem];
		var locaCmpn = [loca componentsSeparatedByString:@":"];
		locaInde = [locaCmpn[1] intValue];
		//alert("mode="+mode+"   custLocaPopu="+[custLocaPopu numberOfItems]+"   titl= *"+titl+"*   inde="+inde+"   loca= *"+loca+"*   locaInde="+locaInde);
	}

	var cond = @"";

	if ( [incoEvenOverChec state] ) {
		if ( mode == 1)
			cond = [CPString stringWithFormat:@"and (t1.location like '%%:%d|' or t2.location like '%%:%d|')",locaInde,locaInde];
		quer = [CPString stringWithFormat:@"insert into %@.scheduleInconsistencies (id1,id2,description,severity) select t1.id,t2.id,concat('Traslape ',t1.location,' y ',t2.location),1 from %@.eventsPermanent t1, %@.eventsPermanent t2 where t1.vehicle=t2.vehicle and t1.personnel=t2.personnel and t1.start_date<=t2.start_date and t1.end_date>=t2.start_date and t1.seriesId!=t2.seriesId %@",dataBase,dataBase,dataBase,cond];
		[self query:quer];
	}

	if ( [incoVehiOverChec state] ) {
		if ( mode == 1)
			cond = [CPString stringWithFormat:@"and (t1.location like '%%:%d|' or t2.location like '%%:%d|')",locaInde,locaInde];
		quer = [CPString stringWithFormat:@"insert into %@.scheduleInconsistencies (id1,id2,description,severity) select t1.id,t2.id,concat('Traslape ',t1.vehicle),2  from %@.eventsPermanent t1, %@.eventsPermanent t2 where t1.vehicle=t2.vehicle and UNIX_TIMESTAMP(t1.start_date)<=UNIX_TIMESTAMP(t2.end_date) and UNIX_TIMESTAMP(t1.end_date)>=UNIX_TIMESTAMP(t2.start_date) and t1.seriesId!=t2.seriesId %@",dataBase,dataBase,dataBase,cond];
		[self query:quer];
		//console.log("1");
	}
	
		/*
		quer = @"insert into test.scheduleInconsistencies (id1,id2,description,severity) select t1.id,t2.id,concat('Traslape ',t1.location),1 from test.eventsPermanent t1, test.eventsPermanent t2 where t1.customer=t2.customer and t1.location=t2.location and t1.start_date<=t2.start_date and t1.end_date>=t2.start_date and t1.seriesId!=t2.seriesId";
		[self query:quer];
		*/

	if ( [incoPersOverChec state] ) {
		if ( mode == 1 )
			cond = [CPString stringWithFormat:@"and (t1.location like '%%:%d|' or t2.location like '%%:%d|')",locaInde,locaInde];
		var coun = [emplArra count];
		for ( var i=0; i<coun; i++ ) {
			var empl = [emplPopu itemTitleAtIndex:1+i];
			quer = [CPString stringWithFormat:@"insert into %@.scheduleInconsistencies (id1,id2,description,severity) select t1.id,t2.id,'Traslape %@',2  from %@.eventsPermanent t1, %@.eventsPermanent t2 where t1.personnel like '%%|%@|%%' and t2.personnel like '%%|%@|%%' and UNIX_TIMESTAMP(t1.start_date)<=UNIX_TIMESTAMP(t2.end_date) and UNIX_TIMESTAMP(t1.end_date)+900>=UNIX_TIMESTAMP(t2.start_date) and t1.seriesId!=t2.seriesId %@",
				dataBase,empl,dataBase,dataBase,empl,empl,cond];
			[self query:quer];
		}
	}

	if ( [incoEmplWorkHourOverChec state] ) {
		if ( mode == 1 )
			cond = [CPString stringWithFormat:@"and t1.location like '%%:%d|'",locaInde];
		coun = [emplArra count];
		for ( var i=0; i<coun; i++ ) {
			var empl = [emplPopu itemTitleAtIndex:1+i];
			var code = [[empl componentsSeparatedByString:@":"] objectAtIndex:1];
			quer = [CPString stringWithFormat:@"insert into %@.scheduleInconsistencies (id1,id2,description,severity) select t1.id,0,'Empleado %@ en horas no laborales',1  from %@.eventsPermanent t1, %@.personSchedule t2 where t1.personnel like '%%|%@|%%' and t2.id='%@' and DAYOFWEEK(t1.start_date)=t2.day and (SUBSTRING(t1.start_date,0,11)<t2.timeStart OR HOUR(t1.end_date)>t2.timeFinish) %@",
				dataBase,empl,dataBase,dataBase,empl,code,cond];
			[self query:quer];
		}
	}

	if ( [incoEmplWorkDayOverChec state] ) {
		if ( mode == 1 )
			cond = [CPString stringWithFormat:@"and location like '%%:%d|'",locaInde];
		for ( var i=0; i<coun; i++ ) {
			var empl = [emplPopu itemTitleAtIndex:1+i];
			var code = [[empl componentsSeparatedByString:@":"] objectAtIndex:1];
			quer = [CPString stringWithFormat:@"insert into %@.scheduleInconsistencies (id1,id2,description,severity) select id,0,'Empleado en dia no laboral %@',2  from %@.eventsPermanent where personnel like '%%|%@|%%' and DAYOFWEEK(start_date) not in (select day from %@.personSchedule where id='%@') %@",
			dataBase,empl,dataBase,empl,dataBase,code,cond];
			[self query:quer];
		}
	}

	if ( [incoOtheOverChec state] ) {
		if ( mode == 1 )
			cond = [CPString stringWithFormat:@"and location like '%%:%d|'",locaInde];
		quer = [CPString stringWithFormat:@"select id,name from %@.organizationLocations where active=1 %@",dataBase,cond];
		var locaArra = [self query:quer];
		coun = [locaArra count];
		for ( var i=0; i<coun; i++ ) {
			var locaIden2 = [[locaArra[i] valueList] objectAtIndex:0];
			var locaName = [[locaArra[i] valueList] objectAtIndex:1];
			quer = [CPString stringWithFormat:@"insert into %@.scheduleInconsistencies (id1,id2,description,severity) select t1.id,t1.id,'Evento en horas no visitables',1  from %@.eventsPermanent t1, %@.locationSchedule t2 where t1.location like '%%:%@|' and t2.organizationLocationId='%@' and DAYOFWEEK(t1.start_date)=t2.day and (SUBSTRING(t1.start_date,0,11)<t2.timeStart OR HOUR(t1.end_date)>t2.timeFinish)",
				dataBase,dataBase,dataBase,locaIden2,locaIden2];
			[self query:quer];
			quer = [CPString stringWithFormat:@"insert into %@.scheduleInconsistencies (id1,id2,description,severity) select id id1,id id2,'Evento en dia no visitable' description,2 severity  from %@.eventsPermanent where location like '%%:%@|' and DAYOFWEEK(start_date) not in (select day from %@.locationSchedule where id='%@')",
			dataBase,dataBase,locaIden2,dataBase,locaIden2];
			[self query:quer];
		}
	}

	/*
	var equiCoun = [equiArra count];
	for ( var e=0; e<equiCoun; e++ ) {
		var valuList = [equiArra[e] valueList];
		var equiIden = valuList[0];
		var equiType = [valuList[4] intValue];
		alert("equiIden="+equiIden+"  of type: "+equiType);
		if ( equiType != 0 )
			continue;

		var quer = [CPString stringWithFormat:@"select lng,lat,start_date from test.eventsPermanent where start_date like '%@%%' and vehicle like '%%:%@|%%' order by start_date",dateNow,equiIden];
		var equiEvenArra = [self query:quer];
		var equiEvenCoun = [equiEvenArra count];

		var lngdPrev = -84.1;
		var latiPrev = 9.9;
		var datePrev = 0;
		var timeInte = 0.;
		for ( var i=0; i<equiEvenCoun; i++ ) {
			var valuList2 = [equiEvenArra[i] valueList];
			var lngd = valuList2[0];
			var lati = valuList2[1];
			var stri = [CPString stringWithFormat:@"%@:00 -0600",valuList[2]];
			if ( i == 0 ) {
				lngdPrev = lngd;
				latiPrev = lati;
				dataPrev = [[CPDate alloc] initWithString:stri];
			}
			else {
				var lngdDiff = lngd - lngdPrev;
				var latiDiff = lati - latiPrev;
				var dist = Math.sqrt(lngdDiff*lngdDiff+latiDiff*latiDiff)*111.45;
				var timeInte = dist/30. * 3600.;
				var datePred = [[CPDate alloc] initWithTimeInterval:timeInte sinceDate:dataPrev];
				var date = [[CPDate alloc] initWithString:stri];
				var timeComp = [date timeIntervalSinceDate:datePred];
				alert("prev="+[datePrev description]+"  dist="+dist+"  inte="+timeInte+"  pred="+[datePred description]+"  date="+[datePrev description]+"   timeComp="+timeComp);

				lngdPrev = lngd;
				latiPrev = lati;
				datePrev = date;
			}
		}
	}
	*/

	[incoTabl reloadData];
}



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



- (void) scheduleImport:(id)sender {
	var quer = @"update " + dataBase + ".eventsPermanent set start_date=eventsPermanent.start_date, end_date=eventsPermanent.end_date where id=eventsPermanent.id";
	[self query:quer];
}



- (void) scheduleNew:(id)sender {
	var x = 100;
	var y = 100;
	var paneWidt = 1500;
	var paneHeig = 800;
	var fram = CGRectMake(x,y, paneWidt,paneHeig);
	
	scheWind = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[scheWind setFloatingPanel:YES]; 
	[scheWind orderFront:self];
	[scheWind setTitle:@"Calendar"];
	
	var paneContView = [scheWind contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:1. heightOrange:4.];
	
	x = 10.;
	y = 15.;
	fram = CGRectMake(x,y, paneWidt-20,paneHeig-25);
	scheView = [[RMSchedulerView alloc] initWithFrame:fram];

	if([custHoliArra count] > 0){
		[scheView setHolidays:custHoliArra];
	}else{

		[scheView setHolidays:holiArra];
	}
	//Responsive
	[scheView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];
	
	[paneContView addSubview:scheView];
	
	[scheView buildScheduler:appCont];
}



- (CPPanel) schedulerPanel {
	return schePane;
}



- (void) schedulerPanel:(id)sender {
	var textFact = 1.04;
	
	var horiPos1;
	var horiPosiWidt = 100;
	var horiPos1= 10;
	var horiPos2= horiPos1 + horiPosiWidt;
	var horiPos3= 390;
	var horiPos4= horiPos3 + horiPosiWidt;
	var horiPosiOffs= -4;
	
	var vertPosi;
	var vertPosiOffs= -4;
	var vertIncr = 25;

	var paneWidt= 350;
	var paneHeig= 780.;
	var tablWidt= paneWidt - 20;
	var tablHeig= 200;
	
	var x= 20 + Math.random()*20;
	var y= 50 + Math.random()*20;
	var fram = CGRectMake(x,y, paneWidt,paneHeig);
	
	var labe;
	
	schePane = [[CPPanel alloc] initWithContentRect:fram styleMask:CPHUDBackgroundWindowMask|CPClosableWindowMask|CPResizableWindowMask]; 
	[schePane setFloatingPanel:YES]; 
	[schePane setDelegate:self];
	[schePane orderFront:self];
	[schePane setTitle:@"Scheduler"];
	
	var paneContView = [schePane contentView];
	[paneContView setBackgroundColor:coloDefaLite];
	[self addBanners:paneContView heightBlue:2. heightOrange:4.];


	// ***************************
	// Common fields

	var view = paneContView;
	// TabView

	/*
	fram = CGRectMake(5,vertPosi,paneWidt-10,paneHeig-vertPosi-20);
	var tabView= [[CPTabView alloc] initWithFrame:fram];
	[tabView setBackgroundColor:coloDefaLite];
	[tabView setAutoresizingMask:CPViewWidthSizable | CPViewHeightSizable];

	[tabView setDelegate:self];

	[paneContView addSubview:tabView];	
	*/

	// *******************************
	// Tab : Databases

	//var tabViewItem= [[CPTabViewItem alloc] initWithIdentifier:@"tabViewItem"];
	//[tabViewItem setLabel:@"Databases"];

	//view= [[CPView alloc] initWithFrame: CGRectMake(50, 50, 50, 50)]; 
	[view setBackgroundColor:coloDefaBrig];

	vertPosi = 20;
	var blckYPosi = vertPosi;

	

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

	titlText = [self addTextField:@"Titulo" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:200*textFact TFHeight:30 VView:view Editable:YES];
	//[titlText setAction:@selector(scheduleEventNumber:)];

	vertPosi += 1.25*vertIncr;
	
	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*textFact TFHeight:30 VView:view Editable:YES];
	[filtText setDelegate:self];
	[filtText setTarget:self];
	[filtText setAction:@selector(filterCustomer:)];
	
	//btnSear = [self addButton:@"Buscar" TFPosX:horiPos2+116 TFPosY:vertPosi TFWidth:75 TFHeight:24  VView:view sizeToFit:NO Action:@selector(filterCustomer:)];

	vertPosi += 1.25*vertIncr;


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

	custPopu = [self addPopupButton:@"Organizaciones" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[custPopu setTarget:self];
	[custPopu setAction:@selector(customerPopupSelection:)];

	
	[self fillOrganizations:self];
	vertPosi += vertIncr;

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

	custLocaPopu = [self addPopupButton:@"Locaciones" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[custLocaPopu setTarget:self];
	[custLocaPopu setAction:@selector(customerLocationPopupSelection:)];


	vertPosi += vertIncr;

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

	custLocaAddrText = [self addTextField:@"" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:200*textFact TFHeight:30 VView:view Editable:YES];

	vertPosi += vertIncr;

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

	statePopu = [self addPopupButton:@"Estado" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[statePopu setTarget:self];
	//[custGeo setAction:@selector(customerLocationPopupSelection:)];
	[self fillState:self];


    blckView1 = [[CPView alloc] initWithFrame:CGRectMake(0,blckYPosi - 5, horiPos2 + 210,vertPosi+20)];
    [blckView1 setBackgroundColor:coloDefaBrig];
    [view addSubview:blckView1];

	vertPosi += 1.25*vertIncr;

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

	actiPopu = [self addPopupButton:@"Actividades" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];
	[actiPopu setTarget:self];
	[actiPopu setAction:@selector(activityPopupSelection:)];

	quer = [CPString stringWithFormat:@"select description,duration,price,id 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 += vertIncr;

	var fram= CGRectMake(horiPos2,vertPosi, 200,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:200];
	[actiListTabl addTableColumn:colu];

	[scroView setDocumentView:actiListTabl];

	[view addSubview:scroView];

	vertPosi += 100;

	

	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];
	hourStarText = [self addTextField:@"07" TFPosX:horiPos2-4+76 TFPosY:vertPosi-4 TFWidth:35 TFHeight:30 VView:view Editable:YES];
	minuStarText = [self addTextField:@"00" TFPosX:horiPos2-4+102 TFPosY:vertPosi-4 TFWidth:35 TFHeight:30 VView:view Editable:YES];
	[self addButton:@"C" TFPosX:horiPos2+175 TFPosY:vertPosi-2 TFWidth:25 TFHeight:24  VView:view sizeToFit:NO Action:@selector(datePickerPanel:)];

	vertPosi += vertIncr;

	//[dateStarText setTarget:self];
	//[dateStarText setAction:@selector(scheduleDateStart:)];

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

	duraText = [self addTextField:@"60" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:60 TFHeight:30 VView:view Editable:YES];

	vertPosi += vertIncr;

    blckYPosi = vertPosi;

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

	var butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2,vertPosi, 30,24)];
	[butt setTitle:"D"];
	[butt setTarget:self];
	[butt setAction:@selector(priceUSDToFCU:)];                
	[view addSubview:butt];

	pricUSDText = [self addTextField:@"0" TFPosX:horiPos2-4+31 TFPosY:vertPosi-3 TFWidth:58 TFHeight:30 VView:view Editable:YES];

	pricEXCText = [self addTextField:@"1" TFPosX:horiPos2-4+80 TFPosY:vertPosi-3 TFWidth:49 TFHeight:30 VView:view Editable:YES];

	pricFCUText = [self addTextField:@"0" TFPosX:horiPos2-4+120 TFPosY:vertPosi-3 TFWidth:58 TFHeight:30 VView:view Editable:YES];

	butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2+170,vertPosi, 30,24)];
	[butt setTitle:"M"];
	[butt setTarget:self];
	[butt setAction:@selector(priceFCUToUSD:)];                
	[view addSubview:butt];

	vertPosi += 1.25*vertIncr;
	var vertHere = vertPosi;

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

	freqPopu = [self addPopupButton:@"Una vez" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view pullsDown:NO];//0
	[freqPopu setTarget:self];
	[freqPopu setAction:@selector(scheduleFrequency:)];
	[freqPopu addItemWithTitle:@"Diario"];//1
	[freqPopu addItemWithTitle:@"Semanal"];//2
	[freqPopu addItemWithTitle:@"Mensual"];//3
	//[freqPopu addItemWithTitle:@"Cada 7 dias"];
	//[freqPopu addItemWithTitle:@"Cada 14 dias"];
	//[freqPopu addItemWithTitle:@"Cada 21 dias"];
	//[freqPopu addItemWithTitle:@"Cada 28 dias"];
	[freqPopu addItemWithTitle:@"Primer domingo del mes"];//4
	[freqPopu addItemWithTitle:@"Primer lunes del mes"];//5
	[freqPopu addItemWithTitle:@"Primer martes del mes"];//6
	[freqPopu addItemWithTitle:@"Primer miércoles del mes"];//7
	[freqPopu addItemWithTitle:@"Primer jueves del mes"];//8
	[freqPopu addItemWithTitle:@"Primer viernes del mes"];//9
	[freqPopu addItemWithTitle:@"Primer sábado del mes"];//10
	[freqPopu addItemWithTitle:@"Segundo domingo del mes"];//11
	[freqPopu addItemWithTitle:@"Segundo lunes del mes"];//12
	[freqPopu addItemWithTitle:@"Segundo martes del mes"];//13
	[freqPopu addItemWithTitle:@"Segundo miércoles del mes"];//14
	[freqPopu addItemWithTitle:@"Segundo jueves del mes"];//15
	[freqPopu addItemWithTitle:@"Segundo viernes del mes"];//16
	[freqPopu addItemWithTitle:@"Segundo sábado del mes"];//17
	[freqPopu addItemWithTitle:@"Tercer domingo del mes"];//18
	[freqPopu addItemWithTitle:@"Tercer lunes del mes"];// 19
	[freqPopu addItemWithTitle:@"Tercer martes del mes"];//20
	[freqPopu addItemWithTitle:@"Tercer miércoles del mes"];//21
	[freqPopu addItemWithTitle:@"Tercer jueves del mes"];//22
	[freqPopu addItemWithTitle:@"Tercer viernes del mes"];//23
	[freqPopu addItemWithTitle:@"Tercer sábado del mes"];//24
	[freqPopu addItemWithTitle:@"Cuarto domingo del mes"];//25
	[freqPopu addItemWithTitle:@"Cuarto lunes del mes"];//26
	[freqPopu addItemWithTitle:@"Cuarto martes del mes"];//27
	[freqPopu addItemWithTitle:@"Cuarto miércoles del mes"];//28
	[freqPopu addItemWithTitle:@"Cuarto jueves del mes"];//29
	[freqPopu addItemWithTitle:@"Cuarto viernes del mes"];//30
	[freqPopu addItemWithTitle:@"Cuarto sábado del mes"];//31
	//add 2017-03-14
	[freqPopu addItemWithTitle:@"Quinto domingo del mes"];//32
	[freqPopu addItemWithTitle:@"Quinto lunes del mes"];//33
	[freqPopu addItemWithTitle:@"Quinto martes del mes"];//34
	[freqPopu addItemWithTitle:@"Quinto miércoles del mes"];//35
	[freqPopu addItemWithTitle:@"Quinto jueves del mes"];//36
	[freqPopu addItemWithTitle:@"Quinto viernes del mes"];//37
	[freqPopu addItemWithTitle:@"Quinto sábado del mes"];//38
	//end

	vertPosi += vertIncr;

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

	evenFreqText = [self addTextField:@"0" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:60 TFHeight:30 VView:view Editable:YES];

	vertPosi += 1.25*vertIncr;

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

	evenNumbText = [self addTextField:@"1" TFPosX:horiPos2-4 TFPosY:vertPosi-4 TFWidth:60 TFHeight:30 VView:view Editable:YES];
	[evenNumbText setTarget:self];
	[evenNumbText setAction:@selector(scheduleEventNumber:)];

    blckView2 = [[CPView alloc] initWithFrame:CGRectMake(0,blckYPosi - 5, horiPos2 + 210,vertPosi+20)];
    [blckView2 setBackgroundColor:coloDefaBrig];
    [view addSubview:blckView2];
    [blckView1 setHidden:YES];
    [blckView2 setHidden:YES];


	vertPosi += 1.25*vertIncr;


	// Personnel

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

	emplPopu = [self addPopupButton:@"Personal" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:170 TFHeight:24  VView:view pullsDown:NO];
	[emplPopu setTarget:self];
	[emplPopu setAction:@selector(employeePopupSelection:)];

	butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2+170,vertPosi, 25,24)];
	[butt setTitle:"R"];
	[butt setTarget:self];
	[butt setAction:@selector(employeePopupRepeat:)];                
	[view addSubview:butt];

	vertPosi += vertIncr;

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

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

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Personal"];
	[[colu headerView] setStringValue:@"Personal"];
	[colu setWidth:200];
	[emplListTabl addTableColumn:colu];

	[scroView setDocumentView:emplListTabl];

	[view addSubview:scroView];

	vertPosi += 100;


	// Vehicles & Equipment
	
	labe= [self addTextField:@"Equipo :" TFPosX:horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	equiPopu = [self addPopupButton:@"Equipo" TFPosX:horiPos2 TFPosY:vertPosi TFWidth:150 TFHeight:24  VView:view pullsDown:NO];
	[equiPopu setTarget:self];
	[equiPopu setAction:@selector(equipmentPopupSelection:)];

	butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2+150,vertPosi, 25,24)];
	[butt setTitle:"A"];
	[butt setTarget:self];
	[butt setAction:@selector(equipmentAssociated:)];                
	[view addSubview:butt];

	butt = [[CPButton alloc] initWithFrame: CGRectMake(horiPos2+175,vertPosi, 25,24)];
	[butt setTitle:"R"];
	[butt setTarget:self];
	[butt setAction:@selector(equipmentPopupRepeat:)];                
	[view addSubview:butt];
//Change
	quer = [CPString stringWithFormat:@"select id0,id1,make,model,year,typeId from %@.equipment where organizationId='%@' and active = 1 order by make,model,year",
		dataBase,orgaId];
		//alert("quer " + quer );
	equiArra = [self query:quer];
	var coun = [equiArra count];
	for ( var i=0; i<coun; i++ ) {
		var valuList = [equiArra[i] valueList];
		var iden0 = valuList[0];
		var iden1 = valuList[1];
		var make = valuList[2];
		var mode = valuList[3];
		var year = valuList[4];
		var stri = [CPString stringWithFormat:@"%@_%@_%@_%@:%@",make,mode,year,iden1,iden0];
		[equiPopu addItemWithTitle:stri];
	}

	vertPosi += vertIncr;

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

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

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Equipo"];
	[[colu headerView] setStringValue:@"Equipo"];
	[colu setWidth:200];
	[equiListTabl addTableColumn:colu];

	[scroView setDocumentView:equiListTabl];

	[view addSubview:scroView];

	vertPosi += 80;
	vertPosi += vertIncr;

	[self addButton:@"1" TFPosX:horiPos2    TFPosY:vertPosi TFWidth:25 TFHeight:24  VView:view sizeToFit:NO Action:@selector(schedulerPanelSize1:)];
	[self addButton:@"2" TFPosX:horiPos2+25 TFPosY:vertPosi TFWidth:25 TFHeight:24  VView:view sizeToFit:NO Action:@selector(schedulerPanelSize2:)];
	[self addButton:@"3" TFPosX:horiPos2+50 TFPosY:vertPosi TFWidth:25 TFHeight:24  VView:view sizeToFit:NO Action:@selector(schedulerPanelSize3:)];



    vertPosi = 20;

	labe= [self addTextField:@"ID/Serie :" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	idenText = [self addTextField:@"" TFPosX:paneWidt+horiPos1+80 TFPosY:vertPosi-4 TFWidth:60 TFHeight:30 VView:view Editable:YES];
	seriText = [self addTextField:@"" TFPosX:paneWidt+horiPos1+140 TFPosY:vertPosi-4 TFWidth:60 TFHeight:30 VView:view Editable:YES];

	vertPosi += 1.25*vertIncr;

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

	/*var colo = [CPString stringWithFormat:@"#%x%x%x",
    		Math.floor(Math.random()*15.99),Math.floor(Math.random()*15.99),Math.floor(Math.random()*15.99)];*/
    		
    //var colo = [CPString stringWithFormat:@"#%x%x%x",   
    //		(Math.floor(Math.random() * 5.99 )+ 10 ) , (Math.floor(Math.random() *  5.99) + 10 ),(Math.floor(Math.random( )* 5.99) + 10)];
	var colo = [self getRandomColor];
	coloText = [self addTextField:colo TFPosX:paneWidt+horiPos1+80 TFPosY:vertPosi-4 TFWidth:60 TFHeight:30 VView:view Editable:YES];

	vertPosi += 1.25*vertIncr;


	btnIngr = [self addButton:@"Ingresar" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventInsert:)];
	btnLimp = [self addButton:@"Limpiar"  TFPosX:paneWidt+horiPos1+100 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(clearFields:)];

	vertPosi += vertIncr;

	btnBorrID = [self addButton:@"Borrar ID"    TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventDeleteID:)];
	btnBorrSr = [self addButton:@"Borrar Serie" TFPosX:paneWidt+horiPos1+100 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventDeleteSeriesFuture:)];

	vertPosi += 1.5*vertIncr;

	btnExtrID = [self addButton:@"Extraer ID"    TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventExtractID:)];
	btnExtrSr = [self addButton:@"Extraer Serie" TFPosX:paneWidt+horiPos1+100 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventExtractSeries:)];

        vertPosi += vertIncr;

	btnUpdt   = [self addButton:@"Actualizar"    TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventModify:)];
	
	btnExit   = [self addButton:@"Cancelar" TFPosX:paneWidt+horiPos1+100 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventCancelModify:)];
	
        [btnUpdt setEnabled:0];
        [btnExit setEnabled:0];
	vertPosi += 1.5*vertIncr;
	/**
	labe= [self addTextField:@"Fecha Final :" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];
	dateEndTextReProg = [self addTextField:[[[CPDate date] description] substringToIndex:10] TFPosX:paneWidt+horiPos1+80-4 TFPosY:vertPosi-4 TFWidth:100 TFHeight:30 VView:view Editable:YES];
	[self addButton:@"C" TFPosX:paneWidt+horiPos1+180 TFPosY:vertPosi-2 TFWidth:25 TFHeight:24  VView:view sizeToFit:NO Action:@selector(datePickerPanelReProg:)];
	
	vertPosi += 1.5*vertIncr;
	**/
	
	btnReprog   = [self addButton:@"Reprogramar" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(reProgramSeries:)];
	[btnReprog setEnabled:0];
	vertPosi += 1.5*vertIncr;

	btnNoFltr = [self addButton:@"Ningún Filtro" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFilterNone:)];

	vertPosi += vertIncr;

	btnFltrID = [self addButton:@"Filtro ID" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFilterIdentification:)];
	btnFltrSr = [self addButton:@"Filtro Serie" TFPosX:paneWidt+horiPos1+100 TFPosY:vertPosi TFWidth:100 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFilterSeries:)];

	vertPosi += vertIncr;

	btnFltrOr = [self addButton:@"Filtro Organización" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFilterOrganizations:)];

	vertPosi += vertIncr;

	btnFltrLc = [self addButton:@"Filtro Locación" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFilterLocation:)];

	vertPosi += vertIncr;

	btnFltrSt= [self addButton:@"Filtro Estado" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFilterState:)];

	vertPosi += vertIncr;

	btnFltrPe = [self addButton:@"Filtro Personal" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFilterEmployees:)];

	vertPosi += vertIncr;

	btnFltrEq = [self addButton:@"Filtro Equipo" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFilterEquipment:)];

	vertPosi += vertIncr;

	btnFltrCm = [self addButton:@"Filtro Campos" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFilterFields:)];

	vertPosi += 1.5*vertIncr;

	btnFltrSch = [self addButton:@"Scheduler" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleNew:)];

	vertPosi += 1.25*vertIncr;

	//[self addButton:@"Import" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleImport:)];

	vertPosi += 2*vertIncr;

	btnFltrSp = [self addButton:@"Spots" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventFreeBlockedSpots:)];

	vertPosi += 2*vertIncr;

	btnFltrRo = [self addButton:@"Routes" TFPosX:paneWidt+horiPos1 TFPosY:vertPosi TFWidth:200 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventRoutes:)];

	vertPosi += vertIncr;


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

	coorLngdText = [self addTextField:@"" TFPosX:paneWidt+horiPos2 TFPosY:vertPosi-4 TFWidth:100 TFHeight:30 VView:view Editable:YES];

	vertPosi += vertIncr;

	coorLatiText = [self addTextField:@"" TFPosX:paneWidt+horiPos2 TFPosY:vertPosi-4 TFWidth:100 TFHeight:30 VView:view Editable:YES];


    vertPosi = 20;

	labe= [self addTextField:@"Eventos :" TFPosX:1.75*paneWidt+horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	vertPosi += vertIncr;

	fram= CGRectMake(1.75*paneWidt+horiPos1,vertPosi, 2.25*tablWidt,tablHeig);
	scroView= [[CPScrollView alloc] initWithFrame:fram];

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

	colu= [[CPTableColumn alloc] initWithIdentifier:@"ID"];
	[[colu headerView] setStringValue:@"ID"];
	[colu setWidth:40];
	[evenTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Series"];
	[[colu headerView] setStringValue:@"Serie"];
	[colu setWidth:60];
	[evenTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Description"];
	[[colu headerView] setStringValue:@"Descripcion"];
	[colu setWidth:140];
	[evenTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Location"];
	[[colu headerView] setStringValue:@"Locacion"];
	[colu setWidth:100];
	[evenTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"DateStart"];
	[[colu headerView] setStringValue:@"FechaInicio"];
	[colu setWidth:100];
	[evenTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"DateFinish"];
	[[colu headerView] setStringValue:@"FechaFinal"];
	[colu setWidth:100];
	[evenTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Personnel"];
	[[colu headerView] setStringValue:@"Personal"];
	[colu setWidth:100];
	[evenTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Equipment"];
	[[colu headerView] setStringValue:@"Equipo"];
	[colu setWidth:100];
	[evenTabl addTableColumn:colu];

	[scroView setDocumentView:evenTabl];
	
	//add 2017-02-27
	evenMenu = [[CPMenu alloc] initWithTitle:@"Opciones comentarios"];
	var seriCommOpti = [evenMenu insertItemWithTitle:@"Agregar comentario a la serie actual" 
							    action:@selector(commentSerieOption:)
							     keyEquivalent:@""
							     atIndex:0];
							      
	var evenCommOpti = [evenMenu insertItemWithTitle:@"Agregar comentario a los eventos seleccionados" 
							    action:@selector(commentEventOption:)
							     keyEquivalent:@""
							     atIndex:1];
	
	[scroView setMenu:evenMenu];
	[[CPArray arrayWithObjects:seriCommOpti, evenCommOpti] makeObjectsPerformSelector:@selector(setTarget:) withObject:self];
	//end
	
	
	

	[view addSubview:scroView];

	vertPosi += tablHeig;

	[self addButton:@"Eventos" TFPosX:1.75*paneWidt+horiPos1 TFPosY:vertPosi TFWidth:75 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEvents:)];

	[self addButton:@"ID" TFPosX:1.75*paneWidt+horiPos1+75 TFPosY:vertPosi TFWidth:75 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleIdentityEvents:)];

	[self addButton:@"Series" TFPosX:1.75*paneWidt+horiPos1+150 TFPosY:vertPosi TFWidth:75 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleSeriesEvents:)];

	//[self addButton:@"Notas" TFPosX:1.75*paneWidt+horiPos1+250 TFPosY:vertPosi TFWidth:75 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleEventBillingNotes:)];


	vertPosi += vertIncr+30;

	labe= [self addTextField:@"Inconsistencias :" TFPosX:1.75*paneWidt+horiPos1 TFPosY:vertPosi TFWidth:0 TFHeight:0 VView:view Editable:NO];
	[labe setTextColor:[CPColor whiteColor]];

	vertPosi += vertIncr;

	var fram= CGRectMake(1.75*paneWidt+horiPos1,vertPosi, 2.25*tablWidt,tablHeig);
	var scroView= [[CPScrollView alloc] initWithFrame:fram];

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

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Severidad"];
	[[colu headerView] setStringValue:@"Severidad"];
	[colu setWidth:40];
	[incoTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Inconsistencia"];
	[[colu headerView] setStringValue:@"Inconsistencia"];
	[colu setWidth:100];
	[incoTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"ID1"];
	[[colu headerView] setStringValue:@"ID1"];
	[colu setWidth:40];
	[incoTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Locacion1"];
	[[colu headerView] setStringValue:@"Locacion1"];
	[colu setWidth:100];
	[incoTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Fecha1"];
	[[colu headerView] setStringValue:@"Fecha1"];
	[colu setWidth:100];
	[incoTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"ID2"];
	[[colu headerView] setStringValue:@"ID2"];
	[colu setWidth:40];
	[incoTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Locacion2"];
	[[colu headerView] setStringValue:@"Locacion2"];
	[colu setWidth:100];
	[incoTabl addTableColumn:colu];

	colu= [[CPTableColumn alloc] initWithIdentifier:@"Fecha2"];
	[[colu headerView] setStringValue:@"Fecha2"];
	[colu setWidth:100];
	[incoTabl addTableColumn:colu];

	[scroView setDocumentView:incoTabl];

	[view addSubview:scroView];

	vertPosi += tablHeig + 5;

	[self addButton:@"Todas"    TFPosX:1.75*paneWidt+horiPos1 TFPosY:vertPosi TFWidth:75 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleInconsistencies:)];
	[self addButton:@"Locación" TFPosX:1.75*paneWidt+horiPos1+75 TFPosY:vertPosi TFWidth:75 TFHeight:24  VView:view sizeToFit:NO Action:@selector(scheduleInconsistenciesForLocation:)];

	vertPosi += vertIncr;

    incoEvenOverChec = [CPCheckBox checkBoxWithTitle:@"Traslape Eventos"];
    [incoEvenOverChec setTextColor:[CPColor whiteColor]];
    [incoEvenOverChec setFrameOrigin:CPPointMake(1.75*paneWidt+horiPos1, vertPosi)];
    [incoEvenOverChec setTarget:self];
    [incoEvenOverChec setEnabled:YES];
    //[checDeshClie setAction:@selector(stateCheck4:)];
    [view addSubview:incoEvenOverChec];

    incoVehiOverChec = [CPCheckBox checkBoxWithTitle:@"Traslape Vehiculos"];
    [incoVehiOverChec setTextColor:[CPColor whiteColor]];
    [incoVehiOverChec setFrameOrigin:CPPointMake(1.75*paneWidt+horiPos1+150, vertPosi)];
    [incoVehiOverChec setTarget:self];
    [incoVehiOverChec setEnabled:YES];
    //[checDeshClie setAction:@selector(stateCheck4:)];
    [view addSubview:incoVehiOverChec];

    incoPersOverChec = [CPCheckBox checkBoxWithTitle:@"Traslape Personal"];
    [incoPersOverChec setTextColor:[CPColor whiteColor]];
    [incoPersOverChec setFrameOrigin:CPPointMake(1.75*paneWidt+horiPos1+300, vertPosi)];
    [incoPersOverChec setTarget:self];
    [incoPersOverChec setEnabled:YES];
    //[checDeshClie setAction:@selector(stateCheck4:)];
    [view addSubview:incoPersOverChec];

    incoEmplWorkHourOverChec = [CPCheckBox checkBoxWithTitle:@"Personal Horas Labor"];
    [incoEmplWorkHourOverChec setTextColor:[CPColor whiteColor]];
    [incoEmplWorkHourOverChec setFrameOrigin:CPPointMake(1.75*paneWidt+horiPos1+450, vertPosi)];
    [incoEmplWorkHourOverChec setTarget:self];
    [incoEmplWorkHourOverChec setEnabled:YES];
    //[checDeshClie setAction:@selector(stateCheck4:)];
    [view addSubview:incoEmplWorkHourOverChec];

    incoEmplWorkDayOverChec = [CPCheckBox checkBoxWithTitle:@"Personal Dias Labor"];
    [incoEmplWorkDayOverChec setTextColor:[CPColor whiteColor]];
    [incoEmplWorkDayOverChec setFrameOrigin:CPPointMake(1.75*paneWidt+horiPos1+600, vertPosi)];
    [incoEmplWorkDayOverChec setTarget:self];
    [incoEmplWorkDayOverChec setEnabled:YES];
    //[checDeshClie setAction:@selector(stateCheck4:)];
    [view addSubview:incoEmplWorkDayOverChec];

	vertPosi += vertIncr;

    incoOtheOverChec = [CPCheckBox checkBoxWithTitle:@"Locacion no visitable"];
    [incoOtheOverChec setTextColor:[CPColor whiteColor]];
    [incoOtheOverChec setFrameOrigin:CPPointMake(1.75*paneWidt+horiPos1, vertPosi)];
    [incoOtheOverChec setTarget:self];
    [incoOtheOverChec setEnabled:YES];
    //[checDeshClie setAction:@selector(stateCheck4:)];
    [view addSubview:incoOtheOverChec];

    [self schedulerPanelSize3:nil];

    quer = [CPString stringWithFormat:@"select id,CountryId,dateStart,dateFinish,description from %@.countryHolidays where CountryId='%@' order by dateStart",
	dataBase,countryCode];
	holiArra = [self query:quer];
	/*
	[tabViewItem setView:view];			
	[tabView addTabViewItem:tabViewItem];
	*/
}



- (void) schedulerPanelSize1:(id)sender {
	var paneWidt = 350;
	var fram= [schePane frame];
	fram.size.width = paneWidt;
	[schePane setFrame:fram];
}



- (void) schedulerPanelSize2:(id)sender {
	var paneWidt = 350;
	var fram= [schePane frame];
	fram.size.width = 1.75*paneWidt;
	[schePane setFrame:fram];
}



- (void) schedulerPanelSize3:(id)sender {
	var paneWidt = 350;
	var fram= [schePane frame];
	fram.size.width = 4*paneWidt;
	[schePane setFrame:fram];
}



- (void) setControllers_ON_OFF:(int)_onOff {
    
    [btnIngr setEnabled:_onOff];
    [btnLimp setEnabled:_onOff];
    [btnBorrID setEnabled:_onOff];
    [btnBorrSr setEnabled:_onOff];
    [btnExtrID setEnabled:_onOff];
    [btnExtrSr setEnabled:_onOff];
    [btnNoFltr setEnabled:_onOff];
    [btnReProg setEnabled:_onOff];
    [btnFltrID setEnabled:_onOff];

	[btnFltrSr setEnabled:_onOff];
	[btnFltrOr setEnabled:_onOff];
	[btnFltrLc setEnabled:_onOff];
	[btnFltrSt setEnabled:_onOff];
   	[btnFltrPe setEnabled:_onOff];
	[btnFltrEq setEnabled:_onOff];
	[btnFltrCm setEnabled:_onOff];    
	[btnFltrSch setEnabled:_onOff];
	[btnFltrSp setEnabled:_onOff];
	[btnFltrRo setEnabled:_onOff];

    if ( _onOff == 0 )
        _onOff = 1;
    else
        _onOff = 0;
    [btnUpdt setEnabled:_onOff];
    [btnExit setEnabled:_onOff];  
    [btnReprog setEnabled:_onOff];
}



- (void) updateOriginalSerieParameters {

	var evenSeri = [seriText intValue];
	var seriModl = [[model_seriesDefinitions alloc] init:appCont Serie:evenSeri];
	//console.log(seriModl);
	var indeOrga = [custPopu indexOfSelectedItem];
	var indeLoca = [custLocaPopu indexOfSelectedItem];
	

	var orgaId = custArra[indeOrga-1][2];
	//if ( [custPopu indexOfItemWithTitle:[seriModl orga]] == -1 ) {
	if ( orgaId != [seriModl orga]){
		[glblAlerPane showWithMessage:@"Oops lo sentimos" info:"Esta serie tiene inconsistencias y no puede ser modificada masivamente, pruebe modificando eventos individuales"];
		alert("Lo sentimos, esta serie tiene inconsistencias y no puede ser modificada masivamente");
		return;
	}
	[self clearFields:nil];
    [self setControllers_ON_OFF:0];
	[seriText setStringValue:[seriModl seriId]];
	[custPopu selectItemAtIndex:indeOrga];
	[self customerPopupSelection:nil];
	//console.log(0);
	if(indeLoca <= 0){
		var locaCount = [custLocaArra count];
		for ( var j=0; j<locaCount; j++ ) {
			var valuList = [custLocaArra[j] valueList];
			if(valuList[0] == [seriModl loca]){
				indeLoca = j+1;
			}
		}
	}
	
	[custLocaPopu selectItemAtIndex:indeLoca];
	[self customerLocationPopupSelection:nil];
	actiListArra = [seriModl getActivities];
	[actiListTabl reloadData];
	[titlText setStringValue:[seriModl titl]];
	[dateStarText setStringValue:[seriModl starDate]];
	[hourStarText setStringValue:[seriModl starHour]];
	[minuStarText setStringValue:[seriModl starMinu]];
	[duraText setStringValue:[seriModl dura]];
	[evenFreqText setStringValue:[seriModl freq]];
	//[freqPopu selectItemAtIndex:-1];  //[[seriModl cale] intValue]];
	[freqPopu selectItemAtIndex:[[seriModl cale] intValue]];
	[evenNumbText setStringValue:[seriModl evnts]];
	emplListArra = [seriModl getPersons];
	[emplListTabl reloadData];
	equiListArra = [seriModl getEquipments];
	[equiListTabl reloadData];
        [seriText setStringValue:[seriModl seriId]];
	updtNumb = evenSeri;
	updtSubj = @"Serie";
	[self scheduleSeriesEvents:nil];
}



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

//

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

//		TABLE SOURCE DELEGATE METHODS

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

	if ( tablView == actiListTabl ) {
		coun = [actiListArra count];
	}
	else if ( tablView == emplListTabl ) {
		coun = [emplListArra count];
	}
	else if ( tablView == equiListTabl ) {
		coun = [equiListArra count];
	}
	else if ( tablView == evenTabl ) {
		if ( evenOpti == 0 ) {
			if ( custStri == 0 )
				quer= @"select e.id,e.seriesId,o.Name,e.start_date,e.end_date,e.text,e.personnel, e.vehicle,e.customer,e.calendar from " + dataBase + ".eventsPermanent as e inner join " + dataBase + ".organizationLocations as o on e.location = o.Id where YEAR(start_date) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR)) order by start_date,end_date,customer,location";
			else if ( custLocaStri == 0 ){
				quer= [CPString stringWithFormat:@"select e.id,e.seriesId,o.Name,e.start_date,e.end_date,e.text,e.personnel, e.vehicle,e.customer,e.calendar from %@.eventsPermanent as e inner join %@.organizationLocations as o on e.location = o.Id   where customer = '%@' order by e.start_date,e.end_date,o.Name",dataBase,dataBase,custStri];
				//alert(custStri);
			}
			else
				quer= [CPString stringWithFormat:@"select e.id,e.seriesId,o.Name,e.start_date,e.end_date,e.text,e.personnel, e.vehicle,e.customer,e.calendar from %@.eventsPermanent as e inner join %@.organizationLocations as o on e.location = o.Id  where customer='%@' and location=%@ order by start_date,end_date",dataBase,dataBase,custStri,custLocaStri];
		}
		else if ( evenOpti == 1 ) {
			var iden = [idenText stringValue];
			if ( [iden length] > 0 )
				quer= [CPString stringWithFormat:@"select e.id,e.seriesId,o.Name,e.start_date,e.end_date,e.text,e.personnel, e.vehicle,e.customer,e.calendar from %@.eventsPermanent as e inner join %@.organizationLocations as o on e.location = o.Id where e.id=%@ order by e.start_date,e.end_date,e.customer,o.Name",dataBase,dataBase,iden];
			else
				return 0;
		}
		else if ( evenOpti == 2 ) {
			var seri = [seriText stringValue];
			if ( [seri length] > 0 )
				quer= [CPString stringWithFormat:@"select e.id,e.seriesId,o.Name,e.start_date,e.end_date,e.text,e.personnel, e.vehicle,e.customer,e.calendar from %@.eventsPermanent as e inner join %@.organizationLocations as o on e.location = o.Id where seriesId=%@ order by e.start_date,e.end_date,e.customer,o.Name",dataBase,dataBase,seri];
			else
				return 0;
		}
		evenArra = [self query:quer];
		coun = [evenArra count];
	}
	else if ( tablView == incoTabl ) {
		quer = @"select t1.severity,t1.description,t1.id1,t2.location,t2.start_date,t1.id2,t3.location,t3.start_date from " + dataBase + ".scheduleInconsistencies t1, (select id,location,start_date from " + dataBase + ".eventsPermanent where YEAR(start_date) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))) AS t2, (select id,location,start_date from " + dataBase + ".eventsPermanent where YEAR(start_date) = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 YEAR))) AS t3 where t1.id1<t1.id2 and t1.id1=t2.id and t1.id2=t3.id order by t2.start_date,t3.start_date limit 20;";
		incoArra = [self query:quer];
		coun = [incoArra count];
	}
	//alert("Count : "+coun)
	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];
	}
	else if ( tablView == emplListTabl ) {
		valu = emplListArra[rowInde];
	}
	else if ( tablView == equiListTabl ) {
		valu = equiListArra[rowInde];
	}
	else if ( tablView == evenTabl ) {
		//alert("Row : "+ rowInde + " Colum: "+headIden);
		var arra = [[evenArra objectAtIndex:rowInde] valueList];
		if ( [headIden isEqualToString:@"ID"] )
			valu = arra[0];
		else if ( [headIden isEqualToString:@"Series"] )
			valu = arra[1];
		else if ( [headIden isEqualToString:@"Location"] )
			valu = arra[2];
		else if ( [headIden isEqualToString:@"DateStart"] )
			valu = arra[3];
		else if ( [headIden isEqualToString:@"DateFinish"] )
			valu = arra[4];
		else if ( [headIden isEqualToString:@"Description"] )
			valu = arra[5];
		else if ( [headIden isEqualToString:@"Personnel"] ){
			/*
			if(arra[6] == ''){
				var striPers = "";
				var quer = [CPString stringWithFormat:@"Select p.id,p.nameLast,p.nameFirst,op.position from %@.persons as p inner join %@.organizationPersons as op on p.Id = op.personId inner join %@.eventPerson as ep on p.Id = ep.idPerson where ep.idEvent = %@ order by p.nameLast,p.nameFirst ASC",
					dataBase,dataBase,dataBase,arra[0]];
				var personArraTemp = [self query:quer];
				var perCoun = [personArraTemp count];
				if(perCoun < 1){
					striPers = "|"
				}
				for ( var j=0; j < perCoun; j++ ) {
					var valuList = [personArraTemp[j] valueList];
					var emplIden = valuList[0];
					var nameLast = valuList[1];
					var nameFirs = valuList[2];
					var posi     = [valuList[5] substringToIndex:1];
					striPers = [CPString stringWithFormat:@"%@|%@, %@ [%@]:%@",striPers,nameLast,nameFirs,posi,emplIden];
				}

				striPers = [CPString stringWithFormat:@"%@|",striPers];



			//console.log(personArraTemp);
				arra[6] = striPers;
				valu = striPers;
			}else{
				valu = arra[6];
			}**/
			valu = arra[6];

		}
		else if ( [headIden isEqualToString:@"Equipment"] ){
			/**if(arra[7] == ''){
				var striEqu = "";/**
				var quer = [CPString stringWithFormat:@"select id0,id1,make,model,year,typeId from %@.equipment  as e inner join %@.eventEquipment as ee on e.id0 = ee.idEquipment where  ee.idEvent = %@ order by make,model,year",
					dataBase,dataBase,arra[0]];
				var equipArraTemp = [self query:quer];
				var equCoun = [equipArraTemp count];
				if(equCoun < 1){
					striEqu = "|"
				}
				for ( var j=0; j < equCoun; j++ ) {
					var valuList = [equipArraTemp[j] valueList];
					var iden0 = valuList[0];
					var iden1 = valuList[1];
					var make = valuList[2];
					var mode = valuList[3];
					var year = valuList[4];
					striEqu = [CPString stringWithFormat:@"%@|%@_%@_%@_%@:%@",striEqu,make,mode,year,iden1,iden0];
				}

				striEqu = [CPString stringWithFormat:@"%@|",striEqu];


			//console.log(personArraTemp);
				arra[7] = striEqu;
				valu = striEqu;
			}else{
				valu = arra[7];
			}**/
			valu = arra[7];
		}
			
	}
	else if ( tablView == incoTabl ) {
		var arra= [[incoArra objectAtIndex:rowInde] valueList];
		if ( [headStri isEqualToString:@"Severidad"] )
			valu = arra[0];
		else if ( [headStri isEqualToString:@"Inconsistencia"] )
			valu = arra[1];
		else if ( [headStri isEqualToString:@"ID1"] )
			valu = arra[2];
		else if ( [headStri isEqualToString:@"Locacion1"] )
			valu = arra[3];
		else if ( [headStri isEqualToString:@"Fecha1"] )
			valu = arra[4];
		else if ( [headStri isEqualToString:@"ID2"] )
			valu = arra[5];
		else if ( [headStri isEqualToString:@"Locacion2"] )
			valu = arra[6];
		else if ( [headStri isEqualToString:@"Fecha2"] )
			valu = arra[7];
	}
	
	return valu;
}


@end





@implementation model_eventsDefinitions : RMControllerObject {
      CPString        recoId             @accessors;
      CPString        acts               @accessors;
      CPString        seriId             @accessors;
      CPString        initDate           @accessors; 
      CPString        enddDate           @accessors;
      CPString        pers               @accessors;
      CPString        eqps               @accessors;
      CPString        dura               @accessors;
      CPString        orga               @accessors;


      CPString        	   starDate       @accessors;
      CPString        	   starHour       @accessors;
      CPString             starMinu       @accessors;
      CPString             evntComm       @accessors;
      CPString             seriComm       @accessors;
}



- (id) getActivities {
    var arra = [acts componentsSeparatedByString:@"|"];
	var coun = [arra count];
    var resuArra = [[CPArray alloc] init];     
    
    for (var i = 0; i < coun; i++) {
    	var objt = [arra objectAtIndex:i];
    	if (objt != ""){
    		[resuArra addObject:objt];    		
    	}
    }
    
    return resuArra;

}



- (id) getEquipments {
    var arra = [eqps componentsSeparatedByString:@"|"];
    var coun = [arra count];
    var resuArra = [[CPArray alloc] init];     
    
    for (var i = 0; i < coun; i++) {
    	var objt = [arra objectAtIndex:i];
    	if (objt != ""){
    		[resuArra addObject:objt];    		
    	}
    }
    
    return resuArra;

}



- (id) getPersons {
    var arra = [pers componentsSeparatedByString:@"|"];
    var coun = [arra count];
    var resuArra = [[CPArray alloc] init];     
    
    for (var i = 0; i < coun; i++) {
    	var objt = [arra objectAtIndex:i];
    	if (objt != ""){
    		[resuArra addObject:objt];    		
    	}
    }
    
    return resuArra;

}



- (id) getEndDate:(id)_dateX {
      
}



- (id) init:(id)paraAppCont eventId:(int)_evenId{
	self = [super init];
	//alert("Levantando el objeto de definiciones de series");
	appCont = paraAppCont;
	dataBase = [appCont getDataBase];
	[self cgiSetHost:[appCont cgiHost] server:[appCont cgiServ]];
    var quer = [CPString stringWithFormat:@"SELECT * FROM %@.eventsPermanent WHERE id=%d",dataBase,_evenId];
    var resuArra = [self query:quer];
    var reco = [[resuArra objectAtIndex:0] valueList];

    recoId     	= reco[0];
    seriId     	= reco[1];
    //evenIden   	= reco[2];
    initDate   	= reco[3];
    enddDate   	= reco[4];
    //titl   		= reco[5];
    //sour        = reco[6];
    acts     	= reco[7];
    pers    	= reco[8];
    //loca   		= reco[9];
    //bill        = reco[11];
    //type        = reco[12];
    //lati        = reco[13];
    //long        = reco[14];
    eqps     	 = reco[15];
    orga         = [[reco[10] componentsSeparatedByString:@":"] objectAtIndex:0];
    orga         = [orga stringByReplacingOccurrencesOfString:@"|" withString:@""];
    evntComm     = reco[18];
    seriComm     = reco[19];

    starDate = [initDate substringToIndex:10];
    //console.log("FECHA EVENTO: " + starDate);
    var fechArra = [initDate componentsSeparatedByString:@" "];
    var fechTime = [fechArra objectAtIndex:1];
    var horaArra = [fechTime componentsSeparatedByString:@":"];
    //console.log("HORA EVENTO: " + fechTime);
    starHour = [horaArra objectAtIndex:0];
    starMinu = [horaArra objectAtIndex:1];

    var seriModl = [[model_seriesDefinitions alloc] init:appCont Serie:[seriId intValue]];
    dura         = [seriModl dura];

    return self;
}

@end



@implementation model_seriesDefinitions : RMControllerObject {

      CPString        recoId             @accessors;
      CPString        inseDate           @accessors;
      CPString        type               @accessors;
      CPString        titl               @accessors;
      CPString        orga               @accessors;
      CPString        loca               @accessors;
      CPString        acts               @accessors;
      CPString        evenIden           @accessors;
      CPString        seriId             @accessors;
      CPString        starDate           @accessors;
      CPString        starHour           @accessors;
      CPString        starMinu           @accessors;

      CPString        dura               @accessors;
      CPString        pric               @accessors;
      CPString        cale               @accessors;

      CPString        freq               @accessors;
      CPString        evnts              @accessors;
      CPString        pers               @accessors;
      CPString        eqps               @accessors;
}



- (id) getActivities {

	var quer = [CPString stringWithFormat:@"Select oa.description,oa.duration,oa.price,oa.id from %@.organizationActivities as oa inner join %@.serieActivity as sa on oa.id = sa.idActivity where idSerie = %@ ;",dataBase,dataBase,recoId];
    var arra = [self query:quer];

    var coun = [arra count];
    var resuArra = [[CPArray alloc] init];     
    
    for (var i = 0; i < coun; i++) {
    	var valuList = [arra[i] valueList];
    	var objt = valuList[0];
    	if (objt != ""){
    		[resuArra addObject:objt];    		
    	}
    }
    return resuArra;
}



- (id) getEquipments {
    var quer = [CPString stringWithFormat:@"Select e.id0,e.id1,e.make,e.model,e.year,e.typeId from %@.equipment  as e inner join %@.serieEquipment as se on e.id0 = se.idEquipment where  se.idSerie = %@ order by make,model,year",
    	dataBase,dataBase,recoId];
    var equipArraTemp = [self query:quer];
    var coun = [equipArraTemp count];
    var resuArra = [[CPArray alloc] init];     
    
    for (var i = 0; i < coun; i++) {
    	var valuList = [equipArraTemp[i] valueList];
		var iden0 = valuList[0];
		var iden1 = valuList[1];
		var make = valuList[2];
		var mode = valuList[3];
		var year = valuList[4];
    	var objt = [CPString stringWithFormat:@"%@_%@_%@_%@:%@",make,mode,year,iden1,iden0];
    	if (objt != ""){
    		[resuArra addObject:objt];    		
    	}
    }
    
    return resuArra;

}



- (id) getPersons {
    var quer = [CPString stringWithFormat:@"Select p.id,p.nameLast,p.nameFirst,op.position from %@.persons as p inner join %@.organizationPersons as op on p.Id = op.personId inner join %@.seriePerson as sp on p.Id = sp.idPerson where sp.idSerie= %@ order by p.nameLast,p.nameFirst ASC",
    	dataBase,dataBase,dataBase,recoId];
    var personArraTemp = [self query:quer];
    var resuArra = [[CPArray alloc] init];     
    var coun = [personArraTemp count];
    for (var i = 0; i < coun; i++) {
    	var valuList = [personArraTemp[i] valueList];
		var emplIden = valuList[0];
		var nameLast = valuList[1];
		var nameFirs = valuList[2];
		var posi     = [valuList[3] substringToIndex:1];
    	var objt = [CPString stringWithFormat:@"%@, %@ [%@]:%@",nameLast,nameFirs,posi,emplIden];
    	if (objt != ""){
    		[resuArra addObject:objt];    		
    	}
    }
    return resuArra;
}



- (id) init:(id)paraAppCont Serie:(int)_seriId {
	self = [super init];

	appCont = paraAppCont;
	dataBase = [appCont getDataBase];
	[self cgiSetHost:[appCont cgiHost] server:[appCont cgiServ]];

    var quer = [CPString stringWithFormat:@"SELECT * FROM %@.scheduleSeriesDefinitions WHERE id=%d ",dataBase,_seriId];
    //alert("select seriesDefi " + quer);
    var resuArra = [self query:quer];
    var coun = [resuArra count];
    if (coun > 0) {
    	var reco = [[resuArra objectAtIndex:0] valueList];

   		 recoId     	= reco[0];
    	inseDate   	= reco[1];
	    type      	= reco[2];
	   	 titl   		= reco[3];
    	orga   		= reco[4];
	    loca   		= reco[5];
    	acts   		= reco[6];
	    evenIden   	= reco[7];

    	seriId     	= reco[0];
	    starDate   	= reco[9];
    	starHour   	= reco[10];
	    starMinu   	= reco[11];
    	dura   		= reco[12];
	    pric    	= reco[13];

    	cale     	= reco[14];
	    freq    	= reco[15];
    	evnts       = reco[16];
	    pers    	= reco[17];

    	eqps    	= reco[18];
    }/*else{
 	    alert("count = 0");
    }*/
    
    

	return self;
}

@end





