var tweetnum=3;
var sendnum=1;
$(document).ready(function() {
    // 페이지초기화
   $('#navi_page').val('1');
   var twtid="";
    
    // 한국날짜로 바꾸어 주는함수
    function changeLocaleDate(pDate) {
        var pLocalDate = new Date(pDate);
        return pLocalDate.toLocaleString().replace('GMT+0900 (Japan Standard Time)', '');
    }
    
    // 더보기
    $('.more_btn').click(function() {
        if ($('#dvNothing').length == 0) {
            $('#navi_page').val(Number($('#navi_page').val()) + 1);
            $('#more_img').attr('src','images/more-loader.gif');            
            getTweet("more",$('#navi_page').val());
            $('#more_img').attr('src','images/more_bt.gif');
        }
    });

    // 닫기
    $('#spClose').click(function() {
        if ($('#navi_page').val() != "1") {
            $('#page' + $('#navi_page').val()).remove();
            $('#navi_page').val(Number($('#navi_page').val()) - 1);
        }
    });
    
    $('.puase').click(function() {
    	
    	clearInterval(tid);
    	$('.puase').css('cursor','default');
    	$('.reflash').css('cursor','pointer');
    	$('.puase').attr('src','images/btn_puase_off.gif');
    	$('.reflash').attr('src','images/btn_reflash_on.gif');
    	$('.realtime').css('color','#9b9a9a');
    	$('.realtime').text('최신글 검색결과');    	
    });
    $('.reflash').click(function() {
    	clearInterval(tid);
    	
    	$('.puase').css('cursor','pointer');
    	$('.reflash').css('cursor','default');
    	$('.puase').attr('src','images/btn_puase_on.gif');
    	$('.reflash').attr('src','images/btn_reflash_off.gif');
    	$('.realtime').css('color','#FF9B30');
    	$('.realtime').text('실시간 업데이트 중..');
    	if(tweetnum<1){
    		
    		getTwitter(5);        	
    		$('#navi_page').val('1');
    		        	
    		getTweet("",$('#navi_page').val());
    		
    		tweetnum=3;
    		$('.puase').css('cursor','pointer');
        	$('.reflash').css('cursor','default');
        	$('.puase').attr('src','images/btn_puase_on.gif');
        	$('.reflash').attr('src','images/btn_reflash_off.gif');
        	$('.realtime').css('color','#FF9B30');
        	$('.realtime').text('실시간 업데이트 중..');
        	
        	tid=setInterval(showtweet,1500);
    	}
    	else{
    		tid=setInterval(showtweet,1500);    		
    	}    	
    });
        
    $('.ollehkt').click(function() {
    	$('#timeline').html("");
    	$('#navi_page').val(1);
    	getApi("ollehkt");
    });
    $('.LG_TheBLOG').click(function() {
    	$('#timeline').html("");
    	$('#navi_page').val(1);
    	getApi("LG_TheBLOG");
    });
    $('.all_view_span').click(function() {
    	clearInterval(tid);
    	getTwitter(5);
    	$('#timeline').html("");
    	$('#navi_page').val('1');        	
    	getTweet("",$('#navi_page').val());
    	tweetnum=3;
    	
    	$('.puase').css('cursor','pointer');
        $('.reflash').css('cursor','default');
        $('.puase').attr('src','images/btn_puase_on.gif');
        $('.reflash').attr('src','images/btn_reflash_off.gif');
        $('.realtime').css('color','#FF9B30');
    	$('.realtime').text('실시간 업데이트 중..');        
        	
        tid=setInterval(showtweet,1500);
    	    	
    });
    $('.buzz_view_span').click(function() {
    	clearInterval(tid);
    	getTwitter(5);
    	$('#timeline').html("");
    	$('#navi_page').val('1');        	
    	getTweet("buzz",$('#navi_page').val());
    	tweetnum=3;
    	
    	$('.puase').css('cursor','pointer');
        $('.reflash').css('cursor','default');
        $('.puase').attr('src','images/btn_puase_on.gif');
        $('.reflash').attr('src','images/btn_reflash_off.gif');
        $('.realtime').css('color','#FF9B30');
    	$('.realtime').text('실시간 업데이트 중..');        
        	
        tid=setInterval(showtweet,1500);
    	    	
    });
    $('.my_view_span').click(function() {
    	clearInterval(tid);
    	getTwitter(5);
    	$('#timeline').html("");
    	$('#navi_page').val('1');        	
    	
    	getTweet($('#screen_name').text(),$('#navi_page').val());
    	tweetnum=3;
    	
    	$('.puase').css('cursor','pointer');
        $('.reflash').css('cursor','default');
        $('.puase').attr('src','images/btn_puase_on.gif');
        $('.reflash').attr('src','images/btn_reflash_off.gif');
        $('.realtime').css('color','#FF9B30');
    	$('.realtime').text('실시간 업데이트 중..');
        	
        tid=setInterval(showtweet,1500);   	
    });
    //홈페이지 로딩시 실행
    if($('#screen_name').text()==''){
    	$('#btn_update_status').attr("disabled", true);
    	
    }else{
    	$('#btn_update_status').attr("disabled", false);
    	
    }
    getTwitter(5);
    getTweet("",$('#navi_page').val());
    tid=setInterval(showtweet,1500);
});
//데이터 db에서 가져오기
function getTweet(qname,page) {
	
	if(qname==""){
		$('#timeline').html("");
	}
	
	if (window.XMLHttpRequest){
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}else {
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			$('#timeline').append(xmlhttp.responseText);
		}
	}    	
	xmlhttp.open("GET","get_tweet.php?q="+qname+"&p="+page+"&id="+$('#screen_name').text(),true);
	xmlhttp.send();
}
//트윗글 보네기
function sendTweet(num,msg) {
	$('#load_bar').css('display','block');
	if (window.XMLHttpRequest){
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
		
	}else {
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	xmlhttp.onreadystatechange=function(){
		
		if (xmlhttp.readyState==4 && xmlhttp.status==200){			
			$('#timeline').prepend(xmlhttp.responseText);
			$('#mt'+(sendnum-1)).slideDown("slow");
			$('#load_bar').css('display','none');
			$('#contents').val('');
			$('#contents').focus();
		}
	}    	
	var url = encodeURI("send_tweet.php?num="+num+"&msg="+msg+"&id="+$('#screen_name').text());
	xmlhttp.open("GET",url);
	xmlhttp.send();
}
//데이터 트위터에서 가져오기
function getTwitter(rpp) {
	
	if (window.XMLHttpRequest){
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}else {
		// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			
		}
	}    	
	xmlhttp.open("GET","twt_cron.php?rpp="+rpp,true);
	xmlhttp.send();
}
//데이터 삭제하기
function delTweet(tw_code,parent_id) {
	
	if(tw_code==""){
		
	}else{
		if(confirm('삭제하시겠습니까?')) {
			if (window.XMLHttpRequest){
				// code for IE7+, Firefox, Chrome, Opera, Safari
				xmlhttp=new XMLHttpRequest();
			}else {
				// code for IE6, IE5
				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			
			xmlhttp.onreadystatechange=function(){
				if (xmlhttp.readyState==4 && xmlhttp.status==200){
					$("#"+parent_id).slideUp("slow");
				}
			}    	
			xmlhttp.open("GET","del_tweet.php?tw_code="+tw_code,true);
			xmlhttp.send();
	    } else {
	        
	    }
		
	}
}
function showtweet() {
	if(tweetnum<1){
		clearInterval(tid);		
    	$('.puase').css('cursor','default');
    	$('.reflash').css('cursor','pointer');
    	$('.puase').attr('src','images/btn_puase_off.gif');
    	$('.reflash').attr('src','images/btn_reflash_on.gif');
    	$('.realtime').css('color','#9b9a9a');
    	$('.realtime').text('최신글 검색결과');   
	}
	else{
		$('#st'+tweetnum).slideDown("slow");
		tweetnum--;
	}
	
}
//배경색 바꾸기
function bg_change(flag,div_id){
	if(flag==1){
		$('#'+div_id).css('background-color','#ececec');
		$('#'+div_id+' .actions-hover').css('visibility','visible');
	}else{
		str = div_id.replace("st", "");
		div_num = str.replace("mt", "");
		if(div_num%2==0){
			$('#'+div_id).css('background-color','#fbfbfb');
			$('#'+div_id+' .actions-hover').css('visibility','hidden');
		}else{
			$('#'+div_id).css('background-color','#ffffff');
			$('#'+div_id+' .actions-hover').css('visibility','hidden');
		}
	}

}
//icon바꾸기
function icon_change(flag,icon_name){
	if(flag==1){
		if(icon_name=='reply'){
			$('.actions-hover .reply-icon').css('background-position','-15px 0');			
		}else if(icon_name=='retweet-link'){
			$('.retweet-icon').css('background-position','-80px 0');
		}else if(icon_name=='del_tweet'){
			$('.del-icon').css('background-position','-47px 0');
		}else{}
		$('.del-icon').css('text-decoration','underline');
		
	}else{
		if(icon_name=='reply'){
			$('.actions-hover .reply-icon').css('background-position','0 0');			
		}else if(icon_name=='retweet-link'){
			$('.retweet-icon').css('background-position','-64px 0');
		}else if(icon_name=='del_tweet'){
			$('.del-icon').css('background-position','-31px 0');			
		}else{}
		$('.del-icon').css('text-decoration','none');
	}
	

}
//리플
function replyTweet(id){
	if($('#screen_name').text()==''){		
		openPopMessage('로그인 후 사용하세요.');
    }else{
    	$('#contents').val("@"+id+" ");
    	$('#contents').focus();
    }
	
}
//RT
function reTweet(div_id){
	if($('#screen_name').text()==''){		
		openPopMessage('로그인 후 사용하세요.');
    }else{
    	$('#contents').val("RT @"+$('#'+div_id+' .st_name').text()+": "+$('#'+div_id+' .tw_text').text().replace("#ebuzzkr",""));
    	$('#contents').focus();
    }
	
}

function ollehkt(){
	$('#timeline').html("");
	getApi("%23twit_perbiz");
} 

//알림레이어
function openPopMessage(){
	document.getElementById('status').style.display = "block";
}


function openPopMessage(msg){
	 var a = document.getElementById("popOKMessage");
	 if(a){		 
		 a.innerHTML = "<span style='margin-left:10px;'>"+msg+"</span>";
		 a.style.display = "block";
		 setTimeout("closePopMessage()",1500); 
	 }
	 

}

function closePopMessage(){
	 var a = document.getElementById("popOKMessage");
	 a.style.display = "none";
}


function eleShow(id){
	document.getElementById(id).style.display = "block";
}
function eleHide(id){
	document.getElementById(id).style.display = "none";
}

function tweetOver(id){
	var a = id.getElementsByTagName("p");
	for(i = 0;i < a.length;i++){
		if(a[i].className == "btn"){
			a[i].style.display = "block";
		}
	}
	id.style.backgroundColor = "#f7f7f7";
}
function tweetOut(id){
	var a = id.getElementsByTagName("p");
	for(i = 0;i < a.length;i++){
		if(a[i].className == "btn"){
			a[i].style.display = "none";
		}
	}
	id.style.backgroundColor = "";
}

function insertEventHashTag(str){
	document.twForm.contents.value += " " + str;
	updateCheck();
	document.twForm.contents.focus();	
}
var owner_screen_name = "";
var trans_country = "ko";

function topButton(){
	var a = document.getElementById("topButton");
	a.style.position = "fixed";
	//a.style.top = "500px";
	btn_pos = document.documentElement.clientHeight * 0.7;	//화면높이의 70%위치
	a.style.top = btn_pos+"px";
		if(document.documentElement.clientWidth > 763){
			a.style.left=((document.documentElement.clientWidth/2)-190)+"px";
		}
		else{
			a.style.left="192px";
		}
	
}

//글쓰기 check
var isLongAlarm = false;			//긴글 알림창용
function updateCheck(e){
	
	if($('#screen_name').text()==''){
		openPopMessage('로그인 후 사용하세요.');
		
	}else{
	
		textLength = 130 - document.getElementById("contents").value.length;
	
		if(document.getElementById("contents").value.length <= 130){
			
			if(textLength >= 20){
				document.getElementById("textcount").className = "a";
			}else if (textLength > 9 && textLength < 20){
				document.getElementById("textcount").className = "b";
			}else{
				document.getElementById("textcount").className = "c";	
			}	
			document.getElementById("textcount").innerHTML = textLength;			
			document.getElementById("btn_update_status").disabled = false; 	
			isLongAlarm = false;
			
			
		}else{
		
			openPopMessage('130자가 초과되었습니다.');
		
			document.twForm.isLongText.value="false";			
			document.getElementById("btn_update_status").disabled = true;
			document.getElementById("textcount").className = "c";
			document.getElementById("textcount").innerHTML = textLength;	   
		}
	}
}

//짦은url만들기
var short_url_id;
function shortUrlDisplay(id){
	if($('#screen_name').text()==''){
		openPopMessage('로그인 후 사용하세요.');
		
	}else{
		
		var stringVar = "";
	
		if(id == "message"){
			short_url_id = id;
			stringVar = document.getElementById('dmContents').value;		
			
		}else{
			if(id > 0){	//layer
				short_url_id = id;
				stringVar = document.getElementById("contentsLayer_"+id).value;
				
			}else{ //top form
				stringVar = document.getElementById('contents').value;		
			}		
		}
		
		if(stringVar.length == 0){
			openPopMessage('긴 URL이 포함된 글을 쓰신 후에 이 버튼을 누르세요.');
		}else{
		
			var str=''; 
			var regexp=/((http|ftp|https):\/\/[-\w\.]+(:\d+)?(\/([\w/_\-.]*(\?\S+)?)?)?)/g; 
			var l_urls='';
			
			str = stringVar.match(regexp);
		
			if(str != null){
				for(idx=0; idx< str.length; idx++){
					regexp2=/(http:\/\/j.mp\/[a-z_A-Z0-9]+)|(http:\/\/bit.ly\/[a-z_A-Z0-9]+)/g;
					match_short = str[idx].match(regexp2);				
					if(!match_short){
						//str[idx] 줄인다. return short_str;
						l_urls+=str[idx];
					}
					match_short = null;
				}			
				if(l_urls != ""){	
					
					if(id > 0){	//layer
						document.getElementById('textcountLayer_'+id).innerHTML = "<img src='http://tw.ebuzz.co.kr/images/loading.gif'>";					
					}else{ //top form
						document.getElementById('textcount').innerHTML = "<img src='http://tw.ebuzz.co.kr/images/loading.gif'>";					
					}				
					
					$.ajax({ url: "./shorturl.php?long_urls="+encodeURIComponent(l_urls), context: document, 
						success: function getShortUrl(res)
						{
							
							var retstr = res;	
							
							if(short_url_id == "message"){
								target_layer = 'dmContents';
							}else{
								if(short_url_id > 0){//layer		
									target_layer = 'contentsLayer_'+short_url_id;	
									
								}else{ //main
									target_layer = 'contents';
								}		
							}
							
							var url_arry, s_url, l_url, part;
							var err_cnt=0;
							url_arry = retstr.split('^_^');
							
							for(i=0;i<url_arry.length;i++){
								part = url_arry[i].split('|_|');
								
								if(part.length == 2){
									s_url = part[0];
									l_url = part[1];
									
								}
								
								//if(s_url.indexOf('http://j.mp') > -1 || s_url.indexOf('http://tln.kr') > -1 || s_url.indexOf('http://is.gd') > -1){
								if(s_url.indexOf('http://bit.ly') > -1){			
									stringVar = document.getElementById(target_layer).value;
									
									stringVar = stringVar.replace(l_url, s_url);
									document.getElementById(target_layer).value = stringVar+ " ";			
								}
								else if(s_url.length > 0){
									err_cnt++;
								}
							}
							
							if(short_url_id > 0){//layer		
								updateCheckLayer(short_url_id);	
								
							}else{ //main
								updateCheck();
							}	
							
							
							if(err_cnt>0){
								openPopMessage('잠시 후 다시 이용해주세요.'+err_cnt);
							}		
						}});
					
				}
			}
		}
	}
}
//twitpic upload
function imgUploadDisplay(id){
	if($('#screen_name').text()==''){
		openPopMessage('로그인 후 사용하세요.');
    }else{
    	//이미지등록 form 창열고 url form닫고
    	if(id > 0){
    		var img_display = document.getElementById('img_upload_id_'+id);		
    		//document.getElementById('short_url_id_'+id).style.display = "none";
    	}else{
    		var img_display = document.getElementById('img_upload_id');		
    		//document.getElementById('short_url_id').style.display = "none";
    	}	

    	if(img_display.style.display != "none"){
    		img_display.style.display = "none";
    	}else{
    		img_display.style.display = "";
    	}
    }	
}
function twit_update(){
	if(document.getElementById("contents").value.length==0){
		openPopMessage('트윗글을 써주세요.');		
	}else{	   	
    	   	
    	sendTweet(sendnum,$('#contents').val());
    	sendnum++;
	}
}
