/**
 * @author maripo
 */

var FULL_WIDTH = 500;
var FULL_HEIGHT = 500;
var URL_PREFIX = 'http://www.flickr.com/photos/';
var IMG_URL_PREFIX = 'http://farm4.static.flickr.com/';

 function  startClock () {
	loadJsonp ('http://www.madin.jp/haikyo/list_static.js')
	loadJsonp ('http://www.madin.jp/haikyo/listLite.js');
 	setInterval (function(){clock.refresh()}, 1000);
 }

 var Clock = function () {
	this.hour = null;
	this.min = null;
	this.sec = null;
	this.currentPicture = null;
	this.pictures = null;
	this.hour12 = null;
 };

 Clock.prototype = {
 	setPictures: function (pictures) {
		this.pictures = pictures;
	},
 	refresh: function () {
		var date = new Date();
		var hour = date.getHours();
		var min = date.getMinutes();
		var sec = date.getSeconds();
		this.sec = sec;
		if (this.pictures==null || (this.hour==hour && this.min==min)) {
			return;
		}
		this.hour = hour;
		this.min = min;
		this.hour12 = this.hour % 12;
		var _newPicture = this.pictures.getNearestPicture(this.currentPicture, this.hour, this.min);
		if (this.currentPicture!=_newPicture) this.swapImage(_newPicture, this.currentPicture);
	},
	swapImage: function (_newPicture, oldPicture) {
		this.currentPicture = _newPicture;
		var img = document.createElement('IMG');
		img.src = this.currentPicture.getPictureUrl();
		img.style.marginLeft = Math.floor((FULL_WIDTH-this.currentPicture.width)/2)  + "px";
		img.style.marginTop = Math.floor((FULL_HEIGHT-this.currentPicture.height)/2)  + "px";
		img.style.display = 'none';
		document.getElementById("clockImageLink").href = this.currentPicture.getUrl();
		document.getElementById('clockImageLink').appendChild(img);
		img.title = this.currentPicture.title + " on Flickr";
		this.currentPicture.imgElement = img;
		var self = this;
		if (oldPicture && oldPicture.imgElement) {
			fade(1,0,oldPicture.imgElement,function(){
				oldPicture.imgElement.parentNode.removeChild(oldPicture.imgElement);
				oldPicture.imgElement = null;
				self.currentPicture.showDetail();
				fade(0, 1, self.currentPicture.imgElement, null);
			});
		} else {
			self.currentPicture.showDetail();
			fade(0, 1, self.currentPicture.imgElement, null);
		}
	},
	getTimeString: function () {
		if (this.hour==null || this.min==null || this.sec==null) return "";
		return this.getNumString(this.hour) + ":" + this.getNumString(this.min) + ":" + this.getNumString(this.sec);	
	},
	getNumString: function (num) {
		if (num < 10) return '0' + num;
		return num;
	}
	
 };
 
 var FADE_DURATION_MSEC = 2000;
 var FADE_FRAME_MSEC = 50;
 
 function fade (startAlpha, finishAlpha, obj, onFinishCallback) {
 	_fade (startAlpha, finishAlpha, (finishAlpha-startAlpha)/(FADE_DURATION_MSEC/FADE_FRAME_MSEC), obj, onFinishCallback);	
 }
 function _fade (currentAlpha, finishAlpha, alphaStep, obj, onFinishCallback) {
	currentAlpha += alphaStep;
	_setAlpha(obj, currentAlpha);
	if ( (alphaStep>0 && currentAlpha >= finishAlpha )|| (alphaStep < 0 && currentAlpha <= finishAlpha )) {
		if (onFinishCallback) onFinishCallback();
	} else {
	 	setTimeout (function () {
			_fade (currentAlpha, finishAlpha, alphaStep, obj, onFinishCallback);
		}, FADE_FRAME_MSEC);
	}
 }
 function _setAlpha (obj, alpha) {
 	obj.style.display = 'inline';
	obj.style.filter = 'alpha(opacity=' + Math.floor(alpha*100) +')';
	obj.style.MozOpacity = alpha; 
	obj.style.opacity = alpha;
 }
 
 function _addEventListener (obj, func) {
 	if (window.attachEvent){
        obj.attachEvent("onload", func, false);
    } else if (window.addEventListener){
        obj.addEventListener("load", func, false);
    } else {
        obj.onload = func;
    }
 }
 
 var StaticPicture = function (obj) {
 	this.hour = obj.hour;
	this.min = obj.min;
	this.width = obj.width || 500;
	this.height = obj.height || 500;
	this.rand = Math.random();
	this.author = obj.author;
	this.file = obj.file;
	this.url = obj.url;
	this.title = obj.title || '';
	this.onlyPm = (obj.amPm && 'PM'==obj.amPm);
	this.onlyAm = (obj.amPm && 'AM'==obj.amPm);
 }
 StaticPicture.prototype = {
 	isAfter: function (hour, min) {
		return (this.hour * 60 + this.min > hour * 60 + min);
	},
	showDetail: function () {
		document.getElementById("clockImageLink").href = this.getUrl();
		document.getElementById("imageLink").href = this.getPictureUrl();
		document.getElementById("imageLink").style.display = 'none';
		document.getElementById("imageTitle").innerHTML = this.title;
		document.getElementById("imageAuthor").innerHTML = 'by ' + this.author;
	},
	getUrl: function () {
		return this.url;
	},
	getPictureUrl: function () {
		return STATIC_PICTURE_PREFIX + this.file;
	}
 }
 var STATIC_PICTURE_PREFIX = 'clock_img/';
 
 var Picture = function (jsonObj) {
 	this.author = jsonObj['author'];
 	this.title = jsonObj['title'];
 	this.height = jsonObj['h']  || FULL_HEIGHT;
 	this.width = jsonObj['w'] || FULL_WIDTH;
 	this.hour = jsonObj['hour'];
 	this.min = jsonObj['min'];
	this.rand = Math.random();
	
	this.aid = jsonObj['aid'];
	this.pid = jsonObj['pid'];
	this.sid = jsonObj['sid'];
	this.suf = jsonObj['suf'];
	this.onlyPm = (jsonObj.amPm && 'PM'==obj.amPm);
	this.onlyAm = (jsonObj.amPm && 'AM'==obj.amPm);
 };
 Picture.prototype = {
 	isAfter: function (hour, min) {
		return (this.hour * 60 + this.min > hour * 60 + min);
	},
	showDetail: function () {
		document.getElementById("clockImageLink").href = this.getUrl();
		document.getElementById("imageLink").href = this.getPictureUrl();
		document.getElementById("imageLink").style.display = 'inline';
		document.getElementById("imageTitle").innerHTML = this.title;
		document.getElementById("imageAuthor").innerHTML = 'by ' + this.author.replace(new RegExp('\'s$'),'');
	},
	getUrl: function () {
		return URL_PREFIX + this.aid + '/' + this.pid + '/';
	},
	getPictureUrl: function () {
		return IMG_URL_PREFIX + this.sid + '/' + this.pid + '_' + this.suf + '.jpg';
	}
 }
 
 var Pictures = function (container) {
 	this.list = new Array();
	var jsonList = container['imgs'];
	for (var i=0, l=jsonList.length; i<l; i++) {
		if (jsonList[i]['author'] && jsonList[i]['pid'] &&  ((new RegExp('^[0-9]+$')).test(jsonList[i]['pid'])))
			this.list.push(new Picture(jsonList[i]));
	}
	if (listStatic) {
		for (var i = 0, l = listStatic.length; i < l; i++) {
			this.list.push(new StaticPicture(listStatic[i]));
		}
	}
	this.list.sort(function(a,b){
		return (a.hour * 60 + a.min + a.rand < b.hour * 60 + b.min + b.rand)?-1:1;
	});
	var tmpArray = new Array();
	for (var key in this.list) {
		tmpArray.push("hour=" + this.list[key].hour + ",min=" + this.list[key].min);
	}
 };
 Pictures.prototype = {
 	getNearestPicture: function (tmpPicture, hour24, min) {
		var hour = hour24 % 12;
		var _picture = tmpPicture;
		for (var i=0, l=this.list.length; i<l; i++) {
			if (_picture != null && this.list[i].isAfter(hour, min)) {
				break;
			}
			_picture = this.list[i];
			if (tmpPicture&& ( (hour24>=12 && tmpPicture.onlyAm) || (hour24<12 && tmpPicture.onlyPm) )) continue;
		}
		
		return _picture;
	}
 };
 
 var clock = new Clock();
function loadJsonp (url) {
	var script = document.createElement('script');
	script.charset = 'utf-8';
	script.src = url;
	document.body.appendChild(script);
}
 function readClock (container) {
 	clock.setPictures(new Pictures(container));
 }
function onLoadImage () {
}

