package athary.audio.ency;

import info.guardianproject.database.sqlcipher.SQLiteDatabase;
import io.vov.utils.StringUtils;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Pattern;
import android.text.Html;
import android.util.TypedValue;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import athary.audio.ency.R;
import athary.audio.ency.Helpers.data.NewDataDbAdapter;
import athary.audio.ency.Helpers.data.IconContextMenu;
import athary.audio.ency.Helpers.main.Utilities;
import athary.audio.ency.Helpers.search.CustomAdapter;
import athary.audio.ency.Helpers.search.RowData;

public class Search_Activity extends Activity {

//Define Views
private TextView txt_result;
private Button nextresult;
private Button prevresult;
private Button search_btn;
private ExpandableListView ExpandList;
private Spinner spinner2;
private Spinner spinner1;
private TextView TextView02;

//Define Other Variables
private NewDataDbAdapter dbHelper;
private Utilities utils;
private AutoCompleteTextView txt;
private RowData row;
private String searchtxt;
private ArrayList<RowData> ROWS = new ArrayList<RowData>();
ArrayList<String> listItems=new ArrayList<String>();
private ListView ls2;
private CustomAdapter lvAdapter;
private ProgressBar progressBar;
private int count = 0;
private int istart;
private int iend;
private int CODE;
private String SHEEKH, BOOK, CHAPTER, LINE;
private int SEQ;
private String TITLE;
private String URL;
private int OFFSET;
private int DURATION;
private String TXT;
private String TAF;
private SharedPreferences athary;
private String link;
private final int CONTEXT_MENU_ID = 1;
private IconContextMenu iconContextMenu = null;
private final int MENU_ITEM_1_ACTION = 1;
private final int MENU_ITEM_2_ACTION = 2;
private final int MENU_ITEM_3_ACTION = 3;
private final int MENU_ITEM_4_ACTION = 4;
private ArrayAdapter<String> adapter;
private SharedPreferences.Editor AtharyEditor;
private int searchtype = 1;
private int method;
private int saerchfield;
private String searchwords;
private String[] Criterias;
private String searchcriterias;
final Pattern pattern = Pattern.compile("[\u0650\u064D\u064E\u064B\u064F\u064C\u0652\u0651]"); 
private FieldSpinnerAdapter spinadapter;
private CustomSpinnerAdapter typeadapter;
private MyExpandableListAdapter mAdapter;
private static int RESULT_PER_PAGE = 50;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.nsearch);
   
	Intializations();
	itializecontextmenu();
	initIntents();
	initViews();
	Appearance();
	FillViews();
	setListeners();

 }

private void Intializations() {

    athary = getSharedPreferences("athary", 0);
    SQLiteDatabase.loadLibs(this);
  	dbHelper = NewDataDbAdapter.getInstance(this);
    dbHelper.open("Athary412Test412");
	 
	 utils = new Utilities();
	 link = athary.getString("link", "http://www.maknoon.com/download/audios/");
	 method = athary.getInt("METHOD", 4);
	 searchwords = athary.getString("TERMS", "");
	 lvAdapter =  new CustomAdapter(this, ROWS);

}

private void itializecontextmenu(){
	
    Resources res = getResources();
    
    //init the menu
    iconContextMenu = new IconContextMenu(this, CONTEXT_MENU_ID);
    iconContextMenu.addItem(res, "تشغيل المادة الصوتية", MENU_ITEM_1_ACTION);
    iconContextMenu.addItem(res, "إضافة إلى المفضلة", MENU_ITEM_2_ACTION);
    iconContextMenu.addItem(res, "مشاركة الفهرس فقط", MENU_ITEM_3_ACTION);
    iconContextMenu.addItem(res, "مشاركة الفهرس والتفريغ", MENU_ITEM_4_ACTION);
    
}

private void initIntents() {

	 saerchfield = getIntent().getIntExtra("SEARCHFEILD", 1);
	 searchcriterias = getIntent().getStringExtra("SEARCHCRITERIA");
	
}

private void initViews() {

	  spinner1 = (Spinner) findViewById(R.id.spinnerfield);
	  spinner2 = (Spinner) findViewById(R.id.spinnertype);
	  ls2 = (ListView) findViewById(R.id.listView1);
	  txt_result = (TextView) findViewById(R.id.txt_result);
	  TextView02 = (TextView) findViewById(R.id.TextView02);
	  progressBar = (ProgressBar)findViewById(R.id.progressbar_Horizontal);
	  search_btn = (Button) findViewById(R.id.search_btn);
	  txt = (AutoCompleteTextView) findViewById(R.id.myFilter);
	  nextresult = (Button) findViewById(R.id.nextresult);
	  prevresult = (Button) findViewById(R.id.prevresult);

}
private void Appearance() {

	  txt_result.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
	  txt_result.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
	  TextView02.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
	  TextView02.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
	  search_btn.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
	  search_btn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
	  txt.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
	  txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
	  nextresult.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
	  nextresult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
	  prevresult.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
	  prevresult.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);

	  progressBar.setProgress(0); 

}

private void FillViews() {

	 if (saerchfield == 2) {String S1 = "البحث في: " + getIntent().getStringExtra("BOOKNAME"); String S2 = "بحث في كل الفهارس"; String S3 = "مجال بحث مخصص..."; String [] spinnerdata = { S1, S2, S3 }; spinadapter = new FieldSpinnerAdapter(this, spinnerdata);}
	 else if (saerchfield == 1) {String S2 = "بحث في كل الفهارس"; String S3 = "مجال بحث مخصص..."; String [] spinnerdata = { S2, S3 }; spinadapter = new FieldSpinnerAdapter(this, spinnerdata);}
	 
	 String[] typedata = { "بحث مطابق", "أجزاء من النص المدخل", "كل كلمة بحث مستقل", "بحث بجذور الكلمات(قريبا)", "بحث بالتشكيل" };
	 typeadapter = new CustomSpinnerAdapter(this, typedata);
		
	 spinner2.setAdapter(typeadapter);
	 spinner1.setAdapter( spinadapter );
	 spinner2.setSelection(method);
	 adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, searchwords.split("#"));
	 txt.setAdapter(adapter);
 	
}

private void setListeners() {

	 search_btn.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) {if (!txt.getText().toString().equals("")){InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(txt.getWindowToken(), 0); count = 0; istart = 0; iend = RESULT_PER_PAGE; new BackgroundAsyncTask().execute(txt.getText().toString());}}});
	 spinner1.setOnTouchListener(new View.OnTouchListener() {@Override public boolean onTouch(View arg0, MotionEvent arg1) {if (spinner1.getSelectedItemPosition() == spinner1.getCount()-1) spinner1.setSelection(0); return false;}});
	 spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {@Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {if (spinner1.getCount() == 3 && arg2 == 0){searchtype = 2; if (searchcriterias.equals("")) searchcriterias="0"; Criterias = searchcriterias.split(" ");}	else if (spinner1.getCount() == 3 && arg2 == 1){searchtype = 1;} else if (spinner1.getCount() == 3 && arg2 == 2){searchtype = 2; showlist();} else if (spinner1.getCount() == 2 && arg2 == 0){searchtype = 1;} else if (spinner1.getCount() == 2 && arg2 == 1){searchtype = 2; showlist();}} @Override public void onNothingSelected(AdapterView<?> arg0) {}});				 
	 spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {@Override	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {method = arg2; AtharyEditor = athary.edit(); AtharyEditor.putInt("METHOD", arg2); AtharyEditor.commit();} @Override public void onNothingSelected(AdapterView<?> arg0) {}});
	 txt.setOnKeyListener(new View.OnKeyListener() {@Override public boolean onKey(View v, int keyCode, KeyEvent event) {if (keyCode == 66 && !txt.getText().toString().equals("")){InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);	mgr.hideSoftInputFromWindow(txt.getWindowToken(), 0); count = 0; istart = 0; iend = RESULT_PER_PAGE; new BackgroundAsyncTask().execute(txt.getText().toString());} return false;}});
	 txt.setOnItemClickListener(new OnItemClickListener() {@Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(txt.getWindowToken(), 0);	count = 0; istart = 0; iend = RESULT_PER_PAGE; new BackgroundAsyncTask().execute(arg0.getItemAtPosition(arg2).toString());}});
	 nextresult.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) {Start_Search(istart + RESULT_PER_PAGE, iend + RESULT_PER_PAGE);}});
	 prevresult.setOnClickListener(new View.OnClickListener() {@Override public void onClick(View v) {Start_Search(istart - RESULT_PER_PAGE, iend - RESULT_PER_PAGE);}});

     ls2.setOnItemClickListener(new OnItemClickListener() 
     {

		public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) 
     	{
	 		CODE = ROWS.get(arg2).getCODE();
	 		SEQ = ROWS.get(arg2).getSEQ();
	 		SHEEKH = ROWS.get(arg2).getSHEEKH();
	 		BOOK = ROWS.get(arg2).getBOOKNAME();
	 		CHAPTER = ROWS.get(arg2).getCHAPTER();
	 		OFFSET = ROWS.get(arg2).getOFFSET();
	 		DURATION = ROWS.get(arg2).getDURATION();
	 		URL = ROWS.get(arg2).getURL();
	 		TITLE = SHEEKH + "\n" + BOOK + "\n" + CHAPTER + "\n" + "بداية المقطع: " + utils.milliSecondsToTimer(OFFSET) + "\n" + "المدة: " + utils.milliSecondsToTimer(DURATION) + "\n" + "الوصلة: " + Pasre_URL(URL);
		 	TXT = ROWS.get(arg2).getTXT();
		 	TAF =  ROWS.get(arg2).getTAF();
		 		
	        showDialog(CONTEXT_MENU_ID);
	        
			}
 		
 	});
          
	    iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
	        
	    	
			@Override
			public void onClick(int menuId) {
				
				switch(menuId) {
				
				case MENU_ITEM_1_ACTION:
					
			    	   SharedPreferences athary = getSharedPreferences("athary", 0);
			  		   SharedPreferences.Editor editor = athary.edit();
			  		   
			  		   editor.putInt("CODE", CODE);
			  		   editor.putString("TITLE", SHEEKH + " - " + BOOK + " - " + CHAPTER);
			  		   editor.putString("URL", URL);
			  		   editor.putInt("OFFSET", OFFSET);
			  		   editor.putInt("DURATION", DURATION);
			  		   editor.putInt("TYPE", 2);
			  		   editor.putString("TXT", TXT);
			  		   editor.putString("TAF", TAF);

			  		   //Commit the edits!
			  		 editor.commit();
			  		 IntroActivity.mytxt = Html.fromHtml(TXT) + "\n\n" + TAF;
			  		 IntroActivity.stime = "التوقيت: " + StringUtils.generateTime(OFFSET);
			  		 IntroActivity.etime = "المدة: " + StringUtils.generateTime(DURATION);
			  		 
			  		 if (IntroActivity.tabHost != null) {
			  			IntroActivity.newmedia = true;
			  			IntroActivity.tabHost.setCurrentTab(0);
			  		 }
					
					break;
					
				case MENU_ITEM_2_ACTION:

					dbHelper.updatebyFAV(CODE, SEQ, 1);
					Toast.makeText(getApplicationContext(), "تم إضافة الفهرس إلى المفضلة", Toast.LENGTH_LONG).show();

					break;

				case MENU_ITEM_3_ACTION:
					Intent sendIntent_IND = new Intent();
					sendIntent_IND.setAction(Intent.ACTION_SEND);
					sendIntent_IND.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(TXT) + "\n" + "المصدر: " + "\n" + TITLE);
					sendIntent_IND.setType("text/plain");
					startActivity(sendIntent_IND);
					
					break;
					
				case MENU_ITEM_4_ACTION:
					Intent sendIntent_TAF = new Intent();
					sendIntent_TAF.setAction(Intent.ACTION_SEND);
					sendIntent_TAF.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(TXT) + "\n" + TAF + "\n" + "المصدر: " + "\n" + TITLE);
					sendIntent_TAF.setType("text/plain");
					startActivity(sendIntent_TAF);
					
				break;
					
				}
			}
		});
}

private void Start_Search(Integer start, Integer end){
	count = 0;
    istart = start;
    iend = end;
    new BackgroundAsyncTask().execute(txt.getText().toString());  
}
 
private void listclicks(){

	if (adapter.getPosition(txt.getText().toString()) < 0){
	
	   searchwords = searchwords + txt.getText().toString() + "#";
	
	   AtharyEditor = athary.edit();
	   AtharyEditor.putString("TERMS", searchwords);
	   AtharyEditor.commit();
	   
	  searchwords = athary.getString("TERMS", "");

	  adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, searchwords.split("#"));
	  txt.setAdapter(adapter);
	}  
	  lvAdapter.notifyDataSetChanged();
  	  ls2.setAdapter(lvAdapter);
	
}

private String Pasre_URL(String URL){
	try {
		URL url;
        URL = URL.replaceAll("\\\\" , "/");
		url = new URL(link + URL);
			URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
			url = uri.toURL();
			URL = url.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}	
	return URL;
}

	 public class BackgroundAsyncTask extends
	    AsyncTask<String, Void, Void> {

		 
		 ArrayList<RowData> ROWS_NEW = new ArrayList<RowData>();
		 Cursor cur;
		 
		 
	  @Override
	  protected void onPostExecute(Void unused) {
		  
		  if (ROWS_NEW.isEmpty()) {
		  		row = new RowData(0, 0, 0, "لا توجد نتائج بحث","كلمة البحث: " + searchtxt,"",0,0,"", "","",0,"");
		  		ROWS_NEW.add(row);
		  		ls2.setEnabled(false);
		  		//ls2.setVisibility(View.VISIBLE);
		  		progressBar.setVisibility(View.GONE);
		  		}
		  ROWS.clear();
		  ROWS.addAll(ROWS_NEW);
		  progressBar.setVisibility(View.GONE);
		  
		  if (iend > RESULT_PER_PAGE && iend < cur.getCount()){
			  nextresult.setVisibility(View.VISIBLE);
			  prevresult.setVisibility(View.VISIBLE);
			  
		  }else if(iend <= RESULT_PER_PAGE && iend == cur.getCount()){
			  nextresult.setVisibility(View.INVISIBLE);
			  prevresult.setVisibility(View.INVISIBLE);
			  
		  }else if(iend <= RESULT_PER_PAGE && iend < cur.getCount()){
			  nextresult.setVisibility(View.VISIBLE);
			  prevresult.setVisibility(View.INVISIBLE);
		  }
		  else if(iend > RESULT_PER_PAGE && iend == cur.getCount()){
			  nextresult.setVisibility(View.INVISIBLE);
			  prevresult.setVisibility(View.VISIBLE);
		  }
			  
		  BackgroundAsyncTask.this.cancel(true);
		  
		  
		 if (count == 0) {
			 count++;
							  
			 listclicks();
		 }
		  nextresult.setEnabled(true);
		  prevresult.setEnabled(true);
		 ls2.setVisibility(View.VISIBLE);
		 if (cur.getCount() > 0) txt_result.setText(" نتائج البحث  من " + String.valueOf(istart + 1) + " إلى " + iend + "\n" + "النتيجة الكلية: " + cur.getCount());
		 else txt_result.setText("");
	  }

	  @Override
	  protected void onPreExecute() {
		  
		  progressBar.setProgress(0);
		  progressBar.setMax(100);
		  ROWS_NEW.clear();
		  ls2.setAdapter(null);
		  ls2.setVisibility(View.INVISIBLE);
		  ls2.setEnabled(true);
		  progressBar.setVisibility(View.VISIBLE);
		  //ls2.setVisibility(View.INVISIBLE);

		  nextresult.setEnabled(false);
		  prevresult.setEnabled(false);
		  
			 
	  }

	  @Override
	  protected Void doInBackground(String... aurl) {

		  	searchtxt = aurl[0];

//#################################################################################################################################################
	  		String inClause = "(";
	  		if (searchtype == 2) {for (int i = 0; i < Criterias.length - 1; i++) inClause = inClause + Criterias[i] + ","; inClause = inClause + Criterias[Criterias.length - 1] + ")";}

			switch (method) {
				case 0: 
					
					if (searchtype == 1) cur   = dbHelper.Contents_SearchAll("Exact", searchtxt.replaceAll("ًٌٍَُِّْ", ""));
					else if (searchtype == 2) { cur   = dbHelper.Contents_Search_Custom("Exact", searchtxt.replaceAll("ًٌٍَُِّْ", ""), inClause);}
					
					break;
				
				case 1:
					if (searchtype == 1) cur   = dbHelper.Contents_SearchAll("Parts", searchtxt.replaceAll("ًٌٍَُِّْ", ""));
					else if (searchtype == 2) { cur   = dbHelper.Contents_Search_Custom("Parts", searchtxt.replaceAll("ًٌٍَُِّْ", ""), inClause);}
						
					break;
					
				case 2:
					
					if (searchtype == 1) cur   = dbHelper.Contents_SearchAll("Each", searchtxt.replaceAll("ًٌٍَُِّْ", ""));
					else if (searchtype == 2) { cur   = dbHelper.Contents_Search_Custom("Each", searchtxt.replaceAll("ًٌٍَُِّْ", ""), inClause);}
						
					break;
					
				case 3:
///#################################   Search By ROOTS
					if (searchtype == 1) cur   = dbHelper.Contents_SearchAll("Root", searchtxt.replaceAll("ًٌٍَُِّْ", ""));
					else if (searchtype == 2) {cur   = dbHelper.Contents_Search_Custom("Root", searchtxt.replaceAll("ًٌٍَُِّْ", ""), inClause);}
							
					break;
					
				case 4:
					
					if (searchtype == 1) cur   = dbHelper.Contents_SearchAll("Tashkeel", searchtxt);
					else if (searchtype == 2) {cur   = dbHelper.Contents_Search_Custom("Tashkeel", searchtxt, inClause);}
							
					break;
					
				
			}

		  	
			 if (cur.getCount() > 0 ) cur.moveToPosition(istart);		
			 

//#################################################################################################################################################
		    for (int i = istart; i < iend; i++) {

			  	//if((searchtype == 5?LINE:pattern.matcher(LINE).replaceAll("")).contains(searchtxt))  	{
		    	if (cur.getPosition() < cur.getCount() && cur.getPosition() >= 0){
				 Cursor sh = dbHelper.SheekhBy_SHEEKH_ID(cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID)));	 
				 Cursor book = dbHelper.BooksBy_BOOK_ID(cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_BOOK_ID)));	
			 	 Cursor chp = dbHelper.ChaptersBy_CODE(cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_CODE)));
				 sh.moveToFirst();
				 book.moveToFirst();
				 chp.moveToFirst();
				 
				 SHEEKH = ""; 
				 BOOK = "";
				 URL = "";
				 CHAPTER = "";
				 LINE = cur.getString(cur.getColumnIndex(NewDataDbAdapter.KEY_LINE));
				 if (sh.getCount() > 0) SHEEKH = sh.getString(sh.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_NAME));
				 if (book.getCount() > 0) BOOK = book.getString(book.getColumnIndex(NewDataDbAdapter.KEY_BOOK_NAME));
				 if (chp.getCount() > 0){
					 URL = chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_PATH)) + "/" + chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_FILENAME)) + "." + chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_FILETYPE));
					 CHAPTER = chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_TITLE)) + "(" + chp.getString(chp.getColumnIndex(NewDataDbAdapter.KEY_FILENAME)) + ")";
				 }
				 
					 
					 row = new RowData(
					 			i,
					 			cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_CODE)),
					 			cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_SEQ)),
					 			SHEEKH,
					 			BOOK,
					 			CHAPTER,
					 			cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_OFFSET)),
					 			cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_DURATION)),
					 			LINE,
					 			cur.getString(cur.getColumnIndex(NewDataDbAdapter.KEY_TAFREEG)),
					 			URL,
					 			cur.getInt(cur.getColumnIndex(NewDataDbAdapter.KEY_FAV)), searchtxt
					 			);
					 ROWS_NEW.add(row);
				 }
				cur.moveToNext();
		    	}

	    	iend = cur.getPosition();
	    	
			 
	   return null;
	  }

	  @Override
	  protected void onProgressUpdate(Void... values) {
	   //progressBar.setProgress(values[0]);
	  }

	 }
	 

	@Override
	protected Dialog onCreateDialog(int id) {
		if (id == CONTEXT_MENU_ID) {
			return iconContextMenu.createMenu("خيارات الفهرس");
		}
		return super.onCreateDialog(id);
	}
		
	  protected class ViewHolder {
	        protected TextView tvGrp;
	        protected TextView tvChld;
	        protected CheckBox group_tick;
	        protected CheckBox child_tick;
	    }
	  
	  public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {
		//----------------------------------------------------------------------
		public MyExpandableListAdapter(
				Cursor cursor,
				Context context,
				int groupLayout,
				int childLayout,
				String[] groupFrom,
				int[] groupTo,
				String[] childrenFrom,
				int[] childrenTo
				) {
			
		        super(context, cursor, groupLayout, groupFrom, groupTo, childLayout, childrenFrom, childrenTo);
		        }
		//----------------------------------------------------------------------

			// returns cursor with childs for given group cursor
		    @Override
		    protected Cursor getChildrenCursor(Cursor groupCursor) {
		           Cursor childCursor = dbHelper.BooksBy_SHEEKH_ID(groupCursor.getInt(groupCursor.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID)));
		           return childCursor;
		    }
		    
		//--------------------------------------------------------------------------------------------------------------------------------------------
		    public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) { 

		       	
		    //	View groupView = super.getGroupView(groupPosition, isExpanded, convertView, parent);
		//    	Cursor cursor = getGroup(groupPosition);
		    	
		   // 	TextView txt = (TextView)groupView.findViewById(R.id.ind);
	//	    	CheckBox group_tick = (CheckBox) groupView.findViewById(R.id.ind_tick);
			//	txt.setTypeface(MainActivity.tf,Typeface.NORMAL);
			//	txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, MainActivity.fontsize);
				
	//	        if (cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 1){ 
	//	        	group_tick.setChecked(true);
	//	        }
	//	        else if (cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 0){ 
	//	        	group_tick.setChecked(false);
	//		    }
		        
		//        return groupView; 	
		    
		        ViewHolder holder;
		    	final Cursor cursor = getGroup(groupPosition);
		    	
		        if (convertView == null) {
		            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		            convertView = vi.inflate(R.layout.group_shaikh_tick, parent, false);
		            holder = new ViewHolder();
		            holder.group_tick = (CheckBox) convertView.findViewById(R.id.ind_tick);
		            holder.tvGrp = (TextView) convertView.findViewById(R.id.ind);
		            convertView.setTag(holder);
		        } else {
		            holder = (ViewHolder) convertView.getTag();
		        }
		        holder.tvGrp.setTypeface(IntroActivity.tf,Typeface.NORMAL);
		        holder.tvGrp.setTextSize(TypedValue.COMPLEX_UNIT_SP, IntroActivity.fontsize);			
		        holder.tvGrp.setText(cursor.getString(cursor.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_NAME)));
		        holder.group_tick.setTag(cursor.getPosition());
		        holder.tvGrp.setTag(cursor.getPosition());
		        
		        if (cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 1){ 
		        	holder.group_tick.setChecked(true);
		        }
		        else if (cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 0){ 
		        	holder.group_tick.setChecked(false);
			    }
		        holder.group_tick.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Cursor cursor2 = getGroup(groupPosition);

				        if (cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 0){ 
				        	dbHelper.Updateby_All_Books_Selection(1, 0);
							dbHelper.Update_Sheekh_Selection(1, cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID)));
							//ExpandList.expandGroup(groupPosition);
							if (!mAdapter.equals(null)) mAdapter.notifyDataSetChanged();
				        }
				        else if (cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 1){ 
				        	dbHelper.Updateby_All_Books_Selection(0, 1);
							dbHelper.Update_Sheekh_Selection(0, cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID)));
							if (!mAdapter.equals(null)) mAdapter.notifyDataSetChanged();

					    }

		            }
		        });


		        return convertView;
		} 
		    	// Process click on click of the button on child item
		    	public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
			
			         ViewHolder holder;
			         final Cursor cursor = getChild(groupPosition, childPosition);
			    	
			        if (convertView == null) {
			            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			            convertView = vi.inflate(R.layout.txt_child_tick, parent, false);
			            holder = new ViewHolder();
			            holder.child_tick = (CheckBox) convertView.findViewById(R.id.ind_tick);
			            holder.tvChld = (TextView) convertView.findViewById(R.id.ind);
			            convertView.setTag(holder);
			        } else {
			            holder = (ViewHolder) convertView.getTag();
			        }
			        holder.tvChld.setTypeface(IntroActivity.tf,Typeface.NORMAL);
			        holder.tvChld.setTextSize(TypedValue.COMPLEX_UNIT_SP, IntroActivity.fontsize - 1);
			        holder.tvChld.setText(cursor.getString(cursor.getColumnIndex(NewDataDbAdapter.KEY_BOOK_NAME)));
			        holder.child_tick.setTag(cursor.getPosition());
			        holder.tvChld.setTag(cursor.getPosition());
			        
			        if (cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 1){ 
			        	 holder.child_tick.setChecked(true);
			        }
			        else if (cursor.getInt(cursor.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 0){ 
			        	 holder.child_tick.setChecked(false);
				    }
			        holder.child_tick.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							Cursor cursor2 = getChild(groupPosition, childPosition);
							
					        if (cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 0){ 
					        	//child_tick.setChecked(true);
								dbHelper.Update_Book_Selection(1, cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID)), cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_BOOK_ID)));
								if (!mAdapter.equals(null)) mAdapter.notifyDataSetChanged();

					        }
					        else if (cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_SELECTION)) == 1){ 
					        	//child_tick.setChecked(false);
								dbHelper.Update_Book_Selection(0, cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_SHEEKH_ID)), cursor2.getInt(cursor2.getColumnIndex(NewDataDbAdapter.KEY_BOOK_ID)));
								if (!mAdapter.equals(null)) mAdapter.notifyDataSetChanged();

						    }
							
						}
					});
			        return convertView; 	

		   		}
			}
	 
	  private class CustomSpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
		    String[] values;
		    Context context;

		    public CustomSpinnerAdapter(Context context, String[] values) {
		        this.context = context;
		        this.values = values;
		    }

		    @Override
		    public int getCount() {
		        return values.length;
		    }

		    @Override
		    public Object getItem(int position) {
		        return values[position];
		    }

		    @Override
		    public long getItemId(int position) {
		        return position;
		    }

		    public boolean isEnabled(int position) {
		        if(position == 3){
		            return false;
		         }else{
		            return true;
		        }        
		    }
		    
		    @Override
		    public View getView(int position, View convertView, ViewGroup parent) {

		        View v = convertView;
		        if (v == null) {
		           LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		           v = vi.inflate(R.layout.txt_spinner, null);
		        } 
				TextView tv=(TextView) v.findViewById(R.id.ind_child);
				tv.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
				tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
					
				tv.setText(values[position]);
				
				return v;  

		    }

		    @Override
		    public View getDropDownView(int position, View convertView, ViewGroup parent) {

		        View v = convertView;
		        if (v == null) {
		           LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		           v = vi.inflate(R.layout.txt_spinner_dropdown, null);
		        } 
				TextView tv=(TextView) v.findViewById(R.id.ind_child);
				tv.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
				tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
				tv.setBackgroundResource(R.drawable.custom_style_nocorners);
	
				tv.setText(values[position]);
				
				switch (position) {
					case 3:  {
						tv.setTextColor(Color.DKGRAY);
					}
					break;
					default:tv.setTextColor(Color.argb(255, 134, 121, 81));
					break;
					}
				return v;  

		    }
		}

		private class FieldSpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
		    String[] values;
		    Context context;

		    public FieldSpinnerAdapter(Context context, String[] values) {
		        this.context = context;
		        this.values = values;
		    }

		    @Override
		    public int getCount() {
		        return values.length;
		    }

		    @Override
		    public Object getItem(int position) {
		        return values[position];
		    }

		    @Override
		    public long getItemId(int position) {
		        return position;
		    }

		    @Override
		    public View getView(int position, View convertView, ViewGroup parent) {

		        View v = convertView;
		        if (v == null) {
		           LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		           v = vi.inflate(R.layout.txt_spinner, null);
		        } 
				TextView tv=(TextView) v.findViewById(R.id.ind_child);
				tv.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
				tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
				tv.setText(values[position]);
				
				return v;  

		    }

		    @Override
		    public View getDropDownView(int position, View convertView, ViewGroup parent) {

		        View v = convertView;
		        if (v == null) {
		           LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		           v = vi.inflate(R.layout.txt_spinner_dropdown, null);
		        } 
				TextView tv=(TextView) v.findViewById(R.id.ind_child);
				tv.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
				tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);
				tv.setBackgroundResource(R.drawable.custom_style_nocorners);
				tv.setTextColor(Color.argb(255, 134, 121, 81));
	
				tv.setText(values[position]);

				return v;  

		    }
		}

		private void showlist(){
			
		    View popUpView = getLayoutInflater().inflate(R.layout.settings_search_criteria, null); // inflating popup layout
		    final PopupWindow mpopup = new PopupWindow(popUpView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, true); // Creation of popup
		    //mpopup.setAnimationStyle(android.R.style.Animation_Dialog);
		    mpopup.showAtLocation(popUpView, Gravity.CENTER, 0, 0); // Displaying popup

			Cursor mGroupsCursor = dbHelper.AllSheekhs();  

		    ExpandList = (ExpandableListView) mpopup.getContentView().findViewById(R.id.EXP);
		    
		    TextView title = (TextView) mpopup.getContentView().findViewById(R.id.title);
		    title.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		    title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);

		    mAdapter = new MyExpandableListAdapter(mGroupsCursor,this,
		    		
		    R.layout.group_shaikh_tick, // group layout
		    
		    R.layout.txt_child_tick, // child layout
		    
		    new String[] { NewDataDbAdapter.KEY_SHEEKH_NAME }, // group title for group layout
		    
		    new int[] { R.id.ind }, // group title to View
		    
		    new String[] { NewDataDbAdapter.KEY_BOOK_NAME }, // child title for child layout
		    
		    new int[] { R.id.ind } // child title to View
		    
		    );
		    
		    ExpandList.setAdapter(mAdapter);

		    //for (int i=0;i<ExpandList.getCount();i++)
		    //ExpandList.expandGroup(i);


		    Button btnCancel = (Button) popUpView.findViewById(R.id.btn_back);
		    CheckBox clear_checkbox = (CheckBox) popUpView.findViewById(R.id.clear_checkbox);
			TextView txt = (TextView)popUpView.findViewById(R.id.ind);
			txt.setTypeface(IntroActivity.tf,Typeface.NORMAL);
			txt.setTextSize(TypedValue.COMPLEX_UNIT_SP, IntroActivity.fontsize);
			
			Cursor all = dbHelper.AllBooks();
			Cursor sel = dbHelper.BooksBy_Selection_Cursor();
			if (sel.getCount() == all.getCount()) clear_checkbox.setChecked(true);
			else  clear_checkbox.setChecked(false);
				
		    btnCancel.setTypeface(Typeface.createFromAsset(getAssets(), "font2.ttf"),Typeface.NORMAL);
		    btnCancel.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f);

		    clear_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
		        @Override
		        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

					if (buttonView.isChecked()){
						dbHelper.Updateby_All_Sheekhs_Selection(1, 0);
						dbHelper.Updateby_All_Books_Selection(1, 0);
						if (!mAdapter.equals(null)) mAdapter.notifyDataSetChanged();
						}
						else if (!buttonView.isChecked()){
						dbHelper.Updateby_All_Sheekhs_Selection(0, 1);
						dbHelper.Updateby_All_Books_Selection(0, 1);
						if (!mAdapter.equals(null)) mAdapter.notifyDataSetChanged();
						}	
		        }
		    });
		    
		    btnCancel.setOnClickListener(new OnClickListener()
		    {
		        public void onClick (View v)
		        {
		        	mpopup.dismiss(); 
		        	Criterias = dbHelper.BooksBy_Selection().split(" ");
		        }
		    });
		}
		
	  @Override
	  protected void onResume() {
	 	 super.onResume();
	  }
	  
	  @Override
	  protected void onDestroy() {
		  super.onDestroy();
	  }

}  




	