/**
 * CONSTANTS 정보
 */
var CMM_DOMAIN = "";
var DEALER_DOMAIN = "/dealer";

if (document.domain.indexOf("enclean") >= 0) {
    document.domain = "enclean.com";
    DEALER_DOMAIN = "http://carmanager.enclean.com";
}


/*
function openCalendar(url, popupname)
{
    window.open(url,popupname,"toolbar=no,width=290,height=170,directories=no,status=no,scrollbars=no,resize=no,menubar=no");
}
*/

//캘린더 팝업창 띄우기(1) - 날짜 직접입력 방식
// flag : 1 - 첫번째, 2 - 두번째( 일자입력 항목이 from - to 2개일경우에 )
// form_name : form 명.(document.form명)
function openCalendar(flag,form_name, clubId, menuId) {
    emate_popup("calendarPopup.do?p_flag="+flag+"&p_form="+form_name+"&clubId="+clubId+"&menuId="+menuId, "calendar",276,298,"no");
}

function dealerPop(lclEtpId) {
	if(!isNumeric(lclEtpId)) {
		alert("딜러정보가 유효하지 않습니다.");
		return;
	}

	//wopen(DEALER_DOMAIN + "/home.do?lclEtpId=" + lclEtpId, "dealerPop",860,590,0);
	location.href = DEALER_DOMAIN + "/home.do?lclEtpId=" + lclEtpId;
}

function dealerSmsPop(lclEtpId, isDealer, sendhpno) {
	if(!isNumeric(lclEtpId)) {
		alert("딜러정보가 유효하지 않습니다.");
		return;
	}
	if(isDealer == true) {
		wopen(DEALER_DOMAIN + "/sms.send.do?lclEtpId=" + lclEtpId+"&isDealer="+isDealer+"&sendhpno="+sendhpno, "delaerSmsPop",700,768,1);
	} else {
		wopen(DEALER_DOMAIN + "/sms.send.do?lclEtpId=" + lclEtpId+"&isDealer="+isDealer+"&sendhpno="+sendhpno, "delaerSmsPop",700,400,0);
	}
}

function dealerReviewPop(lclEtpId) {
	if(!isNumeric(lclEtpId)) {
		alert("딜러정보가 유효하지 않습니다.");
		return;
	}
	//wopen(DEALER_DOMAIN + "/home.review.list.do?lclEtpId=" + lclEtpId, "delaerSmsPop",860,590,0);
	location.href = DEALER_DOMAIN + "/home.review.list.do?lclEtpId=" + lclEtpId;
}

// 10 미만 숫자앞에 '0'을 붙인다.
function setNbtoTest(s)
{
	if( s.length > 1 )
    {
		return s;
	}
    else
    {
		return ("0"+s);
	}
}

// 10미만 숫자앞에 '0' 을 떼어낸다.
function setTextToNumber(s)
{
    if( s.charAt(0) == '0' )
    {
        return s.charAt(1);
    }
    else
    {
        return s;
    }
}

// 바이트수 리턴
function getTextByteSize(str)
{
    var wch, x, uch = "";
    var szLength = 0;

    for ( x = 0; x < str.length; x ++ )
    {
        wch = str.charCodeAt( x );
        if ( !( wch && 0xFF80 ) )
        {
            szLength ++;
        }
        else if ( !( wch & 0xF000 ) )
        {
            szLength ++;
        }
        else
        {
            szLength += 3;
        }
    }
    return szLength;
}



function setTrim(strText) {
    // this will get rid of leading spaces
    while (strText.substring(0,1) == ' ')
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
}

// 타임스탬프 리턴
function getTimeStamp()
{
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    return stemp = hours+minutes+seconds;
}


//스트링에 스페이스가 있는지를 체크한다.
//by jupiter
function IsExistSpace(str)
{
  var e_str = escape(str);

  if( e_str.indexOf("%20") >= 0 )
       return true;

  return false;
}
//랜덤 숫자를 구한다.
//by jupiter
function getRandom(min_num, max_num) {
  var nr=0;
  while ((nr < min_num) || (nr > max_num)) {
     nr = Math.round( min_num*Math.random());
  }
  return nr;
}


/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}


/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function isNumeric(s)
{
    var ch, ch2=1;
	if(!s || s.length==0)
		return (false);

    for ( k = 0; k < s.length; k++ )
    {
        ch = s.charAt(k);
        if ( ch < '0' || ch > '9' )
        {
            return (false);
        }
    }
    return (true);
}


/*******************************
 * 브라우져 정보 시작
 *******************************/
var Browser = new Object();
Browser.ua = navigator.userAgent.toLowerCase();
Browser.isGecko = function() {
	return this.ua.indexOf('gecko') != -1 && this.ua.indexOf('safari') == -1;
}
Browser.isMozilla = function() {
	return this.isGecko() && this.ua.indexOf('gecko/') + 14 == this.ua.length;
}
Browser.isIE = function() {
	return window.ActiveXObject ? true : false;
}
Browser.isFirefox = function() {
	return this.ua.indexOf("firefox")!=-1;
}
Browser.isSafari = function() {
	return this.ua.indexOf("safari")!=-1;
}
Browser.isSafari = function() {
	return this.ua.indexOf("safari")!=-1;
}
Browser.isSafari = function() {
	return this.ua.indexOf("opera")!=-1;
}
/*******************************
 * 브라우져 정보 끝
 *******************************/


 /************************************
 * String 객체의 확장 시작
 ************************************/
String.prototype.trim = function()
{
  return this.replace(/(^\s*)|(\s*$)/gi, "");
}

// replaceAll 구현
String.prototype.replaceAll = function(str1, str2)
{
  var temp_str = this.trim();
  temp_str = temp_str.replace(eval("/" + str1 + "/g"), str2);
  return temp_str;
}

// 정규식을 이용하지 않고 루프를 돌면서 변경한다.
// escape 문자가 들어갔을시 사용해야 한다.
String.prototype.replaceAllWithLoop = function(str1, str2)
{
  var temp_str = this.trim();
  var pre_temp_str = temp_str;
  while(true) {
	temp_str = temp_str.replace(str1, str2);
	if(pre_temp_str == temp_str) break;
	pre_temp_str = temp_str;
  }
  return temp_str;
}

// NJDF의 StringUtil.reEscapeHtmlString() javascript 버전
// &amp;amp;, &amp;lt;, &amp;gt;, &amp;quot;를 &, <, >, " 로 대체한 string으로 바꾸어 줌
String.prototype.reEscapeHtmlString = function()
{
	var str = this;
	str = str.replaceAll("&amp;", "&");
	str = str.replaceAll("&lt;", "<");
	str = str.replaceAll("&gt;", ">");
	str = str.replaceAll("&quot;", "\"");
	return str;
}

// NJDF의 StringUtil.escapeHtmlString() javascript 버전
// &, <, >, "를 &amp;amp;, &amp;lt;, &amp;gt;, &amp;quot; 로 대체한 string으로 바꾸어 줌
String.prototype.escapeHtmlString = function()
{
	var str = this;
	str = str.replaceAll("&", "&amp;");
	str = str.replaceAll("<", "&lt;");
	str = str.replaceAll(">", "&gt;");
	str = str.replaceAll("\"", "&quot;");
	return str;
}

/************************************
 * String 객체의 확장 끝
 ************************************/



/************************************
 * SelectBox 객체
 ************************************/

/*
 * SelectBox를 초기화 시킴
 * defaultName, defaultValue는 옵션
 */
function clearSelectBox(selbox, defaultName, defaultValue) {
	for(i=selbox.length; i > 0; i--){
		selbox.remove(selbox.options[i]);
	}
	if(defaultName)
		selbox.options[selbox.length] = new Option(defaultName,defaultValue);
}

/*
 * Select Box의 옵션중 특정 value의 옵션을 선택되도록 한다.
 */
function initSelectBox(selbox, selectValue) {
	var selectIdx = 0;
	for(i=0; i<selbox.length; i++){
		if(selbox.options[i].value == selectValue) {
			selectIdx = i;
			break;
		}
	}
	selbox.selectedIndex = selectIdx;
}


/************************************
 * RadioButton 객체
 ************************************/
/*
 * 라디오 버튼의 선택된 value를 가져온다.
 */
function $RF(radioName) {
	return $$('input[type=radio][name=' +$(radioName).name+ ']').find(function(el) { return el.checked }).value;
}


/*
 * 주민등록 번호 확인 스크립트
 */
function checkSSN(s1, s2) {
	var n = 2;
	var sum = 0;
	for (var i=0; i<s1.length; i++)
		sum += parseInt(s1.substr(i, 1)) * n++;
	for (var i=0; i<s2.length-1; i++) {
		sum += parseInt(s2.substr(i, 1)) * n++;
		if (n == 10) n = 2;
	}
	var c = 11 - sum % 11;
	if (c == 11) c = 1;
	if (c == 10) c = 0;
	if (c != parseInt(s2.substr(6, 1))) return false;
	else return true;

}

/*
 * 사업자 등록등록 번호 확인 스크립트
 */
function checkBizno(vencod) {
	var sum = 0;
	var getlist =new Array(10);
	var chkvalue =new Array("1","3","7","1","3","7","1","3","5");
	for(var i=0; i<10; i++) { getlist[i] = vencod.substring(i, i+1); }
	for(var i=0; i<9; i++) { sum += getlist[i]*chkvalue[i]; }
	sum = sum + parseInt((getlist[8]*5)/10);
	var sidliy = sum % 10;
	var sidchk = 0;
	if(sidliy != 0) { sidchk = 10 - sidliy; }
	else { sidchk = 0; }
	if(sidchk != getlist[9]) { return false; }
	return true;
}

/*
 * 재외국인 등록 번호 확인 스크립트
 */
function checkFgnno(fgnno) {
	var sum=0;
	var odd=0;
	var buf = new Array(13);
	for(var i=0; i<13; i++) { buf[i]=parseInt(fgnno.charAt(i)); }
	var dd = buf[7]*10 + buf[8];

	if(odd%2 != 0) { return false; }
	if( (buf[11]!=6) && (buf[11]!=7) && (buf[11]!=8) && (buf[11]!=9) ) {
		return false;
	}

	var multipliers = [2,3,4,5,6,7,8,9,2,3,4,5];
	for(var i=0, sum=0; i<12; i++) { sum += (buf[i] *= multipliers[i]); }
	sum = 11 - (sum%11);
	if(sum >= 10) { sum -= 10; }
	sum += 2;
	if(sum >= 10) { sum -= 10; }
	if(sum != buf[12]) { return false }
	return true;
}


/*
 * 팝업 공통 <- ui.js에 있습니다. 검토 요망.
 */
function popUp(url, popupname,x,y,scroll)
{
    window.open(url,popupname,"toolbar=no,width="+x+",height="+y+ ",top="+ (screen.availheight- y )/2+",left="+(screen.availwidth- x)/2 +",directories=no,status=no,scrollbars=no,resize=no,menubar=no");
}


/*
 * 팝업 자동 리사이징
 *  - 윈도 환경에 따라 사이즈가 다를 수 있습니다.
 *  - 팝업페이지의 스크립트 최하단에서 실행하십시오.
 *
 * (ex.) window.onload = function(){popupAutoResize();}
 *
 * nona / 2008.01.04.
 */
function popupAutoResize() {
	var thisX = parseInt(document.body.scrollWidth);
	var thisY = parseInt(document.body.scrollHeight);
	var maxThisX = screen.width - 50;
	var maxThisY = screen.height - 50;
	var marginY = 0;

	// alert("임시 브라우저 확인 : " + navigator.userAgent);
	// 브라우저별 높이 조절. (표준 창 하에서 조절해 주십시오.)
    if (navigator.userAgent.indexOf("MSIE 6") > 0) marginY = 55;        // IE 6.x
    else if(navigator.userAgent.indexOf("MSIE 7") > 0) marginY = 80;    // IE 7.x
    else if(navigator.userAgent.indexOf("Firefox") > 0) marginY = 50;   // FF
    else if(navigator.userAgent.indexOf("Opera") > 0) marginY = 30;     // Opera
    else if(navigator.userAgent.indexOf("Netscape") > 0) marginY = -2;  // Netscape

	if (thisX > maxThisX) {
		window.document.body.scroll = "yes";
		thisX = maxThisX;
	}
	if (thisY > maxThisY - marginY) {
		window.document.body.scroll = "yes";
		thisX += 19;
		thisY = maxThisY - marginY;
	}
    window.resizeTo(thisX+10, thisY+marginY);

    // 센터 정렬
	// var windowX = (screen.width - (thisX+10))/2;
	// var windowY = (screen.height - (thisY+marginY))/2 - 20;
    // window.moveTo(windowX,windowY);
}

/*
 * DIV 내부에 존재하는 이미지 들의 사이즈를 조정한다.
 *
 * divName : 이미지가 존재하는 div명(텍스트로 전달)
 * maxWidth : 허용할 최대 가로크기(옵션) (-1시 무시)
 * maxHeight : 허용할 최대 세로 크기(옵션) (-1시 무시)
 * hideFlag : 이미지 리사이징 동안 본문정보를 보일것인지 여부(옵션) true입력시 감췄다가 보임
 *
 * resize_images('dealerdetsright', 550);
 * resize_images('dealerdetsright', 550, 400);
 */
function resize_images(divName, maxWidth, maxHeight, hideFlag) {
	var isCheckWidth = (maxWidth!=undefined && maxWidth>0);
	var isCheckHeight = (maxHeight!=undefined && maxHeight>0);

	var imgList = $(divName).getElementsByTagName('img');

	if(imgList) {
		if(hideFlag && hideFlag == true) {
			$(divName).style.visibility = "hidden";
		}
		if(!imgList.length) {
			var imgObj = imgList;
			var imgWidth = imgObj.width;
			var imgHeight = imgObj.height;

			if(isCheckWidth) {
				if(imgWidth > maxWidth) {
					var widthRatio = maxWidth/imgWidth;
					imgObj.width = imgWidth * widthRatio;
					imgObj.height = imgHeight * widthRatio;
				}
			}

			imgWidth = imgObj.width;
			imgHeight = imgObj.height;

			if(isCheckHeight) {
				if(imgHeight > maxHeight) {
					var heightRatio = maxHeight/imgHeight;
					imgObj.height = imgHeight * heightRatio;
					imgObj.width = imgWidth * heightRatio;
				}
			}
		} else {
			for(var i=0; i<imgList.length; i++) {
				var imgObj = imgList[i];
				var imgWidth = imgObj.width;
				var imgHeight = imgObj.height;

				if(isCheckWidth) {
					if(imgWidth > maxWidth) {
						var widthRatio = maxWidth/imgWidth;
						imgObj.width = imgWidth * widthRatio;
						imgObj.height = imgHeight * widthRatio;
					}
				}

				imgWidth = imgObj.width;
				imgHeight = imgObj.height;

				if(isCheckHeight) {
					if(imgHeight > maxHeight) {
						var heightRatio = maxHeight/imgHeight;
						imgObj.height = imgHeight * heightRatio;
						imgObj.width = imgWidth * heightRatio;
					}
				}
			}
		}

        tableFix(divName, maxWidth);

		if(hideFlag && hideFlag == true) {
			$(divName).style.visibility = "visible";
		}
	}
}

function tableFix(containerID,width) {
    var wrap = $(containerID);
    var wrapWidth = wrap.offsetWidth;
    var tableEl = wrap.getElementsByTagName("table");
    for (i=0; i<tableEl.length; i++) {
        if (tableEl[i].getAttribute("width") > width) {
            tableEl[i].setAttribute("width",width);
        }
    }
}

function self_resize_image(imgObj, maxWidth, maxHeight) {
	var isCheckWidth = (maxWidth!=undefined && maxWidth>0);
	var isCheckHeight = (maxHeight!=undefined && maxHeight>0);

	var imgWidth = imgObj.width;
	var imgHeight = imgObj.height;

	if(isCheckWidth) {
		if(imgWidth > maxWidth) {
			var widthRatio = maxWidth/imgWidth;
			imgObj.width = imgWidth * widthRatio;
			imgObj.height = imgHeight * widthRatio;
		}
	}

	imgWidth = imgObj.width;
	imgHeight = imgObj.height;

	if(isCheckHeight) {
		if(imgHeight > maxHeight) {
			var heightRatio = maxHeight/imgHeight;
			imgObj.height = imgHeight * heightRatio;
			imgObj.width = imgWidth * heightRatio;
		}
	}
}


/**
 * 금지어 처리
 * 지정된 금지어가 포함되어 있는지 여부를 반환한다.
 * 문자열이 없거나 금지어가 하나도 포함되어 있지 않을 시 true 반환
 * 금지어가 하나라도 포함되면 false 반환
 */
function checkForbiddenWord(str) {
	var url = CMM_DOMAIN + "/ajax.forbidden.word.do";
	var param = "";
	var returnFunc = "checkForbiddenWordResponse";

	if(!str || str.search(/\S/)<0) {
		return true;
	}
	str = str.toLowerCase();
	try {
		var myAjax = new Ajax.Request(
	        url,
	        {
	            method: 'post',
	            parameters: param,
	            onComplete: function() { },
	            onFailure : AjaxRequestError,
	            asynchronous: false,
	            evalJSON : 'force'
	        }
	    );

	    var obj = Xml2DTO(myAjax.transport, "AdmSkfCodeItemDTO");
	    if(obj.success == 'false') {
	    	return true;
	    }

	    for(var i=0; i<obj.totalCount; i++) {
		  	if(str.indexOf(obj[i].codeName.toLowerCase())>=0) {
		  		alert("금지어 \""+obj[i].codeName+"\"이(가) 포함되어 있습니다.");
		  		return false;
		  	}
		}
	}catch(e){}

    return true;
}


/**
 * 검색어 링크삽입
 */
function goAnchoring(str){
	var url = "http://enclean.com/total/total.list.do?kwd=";
	str = encodeURIComponent(str);
	url = url + str;

	window.open(url,'anchorPop','');
}


/**
 * 웹로그 (Xtractor)용 쿠키생성
 */
//	Update 20090116 by Hermoney  vid생성하는로직을 필터로 적용후 jsp인클루드하던방식은 막음.
//document.write("    <SCRIPT LANGUAGE=\"JavaScript\" src=\"http://www.enclean.com/common/XtractorVIDCookie.jsp\"></SCRIPT>      ");


// window onload시 특정 메서드 호출처리
// methodObj는 callback할 메서드객체
function callbackAtwindowLoaded(methodObj) {
	if(typeof(methodObj) == 'function') {
		if(window.attachEvent)
			window.attachEvent("onload", methodObj);
		else
			window.addEventListener("load", methodObj, false);
	} else {
		alert('function 호출에 문제가 있습니다.');
	}
}