var is_login = false;
var is_try_sponsor = false;
var is_sponsor = false;
$(function(){
	//google.load("maps", "3", { other_params : "sensor=false" });
//	google.load("feeds", "1");
	reload();
	setInterval(function(){
		reload();
	}, 1000 * 60);

	init_tweet();
	$("#aatv_tab").click(function(){
		$("#photo_player").hide();
		$("#movie_player").show();
		return false;
	});
	$("#movie_tab").click(function(){
		$("#photo_player").show();
		$("#movie_player").hide();
		return false;
	});
});
function init_tweet(){
	var tweet_suffix = TWEET_SUFFIX;
	var tweet_area = $("#status");
	var tweet_text_limit = $("#tweet_text_limit");
	setInterval(function(){
		var limit = 140 - (tweet_suffix ? tweet_suffix.length + 1 : 0) - tweet_area.val().length;
		tweet_text_limit.text(limit);
	}, 300);
	do_tweet_test(function(){
		is_login = true;
		load_director_tweet();
	});
	$("#director_tweet_login a").attr("href","app.cgi?login=1&cb=" + encodeURIComponent(location.href)); 
	$("#send_status").click(function(){
		//if($(this).hasClass("disable")){ return; }
		if($(this).hasClass("require_login")){
			location.href = "app.cgi?login=1&cb=" + encodeURIComponent(location.href);
			return false;
		}
		var tweet = $("#status").val();
		if(!tweet){
			return false;
		}
		if(tweet_suffix){
			tweet += " " + tweet_suffix;
		}
		do_tweet_post(tweet);
		return false;
	});
}
function do_tweet_test(cb){
	$.post("app.cgi", {
		do_test : 1
	}, function(result){
		if(check_error(result)){
			$("#tweet_user").text($("name", result).text());
			if(cb){ cb(); }
		}
	});
}
function do_tweet_post(status){
	$.post("app.cgi", {
		do_post : 1,
		status : status
	}, function(result){
		if(check_error(result)){
			$("#status").val("");
		}
	});
}
function check_error(result){
	var error = $("error", result).text();
	var url = "app.cgi?login=1&cb=" + encodeURIComponent(location.href);
	if(error){
		$("#send_status").addClass("disable");
		var url = "app.cgi?login=1&cb=" + encodeURIComponent(location.href);
		$("#twitter .require_twitter_login")
		.attr("href", url)
		.show();
		$("#send_status").addClass("require_login");
		$("#twitter .after_twitter_login").hide();
		return false;
	}else{
		$("#send_status").removeClass("disable");
		$("#twitter .require_twitter_login").hide();
		$("#send_status").removeClass("require_login");
		$("#twitter .after_twitter_login").show();
		return true;
	}
}

function reload(){
	if($("#photo_player").css("display") != "none"){
		//load_aatv();
	}
	load_image_gallery();
	load_live_tweet();
	load_ouen_tweet();
	if(is_login){
		load_director_tweet();
	}
}
function load_picasa(url, cb){
	var id = url.substring(0, url.indexOf("?"));
	$.getJSON(url, cb); 
}
function load_aatv(){
	load_picasa(u(AATV_FEED_URL), function(result){
/*
		var last_entry = result.feed.entry[result.feed.entry.length - 1];
		last_entry = last_entry["media$group"]["media$thumbnail"];
		$("#aatv").html(
			$("<img>")
			.attr("src", last_entry[last_entry.length - 1].url)
			.attr("className", "aatv-img")
		);
*/
		var items =  result.feed.entry.reverse();
		var container = $("#aatv").empty();
		$.each(items, function(){
			var item = this;
			var link = item.link[1].href;
			var _thumb = get_child_json(item, ["media$group", "media$thumbnail"]);
			var _content = get_child_json(item, ["media$group", "media$content"]);
			var content = _thumb[_thumb.length - 1].url;
			var content_h = _thumb[_thumb.length - 1].height;
			var content_w = _thumb[_thumb.length - 1].width;
			var box_size = {
				w: 600,
				h: 340
			};
			box_size.w = content_w;
			box_size.h = content_h;
			show_overlay = function(){
				$("#gallery_zoom img.content").attr("src", content);
				$("#gallery_zoom a.link").attr("href", link);
			};
			container.append(
				$("<a>")
				.attr("rel", "superbox[content][" + box_size.w + "x" + box_size.h+ "]")
				.attr("href", "#gallery_zoom")
				.bind("pre_click", show_overlay)
				.html(
					$("<img>")
					.attr("src", _thumb[_thumb.length - 1].url)
					.attr("className", "aatv-img")
				)
			);
		});
	});
}
function _load_aatv(datas){
	var container = $("#aatv").empty();
	$.each(datas, function(index){
		if(index >= 4){ return false; }
		var item = this;
		var link = item.href;
		var content = item.img;
/*
		var _thumb = get_child_json(item, ["media$group", "media$thumbnail"]);
		var _content = get_child_json(item, ["media$group", "media$content"]);
		var content = _thumb[_thumb.length - 1].url;
		var content_h = _thumb[_thumb.length - 1].height;
		var content_w = _thumb[_thumb.length - 1].width;
		box_size.w = content_w;
		box_size.h = content_h;
*/
		var box_size = {
			w: 600,
			h: 340
		};
		var show_overlay = function(){
			$("#gallery_zoom img.content").attr("src", content);
			$("#gallery_zoom a.link").attr("href", link);
		};
		container.append(
			$("<a>")
			//.attr("rel", "superbox[content][" + box_size.w + "x" + box_size.h+ "]")
			//.attr("href", "#gallery_zoom")
			.attr("href", link)
			.attr("target", "_blank")
			//.bind("pre_click", show_overlay)
			.html(
				$("<img>")
				.attr("src", content)
				.attr("className", "aatv-img")
			)
		);
	});
}
function load_image_gallery(){
	var max_image_count = 15;
	load_picasa(u(LIVE_GALLERY_FEED_URL), function(result){
		var ul = $("<ul>");
		var ul2 = $("<ul>");
		if(!result){
			return;
		}
		var items = result.feed.entry;
		if(items.length > max_image_count){
			items = items.slice(items.length - max_image_count, items.length);
		}
		var _items = [];
		for(var i = 0; i < items.length; i++){
			_items.unshift(items[i]);
		}
		items = _items;
		var idx = 0;
		$.each(items, function(){
			var item = this;
			var link = item.link[1].href;
			var pos = get_child_json(item, ["georss$where", "gml$Point", "gml$pos", "$t"]);
			if(pos){
				pos = pos.split(" ");
			}
			var _thumb = get_child_json(item, ["media$group", "media$thumbnail"]);
			var thumb = _thumb[1].url;
			var _content = get_child_json(item, ["media$group", "media$content"]);
			/*var content = _content[0].url;*/
			/*var content_h = _content[0].height;*/
			/*var content_w = _content[0].width;*/
			var content = _thumb[_thumb.length - 1].url;
			var content_h = _thumb[_thumb.length - 1].height;
			var content_w = _thumb[_thumb.length - 1].width;
			var show_overlay;
			var box_size = {
				w: 600,
				h: 340
			};
			if(pos){
				show_overlay = function(){
					var map_url = "http://maps.google.com/maps/api/staticmap?sensor=false&zoom=14&size=" + box_size.w + "x" + box_size.h + "&maptype=roadmap&center=" + pos[0] + "," + pos[1];
					//$("#gallery_zoom_with_map img.map").attr("src", map_url);
					$("#gallery_zoom_with_map").css("background-image", "url(" + map_url + ")");
					$("#gallery_zoom_with_map img.content").attr("src", content);
					$("#gallery_zoom_with_map a.link").attr("href", link);
					//$("#gallery_zoom_with_map img.content").dropShadow();
					if($.browser.msie && parseInt($.browser.version) < 8){
						$("#gallery_zoom_with_map img.content")
						.css("margin-top", ($("#gallery_zoom_with_map").height() - content_h) / 2 )
						;
					}
				};
			}else{
				box_size.w = content_w;
				box_size.h = content_h;
				show_overlay = function(){
					$("#gallery_zoom img.content").attr("src", content);
					$("#gallery_zoom a.link").attr("href", link);
				};
			}
			var img = $("<a>")
			.attr("rel", "superbox[content][" + box_size.w + "x" + box_size.h+ "]")
			.attr("href", pos ? "#gallery_zoom_with_map" : "#gallery_zoom")
			.bind("pre_click", show_overlay)
			.html(
				$("<img>").attr("src", thumb)
				.attr("id", "views")
				.css("cursor", "pointer")
			)
			;
			idx++;
			if(idx > max_image_count / 2){
				ul2.append($("<li>").append(img));
			}else{
				ul.append($("<li>").append(img));
			}
		});
		$("#live_gallery a").remove();
		$("#live_gallery")
		.empty()
		.append(ul)
		.append(ul2);
		$.superbox();
	});
}
function load_director_tweet(){
	if(!is_sponsor && is_try_sponsor){
		return;
	}
	$("#director_tweet_login").css("visibility", "hidden");
/*
	if($("#director_tweet_deny").css("display") != "none"){
		return;
	}
*/
	$.get(u("./app.cgi?do_get=1&t=json&url=" + encodeURIComponent(DIRECTOR_TWEET_URL) + (is_try_sponsor ? "" : "&nocache=1")), function(result){
		var container = $("#director_tweet");
		if(!is_try_sponsor){
			is_try_sponsor = true;
			$("#director_tweet_login").hide();
			if(!result.status.length){
				is_sponsor = false;
				$("#director_tweet_deny").show();
				return;
			}else{
				is_sponsor = true;
				//load_aatv();
				$("#photo_player").show();
			}
			$("#live_tweet").removeClass("live_tweet_long").addClass("live_tweet_short");
		}
		container.empty().hide();
		$.each(result.status, function(){
			var entry = parse_entry(this);
			var elem = $("<div>")
			.attr("className", "comment-container")
			.append(
				$("<img>")
				.attr("className", "icon")
				.attr("src", entry.user_photo)
			)
			.append(
				$("<div>")
				.attr("className", "comment-right")
				.append(
					$("<div>")
					.attr("className", "comment-top")
					.append(
						$("<p>")
						.append(
							$("<a>")
							.attr("href", "http://twitter.com/" + entry.user_id)
							.html(entry.user_name)
						)
					)
				)
				.append(
					$("<div>")
					.attr("className", "comment-text")
					.append(
						$("<p>")
						.html(entry.text)
					)
					
					.append(
						$("<p>")
						.html(entry.date)
					)
					//.append($("<hr />"))
				)
				.append(
					$("<div>")
					.attr("className", "comment-bottom")
				)
			)
			;
			container.append(elem);
		});
		var aatv_imgs = [];
		$(".thumb", container).hide().each(function(){
			aatv_imgs.push({
				href : $(this).attr("href"),
				img : $("img", this).attr("src")
			});
		});
		_load_aatv(aatv_imgs);
		container.show();
		$.superbox();
	}, "json");
}
function load_live_tweet(){
	$.get(u(LIVE_TWEET_URL), function(result){
		var container = $("#live_tweet");
		container.empty().hide();
		$.each(result.status, function(){
			var entry = parse_entry(this);
			var elem = $("<div>")
			.attr("className", "comment-container")
			.append(
				$("<img>")
				.attr("className", "icon")
				.attr("src", entry.user_photo)
			)
			.append(
				$("<div>")
				.attr("className", "comment-right")
				.append(
					$("<div>")
					.attr("className", "comment-top")
					.append(
						$("<p>")
						.append(
							$("<a>")
							.attr("href", "http://twitter.com/" + entry.user_id)
							.html(entry.user_name)
						)
					)
				)
				.append(
					$("<div>")
					.attr("className", "comment-text")
					.append(
						$("<p>")
						.html(entry.text)
					)
					
					.append(
						$("<p>")
						.html(entry.date)
					)
					//.append($("<hr />"))
				)
				.append(
					$("<div>")
					.attr("className", "comment-bottom")
				)
			)
			;
			container.append(elem);
		});
		container.show();
		$.superbox();
	}, "json");
}
function load_ouen_tweet(){
	$.get(u(OUEN_TWEET_URL), function(result){
		var container = $("#ouen_tweet");
		container.empty().hide();
		$.each(result.status, function(){
			var entry = parse_entry(this);
			var elem = $("<div>")
			.attr("className", "comment-container")
			.append(
				$("<img>")
				.attr("className", "icon")
				.attr("src", entry.user_photo)
			)
			.append(
				$("<div>")
				.attr("className", "comment-right")
				.append(
					$("<div>")
					.attr("className", "comment-top")
					.append(
						$("<p>")
						.append(
							$("<a>")
							.attr("href", "http://twitter.com/" + entry.user_id)
							.html(entry.user_name)
						)
					)
				)
				.append(
					$("<div>")
					.attr("className", "comment-text")
					.append(
						$("<p>")
						.html(entry.text)
					)
					
					.append(
						$("<p>")
						.html(entry.date)
					)
					//.append($("<hr />"))
				)
				.append(
					$("<div>")
					.attr("className", "comment-bottom")
				)
			)
			;
			container.append(elem);
		});
		container.show();
		$.superbox();
	}, "json");
}
function parse_entry(entry){
	entry.text = to_viewable(entry.text || '');
	var date = new Date(entry.date * 1000);
	var h = date.getHours();
	var ap = "AM";
	if(h > 12){
		h -= 12;
		ap = "PM";
	}
	var m = [
		'Jan',
		'Feb',
		'Mar',
		'Apr',
		'May',
		'Jun',
		'Jul',
		'Aug',
		'Sep',
		'Oct',
		'Nov',
		'Dec'
	];
	var dp = "th";
	var d = date.getDate();
	if(d == 1){
		dp = "st";
	}else if(d == 2){
		dp = "nd";
	}else if(d == 3){
		dp = "rd";
	}
	var min = date.getMinutes();
	if(min < 10){
		min = '0' + min;
	}
	entry.date = h + ":" + min + " " + ap + " " + (date.getMonth() + 1) + "/" + d;
	return entry;
}
function to_viewable(text){
	//text = text.replace(/(https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:@&=+$,%#]+)/, '<a href="$1">$1</    a>', 'g');
	var thumb_view = '';
	text = text.replace(/(https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:@&=+$,%#]+)/g, function(url){
		var thumb = null;
		if(0 == url.indexOf("http://twitpic.com/")){
			var id = url.substring(url.lastIndexOf("/") + 1);
			thumb = "http://twitpic.com/show/thumb/" + id;
		}else if(0 == url.indexOf("http://www.twitpic.com/")){
			var id = url.substring(url.lastIndexOf("/") + 1);
			thumb = "http://twitpic.com/show/thumb/" + id;
		}else if(0 == url.indexOf("http://twitgoo.com/")){
			var id = url.substring(url.lastIndexOf("/") + 1);
			thumb = "http://twitgoo.com/show/thumb/" + id;
		}
		if(thumb){
			thumb_view = "<a class='thumb' target='_blank' href='" + url + "'><img src='" + thumb + "' /></a>";
		}
		return "<a target='_blank' href='" + url + "'>" + url + "</a>";
	});

	return text + "<br/>" + thumb_view;
}

/*
function load_feed(url, count, cb){
	var feed = new google.feeds.Feed(u(url));
	feed.setNumEntries(count);
	feed.load(function(result){
		if(result.error){
			trace(result.error.message);
			cb(false);
			return;
		}
		cb(true, result.feed.entries);
	});
}
*/
function trace(msg){
	if(window["console"]){
		console.log(msg);
	}
}
function get_name(){
	var path = location.pathname;
	var name = path.substring(path.lastIndexOf("/") + 1);
	name = name.substring(0, name.lastIndexOf("."));
	return name;
}
function async(f){
	setTimeout(f, 1);
}
function get_now(){
	var now = new Date();
	return (1900 + now.getYear()) + "/" + (now.getMonth() + 1) + "/" +now.getDate() + " " + now.getHours() + ":" + now.getMinutes();
}

function split_querystring(search){
	var queryString = {};
	if(search.length == 0){
		return queryString;
	}
	var str = null;
	if(search.charAt(0) == '?'){
		str = search.substring(1);
	}else{
		str = search;
	}
	var ar1 = str.split('&');
	for(var i = 0; i != ar1.length; i++) {
		var ar2 = ar1[i].split('=');
		queryString[decodeURIComponent(ar2[0])] =  decodeURIComponent(ar2[1]);
	}
	return queryString;
}
function u(url){
	if(-1 == url.indexOf("?")){
		url += "?rand=" + (new Date()).getTime();
	}else{
		url += "&rand=" + (new Date()).getTime();
	}
	return url;
}

function get_child_json(item, tags){
	 var len = tags.length;
	for(var i = 0; i < len; i++){                
		item = item[tags[i]];                    
		if(!item){
			return null;
		}   
	}       
    return item;                                 
}           
