﻿/**
 *  common.js version 1.0
 *
 * AUTHORS LIST       E-MAIL  
 * jaehyun lim    jhylim@lgcns.com
 */
var _leftMenu, _quickMenu, _familySite;
var _slideMenu;

/**  Calender variable  **/
var vPreEventElement;        
var objTxt;    

function initPage() { 
	try {
	    document.execCommand("BackgroundImageCache", false, true);
	} catch(ignored) {}

	_leftMenu = $("LblockLeftMenu");
	_quickMenu = $("LblockQuickMenu");
	_familySite = $("LblockFooterFamilySite");
	_ExplanatoryList = $("LblockExplanatoryList");
	initTopMenu();
	if (_leftMenu) initLeftMenu();
	if (_quickMenu) initQuickMenu();
	if (_familySite) initFamilySite();
	if (_ExplanatoryList) initExplanatoryList();
	initTab();
}

function initTopMenu() {
	_topMenu = new dui.hhmenu2.HHMenu2();
	var root = document.getElementById("LblockTopMenu").getElementsByTagName("ul")[0];
	_topMenu.init(root);
}

function initLeftMenu() { 
	if (!_leftMenu) return;
	var root = $(_leftMenu.getElementsByTagName("ul")[0]);
	
	_slideMenu = dui.SlideMenu.makeSlideMenu(root);
	_slideMenu.beforeOpen = function(menu) { 
		menu.addClassName("Lopen");
		menu.removeClassName("Lclose");
	}
	_slideMenu.afterClose = function(menu) { 
		menu.addClassName("Lclose");
		menu.removeClassName("Lopen");
	}
} 

function initFamilySite() {
	_familySite.onmouseover = function () {
		this.getElementsByTagName("ul")[0].style.display = "block";
	}
	_familySite.onmouseout = function () {
		this.getElementsByTagName("ul")[0].style.display = "none";
	}
}

function initExplanatoryList() {
	_familySite.onmouseover = function () {
		this.getElementsByTagName("ul")[0].style.display = "block";
	}
	_familySite.onmouseout = function () {
		this.getElementsByTagName("ul")[0].style.display = "none";
	}
}


function initTab () {
	Tab.initPage();
}

var Tab = function (obj) {
	this.initialize(obj);
}
Tab.initPage = function () {
	var divs = document.getElementsByTagName("div");
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className.indexOf("LblockTab") != -1) new Tab(divs[i]);
	}
}
Tab.prototype = {
	initialize : function(tabList) {
		if (typeof tabList == "string") tabList = document.getElementById(tabList);
		if (!tabList) return;
		var tabs = tabList.getElementsByTagName("li");
		for (var i=0; i<tabs.length; i++) {
			$(tabs[i]);
			tabs[i].index = i;
			tabs[i].onclick = function () {
				for (var k=0; k<tabs.length; k++) {
					var link = tabs[k].getElementsByTagName("a")[0];
					link.onclick = function () {return false;}
					if (link && link.href && (linkIndex = link.href.lastIndexOf("#")) != -1 && 
						(tabarea = document.getElementById(link.href.substring(linkIndex+1)))) {
						if (k == this.index) tabarea.style.display = "block";
						else tabarea.style.display = "none";
					}
					if (k == this.index) this.addClassName("Lcurrent");
					else tabs[k].removeClassName("Lcurrent");
				}
			}
		}
	}
}

var QuickMenu = function (obj) {
	this.initialize(obj);
}
QuickMenu.prototype = {
	qmenu : null,
	lastScrollY : 0,
	position_start : 0,
	position : null,
	action : null,
	speed : .1,
	
	initialize : function(obj) {
		if (typeof obj == "string") obj = document.getElementById(obj);
		if (!obj) return;
		this.qmenu = obj;
		this.position = parseInt($(this.qmenu).getStyle("top"));
		var comp = this;
		var fnc = function() {comp.move();};
		this.action = window.setInterval(fnc,10);
	},
	move : function () {
		var diffY = document.documentElement.scrollTop;
		if (diffY == this.lastScrollY) return;
		var percent = this.speed * (diffY - this.lastScrollY);
		if (percent > 0) percent = Math.ceil(percent);
		else percent = Math.floor(percent);
		this.position += percent;
		this.qmenu.style.top = this.position + this.position_start + "px";
		this.lastScrollY = this.lastScrollY + percent;
	}
}
 
function initQuickMenu() {
	var qmenu = new QuickMenu("LblockQuickMenu");
}

/* input null ckeck */
function displayErrorMsg(ctlControl, errControl, errMsg, className) {

    var strErrMsg = "* Please complete the required field(s) highlighted below to submit your registration information. ";

    if (trimstr(ctlControl.value) == "") {
        if (errMsg == "")
            errControl.innerHTML = strErrMsg;
        else
            errControl.innerHTML = errMsg;

        ctlControl.className = "Ltext Lerror";
        ctlControl.focus();
        return 1;
    } else {
        ctlControl.className = "Ltext";
        return 0;
    }
}

window.onload = initPage;

/*************************************************************************************************/
/**      Calender function   Start                                                              **/
/*************************************************************************************************/
//마우스 이벤트 위치에 따라서 달력Divsion이 보여지거나 보여지지 않도록 함.
function fDisAppearTimeDiv(evt, vDivId, vTxtId, vBtnId, MoveHeight, MoveWidth, rootPath) {
    objDiv = document.getElementById("DIV_CALENDAR");
    objTxt = document.getElementById(vTxtId); 

    var theEvent = evt ? evt : window.event;

    if (navigator.userAgent.indexOf("Firefox") > -1) theEvent.stopPropagation(true);
    else theEvent.cancelBubble = true;

    if ((vDivId == "") || (vDivId == null)) {
        fDisAppearAllTimeDiv();
        return;
    }

    if (vDivId == "DIV_CALENDAR") {
        if ((vPreEventElement == vBtnId) && (objDiv.style.display == "block")) fDisAppearAllTimeDiv()
        else fShowCalendar(evt, objTxt, vBtnId, MoveHeight, MoveWidth, rootPath);
    }

    vPreEventElement = vBtnId; //다음번 호출시 비교하기 위함.
}

//일시 설정 관련된 Select용 Division들을 모두 숨김.
function fDisAppearAllTimeDiv() {

    objDiv = document.getElementById("DIV_CALENDAR");
    objDiv.style.display = "none";
}

//날짜를 선택할 달력을 보여줌.
function fShowCalendar(evt, Obj1, Obj2, MoveHeight, MoveWidth, rootPath) {//Obj1:text, Obj2:Button.

    var vObj_DIV = document.getElementById("DIV_CALENDAR");
    var vObj_TXT = eval(Obj1);
    var vObj_BTN = eval(Obj2);
    var vObj_FRM = document.getElementById("fCal");
    var vObj_targetObj = document.getElementById("targetObj");
    
    var theEvent = evt ? evt : window.event;

    fDisAppearAllTimeDiv();
    vObj_DIV.style.position = "absolute";
    vObj_DIV.style.display = "block";
    vObj_FRM.src = rootPath + "Common/Popup/calender.aspx";

        
    var nTop =   MoveHeight; 
    var nLeft =  MoveWidth;
     
    vObj_DIV.style.top =   nTop + "px";  
    vObj_DIV.style.left = nLeft + "px";   
    vObj_targetObj.value = Obj1; //값이 Setting될 Text Object 명.
   
    vObj_DIV.style.zIndex = 2;
    vObj_DIV.focus();
}

//날짜(YYYYMMDD)값을 TEXT의 Value에 값을 할당.
function fSetCalendarValue(yyyymmdd) {

    //if(yyyymmdd > "") 
    objTxt.value = yyyymmdd;
    objTxt.focus();
    objTxt.blur();
    var vObj_DIV = document.getElementById("DIV_CALENDAR");
    vObj_DIV.style.display = "none";
}

function fSetCalendarSize(vWidth, vHeight) {
    var vObj_FRM = document.getElementById("fCal");
    
    vObj_FRM.style.width = vWidth;
    vObj_FRM.style.height = vHeight;
}

// 날자 숫자만 허용
function fnOnlyNumber(ev)
{
    var evKey = "";

    if(navigator.userAgent.indexOf("Firefox") > -1)
    {
        evKey = ev.which;
        
        if( ((evKey < 48) || (evKey > 57)) && (evKey != 46) && (evKey != 8) && (evKey != 190)) ev.preventDefault(false);
    }
    else
    {
        evKey = event.keyCode;
        
        if( ((evKey < 48) || (evKey > 57)) && (evKey != 46) && (evKey != 8) && (evKey != 190)) event.returnValue=false;
    }
}

function fnChkDateFormat(sValue, objCtl)
{   
    var regexp = ".";
    
    for(var i=0; i < sValue.length; i++)
    {
       var ch = sValue.charAt(i);
       
       if(ch == ".") sValue = sValue.replace(regexp, "");
    }
     
    if(sValue.length == 8)
    {
        var sMon = sValue.substring(0, 2);
        var sDay = sValue.substring(2, 4);
        var sYear = sValue.substring(4, 8);
        var bchk = true;
       
        if((parseInt(sYear) < 1800))
        {
            alert("The date format is invalid.");
            objCtl.value = "";
            bchk = false;
            
            return false;
        } 
        
        if(!(parseInt(sMon) > 0 && parseInt(sMon) < 13))
        {
            alert("Please input Month digits with between '01' and '12'.");
            objCtl.value = "";
            bchk = false;
            
            return false;
        } 

        if(!(parseInt(sDay) > 0 && parseInt(sDay) < 32))
        {
            alert("Please input Day digits with between '01' and '31'.");
            objCtl.value = "";
            bchk = false;
            
            return false;
        }
        
        if(bchk)
        {
            sValue = sMon + "." + sDay + "." + sYear;
            objCtl.value = sValue;
        }  
        else objCtl.focus();      
    }
    else
    {
        if(sValue.length == 0) objCtl.value = "";
        else
        {
           alert("Please input 8 digits with 'MMDDYYYY'.");
           objCtl.value = "";
        }
    }
}

/*************************************************************************************************/
/**      Calender function   End                                                                **/
/*************************************************************************************************/

/**  Png 투명처리 소스  **/
/*function setPng24(obj) {
	obj.width=obj.height=1;
	obj.className=obj.className.replace(\bpng24\b/i,'');
	obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+obj.src+"',sizingMethod='image');"
	obj.src='';
	return '';
}
var clear="../images/clear.gif" //path to clear.gif

pngfix=function(){var els=document.getElementsByTagName('*');var ip=/\.png/i;var i=els.length;while(i-- >0){var el=els[i];var es=el.style;if(el.src&&el.src.match(ip)&&!es.filter){es.height=el.height;es.width=el.width;es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";el.src=clear;}else{var elb=el.currentStyle.backgroundImage;if(elb.match(ip)){var path=elb.split('"');var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";es.height=el.clientHeight+'px';es.backgroundImage='none';var elkids=el.getElementsByTagName('*');if (elkids){var j=elkids.length;if(el.currentStyle.position!="absolute")es.position='static';while (j-- >0)if(!elkids[j].style.position)elkids[j].style.position="relative";}}}}}
window.attachEvent('onload', pngfix);
*/
// ============================================================
// 문자열의 앞뒤 space를 제거한다.
// ============================================================ 
function trimstr(value) {
    if (value == null)
        value = "";
    value = value.replace(/^\s+/, ""); // remove leading  white spaces
    value = value.replace(/\s+$/g, ""); // remove trailing while spaces
    return value;
}

// Enter키 체크 -> EnterKey값이면 Search 버튼에 Focus를 준다.
function fnEnterKey(ev, objfocusId)
{ 
    var evKey = "";

    if(navigator.userAgent.indexOf("Firefox") > -1)
    {
        evKey = ev.which;
    }
    else
    {
        evKey = event.keyCode;
    }
    
    var objSearch = document.getElementById(objfocusId);
    
    if(evKey == 13) objSearch.focus();
}


function updateChar(objContent, objMsg, objfocus, length_limit)
{ 
     var length = calculate_msglen(objContent.value);
     var sfocusValue = objfocus.value;
     
     if (length > length_limit) 
     {
          objMsg.innerHTML = "The maximum length of input is as follows: "+length_limit+" characters. The exceeding message will not be saved.";
          //objContent.value = objContent.value.replace(/\r\n$/, "");
          
           // 마지막 문자가 한글인지 체크
           ch = objContent.value.charAt(objContent.value.length -1);
           if (escape(ch).length > 4)
           { 
               objfocus.focus();
               objfocus.value = sfocusValue;
               objContent.value = assert_msglen(objContent.value, length_limit);
               objContent.focus();         
           }
           else
           {
               objContent.focus();
               objContent.value = assert_msglen(objContent.value, length_limit);
           }
     }
}

//바이트계산 함수 
function calculate_msglen(msg)
{
    var nbytes = 0;

    for (i=0; i<msg.length; i++) 
    {
        var ch = msg.charAt(i);
        
        if(escape(ch).length > 4) 
        {
            nbytes += 1;
        } 
        else if (ch == '\n') 
        {
            if (msg.charAt(i-1) != '\r') 
            {
                nbytes += 1;
            }
        } 
        else if (ch == '<' || ch == '>') 
        {
            nbytes += 4;
        } 
        else { nbytes += 1;  }
    }

    return nbytes;
}

//초과한 바이트에 해당하는 문자열 정리 함수 
function assert_msglen(message, maximum)
{
    var inc = 0;
    var nbytes = 0;
    var msg = "";
    var msglen = message.length;

    for (i=0; i<msglen; i++) 
    {
        var ch = message.charAt(i);
        
        if (escape(ch).length > 4) 
        {
            inc = 1;
        } 
        else if (ch == '\n') 
        {
            if (message.charAt(i-1) != '\r') 
            {
                inc = 1;
            }
        } 
        else if (ch == '<' || ch == '>') 
        {
            inc = 4;
        } 
        else { inc = 1; }
  
        if ((nbytes + inc) > maximum) { break; }
    
        nbytes += inc;
        msg += ch;
    }
    
    return msg;
}