<?
class Func{


	/////////////////////////////////////////////////////////////////
	// $lib_message : message, <br> 사용
	// $lib_link : 있으면 해당 위치로 이동. 1 이면 그냥 Close, 없으면 history.back(-1)
	/////////////////////////////////////////////////////////////////
	
	function modalMsg($lib_message, $lib_link) {
		if (trim($lib_link) != "" && trim($lib_link) != 1) $lib_link = "location.href='".$lib_link."'";
		else if (trim($lib_link) == 1) $lib_link = 1;
		else $lib_link = "history.back(-1);";
				
		include getenv("DOCUMENT_ROOT")."/include/message.php";
	}

	// modalMsg 은 로그인시 login_process.php 같은 프로그램 동작시 독립적인 modal
	// modalMsgIN 은 view=myorder 등 이미 header 부터 script가 들어있고 중간에 삽입되어 동작되므로 jquery, bootstrap 등 불필요
	function modalMsgIN($lib_message, $lib_link) {
		if (trim($lib_link) != "") $lib_link = "location.href='".$lib_link."'";
		else $lib_link = "history.back(-1);";
		
		include getenv("DOCUMENT_ROOT")."/include/message_in.php";
	}

	// 다른곳으로 이동하지 않고 Alert 만 표시하기 위해 사용
	function modalMsgJS($lib_message, $lib_link) {
		if (trim($lib_link) != "") $lib_link = "location.href='".$lib_link."'";
		else $lib_link = "history.back(-1);";
		
		include getenv("DOCUMENT_ROOT")."/include/message_js.php";

		echo "
				<script laguage=javascript>
				$('#myModal').find('.modal-body').text('".$lib_message."');
				$('#myModal').modal('show');
				</script>	
		";
		
	}
	
	// 숫자일 경우 1을 리턴
	function isnum($str) {
		if(eregi("[^0-9]",$str)) return 0;
		return 1;
	}
	
	
	function switchOrder($switch, $switched) {

		$explode = explode("^", $switched);
		$switched = $explode[0];
		$switchedOrder = $explode[1];

		if($switched == $switch && $switchedOrder == "asc") {
				$switchedOrder = "desc";
		}else {
			$switchedOrder = "asc";
		}

		return $switchedOrder;
	}

    #############################################################
    # list 에서 multi sort 를 지원한다.
	#############################################################
	function sort_list($sorting_type, $switch) {

		$add_query = " ORDER BY ";

		if($sorting_type) {

			$sorting_type = unserialize(base64_decode($sorting_type));
			$max_for = sizeof($sorting_type);

			for($i=0; $i<$max_for; $i++)
			{

				list($key, $value) = each($sorting_type);

				if($switch == $key) {
					$sorting_type[$key] = ($sorting_type[$key] == "asc") ? "desc" : "asc";
					$used_switch = 1;
				}

				$add_query .= " " . $key . " " . $sorting_type[$key] . ", ";

			}

			if($switch && $used_switch != 1)
			{
				$sorting_type[$switch] = "asc";
				$add_query .= " " . $switch . " " . "asc";
			}

		} else {

			$sorting_type[$switch] = "asc";
			$add_query .= $switch . " " . $sorting_type[$switch];
		}

		$sorting_type = ($sorting_type == "") ? "" : base64_encode(serialize($sorting_type));

		$add_query = rtrim($add_query);
		$length = strlen($add_query) - 1;

		if($add_query[$length] == ",")
		{
			$add_query = substr($add_query, 0, $length);
		}

		$return_value = $add_query . "^^^^^^^^^^" . $sorting_type;

		return $return_value;
	}

    #############################################################
    # policy number 를 생성한다.
    #############################################################
	function make_pnumber($homeland, $province, $seq) {

		if($homeland == "CANADA") {

			$policy_number = "TI" . substr($province, 0, 1);

		}else {

			$policy_number = "TI" . substr($homeland, 0, 1);

		}

		for($j=0; $j<7-strlen($seq); $j++)
		{
			$zerofill .= "0";
		}

		$policy_number = $policy_number . $zerofill . $seq;
		return $policy_number;
	}
    #############################################################
    # 세션 체크하고 에러가 있을 시에 메세지를 뿌리고
    # 목적지로 돌려 보낸다
    #############################################################

	function session_check($minimum_level, $matched_level, $msg1, $msg2, $destination1, $destiantion2)
	{
		if($matched_level != "")
		{
			if(isset($_SESSION["ss_id"]) && isset($_SESSION["ss_level"]))
			{
				if($_SESSION["ss_level"] != (int)$matched_level)
				{
					$this -> goUrl($destination1, $msg1);
					exit();
				}
			}else
			{
				$this -> goUrl($destiantion2, $msg2);
				exit();
			}

		}else
		{
			if(isset($_SESSION["ss_id"]) && isset($_SESSION["ss_level"]))
			{
				if($_SESSION["ss_level"] < (int)$miuimum_level)
				{
					$this -> goUrl($destination1, $msg1);
					exit();
				}
			}else
			{
				$this -> goUrl($destiantion2, $msg2);
				exit();
			}
		}
	}

    ################################################################
	# $len의 길이로 $str이라는 문자열을 자른다.
	# 한글을 한바이트 단위로 잘르는 경우를 막고 대문자가 많이 쓰인 경우
	# 소문자와의 크기 비율 정도(1.5?)에 따라 문자열을 자름
    ################################################################
	function cutString($str, $len)
	{
		##        넘어온 문자열이 자를려는 것보다 작거나 1글자이면 리턴
		if(strlen($str) <= $len && !eregi("^[a-z]+$", $str))    
			return $str;  
		
		for($i = $len; $i >=1; $i--)
		{      
			# 끝에서부터 한글 byte수를 센다.      
			if($this->check_hangul($str[$i-1]))
					$hangul++;      
			else
					break;
		}    

		if ($hangul)
		{    
			# byte수가 홀수이면, 한글의 첫번째 바이트이다.      
			# 한글의 첫번째 바이트일 때 깨지는 것을 막기 위해 지정된 길이를 한 바이트 줄임      
			if ($hangul%2)
					$len--;            
			
			$str = chop(substr($str, 0, $len));  
		}
		else
		{
			# 문자열의 끝이 한글이 아닐 경우      
			for($i = 1; $i <= $len; $i++)
			{          
					# 대문자의 갯수를 기록          
					if($this->check_alpha($str[$i-1]) == 2)
							$alpha++;
					# 마지막 한글이 나타난 위치 기록      
					if($this->check_hangul($str[$i-1]))
							$last_han=$i;      
			}            
			# 지정된 길이로 문자열을 자르고 문자열 끝의 공백 문자를 삭제함      
			# 대문자의 길이는 1.3으로 계산한다. 문자열 마지막의 영문 문자열이      
			# 빼야할 전체 길이보다 크면 초과된 만큼 뺀다.      
			$capitals = intval($alpha * 0.5);      
			if ( ($len-$last_han) <= $capitals)
					$capitals=0;      
			
			$str = chop(substr($str, 0, $len - $capitals));
			$srt = $str;
		}  
			
		return $str."...";
	}

    ################################################################
	#	@@함수명 : check_hangul
	#
	#	$char : 값
	#
	#   $char이 한글인지 체크
    ################################################################
	function check_hangul($char) {
		// 특정 문자가 한글의 범위내(0xA1A1 - 0xFEFE)에 있는지 검사
		$char = ord($char);

		if($char >= 0xa1 && $char <= 0xfe) {
			return 1;
		}

		return;
	}

    ################################################################
	#	@@함수명 : check_alpha
	#
	#	$char : 값
	#
	#   영문인지 체크
	#   반환값 : 2(대문자), 1(소문자), 0(영문아님)
    ################################################################
	function check_alpha($char) {
		$char = ord($char);

		if($char >= 0x61 && $char <= 0x7a) {
			return 1;
		}
	
		if($char >= 0x41 && $char <= 0x5a) {
			return 2;
		}

		return;
	}

    #############################################################
    # 날짜 구하기이다.. 수시로, 년, 월, 일, 날짜와 시간을 초로 반환한다.
    # 구분자는 $str로 하고 year, month, day, all, time, 현재 년-월-일으로 한다.
    # 사용법은 $str를 넘기면서 return 값을 받으면 된다.
    # 공동구매나 / 호스팅관리 등 날짜에 관련된 사이트 만들때 유용
    #############################################################
    function dateSeek($str) {
        if($str == "year") return date('Y', mktime());
        else if($str == "month") return date('m', mktime());
        else if($str == "day") return date('d', mktime());
        else if($str == "all") return date('Y-m-d', mktime());
        else if($str == "time") return mktime();
        else {
            $tmpArr=explode("-",$str);
            return mktime(0,0,0,$tmpArr[1], $tmpArr[2], $tmpArr[0]);
        }
    }

    #############################################################
    # error 페이지로 보낼때 사용하면 된다.
    # 메세지와 목적지를 인자로 넘기면 된다.
    ##############################################################

	function goErrorPage($msg, $destination) {
		echo "<script laguage=javascript>
		location.href=\"../modules/error.php?destination='$destination'&msg='$msg'\";
		</script>";
	}

    #############################################################
    # 페이지 이동 시킬 때 쓰인다.
    # 메세지와 목적지를 인자로 넘기면 된다.
    ##############################################################

	function goPage($msg, $destination) {
		
		if ($msg != "") $setMsg = "?msg=".$msg;
		else $setMsg = "";
		
		echo "<script laguage=javascript>
		location.href='$destination$setMsg';
		</script>";
	}

    #############################################################
    # 페이지를 뒤로 강제로 Back 시키고자 할때 사용하면 된다.
    # 사용법은 왜 Back을 시키는지 이유를 인자로 넘기면 된다.
    ##############################################################

    function alertBack($msg) {
        echo "<script language=javascript>
        <!--
        	alert(\"".$msg."\");
        	history.back();
        -->
        </script>";
        exit;
    }

    #############################################################
    # 페이지를 이동시킬때 쓴다.
    # 사용법은 url을 넘기면 끝~
    #############################################################

    function goUrl($url, $msg) {
        if(!empty($msg)) {
            echo "
                <script language=javascript>
                <!--
                    alert(\"".$msg."\");
                //-->
                </script>
                ";
        }
        echo "<meta http-equiv='refresh' content=\"0;URL=$url\">";
        exit;
    }


    ################################################################
    # 파일 업로드할때 호출하면 된다.
    # file : form 의 file객체명
    # savedir : 저장할 경로 주의 : 디렉토리는 자동생성되지 않고, 권한 역시 777로 변경
    ################################################################
    function fileUpload($file, $file_name, $savedir) {
        if($file != "none") {
            $pos = strpos($file_name,".");
            $name = substr($file_name,0,$pos);
            $ext = substr($file_name,$pos+1);

            if(strpos($ext,"php") || !strcmp($ext,"php3") || !strcmp($ext,"inc") || !strcmp($ext,"pl") || !strcmp($ext,"cgi") ||
                !strcmp($ext,"asp") || !strcmp($ext,"") ) {
                $this->alertBack("cannot upload this type of file.");
                exit;
            }
            $filename = $savedir.$file_name;
			$filename = str_replace("\\", "", $filename);
			$filename = str_replace("'", "", $filename);
			$filename = str_replace(" ", "_", $filename);
            $i = 1;
            while(file_exists("$filename")) {
                $filename = $savedir.$name."_".$i.".".$ext;
                $i++;
            }

            if(!copy($file,"$filename")) {
                $this->alertBack("upload failure.");
                exit;
            }
			/*
            if(!unlink($file)) {
                $this->alertBack("can't delete the temporary file.");
                exit;
            }
			*/
            $file_name = str_replace($savedir,"",$filename);
            return $file_name;
        }
    }



	function PwriteLog($logFile, $msg) 
    {
    	$getTime = date("Y/m/d H:i:s", time());
    	$logname = date('Y');
    	
    	$fp = @fopen($logFile,"a+");
    
    	@fwrite($fp,"[$getTime] $msg \n");
    
    	@fclose($fp);
    }
    
    

	function thumnail($file, $save_filename, $save_dir, $max_width, $max_height) {

		// 전송받은 이미지 정보를 받는다
		$img_info = getImageSize($file);

		// 전송받은 이미지의 포맷값 얻기 (gif, jpg png)
		if($img_info[2] == 1) {
			$src_img = ImageCreateFromGif($file);
		} else if($img_info[2] == 2) {
			$src_img = ImageCreateFromJPEG($file);
		} else if($img_info[2] == 3) {
			$src_img = ImageCreateFromPNG($file);
		} else {
			return 0;
		}

		// 전송받은 이미지의 실제 사이즈 값얻기
		$img_width = $img_info[0];
		$img_height = $img_info[1];

		if($img_width <= $max_width) {
				$max_width = $img_width;
				$max_height = $img_height;
		}

		if($img_width > $max_width){
				$max_height = ceil(($max_width / $img_width) * $img_height);
		}

		// 새로운 트루타입 이미지를 생성
		$dst_img = imagecreatetruecolor($max_width, $max_height);

		// R255, G255, B255 값의 색상 인덱스를 만든다
		ImageColorAllocate($dst_img, 255, 255, 255);

		// 이미지를 비율별로 만든후 새로운 이미지 생성
		ImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $max_width, $max_height, ImageSX($src_img),ImageSY($src_img));

		$pos = strpos($save_filename,".");
		$name = substr($save_filename,0,$pos);
		$ext = substr($save_filename,$pos+1);
		$filename = $save_dir . $save_filename;
		$i=1;
		while(file_exists("$filename")) {
			$filename = $save_dir.$name."_".$i.".".$ext;
			$i++;
		}

		// 알맞는 포맷으로 저장
		if($img_info[2] == 1) {
			ImageInterlace($dst_img);
			ImageGif($dst_img, $filename);
		} else if($img_info[2] == 2) {
			ImageInterlace($dst_img);
			ImageJPEG($dst_img, $filename, 100);
		} else if($img_info[2] == 3) {
			ImagePNG($dst_img, $filename);
		}

		// 임시 이미지 삭제
		ImageDestroy($dst_img);
		ImageDestroy($src_img);

		$filename = str_replace($save_dir,"",$filename);
		return $filename;
	} 

    ################################################################
    # 파일을 삭제할때 호출하면 된다.
    # file_name : 삭제할 화일명
    # savedir : 저장되어 있는 경로
    ################################################################
    function fileDelete($file_name,$savedir){
        $file = $savedir.$file_name;
        if(file_exists($file)) {
        	//echo "Exist";
        	unlink($file);
        }
    }

    #############################################################
    # 파일을 다운로드 받고자 할때 사용하는 함수이다.
    # 사용법은 자기 자신의 페이지를 리플래쉬 하면서
    # 함수를 호출하는 방식으로 하면된다.
    #############################################################
    function saveFile($filename, $savedir) {
        $filepath = $savedir.$filename;

        if( strstr($_SERVER["HTTP_USER_AGENT"],"MSIE 5.5")){
            header("Content-Type: doesn/matter");
            header("Content-Disposition: filename=$filename");
            header("Content-Transfer-Encoding: binary");
            header("Pragma: no-cache");
            header("Expires: 0");
        } else{
            Header("Content-type: file/unknown");
            Header("Content-Disposition: attachment; filename=$filename");
            header("Content-Transfer-Encoding: binary");
            header("Pragma: no-cache");
            header("Expires: 0");
        }
        @readfile($filepath);
    }


    ################################################################
    # 메일 발송하고자 할때 인수를 넘겨주면 된다. (html, text) 발송
    # to : 받는사람 메일, from : 발송자 메일, from_name : 발송자명
    # subject : 제목, contents : 내용, htmlcheck(y, n) : html발송여부
    ################################################################
    function sendMail($to, $from, $from_name, $subject, $contents, $htmlcheck) {
        $bodytext = $this->htmlText($contents,$htmlcheck);
        $additional = "From:$from_name<$from>"."\nContent-Type:text/html\nReply-To : $from \nX-Mailer: PHP/".phpversion();
        mail($to,$subject,$bodytext,$additional);
    }

    ############################################################
    # HTML 적용되는 컨텐츠..
    # html사용시에는 y, n으로 구분
    ################################################################
    function htmlText($text, $htmlcheck) {
        if($htmlcheck == "n") {
            $text  = stripslashes($text);
            $text = nl2br($text);
        }
        //html을 사용하는 경우
        else {
            $text  = stripslashes($text);
            $text = str_replace("<","<",$text);
            $text = str_replace(">",">",$text);
            $text = str_replace('"','\"',$text);
        }
        return $text;
    }

    ################################################################
    # Paging 함수.. 특정값을 넘겨 받아 함수 호출만으로 페이징 처리를 끝낸다.
    # PageNo : 현재 페이지수
    # PageSize : 라인수
    # totalrows : 총 게시물 수
    # whereqry : 전 검색시에 쿼리값을 SQL 조건문
    # color : 현재 페이지인 경우 색상
    # class : a 로 걸리는 링크에 클래스를 준다.
    ################################################################
    function paging($PageNo, $PageSize, $totalrows, $whereqry, $color, $class) {
        $lastpgno=ceil($totalrows/$PageSize);

        if($lastpgno!=0) {
            if($PageNo>1) echo " <a href=\"$PHP_SELF?PageNo=1&whereqry=$whereqry\" class='$class'>◀</a> ";
            else echo " ◀ ";

            if($PageNo>10) {
                $prevPage=floor(($PageNo-1)/10)*10;
                echo " <a href=\"$PHP_SELF?PageNo=$prevPage&whereqry=$whereqry\" class='$class'>◁</a> ";
            }
            else echo " ◁ ";

            $i=0;
            $startpage=floor(($PageNo-1)/10)*10+1;
            while($i<10 && $startpage<=$lastpgno){
                if($PageNo<>$startpage) echo " <a href=\"$PHP_SELF?PageNo=$startpage&whereqry=$whereqry\" class='$class'>$startpage</a> ";
                else echo " <font color=\"$color\">$startpage</font> ";
                $i++;
                $startpage=$startpage+1;
            }

            $nextPage=floor(($PageNo-1)/10)*10+11;
            if($nextPage<$lastpgno) echo " <a href=\"$PHP_SELF?PageNo=$nextPage&whereqry=$whereqry\" class='$class'>▷</a> ";
            else echo " ▷ ";

            if($PageNo<$lastpgno) echo " <a href=\"$PHP_SELF?PageNo=$lastpgno&whereqry=$whereqry\" class='$class'>▶</a> ";
            else echo " ▶ ";
        }
    }

    ################################################################
    # 데이타를 가져올 첫 시작 포인트를 반환한다.
    ################################################################
    function getDbStartNo($PageNo, $PageSize) {
        return ($PageNo-1)*$PageSize;
    }

    ################################################################
    # 랜덤 문자열 유일키 발생(상품코드로 사용) / 총 50자인데.. 필요한 만큼만 자르자.
    ################################################################
    function getCode($len) {
        $SID = md5(uniqid(rand()));
        $code = substr($SID, 0, $len);
        return $code;
    }

    ################################################################
    # 세션키 생성 주문번호로 가장 괜찮을거 같아 만들었음
    ################################################################
    function getSession() {
        $SID = microtime();
        $str = str_replace("-","",date("ymdHis", mktime()));
        $session = $str.substr($SID, 4, 3);
        return $session;
    }

    ################################################################
    # 배열값들 살펴 보기(HTTP_POST_VARS, HTTP_GET_VARS, HTTP_SERVER_VARS 등
    # 이외에 가끔씩. 배열값이 제대로 넘어오는지 확인해야할때가 있다.. 있대 사용..^^
    ################################################################
    function arrayView($Value) {
        // 실제로 Array라는 문자열을 뿌려주지면 문자열이 아니여서 다시한번 string 관련함수 하나를 실행해 준다.
        $chkArray = ucfirst($Value); //첫문자를 대문자로 변환
        if($chkArray == "Array") while(list($key,$val)=each($Value)) echo $key." ==> ".$val."\n";
        else echo "배열이 아닙니다.";
        exit;
    }

    ################################################################
    # Flash 코드도 꽤 길다.. 그래서. 함수화 해 버렸다.
    ##################################################################
    function flashLoad($urlpath, $width, $height) {
        echo "
            {object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0\"  width=\"$width\" height=\"$height\"}
                {param name=movie value=\"$urlpath\"}
                {param name=quality value=high}
                {embed src=\"$urlpath\" quality=high pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\" width=\"$width\" height=\"$height\"}
                {/embed}
            {/object}
        ";
    }

    /////////// 이하는 빌더형 사이트를  변수를 잘 기억하기 힘들어서 ^^ //////////
    ################################################################
    # 루트 시스템 절대 경로 얻기
    ################################################################
    function getServerSys() {
        return $_SERVER["DOCUMENT_ROOT"];
    }

    ################################################################
    # 루트 Url 얻기(메일 발송할때 사용)
    ################################################################
    function getSeverUrl() {
        return "http://".$_SERVER["HTTP_HOST"];
    }

    ################################################################
    # 현재 시스템 경로 얻기
    ################################################################
    function getSyspath() {
        return $_SERVER["SCRIPT_FILENAME"];
    }

    ################################################################
    # 현재 URL 경로 얻기
    ################################################################
    function getUrlpath() {
        return "http://".$_SERVER["HTTP_HOST"].$_SERVER["SCRIPT_NAME"];
    }

    ################################################################
    # 원격지 아이피 얻기
    ################################################################
    function getIp() {
        return $_SERVER["REMOTE_ADDR"];
    }



    ################################################################################


    function unhtmlspecialchars( $string )
    {
       $string = str_replace ( '&amp;', '&', $string );
       $string = str_replace ( '&#039;', '\'', $string );
       $string = str_replace ( '&quot;', '\"', $string );
       $string = str_replace ( '&lt;', '<', $string );
       $string = str_replace ( '&gt;', '>', $string );
       
       return $string;
    }


	########################################################################
	# Name		: PgetTime($someTime, $gb, $putType)
	# Description : 시간 출력 함수
	# Input	: $someTime => specific time (86400 : 1 day)
	# 		  $gb => 0 : 현재시간, 1 : 현재시간+-특정시간, 2 : 특정시간
	#		  $putType => wanted type (/ . - ...)
	# Output	: [2005/10/15 14:30:22] Log In XXX
	# Example	: 
	########################################################################
	
	function PgetTime($someTime, $gb, $putType)
	{
		if ($gb == 0) {				/* current time */
			$wantedTime = time();
		}
		else if ($gb == 1) {				/* wanted special time */
			$wantedTime = time() + $someTime;
		}
		else if ($gb == 2) {				/* sometime */
			$wantedTime = $sometime;
		} 
		
		switch ($putType) {
			case 0: $result = $wantedTime;				// result : 1130776669 (timestamp)
				break;
			case 1: $result = date("Y/m/d H:i:s", $wantedTime);	// result : 2005/10/27 14:20:55
				break;
			case 2: $result = date("Y.m.d H:i:s", $wantedTime);	// result : 2005.10.27 14:20:55
				break;
			case 3: $result = date("Y-m-d H:i:s", $wantedTime);	// result : 2005-10-27 14:20:55
				break;
			case 4: $result = date("YmdHis", $wantedTime);		// result : 20051027142055
				break;
			case 5: $result = date("Y/m/d", $wantedTime);		// result : 2005/10/27
				break;
			case 6: $result = date("Y.m.d", $wantedTime);		// result : 2005.10.27
				break;
			case 7: $result = date("Y-m-d", $wantedTime);		// result : 2005-10-27
				break;
			case 8: $result = date("Ymd", $wantedTime);		// result : 20051027
				break;	
			case 9: $result = date("M-d-Y", $wantedTime);		// result : Jan-02-2007
				break;		
		}
		
		return $result;
	}
	
	function convertFormat ($str, $tp)
	{
		$yy = substr ($str, 0, 4);
		$mm = substr ($str, 4, 2);
		$dd = substr ($str, 6, 2);
		$hh = substr ($str, 8, 2);
		$min = substr ($str, 10, 2);
		$ss = substr ($str, 12, 2);
		
		switch ($tp) {		
			case 1: 
				$result = $yy."-".$mm."-".$dd." ".$hh.":".$min.":".$ss;
				if ($str == '') $result = "-";
				break;
			case 2:
				$result = date("M-d-Y", mktime($ss,$min,$hh,$mm,$dd,$yy));
				break;
			case 3: 
				$result = $yy."-".$mm."-".$dd;
				if ($str == '') $result = "-";
				break;	
			case 4: 
				$result = $yy."-".$mm."-".$dd." ".$hh.":".$min;
				if ($str == '') $result = "-";
				break;	
			case 5: 
				$result = $mm."/".$dd;
				if ($str == '') $result = "-";
				break;	
			case 6: 
				$result = $yy.".".$mm;
				if ($str == '') $result = "-";
				break;														
			case 7: 
				$result = $yy."-".$mm;
				if ($str == '') $result = "-";
				break;	
		}
		return $result;
	}


	function convertFormatMMDDYYYY ($str, $tp)
	{
		$mm = substr ($str, 0, 2);
		$dd = substr ($str, 3, 2);
		$yy = substr ($str, 6, 4);
		
		switch ($tp) {		
			case 1: 
				$result = $yy.$mm.$dd;
				if ($str == '') $result = "-";
				break;	
			case 2:
				$result = $yy."-".$mm."-".$dd;
				if ($str == '') $result = "-";
				break;											

		}
		return $result;
	}
	
	// setNewImage($B_CDATE, 14, "/images/system/dot_new.gif");
	// $strDate : 게시물 작성일
	// $duringdate : New Image 보이게 하는 기간, 일 단위
	// $filename : New 이미지 디렉토리

	function setNewImage ($strDate, $duringdate, $filename) {
		$newImagePeriod = (60 * 60 * 24) * $duringdate;   // 14 days
	
		$yy = substr ($strDate, 0, 4);
		$mm = substr ($strDate, 4, 2);
		$dd = substr ($strDate, 6, 2);
		$hh = substr ($strDate, 8, 2);
		$min = substr ($strDate, 10, 2);
		$ss = substr ($strDate, 12, 2);
		$changeTime = mktime($ss,$min,$hh,$mm,$dd,$yy);	
		
		//echo "[$changeTime][".time()."]";
		if ((time() - $changeTime) < $newImagePeriod) { 
		    $setNewImg = "&nbsp;<IMG SRC=$filename border=0>";
		} else { 
		    $setNewImg = ""; 
		}
		return $setNewImg;
	}

	
	// ON -> Ontario, Ontario -> ON 출력
	function findProvince ($str) 
	{
		if (strlen($str) == 2)	
			$tp = 1;
		else	
			$tp = 2;
		
		$dt = array (
				array("AB","Alberta"),
				array("BC","British Columbia"),
				array("MB","Manitoba"),
				array("NB","New Brunswick"),
				array("NL","Newfoundland and Labrador"),
				array("NS","Nova Scotia"),
				array("NU","Nunavut"),
				array("NT","N.W.T."),
				array("ON","Ontario"),
				array("PE","Prince Edward Island"),
				array("QC","Quebec"),
				array("SK","Saskatchewan"),
				array("YT","Yukon")
			);
			
		switch ($tp) {
			case 1 :			// return Ontario
				foreach($dt as $dtStr) { 
					list($sStr, $lStr) = $dtStr; 
					if ($dtStr[0] == $str)
						$result = $dtStr[1];
				}
				break;
			
			case 2 :			// return ON
				foreach($dt as $dtStr) { 
					list($sStr, $lStr) = $dtStr; 
					if ($dtStr[1] == $str)
						$result = $dtStr[0];
				}
				break;
		}
		return $result;
	}


	function findRelation ($str) 
	{
		if (strlen($str) == 1)	
			$tp = 1;
		else	
			$tp = 2;
		
		$dt = array (
			array("1","Mother"), 
			array("2","Father"), 
			array("3","Grandparent"), 
			array("4","Aunt"), 
			array("5","Uncle"), 
			array("6","Foster Parent"), 
			array("7","Social Worker"), 
			array("0","Other")
			);
			
		switch ($tp) {
			case 1 :			// return Father
				foreach($dt as $dtStr) { 
					list($sStr, $lStr) = $dtStr; 
					if ($dtStr[0] == $str)
						$result = $dtStr[1];
				}
				break;
			
			case 2 :			// return number
				foreach($dt as $dtStr) { 
					list($sStr, $lStr) = $dtStr; 
					if ($dtStr[1] == $str)
						$result = $dtStr[0];
				}
				break;
		}
		return $result;
	}
	

	function age($birth_year,$birth_month,$birth_day) { 
		$now_year = date("Y"); 
		$now_month = date("m"); 
		$now_day = date("d"); 

		if($birth_month < $now_month)  
			$age= $now_year - $birth_year; 
		else if($birth_month == $now_month) { 
			if($birth_day <= $now_day) 
				$age= $now_year - $birth_year; 
			else 
				$age= $now_year - $birth_year-1; 
		} 
		else 
			$age= $now_year - $birth_year-1; 
      		
		return $age;
	} 
	
	function debugging($msg,$msg1) {
		echo "<script laguage=javascript>
		alert(\"[$msg=$msg1]\");
		</script>";
	}
	
	function dEnc ($str, $mode)
	{
	       if($mode=="e")
	       {
		       $str=base64_encode($str);
		       $str=urlencode($str);
	       }
	       if($mode=="d")
	       {
		       $str=urldecode($str);
		       $str=base64_decode($str);
	       }
	
		return $str;
	}	

	
	
	function set_cart($method,$goods_number=0,$goods_type=0,$goods_type2=0, $goods_type3=0, $quantity=0) 
	{ 
	/* define   $method : add, delete, reset, print 
	            $goods_type :     size, color ... 
	            $goods_number : database id 
	            $quantity 
	             
	            $return = method,status; 
	*/ 
	    if (!($this -> isnum($quantity))) {
	    		$msg = "Please enter a number between 1-99";
			$this -> alertBack($msg);
			exit();
	    }
	    
	
	    switch ($method) 
	    { 
	        case 'add': 
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                //현재 구상 item[]=01,1024,2 
	                //item이 이미 있을경우(array) item에 대한 추가 
	                $count = sizeof($_SESSION['item']); 
	                foreach($_SESSION['item'] as $i => $value) 
	                { 
	                    //unset 아이템 초기화 
	                    unset($item_cart_exp); 
	                    unset($item_tmp); 
	                    unset($item_cart_tmp); 
	                    $item_cart_exp    = explode(',',$value); 
	                    $item_cart_tmp    = $item_cart_exp[0].$item_cart_exp[1].$item_cart_exp[2].$item_cart_exp[3]; 
	                    $item_tmp         = $goods_number.$goods_type.$goods_type2.$goods_type3; 
	                    //echo "EXIST[".$item_cart_exp[0]."],[".$item_cart_exp[1]."],[".$item_cart_exp[2]."],[".$item_cart_exp[3]."],[".$item_cart_exp[4]."],[$item_cart_tmp][$item_tmp]<br>";
	                    if ($item_cart_tmp == $item_tmp) 
	                    { 
	                        //동일 item이 존재할 경우 
	                        $item_cart_exp[4]        = $item_cart_exp[4] + $quantity; 
	                        $_SESSION['item'][$i]    = $item_cart_exp[0].','.$item_cart_exp[1].','.$item_cart_exp[2].','.$item_cart_exp[3].','.$item_cart_exp[4]; 
	                        $flag                    = 1; 
	                    } 
	                } 
	                if ($flag != 1) 
	                { 
	                    //동일 item이 존재하지 안는 경우 
	                    $_SESSION['item'][] = $goods_number.','.$goods_type.','.$goods_type2.','.$goods_type3.','.$quantity; 
	                } 
	                unset($flag); 
	            } 
	            else 
	            { 
	                //$_SESSION['item']이 등록된적이 없는경우 
	                $_SESSION['item'] = array(); 
	                $_SESSION['item'][] = $goods_number.','.$goods_type.','.$goods_type2.','.$goods_type3.','.$quantity; 
	                //echo "[NEW=".$item_cart_exp[0]."][".$item_cart_exp[1]."][".$item_cart_exp[2]."][".$item_cart_exp[3]."][".$item_cart_exp[4]."][$item_cart_tmp][$item_tmp]<br>";
	            } 
	            $return = 'add,ok'; 
	        break; 
	
	         
	        case 'modify': 
	
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                $count = sizeof($_SESSION['item']); 
	                foreach($_SESSION['item'] as $i => $value) 
	                { 
	                    //unset 아이템 초기화 
	                    unset($item_cart_exp); 
	                    unset($item_tmp); 
	                    unset($item_cart_tmp); 
	                    $item_cart_exp    = explode(',',$value); 
	                    $item_cart_tmp    = $item_cart_exp[0].$item_cart_exp[1].$item_cart_exp[2].$item_cart_exp[3]; 
	                    $item_tmp         = $goods_number.$goods_type.$goods_type2.$goods_type3; 
	                    if ($item_cart_tmp == $item_tmp) 
	                    { 
	                        //동일 item이 존재할 경우 
	                        $item_cart_exp[4]        = $quantity; 
	                         
	                        if ($item_cart_exp[4] < 1) 
	                        { 
	                            // 물품갯수가 1이하인 경우 물건삭제 
	                            unset($_SESSION['item'][$i]); 
	                            $flag                    = 1; 
	                        } 
	                        else 
	                        { 
	                            // 물품갯수가 1이상인 경우 
	                            $_SESSION['item'][$i]    = $item_cart_exp[0].','.$item_cart_exp[1].','.$item_cart_exp[2].','.$item_cart_exp[3].','.$item_cart_exp[4]; 
	                            $flag                    = 1; 
	                        } 	                        
	                    } 
	                     
	                } 
	                if ($flag != 1) 
	                { 
	                    //동일 item이 존재하지 안는 경우 error1 
	                    $return = 'delete,error1'; 
	                } 
	                unset($flag); 
	            } 
	            else 
	            { 
	                //$_SESSION['item']이 등록된적이 없는경우 
	                $return = 'delete,error2'; 
	            } 
	
	        break; 
	
	
		   case 'delete': 
	
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                $count = sizeof($_SESSION['item']); 
	                foreach($_SESSION['item'] as $i => $value) 
	                { 
	                    //unset 아이템 초기화 
	                    unset($item_cart_exp); 
	                    unset($item_tmp); 
	                    unset($item_cart_tmp); 
	                    $item_cart_exp    = explode(',',$value); 
	                    $item_cart_tmp    = $item_cart_exp[0].$item_cart_exp[1].$item_cart_exp[2].$item_cart_exp[3]; 
	                    $item_tmp         = $goods_number.$goods_type.$goods_type2.$goods_type3; 
	                    if ($item_cart_tmp == $item_tmp) 
	                    { 
	                        //동일 item이 존재할 경우 
	                        $item_cart_exp[4]        = $item_cart_exp[4] - $quantity; 
	                         
	                        if ($item_cart_exp[4] < 1) 
	                        { 
	                            // 물품갯수가 1이하인 경우 물건삭제 
	                            unset($_SESSION['item'][$i]); 
	                            $flag                    = 1; 
	                        } 
	                        else 
	                        { 
	                            // 물품갯수가 1이상인 경우 
	                            $_SESSION['item'][$i]    = $item_cart_exp[0].','.$item_cart_exp[1].','.$item_cart_exp[2].','.$item_cart_exp[3].','.$item_cart_exp[4]; 
	                            $flag                    = 1; 
	                        } 
	                    } 
	                     
	                } 
	                if ($flag != 1) 
	                { 
	                    //동일 item이 존재하지 안는 경우 error1 
	                    $return = 'delete,error1'; 
	                } 
	                unset($flag); 
	            } 
	            else 
	            { 
	                //$_SESSION['item']이 등록된적이 없는경우 
	                $return = 'delete,error2'; 
	            } 
	
	        break; 
         
	        case 'reset': 
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                unset($_SESSION['item']); 
	            } 
	            $return = 'reset,ok'; 
	        break; 
	
	        case 'print': 
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                foreach($_SESSION['item'] as $key => $value) 
	                { 
	                    echo "$key : $value <br>"; 
	                } 
	            } 
	            $return = 'print,ok'; 
	        break; 
	    } 
	return $return; 
	} 


	function set_cart_org($method,$goods_number=0,$goods_type=0,$goods_type2=0, $quantity=0) 
	{ 
	/* define   $method : add, delete, reset, print 
	            $goods_type :     size, color ... 
	            $goods_number : database id 
	            $quantity 
	             
	            $return = method,status; 
	*/ 
	    switch ($method) 
	    { 
	        case 'add': 
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                //현재 구상 item[]=01,1024,2 
	                //item이 이미 있을경우(array) item에 대한 추가 
	                $count = sizeof($_SESSION['item']); 
	                foreach($_SESSION['item'] as $i => $value) 
	                { 
	                    //unset 아이템 초기화 
	                    unset($item_cart_exp); 
	                    unset($item_tmp); 
	                    unset($item_cart_tmp); 
	                    $item_cart_exp    = explode(',',$value); 
	                    $item_cart_tmp    = $item_cart_exp[0].$item_cart_exp[1].$item_cart_exp[2]; 
	                    $item_tmp         = $goods_number.$goods_type.$goods_type2; 
	                    //echo "[".$item_cart_exp[0]."]"."[".$item_cart_exp[1]."]"."[".$item_cart_exp[2]."]"."[".$item_cart_exp[3]."][$item_cart_tmp][$item_tmp]<br>";
	                    if ($item_cart_tmp == $item_tmp) 
	                    { 
	                        //동일 item이 존재할 경우 
	                        $item_cart_exp[3]        = $item_cart_exp[3] + $quantity; 
	                        $_SESSION['item'][$i]    = $item_cart_exp[0].','.$item_cart_exp[1].','.$item_cart_exp[2].','.$item_cart_exp[3]; 
	                        $flag                    = 1; 
	                    } 
	                } 
	                if ($flag != 1) 
	                { 
	                    //동일 item이 존재하지 안는 경우 
	                    $_SESSION['item'][$count] = $goods_number.','.$goods_type.','.$goods_type2.','.$quantity; 
	                } 
	                unset($flag); 
	            } 
	            else 
	            { 
	                //$_SESSION['item']이 등록된적이 없는경우 
	                $_SESSION['item'] = array(); 
	                $_SESSION['item'][] = $goods_number.','.$goods_type.','.$goods_type2.','.$quantity; 
	                //echo "[NOARRAY=".$item_cart_exp[0]."]"."[".$item_cart_exp[1]."]"."[".$item_cart_exp[2]."]"."[".$item_cart_exp[3]."][$item_cart_tmp][$item_tmp]<br>";
	            } 
	            $return = 'add,ok'; 
	        break; 
	
	         
	        case 'modify': 
	
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                $count = sizeof($_SESSION['item']); 
	                foreach($_SESSION['item'] as $i => $value) 
	                { 
	                    //unset 아이템 초기화 
	                    unset($item_cart_exp); 
	                    unset($item_tmp); 
	                    unset($item_cart_tmp); 
	                    $item_cart_exp    = explode(',',$value); 
	                    $item_cart_tmp    = $item_cart_exp[0].$item_cart_exp[1].$item_cart_exp[2]; 
	                    $item_tmp         = $goods_number.$goods_type.$goods_type2; 
	                    if ($item_cart_tmp == $item_tmp) 
	                    { 
	                        //동일 item이 존재할 경우 
	                        $item_cart_exp[3]        = $quantity; 
	                         
	                        if ($item_cart_exp[3] < 1) 
	                        { 
	                            // 물품갯수가 1이하인 경우 물건삭제 
	                            unset($_SESSION['item'][$i]); 
	                            $flag                    = 1; 
	                        } 
	                        else 
	                        { 
	                            // 물품갯수가 1이상인 경우 
	                            $_SESSION['item'][$i]    = $item_cart_exp[0].','.$item_cart_exp[1].','.$item_cart_exp[2].','.$item_cart_exp[3]; 
	                            $flag                    = 1; 
	                        } 	                        
	                    } 
	                     
	                } 
	                if ($flag != 1) 
	                { 
	                    //동일 item이 존재하지 안는 경우 error1 
	                    $return = 'delete,error1'; 
	                } 
	                unset($flag); 
	            } 
	            else 
	            { 
	                //$_SESSION['item']이 등록된적이 없는경우 
	                $return = 'delete,error2'; 
	            } 
	
	        break; 
	
	
		   case 'delete': 
	
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                $count = sizeof($_SESSION['item']); 
	                foreach($_SESSION['item'] as $i => $value) 
	                { 
	                    //unset 아이템 초기화 
	                    unset($item_cart_exp); 
	                    unset($item_tmp); 
	                    unset($item_cart_tmp); 
	                    $item_cart_exp    = explode(',',$value); 
	                    $item_cart_tmp    = $item_cart_exp[0].$item_cart_exp[1].$item_cart_exp[2]; 
	                    $item_tmp         = $goods_number.$goods_type.$goods_type2; 
	                    if ($item_cart_tmp == $item_tmp) 
	                    { 
	                        //동일 item이 존재할 경우 
	                        $item_cart_exp[3]        = $item_cart_exp[3] - $quantity; 
	                         
	                        if ($item_cart_exp[3] < 1) 
	                        { 
	                            // 물품갯수가 1이하인 경우 물건삭제 
	                            unset($_SESSION['item'][$i]); 
	                            $flag                    = 1; 
	                        } 
	                        else 
	                        { 
	                            // 물품갯수가 1이상인 경우 
	                            $_SESSION['item'][$i]    = $item_cart_exp[0].','.$item_cart_exp[1].','.$item_cart_exp[2].','.$item_cart_exp[3]; 
	                            $flag                    = 1; 
	                        } 
	                    } 
	                     
	                } 
	                if ($flag != 1) 
	                { 
	                    //동일 item이 존재하지 안는 경우 error1 
	                    $return = 'delete,error1'; 
	                } 
	                unset($flag); 
	            } 
	            else 
	            { 
	                //$_SESSION['item']이 등록된적이 없는경우 
	                $return = 'delete,error2'; 
	            } 
	
	        break; 
         
	        case 'reset': 
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                unset($_SESSION['item']); 
	            } 
	            $return = 'reset,ok'; 
	        break; 
	
	        case 'print': 
	            if(isset($_SESSION['item']) or is_array($_SESSION['item'])) 
	            { 
	                foreach($_SESSION['item'] as $key => $value) 
	                { 
	                    echo "$key : $value <br>"; 
	                } 
	            } 
	            $return = 'print,ok'; 
	        break; 
	    } 
	return $return; 
	} 




	function send_mail($emailaddress, $fromaddress, $emailsubject, $body, $attachments=false)
	{
	  $eol="\r\n";
	  $mime_boundary=md5(time());
	  
	  # Common Headers
	  $headers .= 'From: <'.$fromaddress.'>'.$eol;
	  $headers .= 'Reply-To: <'.$fromaddress.'>'.$eol;
	  $headers .= 'Return-Path: '.$fromaddress.'>'.$eol;    // these two to set reply address
	  $headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
	  $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters
	
	  # Boundry for marking the split & Multitype Headers
	  $headers .= 'MIME-Version: 1.0'.$eol;
	  $headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
	
	  $msg = "";      
	  
	  if ($attachments !== false)
	  {
	
	    for($i=0; $i < count($attachments); $i++)
	    {
	      if (is_file($attachments[$i]["file"]))
	      {   
	        # File for Attachment
	        $file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
	        
	        $handle=fopen($attachments[$i]["file"], 'rb');
	        $f_contents=fread($handle, filesize($attachments[$i]["file"]));
	        $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
	        fclose($handle);
	        
	        # Attachment
	        $msg .= "--".$mime_boundary.$eol;
	        $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;
	        $msg .= "Content-Transfer-Encoding: base64".$eol;
	        $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
	        $msg .= $f_contents.$eol.$eol;
	        
	      }
	    }
	  }
	  
	  # Setup for text OR html
	//  $msg .= "Content-Type: multipart/alternative".$eol;
	  
	  # Text Version
	//  $msg .= "--".$mime_boundary.$eol;
	//  $msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
	//  $msg .= "Content-Transfer-Encoding: 8bit".$eol;
	//  $msg .= strip_tags(str_replace("<br>", "\n", $body)).$eol.$eol;
	  
	  # HTML Version
	  $msg .= "--".$mime_boundary.$eol;
	  $msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
	  $msg .= "Content-Transfer-Encoding: 8bit".$eol;
	  $msg .= $body.$eol.$eol;
	  
	  # Finished
	  $msg .= "--".$mime_boundary."--".$eol.$eol;  // finish with two eol's for better security. see Injection.
	    
	  # SEND THE EMAIL
	  ini_set('sendmail_from',$fromaddress);  // the INI lines are to force the From Address to be used !
	  mail($emailaddress, $emailsubject, $msg, $headers);
	  ini_restore('sendmail_from');
	  //echo "mail send";
	}
	
	
	function checkAdmin($dest) 	// 1 - admin, 3 - Employee, 5 - Agent, 9 - Customer
	{ 
		if ($_SESSION['ss_ALEVEL'] > 3) {
			echo "
				<script>
				alert('Sorry, You don\'t have permission or Session Time out.');
				//history.back();
				</script>
				";
			$this -> goUrl($dest, $msg);					
			exit();
		}
	}

	function checkLevelModal ($userLevel) {
		if ($_SESSION['ss_LEVEL'] > $userLevel) { 
			$msg = "Sorry, You don't have permission. Please contact Administrator.";	
			session_destroy();
			$this -> modalMsgIN($msg, "/login_intranet.php");
			exit;
		}
	}	
	
	function checkLevel ($userLevel) {
		if ($_SESSION['ss_LEVEL'] < $userLevel) { 
			echo "			
				<script>
				alert('Sorry, You don\'t have permission.');
				//history.back();
				</script>
				";
			$this -> goUrl("/admin/adm_welcome.php", $msg);
			exit;
		}
	}	
	
	function checkLogin($dest) 
	{ 	
		if (($_SESSION['ss_UID'] == "") || ($_SESSION['ss_LOGIN'] != "1")) {
			echo "
				<script>
				alert('Sorry, You don\'t have permission, Please log in.');
				//history.back();
				</script>
				";
			$this -> goUrl($dest, $msg);					
			exit();
		}
	}

	function getStrCut($str,$len,$str2)
	{
		if (!$str) $str2 = "..";
		if ($len >= strlen($str)) return $str;
		$klen = $len - 1;
		while(ord($str[$klen]) & 0x80) $klen--;
		return substr($str, 0, $len - (($len + $klen + 1) % 2)) .$str2;
	}
	
	

	function DsendMail ($emailaddress, $fromaddress, $emailsubject, $body, $attachments)
	{
	  $eol="\r\n";
	  $mime_boundary=md5(time());
	  
	  # Common Headers
	  $headers .= 'From: <'.$fromaddress.'>'.$eol;
	  $headers .= 'Reply-To: <'.$fromaddress.'>'.$eol;
	  $headers .= 'Return-Path: '.$fromaddress.'>'.$eol;    // these two to set reply address
	  $headers .= "Message-ID: <".$now." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
	  $headers .= "X-Mailer: PHP v".phpversion().$eol;          // These two to help avoid spam-filters
	
	  # Boundry for marking the split & Multitype Headers
	  $headers .= 'MIME-Version: 1.0'.$eol;
	  $headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol;
	
	  $msg = "";      
	  
	  if ($attachments != false)
	  {
	
	    for($i=0; $i < count($attachments['tmp_name']); $i++)
	    {
	    	 //echo "<br>[cnt=$i]Name=[".$attachments['name'][$i]."]<br>";
	      if (is_file($attachments['tmp_name'][$i]))
	      {   
	        # File for Attachment
	        //$file_name = substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
		   $file_name = $attachments['name'][$i];
	        //echo "fileName =[$file_name][".filesize($attachments['tmp_name'][$i])."][".$attachments['size'][$i]."]";
	        $handle=fopen($attachments["tmp_name"][$i], 'rb');
	        $f_contents=fread($handle, filesize($attachments["tmp_name"][$i]));
	        $f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
	        fclose($handle);
	        
	        # Attachment
	        $msg .= "--".$mime_boundary.$eol;
	        $msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol;
	        $msg .= "Content-Transfer-Encoding: base64".$eol;
	        $msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
	        $msg .= $f_contents.$eol.$eol;
	        
	      }
	    }
	  }
	  
	  # Setup for text OR html
	//  $msg .= "Content-Type: multipart/alternative".$eol;
	  
	  # Text Version
	//  $msg .= "--".$mime_boundary.$eol;
	//  $msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
	//  $msg .= "Content-Transfer-Encoding: 8bit".$eol;
	//  $msg .= strip_tags(str_replace("<br>", "\n", $body)).$eol.$eol;
	  
	  # HTML Version
	  $msg .= "--".$mime_boundary.$eol;
	  $msg .= "Content-Type: text/html; charset=EUC-KR".$eol;
	  $msg .= "Content-Transfer-Encoding: 8bit".$eol;
	  $msg .= $body.$eol.$eol;
	  
	  # Finished
	  $msg .= "--".$mime_boundary."--".$eol.$eol;  // finish with two eol's for better security. see Injection.
	    
	  # SEND THE EMAIL
	  ini_set(sendmail_from,$fromaddress);  // the INI lines are to force the From Address to be used !
	  mail($emailaddress, $emailsubject, $msg, $headers);
	  ini_restore(sendmail_from);
	  //echo "mail send";
	}	


	// $wantedWidth : 이미지 포멧 가로길이
	// $wantedHeight : 이미지 포멧 세로길이 
	// $imgSrc : 이미지 상대경로 및 이미지명 	
	function getImageWidthHeight($wantedWidth, $wantedHeight, $imgSrc) 
	{
		$source_pic = getenv("DOCUMENT_ROOT").$imgSrc;
		$max_width = $wantedWidth;
		$max_height = $wantedHeight;
		
		list($width,$height)=getimagesize($source_pic);
		
		$x_ratio = $max_width / $width;
		$y_ratio = $max_height / $height;
		
		if( ($width <= $max_width) && ($height <= $max_height) ){
		    $tn_width = $width;
		    $tn_height = $height;
		    }elseif (($x_ratio * $height) < $max_height){
		        $tn_height = ceil($x_ratio * $height);
		        $tn_width = $max_width;
		    }else{
		        $tn_width = ceil($y_ratio * $width);
		        $tn_height = $max_height;
		}
		
		$www = $tn_width;
		$hhh = $tn_height;
		$strImgSize = "width=$tn_width height=$tn_height";
		return $strImgSize;
	}	
	


################################################################################
// 파일 사이즈를 GB,MB,KB 에 맞추어서 변환해서 리턴
################################################################################
	function get_filesize_size($size) {
	    if(!$size) return "0 Byte";
	
	    if($size >= 1073741824) { 
	        $size = sprintf("%0.3f GB",$size / 1073741824); 
	    } elseif($size >= 1048576) {
			$size = sprintf("%0.2f MB",$size / 1048576); 
	    } elseif($size >= 1024)  {
			$size = sprintf("%0.1f KB",$size / 1024); 
	    } else {
	        $size = $size." Byte"; 
	    }
	
	    return $size;
	}
	
	



	/** * Convert a comma separated file into an associated array. 
	* The first row should contain the array keys. 
	*  
	* Example: 
	*  
	* @param string $filename Path to the CSV file 
	* @param string $delimiter The separator used in the file 
	* @return array 
	* @link http://gist.github.com/385876 
	* @author Jay Williams <http://myd3.com/> 
	* @copyright Copyright (c) 2010, Jay Williams 
	* @license http://www.opensource.org/licenses/mit-license.php MIT License 
	*
	* Example
	* $ttt = csv_to_array('csvsample.csv');
	*
	* for ($i=0; $i< sizeof($ttt); $i++) {
	* 	echo $ttt[$i]['c']."<br>";
	* }
	*/
	/* 첫라인에 컬럼명이 있는 경우 컬럼명을 변수로 가져옴 */
	 
	function csv_to_array($filename='', $delimiter=',')
	{
	    if(!file_exists($filename) || !is_readable($filename))
	        return FALSE;
	
	    $header = NULL;
	    $data = array();
	    if (($handle = fopen($filename, 'r')) !== FALSE)
	    {
	        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
	        {
	            if(!$header)
	                $header = $row;
	            else
	                $data[] = array_combine($header, $row);
	        }
	        fclose($handle);
	    }
	    return $data;
	}

/*
* array 내용을 csv 파일 형식으로 저장. 엑셀에서 open 할수 있음
*
* $mydata = array(
* array('data11,1111', 'data12', '\'data13'),
* array('data21', 'data22', 'data23'),
* array('data31,"123"', 'data32', 'data23'));
*
* outputCSV($mydata, 'csvsampleout.csv');
*/
	function outputCSV($data, $filename) {
	
	    $outstream = fopen($filename, 'w'); 
	
	    function __outputCSV(&$vals, $key, $filehandler) {
	        fputcsv($filehandler, $vals, ',', '"');
	    }
	    array_walk($data, '__outputCSV', $outstream);
	
	    fclose($outstream);
	}


/* #######################################################
달러에 마이너스 처리 (무조건)
changeMinus("-10.12","-","$"); => -$10.12
######################################################### */

function changeMinus ($myStr, $findStr, $specificStr) {
	$pos = strpos($myStr, $findStr);
	
	if ($pos !== false) {
		$myStr = str_replace($findStr, "", $myStr);
		$myStr = $findStr.$specificStr.$myStr;
		return $myStr;
	}
	return $findStr.$specificStr.$myStr;
	
	
}

/* #######################################################
달러에 마이너스 처리 (+값이면 그대로, - 값이면 - 추가)
changeMinus("-10.12","-","$"); => -$10.12
######################################################### */

function changeMinusAuto ($myStr, $findStr, $specificStr) {
	//$pos = strpos($myStr, $findStr);
	
	$myStr = str_replace(',', "", $myStr);  		// 콤마 제거 12,345.00 => 12345.00
	//echo "[$myStr]";
	if ($myStr < 0) {
		//echo "IN";
		$myStr = str_replace($findStr, "", $myStr);	// 마이너스 제거
		$myStr = number_format(floatval($myStr), 2, '.', ',');
		return $findStr.$specificStr.$myStr;
	}
	else {
		$myStr = number_format(floatval($myStr), 2, '.', ',');
		return $specificStr.$myStr;
	}
	
}


function changeMinusAutoPlus ($pointStr, $myStr, $findStr, $specificStr) {
	//$pos = strpos($myStr, $findStr);
	
	$myStr = str_replace(',', "", $myStr);  		// 콤마 제거 12,345.00 => 12345.00
	//echo "[$myStr]";
	if ($myStr < 0) {
		//echo "IN";
		$myStr = str_replace($findStr, "", $myStr);	// 마이너스 제거
		$myStr = number_format(floatval($myStr), $pointStr, '.', ',');
		return $findStr.$specificStr.$myStr;
	}
	else {
		$myStr = number_format(floatval($myStr), $pointStr, '.', ',');
		return $specificStr.$myStr;
	}
	
}

}
?>