
//filter clk evt
function reference_filterClk(){
    $(document).on("click","#referencelistForm [name=second_class],#referencelistForm [name=second_category],#referencelistForm [name=first_agency]",function(){
        //first chk
         if( $(this).parents('.depth-2').find('input:checkbox[name="' + event.target.name + '"]:checked').length >= 1){
            $(this).parents('.depth-2').siblings('.depth-1').find('input').prop("checked", true);
        }else{
            $(this).parents('.depth-2').siblings('.depth-1').find('input').prop("checked", false);
        }
    
        //filter_mylist clk array 
        var filter_mylist = "";
        var filter_mylist_clk = "";
        var filter_agency = "";
        var filter_agency_clk = "";
        filter_agency = $('#filter_agency').val(); 
        filter_mylist = $('#filter_mylist').val();  
        
        if($(this).attr('name') == 'second_class'){
            filter_mylist_clk  = 'class_'+$(this).val() +',';
        }else if($(this).attr('name') == 'second_category'){
            filter_mylist_clk  = 'category_'+$(this).val() +',';
        }else if($(this).attr('name') == 'first_agency'){
            filter_mylist_clk  = 'agency_'+$(this).val() +',';
          //생산기관은 1depth 이므로 별도처리
            filter_agency_clk = $(this).val() +",";
        }
        
        //생산기관은 1depth 이므로 별도처리
        if($(this).is(":checked")){ 
            filter_mylist  += filter_mylist_clk;
            filter_agency  += filter_agency_clk;
        }else{  
            filter_mylist = filter_mylist.replace(filter_mylist_clk,'');
            filter_agency = filter_agency.replace(filter_agency,'');
        }
        $('#filter_mylist').val(filter_mylist);
        $('#filter_agency').val(filter_agency);


        //depth-1      
        var on_classArr = document.querySelectorAll("div.depth-1.on");
        var filter_class = "" ;
        var filter_category = "" ;
        for(var i=0; i<on_classArr.length; i++){
            if($(on_classArr[i]).find('input').attr('name')  == 'first_class') {
                filter_class = $(on_classArr[i]).find('input').val();   
            }else{
                filter_category = $(on_classArr[i]).find('input').val(); 
            }
        }  
        
        var listForm = document.forms["referencelistForm"];
        listForm.pageIndex.value =  1;
        listForm.filter_class.value = filter_class;
        listForm.filter_category.value = filter_category; 
        
        fnFilterSch();    
    });
    
}
function filter_creatYyyyAply(){
	$(document).on("click","#referencelistForm button[class^='btn-apply']",function(){
		var filter_mylist = "";
        filter_mylist = $('#filter_mylist').val();  
        
		//전체
		if($("#m-year-1").is(':checked') == true)
		{
			$("#filter_creatYyyy").val("all");
			filter_mylist = filter_mylist.replace("creat_all","");
			filter_mylist = filter_mylist.replace("creat_date,","");
			filter_mylist += "creat_all,";
			$("#filter_mylist").val(filter_mylist);
		}
		
		//생산년도 검색
		if($("#m-year-2").is(':checked') == true)
		{
			if($("#creatYyyyStart").val() == "")
			{
				alert("생산년도 검색 시작일자를 입력해주세요.");
				return false;
			}
			if($("#creatYyyyEnd").val() == "")
			{
				alert("생산년도 검색 종료일자를 입력해주세요.");
				return false;
			}
			$("#filter_creatYyyy").val("date");
			filter_mylist = filter_mylist.replace("creat_all","");
			filter_mylist = filter_mylist.replace("creat_date,","");
			filter_mylist += "creat_date,";
			$("#filter_mylist").val(filter_mylist);
		}
		
		fnFilterSch();
	});
	
}
//초기화
function reference_filterReset(){
	$(document).on("click","#referencelistForm button[class^='btn-filter-reset']",function(){
		$("#pageIndex").val("1");
		$("#filter_creatYyyy").val("");
		$("#creatYyyyStart").val("");
		$("#creatYyyyEnd").val("");
		$("#filter_class").val("");
		$("#filter_category").val("");
		$("#filter_agency").val("");
		$("#filter_mylist").val("");
		$("#bookIndex").val("");
		$("#mngtNo").val("");
		$("#createStartDate").val("");
		$("#createEndDate").val("");
		$("#ageCode").val("");
		$("#collectionList").val("");
		$("#realQuery").val("");
		$("#reQueryChk").val("query");
		$("#query").val("");
		$("#reQuery").val("");
		$("#collection").val("lib_total");
		$("#referencelistForm [name=first_class],#referencelistForm [name=second_class],#referencelistForm [name=first_category],#referencelistForm [name=second_category],#referencelistForm [name=creatYyyyYn],#referencelistForm [name=first_agency]").prop("checked", false);
		fnFilterSch();
	});
}
//reference 결과 필터  del 클릭
function reference_filterDel(){
    $(document).on("click","#referencelistForm button[id^='c_cate_data-type-chk'],#referencelistForm button[id^='j_cate_theme-chk'],#referencelistForm button[name=first_agency_del]",function(){
      
         var s_cate_id = $(this).attr("id");  
         s_cate_id = s_cate_id.substring(s_cate_id.lastIndexOf("_")+1);

        var reference_gubun_name = "";

        if( $(this).attr('id').indexOf("theme-chk") != -1){
            reference_gubun_name = "second_category";
        }else if( $(this).attr('id').indexOf("data-type-chk")!= -1){
            reference_gubun_name = "second_class";
        }
        //first
        var first_nm = $(this).attr('id').replace('c_cate_', '').replace('j_cate_', '');

        first_nm = first_nm.substring(0,first_nm.indexOf("_",-2)); //data-type-chk1-4
        first_nm = first_nm.substring(0,first_nm.lastIndexOf("-")) ; //data-type-chk1
        
        if($("#referencelistForm input:checkbox[id^='"+ first_nm +"-']:checked").length ==1){   
            $("input:checkbox[id='" +  first_nm + "']").prop("checked", false);
        }
        
        //second
        $("#referencelistForm input[name='"+  reference_gubun_name+ "']:input[value='"+s_cate_id+"']").each(function () {
             $(this).prop("checked",false);
         }); 
    
        
        //filter_mylist clk array remove
        var filter_mylist = "";
        var filter_mylist_clk = "";
        var filter_agency = "";
        var filter_agency_clk = "";
        filter_agency = $('#filter_agency').val();
        filter_mylist = $('#filter_mylist').val();  
        
        if($(this).attr('id').indexOf('c_cate_data-type') >= 0 ){
            filter_mylist_clk  = 'class_'+ s_cate_id +',';
        }else if($(this).attr('id').indexOf('j_cate_theme')>= 0 ){
            filter_mylist_clk  = 'category_'+ s_cate_id +',';
        }else if($(this).attr('name').indexOf('first_agency_del')>= 0 ){
            filter_mylist_clk  = 'agency_'+ s_cate_id +',';
            filter_agency_clk  = s_cate_id +',';
        }    
        filter_agency = filter_agency.replace(filter_agency_clk,'');
        filter_mylist = filter_mylist.replace(filter_mylist_clk,'');
        $('#filter_agency').val(filter_agency);
        $('#filter_mylist').val(filter_mylist);
        

        //depth-1       
        var on_classArr = document.querySelectorAll("div.depth-1.on");
        var filter_class = "" ;
        var filter_category = "" ;
        for(var i=0; i<on_classArr.length; i++){
            if($(on_classArr[i]).find('input').attr('name')  == 'first_class') {
                filter_class = $(on_classArr[i]).find('input').val();   
            }else{
                filter_category = $(on_classArr[i]).find('input').val(); 
            }
        }  
        

        var listForm = document.forms["referencelistForm"];
        listForm.pageIndex.value =  1;
        listForm.filter_class.value = filter_class;
        listForm.filter_category.value = filter_category;
        fnFilterSch();  
            
    });
}   

//reference 결과 필터  del 클릭(상세검색에 추가된 부분)
function reference_detailFilterDel(){
	$(document).on("click","#referencelistForm .detailFilter",function(){
		var filter_mylist = "";
		var deleteFilterId = "";
		var count = 0;
	     filter_mylist = $('#filter_mylist').val();
	     deleteFilterId = $(this).attr('name').substring($(this).attr('name').indexOf("_",0)+1);
	     
	     if($(this).attr('name') == "search_ageCode" || $(this).attr('name') == "search_collectionList")
    	 {
	    	 if($(".filter-wrap button[name="+$(this).attr('name')+"]").length == 1)
    		 {
	    		 filter_mylist = filter_mylist.replace($(this).attr('name')+",",'');
	    		 $("#" + deleteFilterId).val("");
    		 }else{
		    	 var deleteFilterArr = $("#" + deleteFilterId).val().split(",");
		    	 
		    	 
		    	 $("#" + deleteFilterId).val(deleteFilterArr[0]);
		    	 
		    	 for(var i=1; i < deleteFilterArr.length ; i++){
		    		 if($(this).val() != deleteFilterArr[i])
	    			 { 
		    			 if(count == 0)
	    				 {
		    				 $("#" + deleteFilterId).val(deleteFilterArr[i]);
	    				 }else
    					 {
	    					 $("#" + deleteFilterId).val("," + deleteFilterArr[i]);
    					 }
		    			 count+= 1;
	    			 }
		    		//탭 필터 지웠을 시 다른탭 셀렉트
		    		 if($(this).attr('name') == "search_collectionList" && count == 1)
		    		 {
			    		 
			    		 $("#collection").val(deleteFilterArr[i]);
		    		 }
		    	 }
    		 }
    	 }else
    	 {
		     filter_mylist = filter_mylist.replace($(this).attr('name')+",",'');
		     
		     //생산년도는 input이 2개라 따로처리
		     if(deleteFilterId != "era"){
		    	 $("#" + deleteFilterId).val($("#" + deleteFilterId).val().replace($(this).val(),''));
	    	 }
		     else{
		    	 $("#createStartDate").val("");
		    	 $("#createEndDate").val("");
		     }
		     
    	 }
	     $("#filter_mylist").val(filter_mylist);
		fnFilterSch();  
	});
}
function fnLabel_reference(){
    var mylist_arr = $("#referencelistForm [name=filter_mylist]").val().split(",");
    var comparisonData;
    for(var j=0; j < mylist_arr.length ; j++){
        if(mylist_arr[j].indexOf("class") >= 0){    
            var checked = document.querySelectorAll("#referencelistForm [name='second_class']:checked");
                
            for(var i=0; i<checked.length; i++){
                var checkVal = util.xssCheck($(checked[i]).val());
                if(mylist_arr[j].indexOf(checkVal) >=  0 ){ 
                    var second_cate_id = "c_cate_"+ $(checked[i]).attr('id') +"_id_" +checkVal  ;
                    var first_cate_nm =$(checked[i]).parents('.depth-2').siblings('.depth-1').find('label').text();
                    var second_cate_nm = $(checked[i]).next().text(); 

                    first_cate_nm = first_cate_nm.substring(0,first_cate_nm.indexOf("(",-1));
                    second_cate_nm = second_cate_nm.substring(0,second_cate_nm.lastIndexOf("("));
                    
                    if(comparisonData != second_cate_id){
                        first_cate_nm = util.xssCheck(first_cate_nm);
                        second_cate_nm = util.xssCheck(second_cate_nm);
                        second_cate_id = util.xssCheck(second_cate_id);
                        $("#reference_fillter_append").append("<li>"+ first_cate_nm + " &#62; "+ second_cate_nm + "<button type=\"button\" name=\"first_agency_del\" class=\"btn-del-filter\"  id=\""+second_cate_id+"\">삭제</button></li>").text();
                       comparisonData = second_cate_id;
                    }
                    
                }
            }
        }
        else    if(mylist_arr[j].indexOf("category") >= 0){ 
            var checked = document.querySelectorAll("#referencelistForm [name='second_category']:checked");
            var comparisonData;
            //필터라벨
            for(var i=0; i<checked.length; i++){
                var checkVal = util.xssCheck($(checked[i]).val());
                if(mylist_arr[j].indexOf(checkVal) >=  0 ){ 
                    var second_cate_id = "j_cate_"+ $(checked[i]).attr('id') +"_id_" +checkVal  ;
                    var first_cate_nm =$(checked[i]).parents('.depth-2').siblings('.depth-1').find('input').next().text();
                    var second_cate_nm = $(checked[i]).next().text(); 
                    
                    first_cate_nm = first_cate_nm.substring(0,first_cate_nm.indexOf("(",-1));
                    second_cate_nm = second_cate_nm.substring(0,second_cate_nm.indexOf("(",-1));
                    
                    if(comparisonData != second_cate_id){
                        first_cate_nm = util.xssCheck(first_cate_nm);
                        second_cate_nm = util.xssCheck(second_cate_nm);
                        second_cate_id = util.xssCheck(second_cate_id);
                        $("#reference_fillter_append").append("<li>"+ first_cate_nm + " &#62; "+ second_cate_nm + "<button type=\"button\" class=\"btn-del-filter\"  id=\""+second_cate_id+"\">삭제</button></li>").text();
                        comparisonData = second_cate_id;
                    }
                    
                }
            }
        }
        else if(mylist_arr[j].indexOf("creat_all") >= 0){ 
        	$("#reference_fillter_append").append("<li>생산년도 &#62; 전체<button type=\"button\" class=\"btn-del-filter\"  id=\""+second_cate_id+"\">삭제</button></li>").text();
        }
        else if(mylist_arr[j].indexOf("creat_date") >= 0){ 
        	$("#reference_fillter_append").append("<li>생산년도 &#62; " + $("#creatYyyyStart").val() + "~" + $("#creatYyyyEnd").val() +"<button type=\"button\" class=\"btn-del-filter\"  id=\""+second_cate_id+"\">삭제</button></li>").text();
        }else if(mylist_arr[j].indexOf("agency") >= 0){
        	var second_cate_nm = mylist_arr[j].substring(mylist_arr[j].indexOf("_")+1);
        	$("#reference_fillter_append").append("<li>생산기관 &#62; "+ second_cate_nm + "<button type=\"button\" class=\"btn-del-filter\" id=\"" + second_cate_nm + "\" name=\"first_agency_del\" >삭제</button></li>").text();
        }/*else if(mylist_arr[j].indexOf("search_query") >= 0){
	    	$("#reference_fillter_append").append("<li>검색어 &#62; "+ $("#realQuery").val() + "<button type=\"button\" class=\"btn-del-filter detailFilter\" id=\"\" name=\"search_query\">삭제</button></li>").text();
	    }*/else if(mylist_arr[j].indexOf("search_bookIndex") >= 0){
	    	$("#reference_fillter_append").append("<li>목차 &#62; "+ $("#bookIndex").val() + "<button type=\"button\" class=\"btn-del-filter detailFilter\" id=\"\" name=\"search_bookIndex\" value=\"" + $("#bookIndex").val() + "\">삭제</button></li>").text();
	    }else if(mylist_arr[j].indexOf("search_mngtNo") >= 0){
	    	$("#reference_fillter_append").append("<li>관리번호 &#62; "+ $("#mngtNo").val() + "<button type=\"button\" class=\"btn-del-filter detailFilter\" id=\"\" name=\"search_mngtNo\" value=\"" + $("#mngtNo").val() + "\">삭제</button></li>").text();
	    }else if(mylist_arr[j].indexOf("search_era") >= 0){
	    	$("#reference_fillter_append").append("<li>연대 &#62; "+ $("#createStartDate").val() + "~" + $("#createEndDate").val() + "<button type=\"button\" class=\"btn-del-filter detailFilter\" id=\"\" name=\"search_era\">삭제</button></li>").text();
	    }else if(mylist_arr[j].indexOf("search_ageCode") >= 0){
	    	var ageCode_arr = $("#referencelistForm [name=ageCode]").val().split(",");
	    	for(var i=0; i < ageCode_arr.length ; i++)
	    	{
	    		$("#reference_fillter_append").append("<li>시대 &#62; "+ ageCodeNm(ageCode_arr[i]) + "<button type=\"button\" class=\"btn-del-filter detailFilter\" id=\"\" name=\"search_ageCode\" value=\"" + ageCode_arr[i] + "\">삭제</button></li>").text();
	    	}
	    }else if(mylist_arr[j].indexOf("search_collectionList") >= 0){
	    	var collectionList_arr = $("#referencelistForm [name=collectionList]").val().split(",");
	    	for(var i=0; i < collectionList_arr.length ; i++)
	    	{
	    		$("#reference_fillter_append").append("<li>이용구분 &#62; "+ collectionNm(collectionList_arr[i]) + "<button type=\"button\" class=\"btn-del-filter detailFilter\" id=\"\" name=\"search_collectionList\" value=\"" + collectionList_arr[i] + "\">삭제</button></li>").text();
	    	}
	    }
        
    } //for end
}

function ageCodeNm(ageCode){
	if(ageCode == null)
	{
		return ageCode;
	}
	if(ageCode == "03") return "선사";
	if(ageCode == "04|05|06") return "고대";
	if(ageCode == "07") return "고려";
	if(ageCode == "08") return "조선";
	if(ageCode == "11|12") return "근대";
	if(ageCode == "13|14") return "현대";
	if(ageCode == "02") return "시대미상";
	
	return ageCode;
}

function collectionNm(collection){
	if(collection == null)
	{
		return collection;
	}
	if(collection == "lib_online") return "온라인열람";
	if(collection == "lib_loan") return "대출";
	if(collection == "lib_offline") return "열람";
	if(collection == "lib_etc") return "기타";
	
	return collection;
}
function fnLabel_reference_detail(){
     $('#referencelistForm input[name=sojang_council]').prop("checked",false);
     $('#referencelistForm input[name=sido_name]').prop("checked",false);

     $("#referencelistForm .cmm-list-chk").each(function (index, item) {
             $(this).prop("checked",true);
     });  

     $("#reference_council_append").empty();
     
     var mylist_arr = $("#referencelistForm [name=filter_mylist]").val().split(",");
     
     for(var j=0; j < mylist_arr.length ; j++){
         if(mylist_arr[j].indexOf("council") >= 0){ 
             var checked = document.querySelectorAll("#referencelistForm [name='sojang_council']:checked");
                
                for(var i=0; i<checked.length; i++){
                    var checkVal = util.xssCheck($(checked[i]).val());
                    if(mylist_arr[j].indexOf(checkVal) >=  0 ){                 
                        var second_cate_id = $(checked[i]).attr('id')+"_id";
                        var second_cate_id_del = $(checked[i]).attr('id')+"_id_del";
                        var first_cate_nm =$(checked[i]).parents('.depth-2').siblings('.depth-1').find('input').next().text();
                        var second_cate_nm = $(checked[i]).next().text(); 
                        
                        first_cate_nm = first_cate_nm.substring(0,first_cate_nm.indexOf("(",-1));
                        second_cate_nm = second_cate_nm.substring(0,second_cate_nm.indexOf("(",-1));
                        
                        second_cate_id = util.xssCheck(second_cate_id);
                        second_cate_id_del = util.xssCheck(second_cate_id_del);
                        first_cate_nm = util.xssCheck(first_cate_nm);
                        second_cate_nm = util.xssCheck(second_cate_nm);
                        $("#reference_council_append").append("<li  id=\""+second_cate_id+"\"><button type=\"button\" title=\"삭제\"  id=\""+second_cate_id_del+"\"><span class=\"sign\">"+ first_cate_nm+" &gt; </span>"+ second_cate_nm+"</button></li>");
                    }
                }
         }//if end
     }//for end
        
    var checked2 = document.querySelectorAll("#referencelistForm [name='sido_name']:checked");
    for(var i=0; i<checked2.length; i++){
        $(checked2[i]).prop("checked", true);
    }
}
function fnFilterSch(){
	document.referencelistForm.action="/search/searchList.do";
    document.referencelistForm.submit();
}

