/*****jsonp api search*****/
var searchCond = {}; // 検索条件
var VIEW_COUNT;
var fli_height = '260px';
var yt_height = '300px';
var str = navigator.userAgent;
if(str.match(/(Mobile).*(Safari)/)){
	VIEW_COUNT = 3;  // 画面に表示する件数
	$('.ytbody').css('height','auto')
	$('.ytbody').css('height','auto')
	fli_height = '100px';
	yt_height = '320px';
}
else{
	VIEW_COUNT = 9;  // 画面に表示する件数
}
$(function(){
	if($('#touroku_btn').length){
		$('#touroku_btn')
			.mouseover(
				function(){
					$(this).attr("src","./sozai/touroku_hover.gif");
				}
			)
			.mouseout(
				function(){
					$(this).attr("src","./sozai/touroku.gif");
				}
			);
	}
	if($('#ui-tab').length){
		$('#ui-tab').css('display','block');
		$('#ui-tab > ul').tabs();
	}
	if($('.changeback').length){
		// BackgroundChange
		$('.changeback')
			.mouseover(
				function(){
					$(this).css('background',"#ffffff url('http://sendai-web-link.com/sozai/back_ble2.png') no-repeat top right");
				}
			)
			.mouseout(
				function(){
					$(this).css('background','transparent');
				}
			);
	}
	if($('.menu_category li').length){
		// BackgroundChange
		$('.menu_category li').
			mouseover(
				function(){
					$(this).css('backgroundColor',"#f4f9ff");
				}
			)
			.mouseout(
				function(){
					$(this).css('backgroundColor','#f9fcff');
				}
			);
	}
	/*****jsonp api search*****/
	if($('#youtubelist').length | $('#flickrlist').length){
		// --- イベントハンドラ ---

		// flickr検索
		$("#FLsearch").submit(
			function(){
				searchNew({"orderby":"date-taken-desc","site":"flickr","keyword":$("#FLkeyword").val()});
				return false;
			}
		);
		// youtube検索
		$("#YTsearch").submit(
			function(){
				searchNew({"orderby":"published","site":"youtube","keyword":$("#YTkeyword").val()});
				return false;
			}
		);
		// 並び替え
		$("#FLsort > a").click(
			function(){
				Pagejump({"site":"flickr","orderby": this.id, "page":1});
			}
		);
		$("#YTsort > a").click(
			function(){
				Pagejump({"site":"youtube","orderby": this.id, "page":1});
			}
		);
		// flickr前へ
		$("#FLback").click(
			function(){
				if (searchCond.page <= 1) return;
				Pagejump({"site":"flickr","page": searchCond.page-1});
			}
		);
		// youtube前へ
		$("#YTback").click(
			function(){
				if (searchCond.page <= 1) return;
				Pagejump({"site":"youtube","page": searchCond.page-1});
			}
		);
		// flickr次へ
		$("#FLnext").click(
			function(){
				if (searchCond.page*VIEW_COUNT+1 > searchCond.total){
					return;
				}
				Pagejump({"site":"flickr","page": searchCond.page+1});
			}
		);
		// youtube次へ
		$("#YTnext").click(
			function(){
				if (searchCond.page*VIEW_COUNT+1 > searchCond.total) return;
				Pagejump({"site":"youtube","page": searchCond.page+1});
			}
		);
		if($('#flickrlist').length){
			// --- 初期処理 ---
			searchNew({"orderby":"date-taken-desc","site":"flickr","keyword":"仙台"});
		}
		if($('#youtubelist').length){
			// --- 初期処理 ---
			searchNew({"orderby":"published","site":"youtube","keyword":"仙台"});
		}
	}
});
/*****api search function*****/
// --- 新規検索 ---
function searchNew(cond){
	search(
		{
		"keyword":cond.keyword,
		"page": 1,
		"orderby":cond.orderby,
		"site": cond.site
		}
	);
}
// --- ページ推移 ---
function Pagejump(cond){
	search(
		$.extend(
			{},
			searchCond,
			cond
		)
	);
}
// --- 検索 ---
function search(cond){
	// 検索条件の検査
	if (cond == null) return;
	if (cond.keyword == null || cond.keyword.length == 0) {
		alert("検索キーワードを入力してください。");
		return;
	}

	// 検索取得開始インデックス
	var index = (cond.page-1)*VIEW_COUNT+1;

	// 検索条件の保存
	$.extend(searchCond, cond);


	//flickrここから
	if(cond.site == 'flickr'){
		// サムネイル表示を初期化
		$("#flickrlist").html('<div class="loading"><img src="./sozai/loading.gif"></div>');

		// ajax通信定義
		$.ajax(
			{
				dataType: "jsonp",
				jsonp:'jsoncallback',//flickr指定必須
				data:{//test -> http://www.flickr.com/services/rest/?api_key=7da337676a2e9728a3993c03b893d861&sort=data_taken_desc&text=sendai&format=json&method=flickr.photos.search&page=1&per_page=9

					"api_key":'7da337676a2e9728a3993c03b893d861',
					"text": cond.keyword,
					"sort": cond.orderby,
					"page": index,
					"per_page": VIEW_COUNT,
					"format":"json",
					"method":'flickr.photos.search',
					"extras":'date_taken'
				},
				cache: true,
				url: "http://www.flickr.com/services/rest/",
				success: function (data) {
					//通信が成功した場合の処理 (JSONPのコールバック関数)

					// サムネイル表示をクリア
					$("#flickrlist").empty();
					// 検索結果件数を取得・表示
					searchCond.total = parseInt(data.photos.total,10);
					showTotal(index, searchCond.total,cond.site);

					// 検索結果が0件
					if (searchCond.total == 0) {
						return;
					}
					// エントリを参照してサムネイルを生成
					$.each(
						data.photos.photo,
						function(i,item){
							$("<li/>")
							.append(
								$("<img/>")
								.attr("src","http://static.flickr.com/"+item.server+'/'+item.id+'_'+item.secret+'_s.jpg')
								.attr("title",item.title)
								.addClass("flimage")
							)
							.click(
								function(){
									window.open('http://www.flickr.com/photos/'+item.owner+'/'+item.id+'/',null)
								}
							)
							.appendTo("#flickrlist");
						}
					);
					$('.flbody').css('height',fli_height);
					$('.flbody').css('overflow','auto');
				}
			}
		);
	}//flickrここまで

	//youtubeここから
	else if(cond.site == 'youtube'){
		// サムネイル表示を初期化
		$("#youtubelist").html('<div class="loading"><img src="./sozai/loading.gif"></div>');

		// ajax通信定義
		$.ajax(
			{
				dataType: "jsonp",
				data:{
					"vq": cond.keyword,
					"orderby": cond.orderby,
					"start-index": index,
					"max-results": VIEW_COUNT,
					"alt":"json-in-script"
				},
				cache: true,
				url: "http://gdata.youtube.com/feeds/api/videos",
				success: function (data) {
					// サムネイル表示をクリア
					$("#youtubelist").empty();
					// 検索結果件数を取得・表示
					searchCond.total = parseInt(data.feed.openSearch$totalResults.$t,10);
					showTotal(index, searchCond.total,cond.site);

					// 検索結果が0件
					if (searchCond.total == 0) {
						return;
					}
					// エントリを参照してサムネイルを生成
					$.each(
						data.feed.entry,
						function(i,item){
							var group = item.media$group;
							var desctext = group.media$description.$t;
							if(desctext.length > 70){
								desctext = desctext.substr(0,70) + '...';
							}


							$("<li/>")
							.append(
								$("<img/>")
								.attr("src", group.media$thumbnail[0].url)
								.attr("width",90)
								.attr("height",68)
								.addClass("ytimage")
							)
							.append(
								$("<span/>")
								.addClass("title")
								.text(item.title.$t)
							)
							.append(
								$("<span/>")
								.addClass("description")
								.text(desctext)
							)
							.append(
								$("<span/>")
								.addClass("description")
								.text(
									"\再\生\回\数\:" + ((item.yt$statistics == null) ? "0" : item.yt$statistics.viewCount)
								)
							)
							.append(
								$("<span/>")
								.attr("style","display:block;clear:both;color:gray;font-size:0.8em;")
								.text("投稿日時:"+ rfc3339ToJSDate(item.published.$t) +"")
								//.text(item.published.$t)
							)
							.click(
								function(){
									window.open(group.media$player[0].url, null)
								}
							)
							.appendTo("#youtubelist");
						}
					);
					$('.ytbody').css('height',yt_height);
					$('.ytbody').css('overflow','auto');
				}
			}
		);
	}//youtubeここまで
}
// --- 検索結果件数表示 ---
function showTotal(index,total,site) {
	var resultID = site+"result";
	$("#"+resultID).text(
		((total == 0) ? 0 : index)
		+ " - "
		+ (index+VIEW_COUNT > total ? total : index+VIEW_COUNT-1)
		+ " / "
		+ total
		+ "件"
	);
}
// 日本時間
function rfc3339ToJSDate(rfcdate) {
	var dt = rfcdate.split("T");
	dt[0] = dt[0].split("-");
	var time, offset;
	if (dt[1].charAt(dt[1].length - 1) == "Z") {
		time = dt[1].substr(0, dt[1].length);
		offset = "+00:00";
	} else {
		time = dt[1].substr(0, dt[1].length - 6);
		offset = dt[1].substr(dt[1].length - 6, 6);
	}
	time = time.split(":");
	var h = parseInt(time[0],10);
	var m = parseInt(time[1],10);
	var s = parseFloat(time[2]);
	var ms = Date.UTC(dt[0][0], dt[0][1] - 1, dt[0][2], h, m, s);
	var isPlus = offset.charAt(0) == "+";
	offset = offset.substring(1, offset.length);
	offset = offset.split(":");
	var offh, offm;
	offset[0].charAt(0) == "0" ? (offh = parseInt(offset[0].charAt(1))) : (offh = parseInt(offset[0]));
	offset[1].charAt(0) == "0" ? (offm = parseInt(offset[1].charAt(1))) : (offm = parseInt(offset[1]));
	var offms = (offh * 60 + offm) * 60 * 1000;
//	return isPlus ? new Date(ms - offms) : new Date(ms + offms);
	var TIMES = new Date(ms+offms);

	var Warray = new Array(7);
	Warray[0] = "日";
	Warray[1] = "月";
	Warray[2] = "火";
	Warray[3] = "水";
	Warray[4] = "木";
	Warray[5] = "金";
	Warray[6] = "土";

	var YEAR = TIMES.getYear() + 1900;
	var MONTH = TIMES.getMonth() + 1;
	var DATE = TIMES.getDate();
	var DAY = TIMES.getDay();
	var HOUR = TIMES.getHours();
	var MIN = TIMES.getMinutes();
	var SEC = TIMES.getSeconds();
	return YEAR + "年" + MONTH + "月" + DATE + "日(" + Warray[DAY] + ") " + HOUR + ":" + MIN + ":" + SEC;
}
/*****youtube*****/

