/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.onecable.common.util;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import com.ntels.onecable.R;
import com.ntels.onecable.common.AppConfig;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.db.DatabaseOpenHelper;
import com.ntels.onecable.common.db.SqlManager;
import com.ntels.onecable.common.db.entity.TblLoginInfo;
import com.ntels.onecable.common.security.CryptoPaddingSvcImpl;
import com.ntels.onecable.common.security.SeedCipherSvcImpl;
import com.ntels.onecable.view.dialog.CommonToast;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONException;
import org.json.JSONObject;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ForegroundColorSpan;
import android.text.style.MetricAffectingSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.UnderlineSpan;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Pattern;

/**
 * <pre>
 * 1. ClassName :   Util
 * 2. FileName  :   Util.java
 * 3. Package   :   com.ntels.onecable.common.util
 * 4. Date      :   2016-12-06
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class Util {
    private static final String TAG = Util.class.getSimpleName();

    //	public final Activity	mContext			= null;
    private AppConfig appConfig;
    public Activity act;
    //	public String			TAG				= "com.show.kt";
    public String prefs_name = "custom_prefs";
    //    ImageDownloader imageDownloader = new ImageDownloader();

    public InputFilter filterAlphaNum = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            Pattern ps = Pattern.compile("^[a-zA-Z0-9]+$");
            if (!ps.matcher(source).matches()) {
                return "";
            }
            return null;
        }
    };

    public Util() {

    }

    /**
     * 생성자.
     *
     * @param tmpact {@link Activity}
     */
    public Util(Activity tmpact) {

        act = tmpact;
    }

    //    public void LogV(Object oVal1) {
    //
    //        if ( Constants.LOG_PRINT_CHECK ) {
    //            Dlog.v("bill log", "" + oVal1);
    //        }
    //    }
    //    public void LogV(Object oVal1, Object oVal2) {
    //
    //        if ( Constants.LOG_PRINT_CHECK ) {
    //            Dlog.v("" + oVal1, "" + oVal2);
    //        }
    //    }

    /**
     * Get calcurated value with scale.
     *
     * @param fScale Scale
     * @param iVal   value
     * @return Calcurated value
     */
    public int getScaleVal(Float fScale, int iVal) {

        return (int) ((fScale * iVal) + 0.5f);
    }

    /**
     * Convert list to string.
     *
     * @param list Target list
     * @return Converted string
     */
    public String convertToString(ArrayList<String> list) {

        StringBuilder sb = new StringBuilder();
        String delim = "";
        for (String s : list) {
            sb.append(delim);
            sb.append(s);
            ;
            delim = ",";
        }
        return sb.toString();
    }

    /**
     * Convert string to list
     *
     * @param string Target string
     * @return Converted list
     */
    public ArrayList<String> convertToArray(String string) {

        ArrayList<String> list = new ArrayList<String>(Arrays.asList(string.split(",")));
        return list;
    }

    /**
     * 알파값 적용된 컬러코드 가져오기.
     *
     * @param originalColor 기존 컬러 코드
     * @param alpha         알파값
     * @return 알파값 적용된 컬러코드
     */
    public String addAlpha(String originalColor, double alpha) {

        long alphaFixed = Math.round(alpha * 255);
        Dlog.v(alphaFixed);
        String alphaHex = Long.toHexString(alphaFixed);
        Dlog.v(alphaHex);
        if (alphaHex.length() == 1) {
            alphaHex = "0" + alphaHex;
        }
        originalColor = originalColor.replace("#", "#" + alphaHex);

        return originalColor;
    }

    /**
     * 팝업 메뉴 정보 가져오기.
     *
     * @param iType 메뉴 타입
     * @return 타입별 팝업 메뉴 정보
     */
    public HashMap<String, Object> getPopMenu(int iType) {

        HashMap<String, Object> hmTemp = new HashMap<String, Object>();

        switch (iType) {
            case 1:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_detail");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_01));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 2:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_edit");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_02));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 3:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_del");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_03));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 4:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_gorupview");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_04));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 5:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_gorupadd");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_05));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 6:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "d_img_bg_morepopup_icon_refresh");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_06));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 7:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_sortname");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_07));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 8:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_sortdata");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_08));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 9:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_group_deviceadd");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_09));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 10:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_del");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_10));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 11:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_group_deviceadd");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_11));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 12:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_group_deviceadd");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_12));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 13:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_key");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_13));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 14:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_link");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_14));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 15:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "d_img_bg_morepopup_icon_memberadd");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_15));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 16:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "d_img_bg_morepopup_icon_delete");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_16));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 17:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_del");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_17));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 18:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_del");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_18));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 19:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_edit");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_19));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 20:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "img_bg_morepopup_icon_refresh");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_20));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 21:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "d_img_bg_morepopup_icon_masterchange");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_21));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            case 22:
                hmTemp.put(Constants.KEY_IMAGE_FILE_NAME, "d_img_bg_morepopup_icon_masterchange");
                hmTemp.put(Constants.KEY_TITLE, getString(AppConfig.getGlobalApplicationContext(), R.string.layout_context_menu_22));
                hmTemp.put(Constants.KEY_SELECT_TYPE, iType);
                break;
            default:
                break;
        }
        return hmTemp;
    }

    /**
     * String에 취소선 적용.
     *
     * @param context 컨텍스트
     * @param sVal    취소선 적용할 string
     * @return 취소선 적용된 string
     */
    public SpannableStringBuilder setSpCenterLine(Context context, String sVal) {

        SpannableStringBuilder sp = new SpannableStringBuilder(sVal);
        sp.setSpan(new StrikethroughSpan(), 0, sVal.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        sp.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.color_text_03)), 0, sVal.length(), Spannable
                .SPAN_EXCLUSIVE_EXCLUSIVE);
        return sp;
    }

    //    public SpannableString setSpSimbol(Context mContext, String sVal) {
    //        //		SpannableString sp = new SpannableString("●" + sVal);
    //        //		sp.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.color_line_01)), 0, 1, SpannableString
  // .SPAN_EXCLUSIVE_EXCLUSIVE);
    //        //		sp.setSpan(new RelativeSizeSpan(0.5f), 0, 1, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
    //        //		sp.setSpan(new SuperscriptSpanAdjuster(0.3), 0, 1, SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
    //        //		sp.setSpan(new android.text.style.LeadingMarginSpan.Standard(30, 0), 0, 1, SpannableString
  // .SPAN_EXCLUSIVE_EXCLUSIVE);
    //
    //        SpannableString sp = new SpannableString("●" + sVal);
    //        //        Drawable d = mContext.getResources().getDrawable(R.drawable.img_icon_bullet_01);
    //        //        Drawable d = mContext.getResources().getDrawable(R.drawable.img_rule_rbox_trigger_bullet);
    //        Drawable d = mContext.getResources().getDrawable(R.drawable.img_rule_rbox_trigger_bullet);
    //
    //        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    //        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
    //        sp.setSpan(span, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    //
    //        return sp;
    //    }

    class SuperscriptSpanAdjuster extends MetricAffectingSpan {

        double ratio = 0.5;

        public SuperscriptSpanAdjuster(double ratio) {

            this.ratio = ratio;
        }

        @Override
        public void updateDrawState(TextPaint paint) {

            paint.baselineShift += (int) (paint.ascent() * ratio);
        }

        @Override
        public void updateMeasureState(TextPaint paint) {

            paint.baselineShift += (int) (paint.ascent() * ratio);
        }
    }

    /**
     * <pre>
     * This sets the maximum length in characters of an EditText view. Since the max length must be
     * done with a filter, this method gets the current filters. If there is already a length filter
     * in the view, it will replace it, otherwise, it will add the max length filter preserving the
     * other
     * </pre>
     *
     * @param view   필터 적용할 {@link EditText}
     * @param length Max length
     */
    public void setMaxLength(EditText view, int length) {

        InputFilter curFilters[];
        InputFilter.LengthFilter lengthFilter;
        int idx;

        lengthFilter = new InputFilter.LengthFilter(length);

        curFilters = view.getFilters();
        if (curFilters != null) {
            for (idx = 0; idx < curFilters.length; idx++) {
                if (curFilters[idx] instanceof InputFilter.LengthFilter) {
                    curFilters[idx] = lengthFilter;
                    return;
                }
            }

            // since the length filter was not part of the list, but
            // there are filters, then add the length filter
            InputFilter newFilters[] = new InputFilter[curFilters.length + 1];
            System.arraycopy(curFilters, 0, newFilters, 0, curFilters.length);
            newFilters[curFilters.length] = lengthFilter;
            view.setFilters(newFilters);
        } else {
            view.setFilters(new InputFilter[]{lengthFilter});
        }
    }

    /**
     * Toast message 보여주기.
     *
     * @param context  컨텍스트
     * @param body     메세지
     * @param duration 노출 시간
     */
    public CommonToast setShowToast(Context context, String body, int duration) {

        CommonToast toast = new CommonToast(context);
        toast.showToast(body, Toast.LENGTH_SHORT);
        return  toast;
    }

    /**
     * 인증 사용자 설정 정보 가져오기
     *
     * @param context 컨텍스트
     */
    public void setUserInfo(Context context) {

        SqlManager sqlManager = new SqlManager();
        appConfig = (AppConfig) context.getApplicationContext();
        appConfig.setLogin_Id("");
        //        mAppConfig.setSearch_Id("");
        //        mAppConfig.setLogin_TermId("");
        //        mAppConfig.setLogin_Phone("");
        //        mAppConfig.setCustNoType("");
        appConfig.setPush(true);
        appConfig.setManualNotView(false);
        appConfig.setAutoLogin(false);
        appConfig.setSaveId(false);

        SQLiteDatabase db = DatabaseOpenHelper.getInstance(context).getWritableDatabase();
        Cursor cursor = db.rawQuery(sqlManager.qryLoginInfo(), null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            appConfig.setLogin_Id(cursor.getString(cursor.getColumnIndex(TblLoginInfo.LOGIN_ID)));
            appConfig.setAuthToken(cursor.getString(cursor.getColumnIndex(TblLoginInfo.LOGIN_PASS)));
            //            if ( null2empty(cursor.getString(cursor.getColumnIndex(TblLoginInfo.SAVE_ID_YN))).equals("Y") ) {
            //                mAppConfig.setSaveId(true);
            //            } else {
            //                mAppConfig.setSaveId(false);
            //            }
            if (null2empty(cursor.getString(cursor.getColumnIndex(TblLoginInfo.AUTO_LOGIN_YN))).equals("Y")) {
                appConfig.setAutoLogin(true);
            } else {
                appConfig.setAutoLogin(false);
            }
            if (null2empty(cursor.getString(cursor.getColumnIndex(TblLoginInfo.SAVE_ID_YN))).equals("Y")) {
                appConfig.setSaveId(true);
            } else {
                appConfig.setSaveId(false);
            }
            if (null2empty(cursor.getString(cursor.getColumnIndex(TblLoginInfo.MANUAL_NOT_VIEW_YN))).equals("N")) {
                appConfig.setManualNotView(false);
            } else {
                appConfig.setManualNotView(true);
            }
            if (null2empty(cursor.getString(cursor.getColumnIndex(TblLoginInfo.PUSH_YN))).equals("Y")) {
                appConfig.setPush(true);
            } else {
                appConfig.setPush(false);
            }
            cursor.moveToNext();
        }
        cursor.close();
        db.close();
    }

    /**
     * 다이얼로그 보여주기.
     *
     * @param dialog 보여줄 dialog
     * @return 보여줄 dialog
     */
    public Dialog dialog_show(Dialog dialog) {

        if (dialog != null) {
            dialog.cancel();
            dialog = null;
        }
        dialog = new Dialog(act, R.style.NTLES_Dialog1);
        dialog.addContentView(new ProgressBar(act, null, android.R.attr.progressBarStyleInverse), new LayoutParams(LayoutParams
                .WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        dialog.show();

        return dialog;
    }

    /**
     * Convert json string to map.
     *
     * @param tmpData Json string
     * @return Converted map
     */
    public HashMap<String, Object> jsonToMap(String tmpData) {

        HashMap<String, Object> map = new HashMap<String, Object>();
        if (null2string(tmpData).equals("")) {
            return map;
        }
        try {
            map = new ObjectMapper().readValue(tmpData, new TypeReference<HashMap<String, Object>>() {
            });
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * Convert json string to map list.
     *
     * @param tmpData Json string
     * @return Converted map list
     */
    public ArrayList<HashMap<String, Object>> jsonToArrayListMap(String tmpData) {

        Dlog.v(tmpData);
        ArrayList<HashMap<String, Object>> map = new ArrayList<HashMap<String, Object>>();
        if (null2string(tmpData).equals("")) {
            return map;
        }
        try {
            map = new ObjectMapper().readValue(tmpData, new TypeReference<ArrayList<HashMap<String, Object>>>() {
            });
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * Convert list to json string.
     *
     * @param tmpData List
     * @return Converted json string
     */
    public String ArrayToJson(Object tmpData) {

        String jsonString = "";
        if (null2string(tmpData).equals("")) {
            return jsonString;
        }
        try {
            jsonString = new ObjectMapper().writeValueAsString(tmpData);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    /**
     * Convert map to json.
     *
     * @param tmpData Map
     * @return Converted json string
     */
    public String MapToJson(Object tmpData) {

        String jsonString = "";
        if (null2string(tmpData).equals("")) {
            return jsonString;
        }
        try {
            //			map = new ObjectMapper().readValue(tmpData, new TypeReference<ArrayList<HashMap<String, Object>>>() {});

            jsonString = new ObjectMapper().writeValueAsString(tmpData);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    /**
     * Convert json to map.
     *
     * @param json Json object
     * @return Converted map
     */
    public HashMap<String, Object> jsonToMap(Object json) {

        HashMap<String, Object> map = new HashMap<String, Object>();
        if (null2string(json.toString()).equals("")) {
            return map;
        }
        map = jsonToMap(json.toString());

        return map;
    }

    /**
     * Convert json to map list.
     *
     * @param json Json object
     * @return Converted map list
     */
    public ArrayList<HashMap<String, Object>> jsonToArrayListMap(Object json) {

        ArrayList<HashMap<String, Object>> map = new ArrayList<HashMap<String, Object>>();
        if (null2string(json.toString()).equals("")) {
            return map;
        }
        map = jsonToArrayListMap(json.toString());

        return map;
    }

    //
    // public Map jsonToMap(JSONObject json) throws JSONException
    // {
    // Map<String, Object> retMap = new HashMap<String, Object>();
    //
    // if(json != JSONObject.NULL)
    // {
    // retMap = toMap(json);
    // }
    // return retMap;
    // }
    //
    // public Map toMap(JSONObject object) throws JSONException
    // {
    // Map<String, Object> map = new HashMap<String, Object>();
    //
    // Iterator<String> keysItr = object.keys();
    // while(keysItr.hasNext())
    // {
    // String key = keysItr.next();
    // Object value = object.get(key);
    //
    // if(value instanceof JSONArray)
    // {
    // value = toList((JSONArray) value);
    // }
    //
    // else if(value instanceof JSONObject)
    // {
    // value = toMap((JSONObject) value);
    // }
    // map.put(key, value);
    // }
    // return map;
    // }
    //
    // public List toList(JSONArray array) throws JSONException
    // {
    // List<Object> list = new ArrayList<Object>();
    // for(int i = 0; i < array.length(); i++)
    // {
    // list.add(array.get(i));
    // }
    // return list;
    // }

    /**
     * 클릭 시 키보드 숨기기 설정.
     *
     * @param act   Target activity
     * @param vView Target view
     */
    public void setKeyboardHide(final Activity act, View vView) {

        vView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                try {
                    InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(act.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                }
            }
        });
    }

    /**
     * 키보드 보여주기.
     *
     * @param act   Target activity
     * @param vView Target view
     */
    public void setKeyboardShow(final Activity act, final EditText vView) {

        try {

            vView.post(new Runnable() {
                @Override
                public void run() {

                    vView.clearFocus();
                    vView.requestFocus();
                    InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(vView, 0);
                }
            });
        } catch (Exception e) {
        }
    }

    /**
     * Mac address 가져오기.
     *
     * @param act {@link Activity}
     * @return Mac address
     */
    public String getMacAdress(Activity act) {

        WifiManager mainWifi = (WifiManager) act.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo this_wifiInfo = mainWifi.getConnectionInfo();
        String mac = this_wifiInfo.getMacAddress();
        return mac;
    }

    /**
     * 폰 고유번호 가져오기.
     *
     * @param act {@link Activity}
     * @return UUID or Mac address
     */
    public String getDeviceId(Activity act) {
        // UUID구하기
        final TelephonyManager tm = (TelephonyManager) act.getSystemService(Context.TELEPHONY_SERVICE);

        String sDeviceId = null2string(tm.getDeviceId());
        String sReturnVal;

        if (sDeviceId.equals("")) {
            sReturnVal = getMacAdress(act);
        } else {
            sReturnVal = sDeviceId;
        }
        return sReturnVal;
    }

    /**
     * 모바일 로밍상태 가져오기.
     *
     * @param act {@link Activity}
     * @return 모바일 로밍 여부
     */
    public Boolean isMobileRoaming(Activity act) {

        Boolean Roaming = false;
        if (availableCommunication(act) == ConnectivityManager.TYPE_MOBILE) {
            // if(true){
            Roaming = isRoaming(act);
            // Roaming = true;
        }
        return Roaming;
    }

    /**
     * 로밍상태 가져오기.
     *
     * @param act {@link Activity}
     * @return 로밍 여부
     */
    public static Boolean isRoaming(Activity act) {

        TelephonyManager tel = (TelephonyManager) act.getSystemService(Context.TELEPHONY_SERVICE);
        //		Dlog.d(mActivity.getPackageName(), "NetworkOperator: " + tel.getNetworkOperator()); // 로밍 사업자 정보
        return tel.isNetworkRoaming(); // 리턴값이 1 인 경우 Roaming 된 상태이며, 0이면 Roaming 되지 않은 상태입니다.
    }

    /**
     * 네트워크 가능 채널 가져오기.
     *
     * @param act {@link Activity}
     * @return 네트워크 가능 타입 코드
     */
    public int availableCommunication(Activity act) {

        ConnectivityManager cm = (ConnectivityManager) act.getSystemService(act.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        boolean isWifiAvail = ni.isAvailable();
        boolean isWifiConn = ni.isConnected();
        ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        boolean isMobileAvail = ni.isAvailable();
        boolean isMobileConn = ni.isConnected();

        String status = "WiFi\nAvail = " + isWifiAvail + "\nConn = " + isWifiConn + "\nMobile\nAvail = " + isMobileAvail + "\nConn = " +
                isMobileConn + "\n";
        //		Dlog.d("Communication State! ", status);

        if (isWifiAvail == true && isWifiConn == true) {
            return ConnectivityManager.TYPE_WIFI;
        } else if (isMobileAvail == true && isMobileConn == true) {
            return ConnectivityManager.TYPE_MOBILE;
        } else {
            return -1;
        }
    }

    /**
     * {@link Activity#startActivityForResult(Intent, int)}
     *
     * @param ctx       {@link Context}
     * @param intentVal {@link Intent}
     * @param iVal      Request code
     * @see Constants
     */
    public void callActivityForResult(final Context ctx, final Intent intentVal, final int iVal) {

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                intentVal.putExtra(Constants.EXTRA_ACT_NAME, ctx.getClass().getSimpleName());
                ((Activity) ctx).startActivityForResult(intentVal, iVal);
                if (!Constants.CHANGE_EVENT_CHECK) {
                    ((Activity) ctx).overridePendingTransition(R.anim.right_in, R.anim.left_out);
                }
            }
        }, 10);
    }

    /**
     * {@link Activity#startActivityForResult(Intent, int)} with animation.
     *
     * @param ctx       ctx {@link Context}
     * @param intentVal {@link Intent}
     * @param iVal      Request code
     * @param sActAnim  Animation type code
     */
    public void callActivityForResult(final Context ctx, final Intent intentVal, final int iVal, final String sActAnim) {

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                intentVal.putExtra(Constants.EXTRA_ACT_NAME, ctx.getClass().getSimpleName());
                intentVal.putExtra(Constants.EXTRA_ACT_ANIM, sActAnim);
                ((Activity) ctx).startActivityForResult(intentVal, iVal);

                String sAnimStart = sActAnim.substring(0, 1);
                if (sAnimStart.equals("1")) {
                    ((Activity) ctx).overridePendingTransition(R.anim.abc_slide_in_top, R.anim.abc_slide_in_top);
                } else if (sAnimStart.equals("2")) {
                    ((Activity) ctx).overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.abc_slide_in_bottom);
                } else if (sAnimStart.equals("3")) {
                    ((Activity) ctx).overridePendingTransition(R.anim.left_in, R.anim.left_in);
                } else if (sAnimStart.equals("4")) {
                    ((Activity) ctx).overridePendingTransition(R.anim.right_in, R.anim.right_in);
                } else {
                    if (!Constants.CHANGE_EVENT_CHECK) {
                        ((Activity) ctx).overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_bottom);
                    }
                }
            }
        }, 10);
    }

    /**
     * {@link Activity#startActivityForResult(Intent, int)} without animation.
     *
     * @param ctx       {@link Context}
     * @param intentVal {@link Intent}
     * @param iVal      Request code
     */
    public void callActivityForResultNoAnim(final Context ctx, final Intent intentVal, final int iVal) {

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                intentVal.putExtra(Constants.EXTRA_ACT_NAME, ctx.getClass().getSimpleName());
                intentVal.putExtra(Constants.EXTRA_ACT_ANIM, "NO");
                ((Activity) ctx).startActivityForResult(intentVal, iVal);
                ((Activity) ctx).overridePendingTransition(0, 0);
            }
        }, 10);
    }

    /**
     * {@link Activity#startActivity(Intent)}
     *
     * @param ctx       {@link Context}
     * @param intentVal {@link Intent}
     */
    public void callActivity(final Context ctx, final Intent intentVal) {

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                intentVal.putExtra(Constants.EXTRA_ACT_NAME, ctx.getClass().getSimpleName());
                ((Activity) ctx).startActivity(intentVal);
                if (!Constants.CHANGE_EVENT_CHECK) {
                    ((Activity) ctx).overridePendingTransition(R.anim.right_in, R.anim.left_out);
                }
            }
        }, 10);
    }

    /**
     * {@link Activity#startActivity(Intent)} with animation.
     *
     * @param ctx       {@link Context}
     * @param intentVal {@link Intent}
     * @param sActAnim  Animaiton type code
     */
    public void callActivity(final Context ctx, final Intent intentVal, final String sActAnim) {

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                intentVal.putExtra(Constants.EXTRA_ACT_NAME, ctx.getClass().getSimpleName());
                intentVal.putExtra(Constants.EXTRA_ACT_ANIM, sActAnim);
                ((Activity) ctx).startActivity(intentVal);

                String sAnimStart = sActAnim.substring(0, 1);
                if (sAnimStart.equals("1")) {
                    ((Activity) ctx).overridePendingTransition(R.anim.abc_slide_in_top, R.anim.abc_slide_in_top);
                } else if (sAnimStart.equals("2")) {
                    ((Activity) ctx).overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.abc_slide_in_bottom);
                } else if (sAnimStart.equals("3")) {
                    ((Activity) ctx).overridePendingTransition(R.anim.left_in, R.anim.left_in);
                } else if (sAnimStart.equals("4")) {
                    ((Activity) ctx).overridePendingTransition(R.anim.right_in, R.anim.right_in);
                } else {
                    if (!Constants.CHANGE_EVENT_CHECK) {
                        ((Activity) ctx).overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_bottom);
                    }
                }
            }
        }, 5);
    }

    /**
     * {@link Activity#startActivity(Intent)} without animation.
     *
     * @param ctx       {@link Context}
     * @param intentVal {@link Intent}
     */
    public void callActivityNoAnim(final Context ctx, final Intent intentVal) {

//    Handler handler = new Handler();
        Handler handler = new Handler(Looper.getMainLooper());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                intentVal.putExtra(Constants.EXTRA_ACT_NAME, ctx.getClass().getSimpleName());
                intentVal.putExtra(Constants.EXTRA_ACT_ANIM, "NO");
                ((Activity) ctx).startActivity(intentVal);
                ((Activity) ctx).overridePendingTransition(0, 0);
            }
        }, 5);
    }

    /**
     * 이메일 패턴 체크.
     *
     * @param email Email
     * @return 체크 여부
     */
    public static boolean isEmail(String email) {

        if (email == null)
            return false;
        boolean b = Pattern.matches("[\\w\\~\\-\\.]+@[\\w\\~\\-]+(\\.[\\w\\~\\-]+)+", email.trim());
        return b;
    }

    /**
     * Convert double to int
     *
     * @param val Target double
     * @return Converted int
     */
    public int double2int(double val) {

        int tmp = 0;
        Double d = val;
        tmp = d.intValue();
        return tmp;
    }

    /**
     * Convert double to int
     *
     * @param val Target double with string
     * @return Converted int
     */
    public int double2int(String val) {

        int tmp = 0;
        Double d = new Double(val);
        tmp = d.intValue();
        return tmp;
    }

    /**
     * Get edit text view.
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return {@link EditText}
     */
    public EditText getEditText(Context context, int RItem) {

        return ((EditText) ((Activity) context).findViewById(RItem));
    }

    /**
     * Get edit text view.
     *
     * @param view  Root view
     * @param RItem Resource id
     * @return {@link EditText}
     */
    public EditText getEditText(View view, int RItem) {

        return ((EditText) view.findViewById(RItem));
    }

    /**
     * Get edit text value.
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return Edit text value
     */
    public String getEditTextVal(Context context, int RItem) {

        String tmp = ((EditText) ((Activity) context).findViewById(RItem)).getText().toString();
        if (tmp == null)
            tmp = "";
        return tmp;
    }

    /**
     * Get text view.
     *
     * @param view  Root view
     * @param RItem Resource id
     * @return {@link TextView}
     */
    public TextView getTextView(View view, int RItem) {

        return ((TextView) view.findViewById(RItem));
    }

    /**
     * Get text view.
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return {@link TextView}
     */
    public TextView getTextView(Context context, int RItem) {

        return ((TextView) ((Activity) context).findViewById(RItem));
    }

    /**
     * Get image view.
     *
     * @param view  Root view
     * @param RItem Resource id
     * @return {@link ImageView}
     */
    public ImageView getImageView(View view, int RItem) {

        return ((ImageView) view.findViewById(RItem));
    }

    /**
     * Get image view.
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return {@link ImageView}
     */
    public ImageView getImageView(Context context, int RItem) {

        return ((ImageView) ((Activity) context).findViewById(RItem));
    }

    /**
     * {@link ImageView#setImageResource(int)}
     *
     * @param context     {@link Context}
     * @param resourceId  Image resource id
     * @param imageViewId View resource id
     */
    public void setImage(final Context context, final int resourceId, final int imageViewId) {

        getImageView(context, imageViewId).setImageResource(resourceId);
    }

    /**
     * {@link ImageView#setImageResource(int)}
     *
     * @param resourceId Image resource id
     * @param imageView  ImageView
     */
    public void setImage(final int resourceId, final ImageView imageView) {

        imageView.setImageResource(resourceId);
    }

    /**
     * {@link ImageView#setImageResource(int)}
     *
     * @param context     {@link Context}
     * @param imageName   Image resource name
     * @param imageViewId ImageView resource id
     */
    public void setImage(Context context, String imageName, int imageViewId) {

        String imageFileName = "";
        int imageResourceId = 0;
        if (imageName.contains("/")) {
            int startIndex = imageName.lastIndexOf("/") + 1;
            int endIndex = imageName.lastIndexOf(".");
            imageFileName = imageName.substring(startIndex, endIndex);
        } else {
            imageFileName = imageName;
        }
        LogUtil.i(TAG, "Image file name : " + imageFileName);
        imageResourceId = getImageId(context, "img_" + imageFileName);
        getImageView(context, imageViewId).setImageResource(imageResourceId);
    }

    /**
     * {@link ImageView#setImageResource(int)}
     *
     * @param context   {@link Context}
     * @param imageName Image resource name
     * @param imageView ImageView
     */
    public void setImage(Context context, String imageName, ImageView imageView) {

        String imageFileName = "";
        int imageResourceId = 0;
        if (imageName.contains("/")) {
            int startIndex = imageName.lastIndexOf("/") + 1;
            int endIndex = imageName.lastIndexOf(".");
            imageFileName = imageName.substring(startIndex, endIndex);
        } else {
            imageFileName = imageName;
        }
        LogUtil.i(TAG, "Image file name : " + imageFileName);
        imageResourceId = getImageId(context, "img_" + imageFileName);
        imageView.setImageResource(imageResourceId);
    }

    /**
     * Get image resource id
     *
     * @param context       {@link Context}
     * @param sResourceName Image resource name
     * @return image resource id
     */
    public int getImageId(Context context, String sResourceName) {
        return context.getResources().getIdentifier(sResourceName, "drawable", context.getPackageName());
    }

    /**
     * Image refresh.
     *
     * @param context {@link Context}
     * @param sVal    File name
     * @param Ritem   ImageView resource id
     */
    public void setRefreshImage(final Context context, final String sVal, final int Ritem) {

        if (!sVal.equals("")) {
            File files = new File(sVal);
            //파일 유무를 확인합니다.
            if (files.exists() == true) {
                Picasso.with(context).load(files).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into
                        (getImageView(context, Ritem));
            } else {
                Picasso.with(context).load(sVal).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into
                        (getImageView(context, Ritem));
            }
        }
    }

    /**
     * Image refresh.
     *
     * @param context {@link Context}
     * @param sVal    File name
     * @param iView   ImageView
     */
    public void setRefreshImage(final Context context, final String sVal, final ImageView iView) {

        if (!sVal.equals("")) {
            File files = new File(sVal);
            //파일 유무를 확인합니다.
            if (files.exists() == true) {
                Picasso.with(context).load(files).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(iView);
            } else {
                Picasso.with(context).load(sVal).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(iView);
            }
        }
    }

    /**
     * Get {@link RelativeLayout}.
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return {@link RelativeLayout}
     */
    public RelativeLayout getRelativeLayout(Context context, int RItem) {

        return ((RelativeLayout) ((Activity) context).findViewById(RItem));
    }

    /**
     * Get {@link ScrollView} .
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return {@link ScrollView}
     */
    public ScrollView getScrollView(Context context, int RItem) {

        return ((ScrollView) ((Activity) context).findViewById(RItem));
    }

    /**
     * Get {@link LinearLayout}.
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return {@link LinearLayout}
     */
    public LinearLayout getLinearLayout(Context context, int RItem) {

        return ((LinearLayout) ((Activity) context).findViewById(RItem));
    }

    /**
     * Get {@link LinearLayout}.
     *
     * @param view  Root view
     * @param RItem Resource id
     * @return {@link LinearLayout}
     */
    public LinearLayout getLinearLayout(View view, int RItem) {

        return ((LinearLayout) (View) view.findViewById(RItem));
    }

    /**
     * Get {@link GridLayout}.
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return {@link GridLayout}
     */
    public GridLayout getGridLayout(Context context, int RItem) {

        return ((GridLayout) ((Activity) context).findViewById(RItem));
    }

    /**
     * Get {@link GridLayout}.
     *
     * @param view  Root view
     * @param RItem Resource id
     * @return {@link GridLayout}
     */
    public GridLayout getGridLayout(View view, int RItem) {

        return ((GridLayout) (View) view.findViewById(RItem));
    }

    /**
     * Get {@link Button}.
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return {@link Button}
     */
    public Button getButton(Context context, int RItem) {

        return ((Button) ((Activity) context).findViewById(RItem));
    }

    /**
     * Get {@link Button}.
     *
     * @param view  Root view
     * @param RItem Resource id
     * @return {@link Button}
     */
    public Button getButton(View view, int RItem) {

        return ((Button) (View) view.findViewById(RItem));
    }

    /**
     * Get {@link View}.
     *
     * @param context {@link Context}
     * @param RItem   Resource id
     * @return {@link View}
     */
    public View getView(Context context, int RItem) {

        return ((View) ((Activity) context).findViewById(RItem));
    }

    /**
     * Get {@link View}.
     *
     * @param view  Root view
     * @param RItem Resource id
     * @return {@link View}
     */
    public View getView(View view, int RItem) {

        return (View) view.findViewById(RItem);
    }

    public String getInsetValues(Object oVal) {

        return null2empty(oVal).toString().replace("\'", "\''").replace("\"", "\\\"");
    }

    public String getInsetValues(String sVal) {

        return null2empty(sVal).toString().replace("\'", "\''").replace("\"", "\\\"");
    }

    public void getViewUnderline(Context context, int RItem) {

        SpannableString content1 = new SpannableString(getTextViewVal(context, RItem));
        content1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
        getTextView(context, RItem).setText(content1);
    }

    public void getViewUnderline(View view, int RItem) {

        SpannableString content1 = new SpannableString(getTextViewVal(view, RItem));
        content1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
        getTextView(view, RItem).setText(content1);
    }

    public void getViewUnderline(TextView vView) {

        SpannableString content1 = new SpannableString(vView.getText().toString());
        content1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
        vView.setText(content1);
    }

    public void setImageViewGrayScale(ImageView v) {

        ColorMatrix matrix = new ColorMatrix();
        matrix.setSaturation(0);                        //0이면 grayscale
        ColorMatrixColorFilter cf = new ColorMatrixColorFilter(matrix);
        v.setColorFilter(cf);
    }

    //drawable만 grayscale로 변경
    public Drawable convertGrayScale(Drawable d) {

        ColorMatrix matrix = new ColorMatrix();
        matrix.setSaturation(0);                    //0이면 grayscale
        ColorMatrixColorFilter cf = new ColorMatrixColorFilter(matrix);
        d.setColorFilter(cf);

        return d;
    }

    public float getDisplayScale(Context context) {

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        return dm.scaledDensity;
    }

    //
    public String getTextViewVal(View view, int RItem) {

        String tmp = ((TextView) view.findViewById(RItem)).getText().toString();
        if (tmp == null)
            tmp = "";
        return tmp;
    }

    public String getTextViewVal(Context context, int RItem) {

        String tmp = ((TextView) ((Activity) context).findViewById(RItem)).getText().toString();
        if (tmp == null)
            tmp = "";
        return tmp;
    }

    public String null2empty(String str) {

        if (str == null)
            str = "";
        return str;
    }

    public Object null2empty(Object str) {

        if (str == null)
            str = "";
        return str;
    }

    public String null2string(Object str) {

        if (str == null)
            str = "";
        return str.toString();
    }

    public double null2double(Object txt) {

        BigDecimal num;
        if (txt == null || "".equals(txt.toString())) {
            num = new BigDecimal("0.0");
        } else {
            num = new BigDecimal(txt.toString());
        }
        return num.doubleValue();
    }

    public int null2int(Object str) {

        if (str == null)
            str = "";
        return str2int(str.toString());
    }

    public int find(String[] arr, String s) {

        for (int i = 0; i < arr.length; i++) {
            if (arr[i].indexOf(s) >= 0) {
                return i;
            }
        }
        return -1;
    }

    public String getStringValues(Context context, String msgno) {

        String msg = "";
        try {
            int getRes = context.getResources().getIdentifier(msgno, "string", context.getPackageName());
            msg = context.getResources().getString(getRes);
        } catch (Exception e) {
        }
        return msg;
    }

    public int getIDvalues(Context context, String sIdVal) {

        int getRes = 0;
        try {
            getRes = context.getResources().getIdentifier(sIdVal, "id", context.getPackageName());
        } catch (Exception e) {
        }
        return getRes;
    }

    public String[] getStringArrayValues(Context context, String msgno) {

        String[] msg = null;
        try {
            int getRes = context.getResources().getIdentifier(msgno, "array", context.getPackageName());
            msg = context.getResources().getStringArray(getRes);
        } catch (Exception e) {
        }
        return msg;
    }

    public String getStringValues(Context context, int imsgno) {

        int getRes = context.getResources().getIdentifier("MSG" + imsgno, "string", context.getPackageName());
        String msg = context.getResources().getString(getRes);
        return msg;
    }

    public String getString(Context context, int iStrNo) {

        String msg = context.getResources().getString(iStrNo);
        return msg;
    }

    public String getString(Context context, int iStrNo, Object... formatArgs) {
        String msg = context.getResources().getString(iStrNo, formatArgs);
        return msg;
    }

    public void setPreferences(Context context, String prefs_col, String str) {

        String str1 = "";
        SeedCipherSvcImpl miniSeed = new SeedCipherSvcImpl();
        CryptoPaddingSvcImpl miniPaddingSvc = new CryptoPaddingSvcImpl();
        miniSeed.setCryptoPaddingSvc(miniPaddingSvc);
        Dlog.v("******************" + prefs_col + "=" + str);
        try {
            SharedPreferences prefs = context.getSharedPreferences(prefs_name, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            str1 = new String(miniSeed.encryptBase64(str));
            editor.putString(prefs_col, str1);
            editor.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        Dlog.v("******************" + prefs_col + "=" + str1);
    }

    public void setPreferences(Service mService, String prefs_col, String str) {

        try {
            SharedPreferences prefs = mService.getSharedPreferences(prefs_name, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();

            SeedCipherSvcImpl miniSeed = new SeedCipherSvcImpl();
            CryptoPaddingSvcImpl miniPaddingSvc = new CryptoPaddingSvcImpl();
            miniSeed.setCryptoPaddingSvc(miniPaddingSvc);
            String str1 = new String(miniSeed.encryptBase64(str));
            editor.putString(prefs_col, str1);
            editor.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    //    public String getPreferences(Service mService, String prefs_col) {
    //
    //        String str = "", str1 = "";
    //        SeedCipherSvcImpl miniSeed = new SeedCipherSvcImpl();
    //        CryptoPaddingSvcImpl miniPaddingSvc = new CryptoPaddingSvcImpl();
    //        miniSeed.setCryptoPaddingSvc(miniPaddingSvc);
    //        try {
    //            SharedPreferences prefs = mService.getSharedPreferences(prefs_name, Context.MODE_PRIVATE);
    //            str = prefs.getString(prefs_col, "");
    //            if ( str == null ) {
    //                str1 = "";
    //            } else {
    //                str1 = new String(miniSeed.decryptAsStringBase64(str.trim()));
    //            }
    //        } catch (Exception ex) {
    //            ex.printStackTrace();
    //        }
    //        Dlog.v("******************" + prefs_col + "=" + str);
    //        Dlog.v("******************" + prefs_col + "=" + str1);
    //        return str1;
    //    }

    public String getPreferences(Context context, String prefs_col) {

        String str = "", str1 = "";
        SeedCipherSvcImpl miniSeed = new SeedCipherSvcImpl();
        CryptoPaddingSvcImpl miniPaddingSvc = new CryptoPaddingSvcImpl();
        miniSeed.setCryptoPaddingSvc(miniPaddingSvc);
        try {
            SharedPreferences prefs = context.getSharedPreferences(prefs_name, Context.MODE_PRIVATE);
            str = prefs.getString(prefs_col, "");
            if (str == null) {
                str1 = "";
            } else {
                str1 = new String(miniSeed.decryptAsStringBase64(str.trim()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        Dlog.v("******************" + prefs_col + "=" + str);
        Dlog.v("******************" + prefs_col + "=" + str1);
        return str1;
    }

    public String setEncryption(String str) {

        try {
            SeedCipherSvcImpl miniSeed = new SeedCipherSvcImpl();
            CryptoPaddingSvcImpl miniPaddingSvc = new CryptoPaddingSvcImpl();
            miniSeed.setCryptoPaddingSvc(miniPaddingSvc);
            String str1 = new String(miniSeed.encryptBase64(str));
            return str1;
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

    public String setDecryption(String str) {

        try {
            SeedCipherSvcImpl miniSeed = new SeedCipherSvcImpl();
            CryptoPaddingSvcImpl miniPaddingSvc = new CryptoPaddingSvcImpl();
            miniSeed.setCryptoPaddingSvc(miniPaddingSvc);
            String str1 = new String(miniSeed.decryptAsStringBase64(str.trim()));
            return str1;
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }

    // public String getPreferences(Context mContext, String prefs_col) {
    // String str = "", str1 = "";
    // try {
    // SeedCipherSvcImpl miniSeed = new SeedCipherSvcImpl();
    // CryptoPaddingSvcImpl miniPaddingSvc = new CryptoPaddingSvcImpl();
    // SharedPreferences prefs = mContext.getSharedPreferences(prefs_name, Context.MODE_PRIVATE);
    // str = prefs.getString(prefs_col, "");
    // if (str == null) {
    // str1 = "";
    // } else {
    // str1 = new String(miniSeed.decryptAsStringBase64(str.trim()));
    // }
    // } catch (Exception ex) {
    // ex.printStackTrace();
    // }
    // return str1;
    // }

    // 파라미터를 body로 변환
    public String convPostBody(List<HashMap<String, Object>> params) throws UnsupportedEncodingException {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (int i = 0; i < params.size(); i++) {
            if (first) {
                first = false;
            } else {
                result.append("&");
            }

            for (Map.Entry<String, Object> entry : params.get(i).entrySet()) {
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(null2string(entry.getValue()), "UTF-8"));
            }
        }

        return result.toString();
    }

    // 파라미터를 get로 변환
    public String convGetRest(List<HashMap<String, Object>> params) throws UnsupportedEncodingException {

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            for (Map.Entry<String, Object> entry : params.get(i).entrySet()) {
                result.append("/");
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("/");
                result.append(URLEncoder.encode(null2string(entry.getValue()), "UTF-8"));
            }
        }

        return result.toString();
    }

    // 파라미터를 get로 변환
    public String convGetRestReplace(String sURL, String sParam, String sValue) throws UnsupportedEncodingException {

        sURL = sURL.replaceAll(":" + sParam, URLEncoder.encode(sValue, "UTF-8"));
        return sURL;
    }

    // 파라미터를 get로 변환
    public String convGetParam(List<HashMap<String, Object>> params) throws UnsupportedEncodingException {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (int i = 0; i < params.size(); i++) {
            if (first) {
                result.append("?");
                first = false;
            } else {
                result.append("&");
            }

            for (Map.Entry<String, Object> entry : params.get(i).entrySet()) {
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(null2string(entry.getValue()), "UTF-8"));
            }
        }

        return result.toString();
    }

    public String convPostBodyJson(List<HashMap<String, Object>> params) throws UnsupportedEncodingException, JSONException {

        JSONObject joResult = new JSONObject();
        for (int i = 0; i < params.size(); i++) {
            for (Map.Entry<String, Object> entry : params.get(i).entrySet()) {
                joResult.put(entry.getKey(), null2string(entry.getValue()));
            }
        }
        //		String sMsg = "{" + joResult.toString() + "}";
        //		return sMsg;
        return joResult.toString();
    }

    public String convComma(long lVal) {

        long value = lVal;
        DecimalFormat format = new DecimalFormat("###,###");
        return format.format(value);
    }

    public String convComma(long lVal, String sVal) {

        long value = lVal;
        DecimalFormat format = new DecimalFormat("###,###");
        return format.format(value) + sVal;
    }

    public String convComma(String sVal1, String sVal2) {

        long value = str2long(sVal1);
        DecimalFormat format = new DecimalFormat("###,###");
        return format.format(value) + sVal2;
    }

    public String convComma(Object oVal1) {

        long value = str2long(null2empty(oVal1).toString());
        DecimalFormat format = new DecimalFormat("###,###");

        Dlog.v(value + "");
        return format.format(value);
    }

    public String convComma(Object oVal1, String sVal2) {

        long value = str2long(null2empty(oVal1).toString());
        DecimalFormat format = new DecimalFormat("###,###");

        Dlog.v(value);
        return format.format(value) + sVal2;
    }

    //	public static String getTime() {
    //		// decimalformat은 숫자에 대한 자바 포멧 00은 두자리로표현
    //		DecimalFormat decimalFormat = new DecimalFormat("00");
    //		// 현재 날짜 가져오기 시간 분 까지 가능
    //		// 날짜 불러오는 함수
    //		Calendar rightNow = Calendar.getInstance();
    //		int year = rightNow.get(Calendar.YEAR) % 100;
    //		int month = rightNow.get(Calendar.MONTH);
    //		int date = rightNow.get(Calendar.DATE);
    //		int hour = rightNow.get(Calendar.HOUR);
    //		int min = rightNow.get(Calendar.MINUTE);
    //		int sec = rightNow.get(Calendar.SECOND);
    //		String result = decimalFormat.format(year) + decimalFormat.format(month) + decimalFormat.format(date) + decimalFormat.format
  // (hour) + decimalFormat.format(min) + decimalFormat.format(sec);
    //		return result;
    //	}

    public String getTimeAdd(String sVal, int iVal) {

        String newTime = "";
        try {
            String myTime = sVal;
            SimpleDateFormat df = new SimpleDateFormat("HH:mm");
            Date d = df.parse(myTime);
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            cal.add(Calendar.MINUTE, iVal);
            newTime = df.format(cal.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return newTime;
    }

    public String getTimeHOUR() {
        // decimalformat은 숫자에 대한 자바 포멧 00은 두자리로표현
        DecimalFormat decimalFormat = new DecimalFormat("00");
        // 현재 날짜 가져오기 시간 분 까지 가능
        // 날짜 불러오는 함수
        Calendar rightNow = Calendar.getInstance();
        int year = rightNow.get(Calendar.YEAR) % 100;
        int month = rightNow.get(Calendar.MONTH);
        int date = rightNow.get(Calendar.DATE);
        int hour = rightNow.get(Calendar.HOUR);
        int min = rightNow.get(Calendar.MINUTE);
        int sec = rightNow.get(Calendar.SECOND);
        String result = decimalFormat.format(hour);
        return result;
    }

    public String getTimeMINUTE() {
        // decimalformat은 숫자에 대한 자바 포멧 00은 두자리로표현
        DecimalFormat decimalFormat = new DecimalFormat("00");
        // 현재 날짜 가져오기 시간 분 까지 가능
        // 날짜 불러오는 함수
        Calendar rightNow = Calendar.getInstance();
        int year = rightNow.get(Calendar.YEAR) % 100;
        int month = rightNow.get(Calendar.MONTH);
        int date = rightNow.get(Calendar.DATE);
        int hour = rightNow.get(Calendar.HOUR);
        int min = rightNow.get(Calendar.MINUTE);
        int sec = rightNow.get(Calendar.SECOND);
        String result = decimalFormat.format(min);
        return result;
    }

    public String getTimeAM_PM() {
        // decimalformat은 숫자에 대한 자바 포멧 00은 두자리로표현
        DecimalFormat decimalFormat = new DecimalFormat("00");
        // 현재 날짜 가져오기 시간 분 까지 가능
        // 날짜 불러오는 함수
        Calendar rightNow = Calendar.getInstance();
        int year = rightNow.get(Calendar.YEAR) % 100;
        int month = rightNow.get(Calendar.MONTH);
        int date = rightNow.get(Calendar.DATE);
        int hour = rightNow.get(Calendar.HOUR);
        int min = rightNow.get(Calendar.MINUTE);
        int sec = rightNow.get(Calendar.SECOND);
        String result = "";
        if (rightNow.get(Calendar.AM_PM) == Calendar.PM) {
            result = "PM";
        } else {
            result = "AM";
        }
        return result;
    }

    public int str2int(String txt) {

        int num = 0;
        if (txt == null || "".equals(txt)) {

        } else {
            num = double2int(txt);
        }
        return num;
    }

    /**
     * <p> 문자열이 공백("")이거나 <code>null</code>인 검사한다. </p>
     * <pre>
     * StringUtils.isEmpty(null)    = true
     * StringUtils.isEmpty("")      = true
     * StringUtils.isEmpty("   ")   = false
     * StringUtils.isEmpty("han")   = false
     * StringUtils.isEmpty(" han ") = false
     * </pre>
     *
     * @param str 검사할 문자열
     */
    public boolean isEmpty(String str) {

        return str == null || str.length() == 0;
    }

    public String PhoneNo(String sPhone, String sGubun1) {

        String sNewPhone = "";
        if (sPhone.length() == 11) {
            sNewPhone = sPhone.substring(0, 3) + sGubun1 + sPhone.substring(3, 7) + sGubun1 + sPhone.substring(7, 11);
        } else if (sPhone.length() == 10) {
            sNewPhone = sPhone.substring(0, 3) + sGubun1 + sPhone.substring(3, 6) + sGubun1 + sPhone.substring(6, 10);
        }
        return sNewPhone;
    }

    //
    // 인증 사용자 설정 정보 가져오기
    // public void setUserInfo(Context mContext) {
    // SqlManager sqlManager = new SqlManager();
    // mAppConfig = (AppConfig) mContext.getApplicationContext();
    // mAppConfig.setLogin_CustBirth("");
    // mAppConfig.setLogin_MobieAgenyCd("");
    // mAppConfig.setLogin_Name("");
    // mAppConfig.setLogin_Id("");
    // mAppConfig.setSearch_Id("");
    // mAppConfig.setLogin_TermId("");
    // mAppConfig.setLogin_Phone("");
    // mAppConfig.setCustNoType("");
    //
    // SQLiteDatabase db = DatabaseOpenHelper.getInstance(mContext).getWritableDatabase();
    // Cursor cursor = db.rawQuery(sqlManager.QueryLoginInfo(), null);
    // cursor.moveToFirst();
    // while (!cursor.isAfterLast()) {
    // // mAppConfig.setLogin_CustBirth(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_BIRTH)));
    // // mAppConfig.setLogin_MobieAgenyCd(cursor.getString(cursor.getColumnIndex(BillLoginInfo.MOBILE_AGENCY_CD)));
    // // mAppConfig.setLogin_Name(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_NAME)));
    // // mAppConfig.setLogin_Id(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_ID)));
    // // mAppConfig.setSearch_Id(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_ID)));
    // // mAppConfig.setLogin_TermId(cursor.getString(cursor.getColumnIndex(BillLoginInfo.TERM_ID)));
    // // mAppConfig.setLogin_Phone(cursor.getString(cursor.getColumnIndex(BillLoginInfo.MOBILE_SVC_NO)));
    // // mAppConfig.setCustNoType(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_NO_TYPE)));
    //
    // mAppConfig.setLogin_CustBirth(setDecryption(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_BIRTH))));
    // mAppConfig.setLogin_MobieAgenyCd(setDecryption(cursor.getString(cursor.getColumnIndex(BillLoginInfo.MOBILE_AGENCY_CD))));
    // mAppConfig.setLogin_Name(setDecryption(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_NAME))));
    // mAppConfig.setLogin_Id(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_ID)));
    // mAppConfig.setSearch_Id(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_ID)));
    // mAppConfig.setLogin_TermId(setDecryption(cursor.getString(cursor.getColumnIndex(BillLoginInfo.TERM_ID))));
    // mAppConfig.setLogin_Phone(setDecryption(cursor.getString(cursor.getColumnIndex(BillLoginInfo.MOBILE_SVC_NO))));
    // mAppConfig.setCustNoType(setDecryption(cursor.getString(cursor.getColumnIndex(BillLoginInfo.CUST_NO_TYPE))));
    // cursor.moveToNext();
    // }
    // cursor.close();
    // db.close();
    // }

    // setEncryption
    //
    // public String sendDataRowMake(String str1, String str2) {
    // String sTemp = "";
    //
    // sTemp = "<" + str1 + "><![CDATA[" + str2 + "]]></" + str1 + ">\n";
    //
    // return sTemp;
    // }
    //
    // public String sendDataRowMake2(String str1, String str2) {
    // String sTemp = "";
    //
    // sTemp = "<" + str1 + ">" + str2 + "</" + str1 + ">\n";
    //
    // return sTemp;
    // }
    //
    // public void setAuthHM(Context mContext, HashMap<String, String> hm) {
    // mAppConfig.authHM = hm;
    // }
    //
    // public void setAuthMyInfoHM(Context mContext, HashMap<String, String> hm) {
    // mAppConfig.authMyInfoHM = hm;
    // }
    //
    // public void setAuthStyleConfigHM(Context mContext, HashMap<String, String>
    // hm) {
    // mAppConfig.authStyleConfigHM = hm;
    // }
    //
    // public void setAuthListHM(Context mContext, ArrayList<HashMap<String,
    // String>> hm) {
    // mAppConfig.authListHM = hm;
    // }
    //
    //
    // public void setPreferencesContext(Context mContext, String prefs_col,
    // String str) {
    // try {
    // SharedPreferences prefs = mContext.getSharedPreferences(prefs_name,
    // Context.MODE_PRIVATE);
    // SharedPreferences.Editor editor = prefs.edit();
    //
    // miniSeed.setCryptoPaddingSvc(miniPaddingSvc);
    // String str1 = new String(miniSeed.encryptBase64(str));
    // editor.putString(prefs_col, str1);
    // editor.commit();
    // } catch (Exception ex) {
    // ex.printStackTrace();
    // }
    // }
    //
    // public String str2acv(Context mContext, String sStr) {
    // String str1 = "";
    // try {
    // miniSeed.setCryptoPaddingSvc(miniPaddingSvc);
    // str1 = new String(miniSeed.encryptBase64(sStr));
    // } catch (Exception ex) {
    // ex.printStackTrace();
    // }
    // return str1;
    // }
    //
    // public String acv2str(Context mContext, String sStr) {
    // String str1 = "";
    // try {
    // miniSeed.setCryptoPaddingSvc(miniPaddingSvc);
    // str1 = new String(miniSeed.decryptAsStringBase64(sStr.trim()));
    // } catch (Exception ex) {
    // ex.printStackTrace();
    // }
    // return str1;
    // }
    //
    //
    //
    // public String getServicePreferences(Service mService, String prefs_col) {
    // String str = "", str1 = "";
    // try {
    // SharedPreferences prefs = mService.getSharedPreferences(prefs_name,
    // Context.MODE_PRIVATE);
    // str = prefs.getString(prefs_col, "");
    // if (str == null) {
    // str1 = "";
    // } else {
    // str1 = new String(miniSeed.decryptAsStringBase64(str.trim()));
    // }
    // } catch (Exception ex) {
    // ex.printStackTrace();
    // }
    // return str1;
    // }
    //
    //
    // public String str_replace_i(String src, String des, String org) {
    //
    // String org_upper = org.toUpperCase();
    // String src_upper = src.toUpperCase();
    // int fromindex = 0;
    // int toindex = 0;
    // String replaced = "";
    // int i = 0;
    // if ("".equals(src) || src == null) {
    // replaced = org;
    // } else {
    // while (fromindex >= 0) {
    // if (i == 0) {
    // toindex = org_upper.indexOf(src_upper, 0);
    // if (toindex < 0) {
    // replaced = org.substring(0, org_upper.length());
    // break;
    // } else {
    // replaced = org.substring(0, toindex);
    // replaced += des;
    // }
    // } else {
    // toindex = org_upper.indexOf(src_upper, fromindex + src.length());
    // if (toindex < 0) {
    // replaced += org.substring(fromindex + src.length(), org.length());
    // break;
    // } else {
    // replaced += org.substring(fromindex + src.length(), toindex);
    // replaced += des;
    // }
    // }
    // fromindex = toindex;
    // i++;
    // }
    // }
    // return replaced;
    //
    // }
    //

    public float str2float(String txt) {

        float num = 0;
        if (txt == null || "".equals(txt)) {

        } else {
            num = Float.parseFloat(txt);
        }
        return num;
    }

    public double str2double(String txt) {

        //        double num = 0;
        //        if ( txt == null || "".equals(txt) ) {
        //            num = 0.0;
        //        } else {
        ////            num = Double.valueOf(txt).doubleValue();
        ////            num = Double.parseDouble(txt);
        //
        //            num = new BigDecimal(txt).doubleValue();
        //        }
        //
        //        return num;
        BigDecimal num;
        if (txt == null || "".equals(txt)) {
            num = new BigDecimal("0.0");
        } else {
            num = new BigDecimal(txt);
        }
        return num.doubleValue();
    }

    public String minDouble(Double dVal) {

        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);//소수점 아래 최소 자리수
        nf.setMaximumFractionDigits(10);//소수점 아래 최대자리수

        return nf.format(dVal);
    }

    public double doubleMinus(double d1, double d2) {

        BigDecimal bd1 = new BigDecimal(String.valueOf(d1));
        BigDecimal bd2 = new BigDecimal(String.valueOf(d2));

        return bd1.subtract(bd2).doubleValue();
    }

    public double doubleAdd(double d1, double d2) {

        BigDecimal bd1 = new BigDecimal(String.valueOf(d1));
        BigDecimal bd2 = new BigDecimal(String.valueOf(d2));

        return bd1.add(bd2).doubleValue();
    }

    public double doubleMinus(String s1, String s2) {

        BigDecimal bd1 = new BigDecimal(String.valueOf(str2double(s1)));
        BigDecimal bd2 = new BigDecimal(String.valueOf(str2double(s2)));

        return bd1.subtract(bd2).doubleValue();
    }

    public double doubleAdd(String s1, String s2) {

        BigDecimal bd1 = new BigDecimal(String.valueOf(str2double(s1)));
        BigDecimal bd2 = new BigDecimal(String.valueOf(str2double(s2)));

        return bd1.add(bd2).doubleValue();
    }

    public String getIntegParsing(int iTemp) {

        DecimalFormat df = new DecimalFormat("#,##0");

        return df.format(iTemp);
    }

    // FREE_MIN_TOTAL,FREE_MIN_USE, FREE_MIN_ROLL,FREE_MIN_CUR,
    // FREE_MIN_REMAIN,CTN_SECS, SECS_TO_RATE
    // SECS_TO_AMT 의 경우 단위는 '원'이고, 표시법은 3자리마다 ','표시
    // 표기법
    // -- 아래와 같이 변환후에 UNIT값을 뒤에 붙이면 됨.

    /**
     * 단위 표시
     */

    public String getAmountByBunGun(String bunGun, String strValue1, String strUnit) {

        String strResult = "";

        strValue1 = (strValue1 == null || "".equals(strValue1)) ? "0" : strValue1;

        if (bunGun.equals("P")) {
            // strResult = strValue1;
            // double iTemp = (Double.parseDouble(strValue1) * 0.5)/1024;
            // if (iTemp > 1){
            // strResult = format((Double.parseDouble(strValue1) * 0.5)/1024,
            // "#,###")+"MB";
            // } else {
            // strResult = format((Double.parseDouble(strValue1) * 0.5),
            // "#,###")+strUnit;
            // }
            if (strValue1.equals("999999999")) {
                strResult = "무제한";
            } else {
                strResult = format((int) (Double.parseDouble(strValue1) * 0.5) / 1024, "#,###") + "MB";
            }
        } else if (bunGun.equals("D")) {
            strResult = strValue1 + strUnit;
        } else if (bunGun.equals("W")) {
            strResult = format(Integer.parseInt(strValue1), "#,###") + strUnit;
        } else if (bunGun.equals("V")) {
            strResult = (Integer.parseInt(strValue1) / 60) + getString(act, R.string.layout_minute) + " " + (Integer.parseInt(strValue1)
                    % 60) + "초" + strUnit;
        } else {
            strResult = strValue1;
        }

        return strResult;
    }

    public int getArraryFind(String[] arr, String s) {

        for (int i = 0; i < arr.length; i++) {
            if (arr[i].indexOf(s) >= 0)
                return i;
        }
        return -1;
    }
    //
    // public Activity findAct(Context mContext, String menuClass) {
    // String foundClass = "";
    // Class<?> cls;
    // Context contextCategory = null;
    // try {
    // cls = Class.forName(menuClass);
    // actCategory = (Activity) cls.newInstance();
    // foundClass = cls.getName();
    // } catch (ClassNotFoundException e) {
    // foundClass = "";
    // AlertDialog dialog = new AlertDialog.Builder(mContext).create();
    // dialog.setTitle("안내");
    // dialog.setMessage("죄송합니다.\n페이지를 찾을 수 없습니다.");
    // dialog.setButton("확인", new DialogInterface.OnClickListener() {
    // @Override
    // public void onClick(DialogInterface dialog, int which) {
    // return;
    // }
    // });
    // dialog.show();
    // } catch (InstantiationException e) {
    //
    // } catch (IllegalAccessException e) {
    //
    // }
    // return actCategory;
    // }
    //
    // public HashMap<String, String> getAuthHM(Context mContext) {
    // HashMap<String, String> hm = mAppConfig.authHM;
    // return hm;
    // }
    //
    // public HashMap<String, String> getAuthMyInfoHM(Context mContext) {
    // HashMap<String, String> hm = mAppConfig.authMyInfoHM;
    // return hm;
    // }
    //
    // public HashMap<String, String> getAuthStyleConfigHM(Context mContext) {
    // HashMap<String, String> hm = mAppConfig.authStyleConfigHM;
    // return hm;
    // }
    //
    // public ArrayList<HashMap<String, String>> getAuthListHM(Context mContext) {
    // ArrayList<HashMap<String, String>> hm = mAppConfig.authListHM;
    // return hm;
    // }
    //

    //
    // public ToggleButton getToggleButton(Context mContext, int RItem) {
    // return ((ToggleButton) mContext.findViewById(RItem));
    // }
    //
    // public CheckBox getCheckBox(Context mContext, int RItem) {
    // return ((CheckBox) mContext.findViewById(RItem));
    // }
    //
    // public Spinner getSpinner(Context mContext, int RItem) {
    // return ((Spinner) mContext.findViewById(RItem));
    // }
    //
    // public void aniImageGrp(Context mContext, int RItem, int iTotal, int iVal) {
    // ImageView iv = (ImageView) mContext.findViewById(RItem);
    //
    // if (iTotal == 999999999) {
    // iTotal = 100;
    // iVal = 1;
    // }
    // ScaleAnimation scale = new ScaleAnimation(0, (float) iVal / iTotal, 1, 1,
    // 0.5f, 0.5f);
    // scale.setFillAfter(true);
    // scale.setDuration(500);
    // scale.setStartOffset(500);
    // iv.startAnimation(scale);
    // }
    //
    // public void aniImageGrpUp(Context mContext, int RItem1, int iWeight1, int
    // RItem2, int iWeight2, int iViewItem1, float iTotal,
    // int iVal) {
    // float iWeightVal1;
    // float iWeightVal2;
    //
    // // 변경된 항목의 weight를 설정한다.
    // iWeightVal1 = (float) (iWeight1 + (iWeight2 - (iWeight2 * (iVal /
    // iTotal))));
    // iWeightVal2 = (float) (iWeight2 * (iVal / iTotal));
    //
    // LinearLayout.LayoutParams params1, params2;
    // View v1, v3;
    // v1 = mContext.findViewById(RItem1);
    // params1 = (LinearLayout.LayoutParams) v1.getLayoutParams();
    // params1.weight = iWeightVal1;
    // v1.setLayoutParams(params1);
    //
    // v3 = mContext.findViewById(RItem2);
    // params2 = (LinearLayout.LayoutParams) v3.getLayoutParams();
    // params2.weight = iWeightVal2;
    // v3.setLayoutParams(params2);
    //
    // // 애니메이션을 적용시킨다.
    // ImageView iv2 = (ImageView) mContext.findViewById(iViewItem1);
    // ScaleAnimation scale2 = new ScaleAnimation(1, 1, -1, 1,
    // ScaleAnimation.RELATIVE_TO_SELF, 1f, ScaleAnimation.RELATIVE_TO_SELF,
    // 1f);
    // scale2.setFillAfter(true);
    // scale2.setDuration(500);
    // scale2.setStartOffset(500);
    // iv2.startAnimation(scale2);
    // }
    //

    //
    // public String getLoginResult(Context mContext) {
    // String tmp = "";
    // HashMap<String, String> hm = mAppConfig.authHM;
    // tmp = null2empty(hm.get("result_id[0]"));
    // if (tmp.equals("")) {
    // tmp = null2empty(hm.get("sds:userID[0]"));
    // }
    // return tmp;
    // }
    //
    // public boolean getLoginState(Context mContext) {
    // boolean tmp = false;
    // if (getLoginResult(mActivity).length() > 0) tmp = true;
    // return tmp;
    // }
    //
    // public String getMyDisplayInfo(Context mContext) {
    // Display defaultDisplay;
    // defaultDisplay = ((WindowManager)
    // mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    // int width = defaultDisplay.getWidth();
    // int height = defaultDisplay.getHeight();
    // String tmp = width + "*" + height;
    // return tmp;
    // }
    //
    public String getMyDisplayHeight(Context context) {

        Display defaultDisplay;
        defaultDisplay = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int height = defaultDisplay.getHeight();
        String tmp = Integer.toString(height);
        return tmp;
    }

    public int getMyDisplayHeight_i(Context context) {

        Display defaultDisplay;
        defaultDisplay = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int height = defaultDisplay.getHeight();
        return height;
    }

    public String getMyDisplayWidth(Context context) {

        Display defaultDisplay;
        defaultDisplay = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int width = defaultDisplay.getWidth();
        String tmp = Integer.toString(width);
        return tmp;
    }

    public int getMyDisplayWidth_i(Context context) {

        Display defaultDisplay;
        defaultDisplay = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int width = defaultDisplay.getWidth();
        return width;
    }

    public int getScaleVal(Context context, int iVal) {

        appConfig = (AppConfig) context.getApplicationContext();
        return (int) ((appConfig.getScale() * iVal) + 0.5f);
    }

    public String getDeviceName() {

        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }

    public String getPhoneName() {

        BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
        String deviceName = myDevice.getName();
        return deviceName;
    }

    private String capitalize(String s) {

        if (s == null || s.length() == 0) {
            return "";
        }
        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
    //
    // public Boolean getMyDisplayChk(Context mContext) {
    // Display defaultDisplay;
    // Boolean bDisplayChk = false;
    // defaultDisplay = ((WindowManager)
    // mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    // int width = defaultDisplay.getWidth();
    // int height = defaultDisplay.getHeight();
    // if (width == 480) {
    // if (height == 800) {
    // bDisplayChk = true;
    // }
    // }
    // return bDisplayChk;
    // }
    //
    // public String getMyPhoneNumber(Context mContext) {
    // TelephonyManager mTelephonyMgr;
    // mTelephonyMgr = (TelephonyManager)
    // mContext.getSystemService(Context.TELEPHONY_SERVICE);
    // String tmp = mTelephonyMgr.getLine1Number();
    // if (tmp == null) tmp = "";
    // return tmp;
    // }
    //
    // public void goActivity(Context mContext, String menuClass) {
    // String findClass = "";
    // Class<?> cls;
    // Context contextCategory;
    // try {
    // cls = Class.forName(menuClass);
    // actCategory = (Activity) cls.newInstance();
    // Intent intent = new Intent(mContext, actCategory.getClass());
    // mContext.startActivity(intent);
    // findClass = cls.getName();
    // } catch (ClassNotFoundException e) {
    // findClass = "";
    // AlertDialog dialog = new AlertDialog.Builder(mContext).create();
    // dialog.setTitle("안내");
    // dialog.setMessage("죄송합니다.\n페이지를 찾을 수 없습니다.");
    // dialog.setButton("확인", new DialogInterface.OnClickListener() {
    // @Override
    // public void onClick(DialogInterface dialog, int which) {
    // return;
    // }
    // });
    // dialog.show();
    // } catch (InstantiationException e) {
    //
    // } catch (IllegalAccessException e) {
    //
    // }
    // }
    //
    //

    /**
     * 입력받은 String 형의 데이타값을 s1형태로 변환하여 리턴
     *
     * @param s  String
     * @param s1 String
     * @return String
     */
    public String format(String s, String s1) {

        return format(Double.parseDouble(s), s1);
    }

    /**
     * 입력받은 int 형의 데이타값을 s형태로 변환하여 리턴
     *
     * @param i int
     * @param s String
     * @return String
     */

    public String format(int i, String s) {

        DecimalFormat decimalformat = new DecimalFormat(s);
        return decimalformat.format(i);
    }

    /**
     * 입력받은 float형의 데이타값을 s형태로 변환하여 리턴
     *
     * @param f float
     * @param s String
     * @return String
     */
    public String format(float f, String s) {

        DecimalFormat decimalformat = new DecimalFormat(s);
        return decimalformat.format(f);
    }

    /**
     * 입력받은 long형의 데이타값을 s형태로 변환하여 리턴
     *
     * @param l long
     * @param s String
     * @return String
     */
    public String format(long l, String s) {

        DecimalFormat decimalformat = new DecimalFormat(s);
        return decimalformat.format(l);
    }

    /**
     * 입력받은 double형의 데이타값을 s형태로 변환하여 리턴
     *
     * @param d double
     * @param s String
     * @return String
     */
    public String format(double d, String s) {

        DecimalFormat decimalformat = new DecimalFormat(s);
        return decimalformat.format(d);
    }

    // public Boolean isMobileRoaming(Context mContext) {
    // Boolean Roaming = false;
    // if (availableCommunication(mActivity) == ConnectivityManager.TYPE_MOBILE) {
    // // if(true){
    // Roaming = isRoaming(mActivity);
    // // Roaming = true;
    // }
    // return Roaming;
    // }
    //
    // public Boolean isRoaming(Context mContext) {
    // TelephonyManager tel = (TelephonyManager)
    // mContext.getSystemService(Context.TELEPHONY_SERVICE);
    // Dlog.d(mContext.getPackageName(), "NetworkOperator: " +
    // tel.getNetworkOperator()); // 로밍
    // // 사업자
    // // 정보
    // return tel.isNetworkRoaming(); // 리턴값이 1 인 경우 Roaming 된 상태이며, 0이면
    // // Roaming 되지 않은 상태입니다.
    // }
    //
    // public int availableCommunication(Context mContext) {
    // ConnectivityManager cm = (ConnectivityManager)
    // mContext.getSystemService(mContext.CONNECTIVITY_SERVICE);
    // NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    // boolean isWifiAvail = ni.isAvailable();
    // boolean isWifiConn = ni.isConnected();
    // ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    // boolean isMobileAvail = ni.isAvailable();
    // boolean isMobileConn = ni.isConnected();
    //
    // String status = "WiFi\nAvail = " + isWifiAvail + "\nConn = " + isWifiConn
    // + "\nMobile\nAvail = " + isMobileAvail + "\nConn = "
    // + isMobileConn + "\n";
    // Dlog.d("Communication State! ", status);
    //
    // if (isWifiAvail == true && isWifiConn == true) {
    // return ConnectivityManager.TYPE_WIFI;
    // } else if (isMobileAvail == true && isMobileConn == true) {
    // return ConnectivityManager.TYPE_MOBILE;
    // } else {
    // return -1;
    // }
    // }
    //
    //
    // public int str2int(String txt, int mydefault) {
    // int num = 0;
    // if (txt == null || "".equals(txt)) {
    // num = mydefault;
    // } else {
    // try {
    // num = Integer.parseInt(txt);
    // } catch (NumberFormatException e) {
    // Dlog.e(TAG, e.toString());
    // }
    // }
    // return num;
    // }
    //
    public long str2long(String txt) {

        long num = 0;
        if (txt == null || "".equals(txt)) {
            num = 0;
        } else {
            num = (long) str2double(txt);
            // num = Long.valueOf(txt).longValue();
            // Dlog.v(num);
        }
        return num;
    }

    public long str2long(Object txt) {

        long num = 0;
        if (txt == null || "".equals(txt)) {
            num = 0;
        } else {
            num = (long) str2double(txt.toString());
            // num = Long.valueOf(txt).longValue();
            // Dlog.v(num);
        }
        return num;
    }

    //
    // public String han2Cho(String str) { // 유니코드 한글 문자열을 입력 받음
    // char[] ChoSung = { 0x3131, 0x3132, 0x3134, 0x3137, 0x3138, 0x3139,
    // 0x3141, 0x3142, 0x3143, 0x3145, 0x3146, 0x3147, 0x3148, 0x3149,
    // 0x314a, 0x314b, 0x314c, 0x314d, 0x314e };
    //
    // int a, b, c; // 자소 버퍼: 초성/중성/종성 순
    //
    // String result = "";
    // for (int i = 0; i < str.length(); i++) {
    // char ch = str.charAt(i);
    // if (ch >= 0xAC00 && ch <= 0xD7A3) { // "AC00:가" ~ "D7A3:힣" 에 속한 글자면
    // // 분해
    // c = ch - 0xAC00;
    // a = c / (21 * 28);
    // result = result + ChoSung[a];
    // } else {
    // result = result + ch;
    //
    // }
    // break;
    // }
    // return result;
    // }
    //
    // public String str2Estr(String txt) {
    // int i, j, ichk = 0;
    // String sTemp = "";
    // int len = txt.length();
    // txt = null2empty(txt);
    // for (i = 0; i < len; i++) {
    // j = txt.indexOf('\\', i);
    // if (j == -1) {
    // // Dlog.v("==================num1=============",txt.substring(i));
    // sTemp = sTemp + txt.substring(i);
    // break;
    // } else {
    // // Dlog.v("==================num1=============",txt.substring(i,
    // // j));
    // sTemp = sTemp + txt.substring(i, j) + "\n";
    // }
    // i = j + 1;
    // }
    // return sTemp;
    // }
    //
    // public String[] Split(String text, String parser) {
    // int count = 0, index = 0, i = 0, endIdx = 0;
    //
    // do {
    // count++;
    // index++;
    // index = text.indexOf(parser, index);
    // } while (index != -1);
    // String[] data = new String[count];
    //
    // index = 0;
    //
    // while (i < count) {
    // endIdx = text.indexOf(parser, index);
    //
    // if (endIdx == -1) {
    // data[i] = text.substring(index).trim();
    // } else {
    // data[i] = text.substring(index, endIdx).trim();
    // }
    // index = endIdx + 1;
    // i++;
    // }
    //
    // return data;
    // }
    //

    public boolean isViableActivity(Context context, String childActivity) {

        String strPackage = "";
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = am.getRunningTasks(2);

        strPackage = runningTaskInfos.get(0).topActivity.getClassName(); // package이름과 동일함.

        Dlog.e(context.getPackageName(), "PinCodeAtivity: " + strPackage);

        if (strPackage.equals(childActivity)) {
            return true;
        } else {
            return false;
        }
    }

    public String getVersionName(Context context) {

        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionName;
        } catch (NameNotFoundException e) {
            return null;
        }
    }

    // To animate view slide out from left to right
    public void slideToRight(View view) {

        TranslateAnimation animate = new TranslateAnimation(0, view.getWidth(), 0, 0);
        animate.setDuration(500);
        animate.setFillAfter(true);
        view.startAnimation(animate);
        view.setVisibility(View.GONE);
    }

    // To animate view slide out from right to left
    public void slideToLeft(View view) {

        TranslateAnimation animate = new TranslateAnimation(0, -view.getWidth(), 0, 0);
        animate.setDuration(500);
        animate.setFillAfter(true);
        view.startAnimation(animate);
        view.setVisibility(View.GONE);
    }

    // To animate view slide out from top to bottom
    public void slideToBottom(View view) {

        TranslateAnimation animate = new TranslateAnimation(0, 0, 0, view.getHeight());
        animate.setDuration(500);
        animate.setFillAfter(true);
        view.startAnimation(animate);
        view.setVisibility(View.GONE);
    }

    // To animate view slide out from bottom to top
    public void slideToTop(View view) {

        TranslateAnimation animate = new TranslateAnimation(0, 0, 0, -view.getHeight());
        animate.setDuration(500);
        animate.setFillAfter(true);
        view.startAnimation(animate);
        view.setVisibility(View.GONE);
    }

    private Animator mCurrentShowAnim;
    private boolean mShowHideAnimationEnabled;

    public void TitleHide(final View vTitle) {

        if (mCurrentShowAnim != null) {
            mCurrentShowAnim.end();
        }
        if (vTitle.getVisibility() == View.GONE) {
            return;
        }

        if (mShowHideAnimationEnabled) {
            vTitle.setAlpha(1);
            //			vTitle.setTransitioning(true);
            AnimatorSet anim = new AnimatorSet();
            AnimatorSet.Builder b = anim.play(ObjectAnimator.ofFloat(vTitle, "alpha", 0));
            //			if (mContentView != null) {
            //				b.with(ObjectAnimator.ofFloat(mContentView, "translationY", 0, -vTitle.getHeight()));
            b.with(ObjectAnimator.ofFloat(vTitle, "translationY", -vTitle.getHeight()));
            //			}
            //			if (mSplitView != null && mSplitView.getVisibility() == View.VISIBLE) {
            //				mSplitView.setAlpha(1);
            //				b.with(ObjectAnimator.ofFloat(mSplitView, "alpha", 0));
            //			}
            //			anim.addListener(mHideListener);
            anim.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    //		            if (mContentView != null) {
                    //		                mContentView.setTranslationY(0);
                    //		                mContainerView.setTranslationY(0);
                    //		            }
                    //		            if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) {
                    //		                mSplitView.setVisibility(View.GONE);
                    //		            }
                    vTitle.setVisibility(View.GONE);
                    //		        	vTitle.setTransitioning(false);
                    mCurrentShowAnim = null;
                    //		            completeDeferredDestroyActionMode();
                }
            });
            mCurrentShowAnim = anim;
            anim.start();
        } else {
            //			mHideListener.onAnimationEnd(null);
        }
    }

    //    final AnimatorListener mHideListener = new AnimatorListenerAdapter() {
    //        @Override
    //        public void onAnimationEnd(Animator animation) {
    ////            if (mContentView != null) {
    ////                mContentView.setTranslationY(0);
    ////                mContainerView.setTranslationY(0);
    ////            }
    ////            if (mSplitView != null && mContextDisplayMode == CONTEXT_DISPLAY_SPLIT) {
    ////                mSplitView.setVisibility(View.GONE);
    ////            }
    //            mContainerView.setVisibility(View.GONE);
    //            mContainerView.setTransitioning(false);
    //            mCurrentShowAnim = null;
    ////            completeDeferredDestroyActionMode();
    //        }
    //    };
    //
    //    final AnimatorListener mShowListener = new AnimatorListenerAdapter() {
    //        @Override
    //        public void onAnimationEnd(Animator animation) {
    //            mCurrentShowAnim = null;
    //            mContainerView.requestLayout();
    //        }
    //    };

    /**
     * *******************************************************************************************************
     * 날짜 관련 유틸 ********************************************************************************************************
     */

    public String getRealTimeType(String sTemp) {

        Date today = new Date();
        String sTime = "";
        SimpleDateFormat timeStampFormat = new SimpleDateFormat(sTemp);
        sTime = timeStampFormat.format(today);
        // filename = timeStampFormat.format(new
        // Date(System.currentTimeMillis()));
        return sTime;
    }

    public String getDateAdd(int iDay, String sTemp) {

        SimpleDateFormat timeStampFormat = new SimpleDateFormat(sTemp);

        Calendar temp = Calendar.getInstance();
        temp.add(Calendar.DAY_OF_MONTH, iDay);

        int nYear = temp.get(Calendar.YEAR);
        int nMonth = temp.get(Calendar.MONTH) + 1;
        int nDay = temp.get(Calendar.DAY_OF_MONTH);

        String sTime = timeStampFormat.format(temp.getTime());

        return sTime.toString();
    }

    public String getDateAdd(int iDay) {

        Calendar temp = Calendar.getInstance();
        temp.add(Calendar.DAY_OF_MONTH, iDay);

        int nYear = temp.get(Calendar.YEAR);
        int nMonth = temp.get(Calendar.MONTH) + 1;
        int nDay = temp.get(Calendar.DAY_OF_MONTH);

        StringBuffer sbDate = new StringBuffer();
        sbDate.append(nYear);

        if (nMonth < 10)
            sbDate.append("0");
        sbDate.append(nMonth);

        if (nDay < 10)
            sbDate.append("0");
        sbDate.append(nDay);

        return sbDate.toString();
    }

    public String DateYearMonth(String sDate, String sGubun1, String sGubun2) {

        if (sDate == null || sDate.equals("")) {
            return "";
        } else {
            return sDate.substring(0, 4) + sGubun1 + sDate.substring(4, 6) + sGubun2;
        }
    }

    public String DateYearMonth(String sDate, String sGubun1) {

        return sDate.substring(0, 4) + sGubun1 + sDate.substring(4, 6);
    }

    public String GetMonth(String day1, int gap) {

        int year, month;
        String sDate;

        year = str2int(day1.substring(0, 4));
        month = str2int(day1.substring(4));
        if (gap == -1 || gap == 1) {
            month += (gap);
            if (month <= 0) {
                month = 12;
                year = year - 1;
            } else if (month >= 13) {
                month = 1;
                year = year + 1;
            }
        } else if (gap == 12) {
            year++;
        } else if (gap == -12) {
            year--;
        }
        if (month < 10) {
            sDate = Integer.toString(year) + "0" + Integer.toString(month);
        } else {
            sDate = Integer.toString(year) + Integer.toString(month);
        }
        return sDate;
    }

    /**
     * <pre>
     * 문자열 형태의 날짜를 원하는 형태로 변환합니다. *
     * 예시) * "yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
     * "EEE, MMM d, ''yy" Wed, Jul 4, '01 * "h:mm a" 12:08 PM
     * "hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
     * "K:mm a, z" 0:08 PM, PDT
     * "yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
     * "EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
     * "yyMMddHHmmssZ" 010704120856-0700
     * "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
     * </pre>
     *
     * @param date             변환할 날짜
     * @param fromFormatString 변환될 포맷
     * @param toFormatString   변환할 포맷
     * @return 변환된 날짜 문자열
     */
    public String formattedDate(String date, String fromFormatString, String toFormatString) {

        SimpleDateFormat fromFormat = new SimpleDateFormat(fromFormatString);
        SimpleDateFormat toFormat = new SimpleDateFormat(toFormatString);
        Date fromDate = null;
        try {
            fromDate = fromFormat.parse(date);
        } catch (ParseException e) {
            fromDate = new Date();
        }
        return toFormat.format(fromDate);
    }

    public Boolean isBirthDayCheked(String Date) {

        try {
            SimpleDateFormat transFormat = new SimpleDateFormat("yyyy년 MM월 dd일");
            Calendar calendar = Calendar.getInstance();
            Date to = transFormat.parse(Date);
            calendar = transFormat.getCalendar();
            int iTempYear = calendar.get(Calendar.YEAR);
            int iTempMonth = calendar.get(Calendar.MONDAY) + 1;
            int iTempDay = calendar.get(Calendar.DAY_OF_MONTH);
            if (Date.startsWith("19") == false && Date.startsWith("20") == false) {
                return false;
            } else if (iTempMonth < 1 || iTempMonth > 12) {
                return false;
            } else if (iTempDay < 1 || iTempDay > 31) {
                return false;
            }
        } catch (java.text.ParseException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public Boolean isBirthDay14Cheked(String Date) {

        try {
            Calendar today = Calendar.getInstance();
            int curYear = today.get(Calendar.YEAR);
            int curMonth = today.get(Calendar.MONTH);
            int curDay = today.get(Calendar.DAY_OF_MONTH);

            SimpleDateFormat transFormat = new SimpleDateFormat("yyyy년 MM월 dd일");
            Calendar calendar = Calendar.getInstance();
            Date to = transFormat.parse(Date);
            calendar = transFormat.getCalendar();

            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DAY_OF_MONTH);

            int age = curYear - year;
            if (curMonth < month || (month == curMonth && curDay < day)) {
                age--;
            }

            if (age < 14) {
                return false;
            }
        } catch (java.text.ParseException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public String getMonthAdd(String sYearMonth, int iAddcnt) {

        int iYear = str2int(sYearMonth.substring(0, 4));
        int iMonth = str2int(sYearMonth.substring(4, 6));
        int iCnt = 0;
        Boolean bChk = false;
        String sReturn = "";
        if (iAddcnt < 0) {
            bChk = true;
            iCnt = Math.abs(iAddcnt);
        } else if (iAddcnt > 0) {
            bChk = false;
            iCnt = iAddcnt;
        }

        for (int i = 0; i < iCnt; i++) {
            if (bChk) {
                if (iMonth == 1) {
                    iMonth = 12;
                    iYear--;
                } else {
                    iMonth--;
                }
            } else {
                if (iMonth == 12) {
                    iMonth = 1;
                    iYear++;
                } else {
                    iMonth++;
                }
            }
        }
        if (iMonth < 10) {
            sReturn = iYear + "0" + iMonth;
        } else {
            sReturn = iYear + "" + iMonth;
        }
        return sReturn;
    }

    public long getDiffDate(String day1, String day2) {

        long retVal = 0;
        String sDay = day1;
        String pDay = day2;

        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        Date d1 = df.parse(sDay, new ParsePosition(0));
        Date d2 = df.parse(pDay, new ParsePosition(0));

        retVal = (d1.getTime() - d2.getTime()) / (1000 * 60 * 60 * 24);
        return retVal;
    }

    public long getDiffDate1(String day1, String day2) {

        long retVal = 0;
        String sDay = day1;
        String pDay = day2;

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = df.parse(sDay, new ParsePosition(0));
        Date d2 = df.parse(pDay, new ParsePosition(0));

        retVal = (d1.getTime() - d2.getTime()) / (1000 * 60 * 60 * 24);
        return retVal;
    }

    public long getRealTime() {
        // String filename="";
        // SimpleDateFormat timeStampFormat = new
        // SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
        //
        // filename = timeStampFormat.format(new
        // Date(System.currentTimeMillis()));
        long realTime = System.currentTimeMillis();
        return realTime;
    }

    public String getRealTime1() {

        String strResultTime = "";
        try {
            long lTime = System.currentTimeMillis();

            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            strResultTime = dateFormat1.format(new Date(lTime));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    public String getRealYearMonth() {

        String month;

        Calendar cal = Calendar.getInstance(Locale.getDefault());

        StringBuffer buf = new StringBuffer();

        buf.append(Integer.toString(cal.get(Calendar.YEAR)));
        month = Integer.toString(cal.get(Calendar.MONTH) + 1);
        if (month.length() == 1)
            month = "0" + month;

        buf.append(month);

        return buf.toString();
    }

    public String getRealDate() {

        String month, day;

        Calendar cal = Calendar.getInstance(Locale.getDefault());

        StringBuffer buf = new StringBuffer();

        buf.append(Integer.toString(cal.get(Calendar.YEAR)));
        month = Integer.toString(cal.get(Calendar.MONTH) + 1);
        if (month.length() == 1) {
            month = "0" + month;
        }
        buf.append(month);
        day = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
        if (day.length() == 1) {
            day = "0" + day;
        }
        buf.append(day);
        return buf.toString();
    }

    public String getRealDate1() {

        String month, day;

        Calendar cal = Calendar.getInstance(Locale.getDefault());

        StringBuffer buf = new StringBuffer();

        buf.append(Integer.toString(cal.get(Calendar.YEAR)));
        month = Integer.toString(cal.get(Calendar.MONTH) + 1);
        if (month.length() == 1) {
            month = "0" + month;
        }
        buf.append("-");
        buf.append(month);
        day = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
        if (day.length() == 1) {
            day = "0" + day;
        }
        buf.append("-");
        buf.append(day);

        return buf.toString();
    }

    public String getRealDateMonth() {

        String month, day;

        Calendar cal = Calendar.getInstance(Locale.getDefault());

        //        StringBuffer buf = new StringBuffer();
        //
        //        buf.append(Integer.toString(cal.get(Calendar.YEAR)));
        month = Integer.toString(cal.get(Calendar.MONTH) + 1);
        if (month.length() == 1) {
            month = "0" + month;
        }
        //        day = Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
        //        if ( day.length() == 1 )
        //            day = "0" + day;
        //        buf.append(day);

        return month;
    }

    public boolean isDateValid(String date) {

        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            df.setLenient(false);
            df.parse(date);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    public String getUtcTime() {
        String utcTime;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        utcTime = simpleDateFormat.format(new Date());
        LogUtil.i(TAG, "getUtcTime : " + utcTime);

        return utcTime;
    }

    // String local time to UTC time convert
    public String LocaltoUTC(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            // Change the Date Format to UTC
            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the UTC time '-' The offset from local time
            lv_UTCTime = lv_UTCTime - offset;

            strResultTime = dateFormat.format(new Date(lv_UTCTime));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    // String local time to UTC time convert
    public String LocaltoUTC1(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
            // Change the Date Format to UTC
            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the UTC time '-' The offset from local time
            lv_UTCTime = lv_UTCTime - offset;

            strResultTime = dateFormat1.format(new Date(lv_UTCTime)) + "Z";
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    public String LocaltoUTC2(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
            // Change the Date Format to UTC
            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the UTC time '-' The offset from local time
            lv_UTCTime = lv_UTCTime - offset;

            strResultTime = dateFormat1.format(new Date(lv_UTCTime));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    public String[] LocaltoUTC3(String sTime) {

        String sTempTime = "";
        String[] saTime = new String[2];
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("HHmm");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("HH:mm");
            // Change the Date Format to UTC
            Date dateUtcTime = dateFormat.parse(sTime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the UTC time '-' The offset from local time
            lv_UTCTime = lv_UTCTime - offset;

            sTempTime = dateFormat1.format(new Date(lv_UTCTime));
            saTime = sTempTime.split(":");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return saTime;
    }

    // String UTC time to Local time convert
    public String UTCtoLocal(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the local time '-' The offset from UTC time
            lv_UTCTime = lv_UTCTime + offset;

            strResultTime = dateFormat.format(new Date(lv_UTCTime)) + "Z";
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    // String UTC time to Local time convert
    public String UTCtoLocal1(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the local time '-' The offset from UTC time
            lv_UTCTime = lv_UTCTime + offset;

            strResultTime = dateFormat1.format(new Date(lv_UTCTime)) + "Z";
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    // String UTC time to Local time convert
    public String UTCtoLocal2(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.ddHH:mm");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy.MM.dd");

            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the local time '-' The offset from UTC time
            lv_UTCTime = lv_UTCTime + offset;

            strResultTime = dateFormat1.format(new Date(lv_UTCTime));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    public String UTCtoLocal3(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.ddHH:mm");
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("HH:mm");

            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the local time '-' The offset from UTC time
            lv_UTCTime = lv_UTCTime + offset;

            strResultTime = dateFormat1.format(new Date(lv_UTCTime));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    // String UTC time to Local time convert
    public String UTCtoLocal4(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the local time '-' The offset from UTC time
            lv_UTCTime = lv_UTCTime + offset;

            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            strResultTime = dateFormat1.format(new Date(lv_UTCTime));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    public String UTCtoLocal5(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the local time '-' The offset from UTC time
            lv_UTCTime = lv_UTCTime + offset;

            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            strResultTime = dateFormat1.format(new Date(lv_UTCTime));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    public String[] UTCtoLocal6(String sTime) {

        String sTempTime = "";
        String[] saTime = new String[2];
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("HHmm");

            Date dateUtcTime = dateFormat.parse(sTime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            TimeZone z = TimeZone.getDefault();

            // get the offset of the local timezone
            int offset = z.getOffset(lv_UTCTime);
            //  To get the local time '-' The offset from UTC time
            lv_UTCTime = lv_UTCTime + offset;

            SimpleDateFormat dateFormat1 = new SimpleDateFormat("HH:mm");
            sTempTime = dateFormat1.format(new Date(lv_UTCTime));
            saTime = sTempTime.split(":");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return saTime;
    }

    // String UTC time to Local time convert
    public String TimeToTime2(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");

            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            //			// timezone acquisition
            //			TimeZone z = TimeZone.getDefault();
            //
            //			// get the offset of the local timezone
            //			int offset = z.getOffset(lv_UTCTime);
            //			//  To get the local time '-' The offset from UTC time
            //			lv_UTCTime = lv_UTCTime + offset;

            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            strResultTime = dateFormat1.format(new Date(lv_UTCTime + 1));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    // String UTC time to Local time convert
    public String stringTodate(String sDatetime) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");

            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            //			TimeZone z = TimeZone.getDefault();
            //
            //			// get the offset of the local timezone
            //			int offset = z.getOffset(lv_UTCTime);
            //			//  To get the local time '-' The offset from UTC time
            //			lv_UTCTime = lv_UTCTime + offset;

            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
            strResultTime = dateFormat1.format(new Date(lv_UTCTime)) + "Z";
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    public String stringToDate(String sDatetime) {
        SimpleDateFormat original_format = new SimpleDateFormat("yyyyMMddhhmmss");
        SimpleDateFormat new_format = new SimpleDateFormat("yyyy년 MM월 dd일 hh시 mm분 ss초");
        Date original_date = null;
        String sResultDate = "";
        try {
            original_date = original_format.parse(sDatetime);
            sResultDate = new_format.format(original_date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sResultDate;
    }

    public String stringDateAddTime(String sDatetime, int iVal) {

        String strResultTime = "";
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");

            Date dateUtcTime = dateFormat.parse(sDatetime);

            long lv_UTCTime = dateUtcTime.getTime();

            // timezone acquisition
            //			TimeZone z = TimeZone.getDefault();
            //
            //			// get the offset of the local timezone
            //			int offset = z.getOffset(lv_UTCTime);
            //			//  To get the local time '-' The offset from UTC time
            //			lv_UTCTime = lv_UTCTime + offset;

            //            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
            strResultTime = dateFormat.format(new Date(lv_UTCTime + iVal));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return strResultTime;
    }

    public StateListDrawable imageSelect(Drawable normal, Drawable select) {

        StateListDrawable imageDraw = new StateListDrawable();
        imageDraw.addState(new int[]{android.R.attr.state_selected}, select);
        imageDraw.addState(new int[]{}, normal);
        return imageDraw;
    }

    public Bitmap DrawableToBitmap(Drawable drawable, int widthPixels, int heightPixels) {

        Bitmap mutableBitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(mutableBitmap);
        drawable.setBounds(0, 0, widthPixels, heightPixels);
        drawable.draw(canvas);

        return mutableBitmap;
    }

    public Drawable BitmapToDrawable(Bitmap bitmap) {

        Drawable drawable = (Drawable) new BitmapDrawable(bitmap);
        return drawable;
    }

    public View setViewPadding(Context context, View vView, int iLeft, int iTop, int iRight, int iBottom) {

        vView.setPadding(getScaleVal(context, iLeft), getScaleVal(context, iTop), getScaleVal(context, iRight), getScaleVal(context, iBottom));
        return vView;
    }

    //    public Drawable GlideToDrawable(Context mContext, String sUrl) {
    //
    //        try {
    //            //            Bitmap theBitmap = Glide.with(mContext).load(sUrl).asBitmap();
    //            Bitmap theBitmap = Glide.with(mContext).load(sUrl).asBitmap().into(-1, -1).get();
    //            //            Bitmap theBitmap = Glide.with(mContext).load(sUrl).into(getImageView(mContext, Ritem));
    //            return BitmapToDrawable(theBitmap);
    //        } catch (Exception ex) {
    //            ex.printStackTrace();
    //            return null;
    //        }
    //    }

    public StateListDrawable imageChange(Drawable normal, Drawable press) {

        StateListDrawable imageDraw = new StateListDrawable();
        imageDraw.addState(new int[]{android.R.attr.state_pressed}, press);
        imageDraw.addState(new int[]{-android.R.attr.state_pressed}, normal);
        return imageDraw;
    }

    public StateListDrawable imageChange(Drawable normal, Drawable press, Drawable select) {

        StateListDrawable imageDraw = new StateListDrawable();
        imageDraw.addState(new int[]{android.R.attr.state_selected}, select);
        imageDraw.addState(new int[]{android.R.attr.state_pressed}, press);
        imageDraw.addState(new int[]{-android.R.attr.state_pressed}, normal);
        return imageDraw;
    }

    public StateListDrawable colorChange(String normalColor, String pressColor) {

        Drawable normalDraw = new ColorDrawable(Color.parseColor(normalColor));
        Drawable pressDraw = new ColorDrawable(Color.parseColor(pressColor));
        return imageChange(normalDraw, pressDraw);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @SuppressWarnings("deprecation")
    public void setBg(View layout, Drawable TileMe) {

        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            layout.setBackgroundDrawable(TileMe);
        } else {
            layout.setBackground(TileMe);
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    public static final int getColor(Context context, int id) {

        if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return context.getResources().getColor(id);
        } else {
            return ContextCompat.getColor(context, id);
        }
    }

    /**
     * Retrieves the net.hostname system property
     *
     * @param defValue the value to be returned if the hostname could not be resolved
     */
    public String getHostName() {

        try {
            Method getString = Build.class.getDeclaredMethod("getString", String.class);
            getString.setAccessible(true);
            return getString.invoke(null, "net.hostname").toString();
        } catch (Exception ex) {
            return null;
        }
    }

    public void callApp_Start(Context context, String sVal) {

        if (!null2string(sVal).equals("")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setData(Uri.parse(getPreferences(context, Constants.EXTRA_APPSTART_ID) + "://start?type=" + sVal));
            context.startActivity(intent);
        }
    }

    public void setVibrator(int iVal) {

        Vibrator v = (Vibrator) AppConfig.getInstance().getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(iVal);
    }

    public void callBtnGoogleAnalytics(Context context, String sAction, String sVal) {

        Tracker t = AppConfig.getInstance().getTracker(AppConfig.TrackerName.APP_TRACKER);
        t.send(new HitBuilders.EventBuilder().setCategory(context.getClass().getSimpleName()).setAction(sAction).setLabel(sVal).build());
    }

    public void callBtnGoogleAnalytics(String sActVal, String sAction, String sVal) {

        Tracker t = AppConfig.getInstance().getTracker(AppConfig.TrackerName.APP_TRACKER);
        t.send(new HitBuilders.EventBuilder().setCategory(sActVal).setAction(sAction).setLabel(sVal).build());
    }

    public void callActGoogleAnalytics(Context context) {

        Tracker t = AppConfig.getInstance().getTracker(AppConfig.TrackerName.APP_TRACKER);
        t.setScreenName(context.getClass().getSimpleName());
        t.send(new HitBuilders.AppViewBuilder().build());
    }

    public void callActGoogleAnalytics(String sVal) {

        Tracker t = AppConfig.getInstance().getTracker(AppConfig.TrackerName.APP_TRACKER);
        t.setScreenName(sVal);
        t.send(new HitBuilders.AppViewBuilder().build());
    }

    public static InetAddress getIpAddress() {
        try {
            Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) en.nextElement();
                if ("eth0".equals(ni.getName())) {
                    Enumeration<InetAddress> ipList = ni.getInetAddresses();
                    while (ipList.hasMoreElements()) {
                        InetAddress inetAddress = (InetAddress) ipList.nextElement();
                        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                            LogUtil.i(TAG, "get ip addr from eth0 : " + inetAddress);
                            return inetAddress;
                        }
                    }
                }
            }

            en = NetworkInterface.getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) en.nextElement();
                if ("wlan0".equals(ni.getName())) {
                    Enumeration<InetAddress> ipList = ni.getInetAddresses();
                    while (ipList.hasMoreElements()) {
                        InetAddress inetAddress = (InetAddress) ipList.nextElement();
                        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                            LogUtil.i(TAG, "get ip addr from wlan0 : " + inetAddress);
                            return inetAddress;
                        }
                    }
                }
            }

        } catch (SocketException e) {
            LogUtil.d(TAG, "failed to get ip addr from eth0 or wlan0 : " + e.getMessage());
        }

        return null;
    }

    public String getTopActivityName(Context context) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> info = activityManager.getRunningTasks(1);
        ComponentName componentName = info.get(0).topActivity;

        String activityName = componentName.getShortClassName().substring(1);
        String packageName = componentName.getPackageName();
        LogUtil.i(TAG, "Top activity name : " + activityName);
        LogUtil.i(TAG, "Top package name : " + packageName);

        return null2string(activityName);
    }

    public HashMap<String, Object> parseConfiguration(String sConfiguration) {
        if (sConfiguration.isEmpty()) {
            return null;
        }
        HashMap<String, Object> hmRetMap = new HashMap<>();
        String[] saTemp = sConfiguration.split("`");
        for (int i = 0; i < saTemp.length; i++) {
            int iSeparateChar = saTemp[i].indexOf('=');
            String key = saTemp[i].substring(0, iSeparateChar);
            String value = saTemp[i].substring(iSeparateChar + 1, saTemp[i].length());
            LogUtil.i(TAG, "saTemp" + "[" + i + "] key = " + key + ", value = " + value);
            hmRetMap.put(key, value);
        }
        return hmRetMap;
    }

    /**
     * HSB 형식 컬러 String을 ARGB 형식 컬러 int로 변환.
     *
     * @param hsbStr HSB 컬러 String(ex> 298.6653,43,99)
     */
    public int hsbToRgb(String hsbStr) {
        String[] hsbArr = hsbStr.split(",");
        float[] hsb = new float[3];
        for (int i = 0; i < hsb.length; i++) {
            float value;
            if (i == 0) {
                value = Float.valueOf(hsbArr[i]);
            } else {
                // saturation과 brightness는 퍼센테이지로 오기때문에 계산해줘야함.
                value = Float.valueOf(hsbArr[i]) / 100;
            }
            hsb[i] = value;
        }
        LogUtil.i(TAG, "Rgb color int = " + Color.HSVToColor(hsb));
        return Color.HSVToColor(hsb);
    }

    /**
     * Hex color string to int[] array converter.
     *
     * @param hexARGB should be color hex string: #AARRGGBB or #RRGGBB
     * @return int[] array: [alpha, r, g, b]
     */
    public int[] hexStringToARGB(String hexARGB) throws IllegalArgumentException {

        int[] intARGB = new int[4];

        intARGB[0] = Integer.valueOf(hexARGB.substring(0, 2), 16); // alpha
        intARGB[1] = Integer.valueOf(hexARGB.substring(2, 4), 16); // red
        intARGB[2] = Integer.valueOf(hexARGB.substring(4, 6), 16); // green
        intARGB[3] = Integer.valueOf(hexARGB.substring(6), 16); // blue

        return intARGB;
    }

    public float[] rgbToHsb(int color) {
        String colorHexStr = Integer.toHexString(color).toUpperCase();
        LogUtil.i(TAG, "selectedColor = " + colorHexStr);

        // 16진수 컬러 string을 red, green, blue 각각의 int값으로 변환.
        int[] argb = hexStringToARGB(colorHexStr);
        LogUtil.i(TAG, "RGB color R - " + argb[1] + ", G - " + argb[2] + ", B - " + argb[3]);

        // rgb 컬러를 hsb 형식으로 변환.
        float[] hsb = new float[3];
        Color.RGBToHSV(argb[1], argb[2], argb[3], hsb);
        LogUtil.i(TAG, "HSB color Hue - " + hsb[0] + ", Saturation - " + hsb[1] + ", Brightness - " + hsb[2]);

        return hsb;
    }

    public String getHsbStr(float[] hsb) {
        return String.valueOf(hsb[0] + "," + (int) (hsb[1] * 100) + ","
                + (int) (hsb[2] * 100));
    }

}
