/*
PeriodicalExecuter.prototype.registerCallback = function() {
	this.intervalID = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
}

PeriodicalExecuter.prototype.stop = function() {
	clearInterval(this.intervalID);
}

Ajax.Responders.register({
 onCreate : addLoading,
 onComplete : removeLoading
});
*/


function URLencode(name) {
	name = name.replace(/<[^>]*>/g, "");
	var legal = "\"'+.,-=0123456789_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var result = [];	
	name = name.split(" ").join("_"); // convert spaces to underscore	
	for (var i = 0; i < name.length; i++) {
		var ch = name[i];
		if (legal.indexOf(ch) != -1) result.push(ch);
	}
	var ret = result.join("");
	
	ret = ret.replace(/\+/g, '%2B')
			.replace(/\"/g,'%22')
				.replace(/\=/g,'%3D')
					.replace(/\'/g, '%27');
	
	return ret;
}


function aURLencode(sStr) {
	sStr = sStr.replace(/<[^>]*>/g, "");
    return escape(sStr)
       .replace(/\+/g, '%2B')
          .replace(/\"/g,'%22')
             .replace(/\'/g, '%27')
				.replace(/\//g,'%2F');
}





$(".busy")
   .ajaxStart(function(){
		$(this).removeClass('nak');
		$(this).fadeIn(2000);
		addLoading();
   })
   .ajaxStop(function(){
       $(this).fadeOut(1500);
		removeLoading();
   });




var currentID;
currentID = "interesting";


function tmonth(m) {
	var months=['January','February','March','April','May','June','July','August','September','October','November','December']
	if(m < 1) { return; }
	return months[m-1];
}

function displayError (error) {
	$('div#photo_div').html('');
	$('span#link').addClass('nak');
	$('span#link').html('');
	displayInfo(error);
}
function getPhotos (page)
{
	page = (page=='user') ? 'username' : page;
	
	$('#msg').hide();
	$('#msg').html('');
	
	form = $('#request_form');	
	requestType = $('input#request_type').val();
	requestContent = $('input#request_content').val();
	
	if (page > 0 && page < 100000) {
		pagecontent = 'page/'+page+'/';
		pageRequest = '&page='+page;
	} else {
		page = 1;
		pagecontent = '';
		pageRequest = '';
	}
	
	if (!requestType) {
		requestType = 'interesting';
	}
	
	if (requestContent == '' || requestContent.length < 3) {
		displayInfo("I can't do anything without a proper input!...");
		return;
	}
	
	// compute link to this request..
	
	
	if (requestType == 'interesting' && requestContent == 'today' || requestContent == 'go') {
		var d=new Date();
		var translated_content = (d.getUTCDate()-1) + '-' + tmonth(d.getUTCMonth()+1) + '-' + d.getUTCFullYear();
	} else if (requestType == 'interestingweek' && requestContent == 'today' || requestContent == 'go') {
		var d=new Date();
		var translated_content = (d.getUTCDate()) + '-' + tmonth(d.getUTCMonth()+1) + '-' + d.getUTCFullYear();
	} else {
		translated_content = requestContent;
	}
	
	
	encoded = URLencode(translated_content);
	
	// check if something to display... and then display that!
	if (!(translated_content && translated_content.length > 0)) {
		displayError('Sorry, I need a proper input first!');
		return;
	}
	
	
	// only display link if we can display it! Otherwise just pretend everythings okay
	if (true || encoded == translated_content)
	{
		if (requestType == 'interesting' || requestType == 'interestingweek') {
			var literally_content = 'today';
			
			l = 'http://www.flickrgrab.com/'+requestType+'/today/'+pagecontent;
			t = 'http://www.flickrgrab.com/'+requestType+'/'+translated_content+'/'+pagecontent;
			$('span#link').html("<b>DAILY</b> link: <a href='"+l+"'>"+l+"</a> <br/> Current link: <a href='"+t+"'>"+t+"</a>");
		} else {
			t = 'http://www.flickrgrab.com/'+requestType+'/'+requestContent+'/'+pagecontent;
			$('span#link').html("Current URL: <a href='"+t+"'>"+t+"</a>");
		}
	}
	
	
	
	$("span#link").removeClass('nak');
	
	
	
	
	// Formadata holen
	var formdata = $('form#request_form').formSerialize();
	
	// Daten holen
	if (!(requestType == '' || translated_content == ''))
	{
		$("div#photo_div").load("/ajax_console.php",
			{
				'do': "PhotoRequest",
				mode: requestType,
				request_content: requestContent,
				page: page
			}			
		);
	} else {
		$('div#photo_div').html("<div class='msg-class'>I'm so sorry! Something weird just happened! If you entered a correct request but this message keeps showing up, please please <a href='mailto:mail@janoberst.com?subject=[FlickrGrabBug]'>drop me a note</a> about it!");
	}
}


function loadTab (tabname,init)
{
	tabname = (tabname=='user') ? 'username' : tabname;
	
	if (!init || $("span#link").html() == '') $("span#link").addClass('nak');
	
	currentID = tabname;
	topage = tabname;	
	setCookie('tabcookie',tabname);
	
	$('li.sel').removeClass('sel');
	$('#link_'+tabname).addClass('sel');
		
	switch (topage)
	{
		case "interesting":
			var desc = "Enter <b>keywords</b> like '<b><a href='/interesting/olympic games/'>olympic games</a></b>' or <b>dates</b> like <b><a href='/interesting/2008-01-01/'>01/01/2008</a></b>. Bookmark <b><a href='/interesting/today/'>Flickr Daily Explore</a></b>.";
			var input = "today";
			var help = "Date / Keyword";
		break;
		
		case "interestingweek":
			var desc = "The best pictures from the 7 days of 'Explore' before the date (<b>11/25/2006</b> or <b>25.11.2006</b>).";
			var input = "today";
			var help = "Date";
		break;
		
		
		case "favorites":
			var desc = "The <b>favorites</b> of a <b>user</b> like '<i><a href='/favorites/Caterina/'>Caterina</a></i>'. Also use User ID (<a href='http://flickr/username/32042779@N00/'>32042779@N00</a>) and Profile Links.";
			var help = "Username / ID / Link";
		break;
		
		case "username":
			var desc = "The pictures of a <b>user</b> like '<i><a href='/favorites/Caterina/'>Caterina</a></i>'. Also use User ID (<a href='http://flickr/username/32042779@N00/'>32042779@N00</a>) and Profile Links.";
			var help = "Username / ID / Link";
		break;
		
		case "userhits":
			var desc = "The best pictures of a <b>user</b> like '<i><a href='/favorites/Caterina/'>Caterina</a></i>'. Also use User ID (<a href='http://flickr/username/32042779@N00/'>32042779@N00</a>) and Profile Links.";
			var help = "Username / ID / Link";
		break;
		
		
		case "contacts":
			var desc = "Use a users name (like '<b><a href='/contacts/Caterina/'>Caterina</a></b>'), ID (like <b><a href='/contacts/32042779@N00/'>32042779@N00</a></b>) or link (<b>http://flickr.com/contacts/Caterina/</b> or just '<b><a href='/contacts/Caterina/'>Caterina</a></b>')";
			var help = "Username / ID / Link";
		break;
		
		case "photoset":
			var desc = "Enter the photoset's ID like <b><a href='/photoset/72157594510611238/'>72157594510611238</a></b> or even the whole link to it's Flickr page.";
			var help = "Set ID / Link to a Set";
		break;
		
		case "grouppool":
			var desc = "Enter the group's name (like '<b><a href='/grouppool/flickritis/'>flickritis</a></b>') or URL (like '<b>http://www.flickr.com/groups/flickritis/</b>')";
			var help = "Group URL / Link to a group";
		break;
		
		case "search":
			var desc = "Search for pictures. Newest pictures come first. See 'Interestingness' for ordered by interestingness.";
			var help = "Keywords, Tags";
		break;
		case "tags":
			var desc = "Enter a list of tags you want to display (like '<b><a href='/tags/sunset/'>sunset</a></b>'). Seperate by comma if you want to search for the combined tags (like '<b><a href='/tags/sunset,surfer/'>sunset,surfer</a></b>').";
			var help = "List of tags";
		break;
		default:
			return;
		break;
	}
	$('input#request_type').val(topage);
	
		
	if (help) {
		$('label#request_label').html(help);
	} else {
		$('label#request_label').html('Input');
	}
	if (desc) {
		$('label#fieldset_label').html(desc);
	} else {
		$('label#request_label').html('Get the corresponding photos');	
	}
	if (input) {
		$('input#request_content').val(input);		
	} else {
		$('input#request_content').val('');
	}
	  
}

function displayInfo (info)
{
	$('#process_div').html('<p class="warning">'+info+'</p>');
}
function addLoading ()
{
	displayInfo("loading...");
	//deactivate button
	$('#btn_'+currentID).disabled = "disabled";
	
	// Indicator anzeigen
	$('#ind_'+currentID).removeClass('nak');
	
	//Element.removeClassName	($('indicatorbar'),'nak');
	
	
}
function removeLoading ()
{
	$('#process_div').html("");
	$('#btn_'+currentID).disabled = "";
	
	$('#ind_'+currentID).addClass('nak');
	//Element.addClassName	($('indicatorbar'),'nak');
	
}





// Read last tab from Cookie, if existing load this right away...
function setCookie(name, value)
{
	//alert ("setting "+name+" to "+value);
	// sets an endless cookie
	var exp = new Date();
	exp.setTime(exp.getTime() + 365 * 24 * 60 * 60 * 5);
	var curCookie = name + "=" + escape(value) + ((exp) ? "; expires=" + exp.toGMTString() : "");
	self.focus();
	document.cookie = curCookie;
}

function getCookie(name)
{
	var dc = document.cookie;
	//alert("dc: "+dc);
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1)
	{
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} 
	else begin += 2;
		var end = document.cookie.indexOf(";", begin);
		if (end == -1) end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}



/*
		GET THE CURRENT COOKIE
*/
var lastTab = getCookie('tabcookie');




// if server says we have a real link, go to that tab
if (preset != '') {
	setCookie('tabcookie',preset);
	loadTab(preset,true);
	
// if we have a last tab in cookie go to that
} else if (lastTab != undefined && lastTab.length > 0) {
	loadTab(lastTab);

// else we don't have any presets, and go to interesting
} else {
	loadTab('interesting');
}


if (presetdata != '') { $('input#request_content').val(presetdata); }












hiddenpics = new Array();
shownpics = new Array();




// ONLOAD
if (getCookie('livebox') == 'on')
{
	var liveboxes = 1;
	checkliveboxes();
} else {
	var liveboxes = 0;
}

if (getCookie('popups') == 'off') {
	var popups = 0;
	checkpopup(false);
} else if (getCookie('popups') == 'on') {
	var popups = 1;
	checkpopup(true);
} else {
	if (navigator.userAgent.toLowerCase().indexOf('safari') != -1) {
		var popups = 0;
		checkpopup(false);	
	} else {
		var popups = 1;
		checkpopup(true);
	}
}


function checkpopup(state) {
	$("input.popup").each(function()
		{
			this.checked = state;
		});
}
function setpopup()
{
	box = $("input.popup")[0];
	if (!box) { return; }
	// Alle liveboxes nach der aktuellen setzen
	if (box.checked)
	{
		popups = 1;
		setCookie('popups','on');
	} else {
		popups = 0;
		setCookie('popups','off');
	}
}



function checkliveboxes()
{
	liveboxes = 1;
	setwrapper();
	$("input.livebox").each(function()
		{
			this.checked = true;
		});
}
function uncheckliveboxes()
{
	liveboxes = 0;
	unsetwrapper();
	$("input.livebox").each(function()
		{
			this.checked = false;
		});
}


function setlivebox(box)
{
	// Alle liveboxes nach der aktuellen setzen
	if (box.checked)
	{
		setCookie('livebox','on');
		checkliveboxes();
	} else {
		setCookie('livebox','off');	
		uncheckliveboxes();	
	}
}




function setwrapper()
{
	// wenn fenster kleiner ist als globalwrap
		var de = document.documentElement;
		var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
		var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	
		
		// photo-div muss immer nur 75+1+1 halten, also mod 77
		new_width = parseInt((w-272) / 77) * 77;
		
		$('#photo_div').width(new_width+"px");
		
		$('#wrapper').show();
}
function unsetwrapper()
{
		$('#photo_div').width("100%");		
		$('#wrapper').hide();
}































function loadnewwindow (link)
{
	if (true || popups == 1) {
		if (!window.open(link)) {
			alert("Grr! A popup blocker may be preventing Flickr Grab from opening the link to Flickr. If you have a popup blocker, try disabling it to open the window.");
		}
		return false;
	} else {
		return true;
	}
}

function loadoverhead(pid,link,src)
{
	if (shownpics[pid] != 1)
	{
		setwrapper();
		html  = '<div style="display:none;" id="box_'+pid+'" class="flickrbox">';
		html += '<a onclick="loadnewwindow(this);return false;" href="'+link+'" title="see photo"><img src="'+src+'"></a>';
		
		/*
		html += '<p>';
		html += '<a href="http://flickr.com/photos/'+userid+'/'+pid+'/" title="see photo"><img src="/flickr-visit.gif"></a>';
		html += '<a href="" title="fav this picture"><img src="/flickr-add.gif"></a>';
		html += '<a href="http://flickr.com/people/'+userid+'" title="user\'s profile"><img src="/flickr-user.gif"></a>';
		html += '</p>';
		*/
		html += '</div>';
		$('#wrapper').prepend(html);
		$('#box_'+pid).fadeIn(200);
	} else {
		if (hiddenpics[pid] == 1)
		{
			$('#box_'+pid).fadeIn(200);
			hiddenpics[pid] = 0;
		} else {
			$('#box_'+pid).fadeOut(200);
			hiddenpics[pid] = 1;
		}
	}
	shownpics[pid] = 1;
}
function applyLinks() {
	$("#photo_div a").filter(function(index){return $("img", this).length != 0;}).click(function(evt) {
		
		if (liveboxes == 1) {
			evt.preventDefault();
			evt.stopPropagation();
			//console.log("liveboxes on");
			pid = this.href.split('/').pop();
			//console.log("pid: "+pid);
			link = this.href;
			//console.log("link: "+link);
			images = $('img',this);
			if (images.length < 1) {
				// error. this shouldn't have happened
			}
			src = $('img',this)[0].src.replace('_s.jpg','_m.jpg');
			//console.log("src: "+src);
			loadoverhead(pid,link,src);
		} else {
			//console.log("liveboxes off");
			if (popups == 0) {
				return true;
			} else {
				evt.preventDefault();
				evt.stopPropagation();
				window.open(this.href);
				return false;
			}
		}
		return false;
	});
}






















/* JQuery real position plugin
	 * Methods:
	 * 		$.visibleLeft(): returns the distance between the left window edge and current element
	 * 		$.visibleTop(): returns the distance between the top window edge and current element

	 */

$.userTop=function (o) {
	if (!o||!o.offsetParent) {
		return 0;		
	} else {
		var top=o.offsetTop;
		do {
			o=o.offsetParent;
			top+=o.offsetTop;
		} while (o.offsetParent);
	}
	return top;
}
$.userLeft=function(o) {
	
	if (!o||!o.offsetParent) {
		return 0;		
	} else {
		var left=o.offsetLeft;
		do {
			o=o.offsetParent;
			top+=o.offsetLeft;
		} while (o.offsetParent);
	}
	return left;
}
$.fn.visibleTop = function() {
	//multiple elements not anticipated, returns minimum
	var current=-1;
   	this.each(function(){
		//if current isnt defined, then assign it user left
		//or if left is less than left so far
    	current=(current==-1||$.userTop(this)<current)?$.userTop(this):current;
  });
  	return current;
}
$.fn.visibleLeft = function() {
	/*Visible left does not work correctly
	 * 
	 * 
	 */

	//multiple elements not anticipated, returns minimum
	var current=-1;
   	this.each(function(){
		//if current isnt defined, then assign it user left
		//or if left is less than left so far
    	current=(current==-1||$.userLeft(this)<current)?$.userLeft(this):current;
  });
  	return current;
};







jQuery.fn.formToArray = function(semantic) {
    var a = [];
    var q = semantic ? ':input' : 'input,textarea,select,button';

    jQuery(q, this).each(function() {
        var n = this.name;
        var t = this.type;

        if ( !n || this.disabled || t == 'reset' ||
            (t == 'checkbox' || t == 'radio') && !this.checked ||
            (t == 'submit' || t == 'image' || t == 'button') && this.form && this.form.clk != this ||
            this.tagName.toLowerCase() == 'select' && this.selectedIndex == -1)
            return;

        if (t == 'image' && this.form.clk_x != undefined)
            return a.push(
                {name: n+'_x', value: this.form.clk_x},
                {name: n+'_y', value: this.form.clk_y}
            );

        if (t == 'select-multiple') {
            for(var i=0; i < this.options.length; i++)
                if (this.options[i].selected)
                    a.push({name: n, value: this.options[i].value});
            return;
        }
        a.push({name: n, value: this.value});
    });
    return a;
};
jQuery.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return jQuery.param(this.formToArray(semantic));
};
