//メインJS
////////////////////////ここから下は変更しないでね。//////////////////////////////
//jQuery.require(["charCount.js","setting.js","styleswitch.js"]);

var int_num;
var int_tweet_num;
var chkLogon;
var loggedin;
var int_btn_num;
var int_alert_num;
var count = 138 - (hashtag.length + presetURL.length);
var LS = false;
var last_id = null;
var arrTL=new Array();

//onload関数
//defWindowOnload = window.onload;
window.onload = function(){
    //defWindowOnload();
	$("#scr").html('');
	firstWindowSettings();
	getHashTag(hashtag);
	chkLogonStatus(1);
}

//ログイン時にTwitterからのコールバックを受ける
function callbackLogin(){
	//Intervalクリア
	clearInterval(int_num);
	clearInterval(chkLogon);
	clearInterval(int_tweet_num);
	
	chkLogonStatus(1);
}

//div id:scrに必要なdiv要素を追加
function firstWindowSettings(){
	$('<div>',{id:'topArea'}).appendTo('#scr:first');
		$('<div>',{id:'logoArea'}).appendTo('#topArea:first');
			$("#logoArea").html('<img src="'+imgUrl+'twitter.png">');
		$('<div>',{id:'logoutArea'}).appendTo('#topArea:first');
	$('<div>',{id:'contentArea'}).appendTo('#scr:first');
		$('<form>',{id:'form'}).appendTo('#contentArea:first');
	$('<div>',{id:'alert'}).appendTo('#scr:first');
	$('<div>',{id:'twitter'}).appendTo('#scr:first');
	$('<div>',{id:'corp'}).appendTo('#scr:first');
	$('#corp').append('Produced by <a href="#" rel="styles1" class="styleswitch" onclick="showForm();">KiBAN</a> <a href="#" rel="styles2" class="styleswitch" onclick="hideForm();">iNTERNATiONAL</a> SBTweet!');
}

//ログインフォーム(警告文)
function loginForm(art){
	$("#btn_logout").remove();
	$("#form").remove();
	$( '<form>' , {id:'form',submit:function(){window.open(apiUrl+'?method=execLogin','loginWindow','width=800,height=500,menubar=no,toolbar=no,scrollbars=yes'); return false;}}).prependTo('#contentArea:first');
		$( '<div>' , {id:'msg'}).appendTo('#form:first');
			$("#msg").text('Twitterにログインしてください。');
			$( '<input>', { type: 'submit', value: 'Login',id: 'loginButton'} ).appendTo('#form:first');
		$( '<div>' , {id:'art'}).appendTo('#form:first');
		
	if(art){
		$("#msg").append('<font color="red">'+art+'</font>');
	}
}

//ログイン成功後
function loginSuccess(){
	$("#btn_logout").remove();
	$('#logoutArea').append('<input type="button" value="Logout" id="btn_logout" onClick="execLogout(); return false;">');
	$("#form").remove();
	$( '<form>' , {id:'form'}).prependTo('#contentArea:first');
	if(tweetMode=="private"){
		$( '<div>' , {id:'msgPrivate'}).appendTo('#form:first');
			$("#msgPrivate").text('プライベートモードで動作中です。');
	}
		$( '<div>' , {id:'formArea' , style:'font-weight:bold'}).appendTo('#form:first');
			$( '<textarea>', {id: 'tweetContent'} ).appendTo('#formArea:first');
			$('#formArea').append('<input type="button" value="Tweet!" id="btn_tweet" onClick="tweet(); return false;">');
	$("#tweetContent").charCount({allowed: count,warning: 20});
}

//ログイン状態を確認(1:初回ログイン時 その他：特になし)
function chkLogonStatus(mode){
	$.ajax({
		url:apiUrl,
		type:'GET',
		async:true,
		cache: false,
		dataType:'json',
		data:{method:"getLogonStatus"},
		success:function(data){
			if(data.logonStatus == 'true'){
				LS = true;
				if(mode==1){//初回ログイン用
					LS = true;
					loggedin = true;
					arrTL=new Array();
					last_id = null;
					$("#twitter").html('');
					loginSuccess();
					getHashTag(hashtag);
				}
			}else{
				LS = false;
				if(mode=="1"){//初回ログイン用
					loginForm('');
				}else{		//タイムアウト用
					loginForm('<br>タイムアウトしました。再度ログインしてください。');
				}
			}
		}
	});
}

//ログアウト処理
function execLogout(){
	$.ajax({url:apiUrl,
		data:{method:"execLogout"},
		success : function (){
			//Intervalクリア
			clearInterval(int_num);
			clearInterval(chkLogon);
			clearInterval(int_tweet_num);
			
			//グローバル変数初期化
			int_num=0;
			int_tweet_num=0;
			chkLogon=0;
			int_btn_num=0;
			int_alert_num=0;
			count = 138 - (hashtag.length + presetURL.length);
			loggedin = false;
			LS = false;
			last_id = null;
			arrTL=new Array();
			
			//画面初期化
			$("#scr").html('');
			firstWindowSettings();
			getHashTag(hashtag);
			chkLogonStatus(1);
			
			/*
			chkLogonStatus(1);
			$("#scr").html('');
			firstWindowSettings();
			getHashTag(hashtag);
			*/
		}
	});
}

//timer設定、APIへのタイムライン参照
function getHashTag(hashtag){
	$.ajax({
			url:searchURL,
			type:　'GET',
			async:　true,
			cache: false,
			dataType:　'json',
			data:　{action:"get",q:hashtag,rpp:rpp},
			success:　function(data){
			if (!data.results) return;
			if (data.results.length <= 0) return;
			for(i in data.results){
				var item = data.results[i];
				var value="";
				arrTL.unshift(item);
				if (last_id == null || item.id > last_id ){
					var content = makeHashLink(makeUserLink(repUrl(item.text)));
					value += "<div id=\"img\"><img src=\"" + item.profile_image_url + "\" height=\"48\" width=\"48\"></div>";
					value += "<div id=\"content\"><strong><a href=\"http://twitter.com/" + item.from_user + "/\" target=\"_blank\">" + item.from_user + "</a></strong>&nbsp;" + content + "&nbsp;<br><br></div>";
					value += "<div id=\"func\">" + formatDate(item.created_at);
					if (LS){
						value +=  "&nbsp;<a href=\"javascript:void(0)\" onclick=\"rt('" + item.id + "')\">RT</a>&nbsp;<a href=\"javascript:void(0)\" onclick=\"reply('" + item.from_user + "')\">返信</a>";
					}
					value += "</div>";
					value += "<div style=\"clear: both;\"></div>";
					
					$("#twitter").append("<div class=\"tweetsList\" id=\"tweets" + item.id + "\"></div>");
					$("#tweets" + item.id).hide();
					$("#tweets" + item.id).html(value);
					$("#tweets" + item.id).show('fast');
					value_ear = value;
				}
			}
			last_id = arrTL[arrTL.length-1].id
			int_tweet_num = setInterval("makeTL(arrTL)",tweet_timer);
			int_num = setInterval("getHashTagCon(hashtag)",timer);
			if(loggedin){
				chkLogon = setInterval("chkLogonStatus(0)",chklogin_timer);
			}
		}
	});
}
//分解
function getHashTagCon(hashtag){
	clearInterval(int_num);
	$.ajax({
			url:　searchURL,
			type:　'GET',
			async:　true,
			cache: false,
			dataType:　'json',
			data:　{action:"get",q:hashtag,rpp:rpp},
			success:　function(data)
			{
				var arrTemp=new Array();
				var tc = 0;
				for(i in data.results){
					var item = data.results[i];
					if (item.id > last_id){
							arrTemp.unshift(item);
					}
					tc=arrTemp.length;
				}
				arrTL=arrTL.concat(arrTemp);
				arrTL.splice(0,tc);
			}
	});
	int_num = setInterval("getHashTagCon(hashtag)",timer);
}

//タイムライン作成
function makeTL(data){
	var valueTmp="";
	for(i in data){
		var item = data[i];
		var value="";
		
		if (last_id == null || item.id > last_id ){
			var content = makeHashLink(makeUserLink(repUrl(item.text)));
			value += "<div id=\"img\"><img src=\"" + item.profile_image_url + "\" height=\"48\" width=\"48\"></div>";
			value += "<div id=\"content\"><strong><a href=\"http://twitter.com/" + item.from_user + "/\" target=\"_blank\">" + item.from_user + "</a></strong>&nbsp;" + content + "&nbsp;<br><br></div>";
			value += "<div id=\"func\">" + formatDate(item.created_at);
			if (LS){
				value +=  "&nbsp;<a href=\"javascript:void(0)\" onclick=\"rt('" + item.id + "')\">RT</a>&nbsp;<a href=\"javascript:void(0)\" onclick=\"reply('" + item.from_user + "')\">返信</a>";
			}
			value += "</div>";
			value += "<div style=\"clear: both;\"></div>";
			if(valueTmp != value){
				$("#twitter").prepend("<div class=\"tweetsList\" id=\"tweets" + item.id + "\"></div>");
				$("#tweets" + item.id).hide();
				$("#tweets" + item.id).append(value);
				$("#tweets" + item.id).show('fast');
				valueTmp = value;
			}
		}
	}
	last_id = arrTL[arrTL.length-1].id
	$('.tweetsList').each(function(i){
		if(i>rpp){
			$(this).remove();
		}
	});
}

//つぶやき
function tweet(){
	var tweet = $("#tweetContent").get()[0].value;
	$('#btn_tweet').hide();
	int_btn_num = setInterval("showBTN()",5000);
	chkLogonStatus(0);//ログインしているかどうか確認 2010/8/17　追記
	if (tweet == ''){
		return;
	}
	
	if (hashtag!=''){
		tweet += ' ' + hashtag;
	}
	if (presetURL!=''){
		tweet += ' ' + presetURL;
	}
	
	$.ajax({url:apiUrl,
		data:{method:"tweet",tweet:tweet,tweetMode:tweetMode},
		success : function(XMLHttpRequest, textStatus, errorThrown)
		{
			$("#tweetContent").attr("value","");
			$("#countText").html(count);
			$("#countText").removeClass('warning');
			$("#countText").removeClass('exceeded');
            chkLogonStatus();
		},
		error : function(XMLHttpRequest, textStatus, errorThrown)
		{
			alert(textStatus);
		}
		});
	return false;
}

function showForm(){
	$('#form').show();
}

function hideForm(){
	$('#form').hide();
}

function showBTN(){
	$('#btn_tweet').show(1500);
	clearInterval(int_btn_num);
}

function hideAlert(){
	$('#alert').hide(1500);
	clearInterval(int_alert_num);
}

function reply(username){
	$('#tweetContent').val("@" + username + ' ');
	$('#tweetContent').focus();
}

function rt(id){
	var text = ($('#tweets'+id + ' > #content').text()).replace(' ' + hashtag + ' ' + presetURL, "");
	$('#tweetContent').val("RT @" + text);
	$('#tweetContent').focus();
}

function repUrl(str){
	var options = "_blank";
	return str.replace(/[A-Za-z]+?:\/\/[A-Za-z0-9_-]+\.[A-Za-z0-9:%&\?\/.=~_-]+/g, function(m){
	return [
		  '<a href="'
		, m
		, options ? '" target="' + options + '">' : ''
		, m
		, '</a>'
	].join('');
	});
}


function makeUserLink(str){
	return str.replace(/@(\w+)/g, function(user){
		return [
			  '<a href="'
			, 'http://twitter.com/'
			, user
			, '" target="_blank">'
			, user
			, '</a>'
		].join('');
	});
}

function makeHashLink(str){
	return str.replace(/#(\w+)/g, function(m, hashtag){
		return [
			  '#<a href="'
			, 'http://search.twitter.com/search?q='
			, encodeURIComponent(m)
			, '" target="_blank">'
			, hashtag
			, '</a>'
		].join('');
	});
}

function formatDate(date){
	var d = new Date(date);
	var h = d.getHours()
	var m = d.getMinutes()
	var dd = d.getSeconds();
	var y = d.getYear();
	var mon = d.getMonth() + 1;
	var day = d.getDate();
	var ret;

	if(h < 10){h = '0' + h;}
	if(m < 10){m = '0' + m;}
	if(dd < 10){dd = '0' + dd;}
	if(y < 2000) {y = y + 1900}
	if(mon < 10){mon = '0' + mon;}
	if(day < 10){day = '0' + day;}

	ret = y + '/' + mon + '/' + day + ' ' + h + ':' + m + ':' + dd;

	return ret
}

