/**
 * @fileoverview 제품 Front 스크립트
 * @author realsnake@netville.co.kr
 * @version 1.0.0
 * @since 2009.06.08
 */

//------------------------------------------------------제품 카테고리 DWR
/**
 * 제품 카테고리 콤보박스 선택시 DWR 요청 함수
 */

function getProductImage(imagePath, imageName) {
    var imgName = "";
    if (imageName != null && imageName != undefined) {
        imgName = imageName.toLowerCase();    
    }
    return "/product"+imagePath + "/list_" + imageName.toLowerCase();    
}

function showCategoryListByDepth(depth, obj) {
    var prdCtgParentSeq = 0;

    if (typeof(obj) != "undefined") {    // "number", "string", "boolean", "object", "function", "undefined"
        prdCtgParentSeq = obj[obj.selectedIndex].value;
        initProductCategory(depth);
        if (prdCtgParentSeq == "") return;
    }
    
    var pc = new ProductCategory();
    pc.setPrdCtgParentSeq(prdCtgParentSeq);
    pc.setDepth(depth);
    pc.setUseFl("Y");

    ProductDWR.getProductCategoryListByDepth(pc, { 
        callback:function(productCategoryList) {
                callbackCategoryListByDepth(productCategoryList, pc);
            }
        } 
    );
}

/**
 * 제품 카테고리 콤보박스 선택시 DWR 요청 함수의 콜백 함수
 */
function callbackCategoryListByDepth(productCategoryList, productCategory) {
    var categoryLength = productCategoryList.length;
    var updateObj = "product_category_" + productCategory.depth;

    if (productCategory.depth > 1) {
        if (categoryLength == 0) { //더 이상 하위 카테고리가 없으므로 해당 카테고리의 제품 목록을 호출한다.
            showProductListByCategory(productCategory.prdCtgParentSeq);
            return;
        }
        
        dwr.util.byId("spn_" + updateObj).style.display = "";
    }

    dwr.util.removeAllOptions(updateObj);
    dwr.util.addOptions(updateObj, [ { prdCtgNm:"Please select ...", prdCtgSeq:"" } ], "prdCtgSeq", "prdCtgNm");

    for (var i=0; i<categoryLength; i++) {
        dwr.util.addOptions(updateObj, [ { prdCtgNm:productCategoryList[i].prdCtgNm, prdCtgSeq:productCategoryList[i].prdCtgSeq } ], "prdCtgSeq", "prdCtgNm");
    }
}

/**
 * 카테고리 초기화
 */
function initProductCategory(depth) {
    dwr.util.removeAllOptions("product_category_" + (depth));
    dwr.util.byId("spn_product_category_" + (depth)).style.display = "none";
    
    if (depth == 2) {
        dwr.util.removeAllOptions("product_category_" + (depth+1));
        dwr.util.byId("spn_product_category_" + (depth+1)).style.display = "none";
    }

    dwr.util.byId("spn_product").innerHTML = "";
    dwr.util.byId("spn_product").style.display = "none";
}

/**
 * 제품 목록 DWR 요청 함수
 */
function showProductListByCategory(obj) {
    var prdCtgSeq = 0;
    
    if (typeof(obj) == "object") prdCtgSeq = obj.value; 
    else if ((typeof(obj) == "string") || (typeof(obj) == "number")) prdCtgSeq = obj;
    else return;
    
    var p = new Product();
    p.setPrdCtgSeq(prdCtgSeq);
    p.setLangCd("KO");
    p.setDetailCd("COM");
    p.setUseFl("Y");

    ProductDWR.getProductListByCategory(p, { 
        callback:function(productList) {
                callbackProductListByCategory(productList, p);
            }
        } 
    );
}

/**
 * 제품 목록 DWR 요청 함수의 콜백 함수
 */
function callbackProductListByCategory(productList, product) {
    var productLength = productList.length;

    if (productLength == 0) { // 해당 카테고리의 제품 목록이 존재하지 않는다.
        alert("제품 목록이 존재하지 않습니다.");
        return;
    }

    dwr.util.byId("spn_product").style.display = "";

    dwr.util.removeAllOptions("product");
    dwr.util.addOptions("product", [ { langPrdNm:"Please select ...", langPrdSeq:"" } ], "langPrdSeq", "langPrdNm");

    var productListHtml = "<select id=\"product\" name=\"product\">";
    productListHtml += "    <option value=\"\">Please selected ...</option>";

    for (var i=0; i<productLength; i++) {    // 이 무슨 어이없는... 값은 제대로 들어오나 dwr util이 동작하지 않는다.
        productListHtml += "    <option value=\"" + productList[i].langPrdSeq + "\">" + productList[i].langPrdNm + "</option>";
    }
    
    productListHtml += "</select>";
    dwr.util.byId("spn_product").innerHTML = productListHtml;
}

/**
 * Product Finder 정보 조회함수
 */
function getProductFinderList(prdCtgSeq, curPage, effectivePixels, lcdScreen, iso, opticalZoom, otherOption){
    ProductDWR.getProductFinderList(prdCtgSeq, curPage, effectivePixels, lcdScreen, iso, opticalZoom, otherOption, getProductFinderListCallBack);
} 

/**
 * Product Finder 정보 조회 callback 함수
 */
function getProductFinderListCallBack(data){
    try{
    // 이미지 서버 : 상수
    var IMAGE_SERVER = dwr.util.byId("imageServer").value;  
    // 웹 서버 : 상수
    var WEB_SERVER = dwr.util.byId("webServer").value;
    
    //0보다 클경우만 루프를 돌려 contents 목록을 생성
    var htmlString = "";
    var totalCount = data.totalCount;
    if (data.totalCount == undefined) {
        totalCount = 0;
    }
    
    var curPage = data.curPage;
    var listLines = data.listLines;
    var listPages = data.listPages;
    var pageScript = "pageScript";
    if(totalCount > 0) {       
        var resultMap = data.VOMap.resultMap;
        var imgPathList = data.VOMap.imgPathList;
        for(i=0; i<resultMap.length; i++) {
            
            if ((i+1) == resultMap.length) {
                htmlString += "		<div class=\"clearfix mgt10 pos_r pab9\">";
            } else {
                htmlString += "		<div class=\"clearfix mgt10 bdr_btm01 pos_r\">";    
            }
            htmlString += "			<div class=\"floatl\">";
            htmlString += "				<p class=\"textcenter\"><img src=\"" + imgPathList[i] + "\" onmouseover=\"this.style.cursor='hand';\" onclick=\"goViewPage('" + resultMap[i].prdCtgSeq + "','" + resultMap[i].langPrdSeq + "')\" alt=\""+ resultMap[i].langPrdNm+"\" /></p>";
            htmlString += "				<p class=\"mgt5 col_type textcenter\" id=\"ColorCircle"+resultMap[i].langPrdSeq+"\"></p>";
            htmlString += "			</div>";
            htmlString += "			<div class=\"floatl mgl20 \">";
            htmlString += "				<input type=\"checkbox\" id=\"langPrdSeqs\" name=\"langPrdSeqs\" value=\"" + resultMap[i].langPrdSeq + "\" />";
            htmlString += "				<dl class=\"mgt4 dslr_info\">";
            htmlString += "					<dt><a href=\"javascript:goViewPage('" + resultMap[i].prdCtgSeq + "','" + resultMap[i].langPrdSeq + "')\">" + resultMap[i].langPrdNm + "</a>";
            if (resultMap[i].newPrdFl == "Y") {
            	htmlString += "                 <img src=\"" + IMAGE_SERVER + "/img/common/mygallery/icon_new.gif\" alt=\"new\" class=\"mgt7\" /></dt>";
            } else {
            	htmlString += "				</dt>";	
            }
            var tempSalesPoint = resultMap[i].salesPoint;
            
            var separ = "\r\n";
            var salesPoint;
            if (tempSalesPoint != "" && tempSalesPoint != null) { //20090721bae
            	salesPoint = tempSalesPoint.split(separ);
            	if (salesPoint[0] != null && salesPoint[0] != "") {
            		htmlString += "					<dd>" + salesPoint[0] + "</dd>";
            	}
            	if (salesPoint[1] != null && salesPoint[1] != "") {
            		htmlString += "					<dd>" + salesPoint[1] + "</dd>";
            	}
            	if (salesPoint[2] != null && salesPoint[2] != "") {
            		htmlString += "					<dd>" + salesPoint[2] + "</dd>";
            	}
            }
            htmlString += "				</dl>";
            htmlString += "				<div class=\"btn_posm3\"><a href=\"javascript:goViewPage('" + resultMap[i].prdCtgSeq + "','" + resultMap[i].langPrdSeq + "')\"><img src=\"" + IMAGE_SERVER + "/img/community/learn/btn_more01.gif\" alt=\"상세보기\" /></a>";
            if(resultMap[i].swfUrlUseFl == "Y" && resultMap[i].swfUrl != "" && resultMap[i].swfUrl != null){ //20090715수정null check
            	htmlString += "				<a href=\"javascript:goFlashPopUp('" + WEB_SERVER + resultMap[i].swfUrl + "')\"><img src=\"" + IMAGE_SERVER + "/img/community/learn/btn_ultimate.gif\" alt=\"플래시 무비\" class=\"mgl7\" /></a>";
            }
            htmlString += "			</div></div>";
            htmlString += "		</div>";
        }
        htmlString += "	<div class=\"bdr_btm02\"></div>";
        //htmlString += "	<input type=\"hidden\" name=\"prdCtgNm\" id=\"prdCtgNm\" value=\"<%=resultMap[0).get("prdCtgNm"))) %>\"/>";
        
        curPage = data.curPage;
        
    }
    dwr.util.byId("productMatches").innerHTML = htmlString;
    //페이징 네비게이션 HTML 생성하는 PaggingDWR.getPageHtmlScriptByCommunityCount 호출 callback: setPagehtml = 페이징 네이게이션을 화면에 그려준다
    PaggingDWR.getPageHtmlScriptByCount(pageScript, curPage,listLines, listPages,totalCount, setPageHtml);
    
    
    // product circle color
    if(totalCount > 0) {       
        var resultMap = data.VOMap.resultMap;
        for(i=0; i<resultMap.length; i++) {
        	var so = new SWFObject(WEB_SERVER+"/swf/product/ColorCircle.swf", "ColorCircle_flash", "98", "8", "10.0.22", "#FFFFFF");
            if(resultMap[i].langPrdSeq != null ){
                var imgRgbs = resultMap[i].imgRgbs;
                so.addVariable("color", imgRgbs);//20090721bae
                so.addParam("wmode", "opaque");
                so.addParam("menu", "false");
                so.addParam("AllowScriptAccess", "always");
                so.write("ColorCircle"+resultMap[i].langPrdSeq);
            }
        }
    }
     
    
    // 파라미터가 전달 되었을때 totalCount 를 뿌려줌
    if (data.paramFlag == "Y") {
        dwr.util.byId("totalCount").innerHTML = totalCount;
    // 파라미터가 없고 조회결과가 없으면 totalCount 를 뿌려줌 (totalCount = 0)
    } else if (data.paramFlag == undefined && data.totalCount == undefined) {
        dwr.util.byId("totalCount").innerHTML = totalCount;
    // 파라미터가 없을때 'ALL' 을 뿌려줌
    } else {
        dwr.util.byId("totalCount").innerHTML = "전체";
    }
    }catch(e){alert(e)}
     
} 

/**
 * Product Map 정보 조회함수
 */
function getProductMapList(prdCtgSeq, division){
    ProductDWR.getProductMapList(prdCtgSeq, division, getProductMapListCallBack);
} 

/**
 * Product Finder 정보 조회 callback 함수
 */
function getProductMapListCallBack(data){
    dwr.util.byId("mapContents").innerHTML = data.htmlString;
}

/**
 * PaggingDWR.getPageHtmlScriptByCommunityCount 의 callback 함수로써 페이지 네비게이션을 화면에 그려준다
 */
function setPageHtml(data){
    dwr.util.byId("paging").innerHTML = data;
}
//------------------------- 추가개편 START------------------------
/**
 * 타이머 변수 
 */
var tid = null;
/**
 * 0.5초의 시간차로 데이터 조회
 * @param obj
 * @param prdCtgSeq
 * @param langPrdSeq
 * @return
 */
function getProductPopView(obj, langPrdSeq) {
	tid = setTimeout(function(){excuteProductDWR(obj, langPrdSeq)}, 500); 

}

/**
 * 제품 정보 
 * @param obj
 * @param langPrdSeq
 * @return
 */
function excuteProductDWR(obj, langPrdSeq) {
	//dwr.util.byId(obj).style.display='block';
	ProductDWR.getProductPopView(langPrdSeq, getProductPopViewCallBack);
}
/**
 * Product PopView 정보 조회 callback 함수
 * @param data
 * @return
 */
function getProductPopViewCallBack(data){
	//dwr.util.byId("popContent").style.display='block';
	popContent.style.visibility='visible';
	dwr.util.byId("popContent").innerHTML = data.htmlString;
}

/**
 * 제품 설명 레이어 감추기
 * @param obj
 * @return
 */
function productViewOut(obj) {
	clearTimeout(tid);
	//document.getElementById(obj).visibility='hidden';
	popContent.style.visibility='hidden';
	dwr.util.byId(obj).innerHTML = null;
}

//------------------------- 추가개편 END------------------------
function getEventPosition(evt) {
	 var e = evt || window.event;
	 var b = document.body;
	 var scroll = getScrollOffset();
	 var pos = {
	  x : e.pageX || e.clientX+scroll.x-b.clientLeft,
	  y : e.pageY || e.clientY+scroll.y-b.clientTop
	 }
	 return pos;
}
function getScrollOffset(win) {
	 if (!win) win = self;
	 var x = win.pageXOffset || win.document.body.scrollLeft || document.documentElement.scrollLeft || 0;
	 var y = win.pageYOffset || win.document.body.scrollTop || document.documentElement.scrollTop || 0;
	 return { x:x, y:y };
}

	/* str : 20100812  */
	function setPreviewBox(evt, obj, imgPath, prdNm, prdSalesPoint){
		var pos = getEventPosition(evt);
		var openProduct = document.getElementById(obj);
		var cw = ((document.body.clientWidth)/2 + 170);

		if (pos.x < cw ){
			openProduct.style.left = (pos.x + 10) + 'px'; 
		}else{
			openProduct.style.left = (pos.x - 355) + 'px'; 
		}
		openProduct.style.top = (pos.y + 10)+ 'px';  
		
		var prdPop;   
		
		prdPop = "<div class=\"clearfix\">";
		prdPop += 	"<div class=\"photo\"><img src="+imgPath+" \"alt=\"제품 이미지\"></div>";
		prdPop +=		"<dl>";
		prdPop +=			"<dt>"+prdNm+"</dt>";
		prdPop += 				prdSalesPoint;
		prdPop +=		"</dl>";
		prdPop += "</div>"; 
		
		openProduct.innerHTML=prdPop;   
		openProduct.style.display = '';
	} 
	
	function hidePreview(obj)  
	{   
		var openProduct = document.getElementById(obj);
		openProduct.innerHTML='';   
		openProduct.style.display='none';   
	}
	/* end : 20100812 */ 
//------------------------------------------------------제품 카테고리 DWR

String.prototype.trim = function() {
    return this.replace(/\s/g, "");   
}

//------------------------------------------------------제품 S/N 유효성 검사 DWR
function checkSerialNumber() {
    var serialNumber = $("serialNumber").value.trim();
    //camera camcorder 20090730
    var productName = $("product_category_1").options[$("product_category_1").selectedIndex].text.trim();
    ProductDWR.checkSerialNumber(serialNumber, productName, { 
        callback:function(resultValue) {
                callbackCheckSerialNumber(resultValue, serialNumber);
            }
        } 
    );
}

function callbackCheckSerialNumber(resultValue, serialNumber) {
    var resultText = "유효한 제품 S/N가 아닙니다!";
    if (resultValue) resultText = "유효한 제품 S/N입니다.";
    $("result_check_sn").innerHTML = resultText;
}
//------------------------------------------------------제품 S/N 유효성 검사 DWR

