dojo.require('dojo.html');
var pw_style = "#album_name {text-align: center;}";
pw_style += "#album_list_link{}"
pw_style += "#pwFeed ul {margin: 0px; padding: 0px; position: relative;}";
pw_style += "#pwFeed li.photos{list-style: none; text-align: center; float: left; width: 72px; height: 72px; margin: 10px; }";
pw_style += "#pwFeed li.albums{list-style: none; text-align: center; float: left; width: 144px; height: 200px; margin: 8px; }";
pw_style += "#pwFeed img {background: #101010; padding: 0px;}";
pw_style += "#pwFeed img.photos{margin: 0px;}";
pw_style += "#pwFeed img.albums{margin: 0px 0px 5px 0px;}";
pw_style += "#pwFeed li.loading {text-align: center; list-style-type: none; list-style-image: none; list-style-position: outside;}";
pw_style += "#pwFeed a {text-decoration: none;}";
pw_style += "#pwFeed div {clear: both;}";
pw_style += "#pwPopper {border: solid #FF6600 1px; display: none; position: absolute; width: 350px; height: auto; z-index: 500; background: #101010;}";
pw_style += "#pwPopper img {cursor: pointer; float: left; border: solid #585858 2px; background: #101010; margin: 5px;}";
pw_style += "#pwPopper h2 { font-size: 12px; font-weight: bold; text-align: center; clear: both;}";
pw_style += "#pwPopper-info { width: 180px; margin: 5px; float: left;}";
pw_style += "#pwPopper-info .label {color: #FF6600; margin-top: 10px; float: left; line-height: 1.3em; text-align: right; width: 45px; margin-right: 10px;}";
pw_style += "#pwPopper-info .value {color: #AAAAAA; margin-top: 10px; line-height: 1.3em; margin-left: 55px;}";
pw_style += "p.nocomments {display: none;}";

// This is the markup that goes in the page to make this work...
/*
<span id="pwFeedContainer" class="picasa-id"></span>
<script src="http://images.bringthegoat.com/script/picasa.js" type="text/javascript"></script>
*/

function PicasaPhoto()
{
	this.url = '';
	this.title = '';
	this.description = '';
	this.big_thumb = new Object();
	this.tags = '';
	this.width = '';
	this.height = '';
	this.timestamp = '';
	this.size = 0;
	this.gps = "";
}

var PView = 
{
	photos: new Object(),
	cache: new Object(),
	pw_container: "pwFeedContainer",
	pw_user: null,
	timer: null,
	timeout: null,
	popper: null,
	
	write_script: function(){
		var album = this.get_query()['album'] || "";
		var authkey = this.get_query()['authkey'] || "";
		var tag = this.get_query()['t'] || "";
		
		if (authkey != "")
			authkey = "&authkey=" + authkey;
			
		var script = document.createElement('script');
		if (album != "")
			script.setAttribute('src', "http://picasaweb.google.com/data/feed/api/user/" + this.pw_user + "/albumid/" + album + "?kind=photo&thumbsize=72c&imgmax=200&alt=json-in-script&callback=PView.build_page" + authkey);
		else if (tag != "")
			script.setAttribute('src', "http://picasaweb.google.com/data/feed/api/user/" + this.pw_user + "?kind=photo&tag=" + encodeURIComponent(tag) + "&thumbsize=72c&imgmax=200&alt=json-in-script&callback=PView.build_page");
		else
			script.setAttribute('src', "http://picasaweb.google.com/data/feed/api/user/" + this.pw_user + "?kind=album&thumbsize=144c&imgmax=288&alt=json-in-script&callback=PView.build_page");
		script.setAttribute('id', 'jsonScript');
		script.setAttribute('type', 'text/javascript');
		document.documentElement.firstChild.appendChild(script);
	},
	
	get_query: function(){
		var query = new Object();
	
		var args = document.location.search.replace(/^\?/, '').split("&");
		for (var i = 0; i < args.length; i++)
		{
			if (args[i].split('=').length == 2)
			{
				var key = decodeURIComponent(args[i].split('=')[0]);
				var value = decodeURIComponent(args[i].split('=')[1]);
				query[key] = value;
			}
		}
		return query;
	},
	
	init_markup: function(){
		var album = PView.get_query()['album'] || "";
		var tag = PView.get_query()['t'] || "";
		
		var container = document.getElementById(PView.pw_container);
		PView.pw_user = container.className;
		
		PView.insert_css(pw_style);

		if (album != "" || tag != "")
		{
			var link = dojo.create('A', {href: '.', id: 'album_list_link', innerHTML: "\u00ab back to album list"}, container);
			var header = dojo.create('H2', {id: 'album_name'}, container);
		}

		var list = dojo.create('UL', {id: 'pwFeed', className: 'album-carousel-container'}, container);
		var loading = dojo.create('LI', {className: 'loading', innerHTML: 'Loading Photos...'}, list);
	
		PView.popper = dojo.create('DIV', {id: 'pwPopper'}, container);	
		PView.popper.onmouseover = PView.pop_hover;
		PView.popper.onmouseout = PView.leave;
		PView.write_script();
	},

	build_page: function(root) {
		var album = this.get_query()['album'] || "";
		var tag = this.get_query()['t'] || "";
		
		var list = document.getElementById('pwFeed');
		list.removeChild(list.childNodes[0]);
		
		var feed = root.feed;
		var entries = feed.entry || [];
		var album_title = feed.title.$t;

		if (album != "")
			dojo.html.set('album_name', album_title);

		for (var i = 0; i < feed.entry.length; ++i) {
			var entry = feed.entry[i];
			var title = entry.title.$t;
			var id = entry.gphoto$id.$t;
			var thumb = entry.media$group.media$thumbnail[0];
			var url = '';
			for (var j = 0; j < entry.link.length; ++j) 
			{
				if (entry.link[j].rel == "alternate") {
					url = entry.link[j].href;
					break;
				}
			}
			this.photos[id] = new PicasaPhoto();
			this.photos[id].type = (album == "") ? "album" : "photo";
			this.photos[id].title = title;
			this.photos[id].description = entry.media$group.media$description.$t;
			this.photos[id].tags = entry.media$group.media$keywords.$t;
			if (album != "" || tag != "")
			{
				this.photos[id].width = entry.gphoto$width.$t;
				this.photos[id].height = entry.gphoto$height.$t;
				try {
					this.photos[id].timestamp = entry.gphoto$timestamp.$t;
					this.photos[id].size = entry.gphoto$size.$t;
				} catch(e){}
				try {
					this.photos[id].gps = entry.georss$where.gml$Point.gml$pos.$t.replace(' ', ',');
				} catch(e){}
				this.photos[id].big_thumb = entry.media$group.media$content[0];
				this.photos[id].url = url;
				this.cache[id] = new Image();
				this.cache[id].src = this.photos[id].big_thumb.url;
			}
			
			var padding = (thumb.width*1 > thumb.height*1) ? thumb.width*1 - thumb.height*1 - 1 : 0;
			var class_name = (album == "" && tag == "") ? "albums" : "photos";
			var title = (album == "" && tag == "") ? title : "";
			var url = (album == "" && tag == "") ? "?album=" + id : url;
			
			var item = dojo.create('LI', {className: class_name});
			var link = this.link(id, title);
			var thumb_image = this.image(id, padding, class_name, thumb);
			
			list.appendChild(item);
			item.appendChild(link);
			link.appendChild(thumb_image);
			
			if (album == "" && tag == "")
			{
				link.appendChild(document.createTextNode(" " + title));
			} else {
				thumb_image.onmouseover = this.enter;
				thumb_image.onmouseout = this.leave;
			}
		}
		list.appendChild(document.createElement('DIV'));
                //var carousel = new csitko.widget.Carousel('album-carousel', 3, 3, false, false, 1);
	},
	
	item: function(classname){
		return dojo.create('LI', {className: classname});
	},
	
	link: function(id, title){
		return dojo.create('A', {id: 'link-' + id, title: title, href: "javascript:PView.open('" + id + "')"});
	},
	
	image: function(id, padding, classname, thumb, from_cache){
		if (!from_cache)
			from_cache = "";

		var image = document.createElement('IMG');
		image.setAttribute('class', classname);
		image.setAttribute('className', classname);
		image.setAttribute('width', thumb.width);
		image.setAttribute('height', thumb.height);
		image.setAttribute('id', 'thumb-' + id);
		if (padding != null)
			image.style.marginTop = padding + "px";
		if (from_cache == "")
			image.setAttribute('src', thumb.url);
		else
			image.src = this.cache[from_cache].src;
			
		return image;
	},
	
	hover: function(id){
		var photo = this.photos[id];
		
		var width = photo.big_thumb.width*1 + 15 + 190;
		
		offset = PView.offset(document.getElementById('thumb-' + id));
		PView.popper.style.top = offset[1] + "px";
		PView.popper.style.left = offset[0] + "px";
		PView.popper.style.width = width + "px";
		
		var description = document.createElement('H2');
		description.setAttribute('id', 'pwPopper-description');
		description.appendChild(document.createTextNode(photo.description || "(no caption)"));

		var info = document.createElement('DL');
		info.setAttribute('id', 'pwPopper-info');

		dojo.create('DT', {className: 'label', innerHTML: 'date:'}, info);
		dojo.create('DD', {className: 'value', innerHTML: PView.format_date(photo.timestamp)}, info);
		dojo.create('DT', {className: 'label', innerHTML: 'tags:'}, info);
		dojo.create('DD', {className: 'value', innerHTML: photo.tags}, info);
	
		var big_thumb = PView.image('big-thumb', null, '', photo.big_thumb, id);
		big_thumb.onclick = function(){PView.open(id);};
			
		try{
			PView.popper.replaceChild(big_thumb, document.getElementById('thumb-big-thumb'));
			PView.popper.replaceChild(info, document.getElementById('pwPopper-info'));
			PView.popper.replaceChild(description, document.getElementById('pwPopper-description'));
		} catch(e) {
			PView.popper.appendChild(big_thumb);
			PView.popper.appendChild(info);
			PView.popper.appendChild(description);
		}
		
                dojo.style(PView.popper, {display: 'block', opacity: 0});
		PView.makeVisible(document.getElementById('thumb-' + id));
		dojo.anim(PView.popper, {opacity: 1}, 250, null, null);
	},
	
	makeVisible: function(attached)
	{
		var popper = PView.popper;
		var top = popper.style.top.replace(/px/, '')*1;
    	
		var popup_bottom = popper.clientHeight + top - getScrollOffset().pageYOffset;
		var new_top = top - popper.clientHeight + attached.clientHeight;
		var window_height = getSize().height;

		// position the popup above the element if it will fit there but not below
		if (popup_bottom > window_height && new_top > 0)
			popper.style.top = new_top + "px";
	},
	
	blur: function(e){
		dojo.anim(PView.popper, {opacity: 0}, 250, null, function(){
			PView.popper.style.display = "none";
		});
	},
	
	pop_hover: function(e){
		clearTimeout(PView.timeout);
	},
	
	enter: function(e){
		var element = PView.get_source(e);
		var id = element.id.replace(/thumb-/, '');
		
		this.timer = setTimeout("PView.hover('" + id + "');", 1000);
	},
	
	leave: function(e){
		clearTimeout(this.timer);
		PView.timeout = setTimeout("PView.blur()", 250);
	},
	
	open: function(id){
		var photo = this.photos[id];
		if (photo.type == 'album')
			document.location.href = "?album=" + encodeURIComponent(id);
		else
			document.location.href = photo.url;
	},
	
	map: function(id){
		var photo = this.photos[id];
		document.location.href = "http://maps.google.com/?q=" + encodeURIComponent(photo.gps);;
	},
	
	insert_css: function(cssStr){
		if(!cssStr)
			return;

		var doc = document;
		var style = doc.createElement("style");
		style.setAttribute("type", "text/css");
		var head = doc.getElementsByTagName("head")[0];
		if(!head)
			return;
		else
			head.appendChild(style);
		if(style.styleSheet)
		{
			var setFunc = function(){
				try{
					style.styleSheet.cssText = cssStr;
				}catch(e){}
			};
			if(style.styleSheet.disabled)
				setTimeout(setFunc, 10);
			else
				setFunc();
		} else {
			var cssText = doc.createTextNode(cssStr);
			style.appendChild(cssText);
		}
		return style;
	},
	
	get_source: function(ev){
		if(ev)
			if (ev.target)
				return ev.target;
			else if (ev.srcElement)
				return ev.srcElement;
		if(window.event)
			return window.event.srcElement;
	}, 
	
	offset: function(elem){
		var left = 0 + elem.offsetWidth + 10;
		var top = 0;
		while (elem.offsetParent && elem.tagName.toUpperCase() != 'BODY')
		{
			left += elem.offsetLeft;
			top += elem.offsetTop;
			elem = elem.offsetParent;
		}

		left += elem.offsetLeft;
		top += elem.offsetTop;
		return [left, top];
	},
	
	format_date: function(timestamp){
		var date = new Date(timestamp * 1);
//		return date.toLocaleDateString();
		var month = (date.getMonth() < 9) ? "0" + (date.getMonth()+1) : (date.getMonth()+1);
		var day = (date.getDate() < 10) ? "0" + date.getDate() : date.getDate();
		
		return month + "/" + day + "/" + date.getFullYear();
	},
	
	format_size: function(bytes){
		var kbyte = 1024;
		var mbyte = 1048576;
		if (bytes < kbyte)
			return bytes + " bytes";
		else if (bytes >= kbyte && bytes < mbyte)
			return Math.round(bytes/kbyte * 100) / 100 + " KB";
		else if (bytes >= mbyte)
			return Math.round(bytes/mbyte * 100) / 100 + " MB";
	}
}

// cross-browser method to get window size
function getSize() {
	var size = new Object();
	size.width = 0;
	size.height = 0;
	if( typeof( window.innerWidth ) == 'number' )
	{
		//Non-IE
		size.width = window.innerWidth;
		size.height = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		size.width = document.documentElement.clientWidth;
		size.height = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		size.width = document.body.clientWidth;
		size.height = document.body.clientHeight;
	}
	return size;
}

// cross-browser method to get window scroll offsets
function getScrollOffset()
{
	var offset = new Object();
	offset.pageYOffset = document.documentElement.scrollTop;
	offset.pageXOffset = document.documentElement.scrollLeft;
	return offset;
}

// cross-browser method to get window scroll offsets
function getElementScrollOffset(element_id)
{
	var elem = document.getElementById(element_id);
	var offset = new Object();
	if ( typeof(elem.pageYOffset) == 'number')
	{
		offset.pageYOffset = elem.pageYOffset;
		offset.pageXOffset = elem.pageXOffset;
	} else {
		offset.pageYOffset = elem.scrollTop;
		offset.pageXOffset = elem.scrollLeft;
	}
	return offset;
}

function getMaximumScroll()
{
	var page_height = document.body.clientHeight;
	if (typeof( window.innerHeight ) == 'number')
		var window_height = window.innerHeight
	else if (document.documentElement && document.documentElement.clientHeight)
		var window_height = document.documentElement.clientHeight;
	if (page_height > window_height)
		return page_height - window_height;
	else
		return 0;
}

var fader = null;

function fadeIn(id, duration, opacity)
{
	if (!opacity)
		opacity = 0;
	if (!duration)
		duration = 250;

	console.log(opacity);				
	var node = document.getElementById(id);
	set_opacity(opacity, node);
	
	if (opacity < 100)
		fader = setTimeout('fadeIn("'+id+'", '+(duration - 5)+', '+(opacity+2)+')', 5);
	else
		clearTimeout(fader);
	
}

function fadeOut(id, duration, opacity)
{
	if (!opacity && opacity != 0)
		opacity = 100;
	if (!duration)
		duration = 250;

	console.log(opacity);				
	var node = document.getElementById(id);
	set_opacity(opacity, node);
	
	if (opacity > 0)
		fader = setTimeout('fadeOut("'+id+'", '+(duration - 5)+', '+(opacity-2)+')', 5);
	else
		clearTimeout(fader);
}

function set_opacity(opacity, object) 
{
    object.style.opacity = (opacity / 100);
    object.style.MozOpacity = (opacity / 100);
    object.style.KhtmlOpacity = (opacity / 100);
    object.style.filter = "alpha(opacity=" + opacity + ")";
}

dojo.addOnLoad(PView.init_markup);

