/*##############################################################################
DATE OF CREATION :		2009.09.01.
FILE DISCRIPTION :		Pressblog v4.0 pressblog javascript file.
POWERED BY : 			ⓒ2009 DOHOON, LEE (TUFFKID.NET™)
##############################################################################*/

Array.prototype.removeSame = function() {
	var oldArray = this;
    var b = [];
    var j = 0;
    //oldArray.sort();
    while(oldArray.length > 0) {

        var newKey = oldArray.shift();
        if(j == 0) {
        
            b.push(newKey);
            j++;

        } else if(b[j-1] != newKey) {

            b.push(newKey);
            j++;    

        }
    }
    return b;
};

function smcp(_imgId)
{
  var _img = document.getElementById(_imgId);     
  
  _cr = document.body.createControlRange();
  if(_cr)
  {
    _cr.addElement(_img); 
    _cr.execCommand('copy'); 
    jAlert("태그 이미지를 자동 복사하였습니다.\n\n지금 바로 작성한 글에 붙여넣기(Ctrl+V)해주세요.\n\n붙여 넣은 즉시 작성한 글의 뷰카운팅이 프레스블로그에 자동 체크됩니다.");
  }
  else
  {
    jAlert("태그 이미지를 복사하지 못했습니다.\n\n좌측의 태그 이미지를 마우스의 오른쪽 버튼으로 클릭한 후 '복사'를 선택하면 수동으로 복사가 됩니다.");
  }
}

Array.prototype.unique = function()
{
  var a = {};
  for(var i=0; i<this.length; i++)
  {
    if(typeof a[this[i]] == "undefined")
      a[this[i]] = 1;
  }
  this.length = 0;
  for(var i in a)
    this[this.length] = i;
  return this;
}

function copy_clip(meintext) {
    if (window.clipboardData) { // IE일 경우
        window.clipboardData.setData("Text", meintext);
    } else if (window.netscape) { // NS일 경우
        // you have to sign the code to enable this, or see notes below
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

        var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
        if (!clip) return;

        var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return;

        trans.addDataFlavor('text/unicode');

        var str = new Object();
        var len = new Object();

        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

        var copytext = meintext;    // 로컬변수에 복사
        str.data = copytext;

        trans.setTransferData("text/unicode",str,copytext.length*2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clipid) return false;

        clip.setData(trans,null,clipid.kGlobalClipboard);
    } 
    jAlert("태그 이미지 HTML 코드를 자동 복사하였습니다.\n지금 바로 작성한 글에 HTML 코드를 붙여넣기(Ctrl+V)해주세요.");
    return false;
}

$(function(){
	// PV태그 복사
	$("#copy_tag_img").click(function(){
		copy_clip('<img src="'+$("#viewCntCode").val()+'">');
	});
	

	

	
	//블로거 퍼스트 리뷰 작성
	$("#blogfirst_review_apply").click(function(){
		var post_url = $('#post_url').val();	
		var user_comment = $('#user_comment').val();	
		var tid = $('#tid').val();	
		
		if(post_url == "" || post_url =="") jAlert("포스트 URL 을 입력하세요.");
		else if(!user_comment || post_url =="리뷰 한마디") jAlert("참여한마디를 입력하세요.");
		else if(strlen_charCodeAt(user_comment) > 200) {
			jAlert("참여한마디는 200Byte 까지만 입력이 가능합니다.");
		}else{
			$.post("/pressblog/bloggerfirst/bf_review_add", {ajax:"true", post_url:post_url, user_comment:user_comment, tid:tid},function(data){
				eval("var obj=" + data);  
				if(obj.result == "0"){
					jAlert(obj.msg)	
				}else{
					location.reload();
					//jAlert(obj.result)
				}
			});
		}
	});
	
	//블로거 퍼스트 리뷰 수정
	$("#blogfirst_review_update").click(function(){
		var post_url = $('#post_url_mod').val();	
		var user_comment = $('#user_comment_mod').val();	
		var tid = $('#tid').val();	
		
		if(post_url == "") jAlert("포스트 URL 을 입력하세요.");
		else if(!user_comment) jAlert("참여한마디를 입력하세요.");
		else if(strlen_charCodeAt(user_comment) > 200) {
			jAlert("참여한마디는 200Byte 까지만 입력이 가능합니다.");
		}else{
			$.post("/pressblog/bloggerfirst/bf_review_update", {ajax:"true", post_url:post_url, user_comment:user_comment, tid:tid},function(data){
				//jAlert(data);
				eval("var obj=" + data);  
				if(obj.result == "0"){
					jAlert(obj.msg)	
				}else{
					location.reload();
				}
			});
		}
	});	
	
	
	
	//블로거 퍼스트 리뷰 수정창 닫기
	$("#review_edit_hidden").click(function(){
		$('#review_edit_top').hide();
	});	
	
	//블로거 퍼스트 리뷰 삭제
	//$("[id^='blogfirst_review_delete_']").click(function(){
	$("[id^='blogfirst_review_delete_']").live("click", function(){
		var tid = this.id.split("_")[3];
		jConfirm('정말로 삭제하시겠습니까?','삭제확인', function(r){
			if(r==true){
				$.post("/pressblog/bloggerfirst/bf_review_delete", {ajax:"true", tid:tid},function(data){
					//jAlert(data);
					eval("var obj=" + data);  
					if(obj.result == "0"){
						jAlert(obj.msg)	
					}else{
						location.reload();
					}
				});
			}
		});
	});	
	
	// 블로거 퍼스트 리뷰등록
	//1. 수정
	//$("#bf_review_modify").click(function(){
	$("#bf_review_modify").live("click", function(){
		var tid = $(this).attr("tid");
		$(".review_modify_field").hide();//열려진 모든 것 닫기
		
		$(".review_field").each(function(i, elem){	
			if($(this).attr("tid") == tid) $(this).hide();
		});
		
		$(".review_modify_field").each(function(i, elem){	
			if($(this).attr("tid") == tid) $(this).show();
		});
		
		$(this).hide();
			
		$("#bf_review_modify_ex").show();
		$("#bf_review_modify_cancel").show();
		
	});
	//2. 수정취소
	//$("#bf_review_modify_cancel").click(function(){
	$("#bf_review_modify_cancel").live("click", function(){

		$(".review_modify_field").hide();//열려진 모든 것 닫기
		$(".review_field").show();//열려진 모든 것 닫기

		
		$("#bf_review_modify").show();
		$("#bf_review_modify_ex").hide();
		$("#bf_review_modify_cancel").hide();
		
	});		
	
	//3.  수정실행
	//$("#bf_review_modify_ex").click(function(){
	$("#bf_review_modify_ex").live("click", function(){
		var post_url;	
		var user_comment;	
		var tid = $(this).attr("tid");
		var service_tid = $("#service_tid").val();
		
		$(".post_url").each(function(i, elem){	
			if($(this).attr("tid") == tid) post_url = $(this).val();
		});
		$(".user_comment").each(function(i, elem){	
			if($(this).attr("tid") == tid) user_comment = $(this).val();
		});
		
		if(post_url == "") jAlert("포스트 URL 을 입력하세요.");
		else if(!user_comment) jAlert("참여한마디를 입력하세요.");
		else if(strlen_charCodeAt(user_comment) > 200) {
			jAlert("참여한마디는 200Byte 까지만 입력이 가능합니다.");
		}else{
			$.post("/pressblog/bloggerfirst/bf_review_update", {ajax:"true", post_url:post_url, user_comment:user_comment, tid:tid, service_tid:service_tid},function(data){
				//jAlert(data);
				eval("var obj=" + data);  
				if(obj.result == "0"){
					jAlert(obj.msg)	
				}else{
					location.reload();
				}
			});
		}
	});	
	

	// 블퍼 신청 팝업 > 신청취소 클릭시
	$("#bf_cancel_x").click(function(){
		$(".floatingLayers").hide();
		$("#layerBack").hide();
	});

	// 프리미어블로그 신청완료
	$("#premier_submit_btn").click(function(){
		var fields = new Array();
		$("#premier_apply_frm input[type='text'], input[type='checkbox'], input[type='radio'], textarea").each(function(i){
			var gid = this.name.split("_")[1];
			fields[i] = this.name;
		});
		
	
		var newFields = fields.removeSame();
		var swt = 0;
		$(newFields).each(function(i, name){
			if(name.indexOf("gr_") >= 0) { // 라디오 따위
				var cnt = 0;
				$("input[name^='"+name+"']").each(function(j, name){
					if(name.checked==true) {
						cnt += 1;
					}
					title = $(name).attr('title');
				});
				
				title = title.split("<br />")[0];
				title = title.split("<br>")[0];
				
				if(cnt <= 0) {
					jAlert(title +"을(를) 선택하세요");
					swt=0;
					return false;
				} else {
					swt=1;
				}
			}
			
			if(name.indexOf("gc_") >= 0) {
				var cnt = 0;
				
				$("input[name^='"+name+"']").each(function(j, name){
					if(name.checked==true) {
						cnt += 1;
					}
					title = $(name).attr('title');
				});
				
				title = title.split("<br />")[0];
				title = title.split("<br>")[0];

				if(cnt <= 0) {
					jAlert(title +"을(를) 선택하세요");
					swt = 0;
					return false;
				} else {
					swt = 1;
				}
			}
			
			if(name.indexOf("gt_") >= 0) {
				if ($("input[name^='" + name + "']").val() == "") {
					var title = $("input[name^='" + name + "']").attr("title");
					title = title.split("<br />")[0];
					title = title.split("<br>")[0];
					
					jAlert(title + "을(를) 입력해주세요");
					swt = 0;
					return false;
				} else {
					swt = 1;
				}
			} 
			if(name.indexOf("gtt_") >= 0) {
				if ($("textarea[name^='" + name + "']").val() == "") {
					var title = $("textarea[name^='" + name + "']").attr("title");
					title = title.split("<br />")[0];
					title = title.split("<br>")[0];
					
					jAlert(title + "을(를) 입력해주세요");
					swt = 0;
					return false;
				} else {
					swt = 1;
				}
			}
		});

		if (swt == 1) {
			if (a = confirm("현재 정보로 신청을 완료하시겠습니까?") == true) {
				$("#premier_apply_frm").attr("action", "/pressblog/premier/apply_x");
				$("#premier_apply_frm").submit();
			}
		}
		
	});
	
	//메인의 '?"에 대한 각각의 팝업창
	//$("[id^='q_']").click(function(){
	 $("[id^='q_']").live("click", function(){
											
										
		var popup = this.id.split("_")[1];

		var position = $(this).position();
		var left;
		var top;
		var filename;
		
		var body_center_x = document.documentElement.clientWidth/2;
		var body_center_y = document.documentElement.clientHeight/2;
		
		//각각에 대한 위치값 보정
		switch(popup){
			case "infoletteris"://정보레터
				top = position.top;
				filename = "help_infoletter.php";
			break;
			case "bloggerfirstis"://블로거퍼스트
				top = position.top;
				filename = "help_blogerfirst.php";
			break;	
			case "premierbloggeris"://프리미어블로거
				
				//left = position.left;
				//left = (body_center_x * (layer_center_x - ) )/layer_center_x
				//left = body_center_x - $("#infoPop").width()/2;
				top = position.top;
				filename = "help_premierblog.php";
			break;	
			case "50shopis"://50샵
				top = position.top;
				filename = "help_50shop.php";
			break;	
			case "mpis"://Monthly posting
				top = position.top;
				filename = "help_mp.php";
			break;	
			case "wpis"://Weekly posting
				top = position.top;
				filename = "help_wp.php";
			break;			
			case "thereview"://더리뷰
				top = position.top;
				filename = "help_review.php";
			break;	
			case "letterTip"://더리뷰
				top = position.top;
				filename = "help_lettertip.php";
			break;	
		}

		
		$.post("/pressblog/util/info_pop", {ajax:"true", filename:filename}, function (data){
			$('#infoPop').html(data);
			floatingLayerBack();
			left = body_center_x - $("#infoPop").width()/2;
			//top = body_center_y + $("body").scrollTop() - $("#infoPop").height()/2;
			top = body_center_y + $(document).scrollTop() - $("#infoPop").height()/2;
			$("#infoPop").css({"position":"absolute", "left" : left+"px", "top" : top+"px", "z-index":"2010"}).toggle().draggable();	
		});
		
	});	
	
	//메인의 '?"에 대한 각각의 팝업창
	$("#info_close").live("click", function(){
	//$("a[id^='q_close_']").click(function(){
		//var classval = this.id.split("_")[2];
	
		$("#layerBack").hide();
		$("#infoPop").hide();
		//eval('$(".'+classval+'").hide()');
	});

	//프로파일용 이미지 시작 pressblog.js에도 블로그 퍼스트 리뷰참여용으로 사용
	$("#addInfoImg").click(function(){//
		$.post("/mypage/etc/addImg/ajax/true", {}, function (data){
			floatingLayerBack();
			$('#dynamicPop').html(data);
			$("#dynamicPop").locationcenter().css({"position":"absolute","z-index":"2000"}).toggle();
		});
	});


	//프로파일용 이미지 끝


	//블로거 퍼스트 more클릭시 페이지 리스팅
	
	$("#btn_more_all").click(function(){
		getreveiwListAll();
	});
	
});
	var page = 0;
	function getreveiwList(){
		var tid = $("#tid").val();
		$("#btn_more_all").hide();
		$.post("/pressblog/bloggerfirst/get_reveiw_list", {tid:tid, cp:page, ajax:"true", smode:"good"},function(data){
			$("#reviewList").html(data);	
		});//, "json"
	}
	
	function getreveiwListAll(){
		var tid = $("#tid").val();
		page = page+1;
		$("#btn_more_all").show();
	
		$.post("/pressblog/bloggerfirst/get_reveiw_list", {tid:tid, cp:page, ajax:"true", smode:"all"},function(data){
			$("#reviewListall").html($("#reviewListall").html()+data);	
		});//, "json"
	}	
	

	function strlen_charCodeAt(str) {
		var i = 0;
		var lenNum = str.length;
		var tmp = 0;
		var byte = 0;
		for(i=0;i<lenNum;i++) {
			tmp = str.charCodeAt(i);
			if(tmp > 1000) { //크기 비교를 하는 기준 값으로 127를 기준으로 잡는 코드도 있습니다.
			// 줄바꿈(\n) - 10 , 빈공간(" ") - 32, \r - 13, 탭 - 9 의 값을 갖는다. 이러한 경우에 바이트를 계산하지 않는 경우도 있다.
				byte = byte+1;
			}
			byte = byte+1;
		}
		return byte;
	}
