package com.example.waoperations;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.text.Normalizer;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



import com.bimsdk.usb.UsbConnect;
import com.bimsdk.usb.io.OnDataReceive;
import com.example.waoperations.adapter.NavDrawerListAdapter;
import com.example.waoperations.model.NavDrawerItem;
import com.example.waoperations.Inventory.InventoryAdapter;
import com.example.waoperations.Inventory.InventoryAddBarcode;
import com.example.waoperations.Inventory.InventoryDatabaseHelper;
import com.example.waoperations.Inventory.InventoryPositionChange;
import com.example.waoperations.Inventory.InventorySummary;
import com.example.waoperations.Aduanas.AduanasSummary;
import com.example.waoperations.CycleCount.CycleCountDatabaseHelper;
import com.example.waoperations.CycleCount.CycleCountSummary;
import com.example.waoperations.Picking.PickingSummary;
import com.example.waoperations.PutAway.PutAwaySummary;
import com.example.waoperations.Receiving.ReceivingSummary;
import com.example.waoperations.Shipping.ShippingSummary;
import com.example.waoperations.Shipping.ShippingSummaryTransfer;
import com.example.waoperations.Stats.StatsSummary;
import com.example.waoperations.Replenishment.ReplenishmentSummary;
import com.example.waoperations.Transference.TransferenceDataBaseHelper;
import com.example.waoperations.Transference.TransferenceItemSummary;
import com.example.waoperations.Transference.TransferenceZurquiSummary;
import com.example.waoperations.R;


import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.StrictMode;
import android.os.Vibrator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
/*import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;*/
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class OrderLoadTransfer extends Activity {
	
	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
	private static final int REQUEST_CODE = 1234;
	public int COUNTER =0;
	public int GLOBALCOUNTER =0;
	public String Type,USER,OPERATION,USERCODE,LASTPO;
	public String Scanning="";
	public String escaneo="";
	public int execute=0;
	public int timerstarted=0;
	public Boolean timercompleted=false;
	final Context context = this;
	final String PREFS_NAME = "MyPrefsFile";
    private UserPermissionsDatabaseHelper databaseHelper;
    private TransferenceDataBaseHelper databaseHelper2;
	public String CodBarras="";


	@Override
	protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
	setContentView(R.layout.poenter2);
	ActionBar actionBar = getActionBar();
	actionBar.hide();
	
	// more stuff here...
	Intent intent = getIntent();
	Type=intent.getStringExtra("tipo");
    TextView PO = (TextView)findViewById(R.id.po);
    PO.setVisibility(View.GONE);
    TextView emptitel = (TextView)findViewById(R.id.comtitel);
    emptitel.setVisibility(View.GONE);
    TextView bodtitel = (TextView)findViewById(R.id.wartitel);
    bodtitel.setVisibility(View.GONE);
    TextView intro = (TextView)findViewById(R.id.introtext);
    intro.setVisibility(View.GONE);
    TextView eqptitel = (TextView)findViewById(R.id.equipmenttitel);
    eqptitel.setVisibility(View.GONE);
    TextView query = (TextView)findViewById(R.id.queryoperationtitel);
    query.setVisibility(View.GONE);
    Spinner empresa = (Spinner) findViewById(R.id.empresa);
    empresa.setVisibility(View.GONE);
    TextView query2 = (TextView)findViewById(R.id.emptitel);
    query2.setVisibility(View.GONE);
    Spinner empresa2 = (Spinner) findViewById(R.id.empresa2);
    empresa2.setVisibility(View.GONE);
    Spinner bodega = (Spinner) findViewById(R.id.bodega);
    bodega.setVisibility(View.GONE);
    Spinner equipment = (Spinner)findViewById(R.id.equipment);
    equipment.setVisibility(View.GONE);
    Spinner operation = (Spinner)findViewById(R.id.operation);
    operation.setVisibility(View.GONE);
   
	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
	
	    String subtitle ="Picking";
	    OPERATION="Picking";
	    LASTPO=settings.getString("PickingLast", "");
        if(Type.equals("1")){
        subtitle ="Receiving";   
        OPERATION="Receiving";
        LASTPO=settings.getString("ReceivingLast", "");
        }
        if(Type.equals("2")){
        subtitle ="Putaway";  
        OPERATION="Putaway";
        LASTPO=settings.getString("PutAwayLast", "");
        }    
        if(Type.equals("3")){
        subtitle ="Shipping";
       	OPERATION="Shipping";
        LASTPO=settings.getString("ShippingLast", "");
        }  
        if(Type.equals("4")){
       	 subtitle ="Inventory"; 
         OPERATION="Inventory";
         LASTPO=settings.getString("InventoryLast", "");
       } 
        if(Type.equals("5")){
        subtitle ="Cycle count";
        OPERATION="CycleCount";
        intro.setText("Escanee o digite posición a inventariar:");
        LASTPO=settings.getString("CycleCountLast", "");
        }
        if(Type.equals("6")){
        subtitle ="Replenishment";
        OPERATION="Replenishment";
        intro.setText("Seleccione la empresa asociada al reabastecimiento");
        //LASTPO=settings.getString("Replenishment", "");
         }
        if(Type.equals("7")){
            subtitle ="Stats";
            OPERATION="Stats";
            intro.setText("Seleccione la categoría a analizar:");
            //LASTPO=settings.getString("Replenishment", "");
        }
        if(Type.equals("8")){
            subtitle ="Aduanas";
            OPERATION="Aduanas";
            intro.setText("Escanee o digite posición a consultar:");
          LASTPO=settings.getString("AduanasLast", "");
        }
        if(Type.equals("9")){
            subtitle ="Transferencias AC";
            OPERATION="Transfer";
            intro.setText("Digite o escanee el artículo a consultar:");
            LASTPO=settings.getString("TransferLast", "");
        }
        if(Type.equals("10")){
            subtitle ="Envío";
            OPERATION="Shipping";
            LASTPO=settings.getString("ShippingLast", "");
            
        }
        if(Type.equals("12")){
            subtitle ="Transferencias Zurquí";
            OPERATION="Transfer";
            LASTPO=settings.getString("TransferLast2", "");
            
        }
        
      
	    actionBar.setSubtitle(subtitle);
	    actionBar.setTitle("Warehouse");
	    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
	    actionBar.setDisplayShowTitleEnabled(false);  // required to force redraw, without, gray color
	    actionBar.setDisplayShowTitleEnabled(true);
	    actionBar.setDisplayHomeAsUpEnabled(false);
	    actionBar.show(); 
	    
		final TextView view = (TextView) findViewById(R.id.po);
		
		view.setOnClickListener(new View.OnClickListener() {
        //When you click the button, Alert dialog will be showed
        public void onClick(View v) {
       /* Alert Dialog Code Start*/ 	
        	AlertDialog.Builder alert = new AlertDialog.Builder(context);
        	
        	switch(Type){
        	
        	case "9":
        	  	alert.setTitle("Selección de Ítem"); //Set Alert dialog title here
            	alert.setMessage("Digite número de parte"); //Message here
        		break;
        	
        	
        	case "12":
        		alert.setTitle("Selección de Ítem"); //Set Alert dialog title here
            	alert.setMessage("Digite número de parte"); //Message here
        		break;
        		
        	default:
        		 alert.setTitle("Selección de orden"); //Set Alert dialog title here
                 alert.setMessage("Digite número de orden"); //Message here
                break;
        	
        	}
      
 
            // Set an EditText view to get user input 
            final EditText input = new EditText(context);
            
            final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
            input.setText(LASTPO);
  
            alert.setView(input);
            input.selectAll();
           
        	alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int whichButton) {
        	 //You will get as string input data in this variable.
        	 // here we convert the input to a string and show in a toast.
        	 String srt = input.getEditableText().toString().toUpperCase();
        		TextView PO = (TextView)findViewById(R.id.po);
        		PO.setText(srt);
        		LASTPO=input.getEditableText().toString().toUpperCase();
        		
        		PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LemonChiffon)));
        		imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
        		
        	} // End of onClick(DialogInterface dialog, int whichButton)
        }); //End of alert.setPositiveButton
        	alert.setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
        	  public void onClick(DialogInterface dialog, int whichButton) {
        	    // Canceled.
        		  dialog.cancel();
        		  imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
        	  }
        }); //End of alert.setNegativeButton
        	AlertDialog alertDialog = alert.create();
        	alertDialog.show();
       /* Alert Dialog Code End*/        
     }// End of onClick(View v)
  });
		

		
		GetData();
		if (!UsbConnect.isConnect(this)) {
			UsbConnect.Connect(this);
		}

		}
	

	  @Override
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		    	execute=1;
		    	
		        String key = KeyEvent.keyCodeToString(keyCode);
	      
	        // key will be something like "KEYCODE_A" - extract the "A"

	        // use pattern to convert int keycode to some character
	        Matcher matcher = KEYCODE_PATTERN.matcher(key);
	        
	        if (matcher.matches()) {
	            // append character to textview
	        	 Scanning=Scanning+matcher.group(1);
	        //	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexiï¿½n de VPN.", Toast.LENGTH_SHORT).show();
	          //
	        }
	        // let the default implementation handle the event
	        
	    	new CountDownTimer(1000, 1000) {       
				   public void onTick(long millisUntilFinished) {          
				}       

				public void onFinish() {   
					if(execute==1){
					execute=0;
					escaneo=Scanning;
					if(Scanning.equals("")){}
				    else{
				     if(COUNTER==0){
		                	TextView user = (TextView)findViewById(R.id.user);
		                	databaseHelper = new UserPermissionsDatabaseHelper(context.getApplicationContext()); 
		                    StrictMode.setThreadPolicy(policy); 
		                		try{
		                			
		                			String result = null;
		                	    	InputStream is = null;
		                	  
		                	    	String v1 = "'"+Scanning+"'";
		                			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
		                			String v2 = ""+OPERATION+"";

		                		
		                	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		                	     	nameValuePairs.add(new BasicNameValuePair("codigo",v1));
		                	       	nameValuePairs.add(new BasicNameValuePair("operacion",v2));

		                	//apartir de aqui carga ruta
		                		try
		                		{
		                	    	        HttpClient httpclient = new DefaultHttpClient();
		                	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/checkUser.php");
		                	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		                	    	        HttpResponse response = httpclient.execute(httppost); 
		                	    	        HttpEntity entity = response.getEntity();
		                	    	        is = entity.getContent();
		                	    	        Log.e("log_tag", "connection success ");
		                	    	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
		                		}
		                	catch(Exception e)
		                		{
		                	    	        Log.e("log_tag", "Error in http connection "+e.toString());
		                	    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
		                	    	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
		                		}
		                	    	//convert response to string
		                		try{
		                			
		                	    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
		                	    	        StringBuilder sb = new StringBuilder();
		                	    	        String line = null;
		                	    	        while ((line = reader.readLine()) != null) 
		                	    	        {
		                	    	                sb.append(line + "\n");
		                	    	        }
		                	    	        is.close();
		                	    	        result=sb.toString();
		                		}
		                		catch(Exception e)
		                		{
		                	    	       Log.e("log_tag", "Error converting result "+e.toString());
		                		}
		                	int counter=0;
		                	    	//parse json data
		                	    	try{
		                	            databaseHelper.deleteAllData();

		                	    	 	JSONArray jArray = new JSONArray(result);
		                	    		for(int i=0;i<jArray.length();i++)  
		                	            {
		                	    			try{
		                	    		   	JSONObject no = jArray.getJSONObject(i);
		                	    		    String usuario=no.getString("Nombre");
		                	    		    USER=usuario;
		                	    		    user.setText(usuario);
		                	    		    String war=no.getString("Warehouse");
		                	    		    String com=no.getString("Company");
		                	    		    String equ=no.getString("Equipment");
		                	    		   
		                		            NumberFormat nf = NumberFormat.getInstance();
		                		            nf.setMaximumFractionDigits(0);// set as you need
		                	                //databaseHelper.savePickLine(po,loc,sku,"-",qty,type,"0","0",barcode,country);
		                	            	databaseHelper.savePermissions(Scanning, war, com,equ);

		                		            counter++;
		                		   
		                	    			}catch(Exception e)
		                		          	{ 
		                		          	}
		                		            }
		                	    	}
		                	    	catch(JSONException e)
		                	    	{
		                	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
		                	     	} catch (IllegalArgumentException e) {
		                				// TODO Auto-generated catch block
		                				e.printStackTrace();
		                			} 	
		                			}catch(Exception e)
		                	    	{
		                		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
		                		}
		                		
		                		
		                		Cursor x =databaseHelper.getAllUserPermissionLines(Scanning);
		                		
		                		if(x.getCount()==0){
		                			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                          	// Vibrate for 400 milliseconds
	                          	v.vibrate(400);
	                          	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
		                	    Toast.makeText(getBaseContext(), "Usuario no existente o no tiene permisos para accesar esta operación.", Toast.LENGTH_LONG).show();
		                		}else{
		                		    Spinner empresa = (Spinner) findViewById(R.id.empresa);
		                	    	empresa.setVisibility(View.VISIBLE);
		                	    	Spinner empresa2 = (Spinner) findViewById(R.id.empresa2);
		                	    	empresa2.setVisibility(View.GONE);
		                	    	TextView emptitel = (TextView)findViewById(R.id.comtitel);
		                	      	emptitel.setVisibility(View.VISIBLE);
		                	      	TextView bodtitel = (TextView)findViewById(R.id.wartitel);
		                	      	bodtitel.setVisibility(View.VISIBLE);
		                	      	emptitel.setVisibility(View.VISIBLE);
		                	      	TextView emptitel2= (TextView)findViewById(R.id.emptitel);
		                	      	emptitel2.setVisibility(View.GONE);
		                	      	
		                 			x.moveToFirst();
		                 			
		                	        if(Type.equals("4")){
		                	        	Spinner equipment = (Spinner) findViewById(R.id.operation);
		                	        	equipment.setVisibility(View.VISIBLE);
			                	     	TextView eqptitel = (TextView)findViewById(R.id.queryoperationtitel);
			                	     	eqptitel.setVisibility(View.VISIBLE);
			                    		
			                    		// Create an ArrayAdapter using the string array and a default spinner layout
			                    		ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(context,
			                    		        R.array.operations_array, android.R.layout.simple_spinner_item);
			                    		// Specify the layout to use when the list of choices appears
			                    		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			                    		// Apply the adapter to the spinner
			                    		equipment.setAdapter(adapter3);
		                	          }
		                	        else if(Type.equals("0")){
		                	        	Spinner equipment = (Spinner) findViewById(R.id.equipment);
		                	        	equipment.setVisibility(View.VISIBLE);
		                	        	//Spinner empresa2 = (Spinner) findViewById(R.id.empresa2);
		                	        	/*empresa2.setVisibility(View.INVISIBLE);*/
			                	     	TextView eqptitel = (TextView)findViewById(R.id.equipmenttitel);
			                	     	eqptitel.setVisibility(View.VISIBLE);
			                	     	String[] equipos =  x.getString(4).split(";");
			                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, equipos);
			                    		// Specify the layout to use when the list of choices appears
			                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			                    		// Apply the adapter to the spinner
			                    		equipment.setAdapter(adapter2);
			                    		TextView intro = (TextView)findViewById(R.id.introtext);
			                	      	intro.setVisibility(View.VISIBLE);
	                	        		TextView PO = (TextView)findViewById(R.id.po);
			                	      	PO.setVisibility(View.VISIBLE);  
			                	      	
			                	    	Spinner OPERACION = (Spinner) findViewById(R.id.operation);
			                	    	OPERACION.setVisibility(View.VISIBLE);
			                	     	TextView operacion = (TextView)findViewById(R.id.queryoperationtitel);
			                	     	operacion.setVisibility(View.VISIBLE);
			                    		
			                    		// Create an ArrayAdapter using the string array and a default spinner layout
			                    		ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(context,
			                    		        R.array.sort_array, android.R.layout.simple_spinner_item);
			                    		// Specify the layout to use when the list of choices appears
			                    		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			                    		// Apply the adapter to the spinner
			                    		OPERACION.setAdapter(adapter3);
		                	          }
		                	        else if(Type.equals("6")){
		                	        	
			                    		TextView intro = (TextView)findViewById(R.id.introtext);
			                	      	intro.setVisibility(View.VISIBLE);
			                	      	
			                	      	
	                	     
		                	          } 
		                 	        else if(Type.equals("7")){
		                 	        	Spinner bodega = (Spinner) findViewById(R.id.bodega);
			                	    	
		                	        	empresa.setVisibility(View.INVISIBLE);
			                	    
			                	    	bodega.setVisibility(View.INVISIBLE);
			                	    	
			                	      	emptitel.setVisibility(View.INVISIBLE);
			                	      	bodtitel.setVisibility(View.INVISIBLE);
			                	  
				                	     
			                    		TextView intro = (TextView)findViewById(R.id.introtext);
			                	      	intro.setVisibility(View.INVISIBLE);
	                	         
		                	          } 
		                	        else if(Type.equals("9")){

		                	        	Spinner bodega = (Spinner) findViewById(R.id.bodega);
		                	        	bodtitel.setVisibility(View.VISIBLE);
		                	        	bodega.setVisibility(View.VISIBLE);
		                	        	empresa2.setVisibility(View.VISIBLE);
		                	        	emptitel2.setVisibility(View.VISIBLE);
		                	      		empresa.setVisibility(View.GONE);
		                	      		emptitel.setVisibility(View.GONE);

		                	      		String[] bod = {"BOD_AC"};

		                	      		// Create an ArrayAdapter using the string array and a default spinner layout
			                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bod);
			                    		// Specify the layout to use when the list of choices appears
			                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			                    		// Apply the adapter to the spinner
			                    		bodega.setAdapter(adapter2);
		                	       		
			                    		TextView intro = (TextView)findViewById(R.id.introtext);
			                	      	intro.setVisibility(View.VISIBLE);
			                	      	TextView PO = (TextView)findViewById(R.id.po);
			                	      
			                	      	PO.setVisibility(View.VISIBLE);
	                	         
		                	          } 
		                	        else if(Type.equals("12")){

		                	        	Spinner bodega = (Spinner) findViewById(R.id.bodega);
		                	        	bodega.setVisibility(View.VISIBLE);
		                	           	bodtitel.setVisibility(View.VISIBLE);
		                	        	empresa2.setVisibility(View.VISIBLE);
		                	        	emptitel2.setVisibility(View.VISIBLE);
		                	      		empresa.setVisibility(View.GONE);
		                	      		emptitel.setVisibility(View.GONE);

		                	      		
		                	      		String[] bod = {"BOD_01","BOD_03"};
			                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bod);
			                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			                    		bodega.setAdapter(adapter2);
		                	       		
			                      		TextView intro = (TextView)findViewById(R.id.introtext);
			                	      	intro.setVisibility(View.VISIBLE);
			                	      	TextView PO = (TextView)findViewById(R.id.po);
			                	      
			                	      	PO.setVisibility(View.VISIBLE);
	                	         
		                	          } 
		                	        else{
		                	     	     	TextView intro = (TextView)findViewById(R.id.introtext);
				                	      	intro.setVisibility(View.VISIBLE);
		                	        		TextView PO = (TextView)findViewById(R.id.po);
				                	      	PO.setVisibility(View.VISIBLE);    

				                	      	String[] bodegas = x.getString(2).split(";");
				                	      	
				                	        Spinner bodega = (Spinner) findViewById(R.id.bodega);
				                	        bodega.setVisibility(View.VISIBLE);
				                	        
				                	        // Create an ArrayAdapter using the string array and a default spinner layout
				                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bodegas);
				                    		// Specify the layout to use when the list of choices appears
				                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				                    		// Apply the adapter to the spinner
				                    		bodega.setAdapter(adapter2);
				                    		
		                	          }

		                           	String[] empresas =  x.getString(3).split(";");

		                        	// Create an ArrayAdapter using the string array and a default spinner layout
		                    		ArrayAdapter adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, empresas);
		                    		// Specify the layout to use when the list of choices appears
		                    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		                    		// Apply the adapter to the spinner
		                    		empresa.setAdapter(adapter);

		                    		
		                    		/*// Create an ArrayAdapter using the string array and a default spinner layout
		                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bodegas);
		                    		// Specify the layout to use when the list of choices appears
		                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		                    		// Apply the adapter to the spinner
		                    		bodega.setAdapter(adapter2);*/
		                    		
		                    		/// Create an ArrayAdapter using the string array and a default spinner layout
		                    		 String[] empresas2 = new String[]{"jsm","dsr","sts"};
		                       		 ArrayAdapter adapter1 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, empresas2);
		                    		 adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);	
		                       		 empresa2.setAdapter(adapter1);
		                       		 
		                       		 if(Type.equals("12")){
  			 
				                       		 //selecciona bodega de acuerdo con empresa en spinner.
				                       		empresa2.setOnItemSelectedListener(
				                        	        new AdapterView.OnItemSelectedListener() {
				                        	        	
				                        	        public void onItemSelected(AdapterView<?> parent,
				                        	            android.view.View v, int position, long id) {
				                        	   
				                        	        	switch(position)
				                        				{
				                        				case 0:
				                        					
				                        					Spinner bodega = (Spinner) findViewById(R.id.bodega);
				                            	        	    	      		
				                            	      		String[] bod = {"BOD_01"};
				                                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bod);
				                                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				                                    		bodega.setAdapter(adapter2);
				                        					break;
				                        					
				                        				case 1:
				                        					
				                        					Spinner bodega2 = (Spinner) findViewById(R.id.bodega);
				                            	      		
				                            	      		String[] bod2 = {"BOD_03"};
				                                    		ArrayAdapter adapter21 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bod2);
				                                    		adapter21.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				                                    		bodega2.setAdapter(adapter21);
				                        					break;
				                        					
				                        				case 2:
				                        						
				                        						Spinner bodega3 = (Spinner) findViewById(R.id.bodega);
				                        						String[] bod3 = {"BOD_01"};
					                                    		ArrayAdapter adapter23 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bod3);
					                                    		adapter23.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					                                    		bodega3.setAdapter(adapter23);
				                        						break;
				                        				}
				                        	        	
				                        
				                        	        }
				                           	        public void onNothingSelected(AdapterView<?> parent) {
				                        	           // Mensaje.setText("");
				                        	        }
				                        	        
				                        	});

		                       		 }
		                       		 
		                       		 
		                    		 
		                	    	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));		
		                	    	   COUNTER++;
		                		}
		                		Scanning="";


		               }
		               else if(COUNTER==1){
		         
		            	   switch(Type){
		            	   
		            	   case "8":
		            			try{
				                   	String NOMBREITEM=escaneo;
						               
				                   	TextView PO = (TextView)findViewById(R.id.po); 
				                   	LASTPO=NOMBREITEM;
						    	     PO.setText(NOMBREITEM);

						    	    PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LemonChiffon)));	

				                   	}catch(Exception ex){Log.e("log_tag", "Error al cargar el item "+ex.toString());}

				      	      Scanning="";
				      	    COUNTER=1;
		            	   break;
		            	   
		            	   
		            	   case "9":
		            		   StrictMode.setThreadPolicy(policy); 
		            		   databaseHelper2 = new TransferenceDataBaseHelper(context.getApplicationContext()); 
		                   	try{
		                   		String result = null;
		                       	InputStream is = null;
		                       	
		                       	String v1 = "'"+Scanning+"'";
		                   		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
		                   	
		                       	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		                       	nameValuePairs.add(new BasicNameValuePair("barcode",v1));
	
		                   //apartir de aqui carga ruta
		                   	try
		                   	{
					                   	HttpClient httpclient = new DefaultHttpClient();
			          	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getItemBarcodeTransference.php");
			          	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			          	    	        HttpResponse response = httpclient.execute(httppost); 
			          	    	        HttpEntity entity = response.getEntity();
			          	    	        is = entity.getContent();
			          	    	        Log.e("log_tag", "connection success ");
		                   	}
		                   catch(Exception e)
		                   	{
		                       	        Log.e("log_tag", "Error in http connection "+e.toString());
		                       }
		                       	
		                   	try{
		                       	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
		                       	        StringBuilder sb = new StringBuilder();
		                       	        String line = null;
		                       	        while ((line = reader.readLine()) != null) 
		                       	        {
		                       	                sb.append(line + "\n");
		                       	        }
		                       	        is.close();
		                       	        result=sb.toString();
		                   	}
		                   	catch(Exception e)
		                   	{
		                       	       Log.e("log_tag", "Error converting result "+e.toString());
		                   	}
		                   	
		                   int counter=0;
		                   
		                       	//parse json data
		                       	try{
		                               databaseHelper2.deleteAllData();

		                       	 	JSONArray jArray = new JSONArray(result);
		                       		for(int i=0;i<jArray.length();i++)  
		                               {
		                       			try{
		           				            		   	JSONObject no = jArray.getJSONObject(i);
		           				            		   	String itemid=no.getString("ITEMID");
		           				            		    String barcode= no.getString("ITEMBARCODE");
	
		           				        	            databaseHelper2.saveTransferenciasLine(itemid,barcode);

		           				        	            counter++;
		                   	   
		                       			}catch(Exception e)
		                   	          	{ 
		                       				 Log.e("log_tag", "Error cargando datos "+e.toString());
		                   	          	}
		                   	            }
		                       	}
		                       	catch(JSONException e)
		                       	{
		                       	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString( counter));
		                        	 } catch (IllegalArgumentException e) {
		                   			// TODO Auto-generated catch block
		                   			e.printStackTrace();
		                   		} 	
		                   		}catch(Exception e)
		                       	{
		                   	        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
		                   	}
		                   	try{
		                   	String NOMBREITEM="";
				               
		                   	TextView PO = (TextView)findViewById(R.id.po); 
				    	     Cursor cursor = databaseHelper2.getTransferenciasItemBarcode(escaneo);
				    	     if(cursor.getCount()>0){
				    	     cursor.moveToFirst();
				    	     NOMBREITEM=cursor.getString(1);
								 CodBarras=cursor.getString(2);
				    	    LASTPO= NOMBREITEM;
				    	     PO.setText(NOMBREITEM);

				    	    PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LemonChiffon)));	
				    	    
		            	   }
		            	   else{
			            	PO = (TextView)findViewById(R.id.po);
				            PO.setText("");
				            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                          	// Vibrate for 400 milliseconds
                          	v.vibrate(400);
				            PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
				            //Toast.makeText(getBaseContext(), "El item no se cargï¿½ satisfactoriamente. Escanee nuevamente.", Toast.LENGTH_LONG).show();
				            
		            	   }
		                   	}catch(Exception ex){Log.e("log_tag", "Error al cargar el item "+ex.toString());}

				      	      Scanning="";
				      	      COUNTER=1;
		               	   break;
		               	   
		               	   
		            	   case "12":
		            		   StrictMode.setThreadPolicy(policy); 
		            		   databaseHelper2 = new TransferenceDataBaseHelper(context.getApplicationContext()); 
		                   	try{
		                   		String result = null;
		                       	InputStream is = null;
		                       	
		                       	String v1 = "'"+Scanning+"'";
		                   		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
		                   	
		                       	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		                       	nameValuePairs.add(new BasicNameValuePair("barcode",v1));
	
		                   //apartir de aqui carga ruta
		                   	try
		                   	{
					                   	HttpClient httpclient = new DefaultHttpClient();
			          	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getItemBarcodeTransference.php");
			          	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			          	    	        HttpResponse response = httpclient.execute(httppost); 
			          	    	        HttpEntity entity = response.getEntity();
			          	    	        is = entity.getContent();
			          	    	        Log.e("log_tag", "connection success ");
		                   	}
		                   catch(Exception e)
		                   	{
		                       	        Log.e("log_tag", "Error in http connection "+e.toString());
		                       }
		                       	
		                   	try{
		                       	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
		                       	        StringBuilder sb = new StringBuilder();
		                       	        String line = null;
		                       	        while ((line = reader.readLine()) != null) 
		                       	        {
		                       	                sb.append(line + "\n");
		                       	        }
		                       	        is.close();
		                       	        result=sb.toString();
		                   	}
		                   	catch(Exception e)
		                   	{
		                       	       Log.e("log_tag", "Error converting result "+e.toString());
		                   	}
		                   	
		                   int counter=0;
		                   
		                       	//parse json data
		                       	try{
		                               databaseHelper2.deleteAllData();

		                       	 	JSONArray jArray = new JSONArray(result);
		                       		for(int i=0;i<jArray.length();i++)  
		                               {
		                       			try{
		           				            		   	JSONObject no = jArray.getJSONObject(i);
		           				            		   	String itemid=no.getString("ITEMID");
		           				            		    String barcode= no.getString("ITEMBARCODE");
	
		           				        	            databaseHelper2.saveTransferenciasLine(itemid,barcode);

		           				        	            counter++;
		                   	   
		                       			}catch(Exception e)
		                   	          	{ 
		                       				 Log.e("log_tag", "Error cargando datos "+e.toString());
		                   	          	}
		                   	            }
		                       	}
		                       	catch(JSONException e)
		                       	{
		                       	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString( counter));
		                        	 } catch (IllegalArgumentException e) {
		                   			// TODO Auto-generated catch block
		                   			e.printStackTrace();
		                   		} 	
		                   		}catch(Exception e)
		                       	{
		                   	        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
		                   	}
		                   	try{
		                   	String NOMBREITEM="";
				               
		                   	TextView PO = (TextView)findViewById(R.id.po); 
				    	     Cursor cursor = databaseHelper2.getTransferenciasItemBarcode(escaneo);
				    	     if(cursor.getCount()>0){
				    	     cursor.moveToFirst();
				    	     NOMBREITEM=cursor.getString(1);
								 CodBarras=cursor.getString(2);
				    	    LASTPO= NOMBREITEM;
				    	     PO.setText(NOMBREITEM);

				    	    PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LemonChiffon)));	
				    	    
		            	   }
		            	   else{
			            	PO = (TextView)findViewById(R.id.po);
				            PO.setText("");
				            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                          	// Vibrate for 400 milliseconds
                          	v.vibrate(400);
				            PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
				            //Toast.makeText(getBaseContext(), "El item no se cargï¿½ satisfactoriamente. Escanee nuevamente.", Toast.LENGTH_LONG).show();
				            
		            	   }
		                   	}catch(Exception ex){Log.e("log_tag", "Error al cargar el item "+ex.toString());}

				      	      Scanning="";
				      	      COUNTER=1;
		            	   break;
		            	   
		
		            	   default:

		            	   }

		            
		               }
					}
				
				}
				   
				}}.start();  
	    	
	        return super.onKeyDown(keyCode, event);
	    }
	  
	  
	  
		
	 public void onStart(View view) {  
 		 	TextView PO = (TextView)findViewById(R.id.po);
       	    String po=PO.getText().toString();
	      if(COUNTER==0){
		       	Toast.makeText(getApplicationContext(), "Verifique su código para avanzar.", Toast.LENGTH_SHORT).show();
				   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
   			   intentemoslo.putExtra("voz","Verifique su código para avanzar");
   				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
              	// Vibrate for 400 milliseconds
              	v.vibrate(400);
   			   startService(intentemoslo);	
		         
	      }else{
		        Spinner empresa = (Spinner)findViewById(R.id.empresa);
		        String Emp = empresa.getSelectedItem().toString();
  
		        Spinner bodega = (Spinner)findViewById(R.id.bodega);
		        String Bod = bodega.getSelectedItem().toString();
		        
		        po=PO.getText().toString();
		        
		        Spinner empresa2 = (Spinner)findViewById(R.id.empresa2);
		        String Emp2 = empresa2.getSelectedItem().toString();

		       	
		        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);  	 
			    Intent intento = new Intent(getApplicationContext(), PickingSummary.class);
			    if(Type.equals("0")){
		        settings.edit().putString("PickingLast", po).commit();
		        }
                if(Type.equals("1")){
                intento = new Intent(getApplicationContext(), ReceivingSummary.class);  
                settings.edit().putString("ReceivingLast", po).commit();
                }
                if(Type.equals("2")){
                intento = new Intent(getApplicationContext(), PutAwaySummary.class);
                settings.edit().putString("PutAwayLast", po).commit();
                }    
                if(Type.equals("3")){
                intento = new Intent(getApplicationContext(), ShippingSummary.class); 
                settings.edit().putString("ShippingLast", po).commit();
                }  
                if(Type.equals("5")){
                intento = new Intent(getApplicationContext(), CycleCountSummary.class);  
                settings.edit().putString("CycleCountLast", po).commit();
                }
                if(Type.equals("6")){
                intento = new Intent(getApplicationContext(), ReplenishmentSummary.class);  
                settings.edit().putString("Replenishment", po).commit();
                }
                if(Type.equals("7")){
                    intento = new Intent(getApplicationContext(), StatsSummary.class);  
                 }
                if(Type.equals("8")){
                    intento = new Intent(getApplicationContext(), AduanasSummary.class);
                    settings.edit().putString("AduanasLast", po).commit();
                 }
                if(Type.equals("9")){
                    intento = new Intent(getApplicationContext(), TransferenceItemSummary.class);
                    settings.edit().putString("TransferLast", po).commit();
                 }
                if(Type.equals("10")){
                    intento = new Intent(getApplicationContext(), ShippingSummaryTransfer.class);
                    settings.edit().putString("ShippingLast", po).commit();
                 }
                
                if(Type.equals("12")){
                    intento = new Intent(getApplicationContext(), TransferenceZurquiSummary.class);
                    settings.edit().putString("TransferLast2", po).commit();
                 }
                
                if(Type.equals("4")){
                Spinner op = (Spinner)findViewById(R.id.operation);
                settings.edit().putString("InventoryLast", po).commit();
                if(op.getSelectedItemPosition()==1){
                intento = new Intent(getApplicationContext(), InventoryPositionChange.class);  	
            	
            }else if(op.getSelectedItemPosition()==0){
            
            intento = new Intent(getApplicationContext(), InventorySummary.class);  	
            }else{
            intento = new Intent(getApplicationContext(), InventoryAddBarcode.class);  	
            }
            }
            if(Type.equals("0")){
            Spinner equipment = (Spinner)findViewById(R.id.equipment);
            String equip = equipment.getSelectedItem().toString();
            intento.putExtra("EQUIPO",equip);
            intento.putExtra("PO",po);
            Spinner op = (Spinner)findViewById(R.id.operation);
            intento.putExtra("REVERSE","0");
            if(op.getSelectedItemPosition()==1){
            intento.putExtra("REVERSE","1");
             }
            }
     
            else{
		    intento.putExtra("PO",po);}
		    intento.putExtra("EMP",Emp);
		    intento.putExtra("EMP2",Emp2);
		    intento.putExtra("BOD",Bod);
		    intento.putExtra("USER",USER);
		    intento.putExtra("USERCODE",USERCODE);
			  intento.putExtra("BARCODE",CodBarras);
		    startActivity(intento);	  
			}
	 }
	  
	  @Override
	 public boolean onCreateOptionsMenu(Menu menu) {
	        // Inflate the menu items for use in the action bar
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.addcontact
	        ,menu);
	        return super.onCreateOptionsMenu(menu);
	    }
	   
	  
	  @SuppressWarnings("deprecation")
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
				 if (requestCode == 0) {
					    if (resultCode == RESULT_OK) {
	                       
					       final String  contents = data.getStringExtra("SCAN_RESULT"); // This will contain your scan result
			                String format = data.getStringExtra("SCAN_RESULT_FORMAT");
			               
			                if(COUNTER==0){
			                	TextView user = (TextView)findViewById(R.id.user);
			                	databaseHelper = new UserPermissionsDatabaseHelper(this.getApplicationContext()); 
			                    StrictMode.setThreadPolicy(policy); 
			                		try{
			                			String result = null;
			                	    	InputStream is = null;
			                	    	String v1 = "'"+contents+"'";
			                	    	String v2 = ""+OPERATION+"";
			                			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
			                	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			                	     	nameValuePairs.add(new BasicNameValuePair("codigo",v1));
			                	     	nameValuePairs.add(new BasicNameValuePair("operacion",v2));
			                	//apartir de aqui carga ruta
			                		try
			                		{
			                	    	        HttpClient httpclient = new DefaultHttpClient();
			                	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/checkUser.php");
			                	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			                	    	        HttpResponse response = httpclient.execute(httppost); 
			                	    	        HttpEntity entity = response.getEntity();
			                	    	        is = entity.getContent();
			                	    	        Log.e("log_tag", "connection success ");
			                	    	        //Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
			                		}
			                	catch(Exception e)
			                		{
			                	    	        Log.e("log_tag", "Error in http connection "+e.toString());
			                	    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
			                	    	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red. Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
			                		}
			                	    	//convert response to string
			                		try{
			                			
			                	    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
			                	    	        StringBuilder sb = new StringBuilder();
			                	    	        String line = null;
			                	    	        while ((line = reader.readLine()) != null) 
			                	    	        {
			                	    	                sb.append(line + "\n");
			                	    	        }
			                	    	        is.close();
			                	    	        result=sb.toString();
			                		}
			                		catch(Exception e)
			                		{
			                	    	       Log.e("log_tag", "Error converting result "+e.toString());
			                		}
			                	int counter=0;
			                	    	try{
			                	            databaseHelper.deleteAllData();
			                	    	 	JSONArray jArray = new JSONArray(result);
			                	    		for(int i=0;i<jArray.length();i++)  
			                	            {
			                	    			try{
			                	    		   	JSONObject no = jArray.getJSONObject(i);
			                	    		    String usuario=no.getString("Nombre");
			                	    		    USER=usuario;
			                	    		    user.setText(usuario);
			                	    		    String war=no.getString("Warehouse");
			                	    		    String com=no.getString("Company");
			                	    		    String equ=no.getString("Equipment");
			                	    		    
			                		            NumberFormat nf = NumberFormat.getInstance();
			                		            nf.setMaximumFractionDigits(0);// set as you need
			                	                //databaseHelper.savePickLine(po,loc,sku,"-",qty,type,"0","0",barcode,country);
			                	            	databaseHelper.savePermissions(contents, war, com,equ);
			                		            counter++;

			                	    			}catch(Exception e)
			                		          	{ 
			                		          	}
			                		            }
			                	    	}
			                	    	catch(JSONException e)
			                	    	{
			                	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
			                	     	} catch (IllegalArgumentException e) {
			                				// TODO Auto-generated catch block
			                				e.printStackTrace();
			                			} 	
			                			}catch(Exception e)
			                	    	{
			                		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
			                		}
			                		Cursor x =databaseHelper.getAllUserPermissionLines(contents);
			                		if(x.getCount()==0){
			                			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                            	// Vibrate for 400 milliseconds
		                            	v.vibrate(400);
		                            	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
			                	    Toast.makeText(getBaseContext(), "Usuario no existente.", Toast.LENGTH_LONG).show();	
			                		}else{
			                		    Spinner empresa = (Spinner) findViewById(R.id.empresa);
			                	    	empresa.setVisibility(View.VISIBLE);
			                	    	Spinner empresa2 = (Spinner) findViewById(R.id.empresa2);
			                	    	empresa2.setVisibility(View.GONE);
			                	    	TextView emptitel = (TextView)findViewById(R.id.comtitel);
			                	      	emptitel.setVisibility(View.VISIBLE);
			                	      	TextView bodtitel = (TextView)findViewById(R.id.wartitel);
			                	      	bodtitel.setVisibility(View.VISIBLE);
			                	      	emptitel.setVisibility(View.VISIBLE);
			                	      	TextView emptitel2= (TextView)findViewById(R.id.emptitel);
			                	      	emptitel2.setVisibility(View.GONE);
			                	      	
			                 			x.moveToFirst();
			                 			
			                	        if(Type.equals("4")){
			                	        	Spinner equipment = (Spinner) findViewById(R.id.operation);
			                	        	equipment.setVisibility(View.VISIBLE);
				                	     	TextView eqptitel = (TextView)findViewById(R.id.queryoperationtitel);
				                	     	eqptitel.setVisibility(View.VISIBLE);
				                    		
				                    		// Create an ArrayAdapter using the string array and a default spinner layout
				                    		ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(context,
				                    		        R.array.operations_array, android.R.layout.simple_spinner_item);
				                    		// Specify the layout to use when the list of choices appears
				                    		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				                    		// Apply the adapter to the spinner
				                    		equipment.setAdapter(adapter3);
			                	          }
			                	        else if(Type.equals("0")){
			                	        	Spinner equipment = (Spinner) findViewById(R.id.equipment);
			                	        	equipment.setVisibility(View.VISIBLE);
			                	        	//Spinner empresa2 = (Spinner) findViewById(R.id.empresa2);
			                	        	/*empresa2.setVisibility(View.INVISIBLE);*/
				                	     	TextView eqptitel = (TextView)findViewById(R.id.equipmenttitel);
				                	     	eqptitel.setVisibility(View.VISIBLE);
				                	     	String[] equipos =  x.getString(4).split(";");
				                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, equipos);
				                    		// Specify the layout to use when the list of choices appears
				                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				                    		// Apply the adapter to the spinner
				                    		equipment.setAdapter(adapter2);
				                    		TextView intro = (TextView)findViewById(R.id.introtext);
				                	      	intro.setVisibility(View.VISIBLE);
		                	        		TextView PO = (TextView)findViewById(R.id.po);
				                	      	PO.setVisibility(View.VISIBLE);  
				                	      	
				                	    	Spinner OPERACION = (Spinner) findViewById(R.id.operation);
				                	    	OPERACION.setVisibility(View.VISIBLE);
				                	     	TextView operacion = (TextView)findViewById(R.id.queryoperationtitel);
				                	     	operacion.setVisibility(View.VISIBLE);
				                    		
				                    		// Create an ArrayAdapter using the string array and a default spinner layout
				                    		ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(context,
				                    		        R.array.sort_array, android.R.layout.simple_spinner_item);
				                    		// Specify the layout to use when the list of choices appears
				                    		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				                    		// Apply the adapter to the spinner
				                    		OPERACION.setAdapter(adapter3);
			                	          }
			                	        else if(Type.equals("6")){
			                	        	
				                    		TextView intro = (TextView)findViewById(R.id.introtext);
				                	      	intro.setVisibility(View.VISIBLE);
				                	      	
				                	      	
		                	     
			                	          } 
			                 	        else if(Type.equals("7")){
			                 	        	Spinner bodega = (Spinner) findViewById(R.id.bodega);
				                	    	
			                	        	empresa.setVisibility(View.INVISIBLE);
				                	    
				                	    	bodega.setVisibility(View.INVISIBLE);
				                	    	
				                	      	emptitel.setVisibility(View.INVISIBLE);
				                	      	bodtitel.setVisibility(View.INVISIBLE);
				                	  
					                	     
				                    		TextView intro = (TextView)findViewById(R.id.introtext);
				                	      	intro.setVisibility(View.INVISIBLE);
		                	         
			                	          } 
			                	        else if(Type.equals("9")){

			                	        	Spinner bodega = (Spinner) findViewById(R.id.bodega);
			                	        	bodtitel.setVisibility(View.VISIBLE);
			                	        	bodega.setVisibility(View.VISIBLE);
			                	        	empresa2.setVisibility(View.VISIBLE);
			                	        	emptitel2.setVisibility(View.VISIBLE);
			                	      		empresa.setVisibility(View.GONE);
			                	      		emptitel.setVisibility(View.GONE);

			                	      		String[] bod = {"BOD_AC"};

			                	      		// Create an ArrayAdapter using the string array and a default spinner layout
				                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bod);
				                    		// Specify the layout to use when the list of choices appears
				                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				                    		// Apply the adapter to the spinner
				                    		bodega.setAdapter(adapter2);
			                	       		
				                    		TextView intro = (TextView)findViewById(R.id.introtext);
				                	      	intro.setVisibility(View.VISIBLE);
				                	      	TextView PO = (TextView)findViewById(R.id.po);
				                	      
				                	      	PO.setVisibility(View.VISIBLE);
		                	         
			                	          } 
			                	        else if(Type.equals("12")){

			                	        	Spinner bodega = (Spinner) findViewById(R.id.bodega);
			                	        	bodega.setVisibility(View.VISIBLE);
			                	           	bodtitel.setVisibility(View.VISIBLE);
			                	        	empresa2.setVisibility(View.VISIBLE);
			                	        	emptitel2.setVisibility(View.VISIBLE);
			                	      		empresa.setVisibility(View.GONE);
			                	      		emptitel.setVisibility(View.GONE);

			                	      		
			                	      		String[] bod = {"BOD_01","BOD_03"};
				                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bod);
				                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				                    		bodega.setAdapter(adapter2);
			                	       		
				                      		TextView intro = (TextView)findViewById(R.id.introtext);
				                	      	intro.setVisibility(View.VISIBLE);
				                	      	TextView PO = (TextView)findViewById(R.id.po);
				                	      
				                	      	PO.setVisibility(View.VISIBLE);
		                	         
			                	          } 
			                	        else{
			                	     	     	TextView intro = (TextView)findViewById(R.id.introtext);
					                	      	intro.setVisibility(View.VISIBLE);
			                	        		TextView PO = (TextView)findViewById(R.id.po);
					                	      	PO.setVisibility(View.VISIBLE);    

					                	      	String[] bodegas = x.getString(2).split(";");
					                	      	
					                	        Spinner bodega = (Spinner) findViewById(R.id.bodega);
					                	        bodega.setVisibility(View.VISIBLE);
					                	        
					                	        // Create an ArrayAdapter using the string array and a default spinner layout
					                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bodegas);
					                    		// Specify the layout to use when the list of choices appears
					                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					                    		// Apply the adapter to the spinner
					                    		bodega.setAdapter(adapter2);
					                    		
			                	          }

			                           	String[] empresas =  x.getString(3).split(";");

			                        	// Create an ArrayAdapter using the string array and a default spinner layout
			                    		ArrayAdapter adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, empresas);
			                    		// Specify the layout to use when the list of choices appears
			                    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			                    		// Apply the adapter to the spinner
			                    		empresa.setAdapter(adapter);

			                    		
			                    		/*// Create an ArrayAdapter using the string array and a default spinner layout
			                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bodegas);
			                    		// Specify the layout to use when the list of choices appears
			                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			                    		// Apply the adapter to the spinner
			                    		bodega.setAdapter(adapter2);*/
			                    		
			                    		/// Create an ArrayAdapter using the string array and a default spinner layout
			                    		 String[] empresas2 = new String[]{"jsm","dsr","sts"};
			                       		 ArrayAdapter adapter1 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, empresas2);
			                    		 adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);	
			                       		 empresa2.setAdapter(adapter1);
			                       		 
			                       		 if(Type.equals("12")){
			                       			 
					                       		 //selecciona bodega de acuerdo con empresa en spinner.
					                       		empresa2.setOnItemSelectedListener(
					                        	        new AdapterView.OnItemSelectedListener() {
					                        	        	
					                        	        public void onItemSelected(AdapterView<?> parent,
					                        	            android.view.View v, int position, long id) {
					                        	   
					                        	        	switch(position)
					                        				{
					                        				case 0:
					                        					
					                        					Spinner bodega = (Spinner) findViewById(R.id.bodega);
					                            	        	    	      		
					                            	      		String[] bod = {"BOD_01"};
					                                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bod);
					                                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					                                    		bodega.setAdapter(adapter2);
					                        					break;
					                        					
					                        				case 1:
					                        					
					                        					Spinner bodega2 = (Spinner) findViewById(R.id.bodega);
					                            	      		
					                            	      		String[] bod2 = {"BOD_03"};
					                                    		ArrayAdapter adapter21 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bod2);
					                                    		adapter21.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					                                    		bodega2.setAdapter(adapter21);
					                        					break;
					                        				}
					                        	        	
					                        
					                        	        }
					                           	        public void onNothingSelected(AdapterView<?> parent) {
					                        	           // Mensaje.setText("");
					                        	        }
					                        	        
					                        	});

			                       		 }
			                       		 
			                       		 
			                    		 
			                	    	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));		
			                	    	   COUNTER++;
			                		}

			               }
			               else if(COUNTER==1){
			  		         
			            	   switch(Type){
			            	   
			            	   case "8":
			            			try{
					                   	String NOMBREITEM=escaneo;
							               
					                   	TextView PO = (TextView)findViewById(R.id.po); 
					                   	LASTPO=NOMBREITEM;
							    	     PO.setText(NOMBREITEM);

							    	    PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LemonChiffon)));	

					                   	}catch(Exception ex){Log.e("log_tag", "Error al cargar el item "+ex.toString());}

					      	      Scanning="";
					      	    COUNTER=1;
			            	   break;
			            	   
			            	   
			            	   case "9":
			            		   StrictMode.setThreadPolicy(policy); 
			            		   databaseHelper2 = new TransferenceDataBaseHelper(context.getApplicationContext()); 
			                   	try{
			                   		String result = null;
			                       	InputStream is = null;
			                       	
			                       	String v1 = "'"+Scanning+"'";
			                   		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
			                   	
			                       	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			                       	nameValuePairs.add(new BasicNameValuePair("barcode",v1));
		
			                   //apartir de aqui carga ruta
			                   	try
			                   	{
						                   	HttpClient httpclient = new DefaultHttpClient();
				          	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getItemBarcodeTransference.php");
				          	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				          	    	        HttpResponse response = httpclient.execute(httppost); 
				          	    	        HttpEntity entity = response.getEntity();
				          	    	        is = entity.getContent();
				          	    	        Log.e("log_tag", "connection success ");
			                   	}
			                   catch(Exception e)
			                   	{
			                       	        Log.e("log_tag", "Error in http connection "+e.toString());
			                       }
			                       	
			                   	try{
			                       	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
			                       	        StringBuilder sb = new StringBuilder();
			                       	        String line = null;
			                       	        while ((line = reader.readLine()) != null) 
			                       	        {
			                       	                sb.append(line + "\n");
			                       	        }
			                       	        is.close();
			                       	        result=sb.toString();
			                   	}
			                   	catch(Exception e)
			                   	{
			                       	       Log.e("log_tag", "Error converting result "+e.toString());
			                   	}
			                   	
			                   int counter=0;
			                   
			                       	//parse json data
			                       	try{
			                               databaseHelper2.deleteAllData();

			                       	 	JSONArray jArray = new JSONArray(result);
			                       		for(int i=0;i<jArray.length();i++)  
			                               {
			                       			try{
			           				            		   	JSONObject no = jArray.getJSONObject(i);
			           				            		   	String itemid=no.getString("ITEMID");
			           				            		    String barcode= no.getString("ITEMBARCODE");
		
			           				        	            databaseHelper2.saveTransferenciasLine(itemid,barcode);

			           				        	            counter++;
			                   	   
			                       			}catch(Exception e)
			                   	          	{ 
			                       				 Log.e("log_tag", "Error cargando datos "+e.toString());
			                   	          	}
			                   	            }
			                       	}
			                       	catch(JSONException e)
			                       	{
			                       	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString( counter));
			                        	 } catch (IllegalArgumentException e) {
			                   			// TODO Auto-generated catch block
			                   			e.printStackTrace();
			                   		} 	
			                   		}catch(Exception e)
			                       	{
			                   	        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
			                   	}
			                   	try{
			                   	String NOMBREITEM="";
					               
			                   	TextView PO = (TextView)findViewById(R.id.po); 
					    	     Cursor cursor = databaseHelper2.getTransferenciasItemBarcode(escaneo);
					    	     if(cursor.getCount()>0){
					    	     cursor.moveToFirst();
					    	     NOMBREITEM=cursor.getString(1);
									 CodBarras=cursor.getString(2);
					    	    LASTPO= NOMBREITEM;
					    	     PO.setText(NOMBREITEM);

					    	    PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LemonChiffon)));	
					    	    
			            	   }
			            	   else{
				            	PO = (TextView)findViewById(R.id.po);
					            PO.setText("");
					            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                          	// Vibrate for 400 milliseconds
	                          	v.vibrate(400);
					            PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
					            //Toast.makeText(getBaseContext(), "El item no se cargï¿½ satisfactoriamente. Escanee nuevamente.", Toast.LENGTH_LONG).show();
					            
			            	   }
			                   	}catch(Exception ex){Log.e("log_tag", "Error al cargar el item "+ex.toString());}

					      	      Scanning="";
					      	      COUNTER=1;
			               	   break;
			               	   
			               	   
			            	   case "12":
			            		   StrictMode.setThreadPolicy(policy); 
			            		   databaseHelper2 = new TransferenceDataBaseHelper(context.getApplicationContext()); 
			                   	try{
			                   		String result = null;
			                       	InputStream is = null;
			                       	
			                       	String v1 = "'"+Scanning+"'";
			                   		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
			                   	
			                       	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			                       	nameValuePairs.add(new BasicNameValuePair("barcode",v1));
		
			                   //apartir de aqui carga ruta
			                   	try
			                   	{
						                   	HttpClient httpclient = new DefaultHttpClient();
				          	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getItemBarcodeTransference.php");
				          	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				          	    	        HttpResponse response = httpclient.execute(httppost); 
				          	    	        HttpEntity entity = response.getEntity();
				          	    	        is = entity.getContent();
				          	    	        Log.e("log_tag", "connection success ");
			                   	}
			                   catch(Exception e)
			                   	{
			                       	        Log.e("log_tag", "Error in http connection "+e.toString());
			                       }
			                       	
			                   	try{
			                       	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
			                       	        StringBuilder sb = new StringBuilder();
			                       	        String line = null;
			                       	        while ((line = reader.readLine()) != null) 
			                       	        {
			                       	                sb.append(line + "\n");
			                       	        }
			                       	        is.close();
			                       	        result=sb.toString();
			                   	}
			                   	catch(Exception e)
			                   	{
			                       	       Log.e("log_tag", "Error converting result "+e.toString());
			                   	}
			                   	
			                   int counter=0;
			                   
			                       	//parse json data
			                       	try{
			                               databaseHelper2.deleteAllData();

			                       	 	JSONArray jArray = new JSONArray(result);
			                       		for(int i=0;i<jArray.length();i++)  
			                               {
			                       			try{
			           				            		   	JSONObject no = jArray.getJSONObject(i);
			           				            		   	String itemid=no.getString("ITEMID");
			           				            		    String barcode= no.getString("ITEMBARCODE");
		
			           				        	            databaseHelper2.saveTransferenciasLine(itemid,barcode);

			           				        	            counter++;
			                   	   
			                       			}catch(Exception e)
			                   	          	{ 
			                       				 Log.e("log_tag", "Error cargando datos "+e.toString());
			                   	          	}
			                   	            }
			                       	}
			                       	catch(JSONException e)
			                       	{
			                       	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString( counter));
			                        	 } catch (IllegalArgumentException e) {
			                   			// TODO Auto-generated catch block
			                   			e.printStackTrace();
			                   		} 	
			                   		}catch(Exception e)
			                       	{
			                   	        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
			                   	}
			                   	try{
			                   	String NOMBREITEM="";
					               
			                   	TextView PO = (TextView)findViewById(R.id.po); 
					    	     Cursor cursor = databaseHelper2.getTransferenciasItemBarcode(escaneo);
					    	     if(cursor.getCount()>0){
					    	     cursor.moveToFirst();
					    	     NOMBREITEM=cursor.getString(1);
									 CodBarras=cursor.getString(2);
					    	    LASTPO= NOMBREITEM;
					    	     PO.setText(NOMBREITEM);

					    	    PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.LemonChiffon)));	
					    	    
			            	   }
			            	   else{
				            	PO = (TextView)findViewById(R.id.po);
					            PO.setText("");
					            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                          	// Vibrate for 400 milliseconds
	                          	v.vibrate(400);
					            PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
					            //Toast.makeText(getBaseContext(), "El item no se cargï¿½ satisfactoriamente. Escanee nuevamente.", Toast.LENGTH_LONG).show();
					            
			            	   }
			                   	}catch(Exception ex){Log.e("log_tag", "Error al cargar el item "+ex.toString());}

					      	      Scanning="";
					      	      COUNTER=1;
			            	   break;
			            	   
			
			            	   default:

			            	   }

			            
			               }
			                Scanning="";
					    }}

			  
			 }
    
	 @Override
  	 public boolean onOptionsItemSelected(MenuItem item) {
	        // Handle presses on the action bar items

		  switch (item.getItemId()) {
          case R.id.add:
        	  if(execute==0){
            		try{
	                Intent intent = new Intent(
	      	        "com.google.zxing.client.android.SCAN");
	      	        //intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	      	        startActivityForResult(intent, 0);
            		 }catch(Exception e){ 
     	       		Toast.makeText(getApplicationContext(), "Debe instalar ZXING para utilizar esta opción.", Toast.LENGTH_SHORT).show();
     	       		}
	                return true;
	                
            	}else{}
            default:
            return super.onOptionsItemSelected(item);
        }
	    }
	 
	 private void GetData() {
			
			//Receive data from bluetooth scanner
			
			UsbConnect.SetOnDataReceive(new OnDataReceive() {
				@Override
				public void DataReceive(byte[] data , boolean flg) {
			      Scanning=Scanning+new String(data).trim();
			 
				  if(timerstarted==0&&(Scanning.equals("")==false)){
					  timerstarted=1;
				 	new CountDownTimer(300, 300) {       
						   public void onTick(long millisUntilFinished) {          
						}       

						public void onFinish() {  timercompleted=true; 	
						if(timercompleted==true){			
						
							  if(Scanning.equals("")){}else{
								   if(COUNTER==0){
					                	TextView user = (TextView)findViewById(R.id.user);
					                	databaseHelper = new UserPermissionsDatabaseHelper(context.getApplicationContext()); 
					                    StrictMode.setThreadPolicy(policy); 
					                		try{
					                			String result = null;
					                	    	InputStream is = null;
					                	    	String v1 = "'"+Scanning+"'";
					                			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
					                			String v2 = ""+OPERATION+"";
					                	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					                	     	nameValuePairs.add(new BasicNameValuePair("codigo",v1));
					                	       	nameValuePairs.add(new BasicNameValuePair("operacion",v2));
					                		    try
					                		    {
					                	    	        HttpClient httpclient = new DefaultHttpClient();
					                	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/checkUser.php");
					                	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					                	    	        HttpResponse response = httpclient.execute(httppost); 
					                	    	        HttpEntity entity = response.getEntity();
					                	    	        is = entity.getContent();
					                	    	        Log.e("log_tag", "connection success ");
					                	    	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
					                		    }
					                     	catch(Exception e)
					                		{
					                	    	        Log.e("log_tag", "Error in http connection "+e.toString());
					                	    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
					                	    	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red. Verifique conexión de VPN.", Toast.LENGTH_SHORT).show();
					                		}
					                	    	//convert response to string
					                		try{
					                			
					                	    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
					                	    	        StringBuilder sb = new StringBuilder();
					                	    	        String line = null;
					                	    	        while ((line = reader.readLine()) != null) 
					                	    	        {
					                	    	                sb.append(line + "\n");
					                	    	        }
					                	    	        is.close();
					                	    	        result=sb.toString();
					                		}
					                		catch(Exception e)
					                		{
					                	    	       Log.e("log_tag", "Error converting result "+e.toString());
					                		}
					                	int counter=0;
					                	    	//parse json data
					                	    	try{
					                	            databaseHelper.deleteAllData();

					                	    	 	JSONArray jArray = new JSONArray(result);
					                	    		for(int i=0;i<jArray.length();i++)  
					                	            {
					                	    			try{
					                	    		   	JSONObject no = jArray.getJSONObject(i);
					                	    		    String usuario=no.getString("Nombre");
					                	    		    USER=usuario;
					                	    		    user.setText(usuario);
					                	    		    String war=no.getString("Warehouse");
					                	    		    String com=no.getString("Company");
					                	    		    String equ=no.getString("Equipment");
					                		            NumberFormat nf = NumberFormat.getInstance();
					                		            nf.setMaximumFractionDigits(0);// set as you need
					                	                //databaseHelper.savePickLine(po,loc,sku,"-",qty,type,"0","0",barcode,country);
					                	            	databaseHelper.savePermissions(Scanning, war, com,equ);
					                		            counter++;

					                	    			}catch(Exception e)
					                		          	{ 
					                		          	}
					                		            }
					                	    	}
					                	    	catch(JSONException e)
					                	    	{
					                	    	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
					                	     	} catch (IllegalArgumentException e) {
					                				// TODO Auto-generated catch block
					                				e.printStackTrace();
					                			} 	
					                			}catch(Exception e)
					                	    	{
					                		        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
					                		}
					                		Cursor x =databaseHelper.getAllUserPermissionLines(Scanning);
					                		if(x.getCount()==0){
					                			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				                          	// Vibrate for 400 milliseconds
				                          	v.vibrate(400);
				                          	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
					                	    Toast.makeText(getBaseContext(), "Usuario no existente o no tiene permisos para accesar esta operación.", Toast.LENGTH_LONG).show();
					                		}else{
					                			
					                	    	Spinner empresa = (Spinner) findViewById(R.id.empresa);
					                	    	empresa.setVisibility(View.VISIBLE);
					                	    	Spinner empresa2 = (Spinner) findViewById(R.id.empresa2);
					                	    	empresa2.setVisibility(View.INVISIBLE);
					                	    	
					                	     	TextView emptitel = (TextView)findViewById(R.id.comtitel);
					                	      	emptitel.setVisibility(View.VISIBLE);
					                	      	TextView bodtitel = (TextView)findViewById(R.id.wartitel);
					                	      	bodtitel.setVisibility(View.VISIBLE);
					                	      	x.moveToFirst();
					                	      	
					                	        if(Type.equals("4")){
					                	          	
					                	          }
					                	        
					                	        else if(Type.equals("0")){
					                	        	Spinner equipment = (Spinner) findViewById(R.id.equipment);
					                	        	equipment.setVisibility(View.VISIBLE);
						                	     	TextView eqptitel = (TextView)findViewById(R.id.equipmenttitel);
						                	     	eqptitel.setVisibility(View.VISIBLE);
						                	     	String[] equipos =  x.getString(4).split(";");
						                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, equipos);
						                    		// Specify the layout to use when the list of choices appears
						                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
						                    		// Apply the adapter to the spinner
						                    		equipment.setAdapter(adapter2);
						                    		TextView intro = (TextView)findViewById(R.id.introtext);
						                	      	intro.setVisibility(View.VISIBLE);
				                	        		TextView PO = (TextView)findViewById(R.id.po);
						                	      	PO.setVisibility(View.VISIBLE);  
					                	          }else if(Type.equals("9")){
					                	        	  
					                	        	  Spinner bodega = (Spinner) findViewById(R.id.bodega);
							                	    	bodega.setVisibility(View.VISIBLE);
							                	    	
					                	        	   ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(context,
							                    		        R.array.bod_array, android.R.layout.simple_spinner_item);
							                    		// Specify the layout to use when the list of choices appears
							                    		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							                    		// Apply the adapter to the spinner
							                    		bodega.setAdapter(adapter3);
					                	        	  
					                	          }
					                	        else{
					                	     	     	TextView intro = (TextView)findViewById(R.id.introtext);
							                	      	intro.setVisibility(View.VISIBLE);
					                	        		TextView PO = (TextView)findViewById(R.id.po);
							                	      	PO.setVisibility(View.VISIBLE);    
					                	          }
					                	        
					                	        Spinner bodega = (Spinner) findViewById(R.id.bodega);
					                	    	bodega.setVisibility(View.VISIBLE);
					                           	String[] bodegas = x.getString(2).split(";");
					                           	String[] empresas =  x.getString(3).split(";");
					                           	
					                    		
					                    		// Create an ArrayAdapter using the string array and a default spinner layout
					                    		ArrayAdapter adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, empresas);
					                    		// Specify the layout to use when the list of choices appears
					                    		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					                    		// Apply the adapter to the spinner
					                    		empresa.setAdapter(adapter);
					                    		
					                    		
					                    	
					                    		// Create an ArrayAdapter using the string array and a default spinner layout
					                    		ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, bodegas);
					                    		// Specify the layout to use when the list of choices appears
					                    		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					                    		// Apply the adapter to the spinner
					                    		bodega.setAdapter(adapter2);
					                           	
					                           	
					                           	
					                           	
					                	    	user.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));		
					                	    	   COUNTER++;
					                		}


					               }
								   if(Type.equals("9")){
					            		  
				            		   StrictMode.setThreadPolicy(policy); 
				            		   databaseHelper2 = new TransferenceDataBaseHelper(context.getApplicationContext()); 
				                   	try{
				                   		String result = null;
				                       	InputStream is = null;
				                       	String v1 = "'"+Scanning+"'";

				                   		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
				                   	
				                       	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				                       	nameValuePairs.add(new BasicNameValuePair("barcode",v1));
			
				                   //apartir de aqui carga ruta
				                   	try
				                   	{
							                   	HttpClient httpclient = new DefaultHttpClient();
					          	    	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getItemBarcodeTransference.php");
					          	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
					          	    	        HttpResponse response = httpclient.execute(httppost); 
					          	    	        HttpEntity entity = response.getEntity();
					          	    	        is = entity.getContent();
					          	    	        Log.e("log_tag", "connection success ");
				                   	}
				                   catch(Exception e)
				                   	{
				                       	        Log.e("log_tag", "Error in http connection "+e.toString());
				                       }
				                       	
				                   	try{
				                       	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
				                       	        StringBuilder sb = new StringBuilder();
				                       	        String line = null;
				                       	        while ((line = reader.readLine()) != null) 
				                       	        {
				                       	                sb.append(line + "\n");
				                       	        }
				                       	        is.close();
				                       	        result=sb.toString();
				                   	}
				                   	catch(Exception e)
				                   	{
				                       	       Log.e("log_tag", "Error converting result "+e.toString());
				                   	}
				                   	
				                   int counter=0;
				                   
				                       	//parse json data
				                       	try{
				                               databaseHelper2.deleteAllData();

				                       	 	JSONArray jArray = new JSONArray(result);
				                       		for(int i=0;i<jArray.length();i++)  
				                               {
				                       			try{
				           				            		   	JSONObject no = jArray.getJSONObject(i);
				           				            		   	String itemid=no.getString("ITEMID");
				           				            		    String barcode= no.getString("ITEMBARCODE");

				           				        	            databaseHelper2.saveTransferenciasLine(itemid,barcode);

				           				        	            counter++;
				                   	   
				                       			}catch(Exception e)
				                   	          	{ 
				                       				 Log.e("log_tag", "Error cargando datos "+e.toString());
				                   	          	}
				                   	            }
				                       	}
				                       	catch(JSONException e)
				                       	{
				                       	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString( counter));
				                        	 } catch (IllegalArgumentException e) {
				                   			// TODO Auto-generated catch block
				                   			e.printStackTrace();
				                   		} 	
				                   		}catch(Exception e)
				                       	{
				                   	        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
				                   	}
				                   	
				                   	String NOMBREITEM="";
						               
				                   	TextView PO = (TextView)findViewById(R.id.po); 
						    	     Cursor cursor = databaseHelper2.getTransferenciasItemBarcode(escaneo);
						    	     if(cursor.getCount()>0){
						    	     cursor.moveToFirst();
						    	     NOMBREITEM=cursor.getString(1);

										 CodBarras=cursor.getString(2);
			     	     
						    	     PO.setText(NOMBREITEM);

						    	    PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
						    	    COUNTER++;
				            	   }
				            	   else{
					            	PO = (TextView)findViewById(R.id.po);
						            PO.setText("");
						            Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                          	// Vibrate for 400 milliseconds
		                          	v.vibrate(400);
						            PO.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
						            Toast.makeText(getBaseContext(), "El item no se cargó satisfactoriamente. Escanee nuevamente.", Toast.LENGTH_LONG).show();
						            COUNTER=1;
				            	   }
					               }
			                      timerstarted=0;
					      	      Scanning="";
					      	      timercompleted=false;
							  }
							}
						
						
						}}.start();  
						}
				  }
				
			});

		}
	 public void onBackPressed()
	    {
		 
		 new AlertDialog.Builder(this)
	        .setIcon(android.R.drawable.ic_dialog_alert)
	        .setTitle("Salir al menú principal...")
	        .setMessage("Está seguro que desea salir?")
	        .setPositiveButton("Aceptar", new DialogInterface.OnClickListener()
	       {	
	        @Override
	        public void onClick(DialogInterface dialog, int which) {
	            finish();    
	        }

	    })
	    .setNegativeButton("Cancelar", null)
	    .show();
		 	    
	    }

	 
}	
	 