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.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
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.text.format.DateFormat;
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.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
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.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
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 AddEvent03 extends Activity //implements OnClickListener
{

	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_option_delai;
		CheckBox checkBox_option_vibrate;
		CheckBox checkBox_option_ringtone;
		
		
		TimeWidgetSlider start_timeSliderHour = null;
		TimeWidgetSlider start_timeSliderMinutes = null;
		TimeWidgetSlider end_timeSliderHour = null;
		TimeWidgetSlider end_timeSliderMinutes = null;
		
		TextView tv_set_time_start;
		TextView tv_set_time_end;
		
		DB_alarm db;
		private SQLiteDatabase dataBase;
		
		ArrayList<appointment> appointment_liste = new ArrayList<appointment>();
		
		String option_delai = "nodelai";
		String option_vibrate = "novibrate";
		String option_ringtone = "noringtone";
		
		
	    static final int TIME_DIALOG_START = 1200;
	    static final int TIME_DIALOG_END = 1300;
	    	 
		int hour;
		int minute;
		
		int global_start_hour = 0; 
		int global_start_min = 0;

		int global_end_hour = 0; 
		int global_end_min = 0;
		
	@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(); 
        
	}
	
	@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 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(6); 
        /**/
//        tv = new TextView(this);
//        tv.setText("End Time");
//        tv.setPadding(10, 10, 0, 10);
        /**/
// 	    ll.addView(tv);
//        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(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.VERTICAL);
//        ll.setTag(4); 
 		/**/
//        tv = new TextView(this);
//        tv.setText("Start Time");
//        tv.setPadding(10, 10, 0, 30);
        /**/
// 	    ll.addView(tv);
//        mainLayout.addView(ll);
		
		
//		ll = new LinearLayout(this);
//        ll.setOrientation(LinearLayout.VERTICAL);
//        ll.setTag(1234); 
//		TimePicker tp_start = new TimePicker(this); 
//		tp_start.setIs24HourView(true); 
//		tp_start.setForegroundGravity(Gravity.CENTER);
//        tp_start.setCurrentHour(13); 
//        tp_start.setCurrentMinute(27);
        /**/
// 	    ll.addView(tp_start);
//        mainLayout.addView(ll);
        

// 		ll = new LinearLayout(this);
//        ll.setOrientation(LinearLayout.VERTICAL);
//        ll.setTag(4); 
 		/**/
//        tv = new TextView(this);
//        tv.setText("End Time");
//        tv.setPadding(10, 10, 0, 30);
        /**/
// 	    ll.addView(tv);
//        mainLayout.addView(ll);

		
//		ll = new LinearLayout(this);
//        ll.setOrientation(LinearLayout.VERTICAL);
//        ll.setTag(1234); 
//		TimePicker tp_stop = new TimePicker(this); 
//		tp_stop.setIs24HourView(true); 
//		tp_stop.setForegroundGravity(Gravity.CENTER);
//		tp_stop.setCurrentHour(6); 
//        tp_stop.setCurrentMinute(45);
		//tp.setPadding(10, 10, 0, 10);
        /**/
// 	    ll.addView(tp_stop);
//        mainLayout.addView(ll);
        
        
      //  https://www.codota.com/android/methods/android.widget.TimePicker/setCurrentMinute/

 		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);
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        tv_set_time_start = new TextView(this);
        tv_set_time_start.setText("--:--");
        tv_set_time_start.setPadding(10, 10, 50, 30);
 	    ll.addView(tv_set_time_start);
 	    Button btn_start_time = new Button(this);
 	    btn_start_time.setId(144);
 	    btn_start_time.setText("Add");   
 	    ll.addView(btn_start_time);
        mainLayout.addView(ll);

 		ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setTag(4); 
        tv = new TextView(this);
        tv.setText("End Time");
        tv.setPadding(10, 10, 0, 30);
 	    ll.addView(tv);
        mainLayout.addView(ll);
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        tv_set_time_end = new TextView(this);
        tv_set_time_end.setText("--:--");
        tv_set_time_end.setPadding(20, 10, 50, 30);
 	    ll.addView(tv_set_time_end);
 	    Button btn_end_time = new Button(this);
 	    btn_end_time.setId(244);
 	    btn_end_time.setText("Add");   
 	    ll.addView(btn_end_time);
        mainLayout.addView(ll);
        
/******************** option alarme *************************/        
		
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(8); 
 	    
 	   	final TextView tv_delay = new TextView(this);
 	   	tv_delay.setText("Delay");
 	   	tv_delay.setVisibility(View.VISIBLE); 
 	  	tv_delay.setPadding(10, 10, 0, 30);
	   	ll.addView(tv_delay);
 	    
 	    final Spinner Spinner_alarm = new Spinner(this);  
        Spinner_alarm.setId(900);
        Spinner_alarm.setPadding(30, 10, 0, 10);
        layoutParams=new LayoutParams(125, 75);
        layoutParams.width += 50;  //
        Spinner_alarm.setLayoutParams(layoutParams);
        List<String> myArraySpinner = new ArrayList<String>();
        myArraySpinner.add("0min");
        myArraySpinner.add("15min");
        myArraySpinner.add("30min");     
        myArraySpinner.add("1H");
        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.VISIBLE); 
 	    ll.addView(Spinner_alarm);
        mainLayout.addView(ll);
        
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(18); 
 	    checkBox_option_vibrate = new CheckBox(this);
 	    checkBox_option_vibrate.setId(850);
 	    checkBox_option_vibrate.setText("Vibrate");
 	    checkBox_option_vibrate.setPadding(20, 10, 50, 10);
 	    ll.addView(checkBox_option_vibrate);

 	    checkBox_option_ringtone = new CheckBox(this);
 	    checkBox_option_ringtone.setId(870);
 	    checkBox_option_ringtone.setText("Ringtone");
 	    checkBox_option_ringtone.setPadding(20, 10, 50, 10);
 	    ll.addView(checkBox_option_ringtone);
 	    mainLayout.addView(ll);
 	    
 	    
      /* ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(18); 
 	  */  
        RadioGroup rg = new RadioGroup(getApplicationContext());
        rg.setOrientation(RadioGroup.HORIZONTAL);
        rg.setId(1234);
        
        RadioButton rb_ringtone = new RadioButton(getApplicationContext());
        rb_ringtone.setId(1678);
        rb_ringtone.setChecked(true);
        rb_ringtone.setText("Ringtone");
        rb_ringtone.setTextColor(Color.BLACK);
        rg.addView(rb_ringtone);

        // Create another Radio Button for RadioGroup
        RadioButton rb_vibrate = new RadioButton(getApplicationContext());
        rb_vibrate.setId(2678);
        rb_vibrate.setText("Vibrate");
        rb_vibrate.setTextColor(Color.BLACK);
        rg.addView(rb_vibrate);
        
        mainLayout.addView(rg);
 	    
        
/******************** Phone *************************/        
 	    
        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("Ajouter");
        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);
        /*****/
        
        CheckBox_option_vibrate_Listener();
        CheckBox_option_ringtone_Listener();
        
        
        RadioGroup radioGroup=(RadioGroup)findViewById(1234);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() 
        {
            public void onCheckedChanged(RadioGroup arg0, int id) 
            {
	              switch (id) 
	              {
	              		case 1678:
	              			//Toast.makeText(AddEvent03.this, "Ringtone", Toast.LENGTH_SHORT).show();
	              			tv_delay.setVisibility(View.VISIBLE); 
	              			Spinner_alarm.setVisibility(View.VISIBLE); 

	              			break;
	              		case 2678:
	              			//Toast.makeText(AddEvent03.this, "Vibrate", Toast.LENGTH_SHORT).show();
	              			tv_delay.setVisibility(View.INVISIBLE); 
	              			Spinner_alarm.setVisibility(View.INVISIBLE); 
	              			break;
	              }
            }
        });
        
        
        
        //http://supertos.free.fr/supertos.php?page=1127
        
        //addButtonListener();
        
        ButtonListener();

        
        Button btn_valider = (Button) findViewById(1);
        btn_valider.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
				  	start_hour = global_start_hour;
				  	start_minutes = global_start_min;
				  	end_hour = global_end_hour;
				  	end_minutes = global_end_min;
				  	
				  	
				  	// 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 check = true;
			        
			        if(check == true)
			        {
			        	
				    	   long option_delai_valeur = 0; 
				    	   String delai =Spinner_alarm.getSelectedItem().toString();
				    	   
				    	   switch (delai) 
				    	   {
				    	   		case "0min":
			   						option_delai_valeur = 0;
			   						break;
				   				case "15min":
				   					option_delai_valeur = 1000 * 60 * 15;
				   					break;
				   				case "30min":
				   					option_delai_valeur = 1000 * 60 * 30;
				   					break;
				   				case "1H":
				   					option_delai_valeur = 1000 * 60 * 60;
				   					break;
				    	   }
				    	   
					       long id = db.insert_appoitment(titre, date, startTime, endTime, string_phone , string_notes ,  option_delai_valeur,  option_vibrate, option_ringtone , "actif");
				           Toast.makeText(getApplicationContext(), "Rendez-vous pris en compte", Toast.LENGTH_LONG).show();
				    		
					       mois = mois + 1;
					       String dateInString = jour + "-" + mois +  "-" + annee + " " + start_hour + ":" + start_minutes;
						   long  time_millis = Tools.convertir_date_timestamp(dateInString); 
						   
						   // prendre en compte le delai
						   time_millis = time_millis - option_delai_valeur;
						   
						   Intent service = new Intent(AddEvent03.this, AlarmService.class);
						   service.putExtra("ALARMID", id );              
						   service.putExtra("TITRE", titre);
						   service.putExtra("DELAI", option_delai_valeur);
						   //service.putExtra("option_delai", option_delai);
						   service.putExtra("option_vibrate", option_vibrate);
						   service.putExtra("option_ringtone", option_ringtone);
						   service.putExtra("TIME", time_millis);
						   service.setAction(AlarmService.POPULATE);
						   startService(service);  
						   OnClose();  
						   
			        }
			        
			        
 				}
 	    });
        
        
        Button btn_quitter = (Button) findViewById(2);
        btn_quitter.setOnClickListener(new OnClickListener() 
 	    {
 				@Override
 				public void onClick(View arg0) 
 				{
 					finish();
 				}
 	    });
        
	}
	
	public void ButtonListener() 
	{
		
		findViewById(144).setOnClickListener(mGlobal_OnClickListener);
		findViewById(244).setOnClickListener(mGlobal_OnClickListener);
		 
	}
	
	
	//Global On click listener for all views
    OnClickListener mGlobal_OnClickListener = new OnClickListener()
    {
	        public void onClick(final View v)
	        {
	            switch(v.getId())
	            {
	                case 144:
						//Toast.makeText(AddEvent02.this, "un", Toast.LENGTH_LONG).show();
		                //showDialog(TIME_DIALOG_START);
	                	dialog_box_timepicker("Choice start Time", "start");
	                    break;
	                case 244:
	                    //Toast.makeText(AddEvent02.this, "Button2 clicked.", Toast.LENGTH_SHORT).show();
		                //showDialog(TIME_DIALOG_END);
	                	dialog_box_timepicker("Choice end Time", "end");
	                    break;
	            }
	        }
    };
    
	
	
	private TimePickerDialog.OnTimeSetListener timePickerListener_start =  new TimePickerDialog.OnTimeSetListener() 
	{
		public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute)
		{
			hour = selectedHour;
			minute = selectedMinute;
            Toast.makeText(AddEvent03.this, "*********", Toast.LENGTH_SHORT).show();
			tv_set_time_start.setText(new StringBuilder().append(pad(hour))	.append(":").append(pad(minute)));
		}
		
		public void onTimeChanged (TimePicker view,   int hourOfDay, int minute)
		{
            Toast.makeText(AddEvent03.this, "Changed", Toast.LENGTH_SHORT).show();

		}

		
	};
	
	private TimePickerDialog.OnTimeSetListener timePickerListener_end =  new TimePickerDialog.OnTimeSetListener() 
	{
		public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute)
		{
			int hour = selectedHour;
			int minute = selectedMinute;
			//tv_set_time_end.setText(new StringBuilder().append(pad(hour))	.append(":").append(pad(minute)));
		}
		
		//setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTimeChangedListener)
		
		public void onTimeChanged (TimePicker view,   int hourOfDay, int minute)
		{
            Toast.makeText(AddEvent03.this, "Changed", Toast.LENGTH_SHORT).show();

		}
		
	};

	private static String pad(int c)
	{
		if (c >= 10)
		   return String.valueOf(c);
		else
		   return "0" + String.valueOf(c);
	}
	
	/****************************************************************/
	
	private void dialog_box_timepicker(String titre, final String action)
	{
	
		LayoutInflater inflater = getLayoutInflater();
		View alertLayout = inflater.inflate(R.layout.custom_datepicker_layout, null);
    
		final TimePicker tp = (TimePicker) alertLayout.findViewById(R.id.timePicker1);
		
		tp.setIs24HourView(true); 
		
		if(action.equals("start"))
		{
			tp.setCurrentHour(global_start_hour); 
			tp.setCurrentMinute(global_start_min);
		}
		else
		{
			tp.setCurrentHour(global_end_hour); 
			tp.setCurrentMinute(global_end_min);
		}
		
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(titre);
		// this is set the view from XML inside AlertDialog
		alert.setView(alertLayout);
		// disallow cancel of AlertDialog on click of back button and outside touch
		alert.setCancelable(false);
    
		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
			}
		});

		alert.setPositiveButton("Set", new DialogInterface.OnClickListener() 
		{

			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				if(action.equals("start"))
				{	
					global_start_hour = tp.getCurrentHour();
					global_start_min = tp.getCurrentMinute();
	
					tv_set_time_start.setText(new StringBuilder().append(pad(global_start_hour))	.append(":").append(pad(global_start_min)));
				}
				else
				{
					global_end_hour = tp.getCurrentHour();
					global_end_min = tp.getCurrentMinute();
					tv_set_time_end.setText(new StringBuilder().append(pad(global_end_hour))	.append(":").append(pad(global_end_min)));
				}
			}
		});

		AlertDialog dialog = alert.create();
		dialog.show();
	}
	
	/****************************************************************/
	
	
/*	
	public void CheckBox_option_delai_Listener(final Spinner option_alarm)
	{
			checkBox_option_delai = (CheckBox) findViewById(800);
	
			checkBox_option_delai.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v)
				{
		                //is chkIos checked?
					if (((CheckBox) v).isChecked())
					{	 
						option_alarm.setVisibility(View.VISIBLE); 
						option_delai = "delai";
	
						
//						Toast.makeText(AddEvent02.this, "Checkbox", Toast.LENGTH_LONG).show();
					}
					else
					{
						option_alarm.setVisibility(View.INVISIBLE); // hide
						option_delai = "nodelai";


					}
				}
			});

	}
*/	
	public void CheckBox_option_vibrate_Listener()
	{
		
		checkBox_option_vibrate = (CheckBox) findViewById(850);
		
		checkBox_option_vibrate.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v)
			{
                //is chkIos checked?
				if (((CheckBox) v).isChecked())
				{	 
					Toast.makeText(AddEvent03.this, "Vibrate", Toast.LENGTH_LONG).show();
					option_vibrate = "vibrate";
				}
				else
				{
					Toast.makeText(AddEvent03.this, "Silence", Toast.LENGTH_LONG).show();
					option_vibrate = "novibrate";
				}
			}
		});

	}
    

	public void CheckBox_option_ringtone_Listener()
	{
		
		checkBox_option_ringtone = (CheckBox) findViewById(870);
		
		checkBox_option_ringtone.setOnClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v)
			{
                //is chkIos checked?
				if (((CheckBox) v).isChecked())
				{	 
					Toast.makeText(AddEvent03.this, "Ringtone", Toast.LENGTH_LONG).show();
					option_ringtone = "ringtone";
				}
				else
				{
					Toast.makeText(AddEvent03.this, "NoRingtone", Toast.LENGTH_LONG).show();
					option_ringtone = "noringtone";
				}
			}
		});

	}
	
	/*********************************************/
	
	public boolean validation(String titre,long startTime, long endTime)
	{
		
		 ArrayList<String> list_error = new ArrayList<String>();
		
		 long now = System.currentTimeMillis();

		 if(startTime <= now )
		 {
			 list_error.add("Impossible de créer le rendez-vous: Horaire dépassé !");
		 }

		 
		 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 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;
	}
	

}
