﻿/**
* Copyright (c) 2010 Samsung SDS, Inc. All Rights Reserved.
*
* Script Name : Common.js
* Description : 공통 스크립트
* Author: 김기상
* Since: 2010.04.09
*
* Modification Information
* Mod Date		Modifier	Description
* ==========	========	===========================
* 2010.04.09	김기상		최초 생성
*/



/*****************************************************************
* 함수 설명	    : 공통팝업 Scroll 
* 작성자        : 김기상
*****************************************************************/
function CommonPopup(filename, pGubun, pWidth, pHeight, scroll_yn) {
    var winl = (screen.width - pWidth) / 2;
    var wint = (screen.height - pHeight) / 2;
    var scroll_value = "";
    if (scroll_yn == "Y")
        scroll_value = "scrollbars=yes ,resizable=yes";
    else
        scroll_value = "scrollbars=no ,resizable=no";
    winprops = 'width=' + pWidth + ',height=' + pHeight + ',top=' + wint + ',left=' + winl + ',' + scroll_value;
    win = window.open(filename, pGubun, winprops);
}

/*****************************************************************
* 함수 설명	    : 숫자만 입력가능한지 체크하는 함수
* 작성자        : 김기상
*****************************************************************/
function IsNumeric(pObj,pMsg) { // 문자입력 금지 함수 설정
    if (event.keyCode < 48 || event.keyCode > 57) {
        event.keyCode = 0;
        document.getElementById(pObj).value = "";
        alert(pMsg);
    }
}

/*****************************************************************
* 함수 설명	    : 공백 문자열 체크(정상 true 오류 false )
* 작성자        : 김기상
*****************************************************************/
function IsEmpty(toCheck) {
    var chkstr = toCheck + "";
    var is_Space = true;

    if ((chkstr == "") || (chkstr == null))
        return false;

    for (j = 0; j < chkstr.length; j++) {
        if (chkstr.substring(j, j + 1) == " ")
            is_Space = false;
    }

    return is_Space;
}

/*****************************************************************
* 함수 설명	    : 이메일 형식 검증(정상 true 오류 false )
* 작성자        : 김기상
*****************************************************************/
function IsEmail(strEmail) {
    /** 금지사항
    - @가 2개이상
    - .이 붙어서 나오는 경우
    -  @.나  .@이 존재하는 경우
    - 맨처음이.인 경우 **/
    var regDoNot = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;
    /** 필수사항
    - @이전에 하나이상의 문자가 있어야 함
    - @가 하나있어야 함
    - Domain명에 .이 하나 이상 있어야 함
    - Domain명의 마지막 문자는 영문자 2~4개이어야 함 **/
    var regMust = /^[a-zA-Z0-9\-\.\_\!]+\@[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4})$/;

    if (!regDoNot.test(strEmail) && regMust.test(strEmail))
        return true;
    else
        return false;
}

/*****************************************************************
* 함수 설명	    : Image Preview
* 작성자        : 김기상
* Param
    pObjFile    : 파일 업로드 아이디
    pObjImg     : DIV 아이디
*****************************************************************/
function UploadImagePreview(pObjFile, pObjDiv, pMsg) {
    var preViewer = pObjDiv;
    var thisObj = document.getElementById(pObjFile);
    if (!/(\.gif|\.jpg|\.jpeg|\.png)$/i.test(thisObj.value)) {
        alert(pMsg);
        return;
    }

    preViewer = (typeof (preViewer) == "object") ? preViewer : document.getElementById(preViewer);
    var ua = window.navigator.userAgent;

    if (ua.indexOf("MSIE") > -1) {
        var img_path = "";
        if (thisObj.value.indexOf("\\fakepath\\") < 0) {
            img_path = thisObj.value;
        } else {
            thisObj.select();
            var selectionRange = document.selection.createRange();
            img_path = selectionRange.text.toString();
            thisObj.blur();
        }
        
        preViewer.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='fi" + "le://" + img_path + "', sizingMethod='scale')";
    } else {
        preViewer.innerHTML = "";
        var W = preViewer.offsetWidth;
        var H = preViewer.offsetHeight;
        var tmpImage = document.createElement("img");
        preViewer.appendChild(tmpImage);

        tmpImage.onerror = function() {
            return preViewer.innerHTML = "";
        }

        tmpImage.onload = function() {
            if (this.width > W) {
                this.height = this.height / (this.width / W);
                this.width = W;
            }
            if (this.height > H) {
                this.width = this.width / (this.height / H);
                this.height = H;
            }
        }
        if (ua.indexOf("Firefox/3") > -1) {
            var picData = thisObj.files.item(0).getAsDataURL();
            tmpImage.src = picData;
        } else {
            tmpImage.src = "file://" + thisObj.value;
        }
    }
}
/*****************************************************************
* 함수 설명	    : 이스케이프 변환
* 작성자        : 
*****************************************************************/
function _unescape(str) {
    str = unescape(str);
    str = str.replace(/\\u0000/gi, "\0");
    str = str.replace(/\\u0008/gi, "\b");
    str = str.replace(/\\u0009/gi, "\t");
    str = str.replace(/\\u000A/gi, "\n");
    str = str.replace(/\\u000B/gi, "\v");
    str = str.replace(/\\u000C/gi, "\f");
    str = str.replace(/\\u000D/gi, "\r");
    str = str.replace(/\\u0022/gi, "\"");
    str = str.replace(/\\u0027/gi, "\'");
    str = str.replace(/\\u003C/gi, "<");
    str = str.replace(/\\u003E/gi, ">");
    str = str.replace(/\\u005C/gi, "\\");

    return str;
}

/*****************************************************************
* 함수 설명	    : 스크롤 위치 얻기
* 작성자        : 
*****************************************************************/
var getNowScroll = function() {
    var de = document.documentElement;
    var b = document.body;
    var now = {};

    now.X = document.all ? (!de.scrollLeft ? b.scrollLeft : de.scrollLeft) : (window.pageXOffset ? window.pageXOffset : window.scrollX);
    now.Y = document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY);

    return now;

}

/*****************************************************************
* 함수 설명	    : alertCheck 디자인 적용
* 작성자        : 
* Param
msg         : 메시지
*****************************************************************/
window["alertCheck"] = function(msg) {
    if (document.getElementById("snow_alert") == null) {
        div = document.createElement('div');
        div.id = "snow_alert";
        div.style.display = "none";
        html = "<div id='snow_alert_form' class='br5_pop_area' style='z-index:199;'>" +
               "  <div class='ttl_area'>" +
               "    <ul>" +
               "      <h1 class='ttl_txt'>Alert message !!</h1>" +
               "      <li class='close'><a href='javascript:alert_close();'><img src='http://" + document.URL.split('/')[2] + "/content/images/btn/btn_close.gif' /></a></li>" +
               "    </ul>" +
               "  </div>" +
               "  <div class='br7_pop_top'></div>" +
               "  <div class='br7_pop_mid' id='snow_alert_msg'>" + msg + "</div>" +
               "  <div class='br7_pop_btm'></div>" +
               "  <!-- btn -->" +
               "  <div class='btn_blue4_r'><a href='javascript:alert_close();'>OK</a></div>" +
               "  <!-- //btn -->" +
               "</div>";
        div.innerHTML = html;
        document.body.appendChild(div);

    } else {
        document.getElementById("snow_alert_msg").innerText = msg;
    }

    width = 0;
    height = 0;
    if ($.browser.msie) {//익스플로러일경우
        width = document.documentElement.offsetWidth;
        height = document.documentElement.offsetHeight;
    } else {//그외 브라우저
        width = window.innerWidth;
        height = window.innerHeight;
    }
    nowScroll = getNowScroll();

    document.getElementById("snow_alert_form").style.left = ((width / 2) + nowScroll.X - 160) + "px";
    document.getElementById("snow_alert_form").style.top = ((height / 2) + nowScroll.Y - 140) + "px";
    document.getElementById("snow_alert").style.display = "inline";
    document.getElementById("bg_png").style.display = "inline";
};


/*****************************************************************
* 함수 설명	    : 비밀번호 숫자 문자 조합확인
* 작성자        : 김기상
* Param
pValue    : 문자열값
*****************************************************************/
function PasswdCheck(pValue){						
	var intNum = 0;						
	var intEng = 0;				
	//8자이상인지 체크
	if(pValue.length <= 5 ){		
		return false;
	}

	//Object null이 아니라면
	if (pValue.length > 0) {
	    for (i = 0; i < pValue.length; i++) {			
		    //숫자
			if(AsciiCode(pValue.charAt(i)) >= 48 && AsciiCode(pValue.charAt(i)) <= 57){
				intNum = intNum + 1;
            }
            //알파벳 대문자
            if (AsciiCode(pValue.charAt(i)) >= 65 && AsciiCode(pValue.charAt(i)) <= 90) {
                intEng = intEng + 1;
            }
            //알파벳 소문자				
			if(AsciiCode(pValue.charAt(i)) >= 97 && AsciiCode(pValue.charAt(i)) <= 122){
				intEng = intEng + 1;
			}
			
		}		
		if(intNum <= 0 || intEng <= 0 ){			
			return false;
		}

	}
	else{			
		return;
	}

}

/*****************************************************************
* 함수 설명	    : 아스키코드를 리턴한다
* 작성자        : 김기상
* Param
pObjFile    : 문자열값
*****************************************************************/
function AsciiCode(pValue){
	//charCodeAt()함수는 ASCII코드값을 반환한다
	return pValue.charCodeAt();
	 
}


/*****************************************************************
* 함수 설명	    : 텍스트박스 입력사이즈 레이블로 출력
* 작성자        : 김기상
* Param
txtId    : 텍스트입력되는 아이디명 
spId     : 입력사이즈를 출력할 span 태그 아이디명
maxSize: 최대길이 사이즈
*****************************************************************/
function CheckTextLength(txtId, spId, maxSize) {

    var eventObj = document.getElementById(txtId);
    var size = getByteSize(document.getElementById(txtId).value);
    
    //Color setting
    if (size > (maxSize)) {
        document.getElementById(spId).style.color = "red";
    }
    else {
        document.getElementById(spId).style.color = "gray";
    }
     
    document.getElementById(spId).innerHTML = size;
}

/*****************************************************************
* 함수 설명	    : 텍스트박스 입력사이즈를 리턴한다
* 작성자        : 김기상
* Param
pValue    : 텍스트 value

*****************************************************************/
function getByteSize(pValue) { 
    var len = 0;
    if (pValue == null) return 0;
    for (var i = 0; i < pValue.length; i++) {
        var c = escape(pValue.charAt(i));
        if (c.length == 1) len++;
        else if (c.indexOf("%u") != -1) len += 2;
        else if (c.indexOf("%") != -1) len += c.length / 3;
    }
    return len;
}

/*****************************************************************
* 함수 설명	    : 텍스트박스 입력사이즈를 리턴한다
* 작성자        : 김기상
* Param
txtId    : 텍스트입력되는 아이디명 

*****************************************************************/
function CheckTextLengthSize(txtId) {

    var eventObj = document.getElementById(txtId);
    var size = 0;
    var a = document.getElementById(txtId).value;

    //FF
    if (eventObj.addEventListener) {
        size = document.getElementById(txtId).value.length;        
    }
    //IE
    else if (eventObj.attachEvent) {

        for (var i = 0; i < a.length; i++) {
            //아스키코드값 추출
            var j = a.charCodeAt(i);
            //텍스트값 추출
            var s = a.charAt(i);

            if (j > 127) {
                size = size + 2;
            }
            else {
                size = size + 1;
            }
        }
    }
    
    return size;   
}

/*****************************************************************
* 함수 설명	    : 숫자 1~9일 경우 앞에 "0"있으면 제거한다
* 작성자        : 김기상
* Param
pValue    : 값
*****************************************************************/
function IntLengthCheck(pValue) {
    var result = "";
    
    if (pValue == "" || pValue == "undefined" || pValue == null) {
        return result;
    }

    if (pValue.length >= 2) {
        if (pValue.substr(0, 1) == "0") {
            result = pValue.substr(1, 1);
        }
        else {
            result = pValue;
        }
    }
    else {
        result = pValue;
    }

    return result;
}

/*****************************************************************
* 함수 설명	    : 입력받은 문자열을 UTF-8로 byte length를 구한다.
* 작성자        : 김도형
* Param
str    : 문자열
*****************************************************************/
function GetByteLengthToUTF8(str) {
    if (str != null && str.length > 0) {
        res = 0;
        for (i = 0; str.length > i; i++) {
            code = str.charCodeAt(i);
            if (code < 0x000080)
                res += 1;
            else if (code < 0x000800)
                res += 2;
            else if (code < 0x010000)
                res += 3;
            else
                res += 4;
        }
        return res;
    }
    return 0;
}


/*****************************************************************
* 함수 설명	    : 페이징 처리
* 작성자        : 고영태
* Description   : Ajax 리스트 페이징 처리
                  리스트 페이지를 따로 작성해 줘야함
                  변수명 맞춰줘야 함
* Param         : page = 페이지 번호
*****************************************************************/
function goAjaxPage(strPage, strUrl, strSearchField, strSearchText, strOrderField, strOrderType) {
    var randomV = Math.floor(Math.random() * 1000);
    
    $.ajax
    ({
        url: strUrl,
        data: "page=" + strPage +
                "&searchField=" + strSearchField +
                "&searchText=" + strSearchText +
                "&orderField=" + strOrderField +
                "&orderType=" + strOrderType +
                "&random=" + randomV,
        success: function(html) {
            $("#divList").html(html);
        }
    });
}
