/* FavouritePhotographers, v2.0.1
 * Copyright (c) 2007 Patrick Quinn-Graham
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

fp = new Class({
	options: {
		xml: '/flickrtools/xmlproxy', 
		table: 'favs', 
		skeleton: 'favs-s', 
		sticky: ['favs-h'], 
		searchButton: 'theSearch', 
		searchInput: 'theUserName',
		everything: 'contains-everything',
		statusDiv: 'status'
	},
	initialize: function(options) {		
		Object.extend(this.options, options || {});
		this.mypdt = new PDTable(this.options);
		this.mypdt.clear();
		$(this.options.searchButton).addEvent('click', this.run.bind(this));
		$(this.options.searchInput).addEvent('keypress', this.searchKey.bind(this));
		this.setStatus("Initialisation complete. Please begin your search.");
		$(this.options.everything).style.display = 'block';
	},
	searchKey: function(e, box) {
		if(e.keyCode != 13) return false;
		this.run();		
	},
	run: function(){
		// get the users NSID
		this.mypdt.clear();
		firstURL = this.options.xml + "?method=findUser&username=" + escape($(this.options.searchInput).value);
		new Ajax(firstURL, {method: 'get', onComplete: this.gotNSID.bind(this) }).request();
		this.setStatus("Finding user " + $(this.options.searchInput).value + " ...");
	},
	setStatus: function(message) {
		$(this.options.statusDiv).firstChild.nodeValue = message;
	},
	gotNSID: function(t, r) {
		x = r.documentElement;
		if(x.attributes.getNamedItem("stat").value != "ok") {
			j = x.getElementsByTagName("err")[0];
			if(!j) {
				alert("An error occurred. Bugger.");
				return;				
			}
			m = j.attributes.getNamedItem("msg").value;
			this.setStatus(m);			
		}
		this.nsid = x.getElementsByTagName('user')[0].attributes.getNamedItem("id").value;
		this.setStatus("Got user " + this.nsid + ". Handoff to getPage");
		this.currentPage = 0;
		this.pages = 1;
		this.userDetails = {}		
		this.getPage();
	}, 
	getPage: function() {
		this.currentPage++;
		if(this.currentPage > this.pages) {
			return; // we're done... probably should do something else.
		}
		this.setStatus("Getting page " + this.currentPage + " of " + this.pages);
		this.perPage = 500; // should set to 500 to minimize round trips. or..?
		getPageURL = this.options.xml + "?method=getFavorites&user_id=" + this.nsid;
		getPageURL = getPageURL + "&extras=owner_name,icon_server&per_page=" + this.perPage;
		getPageURL = getPageURL + "&page=" + this.currentPage;
		new Ajax(getPageURL, {method: 'get', onComplete: this.gotPage.bind(this) }).request();
	},
	iconUrl: function(owner, iconserver, iconfarm) {
		if(iconserver == 0) {
			return "http://www.flickr.com/images/buddyicon.jpg"
		}
		return 'http://farm' + iconfarm + '.static.flickr.com/' + iconserver + '/buddyicons/' + owner + '.jpg';
	},
	imageUrl: function(farm, server, id, secret, size) {
		if(size) size = "_" + size;
		return 'http://farm' + farm + '.static.flickr.com/' + server + '/' + id + '_' + secret + size + '.jpg';
	},
	gotPage: function(t, r) {
		x = r.documentElement;
		if(x.attributes.getNamedItem("stat").value != "ok") {
			this.setStatus("Error fetching page.");
			return;
		}
		photos = x.getElementsByTagName("photos")[0];
		this.pages = photos.attributes.getNamedItem("pages").value;
		if(this.pages == 0) {
			this.setStatus("User has no favourites.");
			return;
		}
		this.setStatus("There are " + this.pages + " pages to process.");
		photos = x.getElementsByTagName("photo");
		i = 0;
		$A(photos).each(function(a){
			owner = a.attributes.getNamedItem("owner").value;
			if(!this.userDetails[owner]) {
				id = a.attributes.getNamedItem("id").value;				
				ownername = a.attributes.getNamedItem("ownername").value;
				secret = a.attributes.getNamedItem("secret").value;
				server = a.attributes.getNamedItem("server").value;
				iconserver = a.attributes.getNamedItem("iconserver").value;
				iconfarm = a.attributes.getNamedItem("iconfarm").value;
				farm = a.attributes.getNamedItem("farm").value;
				title = a.attributes.getNamedItem("title").value;
				
				this.userDetails[owner] = {
					photoCount: 1,
					name: ownername,
					nsid: owner,
					icon: this.iconUrl(owner, iconserver, iconfarm),
					small: this.imageUrl(farm, server, id, secret, 's'),
					medium: this.imageUrl(farm, server, id, secret),
					photoPage: 'http://www.flickr.com/photos/' + owner + '/' + id + '/',
					imgtitle: title
				}
			} else {
				this.userDetails[owner].photoCount++;
			}
		}.bind(this));
		
		// are we done?
		if(this.currentPage == this.pages) {
			this.setStatus("Reached page count, no more.");
			this.doneLoading();
		} else {
			this.setStatus("Should do another page...");
			this.getPage();
		}
	},
	doneLoading: function() {
		magic = new Array();
		for(x in this.userDetails) {
			magic[magic.length] = { nsid: x, num: this.userDetails[x].photoCount }
		}
		magic.sort(function(a, b) { return b.num - a.num; });
		
		magic.each(function(a, i){
			if(i > 20) { return; }
			myOwner = a.nsid;
			this.userDetails[myOwner].photocount = a.num;
			myOwnersIcon = this.userDetails[myOwner].icon;
			mySmallImage = this.userDetails[myOwner].small;
			myPhotoPage = this.userDetails[myOwner].photoPage;
			
			this.mypdt.addRow({ id: 'fav-' + i, values: this.userDetails[myOwner], callback: function(r) { 
				$A(r.getElementsByTagName('a')).each(function(link, linkContainer) {
					if(linkContainer == 0) {
						link.href = 'http://www.flickr.com/photos/' + myOwner + '/';				
					}
					if(linkContainer == 1) {
						link.href = myPhotoPage;					
					}
				});
				$A(r.getElementsByTagName('img')).each(function(img,imgCounter) {
					if(imgCounter == 0) {
						img.src = myOwnersIcon;						
					}
					if(imgCounter == 1) {
						img.src = mySmallImage;						
					}
				});
			}});
		}.bind(this));
		
		this.setStatus("Done, thanks for visiting.");
	}
});
