var date = new Date();
var current_timestamp = Date.parse(date);

setInterval(function(){
	date = new Date();
	current_timestamp = Date.parse(date);
},5*1000);


// 1 dashboard summary
// 2 analytics
// 3 analytics sidebar ranking
// 4 trends japan
// 5 trends sidebar
// 6 trends regions
// 7 trends tokyo
// 8 dashboard affiliate
var num_of_twad_tabs = 10;

var twad_aws_s3_url = 'http://trends.twad.jp/';
var twad_trends_url = 'http://dashboard.twad.jp/trends/';
var twad_analytics_url = location.href;

var twad_page_title = '';

//コンファメーションダイアログ用空ファンクション
function confirmation_action () {}
//コンファメーション用のアクションタイプ変数を宣言
var confirmation_action_type = "";


//********* RECOGNIZE PAGE FROM URL **********
var twad_page_type = "";
//DASHBOARD
if (location.href == 'https://dashboard.twad.jp/' || location.href == 'https://dashboard.twad.jp/index.php') {
	twad_page_type = 'dashboard';
}
//ANALYTICS
if (location.href.search(/analytics/i) != -1) {
	twad_page_type = 'analytics';
}
//TRENDS
if (location.href.search(/jp\/trends./i) != -1 || location.href.search(/jp\/trends/i) != -1) {
	twad_page_type = 'trends';
}

//********** TAB TO RECORD in URL HASH for reference **********
var tabs_for_hash = new Array();
switch (twad_page_type) {
    case 'trends':
	tabs_for_hash = [3,4,6,7];
    break;
    case 'analytics':
	tabs_for_hash = [2,3];
    break;
    case 'dashboard':
	tabs_for_hash = [2,4,6,7];
    break;
}


//********* GET HASH ANCHOR AND TAB INFO IN URL **********
var hash_values = get_twad_hash_values();
var hashvalue = hash_values['hashvalue'];
if(!hashvalue) {hashvalue='';}
var hashtabs = hash_values['tabs'];
if(!hashtabs) {hashtabs='';}
//SYNC TREND TAB COOKIE for 4 and 7 FROM HASH VALUE
if(hashtabs['4']) {
	hashtabs['7'] = hashtabs['4'];
} else if(hashtabs['7']) {
	hashtabs['4'] = hashtabs['7'];
}

var tt_tm_timestamp = hash_values['tt_tm_t'];
if(!tt_tm_timestamp) {tt_tm_timestamp='';}

$(function() {
	//get pge title
	twad_page_title = $('title').html();

	//update donation amount
	$.getJSON(
	    "/js/donation_featured.php?callback=?",
	    {
		q: "#jquery"
	    },
	    function(data, status) {
		var donation_featured = data['donation_featured'];
		update_donation_featured(donation_featured);
	    }
	);
	//manage ROUND corners
	$('div.box1_header_inner').wrap('<div class="box1_header"></div>');
	$('div.box1_header_inner').corner("round top 8px").parent().css('padding', '4px 8px 4px 8px').corner("round top 14px");
	$('div.box1_contents_inner').wrap('<div class="box1_contents"></div>');
	$('div.box1_contents_inner').corner("round 8px").parent().css('padding', '0 8px 6px 8px').corner("round bottom 14px");
	$('div.box1_contents_continue_inner').wrap('<div class="box1_contents"></div>');
	$('div.box1_contents_continue_inner').corner("round 8px").parent().css({'padding':'0 8px 6px 8px','margin-bottom':'0'});
	$('div.box1_footer_inner').wrap('<div class="box1_footer"></div>');
	$('div.box1_footer_inner').corner("round bottom 8px").parent().css('padding', '0px 8px 8px 8px').corner("round bottom 14px");

	$('div.sidebar_header_inner').wrap('<div class="sidebar_header"></div>');
	$('div.sidebar_header_inner').corner("round top 4px").parent().css('padding', '2px 4px 2px 4px').corner("round top 7px");
	$('div.sidebar_contents_inner').wrap('<div class="sidebar_contents"></div>');
	$('div.sidebar_contents_inner').corner("round 4px").parent().css('padding', '0 4px 3px 4px').corner("round bottom 7px");

	$('div.form_header_inner').wrap('<div class="form_header"></div>');
	$('div.form_header_inner').corner("round top 4px").parent().css('padding', '2px 4px 2px 4px').corner("round top 7px");
	$('div.form_contents_inner').wrap('<div class="form_contents"></div>');
	$('div.form_contents_inner').corner("round 4px").parent().css('padding', '0 4px 3px 4px').corner("round bottom 7px");

	$('div.error_header_inner').wrap('<div class="error_header"></div>');
	$('div.error_header_inner').corner("round top 4px").parent().css('padding', '2px 4px 2px 4px').corner("round top 7px");
	$('div.error_contents_inner').wrap('<div class="error_contents"></div>');
	$('div.error_contents_inner').corner("round 4px").parent().css('padding', '0 4px 3px 4px').corner("round bottom 7px");

	//twad tab menu
	$('div[class^="twad_tab_box_"]').corner("round top 8px");

	//ボタンのアニメーション
	$('button.buttons').hover(
		function(){
			$(this).addClass("ui-state-hover");
		},
		function(){
			$(this).removeClass("ui-state-hover");
		}
	).mousedown(function(){
		$(this).addClass("ui-state-active");
	})
	.mouseup(function(){
			$(this).removeClass("ui-state-active");
	});

	//キャンペーン詳細テーブルの項目TDにDIV追加
	$('.campaign_detail_key').wrapInner('<div class="nowrap"></div>');

	//警告ダイアログ
	$("#alert_dialog").dialog({
		autoOpen: false,
		bgiframe: true,
		resizable: false,
		width:400,
		//height:200,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.1
		},
		buttons: {
			'OK': function() {
				$(this).dialog('close');
			}
		}
	});


	//確認ダイアログ
	$("#confirmation_dialog").dialog({
		autoOpen: false,
		bgiframe: true,
		resizable: false,
		width:400,
		//height:200,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.1
		},
		buttons: {
			'キャンセル': function() {
				$(this).dialog('close');
			},
			'OK': function() {
				confirmation_action();
				$(this).dialog('close');
			}
		}
	});

	//操作不能ダイアログ
	$("#modal_dialog").dialog({
		autoOpen: false,
		bgiframe: true,
		resizable: false,
		width:400,
		//height:200,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.1
		}
	});

	//タブの整形
	$('div[id^="tab_"]').css({"padding":"8px"});

	$('ul.jd_menu').jdMenu();

	//フォームの幅調整
	$('.form_table').css('width','100%');

	//*********** SET TREND TIME MACHINE ***********
	//SET form If trend time machine available
	if (twad_page_type == 'dashboard' || twad_page_type == 'trends') {
		//set time machine form to 1 hour ago.
		var timestamp = current_timestamp;
		timestamp = (Math.floor(timestamp/(3600 * 1000)) -1) * 3600 * 1000;
		//if cookie, overwrite it!!!!
		if($.cookie('twad_tt_tm')) {
			timestamp = $.cookie('twad_tt_tm');
		}
		//if time machine stamp in URL HASH overwrite it again!
		if(tt_tm_timestamp) {
			timestamp = tt_tm_timestamp;
		}
		date.setTime(timestamp);
		$.cookie('twad_tt_tm',timestamp,{ expires: 1, path: '/'});
		//set form
		set_tt_tm_form(date);

		//watch form change for timemachine
		//if timemachine date changed, load data and change # hash strings
		$('select[id^="tt_tm_select_"]').bind('change', function() {
			var selected_timestamp = get_tt_tm_form_date();
			if (selected_timestamp < 1303614000000) {
				selected_timestamp = 1303614000000;
				date.setTime(selected_timestamp);
				set_tt_tm_form(date);
			}
			if (selected_timestamp > current_timestamp - 3600*1000) {
				selected_timestamp = (Math.floor(current_timestamp / (3600*1000))-1)*3600*1000;
				date.setTime(selected_timestamp);
				set_tt_tm_form(date);
			}

			update_tt_tm_data();
			if(twad_page_type == 'trends') {
				location.hash = '!'+ hashvalue + get_twad_hash_anchor_string(tabs_for_hash);
			}
		});
		//if rewind clicked
		$('img[id^="tt_tm_play_"]').click(function() {
			var selected_timestamp = get_tt_tm_form_date();
			date.setTime(selected_timestamp);
			switch(this.id){
			    case 'tt_tm_play_rw1':
				selected_timestamp -= 900*1000;
				break;
			    case 'tt_tm_play_rw2':
				selected_timestamp -= 86400*1000;
				break;
			    case 'tt_tm_play_rw3':
				if(date.getMonth() == 0) {
					date.setMonth(11);
					date.setFullYear(date.getFullYear() - 1);
				} else {
					date.setMonth(date.getMonth() - 1);
				}
				selected_timestamp = Date.parse(date);
				break;
			    case 'tt_tm_play_ff1':
				selected_timestamp += 900*1000;
				break;
			    case 'tt_tm_play_ff2':
				selected_timestamp += 86400*1000;
				break;
			    case 'tt_tm_play_ff3':
				if(date.getMonth() == 11) {
					date.setMonth(0);
					date.setFullYear(date.getFullYear() + 1);
				} else {
					date.setMonth(date.getMonth() + 1);
				}
				selected_timestamp = Date.parse(date);
				break;
			    case 'tt_tm_play_ff4':
				selected_timestamp = Math.floor(current_timestamp/(3600*1000)-1)*3600*1000;
				break;
			}
			date.setTime(selected_timestamp);
			set_tt_tm_form(date);
			update_tt_tm_data();
			if(twad_page_type == 'trends') {
				location.hash = '!'+ hashvalue + get_twad_hash_anchor_string(tabs_for_hash);
			}
		});

	}


	//********** SET TWAD TABS **********
	for (i=0; i<= num_of_twad_tabs; i++) {
		show_twad_tab_content(false,i);
	}

	//show hash anchor when page loaded based on tab loops
	if(twad_page_type == 'analytics' || twad_page_type == 'trends') {
		location.hash = '!' + hashvalue + get_twad_hash_anchor_string(tabs_for_hash);
	}
});

//create anchor strings for unique content embedded URLs
function get_twad_hash_anchor_string (tab_ids) {
	//tabs create string for certain tabs
	var hash_anchor_string_final = '';
	hash_anchor_string_array = new Array();
	var hash_tabs_string = '';
	var hash_tabs_string_array = new Array();
	var hash_tt_tm_timestamp = 0;

	for (var i in tab_ids) {
	    if($.cookie('twad_tab_' + tab_ids[i] )) {
		//**********  TREND CONDITIONS **********
		//tab 4 and 7 are exclusive each other.
		//no 4 or 7 for timemachine
		if (($.cookie('twad_tab_6') == 'default' && tab_ids[i] == 7) ||
		($.cookie('twad_tab_6') == 'tokyo' && tab_ids[i] == 4) ||
		($.cookie('twad_tab_6') == 'timemachine' && (tab_ids[i] == 4 || tab_ids[i] == 7))) {
		//trying to keep URL shorter
		//**********  //TREND CONDITIONS **********
		} else {
			hash_tabs_string_array.push("'" + tab_ids[i] + "':'" +
			$.cookie('twad_tab_' + tab_ids[i] ) + "'");
		}
	    }
	}
	if(hash_tabs_string_array) {
		hash_tabs_string = hash_tabs_string_array.join(',');
	}

	if (hash_tabs_string) {
		//hash_tabs_string = "|twad_params|" + base64.encode("'tabs':{" + hash_tabs_string + '}',1);
		hash_tabs_string = "'tabs':{" + hash_tabs_string + '}';
		hash_anchor_string_array[0] = hash_tabs_string;
	}

	//********** TREND TIMEMACHINE CONDITIONS **********
	//add trend time machine only but not for analytics
	if($.cookie('twad_tt_tm') && $.cookie('twad_tab_6') == 'timemachine' && twad_page_type != 'analytics') {
		hash_tt_tm_timestamp = "'tt_tm_t':" + $.cookie('twad_tt_tm');
		hash_anchor_string_array[1] = hash_tt_tm_timestamp;
	}
	//********** //TREND TIMEMACHINE CONDITIONS **********
	hash_anchor_string_final = hash_anchor_string_array.join(',');


	hash_anchor_string_final = hash_anchor_string_final.replace(/{/g, "/");  //'
	hash_anchor_string_final = hash_anchor_string_final.replace(/}/g, "/");  //'
	hash_anchor_string_final = hash_anchor_string_final.replace(/'/g, "~");  //'
	hash_anchor_string_final = hash_anchor_string_final.replace(/:/g, "-");  //'
	hash_anchor_string_final = "/_twad_/" + hash_anchor_string_final;

	return hash_anchor_string_final;
	//return encodeURIComponent(hash_anchor_string_final);
}


//twad tab menu
//called when page loaded, and also tab clicked
function show_twad_tab_content(section,tab_id) {
	//be numeric!
	tab_id++;
	tab_id--;

	//********** COOKIE SETUP **********
	cookiename = 'twad_tab_' + tab_id;
	//make dashboard tab exp shoreter for notifications: 3 hours
	if (tab_id == 1) {
		exp=new Date();
		exp.setTime(exp.getTime()+1000*60*5);
		var twad_tab_cookie_exp = exp.toGMTString();
	//usually 90 days
	} else {
		var twad_tab_cookie_exp = 90;
	}
	//========================================
	//IF CLICKED
	//========================================
	//set cookie only when tab clicked
	if (section && tab_id) {
		$.cookie(cookiename, section, { expires: twad_tab_cookie_exp, path: '/'});
		//sync tab 4 and 7 for trends

		if(tab_id == 4 || tab_id == 7) {
			$.cookie('twad_tab_4', section, { expires: twad_tab_cookie_exp, path: '/'});
			$.cookie('twad_tab_7', section, { expires: twad_tab_cookie_exp, path: '/'});
		}
	}

	//change hash anchor when tab clicked.
	if(section && twad_page_type != "dashboard") {
		location.hash = '!' + get_twad_hash_anchor_string(tabs_for_hash);
	}
	//********** TREND CONDITIONS **********
	//SYNC CLICKED CONTENTS
	if ((tab_id == 4 || tab_id == 7) && section) {
		load_twad_trends_content(section,4);
		load_twad_trends_content(section,7);
		if (tab_id == 4) {
			show_twad_tab_section(section,7);
		}
		if (tab_id == 7) {
			show_twad_tab_section(section,4);
		}
	}

	//========================================
	//IF NOT CLICKED = PAGE LOADED
	//========================================
	//in case no section, which is paged loaded, which is not clicked on tab
	if (!section) {
		//********** get tab ids from hash anchor **********
		//OVERWRITE sections if tabs defined in hash anchor
		if(hashtabs[tab_id]) {
			section = hashtabs[tab_id];
			$.cookie(cookiename, section, { expires: twad_tab_cookie_exp, path: '/' });
		}

		//********** get section from COOKIE **********
		//no section = default
		if ($.cookie(cookiename)) {
			section = $.cookie(cookiename);
		//if no cookie, no click, and no hash specified
		} else {
			section = 'default';
			$.cookie(cookiename, section, { expires: twad_tab_cookie_exp, path: '/' });
		}

	}

	//at this moment, section is not empty all the time.

	//********** ANALYTICS CONDITIONS **********
	//switch page title for analytics
	if (tab_id == 2 && twad_page_type=='analytics') {

	    switch(section) {
		case "default":
			document.title = twad_page_title + ' - アカウントグレードと信頼性';
		break;
		case "influence":
			document.title = twad_page_title + ' - 影響力（Kloutスコアなど）';
		break;
		case "followers":
			document.title = twad_page_title + ' - フォロワー統計・品質、リーチ数など';
		break;
		case "tweets":
			document.title = twad_page_title + ' - つぶやきやアプリ、ハッシュタグなど';
		break;
		case "tweet_contents":
			document.title = twad_page_title + ' - つぶやきのキーワードや時間帯の傾向など';
		break;
		case "retweets":
			document.title = twad_page_title + ' - 受けた@返信やRTのアプリ、ハッシュタグなど';
		break;
		case "retweet_contents":
			document.title = twad_page_title + ' - 受けた@返信やRTのキーワード、時間帯の傾向など';
		break;
	    }
	}
	//********** TREND CONDITIONS **********
	//switch page title for trends
	if (tab_id == 6) {
		if (section == 'default') {
			//load japan trends
			update_twad_trends_content('twitter_trends_latest_japan');
			if(twad_page_type=='trends'){
				twad_page_title = 'ソエンドトレンド - 日本のtwitterトレンドランキング';
				document.title = twad_page_title;
			}
		}
		if (section == 'tokyo') {
			//load tokyo trends
			update_twad_trends_content('twitter_trends_latest_tokyo');
			if(twad_page_type=='trends'){
				twad_page_title = 'ソエンドトレンド - 東京のtwitterトレンドランキング';
				document.title = twad_page_title;
			}
		}

		if (section == 'timemachine' && (twad_page_type == 'dashboard' || twad_page_type == 'trends')) {
			//update time machine content for launch
			update_tt_tm_data();
		}

	}
	//load appropriate ajax contents for 4 and 7 synced
	if (tab_id == 4 || tab_id == 7) {
		load_twad_trends_content($.cookie('twad_tab_'+tab_id),tab_id);
	}

	show_twad_tab_section(section,tab_id);

}

//decode values from hash in URL!!
function get_twad_hash_values () {
	var hashstring = location.hash.replace("#","");
	hashstring = decodeURIComponent(hashstring);

	//for past compatibility ver 1.0
	if(hashstring.search(/\|twad_tabs\|/i) != -1) {
		hashstring = hashstring.substr(0,hashstring.search(/\|twad_tabs\|/i));
	}
	var hash_tabs_string = '';
	var hash_for_tab = hashstring.search(/\|twad_params\|/i);
	//ver 1.1
	if (hash_for_tab != -1) {
		hash_tabs_string = hashstring.substr(hash_for_tab);
		hash_tabs_string = decodeURI(hash_tabs_string);
		hash_tabs_string = hash_tabs_string.replace('|twad_params|','');

		hash_tabs_string = hash_tabs_string.replace(/\//g, ",");
		/*//'<-ignore this*/
		hash_tabs_string = hash_tabs_string.replace(/\|/g, "'");
		/*//'<-ignore this*/
		hash_tabs_string = hash_tabs_string.replace(/\~/g, "{");
		/*//'<-ignore this*/
		hash_tabs_string = hash_tabs_string.replace(/\;/g, "}");
		/*//'<-ignore this*/
	}
	if(!hash_tabs_string) {
		var hash_for_tab = hashstring.search(/\/_twad_\//i);
	}
	//ver 2
	if (hash_for_tab != -1 && !hash_tabs_string) {
		hash_tabs_string = hashstring.substr(hash_for_tab);
		hash_tabs_string = decodeURI(hash_tabs_string);
		hash_tabs_string = hash_tabs_string.replace('/_twad_/','');

		hash_tabs_string = hash_tabs_string.replace(/-/g, ":");
		/*//'<-ignore this*/
		hash_tabs_string = hash_tabs_string.replace(/~/g, "'");
		/*//'<-ignore this*/

		var i = 0;
		while(hash_tabs_string.search('/') != -1) {
			if (i%2 == 0) {
				hash_tabs_string = hash_tabs_string.replace('/','{');
			} else {
				hash_tabs_string = hash_tabs_string.replace('/','}');
			}
			i++;
		}
	}

	if (hash_tabs_string) {
		//hash_tabs_string = base64.decode(hash_tabs_string,1);
		hash_tabs_string = hash_tabs_string + "})";
		hash_tabs_string = "({" + hash_tabs_string;
		try {
			var hash_tabs_value = eval(hash_tabs_string);
		} catch(e) {
			var hash_tabs_value = new Array();
		}
		hashstring = hashstring.substr(0,hash_for_tab);
	}

	if(hashstring.search('!/') == 0) {
		hashstring = hashstring.substr(2);
	} else if(hashstring.search('!') == 0) {
		hashstring = hashstring.substr(1);
	}


	if (hash_tabs_value) {
		var hash_tabs_results = hash_tabs_value['tabs'];
		var hash_tm_tt_results = hash_tabs_value['tt_tm_t'];
	} else {
		var hash_tabs_results = '';
		var hash_tm_tt_results = '';
	}
	var values = {"hashvalue":hashstring,"tabs":hash_tabs_results,"tt_tm_t":hash_tm_tt_results};
	return values;
}


//queue content update for Ajax
function queue_twad_trends_content(trend_contents,blind) {
	$('.tt_update_buttons').attr('disabled','disabled');
    var exists = $('trend_contents').html();
    if (!exists || blind) {
	var isMSIE = /*@cc_on!@*/false;

	if(!isMSIE && blind) {
		$('#'+trend_contents).prepend('<div class="tt_now_loading">最新のデータを取得しています。。。</div>');
	}
	var randnum = Math.floor( Math.random() * 100000);
	$.getJSON('/trends_get_data.php', {'id': trend_contents,'rand':randnum}, function(data){
		$('#' + data.id).html(data.data);
		$('.tt_update_buttons').attr('disabled','');

	});
    }
}


function update_twad_trends_content(trend_contents,blind) {
	if (trend_contents instanceof Array) {
		var trend_contents_array = trend_contents;
	} else {
		trend_contents_array = new Array();
		trend_contents_array[0] = trend_contents;
	}

	for (var i in trend_contents_array) {
			queue_twad_trends_content(trend_contents_array[i],blind);
	}
}

//define which div should be updated for each tab-section combination!
function load_twad_trends_content(section, tab_id) {
    switch(tab_id) {
	case 4:
	    switch(section) {
		case 'default':
			var trend_contents = ['twitter_trends_24hours_japan_01_25','twitter_trends_24hours_japan_26_50'];
		break;
		case 'yesterday':
			var trend_contents = ['twitter_trends_yesterday_japan_01_25','twitter_trends_yesterday_japan_26_50'];
		break;
		case 'weekly':
			var trend_contents = ['twitter_trends_weekly_japan_01_25','twitter_trends_weekly_japan_26_50'];
		break;
		case 'hashtags':
			var trend_contents = ['twitter_trends_24hours_hashtags_japan','twitter_trends_yesterday_hashtags_japan','twitter_trends_weekly_hashtags_japan'];
		break;

	    }
	break;
	case 7:
	    switch(section) {
		case 'default':
			var trend_contents = ['twitter_trends_24hours_tokyo_01_25','twitter_trends_24hours_tokyo_26_50'];
		break;
		case 'yesterday':
			var trend_contents = ['twitter_trends_yesterday_tokyo_01_25','twitter_trends_yesterday_tokyo_26_50'];
		break;
		case 'weekly':
			var trend_contents = ['twitter_trends_weekly_tokyo_01_25','twitter_trends_weekly_tokyo_26_50'];
		break;
		case 'hashtags':
			var trend_contents = ['twitter_trends_24hours_hashtags_tokyo','twitter_trends_yesterday_hashtags_tokyo','twitter_trends_weekly_hashtags_tokyo'];
		break;

	    }
	break;
    }
	update_twad_trends_content(trend_contents);
}


//GET time stamp from form selects of trend timemachine
function get_tt_tm_form_date() {
		var selected_time = $('#tt_tm_select_year').val() + '/' + formatNum(2,$('#tt_tm_select_month').val()) + '/' + formatNum(2,$('#tt_tm_select_date').val()) + ' ' + formatNum(2,$('#tt_tm_select_hour').val()) + ':' + formatNum(2,$('#tt_tm_select_min').val()) + ':00';

		var selected_timestamp = Date.parse(selected_time);
		return selected_timestamp;
}

//update timemachine contents using AJAX from cache files for trend timemachine
function update_tt_tm_data() {
		var selected_timestamp = get_tt_tm_form_date();
		tt_tm_date_for_tweet = $('#tt_tm_select_year').val() + '年' + formatNum(2,$('#tt_tm_select_month').val()) + '月' + formatNum(2,$('#tt_tm_select_date').val()) + '日' + formatNum(2,$('#tt_tm_select_hour').val()) + ':' + formatNum(2,$('#tt_tm_select_min').val());
		if(twad_page_type=='trends'){
			twad_page_title = tt_tm_date_for_tweet + 'のtwitterトレンドトピックとランキング by ソエンドトレンド･タイムマシン';
			document.title = twad_page_title;
		}

		$.cookie('twad_tt_tm', selected_timestamp, { expires: 1, path: '/'});
		var tt_tm_file_prefix = twad_aws_s3_url + 'tt_ranks_cache/' + $('#tt_tm_select_woeid').val() + '_daily_' + $('#tt_tm_select_type').val() + '_' + (selected_timestamp/1000);

		var url = tt_tm_file_prefix + '_01_25' + '.txt?callback=process_tt_cache';

		//current
		$.jsonp({
			type: "GET",
			dataType: "jsonp",
			callback: 'process_tt_cache',
			url: twad_aws_s3_url + 'tt_ranks_cache/' +
			  $('#tt_tm_select_woeid').val() + '_current_trends_' + (selected_timestamp/1000) +
			  '.txt?callback=process_tt_cache',
			success: function(data) {
				$('#'+data.name).html(data.data);
			},
			error: function() {
			    $('#tt_tm_current').html('<div style="font-size:11px;">データが存在しません。</div>');
			}
		});
		//past 24 hours
		$.jsonp({
			type: "GET",
			dataType: "jsonp",
			callback: 'process_tt_cache',
			url: url,
			success: function(data) {
				$('#'+data.name).html(data.data);
			},
			error: function() {
			    $('#tt_tm_daily_01_25').html('<div style="font-size:11px;">データが存在しません。</div>');
			}
		});
		url = tt_tm_file_prefix + '_26_50' + '.txt?callback=process_tt_cache';
		$.jsonp({
			type: "GET",
			dataType: "jsonp",
			callback: 'process_tt_cache',
			url: url,
			success: function(data) {
				$('#'+data.name).html(data.data);
			},
			error: function() {
			    $('#tt_tm_daily_26_50').html('<div style="font-size:11px;">データが存在しません。</div>');
			}
		});

}


//set and limit form selection of trend timemachine
function set_tt_tm_form(date) {
	var temp_timestamp = Date.parse(date);
	if (temp_timestamp < 1303614000000) {
		temp_timestamp = 1303614000000;
		date.setTime(temp_timestamp);
	}
	var max_timestamp = Math.floor((current_timestamp - 3600*1000)/(3600*1000)) * 3600 * 1000;
	if (temp_timestamp > max_timestamp) {
		temp_timestamp = max_timestamp;
		date.setTime(temp_timestamp);
	}
	jQuery('#tt_tm_select_year').val(date.getFullYear());
	jQuery('#tt_tm_select_month').val(date.getMonth()+1);
	jQuery('#tt_tm_select_date').val(date.getDate());
	jQuery('#tt_tm_select_hour').val(date.getHours());
	jQuery('#tt_tm_select_min').val(date.getMinutes());
}

//GET switch tab contents
function show_twad_tab_section(section,tab_id) {
	if (tab_id) {
		tab_id += '_';
	} else {
		tab_id = '';
	}
	$('div[id^="twad_tab_content_' + tab_id + '"]').hide();
	$('#twad_tab_content_' + tab_id + section).show();
	$('div[id^="twad_tab_menu_' + tab_id + '"]').removeClass('twad_tab_box_active');
	$('div[id^="twad_tab_menu_' + tab_id + '"]').addClass('twad_tab_box_inactive');
	$('#twad_tab_menu_' + tab_id + section).addClass('twad_tab_box_active');
	//return false;
}


//OPEN TWITTER TWEET WINDOW
function open_tweet_window(message,twad_trends_url_final) {
		message = encodeURIComponent(message);
		url = 'http://twitter.com/share?text=';
		related = encodeURIComponent('soendoen:ソーシャル・エンドースメント･サービス(旧つあど)');
		window.open(url+message+'&lang=ja&via=soendoen&related=' + related + '&url='+twad_trends_url_final ,'tweetbox','width=560, height=300');
}



  function GetFileName(file_url){
    file_url = file_url.substring(file_url.lastIndexOf("/")+1,file_url.length)
    //file_url = file_url.substring(0,file_url.indexOf("."));
    return file_url;
  }


function myFormatNumber(x) { // 引数の例としては 95839285734.3245
    var s = "" + x; // 確実に文字列型に変換する。例では "95839285734.3245"
    var p = s.indexOf("."); // 小数点の位置を0オリジンで求める。例では 11
    if (p < 0) { // 小数点が見つからなかった時
        p = s.length; // 仮想的な小数点の位置とする
    }
    var r = s.substring(p, s.length); // 小数点の桁と小数点より右側の文字列。例では ".3245"
    for (var i = 0; i < p; i++) { // (10 ^ i) の位について
        var c = s.substring(p - 1 - i, p - 1 - i + 1); // (10 ^ i) の位のひとつの桁の数字。例では "4", "3", "7", "5", "8", "2", "9", "3", "8", "5", "9" の順になる。
        if (c < "0" || c > "9") { // 数字以外のもの(符合など)が見つかった
            r = s.substring(0, p - i) + r; // 残りを全部付加する
            break;
        }
        if (i > 0 && i % 3 == 0) { // 3 桁ごと、ただし初回は除く
            r = "," + r; // カンマを付加する
        }
        r = c + r; // 数字を一桁追加する。
    }
    return r; // 例では "95,839,285,734.3245"
}

//桁数そろえ
function formatNum(keta, num) {
  var src = new String(num);
  var cnt = keta - src.length;
  if (cnt <= 0) return src;
  while (cnt-- > 0) src = "0" + src; return src;
}

function ajax_session_expired(encoded_url) {
	document.location.href="./logout.php?error_code=login-session_expired&last_position=" + encoded_url;
}

function reload_all_grids () {
	jQuery('[id^="grid_"]').trigger("reloadGrid");
}

function update_donation_featured(donation_featured) {
	$(".donation_featured").text(myFormatNumber(donation_featured));
}



