/*------------------------------------------------------------------------
 * EPMS Common JavaScript for Client Side
 * -----------------------------------------------------------------------
 * ※ 반드시 아래의 function정의 방법에 의거하여 function을 등록하세요.※
 * -----------------------------------------------------------------------
 * ### function정의방법 ### 
 * Common.functionName = function() {
 *     //define logic.
 * }
 * 
 * ### example ###
 * Common.test = function(v) {
 *     alert(v);
 * }
 * 
 * @author cheonbo shim
 * @date 2009-11-11
 *------------------------------------------------------------------------*/

/**
 * 주어진 obj하위에 주어진 element tag에 매치되는 Element의 배열을 리턴한다.
 * 
 * @param {Object} obj 찾으려고 하는 대상 elements오브젝트
 * @param {String} el 찾기대상 element tagName
 * @param {Array} 만약 찾는 대상이 존재하지 않으면 빈 Array Object를 리턴한다.
 */
Common.getChild = function(obj, el) {
    if (typeof obj == 'string')
        obj = document.getElementById(obj);
    var array = new Array();
    var child = obj.childNodes;
    if (child) {
        if (child.length) {
            for (var i = 0 ; i < child.length ; i++) {
                
                var temp = child[i].tagName ? child[i].tagName.toLowerCase() : '';
                if (temp == el) {
                    array[array.length] = child[i];
                }
            }
        }
        else {
            var t = child.tagName ? child.tagName.toLowerCase() : '';
            if (t == el) array[array.length] = child;
        }
    }
    
    return array;
}     

/**
 * 메뉴 이미지호출 url
 * @type {String} 
 */
var IMAGE_CONTROLLER = "/common/image.do?";

/**
 * TOP메뉴 핸들러.
 * 
 * @param {Object} event발생 object
 * @param {String} etype 이벤트유형 [OVER: (onmouseover, onfocus), OUT: (onmouseout, onblur)
 * @param {String} dtype 표시유형(I:이미지, T: 텍스트)
 */
TopMenuHandler = function() {
    
    var callMenu;
    
    function getTopImage(obj) {
        var ahrefval = Common.getChild(obj, 'a');
        return (Common.getChild(ahrefval[0], 'img'))[0];
    }
    function getSubMenuUL(obj) {
        return (Common.getChild(obj, 'div'))[0];
    }
    
    return {
        execute: function(obj, etype, dtype) {
            if (typeof obj == 'string') {
                obj = document.getElementById(obj);
                callMenu = obj;
            }
            
            if (typeof etype == 'undefined') {
                etype = "OVER";
            }
            
            if (obj.tagName) {
                var tn = obj.tagName.toLowerCase();
                var robj = obj.parentNode;
                if (tn == 'a') {
                    robj = robj.parentNode;
                }
                
                var topMenus = Common.getChild(robj, 'li');
                if (topMenus) {
                    for (var i = 0 ; i < topMenus.length ; i++) {
                        var tempObj = topMenus[i];
                        var menuSeq = tempObj.id.split('-');
                        var imgObj = getTopImage(tempObj);
                        var subMenus = getSubMenuUL(tempObj);
                        
                        if (etype == 'OVER') {
                            if (tempObj.id == obj.id) {
                                imgObj.src = IMAGE_CONTROLLER + 'menu=' + menuSeq[1] + '&event=over&type=top';
                                subMenus.style.visibility = 'visible';
                            }
                            else {                            
                                imgObj.src = IMAGE_CONTROLLER + 'menu=' + menuSeq[1]  + '&event=out&type=top';
                                subMenus.style.visibility = 'hidden';
                            }                            
                        }
                        else {
                            if (tempObj.id == callMenu.id) {
                                imgObj.src = IMAGE_CONTROLLER + 'menu=' + menuSeq[1] + '&event=over&type=top';
                                subMenus.style.visibility = 'visible';                                
                            }
                            else {
                                imgObj.src = IMAGE_CONTROLLER + 'menu=' + menuSeq[1]  + '&event=out&type=top';
                                subMenus.style.visibility = 'hidden';                                
                            }
                        }
                    }
                }
            }
        }
    }
}();
topMenuNavi = TopMenuHandler.execute;

/**
 * LEFT메뉴 핸들러.
 * 
 * @param {Object} event발생 object
 * @param {String} depth 메뉴깊이
 * @param {String} id 메뉴 아이디
 * @param {String} dtype 표시유형(I:이미지, T: 텍스트)
 * @param {String} etype 이벤트유형 [OVER: (onmouseover, onfocus), OUT: (onmouseout, onblur) 
 * @param {String} ipath 이미지경로 (Option)
 */
Common.leftMenuhandler = function(obj, depth, id, dtype, etype, ipath) {
    
}
leftMenuNavi = Common.leftMenuhandler;

/**
 * 페이지 만족도 통계저장.
 * @param {Form} form
 * @param {Boolean} commentCheckFlag 커멘트 check여부 {true: 체크, false; 미체크}
 */
Common.pageStatistics = function(form, commentCheckFlag) {
    if (commentCheckFlag) {
        if (form.comment_v.value == "") {
            alert("의견을 입력해 주십시오.");
            form.comment_v.focus();
            return false;
        }
    }
    
    var menuSeq = form.menu_seq_n.value;
    var comment = form.comment_v.value;
    var cdSeq;
    var cdSeqs = form.cd_seq_n;
    if (cdSeqs.length > 1) {
        for (var idx = 0; idx < cdSeqs.length; idx++) {
            if (cdSeqs[idx].checked) cdSeq = cdSeqs[idx].value;
        }
    } else {
        if (cdSeqs.checked) cdSeqs = cdSeqs[idx].value;
    }
    
    jQuery.ajax({
        type: "POST",
        url : form.action,
        data: "menu_seq_n="+ menuSeq +"&cd_seq_n="+ cdSeq +"&comment_v="+comment,
        dataType: "json",
        success: function(data) {
            var msg = data.message;
            alert(msg);
        }
    });
    
    return false;    
}
pageStatistics = Common.pageStatistics;


Common.objE = function(param) {
    return document.getElementById(param);
}
objE = Common.objE;

Common.getUrl = function(url) {
    return window.location.href=url;
}
getUrl = Common.getUrl;

Common.getGo = function(value) {
    return window.history.go(value);
}
getGo = Common.getGo;

Common.getBack = function() {
    return window.history.back();
}
getBack = Common.getBack;

Common.getForward = function() {
    return window.history.forward();
}
getForward = Common.getForward;

Common.getRefresh = function() {
    return window.location.reload(true);
}
getRefresh = Common.getRefresh;

Common.getReload = function() {
    return location.reload();
}
getReload = Common.getReload;

Common.getClose = function() {
    return window.close();
}
getClose = Common.getClose;

Common.getPrint = function() {
    return window.print();
}
getPrint = Common.getPrint;

Common.newWindow = function(url,target,w,h,s,p) {
    var win;

    if (p == 1) {
        if (self.innerHeight) {
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight) {
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        }
        else if (document.body) {
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }
        var x = (windowWidth-w)/2;
        var y = (windowHeight-h)/2;

        win = window.open(url,target,"left="+x+",top="+y+",width="+w+",height="+h+",scrollbars="+s+",resizable=0,status=1");
    } else {
        win = window.open(url,target,"width="+w+",height="+h+",scrollbars="+s+",resizable=0,status=1");
    }
    win.focus();

    return win;
}
newWindow = Common.newWindow;

Common.newFullWindow = function(url) {
    window.open(url,"_blank","fullscreen");
}
newFullWindow = Common.newFullWindow;

Common.embedSwf = function(url,id,w,h,wm) {
    var wmode = (wm == 1) ? 'window' : 'transparent';
    var embed = "";
    embed = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="'+id+'" width="'+w+'" height="'+h+'">';
    embed += '  <param name="movie" value="'+url+'" \/>';
    embed += '  <param name="quality" value="high" \/>';
    embed += '  <param name="bgcolor" value="#FFFFFF" \/>';
    embed += '  <param name="wmode" value="'+wmode+'" \/>';
    embed += '  <param name="menu" value="false" \/>';
    embed += '  <param name="allowScriptAccess" value="sameDomain" \/>';
    embed += '  <embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" name="'+id+'" src="'+url+'" width="'+w+'" height="'+h+'" quality="high" bgcolor="#FFFFFF" wmode="transparent" menu="false" allowScriptAccess="sameDomain"><\/embed>';
    embed += '<\/object>';

    document.write(embed);
}
embedSwf = Common.embedSwf;

Common.embedWmp = function(url,id,w,h,autostart) {
    var embed = "";
    embed = '<object type="application/x-oleobject" classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=6,4,7,1112" id="'+id+'" name="'+id+'" width="'+w+'" height="'+h+'" standby="Loading Windows Media Player components...">';
    embed += '  <param name="url" value="'+url+'" \/>';
    embed += '  <param name="autostart" value="'+autostart+'" \/>';
    embed += '  <param name="autosize" value="0" \/>';
    embed += '  <embed type="application/x-mplayer2" name="'+id+'" id="'+id+'" src="'+url+'" width="'+w+'" height="'+h+'" autostart="'+autostart+'" autosize="0"><\/embed>';
    embed += '<\/object>';

    document.write(embed);
}
embedWmp = Common.embedWmp;

Common.imgSwap = function(obj) {
    if (obj != "undefined" && obj.tagName == "A") {
        var childObj = obj.childNodes;
        if (childObj[0].tagName == "IMG") {
            var strOn = "_on."
            var strOr = "_or."
            var tempSrc = childObj[0].src;
            if (tempSrc.indexOf(strOr) != -1) {
                childObj[0].src = tempSrc.replace(strOr, strOn);
            }
            else {
                childObj[0].src = tempSrc.replace(strOn, strOr);
            }
        }
    }
}
imgSwap = Common.imgSwap;

/**
 * 프레임 resize처리.
 */
Common.iframeResize = function(obj) {
    var iframeHeight = (obj).contentWindow.document.body.scrollHeight;
    (obj).height=iframeHeight+20;
}
iframeResize = Common.iframeResize;

/**
 * 마우스 좌표값을 반환한다.
 * 
 * @param e {Event}
 * @return Object
 */
Common.getPosition = function(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}
getPosition = Common.getPosition;

/**
 * 에러페이지의 버튼 토클 기능 처리.
 */
Common.jsToggle = function() {
    var errMsg = document.getElementById("errStack");
    if (errMsg != null) {
        if (errMsg.style.display == "none") {
            errMsg.style.display = "block";
        }
        else {
            errMsg.style.display = "none";
        }
    }
}
jsToggle = Common.jsToggle;

/**
 * 주어진 element의 class속성을 배열로 리턴한다.
 * @param el {Elements}
 * @return Array
 */
Common.getClassArray = function(el) {
    var vals = new Array();
    var classes = el.className.split(" ");
    for(var j = 0; j < classes.length; j++) {    
        var className = classes[j].replace(" ","");
        vals[i] = className;
    }
    
    return vals;
}
getClassArray = Common.getClassArray;

/**
 * 쿠기삭제
 */
delCookie = Common.deleteCookie;
/**
 * 쿠키호출
 */
getCookie = Common.getCookie;
/**
 * 쿠키설정
 */
setCookie = Common.setCookie;

/**
 * form.field를 매개변수로 하여 
 * 해당하는 필드에 체크된 radio버튼 혹은 checkbox가 있다면 true를
 * 없다면 false를 반환한다.
 * 
 * @param {Object} field_obj
 */
Common.hasChecked = function(obj) {
    if (obj.length > 1) {
        for (var idx = 0; idx < obj.length; idx++) {
            if (obj[idx].checked) return true;
        }
    }
    else {
        if (obj.checked) return true;
    }
    return false;    
}
hasChecked = Common.hasChecked;

Common.hasCheckedValue = function(obj) {
    if (obj.length > 1) {
        for (var idx = 0; idx < obj.length; idx++) {
            if (obj[idx].checked) return obj[idx].value;
        }
    } else {
        if (obj.checked) return obj[idx].value;
    }
    return obj[idx].value;
}
hasCheckedValue = Common.hasCheckedValue;

Common.magicPop = function(id) {
    var obj = document.getElementById(id);
    if(obj) {
        if(obj.style.display == 'block') {
            obj.style.display='none';
            document.getElementById('magic').className='none';
        } else {
            document.getElementById('magic').className='block';
            obj.style.display='block';
        }
    }
}
magicPop = Common.magicPop;

Common.labelCheck = function(obj,id) {
    if (navigator.appVersion.indexOf('MSIE') != -1) {
        if (obj && obj.tagName == "LABEL") {
            var childObj = obj.childNodes;
            if (childObj[0].tagName == "IMG") {
                if (document.getElementById(id).type == "checkbox" || document.getElementById(id).type == "radio" || document.getElementById(id).type == "file") {
                    document.getElementById(id).click();
                }
                else {
                    document.getElementById(id).focus();
                }
            }
        }
    }
}
labelCheck = Common.labelCheck;

var key = false;
Common.clearText = function(id) {
    if (!key) {
        document.getElementById(id).value='';
        key = true;
    }
}
clearText = Common.clearText;

Common.clearValue = function(id) {
    document.getElementById(id).style.backgroundImage='none';
}
clearValue = Common.clearValue;

Common.tabMenu = function(dotabid,num) {
    var inum=parseInt(num)-1;

    var linkTab=document.getElementById(dotabid).getElementsByTagName("li");
    for (i=0;i<linkTab.length;i++) {
        var tabimg = linkTab.item(i).getElementsByTagName("img").item(0);
        var tabContents= document.getElementById(dotabid+(1+i));

        if (i==inum) {
            if(tabContents.style.display!="block") {
                tabimg.src=tabimg.src.replace("_or.","_on.");
                tabContents.style.display="block";
            }
        } else {
            tabimg.src=tabimg.src.replace("_on.","_or.");
            tabContents.style.display="none";
        }
    }
}
tabMenu = Common.tabMenu;

Common.txtMenu = function(dotabid,num) {
    var inum=parseInt(num)-1;
    var linkTab=document.getElementById(dotabid).getElementsByTagName("li");
    for (i=0;i<linkTab.length;i++) {
        var tabContents= document.getElementById(dotabid+(1+i));
        if (i==inum) {
            if(tabContents.style.display!="block") {
                linkTab.item(inum).className="focus";
                tabContents.style.display="block";
            }
        } else {
            linkTab.item(i).className="";
            tabContents.style.display="none";
        }
    }
}
txtMenu = Common.txtMenu;

var nowZoom = 100;
var maxZoom = 200;
var minZoom = 100;
var increaseNum = 10;
Common.zoomIn = function() {
    if (nowZoom < maxZoom) {
        nowZoom += increaseNum; 
    } else {
        return;
    }

    document.getElementById('dobody').style.zoom = nowZoom + "%";
}
zoomIn = Common.zoomIn;

Common.zoomOut = function() {
    if (nowZoom > minZoom) {
        nowZoom -= increaseNum;
    } else {
        return;
    }

    document.getElementById('dobody').style.zoom = nowZoom + "%";
}
zoomOut = Common.zoomOut;

Common.zoomRenew = function() {
    nowZoom = minZoom;
    document.getElementById('dobody').style.zoom = nowZoom + "%";
}
zoomRenew = Common.zoomRenew;

var elem = "tr";
var rClick;
Common.rowHiligh = function() {
    if(document.getElementsByTagName) {
        var el = document.getElementsByTagName(elem);
        for(var i=0; i<el.length; i++) {
            if(el[i].childNodes[0].tagName != "th"
            && el[i].parentNode.parentNode.className.indexOf("list") != -1) {
                if (!(el[i].className == "notice" || el[i].className == "first-child notice")) {
                    if(i%2 == 1) {
                        el[i].className = "first";
                        el[i].oldClassName = "first";
                        el[i].onmouseout  = function() {
                            this.className = "first";
                        }
                    }
                    else {
                        el[i].className = "second";
                        el[i].oldClassName = "second";
                        el[i].onmouseout  = function() {
                            this.className = "second";
                        }
                    }
                }
                el[i].onmouseover = function() {
                    if(!(this.className == "notice" || this.className == "first-child notice")) {
                        if(this.className == this.oldClassName) {
                            this.className = "hover";
                        }
                        else if(this.onmouseout == null && this.className != "click") {
                            this.onmouseout = function() {
                                this.className = this.oldClassName;
                            }
                        }
                    }
                }
            }
        }
    }
}
rowHiligh = Common.rowHiligh;

/* 2009-09-24 edit+ 2dea */
function flash(url,id,w,h) {
	var embed = "";
	embed = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" id="'+id+'" width="'+w+'" height="'+h+'">';
	embed += '	<param name="movie" value="'+url+'" \/>';
	embed += '	<param name="quality" value="high" \/>';
	embed += '	<param name="bgcolor" value="#FFFFFF" \/>';
	embed += '	<param name="wmode" value="transparent" \/>';
	embed += '	<param name="menu" value="false" \/>';
	embed += '	<param name="allowScriptAccess" value="sameDomain" \/>';
	embed += '	<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" name="'+id+'" src="'+url+'" width="'+w+'" height="'+h+'" quality="high" bgcolor="#FFFFFF" wmode="transparent" menu="false" allowScriptAccess="sameDomain"><\/embed>';
	embed += '<\/object>';

	document.write(embed);
}


var destinationUrlTypeStr = "";
var targetTitleStr = "";
var targetUrlStr = "";
var targetMenuNameStr = "";

/* twitter 와 me2day 로 short url 생성후 등록한다. */
function jsSendExportUrl(destinationUrlType, targetTitle, targetUrl, targetMenuName) {
	destinationUrlTypeStr = destinationUrlType;
	targetTitleStr = targetTitle;
	targetMenuNameStr = targetMenuName;

	jsReqShortUrl(targetUrl);
}

function jsReqShortUrl(targetUrl) {
	var scriptObj = document.createElement("script");
	scriptObj.setAttribute("type", "text/javascript");
	scriptObj.setAttribute("charset", "utf-8");
	scriptObj.setAttribute("src", "http://api.bit.ly/v3/shorten?login=greengrowth&apiKey=R_1f24788889eb3e4653f30c5d893b90ef&format=json&callback=jsResShortUrl&longUrl="+targetUrl);
	var headLoc = document.getElementsByTagName("head").item(0);
	headLoc.appendChild(scriptObj);
}
function jsResShortUrl(jsonData) {
	targetUrlStr = jsonData.data.url;

	var destinationUrl = "";

	if(destinationUrlTypeStr == 'twitter') {
		destinationUrl = "http://twtkr.com/index.php?status="+targetTitleStr+encodeURIComponent(":"+targetUrlStr)+"&amp;link_source="+targetMenuNameStr;
	} else if(destinationUrlTypeStr == 'me2day') {
		destinationUrl = "http://me2day.net/posts/new?new_post[body]="+targetTitleStr+encodeURIComponent(":"+targetUrlStr)+"&amp;new_post[tags]="+targetMenuNameStr;
	}
	window.open(destinationUrl,"_blank","");
}

function openWindow(url, name, width, height)   {
    var top  = screen.height / 2 - height / 2 - 50;
    var left = screen.width / 2 - width / 2 ;
    var win =
        open(url,
            name,
            'width=' + width + ', height=' + height + ', top=' + top +
            ', left=' + left + ', resizable=no, status=yes, toolbar=no, menubar=no, scrollbars=auto');
    win.focus();
    return win;
}
