package com.androidbegin.buttonclicktutorial;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar.LayoutParams;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import android.widget.CheckBox;

public class AddEvent02 extends Activity
{

	private Button btnStartTime = null;
	private Calendar dateStart = null;
	
	private String date_event;
	
    
    LinearLayout layout1;
    private static int viewsCount = 0;
    private List<View> allViews = new ArrayList<View>();
    LinearLayout.LayoutParams params;
    
    
	//fields
		private static String sStrSelect = "Select time";
		private static String sStrSet = "set";
		private static String sStrNone = "none";
		
		//fields
		public static final int SELECT_TIME_REQUEST = 112;
		public static final int iSliderViewWidth = 276;
		private static final int iSmallButtonWidth = 100;	
		
		//fields
		private LinearLayout layContent = null;
		private LinearLayout layContent2 = null;
		
		
		private Button btnNone = null;
		private Button btnOK = null;
		
		//fields
		private boolean bNoneButton = true;
		private boolean b24HourMode = false;
		private int start_hour = -1;
		private int start_minutes = -1;
		private int end_hour = -1;
		private int end_minutes = -1;
		
		
		
		private TextView infos; 
		CheckBox checkBox;
		
		TimeWidgetSlider start_timeSliderHour = null;
		TimeWidgetSlider start_timeSliderMinutes = null;
		TimeWidgetSlider end_timeSliderHour = null;
		TimeWidgetSlider end_timeSliderMinutes = null;
		
		DB_alarm db;
		private SQLiteDatabase dataBase;
		
		ArrayList<appointment> appointment_liste = new ArrayList<appointment>();
		String option_alarm;
		
		
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		//setContentView(R.layout.activity_main);

		db = new DB_alarm(getApplicationContext());

		Bundle extras = getIntent().getExtras();
		date_event = extras.getString("EXTRA");
		
		SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy"); 
   	   	Date date = null;
   	   	try
	    {
   	   		date = sdf.parse(date_event);
		} 
	    catch (ParseException e)
	    {
			e.printStackTrace();
		}
	      
   	   	long toto = date.getTime();
		
        Toast.makeText(getBaseContext(),  date_event , Toast.LENGTH_LONG).show();

        // setContentView(widget());
        ActionBar actionBar = getActionBar();
        getActionBar().setHomeButtonEnabled(true);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("Add rendez-vous");
        
        //http://alvinalexander.com/source-code/android/how-get-android-actionbar-backup-button-work-android-back-button
        //http://www.theappguruz.com/blog/android-working-android-actionbar
        
        layout(); 
        
        //	composants();
        //	v3();
		
/*		
		btnStartTime = (Button)findViewById(R.id.button1);  	
		
		btnStartTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				
	    	//TimeWidget.Open(MainActivity.this, false, false, dateStart.get(Calendar.HOUR_OF_DAY), dateStart.get(Calendar.MINUTE));
	    	//TimeWidget.Open(MainActivity.this, false, false, 14 , 10);
				
				//widget();
				
			}
		});
*/		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) { 
	    switch (item.getItemId()) {
	        case android.R.id.home:
	            // app icon in action bar clicked; go home
	           // return true;
	           // default:
	           // return super.onOptionsItemSelected(item); 
	            
	        	//CalendarCustomView.debug();
	        	
	        	
	            this.finish();
	            return true;
	            default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	public LinearLayout createLayout(int iOrientation)
	  {
			LinearLayout lay = new LinearLayout(this);		
			lay.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			lay.setOrientation(iOrientation);
			return lay;
	  }
	
	 public Button createButton(String sText, int iWidth, int iHeight)
	  {
	  	Button btn = new Button(this);
	  	btn.setText(sText);
	  	btn.setLayoutParams(new LayoutParams(iWidth, iHeight));
	  	return btn;
	  }

	  public TextView createLabel(String sText, int iWidth, int iHeight)
	  {
	  	TextView label = new TextView(this);
	  	label.setText(sText);
	  	label.setLayoutParams(new LayoutParams(iWidth, iHeight));
	  	return label;
	  }
	  
	 /* private void getDataFromSliders()
	  {
	  	start_hour = timeSliderHour.getValue();
	  	start_minutes = timeSliderMinutes.getValue();
	  }
	*/
	 public void generateBottomButtons(LinearLayout layBottomControls)
	  {
	  	TextView labMargin = createLabel("Toto", 8, android.view.ViewGroup.LayoutParams.FILL_PARENT);

	  	btnNone = createButton(sStrNone, iSmallButtonWidth, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);  	
	  	btnNone.setBackgroundResource(android.R.drawable.btn_default_small);
	  	
	  	btnOK = createButton(sStrSet, iSmallButtonWidth, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);  	
	  	btnOK.setBackgroundResource(android.R.drawable.btn_default_small);
	  	
	  	//set events
	  	btnNone.setOnClickListener(new Button.OnClickListener()
	  	{
				public void onClick(View arg0) {
					clearTime();
					OnClose();
			}});

	  	btnOK.setOnClickListener(new Button.OnClickListener()
	  	{
				public void onClick(View arg0)
				{
					//getDataFromSliders();
					OnClose();
			}});
	  	
	  	layBottomControls.setGravity(Gravity.CENTER_HORIZONTAL);  	
	  	if (bNoneButton)
	  	{
	  		layBottomControls.addView(btnNone);
	  		layBottomControls.addView(labMargin);
	  	}
	  	layBottomControls.addView(btnOK);
	  }
	
	 
	 public void composants()
	{
/*		
		 
		 LinearLayout parent = new LinearLayout(this);

		// parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		 
		 
		 LayoutParams linearlayoutlayoutparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 
		 parent.setOrientation(LinearLayout.VERTICAL);

		 
		 
		 setContentView(parent, linearlayoutlayoutparams);
	        // add text view
	        TextView tv = new TextView(this);
	        tv.setText("Dynamic Text!");
	        parent.addView(tv);
	 
	        // add edit text
	        linearlayoutlayoutparams  = new LinearLayout.LayoutParams(
	                LinearLayout.LayoutParams.WRAP_CONTENT,
	                LinearLayout.LayoutParams.WRAP_CONTENT);
	             
	        
	        EditText et = new EditText(this);
	        et.setText("Dynamic EditText!");
	        et.setMinLines(1);
	        et.setMaxLines(3);
	        parent.addView(et); // , linearlayoutlayoutparams);
*/	        
	        
	        
	        
	  
	        //LinearLayout myLInearLayout = null;
	        TextView valueTV;
	        Button valueB;
	        
	        LinearLayout myLInearLayout = new LinearLayout(this);	         
	        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
	        myLInearLayout.setOrientation(LinearLayout.VERTICAL);
	        
	        
	        LayoutParams lparams = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	        
	        setContentView(myLInearLayout, lparams);
		    
	         
	        //add textView
	        valueTV = new TextView(this);
	        valueTV.setText("The developer ");
	        valueTV.setId(5);
	        valueTV.setX(50);
	        valueTV.setY(415);
	        
	       //** valueTV.setPadding(200, 20, 20, 20);
	        
	        //valueTV.setGravity(Gravity.CENTER_HORIZONTAL);
	        
	       // valueTV.setLayoutParams(params);
	         
	        // add Button
	        valueB = new Button(this);
	        valueB.setText("thedeveloperworldisyours");
	        valueB.setId(55);
	         
	        //add the textView and the Button to LinearLayout
	        myLInearLayout.addView(valueTV);
	       // myLInearLayout.addView(valueB);
	        
	}
	 
	 /**********************************************/	 
	public void v2()
	{
		LinearLayout linLayout = new LinearLayout(this);
        linLayout.setOrientation(LinearLayout.VERTICAL);
        LayoutParams linLayoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); 
        setContentView(linLayout, linLayoutParam);
         
        LayoutParams lpView = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
         
        TextView tv = new TextView(this);
        tv.setText("TextView");
        tv.setLayoutParams(lpView);
        linLayout.addView(tv);
         
        Button btn = new Button(this);
        btn.setText("Button");
        linLayout.addView(btn, lpView);
 
         
        LinearLayout.LayoutParams leftMarginParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        leftMarginParams.leftMargin = 50;
         
        Button btn1 = new Button(this);
        btn1.setText("Button1");
        linLayout.addView(btn1, leftMarginParams);
 
         
        LinearLayout.LayoutParams rightGravityParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        rightGravityParams.gravity = Gravity.RIGHT;
         
        Button btn2 = new Button(this);
        btn2.setText("Button2");
        linLayout.addView(btn2, rightGravityParams);
	}

	/**********************************************/	 
	public void v3()
	{
		 LinearLayout lm = new LinearLayout(this);
		 lm.setOrientation(LinearLayout.VERTICAL);
		 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		 setContentView(lm, params);
		 
	        //Create four 
	        for(int j=0;j<=4;j++) 
	        {   
	            // Create LinearLayout
	           LinearLayout ll = new LinearLayout(this);
	            ll.setOrientation(LinearLayout.HORIZONTAL);
	             
	            // Create TextView
	            TextView product = new TextView(this);
	            product.setText(" Product"+j+"    ");
	            ll.addView(product);
	             
	            // Create TextView
	            TextView price = new TextView(this);
	            price.setText("  $"+j+"     ");
	            ll.addView(price);
	             
	            // Create Button
	            final Button btn = new Button(this);
	                // Give button an ID
	                btn.setId(j+1);
	                btn.setText("Add To Cart");
	                // set the layoutParams on the button
	                btn.setLayoutParams(params);
	                 
	                final int index = j;
	                // Set click listener for button
	                btn.setOnClickListener(new OnClickListener() {
	                    public void onClick(View v) {
	                         
	                        Log.i("TAG", "index :" + index);
	                         
	                        Toast.makeText(getApplicationContext(), 
	                                "Clicked Button Index :" + index, 
	                                Toast.LENGTH_LONG).show();
	                         
	                    }
	                });
	                 
	               //Add button to LinearLayout
	                ll.addView(btn);
	               //Add button to LinearLayout defined in XML
	                lm.addView(ll);  
	        }
	}
	
	/**********************************************/
	
	public void layout()
	{
		
		LinearLayout layMain = createLayout(LinearLayout.VERTICAL);  	
 		layMain.setPadding(8, 8, 8, 8);
 		
 		ScrollView scrollView= new ScrollView(this);
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);               
        
    	LinearLayout layMargin = createLayout(LinearLayout.HORIZONTAL);
 		LinearLayout layMargin2 = createLayout(LinearLayout.HORIZONTAL);
 		
 		layMargin.getLayoutParams().height = 18;
 		layMargin2.getLayoutParams().height = 18;
        
 		/**/
 		LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(0); 
 		/**/
 		ImageView imageView = new ImageView(this);
 		imageView.setImageResource(R.drawable.appointment);
 		LayoutParams layoutParams=new LayoutParams(75, 75);
 	    layoutParams.setMargins(10,10,0,0);
 	    imageView.setLayoutParams(layoutParams);
 		/**/
 	    ll.addView(imageView);
        mainLayout.addView(ll);
        
        /**/
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(1); 
 		/**/
        TextView tv = new TextView(this);
        tv.setText("Evenement");
        tv.setPadding(10, 10, 0, 0);
        /**/
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
        /**/
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(2); 
 		/**/
        final EditText editText = new EditText(this);
        //editText.setText(titre);
        layoutParams=new LayoutParams(450, 75);
        editText.setLayoutParams(layoutParams);
        editText.setSingleLine(true);
        editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(20) });
        /**/
 	    ll.addView(editText);
        mainLayout.addView(ll);
        
        /**/
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(3); 
 		/**/
        tv = new TextView(this);
        String tmp = "Date : " + date_event;
        tv.setText(tmp);
        tv.setPadding(10, 30, 0, 30);
        /**/
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
        /**/
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(4); 
 		/**/
        tv = new TextView(this);
        tv.setText("Start Time");
        tv.setPadding(10, 10, 0, 30);
        /**/
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
        start_timeSliderHour = new TimeWidgetSlider(this, true, TimeWidgetSlider.STYPE_HOURS, iSliderViewWidth); // 24 heures 
		start_timeSliderMinutes = new TimeWidgetSlider(this, b24HourMode, TimeWidgetSlider.STYPE_MINUTES, iSliderViewWidth);
		
		//start_timeSliderHour.setValue(starthour,true);
	  	//start_timeSliderMinutes.setValue(startminute, true);
	  	
		/**/
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(5); 
        /**/
        ll.addView(start_timeSliderHour);
        ll.addView(layMargin);
        ll.addView(start_timeSliderMinutes);
        ll.setPadding(100, 0, 0, 10);
		/**/
        mainLayout.addView(ll);
		
    	end_timeSliderHour = new TimeWidgetSlider(this, true, TimeWidgetSlider.STYPE_HOURS, iSliderViewWidth); // 24 heures 
		end_timeSliderMinutes = new TimeWidgetSlider(this, b24HourMode, TimeWidgetSlider.STYPE_MINUTES, iSliderViewWidth);
		
		//end_timeSliderHour.setValue(endhour, true);
	  	//end_timeSliderMinutes.setValue(endminute, true);
		
		  
        /**/
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(6); 
        /**/
        tv = new TextView(this);
        tv.setText("End Time");
        tv.setPadding(10, 10, 0, 10);
        /**/
 	    ll.addView(tv);
        mainLayout.addView(ll);
		
        /**/
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(7); 
        /**/
        ll.addView(end_timeSliderHour);
        ll.addView(layMargin2);
        ll.addView(end_timeSliderMinutes);
        ll.setPadding(100, 0, 0, 10);
		/**/
		mainLayout.addView(ll);
        
		
		/**/
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(8); 
        /**/
        checkBox = new CheckBox(this);
        checkBox.setId(800);
        checkBox.setText("Alarm");
        checkBox.setPadding(10, 10, 50, 10);
        /**/
 	    ll.addView(checkBox);

 	    final Spinner Spinner_alarm = new Spinner(this);  
        Spinner_alarm.setId(900);
        Spinner_alarm.setPadding(10, 10, 0, 10);
        layoutParams=new LayoutParams(125, 75);
        Spinner_alarm.setLayoutParams(layoutParams);
        List<String> myArraySpinner = new ArrayList<String>();
        myArraySpinner.add("15mn");
        myArraySpinner.add("1H");
        myArraySpinner.add("Boom");     
        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, myArraySpinner);
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
        Spinner_alarm.setAdapter(spinnerArrayAdapter);
        Spinner_alarm.setVisibility(View.INVISIBLE); // hide
 	    ll.addView(Spinner_alarm);
        mainLayout.addView(ll);
        
        
        
        /**/
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(9); 
        /**/
        tv = new TextView(this);
        tv.setText("Phone");
        tv.setPadding(10, 10, 0, 10);
        /**/
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
        
        /**/
 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(10); 
 		/**/
        EditText editText_phone = new EditText(this);
        editText_phone.setId(100);
        //editText.setText(titre);
        layoutParams=new LayoutParams(300, 75);
        editText_phone.setLayoutParams(layoutParams);
        editText_phone.setSingleLine(true);
        editText_phone.setFilters(new InputFilter[] { new InputFilter.LengthFilter(10) });
        editText_phone.setInputType(InputType.TYPE_CLASS_PHONE);
        /**/
 	    ll.addView(editText_phone);
 	  
 	    //Button btn_phone = new Button(this);
 	    //btn_phone.setPadding(0,0,0,0);
 	    //btn_phone.setText("Call");
        //ll.addView(btn_phone);
        /**/
        mainLayout.addView(ll);
		
		 /**/
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(8); 
        /**/
        tv = new TextView(this);
        tv.setText("Notes");
        tv.setPadding(10, 10, 0, 10);
        /**/
 	    ll.addView(tv);
        mainLayout.addView(ll);
		
        /**/
        ll = new LinearLayout(this);
       	ll.setOrientation(LinearLayout.VERTICAL);
       	ll.setTag(9); 
        /**/
       	final View childView = getLayoutInflater().inflate(R.layout.notes_view, null);
        /**/
        ll.addView(childView);
        mainLayout.addView(ll);
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setGravity(Gravity.CENTER);
       
        Button b1 = new Button(this);
        b1.setId(1);
        b1.setText("Valider");
        ll.addView(b1);
        
        Button b2 = new Button(this);
        b2.setId(2);
        b2.setText("Exit");
        ll.addView(b2);

        mainLayout.addView(ll);
        
        /** appliquer le code dans la vue ***/
        scrollView.addView(mainLayout);
        layMain.addView(scrollView);
        setContentView(layMain);
        /*****/

        
        Button btn_valider = (Button) findViewById(1);
        btn_valider.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
 					start_hour = start_timeSliderHour.getValue();
				  	start_minutes = start_timeSliderMinutes.getValue();
				  	end_hour = end_timeSliderHour.getValue();
				  	end_minutes = end_timeSliderMinutes.getValue();
				  	
				  	// creation des dates
				  	String[] items = date_event.split(" ");
				  	// jour mois annee
				  	int jour = Integer.parseInt(items[0]);
				  	int mois = Integer.parseInt(items[1]);
				  	int annee = Integer.parseInt(items[2]);
				  	mois = mois - 1;
				  	
					Calendar cal_date = Calendar.getInstance();
					cal_date.set(Calendar.YEAR, annee);
					cal_date.set(Calendar.DAY_OF_MONTH, jour);
					cal_date.set(Calendar.MONTH, mois);
					cal_date.set(Calendar.HOUR_OF_DAY, 0);
					cal_date.set(Calendar.MINUTE, 0);
					cal_date.set(Calendar.SECOND, 0);
					cal_date.set(Calendar.MILLISECOND, 0);
			        Date Date_date =  cal_date.getTime();
			        long date = cal_date.getTimeInMillis();
				  			
				  	Calendar cal_start = Calendar.getInstance();
			        cal_start.set(annee,mois,jour,start_hour, start_minutes);
			        cal_start.set(Calendar.SECOND, 0);
			        cal_start.set(Calendar.MILLISECOND, 0);
			        Date Date_start =  cal_start.getTime();
			        long startTime = cal_start.getTimeInMillis();
			        
			    	Calendar cal_end = Calendar.getInstance();
			        cal_end.set(annee,mois,jour, end_hour, end_minutes);
			        cal_end.set(Calendar.SECOND, 0);
			        cal_end.set(Calendar.MILLISECOND, 0);
			        Date Date_end =  cal_end.getTime();
			        long endTime = cal_end.getTimeInMillis();
			        
			        String titre = editText.getText().toString();

			        EditText phone = (EditText)findViewById(100);  
			        String string_phone = phone.getText().toString();
			        
			        EditText notes = (EditText)findViewById(R.id.notes);  
			        String string_notes = notes.getText().toString();
			        
			        boolean check = validation(titre, startTime, endTime);
			        //boolean overlap = non_recouvrement(startTime, endTime);
			        
			        if(check == true)
			        {
			        	checkBox = (CheckBox) findViewById(800);
				        Boolean checkBoxState = checkBox.isChecked();
				        if(checkBoxState == true)
				        {
					        option_alarm = Spinner_alarm.getSelectedItem().toString();
				        }
				        else
				        {
				        	option_alarm = "";
				        }
			        	
			        	
			        	long id = db.insert_appoitment(titre, date, startTime, endTime, string_phone , string_notes , "actif");
			        	Toast.makeText(getApplicationContext(), "DEbug ----- Rendez-vous pris en compte", Toast.LENGTH_LONG).show();
			        	
			        	
			        	
			    		Intent service = new Intent(AddEvent02.this, AlarmService.class);
			    		service.putExtra("ALARMID", String.valueOf(id));
			    		service.putExtra("startTime", startTime);
			    		service.setAction(AlarmService.POPULATE);
			    		startService(service);

			        	
			        	
					  	// fermer l'activity
						OnClose();  
			        }
			        
 				}
 	    });
        
        
        CheckBox_AlarmListener(Spinner_alarm);

        
        Button btn_quitter = (Button) findViewById(2);
        btn_quitter.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
 					finish();
 				}
 	    });
        
	}
	
	
	
	public void CheckBox_AlarmListener(final Spinner option_alarm)
	{
			checkBox = (CheckBox) findViewById(800);
	
			checkBox.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v)
				{
		                //is chkIos checked?
					if (((CheckBox) v).isChecked())
					{	 
						option_alarm.setVisibility(View.VISIBLE); 

//						Toast.makeText(AddEvent02.this, "Checkbox", Toast.LENGTH_LONG).show();
					}
					else
					{
						option_alarm.setVisibility(View.INVISIBLE); // hide

					}
				}
			});

	}
	
	/*********************************************/
	
	public boolean validation(String titre,long startTime, long endTime)
	{
		
		 ArrayList<String> list_error = new ArrayList<String>();
		
		 if(titre.equals("") )
	     {
			 list_error.add("Pas de titre !!!");
	         //Toast.makeText(getApplicationContext(), "Vides ???", Toast.LENGTH_LONG).show();
	     }

	     if (startTime >=  endTime)
	     {
	    	 list_error.add("Incohérence : fin avant le début !!!!");
        	 //Toast.makeText(getApplicationContext(), "Probléme Date !!!!", Toast.LENGTH_LONG).show();
	     }
	        
	        
	     if ( endTime - startTime < 1800000 ) // 30 min : 60 * 1000 * 30  = 1800000
	     {
	    	 list_error.add("Rendez-vous inférieur à 30min !!!");
	         //Toast.makeText(getApplicationContext(), "Rendez-vous inférieur à 30min !!! ", Toast.LENGTH_LONG).show();
	     }
	     
	     
	     boolean overlap = non_recouvrement(startTime, endTime);
	     if(overlap == true)
	     {
	    	 list_error.add("Attention overlap !!!");
	     }
	     
	     
	     if(list_error.size() == 0 )
	     {	 
	     	 return true;
	     }
	     else
	     {
		        String toto = "";	
	    	 
	    	 	for(int x = 0; x <= list_error.size() - 1 ; x++)
	    	 	{
	    	   	 		toto = toto + list_error.get(x);
	    	   	 		toto = toto + System.getProperty("line.separator");
	    	 	}
	    	 	
		    	Toast.makeText(getApplicationContext(), toto, Toast.LENGTH_LONG).show();

		    	return false; 
	     }
	}
	
	/********************************************/
	public boolean non_recouvrement(long borne_startTime, long borne_endTime)
	{
  			// plage qui se chevauche - overlap
		
			SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy"); 
 	   	  	Date date = null;
 	   	  	try
 	   	  	{
 	   	  		date = sdf.parse(date_event);
 	   	  	} 
 	   	  	catch (ParseException e)
 	   	  	{
				e.printStackTrace();
 	   	  	}
	      
 	   	  	long timestamp = date.getTime();
		 	String stimestamp = String.valueOf(timestamp);
		         
		    String requete = "SELECT * FROM table_appointment WHERE date = " + stimestamp ;
		     	
		    Cursor Cursor = db.DB_query(requete);
		    int val = Cursor.getCount();
		   
		    boolean overlap = false;
		    		
		    if(val != 0)
		    {
		    			if (Cursor.moveToFirst()) 
		 				{
			 					do 
			 					{
				 						String string_start_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_START_TIME ));
				 						String string_end_timestamp = Cursor.getString(Cursor.getColumnIndex(DB_alarm.COL_END_TIME ));
				 						
				 						//String s = "ggg " + start_timestamp;
				 						//long ll = Long.parseLong(start_timestamp);   
				 						
				 						long start_timestamp = Long.parseLong(string_start_timestamp);   
				 						long end_timestamp = Long.parseLong(string_end_timestamp);   
				 						
				 						if(  borne_startTime >= start_timestamp && borne_startTime <= end_timestamp  )
				 						{
				 							overlap = true;
				 						}
				 						
				 						
				 						if(  borne_endTime >= start_timestamp && borne_endTime <= end_timestamp  )
				 						{
				 							overlap = true;
				 						}
				 						
				 						
				 						if( borne_startTime <=  start_timestamp && borne_endTime >= end_timestamp)
				 						{
				 							overlap = true;
				 						}
			 						
			 					} while (Cursor.moveToNext());
			 					
		 				}
		    			
		    			
		 		}
		    	
		    
		    	return overlap;
	}
	
	
	/********************************************/
	
	public View widget()
	{
		
	 		LinearLayout layMain = createLayout(LinearLayout.VERTICAL);  	
	 		layMain.setPadding(8, 8, 8, 8);

	 		LinearLayout layTopControls = createLayout(LinearLayout.HORIZONTAL);
	 		LinearLayout layContentTop = createLayout(LinearLayout.HORIZONTAL);
	 		LinearLayout layContentBottom = createLayout(LinearLayout.HORIZONTAL);
	 		LinearLayout layBottomControls = createLayout(LinearLayout.HORIZONTAL);
	 		LinearLayout layMargin = createLayout(LinearLayout.HORIZONTAL);
	 		LinearLayout layMargin2 = createLayout(LinearLayout.HORIZONTAL);
	 		
	 		layContent = createLayout(LinearLayout.VERTICAL);
	  	
	 		layContent2 = createLayout(LinearLayout.VERTICAL);
	 		
		  	
	 		// 	layTopControls.addView(createLabelCaption());  	
	 		layTopControls.setGravity(Gravity.CENTER_HORIZONTAL);
	  	
	 		//generateBottomButtons(layBottomControls);

	 		layContentTop.getLayoutParams().height = 16;
	 		layContentBottom.getLayoutParams().height = 18;
	 		layMargin.getLayoutParams().height = 18;
	 		layMargin2.getLayoutParams().height = 18;
			
	        TextView tv = new TextView(this);
	        tv.setText("Evenement++++");
	        //tv.setFilters(new InputFilter[] { new InputFilter.LengthFilter(7) }); // length
	        
	        int maxLength = 3;
	        InputFilter[] FilterArray = new InputFilter[1];
	        FilterArray[0] = new InputFilter.LengthFilter(maxLength);
	        tv.setFilters(FilterArray);
	        
	        tv.setPadding(10, 0, 0, 0);
	        layMain.addView(tv);
	        
	        final EditText editText = new EditText(this);
	        editText.setId(viewsCount++);
	        editText.setHint("Titre");
	        editText.setSingleLine(true);
	        layMain.addView(editText);
	        
	        tv = new TextView(this);
	        String tmp = "Date : " + date_event;
	        tv.setText(tmp);
	        tv.setPadding(10, 30, 0, 30);
	        layMain.addView(tv);
			
	        tv = new TextView(this);
	        tv.setText("Start Time");
	        tv.setPadding(10, 10, 0, 30);
	        layMain.addView(tv);
	        
	        
			start_timeSliderHour = new TimeWidgetSlider(this, true, TimeWidgetSlider.STYPE_HOURS, iSliderViewWidth); // 24 heures 
			start_timeSliderMinutes = new TimeWidgetSlider(this, b24HourMode, TimeWidgetSlider.STYPE_MINUTES, iSliderViewWidth);

			end_timeSliderHour = new TimeWidgetSlider(this, true, TimeWidgetSlider.STYPE_HOURS, iSliderViewWidth); // 24 heures 
			end_timeSliderMinutes = new TimeWidgetSlider(this, b24HourMode, TimeWidgetSlider.STYPE_MINUTES, iSliderViewWidth);

			
			layContent.addView(start_timeSliderHour);
			layContent.addView(layMargin);
			layContent.addView(start_timeSliderMinutes);
	        layContent.setPadding(100, 0, 0, 60);
	        layMain.addView(layContent);
	        
	        tv = new TextView(this);
	        tv.setText("End Time");
	        tv.setPadding(10, 10, 0, 30);
	        layMain.addView(tv);
	        
	        
	        layContent2.addView(end_timeSliderHour);
		 	layContent2.addView(layMargin2);
			layContent2.addView(end_timeSliderMinutes);
	        layContent2.setPadding(100, 0, 0, 60);
	        layMain.addView(layContent2);
		        
	        
	        LinearLayout ll = new LinearLayout(this);
	        ll.setOrientation(LinearLayout.VERTICAL);
	        
	        /**/
	        ll = new LinearLayout(this);
	        ll.setOrientation(LinearLayout.VERTICAL);
	        ll.setTag(8); 
	        /**/
	        tv = new TextView(this);
	        tv.setText("Notzzzzzes");
	        tv.setPadding(10, 10, 0, 10);
	        /**/
	        layMain.addView(tv);
	 	    //ll.addView(tv);
	        //mainLayout.addView(ll);
	        
			
	        /**/
//	        ll = new LinearLayout(this);
//	       	ll.setOrientation(LinearLayout.VERTICAL);
//	       	ll.setTag(9); 
	        /**/
	       	final View childView = getLayoutInflater().inflate(R.layout.notes_view, null);
	        /**/
//	        ll.addView(childView);
	        layMain.addView(childView);
	        
         
	        Button btn = new Button(this);
	        btn.setText("Ajouter");
	        layMain.addView(btn);
	        
	       
	      	btn.setOnClickListener(new Button.OnClickListener()
		  	{
					public void onClick(View arg0)
					{
						start_hour = start_timeSliderHour.getValue();
					  	start_minutes = start_timeSliderMinutes.getValue();
					  	end_hour = end_timeSliderHour.getValue();
					  	end_minutes = end_timeSliderMinutes.getValue();
					  	
					  	// creation des dates
					  	
					  	String[] items = date_event.split(" ");
					  	// jour mois annee
					  	int jour = Integer.parseInt(items[0]);
					  	int mois = Integer.parseInt(items[1]);
					  	int annee = Integer.parseInt(items[2]);
					  	mois = mois - 1;
					  	
						Calendar cal_date = Calendar.getInstance();
						cal_date.set(Calendar.YEAR, annee);
						cal_date.set(Calendar.DAY_OF_MONTH, jour);
						cal_date.set(Calendar.MONTH, mois);
						cal_date.set(Calendar.HOUR_OF_DAY, 0);
						cal_date.set(Calendar.MINUTE, 0);
						cal_date.set(Calendar.SECOND, 0);
						cal_date.set(Calendar.MILLISECOND, 0);
				        Date Date_date =  cal_date.getTime();
				        long date = cal_date.getTimeInMillis();
					  			
					  	Calendar cal_start = Calendar.getInstance();
				        cal_start.set(annee,mois,jour,start_hour, start_minutes);
				        cal_start.set(Calendar.SECOND, 0);
				        cal_start.set(Calendar.MILLISECOND, 0);
				        Date Date_start =  cal_start.getTime();
				        long startTime = cal_start.getTimeInMillis();
				        
				    	Calendar cal_end = Calendar.getInstance();
				        cal_end.set(annee,mois,jour, end_hour, end_minutes);
				        cal_end.set(Calendar.SECOND, 0);
				        cal_end.set(Calendar.MILLISECOND, 0);
				        Date Date_end =  cal_end.getTime();
				        long endTime = cal_end.getTimeInMillis();
				        
				        String titre = editText.getText().toString();
				        
				        // stockage
/////////////////				       // db.insert_appoitment(titre, date, startTime, endTime,"actif");
					  	
						
					  	// fermer l'activity
						OnClose();  // 9h30 à 12h55
			}});
		  	
	  	
	  //	layMain.addView(layContentBottom);
	 // 	layMain.addView(layBottomControls);  	

	  	return layMain;
		
	}
	
	public void OnClose()
	{
		Bundle data = new Bundle();
		data.putInt("Hour", start_hour);
		data.putInt("Minute", start_minutes);
    
		Intent intentData = new Intent("");
		intentData.putExtras(data);
		setResult(RESULT_OK, intentData);
		
		this.finish();
	}

	public void clearTime()
	{
		start_hour = -1;
		start_minutes = -1;
	}
	

}
