
//_____ Prototyping from here ____________
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}
//_____ Prototyping until here ____________

//_____ class declaration for super-component class _____//
function compRoot(idValue, baseObjectIdValue, isChild, addParams, left, top, auto) {
//    if (compRoot.instanceArray[this.idValue]) {
//        compRoot.compDestroy(this.idValue); 
//    }
    //   if (addParams) alert("on creation, "+addParams);
    compRoot.instanceId = compRoot.instanceId+1;
    this.instanceKey = compRoot.instanceId.toString();
    this.idValue = idValue;
    this.isChild = isChild;
    this.isRel = compRoot.compArray[idValue].isRel;
    this.addParams = ((compRoot.compArray[idValue].defaultParams != "") && (!(isChild))) ? eval(compRoot.compArray[idValue].defaultParams) : addParams;
    this.isFixed = compRoot.compHtmlArray[compRoot.compArray[idValue].html].isFixed;
    this.bSize = compRoot.compArray[idValue].bSize;
    this.pSize = compRoot.compArray[idValue].pSize;
    
    this.addParams += "&pSize=" + this.pSize + "&bSize="+this.bSize;

    this.targetPageNumber = 1;
    this.totalPageCount = 0;
    this.totalRecordCount = 0;
    
    this.queryString = "";
    this.returnValue = 1;
    this.paramNum = 0;
    this.serverCallHit = 0;
    this.pseudoQuery = "";  
    this.callAbove = 1 - parseInt(compRoot.compArray[idValue].draw);

    if (auto && (!(isChild))) this.idValue += "_" + baseObjectIdValue;
    if (isChild) this.idValue += '@' + baseObjectIdValue;
    
    this.containerElement = document.createElement("SPAN");
    this.containerElement.className = "ucr_default";

    this.callback = function(oj) {
    
        if (oj.req.instanceKey != this.instanceKey) return;
    	//      alert("\n[" + this.idValue + "] component callback is just arrived");
      var content = "";
      var bodyHtml = compRoot.compHtmlArray[compRoot.compArray[idValue].html].body;
      
      var pageBand = compRoot.ojPageBand(oj);
      var pageBand2 = compRoot.ojPageBand2(oj);
      
    this.totalPageCount = parseInt((oj.res._totalPageCount)?(oj.res._totalPageCount):(1));
    this.totalRecordCount = parseInt((oj.res._totalRecordCount)?(oj.res._totalRecordCount):(1));
      
      this.pseudoQuery = compRoot.genPseudoQuery(this.addParams, parseInt(compRoot.compArray[idValue].pSize), parseInt(this.targetPageNumber), this.idValue, compRoot.compArray[idValue].html, this.paramNum, this.queryString, this.returnValue, this.serverCallHit, this.instanceKey);
         
      if (compRoot.compHtmlArray[compRoot.compArray[idValue].html].body.lastIndexOf(compRoot.repPseudoString) > -1)
          var pageBand2 = compRoot.ojPageBand2Fixed(this.pseudoQuery);
//      this.ojContents = oj.res.contents;
      
      // Do the replacement of "oj" keyword with the result of call back process   
      content += compRoot.ojRootReplace(compRoot.compHtmlArray[compRoot.compArray[idValue].html].header, oj).replace(eval("/"+compRoot.repCharPageBand+"/g"), pageBand).replace(eval("/"+compRoot.repCharPageBand2+"/g"), pageBand2);
      
    if (this.totalRecordCount>0) {
      if (this.serverCallHit > this.callAbove - 1) content += compRoot.ojContentsReplace( compRoot.ojRootReplace(bodyHtml, oj), oj, this.callAbove);
    } else {
//        if ((idValue=="460")||(idValue=="763")){
//            compRoot.compDestroy(compRoot.findMainComp(this.idValue).id);
//        } else {
            content += compRoot.ojRootReplace(compRoot.compArray[idValue].noresult, oj);
//        }
    }
    
      content += compRoot.ojRootReplace(compRoot.compHtmlArray[compRoot.compArray[idValue].html].footer, oj).replace(eval("/"+compRoot.repCharPageBand+"/g"), pageBand).replace(eval("/"+compRoot.repCharPageBand2+"/g"), pageBand2);      
         
         if ((this.idValue.lastIndexOf("@") > -1)){
            content = content.replace(eval("/" + compRoot.repCharMain + "/g"), this.idValue.substring(this.idValue.lastIndexOf("@") + 1));
         } else {
            content = content.replace(eval("/" + compRoot.repCharMain + "/g"), this.idValue);
         }
         content = content.replace(eval("/" + compRoot.repCharSub + "/g"), this.idValue);
         
         content = content.replace(eval("/" + compRoot.repPseudoString + "/g"), this.pseudoQuery);
         
         if (compRoot.compHtmlArray[compRoot.compArray[idValue].html].body.lastIndexOf(compRoot.repPseudoString) > -1)
               content = content.replace(eval("/"+compRoot.repCharPageBand2+"/g"), pageBand2);
         

    	content = compRoot.paramStringReplace(content, this.addParams);
    	content = compRoot.fixedStringReplace(content);


    	this.containerElement.innerHTML = content;
    	compRoot.funcAssign(idValue);
    	//// the function below should be put only on the MAIN component after all subcomponents load finish //////////////
    	compRoot.setOnloadValue(this.idValue);
    }

    this.elementBaseOnLoad = function() {
        // set Load completion flag using "loadCompleted" attributes for the instances
        this.initRenderComp();
        // Run initiative rendering function for the container first before the creation of the child component
        for (var comp in compRoot.compArray) {
            if (compRoot.compArray[comp].baseFrame == idValue) {
                compRoot.instanceArray[comp + "@" + this.idValue] = new compRoot(comp, this.idValue, true, this.addParams);
            }
        }
    }

    this.initComp = function() {
   
    if ((compRoot.compArray[idValue].cond!=null)&&(compRoot.compArray[idValue].cond!="")&&(!(eval(compRoot.compArray[idValue].cond)))) {
         delete compRoot.instanceArray[this.idValue];
//          this.destroyComp();
        return;
   }
    
        if (((compRoot.authStatus - compRoot.compArray[idValue].visibility + 1) > 0) || (parseInt(compRoot.compArray[idValue].visibility) - compRoot.authStatus == 10)) {
            this.containerElement.id = this.idValue;               
            
            if ((baseObjectIdValue != "body")) {
                if ((parseInt(this.isRel) == 0)||(baseObjectIdValue == "_youcradTitle")) {
                    document.getElementById(baseObjectIdValue).appendChild(this.containerElement);
                } else {
                        document.getElementById(baseObjectIdValue).firstChild.rows(1).cells(1).appendChild(this.containerElement);
                }
            } else {
                if (parseInt(this.isRel) == 0) {
                    document.body.appendChild(this.containerElement);
                } else {
                    document.body.appendChild(this.containerElement);
                }
            }
            this.elementBaseOnLoad();
//            this.containerElement.onload = this.elementBaseOnLoad();
        } else {
            delete compRoot.instanceArray[this.idValue];
            return;
        }
    }

    this.initRenderComp = function() {
        if (parseInt(this.isRel) == 0) {
            this.containerElement.style.position = "absolute";
            this.containerElement.style.pixelTop = (top != null) ? top : this.constructor.compArray[idValue].top;
            this.containerElement.style.pixelLeft = (left != null) ? left : this.constructor.compArray[idValue].left;
//            this.containerElement.style.top = (top != null) ? top : this.constructor.compArray[idValue].top+"px";
//            this.containerElement.style.left = (left != null) ? left : this.constructor.compArray[idValue].left+"px";
            this.containerElement.style.zIndex = this.constructor.compGlobalZindex + parseInt(this.constructor.compArray[idValue].zDelta);
        } else {
            this.containerElement.style.position = "relative";
//                     this.containerElement.style.top = this.constructor.compArray[idValue].top;
//                     this.containerElement.style.left = this.constructor.compArray[idValue].left;
//            this.containerElement.style.zIndex = this.constructor.compGlobalZindex + parseInt(this.constructor.compArray[idValue].zDelta);
        }

        if (!(isChild)) this.containerElement.iscomp = "_youcradComp";
        this.renderBaseHtml();
    }

    this.destroyComp = function() {

        var childSpanNodes = this.containerElement.getElementsByTagName('SPAN');

        if (((baseObjectIdValue=="body")?(true):(document.getElementById(baseObjectIdValue))) && (document.getElementById(this.idValue) != null)) {
            if ((parseInt(this.isRel) == 0)) {
                ((baseObjectIdValue=="body")?(document.body):document.getElementById(baseObjectIdValue)).removeChild(this.containerElement);
            } else if (baseObjectIdValue!="_youcradTitle"){
                ((baseObjectIdValue=="body")?(document.body):document.getElementById(baseObjectIdValue)).firstChild.rows(1).cells(1).removeChild(this.containerElement);
            } else {
                document.getElementById(baseObjectIdValue).removeChild(this.containerElement);
            }
        }

        for (var i = 0; i < childSpanNodes.length; i++) {
            if ((childSpanNodes[i].id.lastIndexOf("@" + this.idValue) > -1) && (childSpanNodes[i].id.lastIndexOf("@" + this.idValue) == (childSpanNodes[i].id.length - this.idValue.length - 1)))
                delete compRoot.instanceArray[childSpanNodes[i].id];
        }

        delete compRoot.instanceArray[this.idValue];
    }

    this.hideComp = function() {
        this.containerElement.style.visibility = "hidden";
    }

    this.showComp = function(left, top) {
    if (left != null) this.containerElement.style.left = left;
    if (top != null) this.containerElement.style.top = top;
        this.containerElement.style.visibility = "visible";
    }

    //// SHOULD TARGET MAIN COMPONENT !!!!!!!!!!! /.//////////////////////////////////////////
   this.redrawComp = function(){
      var childSpanNodes = this.containerElement.getElementsByTagName("SPAN");
      ///// set parameter Oj for recall the component for non-fixed component
      if (this.isFixed < 1) {
         this.queryString = compRoot.buildParamSub(this.idValue).queryString;
         this.returnValue = compRoot.buildParamSub(this.idValue).returnValue;
         this.paramNum = compRoot.buildParamSub(this.idValue).paramNum;
         this.renderBaseHtml();
      } else {   
            if (this.isChild) {
                  this.renderBaseHtml();
            } else {
               for (var i = 0; i < childSpanNodes.length ; i++){
                  if ( (childSpanNodes[i].id.lastIndexOf("@" + this.idValue) > -1) && (childSpanNodes[i].id.lastIndexOf("@" + this.idValue) == ( childSpanNodes[i].id.length - this.idValue.length - 1))){ 
    //               if (compRoot.instanceArray[childSpanNodes[i].id].isFixed < 1) {
                        compRoot.instanceArray[childSpanNodes[i].id].addParams = this.addParams;
                        compRoot.instanceArray[childSpanNodes[i].id].queryString = compRoot.buildParamSub(this.idValue).queryString;
                        compRoot.instanceArray[childSpanNodes[i].id].returnValue = compRoot.buildParamSub(this.idValue).returnValue;
                        compRoot.instanceArray[childSpanNodes[i].id].paramNum = compRoot.buildParamSub(this.idValue).paramNum;
                        compRoot.instanceArray[childSpanNodes[i].id].renderBaseHtml();
//                        compRoot.instanceArray[childSpanNodes[i].id].initRenderComp();
    //               }
                  }
               }
            } 
      }
//      alert(this.idValue);
//      this.elementBaseOnLoad();
   }


    this.renderBaseHtml = function() {

        var content = "";

        if (compRoot.compHtmlArray[compRoot.compArray[idValue].html].isFixed != '1') {

            if (this.serverCallHit > this.callAbove - 1) {
                compRoot.compCall(this.addParams, parseInt(compRoot.compArray[idValue].pSize), parseInt(this.targetPageNumber), this.idValue, compRoot.compArray[idValue].html, this.paramNum, this.queryString, this.returnValue, this.serverCallHit, this.instanceKey);
            } else {
                this.callback();
            }

            this.serverCallHit += 1;

      } else { //////// For Fixed HTML components 
         
          this.pseudoQuery = compRoot.genPseudoQuery(this.addParams, parseInt(compRoot.compArray[idValue].pSize), parseInt(this.targetPageNumber), this.idValue, compRoot.compArray[idValue].html, this.paramNum, this.queryString, this.returnValue, this.serverCallHit, this.instanceKey);
         
         if (compRoot.compHtmlArray[compRoot.compArray[idValue].html].body.lastIndexOf(compRoot.repPseudoString) > -1)
               var pageBand2 = compRoot.ojPageBand2Fixed(this.pseudoQuery);

		 content = compRoot.compHtmlArray[compRoot.compArray[idValue].html].body

         if ((this.idValue.lastIndexOf("@") > -1)){
            content = content.replace(eval("/" + compRoot.repCharMain + "/g"), this.idValue.substring(this.idValue.lastIndexOf("@") + 1));
         } else {
            content = content.replace(eval("/" + compRoot.repCharMain + "/g"), this.idValue);
         }
         
         content = content.replace(eval("/" + compRoot.repCharSub + "/g"), this.idValue);

         content = compRoot.paramStringReplace(content, this.addParams);

         content = content.replace(eval("/" + compRoot.repPseudoString + "/g"), this.pseudoQuery);
         
         if (compRoot.compHtmlArray[compRoot.compArray[idValue].html].body.lastIndexOf(compRoot.repPseudoString) > -1)
               content = content.replace(eval("/"+compRoot.repCharPageBand2+"/g"), pageBand2);

    	content = compRoot.paramStringReplace(content, this.addParams);
         content = compRoot.fixedStringReplace(content);
        
         this.containerElement.innerHTML =  content;
         
            if ((this.containerElement.firstChild) && (this.containerElement.firstChild.tagName == "TABLE")) {
                this.containerElement.firstChild.style.height = (parseInt(compRoot.compArray[idValue].width) > 0) && (parseInt(compRoot.compArray[idValue].height) == 0) ? compRoot.compArray[idValue].height + 1 + "px" : compRoot.compArray[idValue].height + "px";
                if ((parseInt(compRoot.compArray[idValue].width) > 0)) this.containerElement.firstChild.style.width = compRoot.compArray[idValue].width;

//                if ((this.containerElement.style.position == "absolute") && (parseInt(compRoot.compArray[idValue].left) < 0)) 
//                    this.containerElement.style.pixelLeft = (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientWidth + parseInt(compRoot.compArray[idValue].left);
                if ((this.containerElement.style.position == "absolute") && (parseInt(compRoot.compArray[idValue].left) < 0)) 
                    if ((this.idValue==compRoot.baseMinComp)||(this.idValue==compRoot.baseMaxComp)||(this.idValue==compRoot.baseMinMinComp)||(this.idValue==compRoot.requestJoinPop0)||(this.idValue==compRoot.requestJoinPop1)||(this.idValue==compRoot.requestJoinPop2)||(this.idValue==compRoot.requestJoinPop3)||(this.idValue==compRoot.requestJoinPop4)) {
                        this.containerElement.style.pixelLeft = (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientWidth + parseInt(compRoot.compArray[idValue].left);                    
                    } else {
                        this.containerElement.style.pixelLeft = (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollWidth + parseInt(compRoot.compArray[idValue].left);                    
                    }
                if ((this.containerElement.style.position == "absolute") && (parseInt(compRoot.compArray[idValue].top) < 0))
                    this.containerElement.style.pixelTop = (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop - parseInt(compRoot.compArray[idValue].top);

            }
            compRoot.funcAssign(idValue);
        }
        //      if (compRoot.compHtmlArray[compRoot.compArray[idValue].html].isFixed != '1') this.elementOj = compRoot.buildParam(this.idValue);
    }
    //_____ Put any process should be done on creation of the instances _____//   
    this.initComp();
}

//_____ shared functions for the instances _____//
compRoot.addScript = function(targetUrl, callbackFunction) {
    var headId = document.getElementsByTagName("head")[0];
    var newScript = document.createElement("script");
    newScript.type = "text/javascript";
//    newScript.src = targetUrl + '&authedId=' + compRoot.authedId + '&callbackFunction=' + callbackFunction + '&partnerEncoding=' + document.charset + '&partnerArticleId=' + compRoot.articleId + '&partnerId=' + compRoot.partnerId + '&partnerUserId=' + encodeURIComponent(compRoot.partnerUserId) + '&authorId=' + encodeURIComponent(compRoot.authorPartnerUserId) + "&searchOption=" + compRoot.searchOptionType + "&claimStatus=" + compRoot.claimStatusChecked + '&boardId=' + compRoot.boardId + '&agreedYN=' + compRoot.agreedYN + '&authorAgreedYN=' + compRoot.authorAgreedYN + '&enabledYN=' + compRoot.enabledYN;
    
    newScript.src = targetUrl + '&authedId=' + compRoot.authedId + '&callbackFunction=' + callbackFunction + '&partnerEncoding=' + document.charset + '&partnerArticleId=' + compRoot.articleId + '&partnerId=' + compRoot.partnerId + '&partnerUserId=' + encodeURIComponent(compRoot.partnerUserId) + '&authorId=' + encodeURIComponent(compRoot.authorPartnerUserId) + "&searchOption=" + compRoot.searchOptionType + "&claimStatus=" + compRoot.claimStatusChecked + '&timeMark=' + compRoot.callTimeMark.valueOf()  + "&markInstLimit=" + compRoot.markInstLimit+ "&spaceInstLimit=" + compRoot.spaceInstLimit + '&boardId=' + compRoot.boardId + '&agreedYN=' + compRoot.agreedYN + '&authorAgreedYN=' + compRoot.authorAgreedYN + '&enabledYN=' + compRoot.enabledYN;

    newScript.defer = true;
//    KYJ TBD
    if (targetUrl != compRoot.targetUrl+"/temp/compHtmlString4.js?") {
//        window.open(newScript.src); 
    }
    window.setTimeout(function(){ headId.appendChild(newScript);},1);
}

compRoot.importScript = function(targetUrl) {
    var headId = document.getElementsByTagName("head")[0];
    var newScript = document.createElement("script");
    newScript.type = "text/javascript";
    newScript.src = targetUrl;
    newScript.defer = true;
//    window.open(targetUrl);
//    alert(targetUrl);
    window.setTimeout(function(){ headId.appendChild(newScript);},1);
}

compRoot.importScriptTrigger = function(targetUrl, funcObj) {

    if (((compRoot.partnerId=="dctest")||((typeof $ == "function")&&(typeof Prototype != "undefined")))&&(targetUrl==prototypeUrl)) {
        funcObj();
    } else {
        var headId = document.getElementsByTagName("head")[0];
        var newScript = document.createElement("script");
        newScript.type = "text/javascript";
        newScript.src = targetUrl;
        newScript.onreadystatechange= function () { // for IE 
      if ((prototypeLoadCount==0)&&(this.readyState == 'complete')) { if (targetUrl==prototypeUrl) prototypeLoadCount++; funcObj();}
      if ((prototypeLoadCount==0)&&(this.readyState == 'loaded')) { if (targetUrl==prototypeUrl) prototypeLoadCount++; funcObj();}
     }
//    newScript.onload = funcObj; // for other browser
        headId.appendChild(newScript);
    }
}

compRoot.addCSSLink = function(targetUrl) {
    var headId = document.getElementsByTagName("head")[0];
    var newCSS = document.createElement("link");
    newCSS.type = "text/css";
    newCSS.rel = "stylesheet";
    newCSS.href = targetUrl;
    headId.appendChild(newCSS);
    return true;
}

compRoot.funcAssign = function(idValue) {
    for (var func in compRoot.funcArray) {
        if (compRoot.funcArray[func].comp == idValue) {

		if (!(document.getElementById(compRoot.funcArray[func].ele))) return;

            if (compRoot.funcArray[func].onclick)
                document.getElementById(compRoot.funcArray[func].ele).onclick = compRoot.funcArray[func].onclick;
            if (compRoot.funcArray[func].onmousedown)
                document.getElementById(compRoot.funcArray[func].ele).onmousedown = compRoot.funcArray[func].onmousedown;
            if (compRoot.funcArray[func].onmouseover)
                document.getElementById(compRoot.funcArray[func].ele).onmouseover = compRoot.funcArray[func].onmouseover;
            if (compRoot.funcArray[func].onkeydown)
                document.getElementById(compRoot.funcArray[func].ele).onkeydown = compRoot.funcArray[func].onkeydown;
            if (compRoot.funcArray[func].onkeyup)
                document.getElementById(compRoot.funcArray[func].ele).onkeyup = compRoot.funcArray[func].onkeyup;
            if (compRoot.funcArray[func].onload)
                document.getElementById(compRoot.funcArray[func].ele).onload = compRoot.funcArray[func].onload;
            if (compRoot.funcArray[func].onselect)
                document.getElementById(compRoot.funcArray[func].ele).onselect = compRoot.funcArray[func].onselect;
            if (compRoot.funcArray[func].onchange) {
                document.getElementById(compRoot.funcArray[func].ele).onchange = compRoot.funcArray[func].onchange;
                document.getElementById(compRoot.funcArray[func].ele).onblur = compRoot.funcArray[func].onchange;
            }
            if (compRoot.funcArray[func].onpaste)
                document.getElementById(compRoot.funcArray[func].ele).onpaste = compRoot.funcArray[func].onpaste;

            if (compRoot.funcArray[func].onblur)
                document.getElementById(compRoot.funcArray[func].ele).onblur = compRoot.funcArray[func].onblur;
            if (compRoot.funcArray[func].onfocus)
                document.getElementById(compRoot.funcArray[func].ele).onfocus = compRoot.funcArray[func].onfocus;
                
            if ((document.getElementById(compRoot.funcArray[func].ele).type == "text") || (document.getElementById(compRoot.funcArray[func].ele).type == "password") || (document.getElementById(compRoot.funcArray[func].ele).tagName == "TEXTAREA")) {
                if (document.getElementById(compRoot.funcArray[func].ele).name == "_youcrad_formControl"){
                        if (compRoot.funcArray[func].onfocus) {

                        } else {
                            document.getElementById(compRoot.funcArray[func].ele).onfocus = function() { 
                                compRoot.errorElement.style.visibility = "hidden";
                                compRoot.onFocusHighlight(this.id); 
                                if (this.errorString){
                                    compRoot.errorElement.innerHTML = this.errorString;
                                    compRoot.errorElement.style.left = (compRoot.getPosition(this).x - 170) +"px";
	                                compRoot.errorElement.style.top = (compRoot.getPosition(this).y - 45) +"px";
	                                compRoot.errorElement.style.visibility = "visible";
	                            }
                            }
                        }
                   }
                
                document.getElementById(compRoot.funcArray[func].ele).onclick = function() { 
                    eval(compRoot.funcArray[func].onclick); 
                    compRoot.clearDefault(this); 
                };
                
                document.getElementById(compRoot.funcArray[func].ele).onchange = function() { 
                    eval(compRoot.funcArray[func].onchange); 
                    compRoot.returnDefault(this); 
                };
            }
        }
    }
}

compRoot.fixedStringReplace = function(theString) {
    var rxp = new RegExp("([\(]{3})([_a-zA-Z0-9\.])+([\)]{3})", "g");
   var theString = theString 
//    var rxp = new RegExp("([\(]{3})([_a-zA-Z0-9.=!':&\(\)\s\?-]+)([\)]{3})", "g");
//    var rxp = new RegExp("([\(]{3})[.]*([\)]{3})", "g");
    var returnValue = theString;
    var matchedArray = theString.match(rxp);
    var temptemp = "";
   
    if (matchedArray) {
        for (var i = 0; i < matchedArray.length; i++) {
            returnValue = returnValue.replace(matchedArray[i], eval(matchedArray[i].replace("(((", "").replace(")))", "")));
        }
    }
   
   theString = returnValue;
   
   /// for Hangeul extract : [\x{3131}-\x{318E}]|[\x{AC00}-\x{D7A3}]
   var thePattern = /([\{]{3})([_a-zA-Z가-힣0-9,`~!@#\$%\|\^&\[\]\<\>\/\\\*\+=\-\'\"\.\s\?:\(\)]+)([\}]{3})/g;
   rxp = new RegExp(thePattern);
//    var rxp = new RegExp("([\(]{3})[.]*([\)]{3})", "g");
//    var returnValue = theString;
    matchedArray = theString.match(rxp);
    temptemp = "";
   
    if (matchedArray) {
        for (var i = 0; i < matchedArray.length; i++) {
//            alert(matchedArray[i]);
            temptemp = eval(matchedArray[i].replace("{{{", "").replace("}}}", ""));
            returnValue = returnValue.replace(matchedArray[i], temptemp);
        }
    }

    return returnValue;
}

compRoot.paramStringReplace = function(theString, paramString) {
	var rxp = new RegExp("([\<]{3})([_a-zA-Z0-9\.])+([\>]{3})", "g");
	var returnValue = theString;
	var matchedArray = theString.match(rxp);

	if (matchedArray) {
		for (var i = 0; i < matchedArray.length; i++) {
			returnValue = returnValue.replace(matchedArray[i], compRoot.getStringParamValue(paramString, matchedArray[i].replace("<<<", "").replace(">>>", "")));
		}
	}

	return returnValue;
}

compRoot.ojPageBand = function(oj) {

    if (oj) {
        var pageSize = parseInt(oj.res._pageSize);
        var pageNumber = parseInt(oj.res._pageNumber);
        var startPageNumber = 2;
        var totalPageCount = parseInt(oj.res._totalPageCount);
        var totalRecordCount = parseInt(oj.res._totalRecordCount);
        var pageMaxDisplay = (parseInt(compRoot.instanceArray[oj.req.compName].bSize)) ? parseInt(compRoot.instanceArray[oj.req.compName].bSize) : parseInt(compRoot.pageBandSizeDefault);
	   var prevMark = "<img src=\"" +compRoot.imageUrlBase+ "images/p_arrows_left.gif\" align=\"absmiddle\" border=\"0\" >";
	   var nextMark = "<img src=\"" +compRoot.imageUrlBase+ "images/p_arrows_right.gif\" align=\"absmiddle\" border=\"0\" >";
	   var BreakChar = "<img src=\"" +compRoot.imageUrlBase+ "images/p_icon_bar.gif\" align=\"absmiddle\"> ";
        var pageBandString = "";
        var SpaceChar = "<span>...</span> ";
        var prevPageNumber = (pageNumber > 1) ? parseInt(pageNumber - 1) : parseInt(pageNumber);
        var nextPageNumber = (pageNumber < totalPageCount) ? parseInt(pageNumber + 1) : parseInt(pageNumber);

        if (totalPageCount > pageMaxDisplay + 1) {

            pageBandString += compRoot.ojRedrawCompLink(oj.req.compName, prevPageNumber, prevMark, -1);
            pageBandString += compRoot.ojRedrawCompLink(oj.req.compName, 1, 1, pageNumber);

            if (pageNumber - Math.floor(pageMaxDisplay / 2) < Math.floor(pageMaxDisplay / 2) + 1) {
                startPageNumber = 2;
                pageBandString += BreakChar;
            } else if (pageNumber + Math.floor(pageMaxDisplay / 2) > totalPageCount - Math.floor(pageMaxDisplay / 2)) {
                startPageNumber = totalPageCount - (pageMaxDisplay);
                pageBandString += SpaceChar;
            } else {
                startPageNumber = pageNumber - Math.floor(pageMaxDisplay / 2);
                pageBandString += SpaceChar;
            }

            for (var i = startPageNumber; i < startPageNumber + (pageMaxDisplay); i++) {
                pageBandString += compRoot.ojRedrawCompLink(oj.req.compName, i, i, pageNumber);
                pageBandString += (i < startPageNumber + (pageMaxDisplay - 1)) ? BreakChar : "";
            }

            pageBandString += SpaceChar;

            pageBandString += compRoot.ojRedrawCompLink(oj.req.compName, totalPageCount, totalPageCount, pageNumber);
            pageBandString += compRoot.ojRedrawCompLink(oj.req.compName, nextPageNumber, nextMark, -1);

        } else if (totalPageCount > 1) {

            pageBandString += compRoot.ojRedrawCompLink(oj.req.compName, prevPageNumber, prevMark, -1);
            pageBandString += compRoot.ojRedrawCompLink(oj.req.compName, 1, 1, pageNumber);
            pageBandString += BreakChar;

            for (var i = startPageNumber; i < totalPageCount + 1; i++) {
                pageBandString += compRoot.ojRedrawCompLink(oj.req.compName, i, i, pageNumber);
                pageBandString += (i < totalPageCount) ? BreakChar : "";
            }
        } else if (totalPageCount > 0) {
            pageBandString += compRoot.ojRedrawCompLink(oj.req.compName, 1, '1', 1);
        }

    }
    return pageBandString;
}

compRoot.ojPageBand2 = function(oj) {
    if (oj) {
// oj.req.compName
// oj.req.chartType
// oj.req.endDate
// oj.res._prevEndDate
// oj.res._nextEndDate
// oj.req.bridgeName
// oj.req.dateUnit
//  "&chartType=column&startDate=20090101&endDate=" + compRoot.todayString + "&dateUnit=day&bridgeName=statChart" 

      var prevParams = "&chartType="+ oj.req.chartType +"&startDate=20090101&endDate=" + oj.res._prevEndDate + "&dateUnit="+oj.req.dateUnit+"&bridgeName=" + oj.req.bridgeName ;
      var nextParams = "&chartType="+ oj.req.chartType +"&startDate=20090101&endDate=" + oj.res._nextEndDate + "&dateUnit="+oj.req.dateUnit+"&bridgeName=" + oj.req.bridgeName ; 
 	   var prevMark = "<img src=\"" +compRoot.imageUrlBase+ "images/arrows_left_off.gif\" align=\"absmiddle\" border=\"0\" onmouseover=\"this.src='' + compRoot.imageUrlBase+ 'images/arrows_left_on.gif'\" onmouseout=\"this.src='' + compRoot.imageUrlBase+ 'images/arrows_left_off.gif'\">";
	   var nextMark = "<img src=\"" +compRoot.imageUrlBase+ "images/arrows_right_off.gif\" align=\"absmiddle\" border=\"0\" onmouseover=\"this.src='' + compRoot.imageUrlBase+ 'images/arrows_right_on.gif'\" onmouseout=\"this.src='' + compRoot.imageUrlBase+ 'images/arrows_right_off.gif'\">";
	   var linkString = "";
	   linkString += "<a href=\"javascript:compRoot.compRedraw('"+ oj.req.compName + "','"+ prevParams+"');\" >"+ prevMark + "</a> ";
	   linkString += stringLeft(oj.req.endDate,4) + "/" + stringLeft(stringRight(oj.req.endDate,4),2) + "/" + stringRight(stringRight(oj.req.endDate,4),2);
	   linkString += " <a href=\"javascript:compRoot.compRedraw('"+ oj.req.compName + "','"+ nextParams+"');\" >"+ nextMark + "</a>";
	   
	   return linkString;
   }
} 

compRoot.getWeekDiff = function(dateString, diff, type){
   var y = parseInt(stringLeft(dateString,4),10);
   var m = parseInt(stringLeft(stringRight(dateString,4),2),10);
   var d = parseInt(stringRight(stringRight(dateString,4),2),10);
   var theDate = new Date();
   var targetDate = new Date();
   var factor = (type == "day")? 1:5;
   
   theDate.setFullYear(y);
   theDate.setMonth(m-1);
   theDate.setDate(d);

   targetDate.setTime( Date.parse(theDate.toDateString()) +  (7 * (diff) * (factor)* 86400000));

   d = make2Places(targetDate.getDate());
   m = make2Places(targetDate.getMonth()+1);
   y = targetDate.getFullYear().toString();

   return (y + m + d);
}

compRoot.ojPageBand2Fixed = function(oj) {
    if (oj) {
// oj.req.compNamez
// oj.req.chartType
// oj.req.endDate
// oj.res._prevEndDate
// oj.res._nextEndDate
// oj.req.bridgeName
// oj.req.dateUnit
//  "&chartType=column&startDate=20090101&endDate=" + compRoot.todayString + "&dateUnit=day&bridgeName=statChart" 
//compRoot.getStringParamValue = function(theString, paramName) {
/*
   var datestring = new Date();
   datestring.setFullYear(2009);
   datestring.setMonth(04);
   datestring.setDate(23);
   datestring.setTime(Date.parse(datestring.toDateString()) + 7*86400000 );
   alert(Date.parse(datestring.toDateString()))
   alert(datestring.toDateString());
*/

   var chartType = compRoot.getStringParamValue(oj, "chartType");
   var dateUnit = compRoot.getStringParamValue(oj, "dateUnit");
   var compName = compRoot.getStringParamValue(oj, "compName");
   var endDate = compRoot.getStringParamValue(oj, "endDate");   
   var compName = compRoot.getStringParamValue(oj, "compName");   
   var bridgeName = compRoot.getStringParamValue(oj, "bridgeName"); 
   var prevEndDate = compRoot.getWeekDiff(endDate, -1, dateUnit);  
   var nextEndDate = compRoot.getWeekDiff(endDate, 1, dateUnit);   
   
   var prevParams = "&chartType="+ chartType +"&startDate=20090101&endDate=" + prevEndDate + "&dateUnit="+dateUnit+"&bridgeName=" + bridgeName ;
   var nextParams = "&chartType="+ chartType +"&startDate=20090101&endDate=" + nextEndDate + "&dateUnit="+dateUnit+"&bridgeName=" + bridgeName ; 
   var prevMark = "<img src=\"" +compRoot.imageUrlBase+ "images/arrows_left_off.gif\" align=\"absmiddle\" border=\"0\" onmouseover=\"this.src='' + compRoot.imageUrlBase+ 'images/arrows_left_on.gif'\" onmouseout=\"this.src='' + compRoot.imageUrlBase+ 'images/arrows_left_off.gif'\">";
   var nextMark = "<img src=\"" +compRoot.imageUrlBase+ "images/arrows_right_off.gif\" align=\"absmiddle\" border=\"0\" onmouseover=\"this.src='' + compRoot.imageUrlBase+ 'images/arrows_right_on.gif'\" onmouseout=\"this.src='' + compRoot.imageUrlBase+ 'images/arrows_right_off.gif'\">";
   var linkString = "";
   linkString += "<a href=\"javascript:compRoot.compRedraw('"+ compName + "','"+ prevParams+"');\" >"+ prevMark + "</a> ";
   linkString += stringLeft(endDate,4) + "/" + stringLeft(stringRight(endDate,4),2) + "/" + stringRight(stringRight(endDate,4),2);
   linkString += " <a href=\"javascript:compRoot.compRedraw('"+ compName + "','"+ nextParams+"');\" >"+ nextMark + "</a>";
	   
	   return linkString;
   }
} 

compRoot.ojRedrawComp = function(compName, targetPage) {
    compRoot.instanceArray[compName].targetPageNumber = parseInt(targetPage);
    compRoot.instanceArray[compName].redrawComp();
}

compRoot.compPageMove = function(compName, direction){
   var targetPageNumber = parseInt(compRoot.instanceArray[compName].targetPageNumber) + ((direction=="+")?(1):(-1));
   targetPageNumber = (targetPageNumber > (parseInt(compRoot.instanceArray[compName].totalPageCount)))?(parseInt(compRoot.instanceArray[compName].totalPageCount)):(targetPageNumber);
   targetPageNumber = (targetPageNumber < 1)?(1):(targetPageNumber);
   compRoot.instanceArray[compName].targetPageNumber = targetPageNumber;
   compRoot.instanceArray[compName].redrawComp();
}

compRoot.compRedraw = function(compName, addParams) {
    if (compRoot.instanceArray[compName] == null) {
        compRoot.compReplace(compName, addParams);
    } else {
        if (addParams != null) compRoot.instanceArray[compName].addParams = addParams;
//        alert(compRoot.instanceArray[compName].addParams);
        compRoot.instanceArray[compName].redrawComp();
    }
}

compRoot.ojRedrawCompLink = function(compName, targetPage, DisplayStr, currentPage) {

    var linkString = "";

    if (parseInt(currentPage) == parseInt(targetPage)) {
        DisplayStr = "<font style=\"font-size:12px\"><b>" + DisplayStr + "</b></font>";
    }

    linkString += "<a href=\"javascript:compRoot.ojRedrawComp('" + compName + "'," + targetPage + ");\" class=\"ucr_link4\">" + DisplayStr + "</a> ";

    return linkString;
}

compRoot.ojRootReplace = function(theString, oj) {
    var rxp = new RegExp("([\[]{3})([a-zA-Z0-9\_])+([\]]{3})", "g");
    var returnValue = theString;
    var matchedArray = theString.match(rxp);

    if (matchedArray) {
        for (var i = 0; i < matchedArray.length; i++) {
            if (oj) {
//                returnValue = returnValue.replace(matchedArray[i], (oj.res[matchedArray[i].replace("[[[", "").replace("]]]", "")]) ? (oj.res[matchedArray[i].replace("[[[", "").replace("]]]", "")]) : "");
                returnValue = returnValue.replace(matchedArray[i], (oj.res[matchedArray[i].replace("[[[", "").replace("]]]", "")]!=null) ? (oj.res[matchedArray[i].replace("[[[", "").replace("]]]", "")]) : matchedArray[i]);
            } else {
                returnValue = returnValue.replace(matchedArray[i], "");
            }
        }
    }

    return returnValue;
}

compRoot.ojContentsReplace = function(theString, oj, callAbove) {
    var rxp = new RegExp("([\[]{3})([a-zA-Z0-9\_])+([\]]{3})", "g");
    // As the search context contains the "_" character, this should be revised by including "\_"
    var returnValue = "";
    var blockValue = "";
    var matchedArray = theString.match(rxp);
    var i, j;

    //   for (var i = 0 ; i < ((oj.res.contents.length != 0) ? oj.res.contents.length : callAbove) ; i++){
    for (var i = 0; i < oj.res.contents.length; i++) {
        blockValue = theString;
        if (matchedArray)
            for (j = 0; j < matchedArray.length; j++) {

            if (oj.res.contents.length != 0) {
                blockValue = blockValue.replace(matchedArray[j], oj.res.contents[i][matchedArray[j].replace("[[[", "").replace("]]]", "")]);
            } else {
                blockValue = blockValue.replace(matchedArray[j], "");
            }
        }
        returnValue += blockValue;
    }
    return returnValue;
}

compRoot.ojContentsReplaceGeneral = function(theString, ojArray) {
    var rxp = new RegExp("([\[]{3})([a-zA-Z0-9\_])+([\]]{3})", "g");
    // As the search context contains the "_" character, this should be revised by including "\_"
    var returnValue = "";
    var blockValue = "";
    var matchedArray = theString.match(rxp);
    var i, j;

    //   for (var i = 0 ; i < ((oj.res.contents.length != 0) ? oj.res.contents.length : callAbove) ; i++){
    for (var i = 0; i < ojArray.length; i++) {
        blockValue = theString;
        if (matchedArray)
            for (j = 0; j < matchedArray.length; j++) {

            if (ojArray.length != 0) {
                blockValue = blockValue.replace(matchedArray[j], ojArray[i][matchedArray[j].replace("[[[", "").replace("]]]", "")]);
            } else {
                blockValue = blockValue.replace(matchedArray[j], "");
            }
        }
        returnValue += blockValue;
    }
    return returnValue;
}

compRoot.compInstanceInitialize = function() {

    if ((compRoot.articleId!="")&&(compRoot.articleId!=null)&&(compRoot.getArticleElement())) {
       
         var specificCompNo = (parseInt(document.URL.substring(document.URL.lastIndexOf("?") + 1)) != NaN) ? (parseInt(document.URL.substring(document.URL.lastIndexOf("?") + 1)) / compRoot.theFactor) : -1.01;

         for (var comp in compRoot.compArray) {
            if ((comp != compRoot.initializeComp) && (compRoot.compArray[comp].isInitComp == "1") && (comp != compRoot.homeComp)) {
            compRoot.compCreate(comp);
            }
         }

      if ((specificCompNo != parseInt(compRoot.initializeComp)) && (Math.floor(specificCompNo) == specificCompNo)) {   //maybe need to specify the components list acceptable here .....
        if (compRoot.compArray[specificCompNo] && (compRoot.compArray[specificCompNo].pComp == "0") && (compRoot.compArray[specificCompNo].isInitComp != "1"))
            var pseudoFunc = setTimeout("compRoot.compReplace(\"" + specificCompNo + "\")", 0);
            pseudoFunc = null;
         } else {
        //////////// go Home process here /////////////////////
		      if (compRoot.targetComp != "") {
		         compRoot.compReplace(compRoot.targetComp);
		      } else {
		         compRoot.goHome();
		      }
//		   alert("You are At Home");
         }
         

      //////////// Partner Page Initialization ////////////////////////////////
//      if ( (compRoot.useFixedWidget==1)&&(compRoot.getTitleElement())&&youcrad_readCookie("hideWidget")&&(youcrad_readCookie("hideWidget")=="YES")){
      if (compRoot.compInitMode==1) {
          if ( (compRoot.useFixedWidget==1) && (compRoot.getTitleElement() ) ){
            compRoot.compCreate(compRoot.baseBottomComp);
          } else {
            /// force fixedWidgetMode to false
            compRoot.useFixedWidget = 0;
            
            if (youcrad_readCookie("hideWidget")&&(youcrad_readCookie("hideWidget")=="YES")){
                compRoot.compCreate(compRoot.baseMinMinComp);
            } else {
                compRoot.compCreate(compRoot.baseMinComp);
                compRoot.currentWidgetObject = document.getElementById(compRoot.baseMinComp);
	            compRoot.setWidgetYPositionCurrent(0);
	        }
          }     
      }
       if (compRoot.doSpanningDOM(compRoot.articleElement)) { // doSpanning leads adsLoading process
        compRoot.partnerInitialize();
      }
  }
  
    compRoot.errorElement = document.createElement("DIV");
    compRoot.errorElement.className = "youcrad_inputalertbox";
    document.body.appendChild(compRoot.errorElement);
    //////////// Partner Page Initialization ////////////////////////////////
}

compRoot.partnerInitialize = function(e) {

	document.onmouseup = function(e){
	    if (compRoot.mouseMovePartner != null) compRoot.mouseMovePartner(e);
	    compRoot.mouseUp(e);
    }
    
	compRoot.dragMark = document.getElementById(compRoot.dragMarkComp);
	compRoot.dragMark.oops = "";

	compRoot.selectedAdObjectId = "";
	compRoot.dragMark.innerHTML = "";
	compRoot.markInstAddRelease();
	compRoot.spaceInstAddRelease(compRoot.currentTargetSpaceId);
	compRoot.currentTargetSpaceId = "";
	compRoot.currentTargetMarkId = "";
	compRoot.currentTargetPlaceType = "";
	document.onmousemove = compRoot.mouseMovePartner;

	window.setTimeout("document.body.style.cursor = \"auto\";", 0);

	compRoot.markDisplay = document.getElementById(compRoot.markDisplayComp);
	compRoot.markDisplay.innerHTML = "";
	//    compRoot.compDestroy(compRoot.markInstListComp);

	compRoot.adsPlaceLoad();
	
   if ((compRoot.compInitMode==1)&&(compRoot.popupCase > -1)&&(compRoot.getArticleElement())) {
       if (youcrad_readCookie("popcase"+compRoot.popupCase)&&(youcrad_readCookie("popcase"+compRoot.popupCase)=="NOSHOW")) {
           return;
       } else {
           compRoot.compCreate(eval("compRoot.requestJoinPop"+compRoot.popupCase));
       }
    //        compRoot.alertMsg("Popup Case " + compRoot.popupCase);
   }	

	if (compRoot.needClaimPopup == 1) {
		if (document.getElementById("youcrad_showSearchWindow")) {
//////////////////  comment out for disable CLAIM Request Popup 
//		    document.getElementById("youcrad_showSearchWindow").click();
//		    setTimeout("compRoot.compCreate(\"429\");", 0);
		 }
    }

    if (compRoot.searchOptionType == "CAR") compRoot.setVehicleList();
  
//    var markSpans = compRoot.getElementsByClassName("youcradMarkSpan", "SPAN");
//    for (var i = 0; markSpans.length; i++) {
//        markSpans[i].onclick = function() { compRoot.createMarkOnSpan(this); };
//        markSpans[i].onmouseover = function() { compRoot.markOnMouseOver(this); };
//        markSpans[i].onmouseout = function() { compRoot.markOnMouseOut(this); };
//        //            markSpans[i].adplace = "adplace";
//    }

}

compRoot.setAuthor = function(oj) {
//alert(oj.res._claimPartnerUserId);
    if (oj.res._id != ""){
    
       if ((parseInt(compRoot.authStatus) != 1)&&(oj.res._claimStatus != null) && (parseInt(oj.res._claimStatus) >= 1) && (compRoot.authedId != "") && (compRoot.authorPartnerUserId == oj.res._claimPartnerUserId)) {
           compRoot.authStatus = 4;
   //        if (compRoot.authorPartnerUserId == oj.res._claimPartnerUserId) compRoot.authStatus = 4;
       }
       
       if (oj.res._id == compRoot.superUserId) compRoot.authStatus = 4;
       
   } else if (compRoot.partnerId == "test1"){
           compRoot.authStatus = 4;   
   } else if (compRoot.partnerUserId != "") {
        compRoot.authStatus =  ((compRoot.isPartnerUserAuthor > 0)?4:2);
//        compRoot.authedId = "";
   }
   
   compRoot.claimStatusChecked = (compRoot.partnerId == "test1")?1:(oj.res._claimStatus);
   compRoot.authorYoucradId = oj.res._authorYoucradId; // oj.res._claimYoucradId;
//   compRoot.claimPartnerUserId = oj.res._claimPartnerUserId;
   
   /// Check need for calim popup but not in use for accessibility
   compRoot.needClaimPopup = (compRoot.partnerId == "test1")?0:(((parseInt(compRoot.claimStatusChecked)==0)&&(parseInt(compRoot.isPartnerUserAuthor) == 1))?1:0);
   
   /// Reset Publish Mode based on the matrix, can be defined at the moment of distribution in the future (user-selectable mode later) __________________
   compRoot.resetPublishMode();
   
   /// Popup Management from here
   /// cookie name : popcase0, popcase2, popcase1, popcase3, popcase4
   
   var publishCount = oj.res._publishCount;
   var integStatus = parseInt(oj.res._claimStatus);
   
   if (compRoot.authStatus < 2){
            if (compRoot.partnerLogoPostfix!="_dc") compRoot.popupCase = 0;        
   } else if ((integStatus==0)&&(compRoot.authedId=="")) {
        if (publishCount > 0) {
            if (compRoot.partnerLogoPostfix!="_dc") popupCase = 1;        
        } else {
            if (compRoot.partnerLogoPostfix!="_dc") compRoot.popupCase = 2;        
        }
   } else if ((integStatus==0)&&(compRoot.authedId!="")) {
            if (compRoot.partnerLogoPostfix!="_dc") compRoot.popupCase = 3;         
   } else if (integStatus==1) {
            if (compRoot.partnerLogoPostfix!="_dc") compRoot.popupCase = 4;
   } 


   /// Popup Management until here
}

compRoot.setUserIdentity = function(oj){
    if ((oj.res._id)&&(oj.res._id != "")){ 
       compRoot.authedId = oj.res._id;
       compRoot.todayString = oj.res._today; 
       if ((oj.res._status)&&(oj.res._status=="-1")) compRoot.isUnderWright = "Y";    
       if (oj.res._status) compRoot.authStatus = Math.abs(parseInt(oj.res._status));
       if (oj.res._isSponsor) compRoot.sponsorFlag = parseInt(oj.res._isSponsor); 
   } else if ((compRoot.partnerId == "test0")||(compRoot.partnerId == "test1")) { // for guide pages
       compRoot.authedId = "hongkildong";
       compRoot.todayString = oj.res._today; 
//       if ((oj.res._status)&&(oj.res._status=="-1")) compRoot.isUnderWright = "Y";    
       compRoot.authStatus = 2;
//       if (oj.res._isSponsor) compRoot.sponsorFlag = parseInt(oj.res._isSponsor);    
   } else if (compRoot.partnerUserId != "") {
        compRoot.authStatus =  ((compRoot.isPartnerUserAuthor > 0)?4:2);
//        compRoot.authedId = "";
   }
   
   if ((oj.res._spEmail)&&(oj.res._spEmail != "")) {
      compRoot.spEmail = oj.res._spEmail;
      compRoot.spEmailId = compRoot.spEmail.split("@")[0];
      compRoot.spEmailDomain = compRoot.spEmail.split("@")[1];
   }
   
   if ((oj.res._target)&&(oj.res._target != "")) {
      compRoot.targetComp = oj.res._target;
  }

  if ((oj.res._searchOptionType) && (oj.res._searchOptionType != "")) {
      compRoot.searchOptionType = oj.res._searchOptionType;
  }
}

compRoot.getElementsByClassName = function(cl, tagName) {
      var retnode = new Array();
      if (tagName) {
         var elem = document.getElementsByTagName(tagName);
      } else {
         var elem = document.getElementsByTagName("*");      
      }
      for (var i = 0; i < elem.length; i++) {
         var classes = elem[i].className;
         if ((classes != null) && (classes != "") && (classes.indexOf(cl) == 0) && (classes.length == cl.length)) {
            retnode.push(elem[i]);
         }
      }
      return retnode;
}

//Get all the elements of the given classname of the given tag.
// "article entry-content"
compRoot.getArticleElement = function() {
   if (document.getElementById("SG_ArticleContent")) { // This is for 세계일보
        compRoot.articleElement = document.getElementById("SG_ArticleContent").getElementsByTagName("LI")[0];
//        compRoot.articleElement.id = "_youcradContent";
        compRoot.articleElement.adplace = "adplacebase";
        compRoot.articleElement.style.position = "relative";

        return true;
    } else if (((compRoot.domainString.split(".")[1] == "sportsseoul"))&&document.getElementById("content_area")) { // This is for 스포츠서울
        compRoot.articleElement = document.getElementById("content_area");
//        compRoot.articleElement.id = "_youcradContent";
        compRoot.articleElement.adplace = "adplacebase";
        compRoot.articleElement.style.position = "relative";

        return true;
    } else if ((((compRoot.domainString.split(".")[0] == "osen")||(compRoot.domainString.split(".")[0] == "nosen"))&&(compRoot.domainString.split(".")[1] == "mt"))&&(compRoot.getElementsByClassName("newsview_area", "DIV").length == 1)) { // This is for 오센
        compRoot.articleElement = compRoot.getElementsByClassName("newsview_area", "DIV")[0];
        compRoot.articleElement.id = "_youcradContent";
        compRoot.articleElement.adplace = "adplacebase";
        compRoot.articleElement.style.position = "relative";

        return true;
    } else if ((((compRoot.domainString.split(".")[0] == "star")||(compRoot.domainString.split(".")[0] == "nstar"))&&(compRoot.domainString.split(".")[1] == "mt"))&&document.getElementById("article")) { // This is for 스타뉴스
        compRoot.articleElement = document.getElementById("article");
//        compRoot.articleElement.id = "_youcradContent";
        compRoot.articleElement.adplace = "adplacebase";
        compRoot.articleElement.style.position = "relative";

        return true;
    } else if (((compRoot.domainString.split(".")[0] == "donga")||(compRoot.domainString.split(".")[1] == "donga"))&&document.getElementById("CONTENT")) { // This is for 동아닷컴
        compRoot.articleElement = document.getElementById("CONTENT");
//        compRoot.articleElement.id = "_youcradContent";
        compRoot.articleElement.adplace = "adplacebase";
        compRoot.articleElement.style.position = "relative";

        return true;
    } else  if (compRoot.getElementsByClassName("contentBody", "DIV").length == 1) {
        var articleElement = compRoot.getElementsByClassName("contentBody", "DIV")[0];
        articleElement.id = "_youcradContent";

        compRoot.articleElement = document.getElementById("_youcradContent");
        compRoot.articleElement.adplace = "adplacebase";
        compRoot.articleElement.style.position = "relative";

        return true;
    } else if (compRoot.getElementsByClassName("article entry-content", "DIV").length == 1) { // This is for TEXTCUBE specific requirements
        var articleElement = compRoot.getElementsByClassName("article entry-content", "DIV")[0];
        articleElement.id = "_youcradContent";

        compRoot.articleElement = document.getElementById("_youcradContent");
        compRoot.articleElement.adplace = "adplacebase";
        compRoot.articleElement.style.position = "relative";

        return true;
    } else if (compRoot.getElementsByClassName("article_post", "DIV").length == 1) { // This is for TISTORY inayou
        var articleElement = compRoot.getElementsByClassName("article_post", "DIV")[0];
        articleElement.id = "_youcradContent";

        compRoot.articleElement = document.getElementById("_youcradContent");
        compRoot.articleElement.adplace = "adplacebase";
        compRoot.articleElement.style.position = "relative";

        return true;
    } else if (compRoot.getElementsByClassName("article", "DIV").length == 1) { // This is for TISTORY others
        var articleElement = compRoot.getElementsByClassName("article", "DIV")[0];
        articleElement.id = "_youcradContent";

        compRoot.articleElement = document.getElementById("_youcradContent");
        compRoot.articleElement.adplace = "adplacebase";
        compRoot.articleElement.style.position = "relative";

        return true;
    } else {
        return false;
    }
}

compRoot.getTitleElement = function(){
    
    var titleElement;  
  
    if (compRoot.getElementsByClassName("title", "DIV").length > 0) {
        titleElement = compRoot.getElementsByClassName("title", "DIV")[0];
        titleElement.id = "_youcradTitle";
        compRoot.titleElement = document.getElementById("_youcradTitle");
        return true;
     } else if (compRoot.getElementsByClassName("titleWrap", "DIV").length > 0) {
        titleElement = compRoot.getElementsByClassName("titleWrap", "DIV")[0];
        titleElement.id = "_youcradTitle";
        compRoot.titleElement = document.getElementById("_youcradTitle");
        return true;
     } else if (compRoot.getElementsByClassName("_youcradTitle", "DIV").length > 0) {
        titleElement = compRoot.getElementsByClassName("_youcradTitle", "DIV")[0];
        titleElement.id = "_youcradTitle";
        compRoot.titleElement = document.getElementById("_youcradTitle");
        return true;
     } else if (compRoot.getElementsByClassName("articleView-TMR", "DIV").length > 0) {  // articleView-TMR (세계일보 class)
        titleElement = compRoot.getElementsByClassName("articleView-TMR", "DIV")[0];
        titleElement.id = "_youcradTitle";
        compRoot.titleElement = document.getElementById("_youcradTitle");
        return true;     
     } else {
        return false;     
     }
}

compRoot.doSpanningDOM = function(obj) { /// obj = articleElement-self
    if (obj.SpannedFlag == 'Y') {
//        alert('이미 광고게시 준비가 되어 있습니다.');
        return;
    }

    var theSpanElements, theSpaceElements;
    var spanElement = document.createElement("SPAN");
    spanElement.adplace = "";
    spanElement.className = "youcrad_MarkSpan";
    
    var spanElementAb = document.createElement("SPAN");
    spanElementAb.adplace = "adplace";
    spanElementAb.className = "youcradMarkSpan";
    
    spanElement.appendChild(spanElementAb);
        
    var spaceElement = document.createElement("SPAN");
    spaceElement.style.position = "relative";
    spaceElement.style.zIndex = 10;
    spaceElement.className = "ucr_default_space";
    
    var spaceTable = document.createElement("TABLE");
    spaceTable.style.position = "relative";
    spaceTable.cellSpacing = 0;
    spaceTable.cellPadding = 0;
    spaceTable.style.zIndex = 10;
    spaceTable.style.margin = "0px";
    spaceTable.style.padding = "0px";
    spaceTable.adplace = "adplace";
    spaceTable.border = 0;
    spaceTable.style.width = "100%";

    spaceElement.appendChild(spaceTable);
        
    var newTr= spaceTable.insertRow(document.createElement("TR"));
    var newTd= newTr.insertCell(document.createElement("TD"));
        newTd.style.zIndex = 10;
        newTd.adplace = "adplace";
        newTd.iscomp = "_youcradComp";
        newTd.className = "youcradSpaceTd";
        newTd.innerHTML = "";
        newTd.style.height = "";
        newTd.style.position = "relative";
        newTd.border = 0;
        newTd.name = null;
        newTd.style.width = "100%";

        newTd.colorType = null;
        newTd.objType = null;
        newTd.objAlign = null;
        newTd.vertical = null;
           
    var pNodes = obj.getElementsByTagName("P");
    var liNodes = obj.getElementsByTagName("LI");
    var brNodes = obj.getElementsByTagName("BR");
    
//    alert("p = " + pNodes.length + ", li = " + liNodes.length + ", br = " + brNodes.length);
    obj.insertAdjacentElement("beforeEnd", spanElement.cloneNode(true)); 
    obj.insertAdjacentElement("afterBegin", spaceElement.cloneNode(true));
    obj.insertAdjacentElement("beforeEnd", spaceElement.cloneNode(true));
    
    for(var i=0; i< pNodes.length; i++){
        pNodes[i].insertAdjacentElement("beforeEnd", spanElement.cloneNode(true)); 
//        pNodes[i].insertAdjacentElement("afterEnd", spaceElement.cloneNode(true)); 
        pNodes[i].insertAdjacentElement("beforeEnd", spaceElement.cloneNode(true));         
    }
    
    for(var j=0; j< liNodes.length; j++){
        liNodes[j].insertAdjacentElement("beforeEnd", spanElement.cloneNode(true));
        liNodes[j].insertAdjacentElement("afterEnd", spaceElement.cloneNode(true));          
    }
    
    for(var k=0; k< brNodes.length; k++){
        brNodes[k].insertAdjacentElement("beforeBegin", spanElement.cloneNode(true));
        brNodes[k].insertAdjacentElement("afterEnd", spaceElement.cloneNode(true));          
    }

    theSpanElements = compRoot.getElementsByClassName("youcradMarkSpan", "SPAN");
    theSpaceElements = compRoot.getElementsByClassName("ucr_default_space", "SPAN");
    
//    alert(" theSpan = " + theSpanElements.length);
    
    for(var i=0; i<theSpanElements.length;i++){
        theSpanElements[i].id = "_" + (i + 1);
        theSpanElements[i].onclick = function(){compRoot.createMarkOnSpan(this);};
        theSpanElements[i].onmouseover = function(){compRoot.markOnMouseOver(this);};
        theSpanElements[i].onmouseout = function(){compRoot.markOnMouseOut(this);};
        theSpanElements[i].innerHTML = compRoot.markPlaceString;
    }

    for(var i=0; i<theSpaceElements.length;i++){
        theSpaceElements[i].id = "div__-" + (i+1);
        theSpaceElements[i].firstChild.id = "_-" + (i+1);
        theSpaceElements[i].firstChild.cells[0].id = "__-" + (i+1);
        theSpaceElements[i].firstChild.cells[0].onmouseover= function() {compRoot.spaceOn(this);}; 
        theSpaceElements[i].firstChild.cells[0].onmouseout= function() {compRoot.spaceOut(this);}; 
        theSpaceElements[i].firstChild.cells[0].onmouseup= function() {compRoot.createSpace(document.getElementById(this.id.replace("__", "_")));};
    }
   
//    alert("spanning Done");
    
    obj.SpannedFlag = 'Y';

    return true;
}

compRoot.doSpanning = function(obj) { /// obj = articleElement-self
    if (obj.SpannedFlag == 'Y') {
//        alert('이미 광고게시 준비가 되어 있습니다.');
        return;
    }
    var sourceHTML = obj.innerHTML;
    
    rxp = new RegExp("<COLGROUP>", "g");
    sourceHTML = sourceHTML.replace(rxp, "");
//    rxp = new RegExp("<TBODY>", "g");
    sourceHTML = sourceHTML.replace(rxp, "");
    rxp = new RegExp("</TBODY>", "g");
    sourceHTML = sourceHTML.replace(rxp, "");
    rxp = new RegExp("</P>", "g");
    sourceHTML = sourceHTML.replace(rxp, "</P><BR>");
    rxp = new RegExp("</li>", "g");
    sourceHTML = sourceHTML.replace(rxp, "</LI>");
    rxp = new RegExp("</LI>", "g");
    sourceHTML = sourceHTML.replace(rxp, "</LI><BR>");

    rxp = new RegExp("<BR/>", "g");
    sourceHTML = sourceHTML.replace(rxp, "<BR>")
    rxp = new RegExp("<BR />", "g");
    sourceHTML = sourceHTML.replace(rxp, "<BR>")
    rxp = new RegExp("<br />", "g");
    sourceHTML = sourceHTML.replace(rxp, "<BR>")
    rxp = new RegExp("<br>", "g");
    sourceHTML = sourceHTML.replace(rxp, "<BR>")

    rxp = new RegExp("<BR>", "g");
    sourceHTML = sourceHTML.replace(rxp, "@@@@@@<BR>")

    rxp0 = new RegExp("</LI>@@@@@@");
    rxp1 = new RegExp("</P>@@@@@@");
    rxp2 = new RegExp("@@@@@@");
    
    var BRarray = sourceHTML.split(rxp);
    sourceHTML = "";

    for (var i = 1; i < BRarray.length + 1; i++) { // must start from '1' preventing '0' from being populated.
        sourceHTML += BRarray[i - 1].substring(0, BRarray[i - 1].length - 0).replace(rxp0, "<SPAN id=_" + i + " onclick='javascript:compRoot.createMarkOnSpan(this);' onmouseover='javascript:compRoot.markOnMouseOver(this);' onmouseout='javascript:compRoot.markOnMouseOut(this);' style='position: relative;' adplace='adplace' class='youcradMarkSpan'>"+compRoot.markPlaceString+"</SPAN></LI>").replace(rxp1, "<SPAN id=_" + i + " onclick='javascript:compRoot.createMarkOnSpan(this);' onmouseover='javascript:compRoot.markOnMouseOver(this);' onmouseout='javascript:compRoot.markOnMouseOut(this);' style='position: relative;' adplace='adplace' class='youcradMarkSpan'>"+compRoot.markPlaceString+"</SPAN></P>").replace(rxp2, "<SPAN id=_" + i + "  onclick='javascript:compRoot.createMarkOnSpan(this);' onmouseover='javascript:compRoot.markOnMouseOver(this);' onmouseout='javascript:compRoot.markOnMouseOut(this);' adplace='adplace' style='position: relative;' class='youcradMarkSpan'>"+compRoot.markPlaceString+"</SPAN>");
         sourceHTML += "<DIV id='div__-" + i + "' style='position: relative; z-index: 10;' class='ucr_default_space'><TABLE style='position: relative; z-index: 10; border:solid 0px; margin:0px; padding:0px' adplace='adplace' border='0' cellpadding=0 cellspacing=0 id='_-" + i + "' width='100%' >";
        sourceHTML += "<TR><TD width='100%' class='youcradSpaceTd' name='_spaceBaseTd' iscomp='_youcradComp' id='__-" + i + "' style='position: relative; border=0' adplace='adplace' onmouseover='javascript:compRoot.spaceOn(this);' onmouseout='javascript:compRoot.spaceOut(this);' onmouseup='compRoot.createSpace(document.getElementById(\"_-" + i + "\"));' >";
        sourceHTML += "</TD></TR></TABLE></DIV>";
    }

    compRoot.currentSpannedHTML = sourceHTML;

    compRoot.articleElement.innerHTML = sourceHTML;
    compRoot.articleElement.SpannedFlag = 'Y';

    return true;
}

compRoot.markOnMouseOver = function(el) {
    if ((compRoot.authStatus < 2) || ((compRoot.selectedAdObjectId == "")&&(compRoot.movingPlaceId == ""))) return;
    if ((compRoot.currentPublishMode!="MARK") && (compRoot.selectedAdObjectId != "")) return;
//    if ((parseInt(compRoot.authStatus) == 4) && (compRoot.selectedAdObjectId != "")) return;
//    if (el.getElementsByTagName("IMG")) return;
    if ((compRoot.movingPlaceId != "")&&(compRoot.movingPlaceType != "mark")) return;
    if (el&&el.getElementsByTagName("IMG").length!=0) return;
    el.style.background = "#ffae5e";
}

compRoot.markOnMouseOut = function(el) {
    if ((compRoot.authStatus < 2) || ((compRoot.selectedAdObjectId == "")&&(compRoot.movingPlaceId == ""))) return;
    if ((compRoot.currentPublishMode!="MARK") && (compRoot.selectedAdObjectId != "")) return;
//    if ((parseInt(compRoot.authStatus) == 4) && (compRoot.selectedAdObjectId != "")) return;
//    if (el.getElementsByTagName("IMG")) return;
    if ((compRoot.movingPlaceId != "")&&(compRoot.movingPlaceType != "mark")) return;
    if (el&&el.getElementsByTagName("IMG").length!=0) return;
    el.style.background = "#fffb97";
}

compRoot.turnOnMarks = function() {
    var markSpans = compRoot.getElementsByClassName("youcradMarkSpan", "SPAN");
    if ((markSpans) && (markSpans.length > 0)) {
        for (var i = 0;i< markSpans.length; i++) if (markSpans[i].getElementsByTagName("IMG").length==0){markSpans[i].style.background="#fffb97";/*markSpans[i].appendChild(compRoot.markPlaceStringOn.cloneNode(true));*/}
    }
}

compRoot.turnOffMarks = function() {
    var markSpans = compRoot.getElementsByClassName("youcradMarkSpan", "SPAN");
    if ((markSpans) && (markSpans.length > 0)) {
        for (var i = 0; i < markSpans.length; i++) { markSpans[i].style.background = "";}
    }
}

compRoot.turnOnSpaces = function() {
    var spaceDivs = compRoot.getElementsByClassName("ucr_default_space", "SPAN");
    if ((spaceDivs) && (spaceDivs.length > 0)) {
        for (var i = 0;i< spaceDivs.length; i++) {
            if ((spaceDivs[i].firstChild)&&(spaceDivs[i].firstChild.cells[0].innerHTML=="")) {
                spaceDivs[i].firstChild.cells[0].style.height = compRoot.spaceHeightOpened + "px"; 
                spaceDivs[i].firstChild.style.height = compRoot.spaceHeightOpened + "px"; 
                spaceDivs[i].style.background = "#fffb97";
            }
        }
   }
}

compRoot.turnOffSpaces = function() {
    var spaceDivs = compRoot.getElementsByClassName("ucr_default_space", "SPAN");
    if ((spaceDivs) && (spaceDivs.length > 0)) {
        for (var i = 0;i< spaceDivs.length; i++) {
            if ((spaceDivs[i].firstChild)&&(spaceDivs[i].firstChild.cells[0].innerHTML=="")) {
                spaceDivs[i].firstChild.cells[0].style.height = ""; 
                spaceDivs[i].firstChild.style.height = ""; 
                spaceDivs[i].style.background = "";
            }
         }
    }
}

compRoot.spaceTableOnload = function() {
}

compRoot.spaceOn = function(obj) {
//    if ((compRoot.authStatus != 4) || ((compRoot.selectedAdObjectId == "")&&(compRoot.movingPlaceId == ""))) return;
    if ((compRoot.authStatus < 2) || ((compRoot.selectedAdObjectId == "")&&(compRoot.movingPlaceId == ""))) return;
    if ((compRoot.selectedAdObjectId !="")&&(compRoot.currentPublishMode!="SPACE")) return;
    if ((compRoot.movingPlaceId != "")&&(compRoot.movingPlaceType != "space")) return;
    
    obj.style.backgroundColor = 'e4e4e4';
//    obj.style.height = compRoot.spaceHeightOpened;
    obj.style.height = ((compRoot.dragMark.innerHTML == "")? (0):(compRoot.dragMark.clientHeight + 16)) + "px";
    obj.style.border = "2px solid black";
    obj.style.cursor = "crosshair";
    var tempElement = document.createElement("DIV");
    tempElement.innerHTML = compRoot.dragMark.innerHTML;
    tempElement.style.position = "absolute";
    tempElement.style.zIndex = "1";
    tempElement.style.left = 8;
    tempElement.style.top = 8;
    tempElement.id = obj.id + "_temp";
    tempElement.style.filter = "alpha(opacity=70)";
    document.getElementById("div" + obj.id).appendChild(tempElement);
    compRoot.dragMark.style.visibility = "hidden";
    obj.style.filter = "alpha(opacity=40)";
}

compRoot.spaceOut = function(obj) {
//	if ((compRoot.authStatus != 4) || ((compRoot.selectedAdObjectId == "")&&(compRoot.movingPlaceId == ""))) return;
	if ((compRoot.authStatus < 2) || ((compRoot.selectedAdObjectId == "")&&(compRoot.movingPlaceId == ""))) return;
    if ((compRoot.selectedAdObjectId !="")&&(compRoot.currentPublishMode!="SPACE")) return;
    if ((compRoot.movingPlaceId != "")&&(compRoot.movingPlaceType != "space")) return;
	
	obj.style.backgroundColor = '';
	obj.style.border = "";
	obj.style.cursor = "default";
	obj.innerHTML = "";
	obj.style.height = compRoot.spaceHeightOpened +"px";
	obj.style.filter = "";
	document.getElementById("div" + obj.id).removeChild(document.getElementById(obj.id + "_temp"));
	compRoot.dragMark.style.visibility = "visible";
}

compRoot.scanPid = function() {
    var partnerScripts = document.getElementsByTagName("script");
    var pid = null;
    var UCRAD_Pattern = new RegExp("pid=([a-zA-Z0-9]+)");

    for (var i = 0; i < partnerScripts.length; i++) {
        if (partnerScripts[i].src.match(UCRAD_Pattern)) {
            pid = partnerScripts[i].src.match(UCRAD_Pattern)[1];
        }
    }

    return pid;
}

compRoot.scanArticleId = function(idParamName) {
    var articleId = null;
    var expString = idParamName + "=([0-9]+)";
    var UCRAD_Pattern = new RegExp(expString);
    articleId = (document.URL.match(UCRAD_Pattern))?document.URL.match(UCRAD_Pattern)[1]:"";

    return articleId;
}

compRoot.scanBoardId = function(idParamName) {
    var boardId = null;
    var expString = idParamName + "=([_0-9a-zA-Z]+)";
    var UCRAD_Pattern = new RegExp(expString);
    boardId = (document.URL.match(UCRAD_Pattern))?document.URL.match(UCRAD_Pattern)[1]:"";

    return boardId;
}

compRoot.getStringParamValue = function(theString, paramName) {
	var returnValue = null;
	var paramPari = null;
	if((theString != null)&&(theString != "")){
		var paramSetArray = theString.split("&");
		for (var i = 0; i < paramSetArray.length; i++) {
			paramPair = paramSetArray[i].split("=");
			if (paramName == paramPair[0]) returnValue = paramPair[1];
		}
	}
	return returnValue;
}

compRoot.finalizePublish = function() {

    window.setTimeout("compRoot.turnOffMarks();",0);
    
    window.setTimeout("compRoot.turnOffSpaces();",0);
    
    window.setTimeout("compRoot.movingPlaceId = '';",0);
    window.setTimeout("compRoot.movingPlaceType = '';",0);
    
    compRoot.selectedAdObjectId = "";
    
    compRoot.dragMark.keyword = null;
    compRoot.dragMark.rank = null;
    compRoot.dragMark.curcpc = null;
    compRoot.dragMark.pSize = null;
    compRoot.dragMark.placeType = null;   
    compRoot.dragMark.objType = null;   
        
    compRoot.dragMark.innerHTML = "";
    compRoot.dragMark.style.height = "";
    window.setTimeout("compRoot.markInstAddRelease();",0);
    window.setTimeout("compRoot.spaceInstAddRelease('"+compRoot.currentTargetSpaceId+"');",0);
    compRoot.currentTargetSpaceId = "";
    compRoot.currentTargetMarkId = "";
    compRoot.currentTargetPlaceType = "";
    document.onmousemove = compRoot.mouseMovePartner;

    window.setTimeout("document.body.style.cursor = \"auto\";", 0);

//        compRoot.adsPlaceLoad(compRoot.movingPlaceId);
}

compRoot.prepareMovePlace = function(markId, type){

    if (document.getElementById("youcrad_tempMark") != null) { compRoot.dragMark.innerHTML = ""; }
    if ((parseInt(compRoot.authStatus) != 4) && (parseInt(compRoot.authStatus) != 2)) return;
//    compRoot.movingPlaceId = "";
//    compRoot.movingPlaceBaseId = "";
    var theEvent = window.event;
    compRoot.movingPlaceId = markId;
    compRoot.movingPlaceType = type;

    compRoot.compDestroy(compRoot.markInstListComp);
    compRoot.compDestroy(compRoot.markEditBoxComp);

    var x = compRoot.mouseCoords(theEvent).x; //+ (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollLeft ;
    var y = compRoot.mouseCoords(theEvent).y; //+ (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop  ;

    var h = "";

    if (type == "space") {
        h += document.getElementById(compRoot.spaceInstListEditComp+"_ucrad_"+markId).innerHTML;
        compRoot.dragMark.innerHTML = h;
        compRoot.dragMark.style.filter = "alpha(opacity=60)";
        compRoot.dragMark.style.left = x + 7;
        compRoot.dragMark.style.top = y + 7;

        if ((compRoot.currentTargetMarkId == "") && (compRoot.currentTargetSpaceId == "")) window.setTimeout("compRoot.turnOnSpaces();",0);
        
        
    } else if (type == "mark") {
    
        var ad_title = (ad_title) ? ad_title : " 이동중입니다...";
//        var ad_obj_id = (ad_obj_id) ? ad_obj_id : null;

        h += "<div id='youcrad_tempMark' status='created' style='position:relative; width: 100; left:0; top:0; cursor: url(" + compRoot.imageUrlBase + "images/spacer.cur),auto;' >"
        h += "<img src='" + document.getElementById("ucrad_"+markId).src + "'  >" + ad_title;
        h += "</div>";
        compRoot.dragMark.innerHTML = h;
        compRoot.dragMark.style.left = x + 5;
        compRoot.dragMark.style.top = y + 5;
        
        if ((compRoot.currentTargetMarkId == "") && (compRoot.currentTargetSpaceId == "")) window.setTimeout("compRoot.turnOnMarks();",0);
//        document.body.style.cursor = "url('" + compRoot.imageUrlBase + "images/spacer.cur')";
    }

    compRoot.dragObject = document.getElementById(compRoot.dragMark.id);
    compRoot.mouseOffset = compRoot.getMouseOffset(document.getElementById(compRoot.dragMark.id), null);
    document.onmousemove = compRoot.mouseMove;

//    stopEvent(theEvent);
}

compRoot.checkDistImpossible = function(){
    
        if (compRoot.currentPublishMode=="SPACE"){
            ////////////////// spaceCount
            if (compRoot.spaceCount >= compRoot.articleSpaceLimit) {
                compRoot.alertMsg("한 페이지에서 배포할 수 있는 광고영역(ADSPACE)은 전체 "+ compRoot.articleSpaceLimit +" 개로 제한되어 있습니다.");
                return true;
            }
            ///////////////// visitorSpaceCount
             if ((compRoot.authStatus<4)&&(compRoot.visitorSpaceCount >= compRoot.visitorSpaceLimit)) {
                if (compRoot.visitorSpaceLimit > 0) {
                    compRoot.alertMsg("방문자가 이 글에 배포할 수 있는 광고영역(ADSPACE)은 "+ compRoot.visitorSpaceLimit +" 개로 제한되어 있습니다.");
                } else {
                    compRoot.alertMsg("방문자가 이 글에 광고영역(ADSPACE)을 만드실 수 없습니다.");
                }
                return true;
            }
        } else if (compRoot.currentPublishMode=="MARK"){ 
            ////////////////// markCount
            if ((compRoot.markCount >= compRoot.articleMarkLimit)) {

                compRoot.alertMsg("한 페이지에서 배포할 수 있는 광고마크(ADMARK)는 전체 "+ compRoot.articleMarkLimit +" 개로 제한되어 있습니다.");
                return true;                
            }
            ///////////////// visitorMarkCount
             if ((compRoot.authStatus<4)&&(compRoot.visitorMarkCount >= compRoot.visitorMarkLimit)) {
                if (compRoot.visitorMarkLimit >0 ){
                    compRoot.alertMsg("방문자가 이 글에 배포할 수 있는 광고마크(ADMARK)는 "+ compRoot.visitorMarkLimit +" 개로 제한되어 있습니다.");
                } else {
                    compRoot.alertMsg("방문자가 이 글에 광고마크(ADMARK)를 배포하실 수 없습니다.");
                }
                return true;   
            }        
        }   
        
    return false;
}

compRoot.prepareNewMark = function(ad_title, ad_obj_id, keyword, rank, curcpc, pSize, placeType, objType) { ///// placeType : U - 자체시스템 (직접+디비), O - 오버추어.__________
    if (document.getElementById("youcrad_tempMark") != null) { compRoot.dragMark.innerHTML = ""; }
    if ((parseInt(compRoot.authStatus) != 4) && (parseInt(compRoot.authStatus) != 2)) return;
    if ((compRoot.currentPublishMode!="MARK")&&(compRoot.currentPublishMode!="SPACE")) return;
    
    window.setTimeout("compRoot.turnOffMarks();",0);
    window.setTimeout("compRoot.turnOffSpaces();",0);

    var theEvent = window.event;
    compRoot.selectedAdObjectId = ad_obj_id;

    // dispose all members as of NULL after finalize publishing
    compRoot.dragMark.keyword = encodeURIComponent(keyword);
    compRoot.dragMark.rank = rank;
    compRoot.dragMark.curcpc = curcpc;
    compRoot.dragMark.pSize = pSize;
    compRoot.dragMark.placeType = placeType;
    compRoot.dragMark.objType = objType;
    
    if (compRoot.currentTargetMarkId != "") {
        if (compRoot.currentTargetPlaceType!=placeType){
            compRoot.finalizePublish();
            compRoot.alertMsg("종류가 다른 광고를 한 곳에 배포하실 수 없습니다.");
            return;
        }
        compRoot.createMarkInstance(compRoot.currentTargetMarkId);
    } else if (compRoot.currentTargetSpaceId != "") {
        if (compRoot.currentTargetPlaceType!=placeType){
            compRoot.finalizePublish();
            compRoot.alertMsg("종류가 다른 광고를 한 곳에 배포하실 수 없습니다.");
            return;
        }
        compRoot.createSpaceInstance(compRoot.currentTargetSpaceId);
    } else {
        
        if (compRoot.currentPublishMode=="SPACE"){
            ////////////////// spaceCount
            if (compRoot.spaceCount >= compRoot.articleSpaceLimit) {
                compRoot.alertMsg("한 페이지에서 배포할 수 있는 광고영역(ADSPACE)은 전체 "+ compRoot.articleSpaceLimit +" 개로 제한되어 있습니다.");
                compRoot.finalizePublish();
                return;
            }
            ///////////////// visitorSpaceCount
             if ((compRoot.authStatus<4)&&(compRoot.visitorSpaceCount >= compRoot.visitorSpaceLimit)) {
                if (compRoot.visitorSpaceLimit > 0) {
                    compRoot.alertMsg("방문자가 이 글에 배포할 수 있는 광고영역(ADSPACE)은 "+ compRoot.visitorSpaceLimit +" 개로 제한되어 있습니다.");
                } else {
                    compRoot.alertMsg("방문자가 이 글에 광고영역(ADSPACE)을 만드실 수 없습니다.");
                }
                compRoot.finalizePublish();
                return;
            }
        } else if (compRoot.currentPublishMode=="MARK"){ 
            ////////////////// markCount
            if ((compRoot.markCount >= compRoot.articleMarkLimit)) {
                compRoot.alertMsg("한 페이지에서 배포할 수 있는 광고마크(ADMARK)는 전체 "+ compRoot.articleMarkLimit +" 개로 제한되어 있습니다.");
                compRoot.finalizePublish();
                return;
            }
            ///////////////// visitorMarkCount
             if ((compRoot.authStatus<4)&&(compRoot.visitorMarkCount >= compRoot.visitorMarkLimit)) {
                if (compRoot.visitorMarkLimit >0 ){
                    compRoot.alertMsg("방문자가 이 글에 배포할 수 있는 광고마크(ADMARK)는 "+ compRoot.visitorMarkLimit +" 개로 제한되어 있습니다.");
                } else {
                    compRoot.alertMsg("방문자가 이 글에 광고마크(ADMARK)를 배포하실 수 없습니다.");
                }
                compRoot.finalizePublish();
                return;
            }        
        }   
        

        var x = compRoot.mouseCoords(theEvent).x; //+ (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollLeft ;
        var y = compRoot.mouseCoords(theEvent).y; //+ (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop  ;
        //var x = compRoot.getPosition(theEvent.srcElement).x + (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollLeft; 
        //var y = compRoot.getPosition(theEvent.srcElement).y + (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop;
        var h = "";

        var ad_title = (ad_title) ? ad_title : "...";
        var ad_obj_id = (ad_obj_id) ? ad_obj_id : null;
  
        if (compRoot.currentPublishMode=="SPACE") {
        
        	for (var i = 0; i < compRoot.spaceInstObjKeys.length; i++) {
		//		alert(compRoot.markInstObjKeys[i]);
		        if (((compRoot.spaceInstObjKeys[i]) == (compRoot.selectedAdObjectId))) {
			        alert("동일한 광고가 배포되어 있습니다. 다른 광고를 선택해 주세요.");
			        compRoot.finalizePublish();
			        return;
		        }
	        }

            h += document.getElementById("_adObj" + ad_obj_id).innerHTML;
 
            compRoot.dragMark.innerHTML = h;
            compRoot.dragMark.style.filter = "alpha(opacity=60)";
            compRoot.dragMark.style.left = x + 7;
            compRoot.dragMark.style.top = y + 7;
                 
            if ((compRoot.currentTargetMarkId == "") && (compRoot.currentTargetSpaceId == "") && (parseInt(compRoot.authStatus)>=2)) {
                window.setTimeout("compRoot.turnOnSpaces();",0);
            }

        } else if (compRoot.currentPublishMode=="MARK") {

            	for (var i = 0; i < compRoot.markInstObjKeys.length; i++) {
	                //		alert(compRoot.markInstObjKeys[i]);
	                if (((compRoot.markInstObjKeys[i]) == (compRoot.selectedAdObjectId))) {
		                alert("동일한 광고가 배포되어 있습니다. 다른 광고를 선택해 주세요.");
		                compRoot.finalizePublish();
		                return;
	                }
                }
            h += "<div id='youcrad_tempMark' status='created' style='position:relative; width: 100; left:0; top:0; cursor: url(" + compRoot.imageUrlBase + "images/spacer.cur),auto;' >"
            h += "<img src='" + compRoot.imageUrlBase + "images/admark0.gif'  >" + ad_title;
            h += "</div>";
            compRoot.dragMark.innerHTML = h;
            compRoot.dragMark.style.left = x + 2;
            compRoot.dragMark.style.top = y + 2;
//            document.body.style.cursor = "url('" + compRoot.imageUrlBase + "images/spacer.cur')";
            if ((compRoot.currentTargetMarkId == "") && (compRoot.currentTargetSpaceId == "") && (parseInt(compRoot.authStatus)>=2)) window.setTimeout("compRoot.turnOnMarks();",0);

        }

        compRoot.dragObject = document.getElementById(compRoot.dragMark.id);
        compRoot.mouseOffset = compRoot.getMouseOffset(document.getElementById(compRoot.dragMark.id), null);
        document.onmousemove = compRoot.mouseMove;

        if (document.getElementById("youcrad_btnMin")) compRoot.widgetTimeOut = window.setTimeout("document.getElementById(\"youcrad_btnMin\").click();", 50);        
    }
//    stopEvent(theEvent);
}

compRoot.createMarkOnSpan = function(obj) {
    //    alert("ccclick");
    if ((compRoot.dragMark.innerHTML != "") && ((compRoot.selectedAdObjectId != "")||(compRoot.movingPlaceId != ""))) {
        if ((parseInt(compRoot.authStatus) == 4)&&(compRoot.selectedAdObjectId != "")) {
            //alert("글작성자님은 애드마크형 광고를 배포할 수 없습니다. \n 광고를 배포하시려면 애드스페이스를 이용하세요");
            //compRoot.finalizePublish();
            //return;
        }

        if ((compRoot.markCount >= compRoot.articleMarkLimit)&&(compRoot.movingPlaceId == "")) {
            alert("한 게시물에 애드마크는 " + compRoot.articleMarkLimit + " 개 이상 배포할 수 없습니다");
            compRoot.finalizePublish();
            return;
        }

        var ADMexist = false;
        if ((obj.adplace == "adplace") && (obj.children.length) > 0) {
            //            alert('The adMark having the id such as \'' + obj.children.item(0).id + '\' already exists');
            alert("해당 위치에 이미 애드마크가 배포되어 있습니다. 다른 위치를 선택해 주세요.");
            ADMexist = true;
        }
        
        if (!(ADMexist)) {
            if (compRoot.movingPlaceId != "") {
                compRoot.adsPlaceMoving(compRoot.movingPlaceId, obj.id);
            } else {
                compRoot.adsPlacePositioning(obj.id);
            }
            compRoot.finalizePublish();
        } else {
            compRoot.finalizePublish();
        }
    } else {
        //        alert("To create an ads-place, please do start from drag");
    }
}

compRoot.createMark = function(posX, posY) {

	if ((compRoot.dragMark.innerHTML != "") && (compRoot.selectedAdObjectId != "")) {
		if (parseInt(compRoot.authStatus) == 4) {
//			alert("글작성자님은 애드마크형 광고를 배포할 수 없습니다. \n 광고를 배포하시려면 애드스페이스를 이용하세요");
			compRoot.finalizePublish();
			return;
		}

		if ((compRoot.markCount >= compRoot.articleMarkLimit)) {
			alert("한 게시물에 애드마크는 " + compRoot.articleMarkLimit + " 개 이상 배포할 수 없습니다");
			compRoot.finalizePublish();
			return;
		}

		compRoot.adsPlacePositioning("_0", posX, posY);
		compRoot.finalizePublish();
	} else {
		//        alert("To create an ads-place, please do start from drag");
	}
}

compRoot.createSpace = function(obj) {

//	if (parseInt(compRoot.authStatus) != 4) { return; compRoot.finalizePublish(); }
    if (parseInt(compRoot.authStatus) < 2) { return; compRoot.finalizePublish(); }

	if ((compRoot.dragMark.innerHTML != "")) {

/////////// PrepareNew 단계에서 제한하는 것으로 하고 아래는 무시 /////////////////////
//		if ((compRoot.spaceCount >= compRoot.articleSpaceLimit)&&(compRoot.movingPlaceId == "")) {
//			alert("한 게시물에 애드스페이스는 " + compRoot.articleSpaceLimit + " 개 이상 배포할 수 없습니다");
//			compRoot.finalizePublish();
//			return;
//		}
		
        if (compRoot.movingPlaceId != "") {
            compRoot.adsPlaceMoving(compRoot.movingPlaceId, obj.id);
        } else {
		    compRoot.adsPlacePositioning(obj.id, 0, 0);
		}
		
		compRoot.spaceOut(obj.cells[0]);
		
		compRoot.finalizePublish();
	} else {
		//      alert("No ads selected, please try again");
		compRoot.finalizePublish();
	}
	//	stopEvent(window.event);
}

compRoot.adsPlaceMoving = function(markId, base_id) {
//	alert("compRoot.selectedAdObjectId = " + compRoot.selectedAdObjectId);
//    var theBaseId = parseInt(base_id.replace("_", ""));
//	var _posX = (posX!=null)?(posX):(0);
//	var _posY = (posY!=null)?(posY):(0);
	
//	for (var i = 0; i < compRoot.markInstObjKeys.length; i++) {
//		//		alert(compRoot.markInstObjKeys[i]);
//		if ((theBaseId >= 0) && (parseInt(compRoot.markInstObjKeys[i]) == parseInt(compRoot.selectedAdObjectId))) {
//			alert("동일한 광고가 배포되어 있습니다. 다른 광고를 선택해 주세요.");
//			compRoot.finalizePublish();
//			return;
//		}
//	}

//	for (var i = 0; i < compRoot.spaceInstObjKeys.length; i++) {
//		//		alert(compRoot.markInstObjKeys[i]);
//		if ((theBaseId < 0) && (parseInt(compRoot.spaceInstObjKeys[i]) == parseInt(compRoot.selectedAdObjectId))) {
//			alert("동일한 광고가 배포되어 있습니다. 다른 광고를 선택해 주세요.");
//			compRoot.finalizePublish();
//			return;
//		}
//	}
	var Url = compRoot.targetUrl + compRoot.procCallTarget;
	Url += "?funcName=ptrAdPlaceMove";
	Url += "&Mark_Partner_ID=" + compRoot.partnerId;
	Url += "&Mark_Board_ID=" + compRoot.boardId;
	Url += "&Mark_Article_ID=" + compRoot.articleId;
	Url += "&Mark_Base_ID=" + base_id.replace("_", "");
	Url += "&Mark_Publisher_ID=" + compRoot.authedId;
	Url += "&movingPlaceId=" + compRoot.movingPlaceId;
	Url += "&articleUrl=" + compRoot.articleUrl;
//	if (compRoot.selectedAdObjectId) {
//		Url += "&DirectInsert=Yes";
//	} else {
//		Url += "&DirectInsert=No";
//	}
	window.setTimeout("compRoot.addScript('"+Url+"', 'compRoot.adsPlaceMovingCallback');",0);
}

compRoot.adsPlaceMovingCallback = function(funcName, oj) {
    compRoot.adsPlaceLoad(oj.res._markId)   // just Inserted 된 Mark ID 를 넘겨준다. Inserted Ads Instance Automatic Display 를 위함.  
}

compRoot.adsPlacePositioning = function(base_id, posX, posY) {
	//	alert("compRoot.selectedAdObjectId = " + compRoot.selectedAdObjectId);
    var theBaseId = parseInt(base_id.replace("_", ""));
	var _posX = (posX!=null)?(posX):(0);
	var _posY = (posY!=null)?(posY):(0);
	var _colorType = (theBaseId >= 0)?(compRoot.markDefaultColor):(compRoot.spaceDefaultColor );
	
	for (var i = 0; i < compRoot.markInstObjKeys.length; i++) {
		//		alert(compRoot.markInstObjKeys[i]);
		if ((theBaseId >= 0) && ((compRoot.markInstObjKeys[i]) == (compRoot.selectedAdObjectId))) {
			alert("동일한 광고가 배포되어 있습니다. 다른 광고를 선택해 주세요.");
			compRoot.finalizePublish();
			return;
		}
	}

	for (var i = 0; i < compRoot.spaceInstObjKeys.length; i++) {
		//		alert(compRoot.markInstObjKeys[i]);
		if ((theBaseId < 0) && ((compRoot.spaceInstObjKeys[i]) == (compRoot.selectedAdObjectId))) {
			alert("동일한 광고가 배포되어 있습니다. 다른 광고를 선택해 주세요.");
			compRoot.finalizePublish();
			return;
		}
	}
	
	

	var Url = compRoot.targetUrl + compRoot.procCallTarget;
	Url += "?funcName=ptrAdPlaceCreate";
	Url += "&Mark_Partner_ID=" + compRoot.partnerId;
	Url += "&Mark_Board_ID=" + compRoot.boardId;
	Url += "&posX=" + (100 * (_posX) / (compRoot.articleElement.offsetWidth));
	//    Url += "&posY=" + (100 * (posY) / (compRoot.articleElement.offsetHeight));
	Url += "&posY=" + (_posY);
	Url += "&Mark_Article_ID=" + compRoot.articleId;
	Url += "&Mark_Base_ID=" + base_id.replace("_", "");
	Url += "&Mark_Publisher_ID=" + compRoot.authedId;
	Url += "&selectedAdObjectId=" + compRoot.selectedAdObjectId;
	Url += "&articleUrl=" + compRoot.articleUrl;
	
//	  compRoot.dragMark.keyword = null;
//    compRoot.dragMark.rank = null;
//    compRoot.dragMark.curcpc = null;

	Url += "&youcrad_searchKeyword=" + compRoot.dragMark.keyword;
	Url += "&youcrad_rank=" + compRoot.dragMark.rank;
	Url += "&youcrad_currnetCPC=" + compRoot.dragMark.curcpc;
	Url += "&youcrad_pSize=" + compRoot.dragMark.pSize;    
	Url += "&youcrad_placeType=" + compRoot.dragMark.placeType;    
	Url += "&youcrad_objType=" + compRoot.dragMark.objType;    
	Url += "&youcrad_colorType=" + _colorType;

	if (compRoot.selectedAdObjectId) {
		Url += "&DirectInsert=Yes";
	} else {
		Url += "&DirectInsert=No";
	}
	//    alert("x%=" + (100 * (posX) / (compRoot.articleElement.offsetWidth)) + ", y%=" + (100 * (posY) / (compRoot.articleElement.offsetHeight)));
	//    alert("x%=" + (posX) +", y%=" + (posY) );
	compRoot.addScript(Url, 'compRoot.adsPlacePositioningCallback');
}

compRoot.adsPlacePositioningCallback = function(funcName, oj) {
    if (oj.res._status == "1"){
        compRoot.adsPlaceLoad(oj.res._markId)   // just Inserted 된 Mark ID 를 넘겨준다. Inserted Ads Instance Automatic Display 를 위함.  
    } else {
        compRoot.alertMsg("광고 배포가 이루어지지 않았습니다. 잠시 후 다시 시도해 주세요");
        compRoot.adsPlaceLoad(oj.res._markId);
    }
}

compRoot.adsPlaceLoad = function(Inserted) {
    var Inserted_ID;   
    if ((Inserted != '') && (Inserted != null)) { Inserted_ID = Inserted; } else { Inserted_ID = 'None'; }
    var Url = compRoot.targetUrl + compRoot.procCallTarget;
    Url += "?funcName=ptrAdPlaceLoad";
    Url += "&Mark_Partner_ID=" + compRoot.partnerId;
    Url += "&Mark_Inserted_ID=" + Inserted_ID;
    Url += "&Mark_Board_ID=" + compRoot.boardId;
    Url += "&Mark_Article_ID=" + compRoot.articleId;
    compRoot.addScript(Url, 'compRoot.adsPlaceRender');
}

compRoot.adPlaceMarkRender = function(oj) {
    var tempobj;
    var markClicked;
    var imagesInArticle;
    compRoot.imagesInArticle = null;
    compRoot.imagesInArticle = new Array();
    //	Destroy Marks
    compRoot.compDestroy(compRoot.markInstListComp);
    
//    window.setTimeout("compRoot.imagesInArticle = compRoot.articleElement.getElementsByTagName('IMG');",0);
//    for (var i = 0; i < compRoot.imagesInArticle.length; i++) {
//        if ((compRoot.imagesInArticle[i].id != null) && ((compRoot.imagesInArticle[i].id.indexOf("ucrad_")) == 0)) {
////            alert(imagesInArticle[i].id);
////            imagesInArticle[i].parentElement.removeChild(imagesInArticle[i]);
//            compRoot.imagesInArticle[i].parentElement.innerHTML = "";
////            window.setTimeout("document.getElementById('" + compRoot.imagesInArticle[i].id + "').parentElement.removeChild(document.getElementById('" + compRoot.imagesInArticle[i].id + "'));", 0);            
//        }
//    }

//    compRoot.markCount = parseInt(oj._markCount.cnt);
    
    
    compRoot.markInstObjKeys = null; compRoot.markInstObjKeys = new Array();
//    for (var i = 0; i < oj._markCount.adObjKey.length; i++) {
//        compRoot.markInstObjKeys.push(oj._markCount.adObjKey[i].adsObjKey)
//    }
    
    for (var i = 0; i < oj._instArray.length; i++){
        if (oj._instArray[i].type=="mark") compRoot.markInstObjKeys.push(oj._instArray[i].adsObjKey);
    }

    compRoot.visitorMarkCount = 0;
    compRoot.markCount = 0;
    
    for (var i = 0; i < oj.Mark_Arr.length; i++) {
        tempobj = document.getElementById("_" + oj.Mark_Arr[i].Mark_Base_ID);
        if (parseInt(oj.Mark_Arr[i].Mark_Base_ID) > 0) {
            
            var _instCount = 0;
            for (var j = 0; j < oj._instArray.length; j++){
                if (oj._instArray[j].baseId == oj.Mark_Arr[i].Mark_Base_ID) _instCount++;
            }
            
            compRoot.markCount = compRoot.markCount + 1;
            
            var img = new Image();
            var repStringBlock;
            var repStringColor = "#";

            img.src = compRoot.imageUrlBase + "images/admark" + oj.Mark_Arr[i]._colorType + ".gif";
            img.id = 'ucrad_' + oj.Mark_Arr[i].Mark_ID;
            img.name = oj.Mark_Arr[i].Mark_Publisher_ID;
            img.partnerUserId = oj.Mark_Arr[i]._partnerUserId;
//            img.totalInstCount = oj.Mark_Arr[i]._instCount;
            img.totalInstCount = _instCount;
            img.placeType = oj.Mark_Arr[i]._placeType;
            img.isVisitorElement = compRoot.isVisitorElement( img.name, img.partnerUserId);
            img.style.cursor = 'hand';
            img.style.filter = "alpha(opacity=80)";
            img.style.position = "absolute";
            img.style.verticalAlign = "middle";
            img.style.top = "1px";   // Need to apply the current inner Character's size
            img.style.left = "10px";   // Need to apply the current inner Character's size
            //              img.zIndex="1000000";   // Do not need to apply this property
            img.onmouseover = function() { 
                UCRAD_MouseOverADMark(this.id); 
                window.clearTimeout(compRoot.timeId2); 
                window.clearTimeout(compRoot.timeId3); 
            }
            img.onmouseout = function() { 
                window.clearTimeout(compRoot.timeId1); 
                compRoot.timeId2 = window.setTimeout("compRoot.compDestroy(compRoot.markEditBoxComp);", compRoot.editBoxTime); 
                if (compRoot.partnerLogoPostfix=="_dc") compRoot.timeId3 = window.setTimeout("compRoot.compDestroy(compRoot.markInstListComp);", compRoot.markTime); 
            }
            img.onmouseup = function() { stopEvent(window.event); }

            tempobj.appendChild(img);

            switch (parseInt(oj.Mark_Arr[i]._colorType)){
                case 0: // dark gray
                    repStringColor += "999999";
                break;
                case 1: // orange-wrapped gray
                    repStringColor += "aaaaaa";
                break;            
                case 2: // sky blue
                    repStringColor += "14c4ef";
                break;            
                case 3: // orange
                    repStringColor += "f78a0c";
                break;
                case 4: // green
                    repStringColor += "8bc645";
                break;
                case 5: // pink
                    repStringColor += "f80bb9";
                break;
                default: // dark gray
                    repStringColor += "999999";
                break;                                                            
            }
                        
            
            if (compRoot.showMarkComment){
                repStringBlock = document.createElement("DIV");
                repStringBlock.className = "ucr_default";
                repStringBlock.style.color = repStringColor;
                repStringBlock.style.position = "absolute";
                repStringBlock.style.filter = "alpha(opacity=80)";
                repStringBlock.style.top = "-1px";
                repStringBlock.style.left = "31px";
                repStringBlock.style.width = (oj.Mark_Arr[i]._placeKeyword.length*10*2) +"px";
                repStringBlock.innerText = oj.Mark_Arr[i]._placeKeyword;
                
                tempobj.appendChild(repStringBlock);
            }
                        
            compRoot.visitorMarkCount = compRoot.visitorMarkCount + compRoot.isVisitorElement( img.name, img.partnerUserId);

            if (oj.Mark_Arr[i].Mark_ID == oj.Mark_Inserted_ID) {/// ADMark 에서 direct insert 가 일어난 경우에만 자동으로 해당 mark 를 열어서 보여주는 것
                markClicked = "Yes";
                UCRAD_MouseOverADMark('ucrad_' + oj.Mark_Inserted_ID);
            }
        }
    }
}

compRoot.adPlaceSpaceRender = function(oj) {
    var tempobj;
    var markClicked;
    var spaceHeight = 0;

//    compRoot.spaceCount = parseInt(oj._spaceCount.cnt);

    compRoot.spaceInstObjKeys = null; compRoot.spaceInstObjKeys = new Array();
//    for (var i = 0; i < oj._spaceCount.adObjKey.length; i++) {
//        compRoot.spaceInstObjKeys.push(oj._spaceCount.adObjKey[i].adsObjKey)
//    }

    for (var i = 0; i < oj._instArray.length; i++){
        if (oj._instArray[i].type=="space") compRoot.spaceInstObjKeys.push(oj._instArray[i].adsObjKey);
    }

    compRoot.visitorSpaceCount = 0;
    compRoot.spaceCount = 0;

    for (var i = 0; i < oj.Mark_Arr.length; i++) {
        if (parseInt(oj.Mark_Arr[i].Mark_Base_ID) < 0) {  // oj.Mark_Arr[i]._instCount

            var _instCount = 0;
            for (var j = 0; j < oj._instArray.length; j++){
                if (oj._instArray[j].baseId == oj.Mark_Arr[i].Mark_Base_ID) _instCount++;
            }
            
            compRoot.spaceCount += 1;      
            
            tempobj = document.getElementById("_" + oj.Mark_Arr[i].Mark_Base_ID);
        
// get the instCount from Array comparison _ new method
//            if (parseInt(oj.Mark_Arr[i]._objType) == 0) {
//                spaceHeight = 35 + parseInt(oj.Mark_Arr[i]._instCount) * 80;
//            } else if ((parseInt(oj.Mark_Arr[i]._objType) != 0) && (parseInt(oj.Mark_Arr[i]._vertical) == 1)) {
//                spaceHeight = 35 + parseInt(oj.Mark_Arr[i]._instCount) * 40;
//            } else {
//                spaceHeight = 35 + 1 * 40;
//            }
            if (parseInt(oj.Mark_Arr[i]._objType) == 0) {
                spaceHeight = 35 + _instCount * 80;
            } else if ((parseInt(oj.Mark_Arr[i]._objType) != 0) && (parseInt(oj.Mark_Arr[i]._vertical) == 1)) {
                spaceHeight = 35 + _instCount * 40;
            } else {
                spaceHeight = 35 + 1 * 40;
            }
            
//            spaceHeight = "0";
            
            tempobj.cells[0].style.height = spaceHeight + "px";
            
            tempobj.cells[0].style.position = "relative";
            tempobj.cells[0].id = "ucrad_" + oj.Mark_Arr[i].Mark_ID;
            tempobj.cells[0].name = oj.Mark_Arr[i].Mark_Publisher_ID;
            tempobj.cells[0].partnerUserId = oj.Mark_Arr[i]._partnerUserId;
            
            compRoot.visitorSpaceCount = compRoot.visitorSpaceCount + compRoot.isVisitorElement( tempobj.cells[0].name, tempobj.cells[0].partnerUserId);

            tempobj.cells[0].colorType = oj.Mark_Arr[i]._colorType;
            tempobj.cells[0].objType = oj.Mark_Arr[i]._objType;
            tempobj.cells[0].objAlign = oj.Mark_Arr[i]._objAlign;
            tempobj.cells[0].vertical = oj.Mark_Arr[i]._vertical;
//            tempobj.cells[0].totalInstCount = oj.Mark_Arr[i]._instCount;
            tempobj.cells[0].totalInstCount = _instCount;
            tempobj.cells[0].placeType = oj.Mark_Arr[i]._placeType;
            
            tempobj.cells[0].isVisitorElement = compRoot.isVisitorElement( tempobj.cells[0].name, tempobj.cells[0].partnerUserId);
            
            tempobj.onclick = null;
            tempobj.cells[0].adplace = "";

            tempobj.cells[0].onmouseover = null;
            tempobj.cells[0].onmouseout = null;
            tempobj.cells[0].onmouseup = null;
            tempobj.cells[0].style.cursor = "auto";
            tempobj.style.cursor = "auto";
            tempobj.cells[0].style.backgroundColor = "";

//            window.setTimeout("compRoot.showSpaceAds(\"" + tempobj.cells[0].id + "\");", 0);
            compRoot.showSpaceAds(tempobj.cells[0].id);
            //            deleted = ((oj.Mark_Base_ID == oj.Mark_Arr[i].Mark_Base_ID) ? (false) : (true));
        }
    }
}

compRoot.adsPlaceRender = function(oj) {
    
    var spaceBases;
    var markBases;

    if (compRoot.articleElement.SpannedFlag != "Y") {
        alert("아직 광고물 게시를 위한 준비가 되어 있지 않습니다.");
        return;
    }

    if (oj.Mark_Base_ID == "") {
    
        spaceBases = compRoot.getElementsByClassName("ucr_default_space", "SPAN");
        for (var i = 0; i < spaceBases.length; i++) {
            if ((spaceBases[i].firstChild) && (spaceBases[i].firstChild.adplace == "adplace")) {
                window.setTimeout("compRoot.compDestroy('"+ compRoot.spaceInstListEditComp + "_" + spaceBases[i].firstChild.cells[0].id+"');",0);
                spaceBases[i].firstChild.cells[0].adplace = "adplace";
                spaceBases[i].firstChild.cells[0].innerHTML = "";
                spaceBases[i].firstChild.cells[0].style.height = "";
                spaceBases[i].firstChild.cells[0].style.position = "relative";
                spaceBases[i].firstChild.cells[0].id = spaceBases[i].id.replace("div","");
                spaceBases[i].firstChild.cells[0].name = "";
                spaceBases[i].firstChild.cells[0].partnerUserId = "";
                spaceBases[i].firstChild.cells[0].totalInstCount = "";
                spaceBases[i].firstChild.cells[0].placeType = "";
                spaceBases[i].firstChild.cells[0].onmouseover= function() {compRoot.spaceOn(this);}; 
                spaceBases[i].firstChild.cells[0].onmouseout= function() { compRoot.spaceOut(this);}; 
                spaceBases[i].firstChild.cells[0].onmouseup= function() {compRoot.createSpace(document.getElementById(this.id.replace("__", "_")));};

                spaceBases[i].firstChild.cells[0].colorType = "";
                spaceBases[i].firstChild.cells[0].objType = "";
                spaceBases[i].firstChild.cells[0].objAlign = "";
                spaceBases[i].firstChild.cells[0].vertical = "";

            }
        }
        compRoot.adPlaceSpaceRender(oj);
        
        markBases = compRoot.getElementsByClassName("youcradMarkSpan", "SPAN");
        for (var i = 0; i < markBases.length; i++) {
            markBases[i].innerHTML = compRoot.markPlaceString;
        }
        
        compRoot.adPlaceMarkRender(oj);
        
    } else if (parseInt(oj.Mark_Base_ID) < 0) {
    
        spaceBases = compRoot.getElementsByClassName("ucr_default_space", "SPAN");
        for (var i = 0; i < spaceBases.length; i++) {
            if ((spaceBases[i].firstChild) && (spaceBases[i].firstChild.adplace == "adplace")) {
                window.setTimeout("compRoot.compDestroy('"+ compRoot.spaceInstListEditComp + "_" + spaceBases[i].firstChild.cells[0].id+"');",0);
                spaceBases[i].firstChild.cells[0].adplace = "adplace";
                spaceBases[i].firstChild.cells[0].innerHTML = "";
                spaceBases[i].firstChild.cells[0].style.height = "";
                spaceBases[i].firstChild.cells[0].style.position = "relative";
                spaceBases[i].firstChild.cells[0].id = spaceBases[i].id.replace("div","");
                spaceBases[i].firstChild.cells[0].name = "";
                spaceBases[i].firstChild.cells[0].partnerUserId = "";
                spaceBases[i].firstChild.cells[0].totalInstCount = "";
                spaceBases[i].firstChild.cells[0].placeType = "";                
                spaceBases[i].firstChild.cells[0].onmouseover= function() {compRoot.spaceOn(this);}; 
                spaceBases[i].firstChild.cells[0].onmouseout= function() { compRoot.spaceOut(this);}; 
                spaceBases[i].firstChild.cells[0].onmouseup= function() {compRoot.createSpace(document.getElementById(this.id.replace("__", "_")));};

                spaceBases[i].firstChild.cells[0].colorType = "";
                spaceBases[i].firstChild.cells[0].objType = "";
                spaceBases[i].firstChild.cells[0].objAlign = "";
                spaceBases[i].firstChild.cells[0].vertical = "";
            }
        }
            
        compRoot.adPlaceSpaceRender(oj); 
        
    } else if (parseInt(oj.Mark_Base_ID) >=0) {
    
        markBases = compRoot.getElementsByClassName("youcradMarkSpan", "SPAN");
        for (var i = 0; i < markBases.length; i++) {
            markBases[i].innerHTML = compRoot.markPlaceString;
        }
        
        compRoot.adPlaceMarkRender(oj);
    }

}

function UCRAD_MouseOverADMark(id){
	compRoot.timeId1 = window.setTimeout("compRoot.openAdMark(\"" + id + "\")", 100); 
}

//function UCRAD_MouseDownADMark(id){      
//    compRoot.openAdMark(id);
//    window.clearTimeout(compRoot.timeId1);
//}

compRoot.openAdMark = function(markDivId) {
    compRoot.compDestroy(compRoot.markInstListComp);
    compRoot.compDestroy(compRoot.markEditBoxComp);
	compRoot.showMarkAds(markDivId);
}

compRoot.openAdSpace = function(spaceDivId) {
//	document.getElementById(spaceDivId).innerHTML = "<table border='0' cellspacing='0' cellpadding='0' style='POSITION:relative;'><tr><td></td><td height='0'></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td height='0'></td><td></td></tr></table>";
    compRoot.showSpaceAds(spaceDivId);
}

compRoot.showMarkAds = function(id)    //// popup mark adinstances, id from the image
{
    if ((compRoot.selectedAdObjectId != "")||(compRoot.movingPlaceId != "")) return;
    
    if (compRoot.compDestroy(compRoot.markInstListComp) && compRoot.compDestroy(compRoot.markEditBoxComp)) {

        var thePosition = compRoot.getPosition(document.getElementById(id).parentElement.parentElement);
        
    var placeType = document.getElementById(id).placeType;
    var isVisitorElement = document.getElementById(id).isVisitorElement;
    var name = document.getElementById(id).name;
    var partnerUserId = document.getElementById(id).partnerUserId;
    var markId = id.replace("ucrad_", "");
    var totalInstCount = document.getElementById(id).totalInstCount; 
    var colorType = document.getElementById(id).colorType;

        // mark inst list box width = 384
        compRoot.compCreate(compRoot.markInstListComp, "&youcrad_markId=" + markId + "&youcrad_name=" + name + "&youcrad_partnerUserId=" + partnerUserId + "&youcrad_isVisitorElement=" + isVisitorElement + "&youcrad_totalInstCount=" + totalInstCount + "&youcrad_placeType=" + placeType , thePosition.x + 9, thePosition.y + 8);
        
        document.getElementById(compRoot.markInstListComp).style.left = (thePosition.x + 9 + 386 <  (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientWidth +  (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollLeft  ) ? (thePosition.x + 9) : ( (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientWidth +  (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollLeft - 386);
        
        document.getElementById(compRoot.markInstListComp).style.top = thePosition.y + 12;

//        if ((compRoot.authStatus == 4) || (compRoot.authedId == document.getElementById(id).name)) {   /// version 1
//        if ((compRoot.isOwner(document.getElementById(id).name, document.getElementById(id).partnerUserId))) {   /// version 2
        if ((parseInt(compRoot.authStatus)==4)||((placeType=="O") && compRoot.isOwner(name,partnerUserId))) {   /// version 3 - only for Author & Owner in case of Overture ads
            compRoot.compCreate(compRoot.markEditBoxComp, "&youcrad_markId=" + markId + "&youcrad_name=" + name + "&youcrad_partnerUserId=" + partnerUserId + "&youcrad_isVisitorElement=" + isVisitorElement + "&youcrad_totalInstCount=" + totalInstCount + "&youcrad_placeType=" + placeType + "&youcrad_colorType=" + colorType, thePosition.x + 9, thePosition.y - 25);
 
//            document.getElementById(compRoot.markEditBoxComp).style.left = thePosition.x + 9;
            document.getElementById(compRoot.markEditBoxComp).style.left = (thePosition.x + 9 + 386 <  (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientWidth +  (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollLeft  ) ? (thePosition.x + 9) : ( (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientWidth +  (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollLeft - 386);
            document.getElementById(compRoot.markEditBoxComp).style.top = thePosition.y - 24;
        }

        document.getElementById(compRoot.markInstListComp).isdragged = "N"; /// return to the un-dragged status as initial

        compRoot.setDrag(compRoot.markInstListComp);
        
        if ((parseInt(compRoot.authStatus) >= 2)) {
            document.getElementById(compRoot.markInstListComp).onclick = function() { compRoot.insertInstance(this,"admark"); };
            document.getElementById(compRoot.markInstListComp).youcrad_markId = id.replace("ucrad_", "");
            document.getElementById(compRoot.markInstListComp).totalInstCount = document.getElementById(id).totalInstCount;
            document.getElementById(compRoot.markInstListComp).name = document.getElementById(id).name;
            document.getElementById(compRoot.markInstListComp).partnerUserId = document.getElementById(id).partnerUserId;
            document.getElementById(compRoot.markInstListComp).placeType = document.getElementById(id).placeType;
            document.getElementById(compRoot.markInstListComp).isVisitorElement = document.getElementById(id).isVisitorElement;
        }

//        compRoot.timeId2 = window.setTimeout("compRoot.compDestroy(compRoot.markEditBoxComp);", compRoot.editBoxTime);
    }
}

//compRoot.markIconBoxComp = "756";
//compRoot.spaceEditBoxComp = "757";

compRoot.showIconEditBox = function(id) {
	var thePosition = compRoot.getPosition(document.getElementById("ucrad_" + id));

	if ((compRoot.authStatus == 4) || (compRoot.authedId == document.getElementById("ucrad_" + id).name)) {
		compRoot.compCreate(compRoot.markIconBoxComp, "&youcrad_markId=" + id + "&youcrad_colorType=" + document.getElementById("ucrad_" + id).colorType, thePosition.x + 9, thePosition.y - 25);
		document.getElementById(compRoot.markIconBoxComp).style.left = thePosition.x + 12;
		document.getElementById(compRoot.markIconBoxComp).style.top = thePosition.y - 135;
	}
}

compRoot.showSpaceEditBox = function(id) {

	var thePosition = compRoot.getPosition(document.getElementById("ucrad_" + id));

	if ((compRoot.authStatus == 4) || (compRoot.authedId == document.getElementById("ucrad_" + id).name)) {
		compRoot.compCreate(compRoot.spaceEditBoxComp, "&youcrad_markId=" + id + "&youcrad_colorType=" + document.getElementById("ucrad_" + id).colorType + "&youcrad_placeType=" + document.getElementById("ucrad_" + id).placeType + "&youcrad_objType=" + document.getElementById("ucrad_" + id).objType + "&youcrad_objAlign=" + document.getElementById("ucrad_" + id).objAlign + "&youcrad_vertical=" + document.getElementById("ucrad_" + id).vertical, thePosition.x + 9, thePosition.y - 25);
		document.getElementById(compRoot.spaceEditBoxComp).style.left = thePosition.x + 12;
		document.getElementById(compRoot.spaceEditBoxComp).style.top = thePosition.y - 135;

		compRoot.setDrag(compRoot.spaceEditBoxComp);
	}
}


compRoot.instDelButtonHide = function(el) {
//    compRoot.findMainCompEl(el).totalInstCount = el.totalInstCount;
//    compRoot.findMainCompEl(el).youcrad_markId = el.youcrad_markId;

//    var theImages = compRoot.findMainCompEl(el).getElementsByTagName("IMG");
//    var mainCompEl = compRoot.findMainCompEl(el);

//    for (var i = 0; i < theImages.length; i++) {
//        if (theImages[i].id == "youcrad_btnAddAd") {
//            theImages[i].youcrad_markId = el.youcrad_markId;
//            if ((mainCompEl.placetype == "admark") ? (mainCompEl.totalInstCount >= compRoot.markInstLimit) : (mainCompEl.totalInstCount >= compRoot.spaceInstLimit)) theImages[i].style.visibility = "hidden";
//            if ((mainCompEl.placetype == "admark") && (parseInt(compRoot.authStatus) == 4)) theImages[i].style.visibility = "hidden";
//        }
//    }
    if ((compRoot.authedId == "") || ((compRoot.authedId != "") && (compRoot.authedId != el.instcreator))) el.style.visibility = "hidden";
    if (document.getElementById("youcrad_instListIframe")) document.getElementById("youcrad_instListIframe").style.pixelHeight = 118 + 80 * (el.totalInstCount - 1);
}

compRoot.showSpaceAds = function(id) /// Drwaing the Ads instances within ADSpace by loads - by Inkee Paek, id is out of TD object
{
//    alert(id);
	compRoot.compDestroy(compRoot.spaceInstListEditComp + "_" + id);
	
	var colorType = document.getElementById(id).colorType;
	var objType = document.getElementById(id).objType;
	var vertical = document.getElementById(id).vertical;
	var objAlign = document.getElementById(id).objAlign;
	var totalInstCount = document.getElementById(id).totalInstCount;
	var placeType = document.getElementById(id).placeType;
	var name = document.getElementById(id).name;
    var partnerUserId = document.getElementById(id).partnerUserId;
    var isVisitorElement = document.getElementById(id).isVisitorElement;
    
	var alignString = (objAlign=='0')?('left'):((objAlign=='1')?('center'):('right'));

	var h = '<table border="0" align="' + alignString + '" cellspacing="0" cellpadding="0" style="POSITION: relative; height: 0px;"><tr><td></td><td height="0"></td><td></td></tr><tr><td></td><td></td><td></td></tr><tr><td></td><td style="POSITION: relative; height: 0px;"></td><td></td></tr></table>';
	document.getElementById(id).innerHTML = h;
	
	var idTag = id.replace("ucrad_", "");

	var tempVar = window.setTimeout("compRoot.compCreateAsChild(compRoot.spaceInstListEditComp, \"" + id + "\", \"&youcrad_markId=" + idTag + "&youcrad_isVisitorElement=" + isVisitorElement + "&youcrad_name=" + name + "&youcrad_partnerUserId=" + partnerUserId + "&youcrad_colorType=" + colorType + "&youcrad_objType=" + objType + "&youcrad_vertical=" + vertical + "&youcrad_totalInstCount=" + totalInstCount + "&youcrad_placeType=" + placeType + "&youcrad_objAlign=" + objAlign + "\");", 0);
	
	tempVar = null;
	
//	window.setTimeout("document.getElementById('"+id+"').style.height = '0px';",0); // to adjust height variation .... doesn't work here.
}

compRoot.triggerMarkInstance = function(theElement) {
	if ((compRoot.currentTargetMarkId != "")&&(compRoot.currentTargetMarkId == theElement.youcrad_markId)){
	    compRoot.markInstAddRelease(compRoot.currentTargetMarkId);
	    return;
	}
	
	compRoot.markInstAddRelease(compRoot.currentTargetMarkId);	
	
	compRoot.currentTargetMarkId = theElement.youcrad_markId;
	compRoot.currentTargetPlaceType = theElement.placeType;
	if (compRoot.useFixedWidget==1){
	    compRoot.compShow(compRoot.baseMaxComp);
	} else {
	    if (document.getElementById("youcrad_showSearchWindow")) document.getElementById("youcrad_showSearchWindow").click();
	}
	compRoot.markInstAddReady();
	document.getElementById(compRoot.markInstListComp).isdragged = "Y";
}

compRoot.triggerSpaceInstance = function(theElement) {
	if ((compRoot.currentTargetSpaceId != "")&&(compRoot.currentTargetSpaceId == theElement.youcrad_markId)){
	    compRoot.spaceInstAddRelease(compRoot.currentTargetSpaceId);
	    return;
	}

    compRoot.spaceInstAddRelease(compRoot.currentTargetSpaceId);
    	
    if (compRoot.currentTargetSpaceId != "") return;
	compRoot.currentTargetSpaceId = theElement.youcrad_markId;
	compRoot.currentTargetPlaceType = theElement.placeType;
	compRoot.spaceInstAddReady(compRoot.currentTargetSpaceId);
	if (compRoot.useFixedWidget==1){
	    compRoot.compShow(compRoot.baseMaxComp);
	} else {
	    if (document.getElementById("youcrad_showSearchWindow")) document.getElementById("youcrad_showSearchWindow").click();
	}
}

compRoot.markInstAddReady = function() {
	if (document.getElementById("youcrad_partnerMarkFrame")) document.getElementById("youcrad_partnerMarkFrame").style.border = "2px solid black";
}

compRoot.markInstAddRelease = function() {
	if (document.getElementById("youcrad_partnerMarkFrame")) document.getElementById("youcrad_partnerMarkFrame").style.border = "";
    compRoot.currentTargetMarkId = "";
    compRoot.currentTargetPlaceType = "";
}

compRoot.spaceInstAddReady = function(markId) {
	if (document.getElementById(compRoot.spaceInstListEditComp + "_ucrad_" + markId)) document.getElementById(compRoot.spaceInstListEditComp + "_ucrad_" + markId).style.border = "2px solid black";
}

compRoot.spaceInstAddRelease = function(markId) {
	if (document.getElementById(compRoot.spaceInstListEditComp + "_ucrad_" + markId)) document.getElementById(compRoot.spaceInstListEditComp + "_ucrad_" + markId).style.border = "";
    compRoot.currentTargetSpaceId = "";
    compRoot.currentTargetPlaceType = "";
}

compRoot.insertInstance = function(placeElement, adsPlace) {
    if ((parseInt(compRoot.authStatus)<2) || (compRoot.selectedAdObjectId == "" || compRoot.selectedAdObjectId == null)) {
        return;
    }
    
//    if (placeElement.placeType=="O") {
//        compRoot.finalizePublish();
//        compRoot.alertMsg("오버추어 광고영역에는 광고를 추가하실 수 없습니다.");
//        return;
//    }
    
    if ((placeElement.placeType!=compRoot.dragMark.placeType)){
        compRoot.finalizePublish();
        compRoot.alertMsg("종류가 다른 광고를 한 곳에 배포하실 수 없습니다.");
        return;
    }
    
    
	var markId = placeElement.youcrad_markId;
	var currentCount = placeElement.totalInstCount;
	var isVisitorElement = parseInt(compRoot.isVisitorElement( placeElement.name, placeElement.partnerUserId));
//	  alert("placeElement.name = " + placeElement.name + " placeElement.partnerUserId = " + placeElement.partnerUserId + " is Visitor = " + isVisitorElement);
//    alert(currentCount);

    if ((parseInt(compRoot.authStatus)==4)&&(isVisitorElement==1)) {
        compRoot.finalizePublish();
        compRoot.alertMsg("글작성자님은 방문자용 영역에 광고를 배포하실 수 없습니다.");
        return;
    } else if ((parseInt(compRoot.authStatus)==2)&&(isVisitorElement==0)) {
        compRoot.finalizePublish();
        compRoot.alertMsg("글방문자는 글쓴이용 영역에 광고를 배포하실 수 없습니다.");
        return;
    } else {
	    if (adsPlace == "adspace") { // do insert on adspace
		    if (currentCount < compRoot.spaceInstLimit) {
			    compRoot.createSpaceInstance(markId);
			    return;
		    } else {
			    compRoot.finalizePublish();
			    alert("애드스페이스에는 광고를 " + compRoot.spaceInstLimit + " 개까지 배포하실 수 있습니다.");
			    return;
		    }
	    } else if (adsPlace == "admark") { // do insert on admark
		    if (currentCount < compRoot.markInstLimit) {
			    compRoot.createMarkInstance(markId);
			    return;
		    } else {
			    compRoot.finalizePublish();
			    alert("애드마크에는 광고를 " + compRoot.markInstLimit + " 개까지 배포하실 수 있습니다.");
			    return;
		    }
	    }
	} // else {
	
}

compRoot.createMarkInstance = function(Mark_ID) {
//    window.event.cancelBubble = true;
    if (compRoot.selectedAdObjectId == "" || compRoot.selectedAdObjectId == null) {
        alert("선택된 광고가 없습니다. 오른쪽의 광고 선택창에서 광고를 선택한 후에 다시 시도하십시오.");
        return;
    }

    if (parseInt(compRoot.authStatus) == 4) {
//    	alert("글작성자님은 애드마크형 광고를 배포할 수 없습니다. \n 광고를 배포하시려면 애드스페이스를 이용하세요");
//    	compRoot.finalizePublish();
//    	return;
    }

    for (var i = 0; i < compRoot.markInstObjKeys.length; i++) {
        if ((compRoot.markInstObjKeys[i]) == (compRoot.selectedAdObjectId)) {
            clearTimeout(compRoot.widgetTimeOut);
            alert("동일한 광고가 배포되어 있습니다. 다른 광고를 선택해 주세요.");
            compRoot.finalizePublish();         
            return;
        }
    }

    var Url = compRoot.targetUrl + compRoot.procCallTarget;
    Url += "?funcName=ptrAdInstCreate";
    Url += "&Mark_ID=" + Mark_ID + "&Mark_Board_ID=" + compRoot.boardId + "&Ad_Object_ID=" + compRoot.selectedAdObjectId + "&UCRAD_ID=" + compRoot.authedId;
    
//	  compRoot.dragMark.keyword = null;
//    compRoot.dragMark.rank = null;
//    compRoot.dragMark.curcpc = null;

	Url += "&youcrad_searchKeyword=" + compRoot.dragMark.keyword;
	Url += "&youcrad_rank=" + compRoot.dragMark.rank;
	Url += "&youcrad_currnetCPC=" + compRoot.dragMark.curcpc;
	Url += "&youcrad_pSize=" + compRoot.dragMark.pSize;
	Url += "&youcrad_placeType=" + compRoot.dragMark.placeType;   
    Url += "&youcrad_objType=" + compRoot.dragMark.objType;   


    compRoot.addScript(Url, "compRoot.createMarkInstanceCallBack");
    compRoot.selectedAdObjectId = "";

    compRoot.finalizePublish();
    if (document.getElementById("youcrad_btnMin")) compRoot.widgetTimeOut = window.setTimeout("document.getElementById(\"youcrad_btnMin\").click();", 200);

}

compRoot.createMarkInstanceCallBack = function(funcName,oj) {
	if (document.getElementById("ucrad_" + oj.res._markId)&&(parseInt(oj.res._status) == 1)) {
		compRoot.markInstObjKeys.push(oj.res._adObjId);
		document.getElementById("ucrad_" + oj.res._markId).totalInstCount = parseInt(document.getElementById("ucrad_" + oj.res._markId).totalInstCount) + 1;
		compRoot.showMarkAds("ucrad_" + oj.res._markId);
	} else {
		alert("광고가 추가되지 않았습니다.");
	}
}

compRoot.createSpaceInstance = function(Mark_ID) {

	if (compRoot.selectedAdObjectId == "" || compRoot.selectedAdObjectId == null) {
		alert("선택된 광고가 없습니다. 오른쪽의 광고 선택창에서 광고를 선택한 후에 다시 시도하십시오.");
		compRoot.finalizePublish();
		return;
	}

	for (var i = 0; i < compRoot.spaceInstObjKeys.length; i++) {
		if ((compRoot.spaceInstObjKeys[i]) == (compRoot.selectedAdObjectId)) {
		    alert("동일한 광고가 배포되어 있습니다. 다른 광고를 선택해 주세요.");
		    compRoot.finalizePublish();
			return;
		}
	}

	var Url = compRoot.targetUrl + compRoot.procCallTarget;
	Url += "?funcName=ptrAdInstCreate";
	Url += "&Mark_ID=" + Mark_ID + "&Mark_Board_ID=" + compRoot.boardId + "&Ad_Object_ID=" + compRoot.selectedAdObjectId + "&UCRAD_ID=" + compRoot.authedId;

//	  compRoot.dragMark.keyword = null;
//    compRoot.dragMark.rank = null;
//    compRoot.dragMark.curcpc = null;

	Url += "&youcrad_searchKeyword=" + compRoot.dragMark.keyword;
	Url += "&youcrad_rank=" + compRoot.dragMark.rank;
	Url += "&youcrad_currnetCPC=" + compRoot.dragMark.curcpc;
	Url += "&youcrad_pSize=" + compRoot.dragMark.pSize;
	Url += "&youcrad_placeType=" + compRoot.dragMark.placeType;   
	Url += "&youcrad_objType=" + compRoot.dragMark.objType;   
	
	compRoot.addScript(Url, "compRoot.createSpaceInstanceCallBack");
    
	compRoot.selectedAdObjectId = "";

	compRoot.finalizePublish();
	if (document.getElementById("youcrad_btnMin")) compRoot.widgetTimeOut = window.setTimeout("document.getElementById(\"youcrad_btnMin\").click();", 50);

}

compRoot.createSpaceInstanceCallBack = function(funcName,oj) {
	if (parseInt(oj.res._status) == 1) {
		compRoot.spaceInstObjKeys.push(oj.res._adObjId);
		document.getElementById("ucrad_" + oj.res._markId).totalInstCount = 1 + parseInt(document.getElementById("ucrad_" + oj.res._markId).totalInstCount);
		compRoot.openAdSpace("ucrad_" + oj.res._markId);
	} else {
		alert("광고가 추가되지 않았습니다.");
	}
}

//____________________________________________________

compRoot.compHide = function(compName) {
//   if (compName==compRoot.baseMinComp){
//        compRoot.compDestroy(compName);
//   } else { 
        if (compRoot.instanceArray[compName])
            compRoot.instanceArray[compName].hideComp();
//   }
}

compRoot.compShow = function(compName, left, top) {
	if (compRoot.instanceArray[compName]) {
		compRoot.instanceArray[compName].showComp(left, top);
	} else {
		if (compName == compRoot.baseMaxComp) {
			compRoot.compCreate(compName, null, left, top);
			compRoot.compCreate("266");
			compRoot.compCreate("409");

			compRoot.compCreate("316");
			compRoot.compCreate("301"); // ListEmpty
			
//			compRoot.compCreate("304"); // AdsList

		} else {
			compRoot.compCreate(compName, null, left, top);
		}

	}
	window.setTimeout("compRoot.setWidgetXPosition();", 0);
}

compRoot.callLoginBox = function() {
	if ((compRoot.currentWidgetObject) && (compRoot.currentWidgetObject.id == compRoot.baseMinComp))
		document.getElementById("youcrad_showSearchWindow").click();
	
	compRoot.compCreate("313");
}

compRoot.compCreate = function(compName, addParams, left, top) {
    if (!(compRoot.compArray[compName])) return;
    
    var baseFrame = compRoot.compArray[compName].baseFrame;

    if (!(compRoot.instanceArray[compName])) {
        compRoot.instanceArray[compName] = new compRoot(compName, baseFrame, false, addParams, left, top);
//        var pseudoVar = setTimeout("compRoot.showImage(\"" + compRoot.instanceArray[compName].idValue + "\")", 0);
//        pseudoVar = null;
    }

    if ((compName == compRoot.baseMinComp) || (compName == compRoot.baseMaxComp)) {
//    if ((compName == compRoot.baseMinComp)) {
        compRoot.setDrag(compName, "v");
    }
}

compRoot.compCreateAsChild = function(compName, baseFrame, addParams, left, top) {
//	if (!(compRoot.instanceArray[compName + "_" + baseFrame])) {
	if (compRoot.compDestroy(compName + "_" + baseFrame)) {
		compRoot.instanceArray[compName + "_" + baseFrame] = new compRoot(compName, baseFrame, false, addParams, left, top, true);
//		var pseudoVar = setTimeout("compRoot.showImage(\"" + compRoot.instanceArray[compName + "_" + baseFrame].idValue + "\")", 0);
//		pseudoVar = null;
		
//		if ((parseInt(compRoot.authStatus) == 4)&&(compName == compRoot.spaceInstListEditComp)){ 
		if ((compName == compRoot.spaceInstListEditComp)){   //// Now open to everybody, not only author
			document.getElementById(compName + "_" + baseFrame).onclick = function() { compRoot.insertInstance(this, "adspace"); }
            document.getElementById(compName + "_" + baseFrame).youcrad_markId = baseFrame.replace("ucrad_", ""); 
            document.getElementById(compName + "_" + baseFrame).name = document.getElementById(baseFrame).name;
            document.getElementById(compName + "_" + baseFrame).partnerUserId = document.getElementById(baseFrame).partnerUserId;
            document.getElementById(compName + "_" + baseFrame).placeType = document.getElementById(baseFrame).placeType;
            document.getElementById(compName + "_" + baseFrame).totalInstCount = document.getElementById(baseFrame).totalInstCount;
        }
	} 
}

compRoot.compDestroy = function(compName) {
    if (!(compRoot.instanceArray[compName])) return true;

    for (var comp in compRoot.instanceArray){
         if ( ( (comp.lastIndexOf("@" + compName) > -1) && (comp.lastIndexOf("@" + compName) == ( comp.length - compName.length - 1))) ){
            if (compRoot.instanceArray[comp]) compRoot.instanceArray[comp].destroyComp();    
         }
    }
      //compRoot.killBgLayer();

    if (compRoot.instanceArray[compName]) compRoot.instanceArray[compName].destroyComp();    
    if (compRoot.compArray[compName] && compRoot.compArray[compName].baseFrame == "frameMiddle") document.getElementById("frameMiddle").firstChild.style.display = "block";
    
//    var errNoticeElements= compRoot.getElementsByClassName("ucr_err_" + compName, "DIV");
//    for (var i = 0; i < errNoticeElements.length; i++){
//        document.body.removeChild(errNoticeElements[i]);
//    }

    if (compRoot.errorElement) compRoot.errorElement.style.visibility = "hidden";
      
    return true;
}

compRoot.compReplace = function(compName, addParams, left, top) {
    //   alert(compRoot.compArray[compName].baseFrame);
    if (compRoot.instanceArray[compName]) compRoot.compDestroy(compName);

    for (var comp in compRoot.instanceArray) {
        if ((compRoot.compArray[compName])&&(compRoot.compArray[comp] != null) && (compRoot.instanceArray[comp] != null))
            if ((compRoot.compArray[compName])&&(compRoot.compArray[comp])&&(compRoot.compArray[comp].baseFrame == compRoot.compArray[compName].baseFrame))
                if (parseInt(compRoot.compArray[compName].isRel) != 0) compRoot.compDestroy(comp);
    }

    compRoot.compCreate(compName, addParams, left, top);
//    compRoot.addPagingHistory(compName);
}

//compRoot.compSetDhtml = function(){
//   for ( var comp in compRoot.compArray) {
//      SET_DHTML(comp);
//   }
//}

compRoot.goHome = function(){

    if (compRoot.homeComp == "") {
        return;
    }  else {
        if (parseInt(compRoot.compArray[compRoot.homeComp].isRel) != 0) {
            compRoot.compReplace(compRoot.homeComp);
        } else {
            compRoot.compCreate(compRoot.homeComp);
        }
    }
}

compRoot.reloadPage = function() {
    var tempArray = new Array();
    for (var comp in compRoot.instanceArray) {
        if ((comp.indexOf("@") < 0) && (parseInt(compRoot.compArray[comp].isInitComp) == 0))
            tempArray[comp] = comp;
    }

    for (var comp in compRoot.instanceArray) {
        if ((comp.indexOf("@") < 0)) {
            compRoot.compDestroy(comp);
        }
    }

    compRoot.compCreate(compRoot.initializeComp);

    for (var comp in tempArray) {
        compRoot.compCreate(comp);
    }
}

compRoot.loadCompWHtml = function(oj) {
    compRoot.compArray = oj.comps;
    compRoot.compHtmlArray = oj.htmls;
    compRoot.funcArray = oj.funcs;

    for (var i=0; i<compRoot.urlRegistered.length; i++){
        if (document.URL == compRoot.urlRegistered[i]) compRoot.flagRegistered = true;
    }
    
    if (compRoot.flagRegistered) compRoot.compCreate(compRoot.initializeComp);
}

// to load the intiative Html parts of all components considered to be rendered later on
// the callback of this function includes setting the initiative actions -  compRoot.compInstanceInitialize()

///////////////////////////////////////////////////////____ Scripts for graphic functionality from here_________________________________________
function setPng24(obj) {
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseFloat(navigator.appVersion.split("MSIE")[1]);

    if ((browser == "Microsoft Internet Explorer")&&(version == 6)){
        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 '';
    }
}

function youcrad_showHide(youcrad_divId) {
    if( document.getElementById(youcrad_divId).style.display == "" )
       document.getElementById(youcrad_divId).style.display = "none";
    else
        document.getElementById(youcrad_divId).style.display = "";
}

function autoBlur() {
    if (event.srcElement.tagName == "A" || event.srcElement.tagName == "IMG")
        document.body.focus();
}

//document.onfocusin = autoBlur;

function showLocalImage() {

    document.getElementById("youcrad_btnFindImage").src = (compRoot.tempAdOjImagePath != "") ? compRoot.tempAdOjImagePath : compRoot.imageUrlBase + compRoot.tempAdOjImagePathDefault;
    
}

function showLocalImageSeq(seq) {

    document.getElementById("youcrad_btnFindImage"+seq).src = (compRoot.tempAdOjImagePath != "") ? compRoot.tempAdOjImagePath : compRoot.imageUrlBase + compRoot.tempAdOjImagePathDefault;
    
}

function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (var i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; } 
    }
}


function MM_findObj(n, d) { //v4.01
    var p, i, x;
    if (!d) d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n];
    for (var i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (var i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n);
    return x;
}

function _youcrad_fixSubMenu(theElement) {
	//       	var theElement = window.event.srcElement;
	var subMenus = document.getElementsByName(theElement.name);
	var tempString, tempString2;

	for (var i = 0; i < subMenus.length; i++) {
		if (subMenus[i] == theElement) {
			//       				alert(theElement.name);
			tempString = theElement.src.replace(eval("/_off/g"), "_on")
			theElement.src = tempString;
			theElement.ooSrc = tempString;
			theElement.oSrc = tempString;
		} else {
			tempString = subMenus[i].src.replace(eval("/_on/g"), "_off");
			tempString2 = subMenus[i].src.replace(eval("/_off/g"), "_on");
			subMenus[i].src = tempString;
			subMenus[i].ooSrc = tempString2;
		}
	}
}

function _youcrad_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 '';
}

function _youcrad_autoBlur() {
    if (event.srcElement.tagName == "A" || event.srcElement.tagName == "IMG")
        document.body.focus();
}

function _youcrad_showLocalImage(imgname) {
    document.getElementById("youcrad_btnFindImage").src = imgname;
}

function _youcrad_MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (var i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; } 
    }
}

function _youcrad_MM_swapImgRestore() { //v3.0
	var i, x, a = document.MM_sr;
	//         for (var i = 0; a && (i < a.length) && (x = a[i]) && (x.oSrc); i++) {
	//         	x.src = x.oSrc;
	//         }
	var el = window.event.srcElement;
	el.src = el.oSrc;
}

function MM_swapImgRestore() { //v3.0
	var i, x, a = document.MM_sr;
	//         for (var i = 0; a && (i < a.length) && (x = a[i]) && (x.oSrc); i++) {
	//         	x.src = x.oSrc;
	//         }
	var el = window.event.srcElement;
	el.src = el.oSrc;
}

function _youcrad_MM_findObj(n, d) { //v4.01
    var p, i, x;

    if (!d) d = document;

    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n];
    for (var i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (var i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n);

    return x;
}
//    onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('youcrad_btnX','','images/btn_x_on.gif',1)"
function _youcrad_MM_swapImage() { //v3.0
	var i, j = 0, x, a = _youcrad_MM_swapImage.arguments;
	var el = window.event.srcElement;
	document.MM_sr = new Array;
	for (var i = 0; i < (a.length - 2); i += 3) {
		if (!el.ooSrc) {
			document.MM_sr[j++] = el;
			if (!el.oSrc) el.oSrc = el.src;
			el.src = a[i + 2];
		} else {
			//       			document.MM_sr[j++] = el;
			el.oSrc = el.src;
			el.src = el.ooSrc;
		}
	}

}

function MM_swapImage() { //v3.0
	var i, j = 0, x, a = MM_swapImage.arguments;
	var el = window.event.srcElement;
	document.MM_sr = new Array;
	for (var i = 0; i < (a.length - 2); i += 3) {
		if (!el.ooSrc) {
			document.MM_sr[j++] = el;
			if (!el.oSrc) el.oSrc = el.src;
			el.src = a[i + 2];
		} else {
			//       			document.MM_sr[j++] = el;
			el.oSrc = el.src;
			el.src = el.ooSrc;
		}
	}
}

//____ Scripts for graphic functionality until here_________________________________________

///////////////////////////////////////////////////////____ Scripts for complementary functionality from here_________________________________________
function stringLeft(str, n){
   if (n <= 0)
       return "";
   else if (n > String(str).length)
       return str;
   else
       return String(str).substring(0,n);
}

function stringRight(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function stopEvent(evt) {
    if (evt.stopPropagation) {
        evt.stopPropagation();
        evt.preventDefault();
    } else if (typeof evt.cancelBubble != "undefined") {
        evt.cancelBubble = true;
        evt.returnValue = false;
    }
    return false;
}

function checkImageFileType(file) {
	var extArray = new Array(".gif", ".jpg", ".png");
	allowSubmit = false;
	if (!file) return;
	while (file.indexOf("\\") != -1)
		file = file.slice(file.indexOf("\\") + 1);
	ext = file.slice(file.indexOf(".")).toLowerCase();
	
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) { allowSubmit = true; break; }
	}
	if (allowSubmit) {
		return true;
	} else {
	alert("광고이미지로는 " + (extArray.join(" ")) + " 파일을 이용해주시기 바랍니다..");
	return false;
	}
}

function stopDragPropagation(element) {
    var evt = window.event;
    if (evt.stopPropagation) {
        evt.stopPropagation();
        evt.preventDefault();
    } else if (typeof evt.cancelBubble != "undefined") {
        evt.cancelBubble = true;
        evt.returnValue = false;
    }
    if (element) element.style.cursor = "default"
    return false;
}

function runOnEnterKey(targetFunction) {
    var codecode = event.keyCode;
    var returnValue = false;
    event.returnValue = false;
    if (codecode == 13) {
        targetFunction();
    }
}

function setHiddenSvrCall(hiddenElementId, theValue, targetElementId) {

    document.getElementById(hiddenElementId).value = (theValue);
    document.getElementById(targetElementId).click();
}



 function checkStrLength(displayElement){

       var temp;
       var theElement = window.event.srcElement;
       var f = theElement.value.length;
       var msglen = 80; //최대 길이
       var tmpstr = "";
       var enter = 0;
       var strlen;
//      alert(theElement.id);
       if(f == 0){
            if (displayElement!=null) displayElement.innerHTML = msglen;
       } else {
              for (var k=0;k<f;k++)
              {
                  temp = theElement.value.charAt(k);
                  
                  if(temp == '\n')
                  {
                     enter++;
                  }

                  if(escape(temp).length > 4)
                     msglen = msglen - 2;
                  else
                     msglen = msglen - 1.3;

                  if(msglen < 0)
                  {
                      alert("총 영문 80자 한글 40자 까지 쓰실 수 있습니다.");
                      theElement.value = tmpstr;
                      break;

                  } else if (Math.round(theElement.createTextRange().boundingHeight/15) > 2){
                      alert("자동라인수 2라인을 넘을수 없습니다.");
                      tempstr =  theElement.value; 
                      for (var i=0; i<tempstr.length;i++){
                        theElement.value = tempstr.substring(0, tempstr.length - i - 1);
                        if (Math.round(theElement.createTextRange().boundingHeight/15) == 2) break;
                     } 
                     
                     break;
                  } else if (enter > 1) {
                      alert("라인수 2라인을 넘을수 없습니다.");
                      enter = 0;
                      strlen = tmpstr.length - 1;
                      //alert(strlen);
                      theElement.value = tmpstr.substring(0,strlen);
                      break;
                   } else {
                      if (displayElement!=null) displayElement.innerHTML = Math.floor(msglen);
                      tmpstr += temp;
                  }
                 }
             }
 }

function convImageToNumber(elementId, numString, numSlot){
   var returnHTML = "<table border='0' cellpadding='0' cellspacing='0'><tr>";
   
   for (var i=0; i<numSlot; i++){
      if (i < numSlot - numString.length) {
         returnHTML += "<TD align=left width=20><IMG src='"+ compRoot.imageUrlBase +"images/adv_number10.gif' align=absMiddle border=0></TD>" 
      } else {
         returnHTML += "<TD align=left width=20><IMG src='"+ compRoot.imageUrlBase +"images/adv_number0" + (numString.charAt(i - numSlot + numString.length))+ ".gif' align=absMiddle border=0></TD>" 
      }
      if (((numSlot - i - 1) != 0) && ((numSlot - i - 1)%3 == 0)) returnHTML += "<TD vAlign=bottom><IMG src='"+ compRoot.imageUrlBase +"images/adv_icon_com.gif' align=absMiddle border=0></TD>"    
   }

   returnHTML += "</tr></table>";
   
   document.getElementById(elementId).innerHTML = returnHTML;
}

compRoot.markIconDisplay = function(currentColor) {

	var returnString = "";

	for( var i =0; i<6; i++){

		if (i == currentColor) {
			returnString += '<td width="40" height="30" align="center" valign="middle">';
			returnString += '<table width="30" height="24" style="border:solid #ff9933 2px " cellpadding="0" cellspacing="0">';
			returnString += '<tr><td align="center" valign="middle" onclick="javascript:document.getElementById(\'youcrad_colorType\').value=' + i + ';youcrad_iconBtnOk.click();" onmouseover="this.style.backgroundColor=\'#f3f3f3\'" onmouseout="this.style.backgroundColor=\'#ffffff\'"><img src="' + compRoot.imageUrlBase + 'images/admark' + i + '.gif" border="0" style="cursor:pointer"></td></tr></table></td>'
		} else {
			returnString += '<td width="40" height="30" align="center" valign="middle">';
			returnString += '<table width="30" height="24" border="0" cellpadding="0" cellspacing="1" bgcolor="#ffffff" onmouseover="this.style.backgroundColor=\'#fc7803\'" onmouseout="this.style.backgroundColor=\'#ffffff\'">';
			returnString += '<tr><td align="center" valign="middle" onclick="javascript:document.getElementById(\'youcrad_colorType\').value=' + i + ';youcrad_iconBtnOk.click();" onmouseover="this.style.backgroundColor=\'#f3f3f3\'" onmouseout="this.style.backgroundColor=\'#ffffff\'"><img src="' + compRoot.imageUrlBase + 'images/admark' + i + '.gif" border="0" style="cursor:pointer"></td></tr></table></td>';
		}

	}
	return returnString;
}

compRoot.spaceBgDisplay = function(currentColor) {

	var returnString = '      <table border="0" cellpadding="0" cellspacing="0"> <tr>';

	for (var i = 0; i < 16; i++) {

		if (i == currentColor) {
			returnString += '<td width="36" height="30" align="center" valign="middle"><table onclick="spaceBgTiles.innerHTML=compRoot.spaceBgDisplay('+i+');youcrad_colorType.value='+i+';" width="30" height="24" style="border:solid #ff9933 2px;cursor:pointer;" cellpadding="0" cellspacing="1" bgcolor="#eeeeee" onmouseover="this.style.backgroundColor=\'#fc7803\'" onmouseout="this.style.backgroundColor=\'#eeeeee\'"><tr><td style="background-color:#ffffff;" background="' + compRoot.imageUrlBase + 'images/p_bg_sp_' + i + '00.gif"></td></tr></table></td>';
		} else {
			returnString += '<td width="36" height="30" align="center" valign="middle"><table onclick="spaceBgTiles.innerHTML=compRoot.spaceBgDisplay(' + i + ');youcrad_colorType.value=' + i + ';" width="30" height="24" style="border:none;cursor:pointer;" cellpadding="0" cellspacing="1" bgcolor="#eeeeee" onmouseover="this.style.backgroundColor=\'#fc7803\'" onmouseout="this.style.backgroundColor=\'#eeeeee\'"><tr><td style="background-color:#ffffff;" background="' + compRoot.imageUrlBase + 'images/p_bg_sp_' + i + '00.gif"></td></tr></table></td>';
		}


		if (i == 7)
			returnString += "</tr><tr>";
	}

	returnString += "</tr></table>";

	return returnString;
}

function adContentLimiter() {

    var codecode = event.keyCode;
    var theTextarea = event.srcElement;
    var inputString = theTextarea.value;
    var beforeReturnCount = inputString.split("\n").length - 1;

    if ((codecode == 8) || (codecode == 21) || (codecode == 25) || (codecode == 45) || (codecode == 46) || ((codecode >= 33) && (codecode <= 40))) return;

    if (inputString.length > 40) { alert("광고내용은 한글 40 자를 넘을 수 없습니다."); event.returnValue = false; }

    if ((codecode != 13) && (beforeReturnCount == 1) && ((inputString.split("\n")[0].length > 20) || (inputString.split("\n")[1].length > 20))) {
        alert("한 줄당 한글 20 자를 넘을 수 없습니다."); event.returnValue = false;
    }

    ////// should include cursor position & get the expected length of split //////////////////////
    //      	if ((codecode == 13) && (beforeReturnCount ==0) && ((inputString.split("\n")[0].length > 20) || (inputString.split("\n")[1].length > 20))) {
    //      	   alert("Row length limited as of 20 characters"); event.returnValue = false;
    //      	}
    if ((codecode == 13) && (beforeReturnCount > 0)) { alert("광고내용은 두 줄 이상 입력하실 수 없습니다."); event.returnValue = false; }
}

function checkEnterKey() {
    var codecode = event.keyCode;
    var returnValue = false;
    if (codecode == 13) returnValue = true;
    return returnValue;
}

function selectOptionValue(valueString) {

    for (var i = 0; i < this.children.length - 1; i++) {
        if (this.children(i).value == valueString) { this.children(i).selected = true; return; }
    }

}

function ifEnterKeyDoClick(elementId) {
    var codecode = event.keyCode;
    var returnValue = false;
    
    if (codecode == 13) {
        document.getElementById(elementId).click();
        stopEvent(window.event)
    }
}

function ifEnterKeyDoClick_stop(evt) {
//    if (evt.stopPropagation) {
//        evt.stopPropagation();
//        evt.preventDefault();
//    } else if (typeof evt.cancelBubble != "undefined") {
//        evt.cancelBubble = true;
//        evt.returnValue = false;
//    }
//    return false;
}

function goVoid() {
}

/* Javascript Console*/
/*^ $ \ / ( ) | ? + * [ ] { } , . */
       function validateForm(patternType, e, el) {
       
        var theElement;
    
        theElement = (e)?e.srcElement:el;
       
       	compRoot.clearDefault(theElement);
       	var str = theElement.value;
       	//                  var ptn_nonSpecialChar=/^[^\f\r\n\t\v\b\s`~!@#\$%\^&\*\(\)\-_\+=\|\\\[\]\{\}<>\.\,\/\?;:'"]+$/;
       	// to accept a DOT, HYPEN
       	var ptn_nonSpecialChar = /^[^\f\r\n\t\v\b\s`~!@#\$%\^&\*\(\)_\+=\|\\\[\]\{\}<>\,\/\?;:'"]+$/;
       	var ptn_nonSpace = /^[^\f\r\n\t\v\b\s]+$/;
       	var ptn_digitOnly = /^[0-9]+$/;
       	var ptn_emailAddress = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
       	var ptn_acceptAll = /.*/;
       	var msg = "";
       	var returnValue = 0;
       	var oj = { "msg": msg, "returnValue": 0, "fitSize": false, "sizeBand": false }; // fitSize default == false

       	switch (patternType) {
       		case (0):
       			var rxp = new RegExp(ptn_digitOnly);
       			if (theElement.checked) { str = "1"; } else { str = "a"; }
       			msg = "다음 단계로 진행하기 위해서는 체크해 주셔야 합니다.";
       			break;
       		case (1):
       			var rxp = new RegExp(ptn_nonSpecialChar);
       			msg = "띄어쓰기 없이 특수문자를 제외한 글자를 입력해주세요.";
       			break;
       		case (2):
       			var rxp = new RegExp(ptn_digitOnly);
       			msg = "띄어쓰기 없이 숫자로 입력해주세요.";
       			oj.fitSize = true;
       			break;
       		case (3):
       			var rxp = new RegExp(ptn_digitOnly);
       			msg = "띄어쓰기 없이 숫자로 입력해주세요.";
       			break;
       		case (4):
       			var rxp = new RegExp(ptn_nonSpace);
       			msg = "띄어쓰기 없이 입력해주세요";
       			//            oj.fitSize = true;
       			break;
       		case (5): // password 용도
       			var rxp = new RegExp(ptn_nonSpecialChar);
       			msg = "입력하신 비밀번호를 정확히 확인해 주세요";
       			//            oj.sizeBand = true;                 
       			break;
       		case (6): // type 1 + dup Check
       			var rxp = new RegExp(ptn_nonSpecialChar);
       			msg = "띄어쓰기나 특수문자 없이 입력하시고 중복체크를 해주셔야합니다.";
       			break;
       		case (7): // type 4 + dup Check
       			var rxp = new RegExp(ptn_digitOnly);
       			if (str != "") { } else { str = "1"; }
       			msg = "숫자로 입력하시고 중복체크를 해주셔야합니다.";
       			break;
       		case (8): // should not be empty and of digit
       			var rxp = new RegExp(ptn_digitOnly);
       			if (str != "") { str = "1"; } else { str = "a"; }
       			msg = "입력해 주세요.";
       			break;
       		case (9): // can be empty but should be of digit if any 
       			var rxp = new RegExp(ptn_digitOnly);
       			if (str != "") {  } else { str = "1"; }
       			msg = "숫자로 입력해 주세요.";
       			break;
       		case (10): // email pattern
       			var rxp = new RegExp(ptn_emailAddress);
       			msg = "email주소가 유효하지 않습니다.";
       			break;
           case (11): // accept all pattern even empty case
           	   var rxp = new RegExp(ptn_acceptAll);
           	   msg = "입력하지 않으셔도 됩니다";
           	   break;

       		default:
       			var rxp = new RegExp(ptn_nonSpecialChar);
       			msg = "띄어쓰기 없이 특수문자를 제외한 글자를 입력해주세요.";
       			break;
       	}

       	if (str.match(rxp) && ((oj.fitSize) ? (theElement.maxLength == str.length) : true) && ((theElement.minLength) ? ((theElement.minLength <= str.length)) : true)) {
       		oj.msg = msg;
       		oj.returnValue = 1;
       	} else {
       		oj.msg = msg + ((theElement.minLength) ? " " + theElement.minLength + "자 이상," + theElement.maxLength + "이하로 입력해 주세요" : "") + ((oj.fitSize) ? " " + theElement.maxLength + " 자로 입력해주셔야 합니다" : "");
       		oj.returnValue = 0;
       	}
       	compRoot.returnDefault(theElement);
       	return oj;
}


//returns the absolute position of some element within document   
var __isFireFox = navigator.userAgent.match(/gecko/i);

function GetElementAbsolutePos(element) {
    var res = new Object();
    res.x = 0; res.y = 0;
    if (element !== null) {
        res.x = element.offsetLeft;
        res.y = element.offsetTop;

        var offsetParent = element.offsetParent;
        var parentNode = element.parentNode;

        while (offsetParent !== null) {
            res.x += offsetParent.offsetLeft;
            res.y += offsetParent.offsetTop;

            if (offsetParent != document.body && offsetParent != document.documentElement) {
                res.x -= offsetParent.scrollLeft;
                res.y -= offsetParent.scrollTop;
            }
            //next lines are necessary to support FireFox problem with offsetParent   
            if (__isFireFox) {
                while (offsetParent != parentNode && parentNode !== null) {
                    res.x -= parentNode.scrollLeft;
                    res.y -= parentNode.scrollTop;

                    parentNode = parentNode.parentNode;
                }
            }
            parentNode = offsetParent.parentNode;
            offsetParent = offsetParent.offsetParent;
        }
    }
    return res;
}
///////////////////////////////////////////////////////____ Scripts for complementary functionality until here_________________________________________  

//_____ define process-specific functions from here _____________________________________________________
compRoot.flashMenuClick = function(funcName) {
   if(funcName && document.getElementById("youcrad_" + funcName)) 
      document.getElementById("youcrad_" + funcName).click();
}

compRoot.addFormControlHidden = function(controlId, theValue, mainComp) {

    var tempElement = document.createElement("input");
    tempElement.type = "hidden";
    tempElement.name = "_youcrad_formControl";
    tempElement.id = controlId;
    tempElement.value = theValue;
    mainComp.appendChild(tempElement);

    tempElement = null;
}

compRoot.addFormControlFile = function(theElement, mainComp) {
    var tempElement = document.createElement("input");
    tempElement.type = "file";
    tempElement.style.visibility = "hidden";
    tempElement.name = theElement.name;
    tempElement.alt = theElement.id;
    mainComp.appendChild(tempElement);
}

compRoot.openFileBox = function() {
    //document.getElementById("youcrad_uploadFile") = window.event.srcElement;

    //window.event.srcElement=document.getElementById("youcrad_uploadFile");
    //	document.getElementById("youcrad_uploadFile").click();
}

compRoot.showImage = function(compName) {

    if ((document.getElementById(compName)) && (compName != compRoot.initializeComp)) {  //// need to leave out the first component to prevent reInitiate the loading ///////////////

        var imgElement = document.getElementById(compName).getElementsByTagName("IMG");

        for (var i = 0; i < imgElement.length; i++) {
            if ((imgElement[i].onload == "") || (imgElement[i].onload == null)) imgElement[i].src = imgElement[i].src;
        }

    }
}

compRoot.setZipCode = function(zipCode1, zipCode2, zipAddress, zipSeq) {
    compRoot.compDestroy("334");
    document.getElementById("youcrad_zipCode1").value = zipCode1;
    document.getElementById("youcrad_zipCode2").value = zipCode2;
    document.getElementById("youcrad_zipSeq").value = zipSeq;
    document.getElementById("youcrad_bizAddress1").value = compRoot.removeHTMLTags(zipAddress);
}

compRoot.setAdOjSponsor = function(sponsorName, sponsorEmailFull, sponsorPhoneNo, sponsorFaxNo) {

    document.getElementById("youcrad_advName").value = sponsorName;
    document.getElementById("youcrad_advEmail").value = sponsorEmailFull;
    document.getElementById("youcrad_advPhone1").value = sponsorPhoneNo.split("-")[0];
    document.getElementById("youcrad_advPhone2").value = sponsorPhoneNo.split("-")[1];
    document.getElementById("youcrad_advPhone3").value = sponsorPhoneNo.split("-").length == 2 ? "" : sponsorPhoneNo.split("-")[2];
    document.getElementById("youcrad_advFax1").value = sponsorFaxNo.split("-")[0];
    document.getElementById("youcrad_advFax2").value = sponsorFaxNo.split("-")[1];
    document.getElementById("youcrad_advFax3").value = sponsorFaxNo.split("-").length == 2 ? "" : sponsorFaxNo.split("-")[2];
}

compRoot.removeHTMLTags = function(htmlString) {

    if (htmlString) {
        var mydiv = document.createElement("DIV");
        mydiv.innerHTML = htmlString;

        if (document.all) // IE Stuff
        {
            return mydiv.innerText;
        }
        else // Mozilla does not work with innerText
        {
            return mydiv.textContent;
        }
        mydiv = null;
    }
}

compRoot.addPagingHistory = function(compNo) {
    //	alert("a Page Added for compNo = " + compNo);
    compRoot.pagingHistory.splice(compRoot.currentPage, compRoot.pagingHistory.length, compNo);
    compRoot.currentPage += 1;
}

compRoot.moveToPage = function(delta) {
    //alert("page Number : " + compRoot.currentPage + " at Max : " + compRoot.pagingHistory.length);
    /*  
    if (compRoot.pagingHistory.length < 1) return;
    if (compRoot.pagingHistory.length < compRoot.currentPage + delta) return;
  
  compRoot.currentPage += delta;
 
  if (compRoot.currentPage < 1)  compRoot.currentPage = 1;
    if (compRoot.pagingHistory.length < compRoot.currentPage) compRoot.currentPage = compRoot.pagingHistory.length;
    if (compRoot.instanceArray[compRoot.pagingHistory[compRoot.currentPage-1]]) compRoot.compDestroy(compRoot.pagingHistory[compRoot.currentPage-1]);
    for (var comp in compRoot.instanceArray){
    if ((compRoot.compArray[comp] != null) && (compRoot.instanceArray[comp] != null))
    if ((compRoot.compArray[comp].baseFrame == compRoot.compArray[compRoot.pagingHistory[compRoot.currentPage-1]].baseFrame) || ((compRoot.compArray[comp].baseFrame == "frameMiddle") && (compRoot.compArray[compRoot.pagingHistory[compRoot.currentPage-1]].baseFrame == "subFrameMiddleMiddle")))
    compRoot.compDestroy(comp);
    }
    compRoot.compCreate(compRoot.pagingHistory[compRoot.currentPage-1]);
    */
}

compRoot.borderOn = function(element) {
	if ((compRoot.selectedAdObjectId !="")&&(compRoot.currentPublishMode=="SPACE"))
		element.style.border = "2px solid black";
}

compRoot.borderOut = function(element) {
	if (element.style.border != "") 
		element.style.border = "";
}

compRoot.clearDefault = function(element) {
	if ((element.defaultvalue != null) && (element.defaultvalue != "") && (element.value == element.defaultvalue)) element.value = "";
}

compRoot.returnDefault = function(element) {
	if ((element.defaultvalue != null) && (element.defaultvalue != "") && (element.value == "")) element.value = element.defaultvalue;
}

compRoot.checkFormControl = function(type, e, el) {
    var theElement = (e)?e.srcElement:el;
    var theParentElement = theElement.parentElement;
    var mainComp = (compRoot.findMainCompEl(theElement))?(compRoot.findMainCompEl(theElement)):(document.body);

	compRoot.clearDefault(theElement);
	if (document.getElementById(theElement.id).value) document.getElementById(theElement.id).value = document.getElementById(theElement.id).value.trim();

	var msg = validateForm(type, e, el).msg;
	var returnValue = validateForm(type, e, el).returnValue;

	// describe explicitly for better legibility here
	if (type == 5) { returnValue *= (document.getElementById("youcrad_pw1").value == theElement.value) ? 1 : 0; }
	if (type == 6) { returnValue *= parseInt(document.getElementById(theElement.id + "DupChecked").value); }
	if ((type == 7) && (document.getElementById(theElement.id).value!="")) { returnValue *= parseInt(document.getElementById(theElement.id + "DupChecked").value); }

	theElement.title = "";

	if (returnValue > 0) {
		if ((theElement.className == "youcrad_inputalert") || (theElement.className == "youcrad_focus")) {
			theElement.className = theElement.alt;
			theElement.alt = "";
			theElement.title = "";
			theElement.errorString = null;
		    theElement.onmouseover = null;
		    theElement,onmouseout = null;
		}
	} else {
		if ((theElement.alt == "") || theElement.alt == null) theElement.alt = theElement.className;
		theElement.className = "youcrad_inputalert";
		theElement.title = msg;
		theElement.errorString = msg;
	}
	
	if (e&&e.type=="blur") compRoot.errorElement.style.visibility = "hidden";

	return returnValue;
}


compRoot.onFocusHighlight = function(elementId) {

    if (document.getElementById(elementId)) {
        var el = document.getElementById(elementId);
    } else {
        return;
    }
    //  alert(elementId); 
    if ((el.alt == "") || (el.alt == null)) { el.alt = el.className; }
    if (!(el.readOnly)) { el.className = "youcrad_focus"; }
    //   el.title = "";
}

compRoot.enableControls = function(controlArray) {
    if ((controlArray != null) && (controlArray.length > 0)) {
        for (var i = 0; i < controlArray.length; i++) {
            controlArray[i].disabled = false;
            if (controlArray[i].className == "youcrad_inputalert") {
                controlArray[i].className = controlArray[i].alt;
                controlArray[i].alt = "";
                controlArray[i].title = "";
            }
            controlArray[i].value = "";
        }
    }
}

compRoot.disableControls = function(controlArray) {
    if ((controlArray != null) && (controlArray.length > 0)) {
        for (var i = 0; i < controlArray.length; i++) {
            if (controlArray[i].className == "youcrad_inputalert") {
                controlArray[i].className = controlArray[i].alt;
                controlArray[i].alt = "";
                controlArray[i].title = "";
            }
            controlArray[i].value = "";
            controlArray[i].disabled = true;

        }
    }
}

compRoot.findMainComp = function(elementId) {
    //	alert(elementId);
   if (document.getElementById(elementId) != null){
    var recurElement = document.getElementById(elementId).parentElement;
    var searchingFlag = true;
    var mainCompName = "";

    while (searchingFlag && recurElement) {
        if (recurElement.iscomp == "_youcradComp") {
            mainCompName = recurElement.id.substring(recurElement.id.lastIndexOf("@") + 1);
            //            mainCompName = recurElement.id;
            searchingFlag = false;
        } else {
            recurElement = recurElement.parentElement;
        }
    }
    //alert(mainCompName);
    return (searchingFlag) ? document.getElementById(elementId) : document.getElementById(mainCompName);
   } else {
      return null;
   }
}


compRoot.findMainCompEl = function(element) {
	//	alert(elementId);
	var recurElement = element.parentElement;
	var searchingFlag = true;
	var mainCompName = "";

	while (searchingFlag && recurElement) {
		if (recurElement.iscomp == "_youcradComp") {
			mainCompName = recurElement.id.substring(recurElement.id.lastIndexOf("@") + 1);
			//            mainCompName = recurElement.id;
			searchingFlag = false;
		} else {
			recurElement = recurElement.parentElement;
		}
	}
	//alert(mainCompName);
	return (searchingFlag) ? element : document.getElementById(mainCompName);
}

compRoot.buildParamSpec = function(elements) {
    var oj = elements;
    var returnOj = { "queryString": "", "paramNum": 0, "returnValue": 1, "elements": {} };

    var queryString = "";
    var paramNum = 0;
    var returnValue = 1;
    var elements = new Array();

    if ((oj != null) && (oj.length > 0)) {
        paramNum = oj.length;
        for (var i = 0; i < oj.length; i++) {
            if ((oj[i].style.visibility == "hidden") || (oj[i].type == "hidden") || (oj[i].disabled) || (oj[i].readOnly) || ((oj[i].type == "radio")))
                continue;
         oj[i].focus();
         oj[i].blur();
//           if (oj[i].onchange) oj[i].onchange();
        }
        for (var i = 0; i < oj.length; i++) {
            if (((oj[i].disabled) && (oj[i].tagName != "SELECT")) || (oj[i].type == "radio"))
                continue;
            if (i < oj.length - 1)
                queryString += oj[i].id + "=" + encodeURIComponent(oj[i].value) + "&";
            else
                queryString += oj[i].id + "=" + encodeURIComponent(oj[i].value);

            returnValue = returnValue * ((oj[i].title != "") ? 0 : 1);

            elements.push(oj[i]);
        }
    }

    returnOj.queryString = "&" + queryString;
    returnOj.paramNum = paramNum;
    returnOj.returnValue = returnValue;
    returnOj.elements = elements;

    return returnOj;
}

compRoot.setOnloadValue = function(elementid){
if (compRoot.findMainComp(elementid) !=null){
        var innerElements = compRoot.findMainComp(elementid).getElementsByTagName("*");
        var returnOj = { "queryString" : "", "paramNum" : 0, "returnValue" : 1, "elements" : {}} ;
         var oj = new Array();
            if (innerElements) {
               for (var i = 0; i < innerElements.length; i++){
      //        alert( innerElements[i].id);
                  if ((innerElements[i].name)&&(innerElements[i].name == "_youcrad_formControl") ){
                     oj.push(innerElements[i]);
      //               alert(innerElements[i].id + " - " + innerElements[i].value);
                  }
               }  
            }else{
               oj = document.getElementsByName("_youcrad_formControl");
            }
         
         if( (oj != null) && (oj.length > 0) ){ 
            for(var i = 0; i < oj.length; i++){         
               if ((oj[i].tagName == "SELECT") && (oj[i].onload != null) && (oj[i].onload != ""))
				      oj[i].value = oj[i].onload;
      //         if ((oj[i].tagName != "SELECT") && (oj[i]._onload != null))
      //         		oj[i].value = oj[i]._onload;
            }
         }
   }
}

compRoot.buildParam = function(elementid) {
    var innerElements = compRoot.findMainComp(elementid).getElementsByTagName("*");
    var returnOj = { "queryString": "", "paramNum": 0, "returnValue": 1, "elements": {} };
    var oj = new Array();
    if (innerElements) {
        for (var i = 0; i < innerElements.length; i++) {
            //        alert( innerElements[i].id);
            if ((innerElements[i].name) && (innerElements[i].name == "_youcrad_formControl")) {
                oj.push(innerElements[i]);
                //               alert(innerElements[i].id + " - " + innerElements[i].value);
            }
        }
    } else {
        oj = document.getElementsByName("_youcrad_formControl");
    }

    var queryString = "";
    var paramNum = 0;
    var returnValue = 1;
    var elements = new Array();

    if ((oj != null) && (oj.length > 0)) {
        paramNum = oj.length;
        for (var i = 0; i < oj.length; i++) {
            if ((oj[i].style.visibility == "hidden") || (oj[i].type == "hidden") || (oj[i].disabled) || (oj[i].readOnly) || ((oj[i].type == "radio")))
                continue;
         oj[i].focus();
         oj[i].blur();
//           if (oj[i].onchange) oj[i].onchange();
            //         alert(oj[i].id + " - " + oj[i].value);
        }
        for (var i = 0; i < oj.length; i++) {
            if (((oj[i].disabled) && (oj[i].tagName != "SELECT")) || (oj[i].type == "radio"))
                continue;
            //         alert(oj[i].id + " | " + oj[i].title);
            if (i < oj.length - 1)
                queryString += oj[i].id + "=" + encodeURIComponent(oj[i].value) + "&";
            else
                queryString += oj[i].id + "=" + encodeURIComponent(oj[i].value);

            returnValue = returnValue * ((oj[i].title != "") ? 0 : 1);

            elements.push(oj[i]);
        }
    }

    returnOj.queryString = "&" + queryString;
    returnOj.paramNum = paramNum;
    returnOj.returnValue = returnValue;
    returnOj.elements = elements;

    return returnOj;
}

compRoot.buildParamSub = function(elementid) {
    var innerElements = document.getElementById(elementid).getElementsByTagName("*");
    var returnOj = { "queryString": "", "paramNum": 0, "returnValue": 1, "elements": {} };
    var oj = new Array();
    if (innerElements) {
        for (var i = 0; i < innerElements.length; i++) {
            //        alert( innerElements[i].id);
            if ((innerElements[i].name) && (innerElements[i].name == "_youcrad_formControl")) {
                oj.push(innerElements[i]);
                //               alert(innerElements[i].id + " - " + innerElements[i].value);
            }
        }
    } else {
        //         oj = document.getElementsByName("_youcrad_formControl");
    }

    var queryString = "";
    var paramNum = 0;
    var returnValue = 1;
    var elements = new Array();

    if ((oj != null) && (oj.length > 0)) {
        paramNum = oj.length;
        for (var i = 0; i < oj.length; i++) {
            if ((oj[i].style.visibility == "hidden") || (oj[i].type == "hidden") || (oj[i].disabled) || (oj[i].readOnly) || ((oj[i].type == "radio")))
                continue;
         oj[i].focus();
         oj[i].blur();
//           if (oj[i].onchange) oj[i].onchange();
            //         alert(oj[i].id + " - " + oj[i].value);
        }
        for (var i = 0; i < oj.length; i++) {
            if (((oj[i].disabled) && (oj[i].tagName != "SELECT")) || (oj[i].type == "radio"))
                continue;
            //         alert(oj[i].id + " | " + oj[i].title);
            if (i < oj.length - 1)
                queryString += oj[i].id + "=" + encodeURIComponent(oj[i].value) + "&";
            else
                queryString += oj[i].id + "=" + encodeURIComponent(oj[i].value);

            returnValue = returnValue * ((oj[i].title != "") ? 0 : 1);

            elements.push(oj[i]);
        }
    }

    returnOj.queryString = "&" + queryString;
    returnOj.paramNum = paramNum;
    returnOj.returnValue = returnValue;
    returnOj.elements = elements;

    return returnOj;
}

compRoot.checkParam = function() {
    var oj = document.getElementsByName("_youcrad_formControl");
    var returnValue = 1;

    if ((oj != null) && (oj.length > 0)) {
        for (var i = 0; i < oj.length; i++) {
            //         if ((oj[i].disabled) || (((oj[i].type == "radio")) && !(oj[i].checked)))
            if ((oj[i].style.visibility == "hidden") || (oj[i].type == "hidden") || (oj[i].disabled) || (oj[i].readOnly) || ((oj[i].type == "radio")))
                continue;
            returnValue = returnValue * ((oj[i].title != "") ? 0 : 1);
        }
    }
    return returnValue;
}

//_____ define process-specific functions until here _______________________________________________________
compRoot.compCall = function(addParams, pageSize, pageNumber, compName, htmlName, paramNum, queryString, returnValue, serverCallHit, instanceKey) {
    //   alert("\n[" + compName + "] component oj has been just called");
    var targetUrl = compRoot.targetUrl + compRoot.compCallTarget;

//    targetUrl += "?authStatus=" + compRoot.authStatus + "&authedId=" + compRoot.authedId + "&compName=" + compName + "&htmlName=" + htmlName + "&pageSize=" + pageSize + "&pageNumber=" + pageNumber + "&serverCallHit=" + serverCallHit;
    targetUrl += "?authStatus=" + compRoot.authStatus + "&compName=" + compName + "&htmlName=" + htmlName + "&pageSize=" + pageSize + "&pageNumber=" + pageNumber + "&serverCallHit=" + serverCallHit+ "&instanceKey=" + instanceKey;
   if((addParams != null) && (addParams != "")) targetUrl += addParams;

    if ((paramNum < 1) || ((paramNum * returnValue) > 0)) {
        targetUrl += queryString;
//        alert("compRoot.addScript(\"" + targetUrl +"\", \"compRoot.instanceArray[\""+compName+"\"].callback\")");
        var pseudoVar = setTimeout("compRoot.addScript(\"" + targetUrl + "\", \"compRoot.instanceArray[\\\"" + compName + "\\\"].callback\")", 0);
    } else {
        alert("입력오류가 있습니다. 확인하시고 다시 입력해 주시기 바랍니다.");
    }
}

compRoot.genPseudoQuery = function(addParams, pageSize, pageNumber, compName, htmlName, paramNum, queryString, returnValue, serverCallHit, instanceKey){
//   alert("\n[" + compName + "] component oj has been just called");
   var targetUrl = compRoot.targetUrl + compRoot.compCallTarget;
   
//   targetUrl += "?authStatus=" + compRoot.authStatus+ "&authedId=" + compRoot.authedId + "&spEmail=" + compRoot.spEmail + "&compName=" + compName + "&htmlName=" + htmlName + "&pageSize=" + pageSize + "&pageNumber=" + pageNumber + "&serverCallHit=" + serverCallHit;
   targetUrl += "?authStatus=" + compRoot.authStatus+ "&spEmail=" + compRoot.spEmail + "&authedId=" + compRoot.authedId + "&compName=" + compName + "&htmlName=" + htmlName + "&pageSize=" + pageSize + "&pageNumber=" + pageNumber + "&serverCallHit=" + serverCallHit +"&instanceKey" + instanceKey;

   if((addParams != null) && (addParams != "")) targetUrl += addParams;
  
   targetUrl += queryString;
//      alert("compRoot.addScript(\"" + targetUrl +"\", \"compRoot.instanceArray[\""+compName+"\"].callback\")");

   return targetUrl;
}

compRoot.svrCall = function(funcName, e, elements, method) {
    if (!(elements))
        compRoot.svrCallOrg(funcName, e, method);
    else
        compRoot.svrCallSpec(funcName, e, elements, method);
}

compRoot.svrCallOrg = function(funcName, e, method) {
    var srcElementId = e.srcElement.id;
    var srcEventType = e.type;
    // get room for applying validation process
    var paramNum = compRoot.buildParam(srcElementId).paramNum;
    var pseudoVar = (method == "post") ? setTimeout("compRoot.svrCallTimeoutOrgPost('" + srcElementId + "','" + srcEventType + "','" + funcName + "')", 0) : setTimeout("compRoot.svrCallTimeoutOrg('" + srcElementId + "','" + srcEventType + "','" + funcName + "')", 0); // 20*paramNum
}

compRoot.svrCallSpec = function(funcName, e, elements, method) {
    var srcElementId = e.srcElement.id;
    var srcEventType = e.type;
    compRoot.forPassingParams = elements;
    // get room for applying validation process
    var paramNum = compRoot.buildParamSpec(elements).paramNum;
    //   alert(compRoot.forPassingParams[0].id);
    var pseudoVar = (method == "post") ? setTimeout("compRoot.svrCallSpecTimeoutPost('" + srcElementId + "','" + srcEventType + "','" + funcName + "', compRoot.forPassingParams)", 0) : setTimeout("compRoot.svrCallSpecTimeout('" + srcElementId + "','" + srcEventType + "','" + funcName + "', compRoot.forPassingParams)", 0); //100*paramNum
}

compRoot.svrCallTimeoutOrg = function(srcElementId, srcEventType, funcName) {
    var paramOj = compRoot.buildParam(srcElementId);

    //      alert("\n[" + funcName + "] function is just called by svrCallOrg, element - " + srcElementId + ", type - " + srcEventType );

    var targetUrl = compRoot.targetUrl + compRoot.procCallTarget;
//    targetUrl += "?authStatus=" + compRoot.authStatus + "&authedId=" + compRoot.authedId + "&funcName=" + funcName + "&srcElementId=" + srcElementId;
    targetUrl += "?authStatus=" + compRoot.authStatus + "&funcName=" + funcName + "&srcElementId=" + srcElementId;
    targetUrl += paramOj.queryString;

    //      alert(targetUrl);

    if (paramOj.returnValue > 0) {
        //        alert("Valid Input!"); 
    } else {
        alert("입력오류가 있습니다. 확인하시고 다시 입력해 주시기 바랍니다.");
        return;
    }
    compRoot.addScript(targetUrl, srcElementId + ".on" + srcEventType);
}

compRoot.svrCallSpecTimeout = function(srcElementId, srcEventType, funcName, elements) {

    var paramOj = compRoot.buildParamSpec(elements);

    //      alert("\n[" + funcName + "] function is just called by svrCallSpec, element - " + srcElementId + ", type - " + srcEventType );
    var targetUrl = compRoot.targetUrl + compRoot.procCallTarget;
//    targetUrl += "?authStatus=" + compRoot.authStatus + "&authedId=" + compRoot.authedId + "&funcName=" + funcName + "&srcElementId=" + srcElementId;
    targetUrl += "?authStatus=" + compRoot.authStatus + "&funcName=" + funcName + "&srcElementId=" + srcElementId;
    targetUrl += paramOj.queryString;

    if (paramOj.returnValue > 0) {
        //        alert("Valid Input!"); 
    } else {
        alert("입력오류가 있습니다. 확인하시고 다시 입력해 주시기 바랍니다.");
        return;
    }
    compRoot.addScript(targetUrl, srcElementId + ".on" + srcEventType);
}

compRoot.svrCallTimeoutOrgPost = function(srcElementId, srcEventType, funcName) {
    //      alert("\n[" + funcName + "] function is just called by svrCallOrg, element - " + srcElementId + ", type - " + srcEventType );
    var paramOj = compRoot.buildParam(srcElementId);
    var returnParent = new Array();
    var returnFile = new Array();

    if (document.getElementById("youcrad_postForm")) document.body.removeChild(document.getElementById("youcrad_postForm"));
    if (document.getElementById("youcrad_postFrame")) document.body.removeChild(document.getElementById("youcrad_postFrame"));

    this.funcName = funcName;
    var targetUrl = compRoot.targetUrl + compRoot.procCallTarget;
//    targetUrl += "?authStatus=" + compRoot.authStatus + "&authedId=" + compRoot.authedId + "&funcName=" + funcName + "&srcElementId=" + srcElementId;
    targetUrl += "?authStatus=" + compRoot.authStatus + "&funcName=" + funcName + "&srcElementId=" + srcElementId;
    targetUrl += "&callbackFunction=" + srcElementId + ".on" + srcEventType + '&partnerEncoding=' + document.charset + '&partnerArticleId=' + compRoot.articleId + '&partnerId=' + compRoot.partnerId + '&authorId=' + compRoot.authorPartnerUserId + "&claimStatus=" + compRoot.claimStatusChecked + "&method=post";
    var pseudoFrame = document.createElement("<iframe onload=\"javascript:compRoot.iframeOnload('" + funcName + "')\" name=\"youcrad_postFrame\"  countflag=\"0\" >");
    pseudoFrame.name = "youcrad_postFrame";
    pseudoFrame.id = "youcrad_postFrame";
    pseudoFrame.style.zIndex = "-1";
    pseudoFrame.style.display = "none";
    pseudoFrame.style.position = "absolute";
    document.body.appendChild(pseudoFrame);

    var pseudoForm = document.createElement("form");
    pseudoForm.id = "youcrad_postForm";
    pseudoForm.name = "youcrad_postForm";

    for (var i = 0; i < paramOj.elements.length; i++) {
        if (paramOj.elements[i].type == "file") {
            returnParent.push(paramOj.elements[i].parentElement);
            returnFile.push(paramOj.elements[i]);

            pseudoForm.appendChild(document.getElementById(paramOj.elements[i].id));
            //         	alert(tempVar.value);
            continue;
        }
        var tempElement = document.createElement(paramOj.elements[i].tagName);
        tempElement.name = paramOj.elements[i].id;
        tempElement.value = encodeURIComponent(paramOj.elements[i].value);
        pseudoForm.appendChild(tempElement);
    }

    //	var tempButton = document.createElement("input");
    //	tempButton.type = "submit";
    //	tempButton.id = "youcrad_neo";
    //	tempButton.name = "youcrad_neo";
    //	pseudoForm.appendChild(tempButton);

    pseudoForm.action = targetUrl;
    pseudoForm.method = "post";
    pseudoForm.encoding = "multipart/form-data";
    
    pseudoForm.style.display = "none";
    pseudoForm.style.position = "absolute";
    pseudoForm.target = "youcrad_postFrame";

    document.body.appendChild(pseudoForm);

    if (paramOj.returnValue > 0) {
        //        alert("Valid Input!"); 
        pseudoForm.submit();
        for (var i = 0; i < returnFile.length; i++) returnParent[i].appendChild(returnFile[i]);

    } else {
        alert("입력오류가 있습니다. 확인하시고 다시 입력해 주시기 바랍니다.");
        for (var i = 0; i < returnFile.length; i++) returnParent[i].appendChild(returnFile[i]);
        return;
    }
}

compRoot.svrCallSpecTimeoutPost = function(srcElementId, srcEventType, funcName, elements) {
    var paramOj = compRoot.buildParamSpec(elements);

    var returnParent = new Array();
    var returnFile = new Array();

    if (document.getElementById("youcrad_postForm")) document.body.removeChild(document.getElementById("youcrad_postForm"));
    if (document.getElementById("youcrad_postFrame")) document.body.removeChild(document.getElementById("youcrad_postFrame"));

    this.funcName = funcName;
    var targetUrl = compRoot.targetUrl + compRoot.procCallTarget;
//    targetUrl += "?authStatus=" + compRoot.authStatus + "&authedId=" + compRoot.authedId + "&funcName=" + funcName + "&srcElementId=" + srcElementId;
    targetUrl += "?authStatus=" + compRoot.authStatus + "&funcName=" + funcName + "&srcElementId=" + srcElementId;
    targetUrl += "&callbackFunction=" + srcElementId + ".on" + srcEventType + '&partnerEncoding=' + document.charset + '&partnerArticleId=' + compRoot.articleId + '&partnerId=' + compRoot.partnerId + '&authorId=' + compRoot.authorPartnerUserId + "&claimStatus=" + compRoot.claimStatusChecked + "&method=post";

    var pseudoFrame = document.createElement("<iframe onload=\"javascript:compRoot.iframeOnload('" + funcName + "')\" name=\"youcrad_postFrame\" countflag=\"0\" >");
    pseudoFrame.name = "youcrad_postFrame";
    pseudoFrame.id = "youcrad_postFrame";
//    pseudoFrame.style.position = "relative";
    pseudoFrame.style.zIndex = "0";
    pseudoFrame.style.width = "0px";
    pseudoFrame.style.height = "0px";
    pseudoFrame.style.visibility = "hidden";
    document.body.appendChild(pseudoFrame);

    var pseudoForm = document.createElement("form");
    pseudoForm.id = "youcrad_postForm";
    pseudoForm.name = "youcrad_postForm";

    for (var i = 0; i < paramOj.elements.length; i++) {
        if (paramOj.elements[i].type == "file") {
            returnParent.push(paramOj.elements[i].parentElement);
            returnFile.push(paramOj.elements[i]);
            pseudoForm.appendChild(document.getElementById(paramOj.elements[i].id));
//            alert("The file as " + paramOj.elements[i].value + " has been added to the pseudoForm");
            continue;
        }
        var tempElement = document.createElement(paramOj.elements[i].tagName);
        tempElement.name = paramOj.elements[i].id;
        tempElement.value = encodeURIComponent(paramOj.elements[i].value);
        pseudoForm.appendChild(tempElement);
    }

    pseudoForm.action = targetUrl;
    pseudoForm.method = "post";
    pseudoForm.encoding = "multipart/form-data";
    pseudoForm.style.visibility = "hidden";
    pseudoForm.style.zIndex = "0";
    pseudoForm.style.width = "0px";
    pseudoForm.style.height = "0px";
//    pseudoForm.style.position = "relative";
    pseudoForm.target = "youcrad_postFrame";
    document.body.appendChild(pseudoForm);

    if (paramOj.returnValue > 0) {
        //        alert("Valid Input!"); 

        pseudoForm.submit();

        for (var i = 0; i < returnFile.length; i++) returnParent[i].appendChild(returnFile[i]);

    } else {
        alert("입력오류가 있습니다. 확인하시고 다시 입력해 주시기 바랍니다.");
        for (var i = 0; i < returnFile.length; i++) returnParent[i].appendChild(returnFile[i]);
        return;
    }
}

compRoot.alertMsg = function(msg, type) {
    alert(msg);
}

compRoot.createFormControl = function(theForm, type, name, value) {
    var aControl = document.createElement("input");
    aControl.type = type;
    aControl.name = name;
    aControl.value = value;
    aControl.id = theForm.id + name;
    theForm.appenChild(aControl);
}

compRoot.iframeOnload = function(funcName) {
    var theIframe = window.event.srcElement;
    var targetUrl = compRoot.targetUrl + "/temp/_getSessionValue.aspx?funcName=" + funcName + '&partnerEncoding=' + document.charset;

    if (parseInt(theIframe.countflag) == 0) {
        compRoot.importScript(targetUrl);
//                 alert(targetUrl);
//                 if (document.getElementById("youcrad_postForm"))  document.body.removeChild(document.getElementById("youcrad_postForm"));
//                 if (document.getElementById("youcrad_postFrame")) document.body.removeChild(document.getElementById("youcrad_postFrame"));
    }
    theIframe.countflag++;
}

compRoot.clientCall = function(fnString, e) {
    var srcElementId = e.srcElement.id;
    var srcEventType = e.type;
    // get room for applying validation process
    var paramNum = compRoot.buildParam(srcElementId).paramNum;
    var pseudoVar = setTimeout("compRoot.clientCallTimeout('" + srcElementId + "','" + srcEventType + "','" + fnString + "')", 20 * paramNum);
}

compRoot.clientCallTimeout = function(srcElementId, srcEventType, fnString) {
    var paramOj = compRoot.buildParam(srcElementId);
    //      alert("\n[" + fnString + "] function is just called by clientCall, element - " + srcElementId + ", type - " + srcEventType );
    if (paramOj.returnValue > 0) {
        //        alert("Valid Input!"); 
    } else {
        alert("입력오류가 있습니다. 확인하시고 다시 입력해 주시기 바랍니다.");
        return;
    }
    eval(fnString);
}



compRoot.initBgLayer = function() {
    var bg = document.createElement("div");
    bg.id = "youcrad_bg_layer";
    bg.style.position = "absolute";
    bg.style.top = "0px";
    bg.style.left = "0px";
    bg.style.width = "100%";
    bg.style.height = document.body.scrollHeight + "px";
    bg.style.zIndex = 1001;
    bg.style.filter = "alpha(opacity=10)";
    bg.style.background = "black";

    document.body.appendChild(bg);

    var oLayer = document.getElementById(compRoot.oLayerComp);
    oLayer.style.position = "absolute";
    oLayer.style.top = "0px";
    oLayer.style.left = "0px";
    oLayer.style.width = "100%";
    oLayer.firstChild.style.width = "100%";
    oLayer.style.height = document.body.scrollHeight + "px";
    oLayer.style.zIndex = compRoot.compGlobalZindex + 1;

    compRoot.updateBgLayer();

    // attach body event dynamically
    var obody = document.getElementsByTagName("body")[0];
    if (obody != null)
        obody.onresize = compRoot.updateBgLayer;
    //      obody.onscroll = compRoot.updateBgLayer
}

compRoot.updateBgLayer = function() {
    var bg = document.getElementById("youcrad_bg_layer");
    if (bg == null) return;

    var size = new Object;
    size = compRoot.getBodySize();

    if (size.h > document.body.scrollHeight)
        bg.style.height = size.h + 'px';
    else
    //		bg.style.height = document.body.scrollHeight+30+'px';
        bg.style.height = document.body.scrollHeight + 'px';

    if (size.x > document.body.scrollWidth)
        bg.style.width = size.w + 'px'
    else
    //		bg.style.width = document.body.scrollWidth+20+'px';
        bg.style.width = document.body.scrollWidth + 'px';
}

compRoot.getBodySize = function() {

    var size = new Object;
    if (self.innerWidth) {
        size.h = self.innerHeight;
        size.w = self.innerWidth;
    }
    else if (document.documentElement && (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientHeight) {
        size.h = (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientHeight;
        size.w = (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientWidth;
    }
    else if (document.body) {
        size.h = document.body.clientHeight;
        size.w = document.body.clientWidth;
    }
    return size;
}

compRoot.killBgLayer = function() {
    var bg = document.getElementById("youcrad_bg_layer");

    if (bg != null) document.body.removeChild(bg);

    var oLayer = document.getElementById(compRoot.oLayerComp);
    if (oLayer) {
        oLayer.style.top = "0px";
        oLayer.style.left = "0px";
        oLayer.style.width = "0px";
        oLayer.style.height = "0px";
        oLayer.style.zIndex = -1;
    }
}

//_____ Partner related global functions from here _____//
compRoot.mouseCoords = function(ev){
   if ((document.body.scrollLeft==0) && (document.body.scrollTop==0)){
	   return { x:ev.clientX + (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollLeft - (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientLeft, y:ev.clientY + (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop  - (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientTop };
	} else {
		return { x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, y:ev.clientY + document.body.scrollTop  - document.body.clientTop };
	}
}

compRoot.getPosition = function(e) {
    var left = 0; var top = 0;
    while (e.offsetParent) {
        left += e.offsetLeft; 
        top += e.offsetTop; 
        e = e.offsetParent;
    }
    left += e.offsetLeft; top += e.offsetTop;
    return { x: left, y: top };
}

compRoot.checkParent = function(eChild, eParent) {
	if (!(eChild)) return false;	
	var recurElement = (eChild.parentElement)? eChild.parentElement:null;
	var searchingFlag = true;

	while (searchingFlag && recurElement) {
		if (eParent == recurElement) {
			searchingFlag = false;
		} else {
			recurElement = recurElement.parentElement;
		}
	}
return (!(searchingFlag))
}

compRoot.checkInvisible = function(eChild){
 	if (!(eChild)) return true;	
	var recurElement = (eChild.parentElement)? eChild.parentElement:null;
	var invisibleFlag = ((eChild.style.visibilty=="hidden")||(eChild.style.display=="none"))?(true):(false);

	while (!(invisibleFlag) && recurElement) {
		if ((recurElement.style.visibilty=="hidden")||(recurElement.style.display=="none")) {
			invisibleFlag = true;
		} else {
			recurElement = recurElement.parentElement;
		}
	}	
	
    return invisibleFlag;
}

compRoot.getMouseOffset = function(target, ev) {
	ev = ev || window.event;
	var docPos = compRoot.getPosition(target);
	var mousePos = compRoot.mouseCoords(ev);
	return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}

compRoot.makeDraggable = function(elementId, option){ /// element should be An Element - use getElementById() 
   var element = document.getElementById(elementId); 
    if (!element) {return;}
    
    element.onmousedown = function(ev) {
       document.onmousemove = compRoot.mouseMove; 
        ev = ev || window.event;
        compRoot.dragObject = element;
        compRoot.dragObject.dragOption = option;
        compRoot.mouseOffset = compRoot.getMouseOffset(element, ev);
//        compRoot.dragObject.isdragged = null;
        return false;
    }
}

compRoot.setDrag = function(elementId, option) {
    if (option == "c") {
        var element = document.getElementById(elementId).cloneNode(true);
        element.id = elementId + "Cloned";
        element.style.zIndex += 1;
//        element.style.filter = "alpha(opacity=60)";
        document.body.appendChild(element);
    } else {
        var element = document.getElementById(elementId);
    }

    if (!element) { return; }

    element.style.cursor = "move";
    compRoot.makeDraggable(element.id, option);
}

compRoot.releaseDrag = function(elementId){
   var element = document.getElementById(elementId); 
   var option =  document.getElementById(elementId).dragOption; 

    if (!element) {return;}

     element.style.cursor = "";
     element.onmousedown = function() {return false};
      
   if (document.getElementById(elementId+"Cloned")) document.body.removeChild(document.getElementById(elementId+"Cloned"));
}

// store the original document event handlers for restoration just after youcrad event handling
compRoot.mouseUpPartner = document.onmouseup;
compRoot.mouseMovePartner = document.onmousemove;
compRoot.onfocusinPartner = document.onfocusin;

document.onfocusin = function(e){
    if (compRoot.onfocusinPartner != null) compRoot.onfocusinPartner(e);
    autoBlur(e);
}

compRoot.mouseUp = function(e) {
    var evt = window.event;
    var srcElement = evt.srcElement;
//    alert(compRoot.findMainCompEl(srcElement).id);

    if (compRoot.dragObject) {
        var elementId = compRoot.dragObject.id;
        var option = compRoot.dragObject.dragOption;

        document.onmousemove = compRoot.mouseMovePartner;

        if (option == "c")
            document.body.removeChild(compRoot.dragObject)
        else {
            compRoot.dragObject.onmousedown = function() { return false };
            compRoot.setDrag(elementId, option);
        }

        if (compRoot.dragObject == compRoot.currentWidgetObject) {
            if (compRoot.currentWidgetObject.style.pixelTop <= (document.compatMode == "CSS1Compat" ? document.documentElement : document.body).scrollTop) {
                compRoot.currentWidgetObject.startTop = 0;
            } else if (compRoot.currentWidgetObject.style.pixelTop >= (document.compatMode == "CSS1Compat" ? document.documentElement : document.body).scrollTop + (document.compatMode == "CSS1Compat" ? document.documentElement : document.body).clientHeight) {
                compRoot.currentWidgetObject.startTop = (document.compatMode == "CSS1Compat" ? document.documentElement : document.body).clientHeight - 15;
            }
        }
    }

    if ((compRoot.dragMark.innerHTML != "") && (srcElement.adplace != "adplace") && (compRoot.findMainCompEl(srcElement) != document.getElementById(compRoot.markInstListComp))) {
//        alert("Wrong Point Of Distribution : " + srcElement.id + "|" + srcElement.tagName + "|" + srcElement.adplace); 
        compRoot.finalizePublish();
    }

    if ((document.getElementById(compRoot.markInstListComp)) && ((document.getElementById(compRoot.markInstListComp).isdragged == "N")) && (compRoot.findMainCompEl(srcElement) != document.getElementById(compRoot.markInstListComp)) ) {
    	compRoot.compDestroy(compRoot.markInstListComp);
    }

    if ((document.getElementById(compRoot.markEditBoxComp)) && (compRoot.findMainCompEl(srcElement) != document.getElementById(compRoot.markIconBoxComp)) && (compRoot.findMainCompEl(srcElement) != document.getElementById(compRoot.markEditBoxComp))) {
    	compRoot.compDestroy(compRoot.markEditBoxComp);
    }
   
    compRoot.dragObject = null;
    
    // DCInside 의 경우에만 별도로 추가 체크, 작동하는 코드
    if ((compRoot.partnerLogoPostfix=="_dc")&&(srcElement.id == "youcrad_restoreWidget")){
        var theCase = "0";
        if((document.getElementById("youcrad_partnerUserId")) && (document.getElementById("youcrad_partnerUserId").value != "") && (document.getElementById("youcrad_agreedYN").value == "YES") )
        {

            
            if ( /*글쓴이 비로그인 여부 체크 */ (document.getElementById("youcrad_partnerAuthorId")) && (document.getElementById("youcrad_partnerAuthorId").value == ""))
            {
                //alert("비로그인한 상태에서 쓴 글에는 광고가 들어갈 수 없습니다.");
                theCase = "1";
            } else if ( /* 글쓴이 비동의인 경우 */ (document.getElementById("youcrad_authorAgreedYN")) && (document.getElementById("youcrad_authorAgreedYN").value != "YES") )
            {
                //alert("글쓴이가 DC@Tag 서비스 동의를 하지 않은 글입니다.");
                theCase = "2";
            } else if ( /* 글쓴이가 광고배포 비허용인 경우 */ ((document.getElementById("youcrad_enabled")) && (document.getElementById("youcrad_enabled").value != "YES")) || (compRoot.visitorMarkLimit==0) )
            {
                //alert("글쓴이가 광고 배포를 허용하지 않은 글입니다.");
                theCase = "3";
            }
        }
        compRoot.addScript(compRoot.targetUrl+"/temp/_perfCounter.aspx?funcName=perfCounter&theCase="+theCase, "");    
    }
}

compRoot.mouseMove = function(ev) {
	ev = ev || window.event;
	var mousePos = compRoot.mouseCoords(ev);
	if (compRoot.dragObject) {
		compRoot.dragObject.style.position = "absolute";
		if (compRoot.dragObject.dragOption == "h") {
			compRoot.dragObject.style.left = mousePos.x - compRoot.mouseOffset.x;
		} else if (compRoot.dragObject.dragOption == "v") {
			if (compRoot.dragObject == compRoot.currentWidgetObject) {
				compRoot.dragObject.style.top = mousePos.y - compRoot.mouseOffset.y;
				if (compRoot.currentWidgetObject.style.pixelTop <= (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop) {
					compRoot.currentWidgetObject.startTop = 0;
					compRoot.mouseUp();
				} else if (compRoot.currentWidgetObject.style.pixelTop >= (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop + (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientHeight - 12) {
					compRoot.currentWidgetObject.startTop = (document.compatMode=="CSS1Compat"?document.documentElement:document.body).clientHeight - 15;
					compRoot.mouseUp();
				} else {
					compRoot.currentWidgetObject.startTop = null;
				}
			} else {
				compRoot.dragObject.style.top = mousePos.y - compRoot.mouseOffset.y;
			}
		} else {
			compRoot.dragObject.style.top = mousePos.y - compRoot.mouseOffset.y;
			compRoot.dragObject.style.left = mousePos.x - compRoot.mouseOffset.x;
		}
		if (compRoot.dragObject) compRoot.dragObject.isdragged = "Y";
	}  //	if (compRoot.dragObject) {
	return false;
}

compRoot.setWidgetYPositionCurrent = function(type) {
    if (compRoot.currentWidgetObject) {
        if (compRoot.currentWidgetObject.startTop == null) compRoot.currentWidgetObject.startTop = compRoot.currentWidgetObject.style.pixelTop - (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop;
        compRoot.currentWidgetObject.scrollType = type;
        if (type == 0) {

            var yMenuFrom, yMenuTo, yOffset;
            yMenuFrom = parseInt(compRoot.currentWidgetObject.style.top, 10);
            yMenuTo = (document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop + compRoot.currentWidgetObject.startTop;

            if ((yMenuFrom != yMenuTo)) {
                yOffset = Math.ceil(Math.abs(yMenuTo - yMenuFrom) / 3);
                if (yMenuTo < yMenuFrom) yOffset = (-1) * yOffset;
                compRoot.currentWidgetObject.style.top = yMenuFrom + yOffset;
            }

            setTimeout("compRoot.setWidgetYPositionCurrent(0);", 0);
        } else if (type == 1) {
            compRoot.currentWidgetObject.style.top = compRoot.currentWidgetObject.startTop;
            (document.compatMode=="CSS1Compat"?document.documentElement:document.body).onscroll = function() {
                var newTop = ((document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop + compRoot.currentWidgetObject.startTop);
                compRoot.currentWidgetObject.style.top = newTop + "px";
            }
        } else if (type == 2) {
            compRoot.currentWidgetObject.style.pixelTop = ((document.compatMode=="CSS1Compat"?document.documentElement:document.body).scrollTop + compRoot.currentWidgetObject.startTop);
        }
    } 
}

compRoot.setWidgetXPosition = function() {
	if (compRoot.currentWidgetObject!=null) {
		var currentWidth = (compRoot.currentWidgetObject.id == compRoot.baseMaxComp) ? 408 : 89;
		compRoot.currentWidgetObject.style.pixelLeft = (document.compatMode == "CSS1Compat" ? document.documentElement : document.body).clientWidth - currentWidth;
	}
}

if (document.compatMode == "CSS1Compat") {
//	document.documentElement.onresize = compRoot.setWidgetXPosition;
	window.onresize = compRoot.setWidgetXPosition;
////	window.onscroll = compRoot.setWidgetXPosition;
} else {
	document.body.onresize = compRoot.setWidgetXPosition;
////	document.body.onscroll = compRoot.setWidgetXPosition;
}

//document.onmousemove = compRoot.mouseMove;

//_____ Partner related global functions until here _____//

//_____ initializing section for page load _____//

//_____ put any attributes needed for global level control _____//
function youcradArray(){
    Array();
}

compRoot.compArray = new youcradArray();
compRoot.compHtmlArray = new youcradArray();
compRoot.funcArray = new youcradArray();
compRoot.instanceArray = new youcradArray();
compRoot.pagingHistory = new youcradArray();
compRoot.optionArrays = new Object();
compRoot.imagesInArticle = new youcradArray();
compRoot.currentPage = 0;
compRoot.forPassingParams; //used for passing elements[] as a setTimeout function string parameter
compRoot.homeComp = "";
compRoot.todayString = "";
compRoot.initializeComp = "399";
compRoot.baseMaxComp = "259";
compRoot.baseMinComp = "258";
compRoot.baseBottomComp = "799";
compRoot.baseMinMinComp = "798";
compRoot.oLayerComp = "342";
compRoot.requestJoinPop0 = "858";
compRoot.requestJoinPop1 = "841";
compRoot.requestJoinPop2 = "858";
compRoot.requestJoinPop3 = "842";
compRoot.requestJoinPop4 = "843";

compRoot.repCharMain = "_mainComp#";
compRoot.repCharSub = "_subComp#";
compRoot.repPseudoString = "_pseudoString#";
compRoot.repCharPageBand = "_pageBand#";
compRoot.repCharPageBand2 = "_pageBand2#";
compRoot.theFactor = 1;
compRoot.callTimeMark = new Date();

compRoot.authedId = "";
compRoot.authStatus = 0;
compRoot.sponsorFlag = 0;
compRoot.tempId = "";
compRoot.spEmail = "";
compRoot.targetComp = "";
compRoot.isUnderWright = "N";

compRoot.pageBandSizeDefault = 5;
compRoot.pageSizeDefault = 3;

compRoot.domainString = window.location.href.match(/:\/\/(.[^/]+)/)[1];
compRoot.compCallTarget = "/temp/_compCall.aspx";
compRoot.procCallTarget = "/temp/_procCall.aspx";
compRoot.targetUrl = "http://dev.youcrad.com";
compRoot.imageUrlBase = compRoot.targetUrl+"/temp/";
compRoot.homeBaseUrl = compRoot.targetUrl+"/temp/default3.htm";
compRoot.homePopupUrl = compRoot.targetUrl+"/temp/defaultpop.htm";
compRoot.logoHomeBaseUrl = compRoot.homeBaseUrl;
//compRoot.markPlaceStringOn = document.createElement("<DIV style='width: 80px; display: inline;' ></DIV>");
compRoot.markPlaceStringOn = document.createTextNode("       ");
compRoot.markPlaceString = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

compRoot.topObj = document.body;
// set the top base element for rendering the root components

compRoot.compGlobalZindex = 1001;
// value for the global ZIndex of all components instances
/////// to pass the parameters already input from the previous STEPs from here______________________________________ 
//____ for SSN verification_________________
compRoot.youcrad_compName = "";
compRoot.youcrad_compNo1 = "";
compRoot.youcrad_compNo2 = "";
compRoot.youcrad_compNo3 = "";
compRoot.youcrad_indivName = "";
compRoot.youcrad_indivNo1 = "";
compRoot.youcrad_indivNo2 = "";

compRoot.youcrad_mailAddress = "";

//____ for AdObject Registration_________________
compRoot.tempAdOjImagePathDefault = compRoot.imageUrlBase + "images/p_btn_find2.gif";
compRoot.regAdOjImagePath = "";
compRoot.regAdOjId = "";
compRoot.tempAdOjTitleDefault = "제목:(18자 이내)";
compRoot.tempAdOjContentDefault = "내용:상세설명/광고문구.(40자 이내).";
compRoot.tempAdOjUrlDefault = "URL:예)puppynara.com";
compRoot.tempAdOjRealUrlDefault = "해당 광고의 링크 URL을 넣어주세요.예)puppy.com/dog.html";
compRoot.tempAdOjKeywordDefault = "해당 광고의 키워드를 입력하세요.예)강아지,분양..";
compRoot.tempAdOjSpNameDefault = "예) 강아지세상, 네이버등";
compRoot.tempAdOjSpEmailDefault = "예) mama@naver.com";
compRoot.tempAdOjSpPhone1Default = "";
compRoot.tempAdOjSpPhone2Default = "";
compRoot.tempAdOjSpPhone3Default = "";
compRoot.tempAdOjSpFax1Default = "";
compRoot.tempAdOjSpFax2Default = "";
compRoot.tempAdOjSpFax3Default = "";

compRoot.tempAdOjImagePath = compRoot.tempAdOjImagePathDefault;
compRoot.tempAdOjTitle = compRoot.tempAdOjTitleDefault;
compRoot.tempAdOjContent = compRoot.tempAdOjContentDefault;
compRoot.tempAdOjUrl = compRoot.tempAdOjUrlDefault;
compRoot.tempAdOjRealUrl = compRoot.tempAdOjRealUrlDefault;
compRoot.tempAdOjKeyword = compRoot.tempAdOjKeywordDefault;
compRoot.tempAdOjSpName = compRoot.tempAdOjSpNameDefault;
compRoot.tempAdOjSpEmail = compRoot.tempAdOjSpEmailDefault;
compRoot.tempAdOjSpPhone1 = compRoot.tempAdOjSpPhone1Default;
compRoot.tempAdOjSpPhone2 = compRoot.tempAdOjSpPhone2Default;
compRoot.tempAdOjSpPhone3 = compRoot.tempAdOjSpPhone3Default;
compRoot.tempAdOjSpFax1 = compRoot.tempAdOjSpFax1Default;
compRoot.tempAdOjSpFax2 = compRoot.tempAdOjSpFax2Default;
compRoot.tempAdOjSpFax3 = compRoot.tempAdOjSpFax3Default;

//____ for Partner Site registration________________
compRoot.tempPartnerNameDefault = "해당 사이트의 공식 명칭을 입력해 주세요.";
compRoot.tempPartnerSiteUrlDefault = "사이트 URL을 입력해 주세요.";
compRoot.tempPartnerAdminUserDefault = "관리자 아이디";

compRoot.tempPartnerName = "";
compRoot.tempPartnerSiteUrl = "";
compRoot.tempPartnerInstallType = 0;  // 0 - Script 1 - Plugin 
compRoot.tempPartnerAdminUser = "";
compRoot.tempPluginType = 0;
compRoot.tempPartnerKey = "";

//____ for AdObject manipulation HTML string block for component render _______________
compRoot.stringOff = '중단';
compRoot.stringOver = '종료';
compRoot.stringBtnExtend = '<td align="left"><img src="' + compRoot.imageUrlBase + 'images/btn_extend_off.gif" border="0" style="cursor: pointer" onmouseover="this.src=' + compRoot.imageUrlBase + 'images/btn_extend_on.gif" onmouseout="this.src=' + compRoot.imageUrlBase + 'images/btn_extend_off.gif"></td>';
compRoot.stringInstListOpen = '<td style="POSITION: relative; height: 0px" align="center" valign="top">';
compRoot.stringInstListClose = '</td>';


/////// to pass the parameters already input from the previous step until here______________
compRoot.setArticleId = function() {
    var theArticleId = "";
    
    if (((compRoot.domainString.split(".")[1] == "tistory"))&& (compRoot.getElementsByClassName("trackback-url").length > 0)){
        theArticleId = compRoot.getElementsByClassName("trackback-url")[0].innerText.replace("http://", "").split("/")[2];
    } else if ((compRoot.checkTistory2nd())&& (compRoot.getElementsByClassName("trackback-url").length > 0)){
        theArticleId = compRoot.getElementsByClassName("trackback-url")[0].innerText.replace("http://", "").split("/")[2];
    } else if (document.getElementById("youcrad_articleId")) {
        theArticleId = document.getElementById("youcrad_articleId").value;
//    } else if (compRoot.searchOptionType=="TSI") {
    } else if (compRoot.getElementsByClassName("trackback-url")[0]) {
//        theArticleId = compRoot.getElementsByClassName("trackback-url")[0].innerText.replace("http://", "").split("/")[2];
    } else if (document.getElementById("SG_ArticleID")) {  /// 세계일보 
        theArticleId = document.getElementById("SG_ArticleID").innerText;
    } else if ((compRoot.domainString.split(".")[1] == "sportsseoul")) {  /// 스포츠서울 
	    var searchStr = parent.document.location.href.toString().split("/");
	    searchStr = searchStr[searchStr.length-1];
	    searchStr = searchStr.split(".");
	    searchStr = searchStr[0].split("_");
	    theArticleId = searchStr[1].substring(0, searchStr[1].length-4);
    } else if (((compRoot.domainString.split(".")[0] == "osen")||(compRoot.domainString.split(".")[0] == "nosen"))&&(compRoot.domainString.split(".")[1] == "mt")) {  /// 오센 
        theArticleId = js_docUrl.split("gid")[1].substr(3);;
    } else if (((compRoot.domainString.split(".")[0] == "star")||(compRoot.domainString.split(".")[0] == "nstar"))&&(compRoot.domainString.split(".")[1] == "mt")) {  /// 스타 
        theArticleId = js_docUrl.split("no")[1].substr(3).split("type")[0].slice(0,-3);
    } else if ((compRoot.domainString.split(".")[0] == "donga")||(compRoot.domainString.split(".")[1] == "donga")) {  /// 동아닷컴 
        theArticleId = document.getElementsByName("kisa_id")[0].value;
    } else {
        theArticleId = ((document.URL.indexOf("http://wpkr.youcrad.com") > -1) || (document.URL.indexOf("http://wp.youcrad.com") > -1)) ? compRoot.scanArticleId("p") : compRoot.scanArticleId("document_srl");
    } 
    return theArticleId;
}

compRoot.setBoardId = function() {
    var theBoardId = "";
    if (document.getElementById("youcrad_boardId")) {
        theBoardId = document.getElementById("youcrad_boardId").value;
    } else {
        theBoardId = ((document.URL.indexOf("http://www.sorento.net") > -1) || (document.URL.indexOf("http://sorento.net") > -1)) ? compRoot.scanBoardId("db") : compRoot.scanBoardId("id");
    }
    return theBoardId;
}

compRoot.isOwner = function(youcradCreator, partnerCreator){
    var youcradCreator = (youcradCreator)?youcradCreator:"";
    var partnerCreator = (partnerCreator)?partnerCreator:"";
    if ((compRoot.authedId!="")&&(youcradCreator == compRoot.authedId)){
        return true;
//    } else if ((compRoot.authedId!="")&&(partnerCreator == compRoot.claimPartnerUserId)){
//        return true;
    } else if ((compRoot.partnerUserId!="")&&(partnerCreator == compRoot.partnerUserId)){
        return true;
    } else {
       return false;
    }
}

compRoot.isVisitorElement = function (youcradCreator, partnerCreator){
    if (((youcradCreator!=null)&&(youcradCreator!="")&&(youcradCreator==compRoot.authorYoucradId)) || ((partnerCreator!=null)&&(partnerCreator!="")&&(partnerCreator==compRoot.authorPartnerUserId)))
        return 0
    else 
        return 1
}

compRoot.setPublishModeMgmt = function(oj){  /// Set the values at initial loading time __ not at login / logout time
//  oj.res._currentPublishMode
//, oj.res._articleMarkLimit
//, oj.res._articleSpaceLimit
//, oj.res._visitorMarkLimit
//, oj.res._visitorSpaceLimit
//, oj.res._markInstLimit
//, oj.res._spaceInstLimit
    
    compRoot.compInitMode = parseInt(oj.res._initStatus);
    compRoot.modeNum = parseInt(oj.res._currentPublishMode);
    var mode ="";

    compRoot.articleMarkLimit = parseInt(oj.res._articleMarkLimit);
    compRoot.articleSpaceLimit = parseInt(oj.res._articleSpaceLimit);

    compRoot.markInstLimit = parseInt(oj.res._markInstLimit);
    compRoot.spaceInstLimit = parseInt(oj.res._spaceInstLimit);

    compRoot.visitorMarkLimit = parseInt(oj.res._visitorMarkLimit);
    compRoot.visitorSpaceLimit = parseInt(oj.res._visitorSpaceLimit);
    
    /// Set fixed widget mode. 0 - use fixed widget 1 - don't use fixed widget (shoud get from oj.res._useFixedWidget )
    compRoot.useFixedWidget = parseInt(oj.res._useFixedWidget);
    /// get logo img name's postfix string
    compRoot.partnerLogoPostfix = oj.res._partnerLogoPostfix;
    /// get registered home Url for logo link
    
    switch (compRoot.partnerLogoPostfix) {
        case '_dc':
            compRoot.logoHomeBaseUrl = "http://wstatic.dcinside.com/youcrad/dctag_guide.html";
          break;
        default:
            compRoot.logoHomeBaseUrl = compRoot.homeBaseUrl;
          break;
    }
    
    
    compRoot.superUserId = oj.res._superUserId;
    
    compRoot.markDefaultColor = parseInt(oj.res._markDefaultColor);
    compRoot.spaceDefaultColor = parseInt(oj.res._spaceDefaultColor);
    compRoot.showMarkComment = parseInt(oj.res._showMarkComment);

    if (compRoot.modeNum==0) {
        mode = "MARK";
            compRoot.articleSpaceLimit = 0;
            compRoot.spaceInstLimit = 0;
            compRoot.visitorSpaceLimit = 0;
            compRoot.visitorMarkLimit = (compRoot.partnerVisitorLimit()>-1)?(compRoot.partnerVisitorLimit()):(compRoot.visitorMarkLimit);
    } else if (compRoot.modeNum==1){
        mode = "SPACE";
            compRoot.articleMarkLimit = 0;
            compRoot.markInstLimit = 0;
            compRoot.visitorMarkLimit = 0;
            compRoot.visitorSpaceLimit = (compRoot.partnerVisitorLimit()>-1)?(compRoot.partnerVisitorLimit()):(compRoot.visitorSpaceLimit);
    } else if (compRoot.modeNum==2){
        /// need to prohibit mark instance population by author here ___
        compRoot.visitorSpaceLimit = 0;
        compRoot.visitorMarkLimit = (compRoot.partnerVisitorLimit()>-1)?(compRoot.partnerVisitorLimit()):(compRoot.visitorMarkLimit);
        
        if(compRoot.authStatus==4) {
            mode = "SPACE";
        } else { 
            mode = "MARK";
        }
    }
    
    compRoot.currentPublishMode = mode;
    return mode;
}

compRoot.resetPublishMode = function(){
    var mode = "";
    
    if (compRoot.modeNum==0) {
        mode = "MARK";
            compRoot.articleSpaceLimit = 0;
            compRoot.spaceInstLimit = 0;
            compRoot.visitorSpaceLimit = 0;
            compRoot.visitorMarkLimit = (compRoot.partnerVisitorLimit()>-1)?(compRoot.partnerVisitorLimit()):(compRoot.visitorMarkLimit);
    } else if (compRoot.modeNum==1){
        mode = "SPACE";
            compRoot.articleMarkLimit = 0;
            compRoot.markInstLimit = 0;
            compRoot.visitorMarkLimit = 0;
            compRoot.visitorSpaceLimit = (compRoot.partnerVisitorLimit()>-1)?(compRoot.partnerVisitorLimit()):(compRoot.visitorSpaceLimit);
    } else if (compRoot.modeNum==2){
        /// need to prohibit mark instance population by author here ___
        compRoot.visitorSpaceLimit = 0;
        compRoot.visitorMarkLimit = (compRoot.partnerVisitorLimit()>-1)?(compRoot.partnerVisitorLimit()):(compRoot.visitorMarkLimit);
        
        if(compRoot.authStatus==4) {
            mode = "SPACE";
        } else { 
            mode = "MARK";
        }
    }
    
    compRoot.currentPublishMode = mode;
    return mode;
}

compRoot.partnerVisitorLimit = function(){
    var returnValue = -1;
    var visitorLimit;

    returnValue = ( (document.getElementById("youcrad_markCount"))  )?(((document.getElementById("youcrad_enabled")) && (document.getElementById("youcrad_enabled").value=="YES") && (document.getElementById("youcrad_agreedYN")) && (document.getElementById("youcrad_agreedYN").value=="YES"))?(parseInt(document.getElementById("youcrad_markCount").value)):(0)):(-1);

    return returnValue;
}


compRoot.checkTistory2nd = function(){
var returnValue = false;

    if  ((compRoot.partnerId=="fcworldcup")||(compRoot.partnerId=="justintistory")){
        returnValue = true;
    }

return returnValue;
}

compRoot.getPartnerAuthorId = function(){
    var partnerAuthorId = "";

        if (compRoot.domainString.split(".")[1] == "tistory"){
            partnerAuthorId = compRoot.domainString.split(".")[0];
        } else if (compRoot.checkTistory2nd()){
            partnerAuthorId = compRoot.domainString;
        } else {
            partnerAuthorId = (document.getElementById("youcrad_partnerAuthorId")) ? document.getElementById("youcrad_partnerAuthorId").value : "";
        }

    return partnerAuthorId;
}

compRoot.getPartnerUserId = function(){
var partnerUserId = "";

if (((compRoot.domainString.split(".")[1] == "tistory"))&&((compRoot.getElementsByClassName("article_admin").length>0)||(compRoot.getElementsByClassName("admin").length>0))){
    partnerUserId = compRoot.domainString.split(".")[0];
} else if ((compRoot.checkTistory2nd())&&((compRoot.getElementsByClassName("article_admin").length>0)||(compRoot.getElementsByClassName("admin").length>0))){
    partnerUserId = compRoot.domainString;
} else if (((compRoot.domainString.split(".")[1] == "tistory"))&&((compRoot.getElementsByClassName("article_admin").length==0)&&(compRoot.getElementsByClassName("admin").length==0))){
    partnerUserId = (typeof permissionNotice == 'function')? ((permissionNotice.toString().match(/(http:\/\/)([_a-zA-Z가-힣0-9,`~!@#\$%\|\^&\[\]\<\>\/\\\*\+=\-\'\"\.\s\?:\(\)]+)(admin)/g)[0].replace("http://","").split(".")[1]=="tistory")?(permissionNotice.toString().match(/(http:\/\/)([_a-zA-Z가-힣0-9,`~!@#\$%\|\^&\[\]\<\>\/\\\*\+=\-\'\"\.\s\?:\(\)]+)(admin)/g)[0].replace("http://","").split(".")[0]):(permissionNotice.toString().match(/(http:\/\/)([_a-zA-Z가-힣0-9,`~!@#\$%\|\^&\[\]\<\>\/\\\*\+=\-\'\"\.\s\?:\(\)]+)(admin)/g)[0].replace("http://",""))):("");
} else if ((compRoot.checkTistory2nd())&&((compRoot.getElementsByClassName("article_admin").length==0)&&(compRoot.getElementsByClassName("admin").length==0))){
    partnerUserId = (typeof permissionNotice == 'function')? ((permissionNotice.toString().match(/(http:\/\/)([_a-zA-Z가-힣0-9,`~!@#\$%\|\^&\[\]\<\>\/\\\*\+=\-\'\"\.\s\?:\(\)]+)(admin)/g)[0].replace("http://","").split(".")[1]=="tistory")?(permissionNotice.toString().match(/(http:\/\/)([_a-zA-Z가-힣0-9,`~!@#\$%\|\^&\[\]\<\>\/\\\*\+=\-\'\"\.\s\?:\(\)]+)(admin)/g)[0].replace("http://","").split(".")[0]):(permissionNotice.toString().match(/(http:\/\/)([_a-zA-Z가-힣0-9,`~!@#\$%\|\^&\[\]\<\>\/\\\*\+=\-\'\"\.\s\?:\(\)]+)(admin)/g)[0].replace("http://",""))):("");
} else {
    partnerUserId = (document.getElementById("youcrad_partnerUserId")) ? document.getElementById("youcrad_partnerUserId").value : "";
}

return partnerUserId;
}

//_______ Variables List for Partner Manipulation from here ________//
compRoot.instanceId = 0;
compRoot.partnerId = compRoot.scanPid();
compRoot.articleUrl = encodeURIComponent(document.URL);
compRoot.articleId = compRoot.setArticleId();  // compRoot.articleUrl;
compRoot.articleElement = null;
compRoot.titleElement = null;
compRoot.currenSpannedHTML = "";
compRoot.boardId = compRoot.setBoardId();
compRoot.authorYoucradId = "";
compRoot.claimPartnerUserId = "";
compRoot.popupCase = -1;
compRoot.authorPartnerUserId = compRoot.getPartnerAuthorId();
compRoot.partnerUserId = compRoot.getPartnerUserId();
compRoot.isPartnerUserAuthor = ((compRoot.partnerUserId != "") && (compRoot.partnerUserId == compRoot.authorPartnerUserId)) ? 1 : 0;

//DC checkup
compRoot.agreedYN = (document.getElementById("youcrad_agreedYN"))?(document.getElementById("youcrad_agreedYN").value):("");
compRoot.authorAgreedYN = (document.getElementById("youcrad_authorAgreedYN"))?(document.getElementById("youcrad_authorAgreedYN").value):("");
compRoot.enabledYN = (document.getElementById("youcrad_enabled"))?(document.getElementById("youcrad_enabled").value):("");

compRoot.claimStatusChecked = 0;
compRoot.needClaimPopup = 0;
compRoot.isArticleAdsOff = 0;
compRoot.searchOptionType = "BASIC"; // partner Category, future feature.

//compRoot.userMarkInstanceLimit = 5;
//compRoot.visitorInstLimit = 4;
//compRoot.instLimit = 30;
//compRoot.visitorInstCount = 0;
//compRoot.instCount = 0;

// Constraints Parameters for handling counts of Ads & logo graphics & etc.... from here ______
compRoot.articleMarkLimit = 3;
compRoot.articleSpaceLimit = 3;

compRoot.markInstLimit = 3;
compRoot.spaceInstLimit = 3;

compRoot.visitorMarkLimit = 2;
compRoot.visitorSpaceLimit = 1;

compRoot.currentPublishMode = "";
compRoot.compInitMode = 0;
compRoot.modeNum = 0;
compRoot.useFixedWidget = 0;
compRoot.superUserId = "";
compRoot.partnerLogoPostfix = "";
compRoot.markDefaultColor = 0;
compRoot.spaceDefaultColor = 0;
compRoot.showMarkComment = 0;
// Constraints Parameters for handling counts of Ads until here ______

compRoot.markCount = 0;
compRoot.spaceCount = 0;
compRoot.visitorSpaceCount = 0;
compRoot.visitorMarkCount = 0;  // 

compRoot.markInstObjKeys = new Array();
compRoot.spaceInstObjKeys = new Array();

compRoot.imagePath = compRoot.targetUrl+"/images/";
compRoot.currentTargetMarkId = "";
compRoot.currentTargetSpaceId = "";
compRoot.currentTargetPlaceType = "";
compRoot.selectedAdObjectId = "";
compRoot.movingPlaceId = "";
compRoot.movingPlaceBaseId = "";
compRoot.movingPlaceType = "";
compRoot.timeId1 = "";  ///// For Render of ADMARK BOX WINDOW //////////
compRoot.timeId2 = ""; ///// For Render of ADMARK EDIT BOX WINDOW ///////////
compRoot.timeId3 = "";
compRoot.widgetTimeOut = "";
compRoot.editBoxTime = 900;
compRoot.markTime = 3000;
compRoot.spaceHeightDefault = '1';
compRoot.spaceHeightOpened = '18';

compRoot.dragMarkComp = "413";
compRoot.dragMark = null;
compRoot.markDisplayComp = "414";
compRoot.markDisplay = null;
compRoot.markInstListComp = "449";
compRoot.spaceInstListComp = "450";
compRoot.spaceInstListEditComp = "451";
compRoot.markInstListHtmlComp = "416";
compRoot.markEditBoxComp = "471";
compRoot.markIconBoxComp = "756";
compRoot.spaceEditBoxComp = "757";
compRoot.overtureListComp = "855";

compRoot.partnerImagePath = compRoot.targetUrl+"/images/";
compRoot.dragObject = null;
compRoot.mouseOffset = null;
compRoot.currentWidgetObjectComp = "";
compRoot.currentWidgetObject = null;


// Cookie Handlers
// Use the name "hideWidget" 
function youcrad_createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function youcrad_readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function youcrad_eraseCookie(name) {
	youcrad_createCookie(name,"",-1);
}

// Copy Hander from here ______________
function youcrad_copyPath(inputPath) {
if (document.getElementById(inputPath)==null) return;

    var inElement = document.getElementById(inputPath);
    var browserName = navigator.appName;  

    if ( browserName.search("Explorer") > 0 ) {  
        var range = inElement.createTextRange();     
        range.execCommand('Copy');  
    } else {  
       var flashcopier = 'flashcopier';  
       if(!document.getElementById(flashcopier)) {  
           var divholder = document.createElement('div');  

           divholder.id = flashcopier;  
           document.body.appendChild(divholder);  
       }  
       document.getElementById(flashcopier).innerHTML = '';  
       var divinfo = '<embed src="' + compRoot.imageUrlBase + 'clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';  
       document.getElementById(flashcopier).innerHTML = divinfo;  
    }  

    alert("내용을 복사했습니다.");

}





// Chained Selects

// Copyright Xin Yang 2004
// Web Site: www.yxScripts.com
// EMail: m_yangxin@hotmail.com
// Last Updated: 2004-08-23

// This script is free as long as the copyright notice remains intact.

var _disable_empty_list=false;
var _hide_empty_list=false;

// ------
if (typeof(disable_empty_list)=="undefined") { disable_empty_list=_disable_empty_list; }
if (typeof(hide_empty_list)=="undefined") { hide_empty_list=_hide_empty_list; }

var cs_goodContent=true, cs_M="M", cs_L="L", cs_curTop=null, cs_curSub=null;

function cs_findOBJ(obj,n) {
  for (var i=0; i<obj.length; i++) {
    if (obj[i].name==n) { return obj[i]; }
  }
  return null;
}
function cs_findContent(n) { return cs_findOBJ(cs_content,n); }

function cs_findM(m,n) {
  if (m.name==n) { return m; }

  var sm=null;
  for (var i=0; i<m.items.length; i++) {
    if (m.items[i].type==cs_M) {
      sm=cs_findM(m.items[i],n);
      if (sm!=null) { break; }
    }
  }
  return sm;
}
function cs_findMenu(n) { return (cs_curSub!=null && cs_curSub.name==n)?cs_curSub:cs_findM(cs_curTop,n); }

function cs_contentOBJ(n,obj){ this.name=n; this.menu=obj; this.lists=new Array(); this.cookie=""; }; cs_content=new Array();
function cs_topmenuOBJ(tm) { this.name=tm; this.items=new Array(); this.df=0; this.addM=cs_addM; this.addL=cs_addL; }
function cs_submenuOBJ(dis,link,sub) {
  this.name=sub;
  this.type=cs_M; this.dis=dis; this.link=link; this.df=0;

  var x=cs_findMenu(sub);
  this.items=x==null?new Array():x.items;

  this.addM=cs_addM; this.addL=cs_addL;
}
function cs_linkOBJ(dis,link) { this.type=cs_L; this.dis=dis; this.link=link; }

function cs_addM(dis,link,sub) { this.items[this.items.length]=new cs_submenuOBJ(dis,link,sub); }
function cs_addL(dis,link) { this.items[this.items.length]=new cs_linkOBJ(dis,link); }

function cs_showMsg(msg) { window.status=msg; }
function cs_badContent(n) { cs_goodContent=false; cs_showMsg("["+n+"] Not Found."); }

function cs_optionOBJ(text,value) { this.text=text; this.value=value; }
function cs_emptyList(list) { for (var i=list.options.length-1; i>=0; i--) { list.options[i]=null; } }
function cs_refreshList(list,opt,df) {
  cs_emptyList(list);

  for (var i=0; i<opt.length; i++) {
    list.options[i]=new Option(opt[i].text, opt[i].value);
  }

  if (opt.length>0) {
    list.selectedIndex=df;
  }
}
function cs_getOptions(menu) {
  var opt=new Array();
  for (var i=0; i<menu.items.length; i++) {
    opt[i]=new cs_optionOBJ(menu.items[i].dis, menu.items[i].link);
  }
  return opt;
}
function cs_updateListGroup(content,idx,sidx,mode) {
  var i=0, curItem=null, menu=content.menu;

  while (i<idx) {
    menu=menu.items[content.lists[i++].selectedIndex];
  }

  if (menu.items[sidx].type==cs_M && idx<content.lists.length-1) {
    var df=cs_getIdx(mode,content.cookie,idx+1,menu.items[sidx].df);

    cs_refreshList(content.lists[idx+1], cs_getOptions(menu.items[sidx]), df);
    if (content.cookie) {
      cs_setCookie(content.cookie+"_"+(idx+1),df);
    }

    if (idx+1<content.lists.length) {
      if (disable_empty_list) {
        content.lists[idx+1].disabled=false;
      }
      if (hide_empty_list) {
        content.lists[idx+1].style.display="";
      }

      cs_updateListGroup(content,idx+1,df,mode);
    }
  }
  else {
    for (var s=idx+1; s<content.lists.length; s++) {
      cs_emptyList(content.lists[s]);

      if (disable_empty_list) {
        content.lists[s].disabled=true;
      }
      if (hide_empty_list) {
        content.lists[s].style.display="none";
      }

      if (content.cookie) {
        cs_setCookie(content.cookie+"_"+s,"");
      }
    }
  }
}
function cs_initListGroup(content,mode) {
  var df=cs_getIdx(mode,content.cookie,0,content.menu.df);

  cs_refreshList(content.lists[0], cs_getOptions(content.menu), df);
  if (content.cookie) {
    cs_setCookie(content.cookie+"_"+0,df);
  }

  cs_updateListGroup(content,0,df,mode);
}

function cs_updateList() {
  var content=this.content;
  for (var i=0; i<content.lists.length; i++) {
    if (content.lists[i]==this) {
      if (content.cookie) {
        cs_setCookie(content.cookie+"_"+i,this.selectedIndex);
      }

      if (i<content.lists.length-1) {
        cs_updateListGroup(content,i,this.selectedIndex,"");
      }
    }
  }
}

function cs_getIdx(mode,name,idx,df) {
  if (mode) {
    var cs_idx=cs_getCookie(name+"_"+idx);
    if (cs_idx!="") {
      df=parseInt(cs_idx);
    }
  }
  return df;
}

function _setCookie(name, value) {
  document.cookie=name+"="+value;
}
function cs_setCookie(name, value) {
  setTimeout("_setCookie('"+name+"','"+value+"')",0);
}

function cs_getCookie(name) {
  var cookieRE=new RegExp(name+"=([^;]+)");
  if (document.cookie.search(cookieRE)!=-1) {
    return RegExp.$1;
  }
  else {
    return "";
  }
}

// ----
function addListGroup(n,tm) {
  if (cs_goodContent) {
    cs_curTop=new cs_topmenuOBJ(tm); cs_curSub=null;

    var c=cs_findContent(n);
    if (c==null) {
      cs_content[cs_content.length]=new cs_contentOBJ(n,cs_curTop);
    }
    else {
      delete(c.menu); c.menu=cs_curTop;
    }
  }
}

function addList(n,dis,link,sub,df) {
  if (cs_goodContent) {
    cs_curSub=cs_findMenu(n);

    if (cs_curSub!=null) {
      cs_curSub.addM(dis,link||"",sub);
      if (typeof(df)!="undefined") { cs_curSub.df=cs_curSub.items.length-1; }
    }
    else {
      cs_badContent(n);
    }
  }
}

function addOption(n,dis,link,df) {
  if (cs_goodContent) {
    cs_curSub=cs_findMenu(n);

    if (cs_curSub!=null) {
      cs_curSub.addL(dis,link||"");
      if (typeof(df)!="undefined") { cs_curSub.df=cs_curSub.items.length-1; }
    }
    else {
      cs_badContent(n);
    }
  }
}

function initListGroup(n) {
  var _content=cs_findContent(n), count=0;
  if (_content!=null) {
    content=new cs_contentOBJ("cs_"+n,_content.menu);
    cs_content[cs_content.length]=content;

    for (var i=1; i<initListGroup.arguments.length; i++) {
      if (typeof(arguments[i])=="object" && arguments[i].tagName && arguments[i].tagName=="SELECT") {
        content.lists[count]=arguments[i];

        arguments[i].onchange=cs_updateList;
        arguments[i].content=content; arguments[i].idx=count++;
      }
      else if (typeof(arguments[i])=="string" && /^[a-zA-Z_]\w*$/.test(arguments[i])) {
        content.cookie=arguments[i];
      }
    }

    if (content.lists.length>0) {
      cs_initListGroup(content,content.cookie);
    }
  }
}

function resetListGroup(n) {
  var content=cs_findContent("cs_"+n);
  if (content!=null && content.lists.length>0) {
    cs_initListGroup(content,"");
  }
}

var disable_empty_list =true;

compRoot.setVehicleList = function(){
    var i,j,k;
    addListGroup("vehicles", "car-makers");
    addOption("car-makers", "Select a Maker", "", "")
    for (var i=0;i<compRoot.optionArrays[0].length; i++){
    
	    addList("car-makers", compRoot.optionArrays[0][i],compRoot.optionArrays[0][i],compRoot.optionArrays[0][i]);
	
	    addOption(compRoot.optionArrays[0][i],"Select a Model", "", "");
	
	    for (var j=0;j<compRoot.optionArrays[1][i].length; j++){
	    
		    addList(compRoot.optionArrays[0][i], compRoot.optionArrays[1][i][j], compRoot.optionArrays[1][i][j], compRoot.optionArrays[1][i][j]);
		    
		    addOption(compRoot.optionArrays[1][i][j], "Select a Class", "", "");
		    
		    for (var k=0;k<compRoot.optionArrays[2][i][j].length; k++){
			
			    addOption(compRoot.optionArrays[1][i][j],compRoot.optionArrays[2][i][j][k],compRoot.optionArrays[2][i][j][k]);
		    
		    }
	    }
    }
}

// For DC monitor add a check call to know if the user click the fixedWidget or not

//      initListGroup("vehicles", document.getElementById("youcrad_carCompany"), document.getElementById("youcrad_carModel"), document.getElementById("youcrad_carClass"), "cs");
// ------ // End of Chained Selects 

//_______ Variables List for Partner Manipulation until here ________//
compRoot.urlRegistered = new Array();
compRoot.flagRegistered = true;   // True if open to all the URLs script-installed 
compRoot.urlRegistered.push("http://clubnf.net/bbs/zboard.php?id=free&page=242&sn1=&divpage=2&sn=off&ss=on&sc=on&select_arrange=headnum&desc=asc&no=6");
compRoot.urlRegistered.push("http://1000cc.net/2008/bbs/zboard.php?id=free&page=403&sn1=&divpage=3&sn=off&ss=on&sc=on&select_arrange=headnum&desc=asc&no=192");
compRoot.urlRegistered.push("http://192.168.1.230/bbs/view.php?id=test&page=1&sn1=&divpage=1&sn=off&ss=on&sc=on&select_arrange=headnum&desc=asc&no=2");
compRoot.urlRegistered.push("http://clubnf.net/bbs/zboard.php?id=free&page=242&sn1=&divpage=2&sn=off&ss=on&sc=on&select_arrange=headnum&desc=asc&no=18");
compRoot.urlRegistered.push("http://zblog.youcrad.com/xe/?document_srl=300");
//compRoot.importScript(compRoot.targetUrl+"/temp/prototype.js");

var prototypeUrl = "http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" //  compRoot.targetUrl+"/temp/prototype.js"; // need to route to the official Prototype url.
var prototypeLoadCount = 0;

compRoot.igniteYoucrad = function (){
    compRoot.importScript(compRoot.targetUrl+"/temp/compHtmlString4.js");
}

compRoot.preIgnite = function (){
    document.stopObserving("dom:loaded", compRoot.preIgnite);
    compRoot.igniteYoucrad();
}

//www.sportsseoul.com
//www.segye.com
//osen.mt.co.kr
//star.mt.co.kr
//news.donga.com

compRoot.afterPrototypeExec = function(){
    if ((compRoot.articleId!="")&&(compRoot.addCSSLink(compRoot.targetUrl+"/temp/partnerjs/p_uc_style.css"))){
        var browser=navigator.appName;
        var version=(navigator.appVersion.split("MSIE"))?(parseFloat(navigator.appVersion.split("MSIE")[1])):(-1);
        if ((browser=="Microsoft Internet Explorer") && (version>=6)){
            if ((compRoot.domainString == "www.segye.com")||(compRoot.domainString == "www.sportsseoul.com")||(compRoot.domainString == "osen.mt.co.kr")||(compRoot.domainString == "star.mt.co.kr")||(compRoot.domainString == "news.donga.com")){
               document.observe("dom:loaded", compRoot.preIgnite); 
            } else {
                compRoot.importScript(compRoot.targetUrl+"/temp/compHtmlString4.js");
                compRoot.importScript(compRoot.targetUrl+"/temp/carOptionList.js");
            }
        }
    }
}

compRoot.importScriptTrigger( prototypeUrl, compRoot.afterPrototypeExec);