var contextPath; 
var currentGnbEl;
//Autocomplete JScode Start
var oT;
var focusImg = "&nbsp;<img src=\"http://web.tradekorea.com/images/icon/keyword_bullet.gif\" alt=\"\" />";

//키워드 값이 Tip 키워드인지 여부 체크 : Tip인 경우 true 반환
function checkSearchTipKeyword( keyword )
{
	var searchTipKwd = new Array("Search Products", "Search Selling Leads", "Search Buying Leads", "Search Companies");
	var flag = false;
	
	for ( var i = 0; i < searchTipKwd.length; i++) {
		if( keyword == searchTipKwd[i]) {
			flag = true;
			break;
		}
	}
	
	return flag;
}

// 검색 탭메뉴 상태 변경 함수
function setSearchTabStatus(el, type){
	var $el = $(el);
	var elIdx = $( "li", ".gnb").index( $el ) + 1;
	var currentElIdx = $( "li", ".gnb").index( currentGnbEl ) + 1; 

	// 기존에 선택되어진 탭 항목 설정 제거
	if(currentGnbEl != null){
		currentGnbEl.removeClass("gnb" + currentElIdx + "_on");
		currentGnbEl.addClass("gnb" + currentElIdx + "_off");
		$( "a", currentGnbEl ).removeClass( "gnb_on" );

		preDetailSearchTab = $( $( "h2", ".sch_Layer_left")[currentElIdx - 1] );
		$( preDetailSearchTab ).removeClass( "title1" );
		$( "img", preDetailSearchTab ).remove();
	}

	// 선택된 탭 항목 설정 설정
	$el.removeClass("gnb" + elIdx + "_off");
	$el.addClass("gnb" + elIdx + "_on");
	$( "a", $el ).addClass( "gnb_on" );

	detailSearchTab = $( $( "h2", ".sch_Layer_left")[elIdx - 1] );
	$( detailSearchTab ).addClass( "title1" );
	$( focusImg ).appendTo( detailSearchTab );

	// 선택한 탭이 Products 인경우 상세 검색 탭의 인증서 정보 입력 부분 출력.
	if( elIdx == 1) {
		$( "#gnbCertFrmBox" ).show();
	} else {
		$( "#gnbCertFrmBox" ).hide();
	}
	
	// 카테고리 레이어 박스 타겟 설정
	var targetElementId;
	switch( elIdx ) {
		case 1 :
			targetElementId = "Search Products";
            oT.sCollection = "products";
			break;
		case 2 :
			targetElementId = "Search Selling Leads";
			oT.sCollection = "sell-leads";
			break;
		case 3 :
			targetElementId = "Search Buying Leads";
			oT.sCollection = "buyers";
			break;
		case 4 :
			targetElementId = "Search Companies";
			oT.sCollection = "companies";
			break;
		default :
			targetElementId = "Search Products";
			oT.sCollection = "products";
			break;
	}
	
	keyword = $( "input[name=keyword]", "form[name=gnbForm]" ).val();
	
	if( keyword == "" || checkSearchTipKeyword(keyword) ) {
		$( "input[name=keyword]", "form[name=gnbForm]" ).val( targetElementId );
	}
	
	currentGnbEl = $el;
}

// 상세 검색 박스 display
function showGnbDetailForm()
{
	if( $( "#search_Layer" ).css("display") == "none" ) {
		$( "#search_Layer" ).show();

		var nationCdCount = $( "select[name=nationCd] option", "form[name=gnbInfoForm]").size();

		// 국가 선택 박스 목록이 없는 경우 목록 불러와 삽입 처리함.
		if(nationCdCount == 1) {
			TK.Ajax.send( {
			 	url : contextPath + "/common/listNationAjax.mvc",
			 	type : "get",
			 	success : function(JSONData, respText){
			 		var obj = TK.Ajax.parseJson(JSONData);
			 		var size = obj.length;

			 		if(size > 0) {
				 		for(i = 0; i < size; i++) {
					 		var nation = obj[i];
					 		$( "select[name=nationCd]", "form[name=gnbInfoForm]" ).get(0).options[i + 1] = new Option( nation.nationNm, nation.nationCd );
				 		}

				 		// 상위 검색 박스에 국가 선택 정보가 있는 경우 상세 검색 박스의 국가 선택 정보 설정.
				 		if( $( "input[name=nationCd]", "form[name=gnbForm]" ).val() != "" ) {
				 			$( "select[name=nationCd]", "form[name=gnbInfoForm]" ).val( $( "input[name=nationCd]", "form[name=gnbForm]" ).val() );
				 		}
			 		}
				},
			 	error : function(respText){
				 	alert("Error!!");
				}
			} );
		}
		
		// 상위 검색 박스에 카테고리 정보가 있는 경우
		if( $( "input[name=catCd]", "form[name=gnbForm]" ).val() != "" ) {
			// 상세 검색 박스의 카테고리 정보 설정.
 			$( "input[name=catCd]", "form[name=gnbInfoForm]" ).val( $( "input[name=catCd]", "form[name=gnbForm]" ).val() );
 			$( "input[name=catNm]", "form[name=gnbInfoForm]" ).val( $( "input[name=catNm]", "form[name=gnbForm]" ).val() );
		}
		
		var keyword = $( "input[name=keyword]", "form[name=gnbForm]").val();

		// 키워드가 있고 기본 팁 키워드가 아닌 경우
		if(	keyword != "" && checkSearchTipKeyword(keyword) == false ) {
			$( "input[name=keyword]", "form[name=gnbInfoForm]").val( keyword );
		}
		$( "input[name=keyword]", "form[name=gnbInfoForm]").focus();
		
		// 서브페이지에서 카테고리 검색 파라미터 정보가 있는 경우.
		if( $( "input[name=catCd]", "form[name=gnbForm]" ) != null
				&& $( "input[name=catCd]", "form[name=gnbForm]" ).val() ) {
			// 카테고리 정보 상세 검색 박스에 정보 설정
			searchCatCd = $( "input[name=catCd]", "form[name=gnbForm]" ).val();
			$( "input[name=catCd]", "form[name=gnbInfoForm]" ).val( searchCatCd );
			$( "input[name=catNm]", "form[name=gnbInfoForm]" ).val( $( "li[code=" + searchCatCd + "]", "#sch_drop_02" ).text() );
		}
		
		// 서브페이지에서 국가 검색 파라미터 정보가 있는 경우.
		if( $( "input[name=nationCd]", "form[name=gnbForm]" ) != null
				&& $( "input[name=nationCd]", "form[name=gnbForm]" ).val() ) {
			// 국가 정보 상세 검색 박스에 정보 설정
			searchNationCd = $( "input[name=nationCd]", "form[name=gnbForm]" ).val();
			$( "select[name=nationCd]", "form[name=gnbInfoForm]" ).val( searchNationCd );
		}
	} else {
		$( "#search_Layer" ).hide();
	}
}

// 키워드 입력 엘레멘트 포커스시 액션.
function checkKeyword( formName )
{
	var keyword = $( "input[name=keyword]", "form[name=" + formName + "]").val();
	
	// 기본 Tip 키워드인 경우 제거함.
	if(checkSearchTipKeyword(keyword)) {
		$( "input[name=keyword]", "form[name=" + formName + "]").val("");
	}
}

// 상세 검색 실행
function searchDetailGnb() {
	var elIdx = $( "li", ".gnb").index( currentGnbEl ) + 1;
	
	var searchAction;
	var keyword = $( "input[name=keyword]", "form[name=gnbInfoForm]" ).val();
	var catCd = $( "input[name=catCd]", "form[name=gnbInfoForm]" ).val();
	var nationCd = $( "select[name=nationCd] option:selected", "form[name=gnbInfoForm]" ).val();
	var certNm = $( "input[name=certNm]", "form[name=gnbInfoForm]" ).val();

	if( $.trim(keyword).length > 0 && checkSearchTipKeyword(keyword) == false ) {

		searchAction = contextPath + "/" + $( currentGnbEl ).attr( "action" ) + "/";

		// 카테고리 정보가 있는 경우 action 정보에 추가
		if(catCd != "" && catCd != null) {
			searchAction += catCd + "/";
		}

		// 키워드 정보가 있는 경우 설정하고 없는 경우 엘레멘트 제거함.
		if(keyword != "" && keyword != null) {
			$( "input[name=keyword]", "form[name=gnbDetailForm]" ).val( keyword );
		} else {
			$( "input[name=keyword]", "form[name=gnbDetailForm]" ).remove();
		}

		searchAction += keyword + ".html";

		// 국가 코드 정보가 있는 경우 설정하고 없는 경우 엘레멘트 제거함.
		if(nationCd != "" && nationCd != null) {
			$( "input[name=nationCd]", "form[name=gnbDetailForm]" ).val( nationCd );
		} else {
			$( "input[name=nationCd]", "form[name=gnbDetailForm]" ).remove();
		}

		// 검색 타입이 Product인 경우 인증서 검색 정보 설정하고 없는 경우 엘레멘트 제거함.
		if(elIdx == 1 && certNm != "" && certNm != null) {
			$( "input[name=certNm]", "form[name=gnbDetailForm]" ).val( certNm );
		} else {
			$( "input[name=certNm]", "form[name=gnbDetailForm]" ).remove();
		}

		$( "form[name=gnbDetailForm]" ).attr( "action", searchAction );
		$( "form[name=gnbDetailForm]" ).submit();
	} else {
		alert("Please Enter Search Keyword.");
	}
}

// 카테고리 선택 팝업창 출력
function openCategoryPopup()
{
	window.open(
		contextPath + "/category/showCategoryPopup.mvc?formName=gnbInfoForm"
		, ""
		, "top=100, left=200, width=500, height=550, status=no, toolbar=no, location=no, resizable=yes"
	);
}

// 카테고리 입력창 초기화
function clearGnbCategory()
{
	$( "input[name=catCd]", "form[name=gnbInfoForm]").val("");
	$( "input[name=catNm]", "form[name=gnbInfoForm]").val("");
}


//Autocomplete JScode Start
var oT;

function oT_Init(contextPath, t_width){
	
        try{
                if(oT == null){
                        oT = new Tom();
                }
                
                var o = oT;
                //alert(contextPath);
                if(o.contextPath==null){
                    o.contextPath = contextPath;
                }
                
                if(o.oForm==null){
                        o.oForm = document.getElementById('gnbForm');;
                }
                
                if(o.oKeyword==null){
                        o.oKeyword = o.oForm.keyword;//document.getElementById("keyword");            
                }
                if(o.sCollection == null){
                	var currentSearchTab = $($( "li a.gnb_on", ".gnb" ).parent());
                	o.sCollection = currentSearchTab.attr("action");
                	//alert("colName"+currentSearchTab.attr("action"));
                	if(o.sCollection == "" || o.sCollection == null) o.sCollection = "products";
                }
                o.oKeyword.setAttribute("autocomplete","off");
                if(o.oAc_lyr==null){
                        o.oAc_lyr = document.getElementById("ac_layer");
                }
                if(o.oAc_ifr==null){
                        o.oAc_ifr = document.getElementById("ifr_ac");
                }
                if(o.oImg_Toggle == null){
                        o.oImg_Toggle = document.getElementById("ac_img");
                }
                if(o.t_width == null){
                    o.t_width = t_width;
            }
               
                o.sSubmitFunctionName = "autocomSubmit()";
        }catch(e){
                setTimeout("oT_Init()", 1000);
        }
}

function oT_search(e){
    try{
    	var temp = null;
        if(oT == temp){
            oT_Init();
        }
        var o = oT;
        var event = window.event || e;
        var obj = getIFrameDocument(o.oAc_ifr.name);
        if(event.keyCode==40){
            obj.Jerry_next();
        }else if(event.keyCode==38){
            obj.Jerry_prev();
        }else if(event.keyCode==37){
        }else if(event.keyCode==39){
        }else if(event.keyCode==13){
        }else{
            setTimeout("oT.find()", o.TimerInterval);
        }
    }catch(e){
    }
}
function calculateOffsetLeft(field) {
  return calculateOffset(field, "offsetLeft");
}

function calculateOffsetTop(field) {
  return calculateOffset(field, "offsetTop");
}

function calculateOffset(field, attr) {
  var offset = 0;
  while(field) {
    offset += field[attr]; 
    field = field.offsetParent;
   }
  return offset;
}


function Tom(){
	
	this.version="1.0";
	this.name = "AutoComplete Tom";
	this.oForm = null;
	this.sCollection = null; 
	this.oKeyword = null;	
	this.sOldkwd = "";	
	this.sNewkwd = "";	
	this.oAc_lyr = null;
	this.oAc_ifr = null;
	this.oImg_Toggle = null;	
	this.sImg_Toggle_on =  "http://web.tradekorea.com/images/btn/btn_drop_01.gif"; 
	this.sImg_Toggle_off = "http://web.tradekorea.com/images/btn/btn_drop_01.gif";
	this.sSkipWrd = "ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅊㅋㅌㅍㅎ";
	this.bSkipTF = false;
	this.TimerInterval = 200;
	this.act =0;
	this.sSubmitFunctionName = "";
	this.contextPath = null;
	this.t_width = null;
	this.isExistSkipwrd = function(){
		var i;
		s = arguments[0]; 
		t = arguments[1];
		for(i=0;i<s.length;i++){
			if(t.indexOf(s.substring(i, i+1)) < 0){
				ret = false;
			}else{
				ret = true;
				break;
			}
		}
		return ret;
	};
	
	this.toggle = function(){
		if(this.oAc_ifr!=null){
			obj = getIFrameDocument(this.oAc_ifr.name);
			obj.Jerry_Alive();
			obj.Jerry_on_off();
		}
	};
	this.click = function(){
		if(this.oAc_ifr!=null){
			obj = getIFrameDocument(this.oAc_ifr.name);
			if(obj.is_Jerry_use()){
				obj.Jerry_on_off();
			}
		}
	};
	this.find = function(){

		if(this.sOldkwd == this.oKeyword.value.trim()){
			return;
		}else{
			if(this.act){
				return;
			}else{
				if(this.bSkipTF){
					if(this.isExistSkipwrd(this.oKeyword.value.trim(), this.sSkipWrd)){
						return;
					}
				}
				this.act=1;
				this.sNewkwd = this.oKeyword.value.trim();
				obj = getIFrameDocument(this.oAc_ifr.name);
				obj.Jerry_AutoSearch(this);
				this.sOldkwd = this.sNewkwd;
				this.act=0;
			}
		}
	};
	
}
function getIFrameDocument(aID){ 
	// if contentDocument exists, W3C compliant (Mozilla) 
	if (document.getElementById(aID).contentWindow){
		rv = document.getElementById(aID).contentWindow;
	} else { 
		// IE 
		rv = document.frames[aID];
	}
	return rv; 
};

