/* json */
(function(){var m={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r","\"":"\\\"","\\":"\\\\"},s={array:function(x){var a=["["],b,f,i,l=x.length,v;for(i=0;i<l;i+=1){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=="string"){if(b){a[a.length]=",";}a[a.length]=v;b=true;}}}a[a.length]="]";return a.join("");},"boolean":function(x){return String(x);},"null":function(x){return "null";},number:function(x){return isFinite(x)?String(x):"null";},object:function(x){if(x){if(x instanceof Array){return s.array(x);}var a=["{"],b,f,i,v;for(i in x){v=x[i];f=s[typeof v];if(f){v=f(v);if(typeof v=="string"){if(b){a[a.length]=",";}a.push(s.string(i),":",v);b=true;}}}a[a.length]="}";return a.join("");}return "null";},string:function(x){if(/["\\\x00-\x1f]/.test(x)){x=x.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=m[b];if(c){return c;}c=b.charCodeAt();return "\\u00"+Math.floor(c/16).toString(16)+(c%16).toString(16);});}return "\""+x+"\"";}};Object.prototype.toJSONString=function(){return s.object(this);};Array.prototype.toJSONString=function(){return s.array(this);};})();String.prototype.parseJSON=function(){try{return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(this.replace(/"(\\.|[^"\\])*"/g,"")))&&eval("("+this+")");}catch(e){return false;}};

/* xhconn */
function XHConn(){var _1,_2=false;try{_1=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{_1=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){try{_1=new XMLHttpRequest();}catch(e){_1=false;}}}if(!_1){return null;}this.connect=function(_3,_4,_5,_6){if(!_1){return false;}_2=false;_4=_4.toUpperCase();try{if(_4=="GET"){_1.open(_4,_3+"?"+_5,true);_5="";}else{_1.open(_4,_3,true);_1.setRequestHeader("Method","POST "+_3+" HTTP/1.1");_1.setRequestHeader("Content-Type","application/x-www-form-urlencoded");}_1.onreadystatechange=function(){if(_1.readyState==4&&!_2){_2=true;if(_6!=null){_6(_1);}}};_1.send(_5);}catch(z){return false;}return true;};return this;}

function elm(id)
{
	return document.getElementById(id);
}

function hide(id)
{
	e = elm(id);
	if (e)
	{
		f = new Fadomatic(e);
		f.hide();
	}
}

function show(id)
{
	e = elm(id);
	if (e)
	{
		f = new Fadomatic(e);
		f.show();
	}
}

function showError(text)
{
	e = document.getElementById("loader");
	e.innerHTML = "<center><font style='font-size: 12;'>" + text + "</font></center>";
	show("loader");
}

function showLoader(text)
{
	e = document.getElementById("loader");
	e.innerHTML = "<center><table><tr valign='middle'><td><img src='/images/loader.gif' alt=''></td><td>" + text + "</td></tr></table></center>";
	show("loader");
}

function trim(str)
{
	return str.replace(/^\s*|\s*$/g,"");
}

function show_preview(filename)
{
	url = "http://www.dumpr.net/" + filename;
	window.open(url, "Preview", 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=500,height=500');
}

/*
function imageCreatedStateChange(http_request, url)
{
	if (http_request.readyState == 4)
	{
		hide("loader");
		document.location = url;
	}
}

function popRasterizer(ticket)
{
	document.location = "#top";
	showLoader("Creating image, please wait..");

	url = "rasterizr.php?ticketid=" + ticket;

	request = createRequestObject();
	if (request)
	{
		request.onreadystatechange = function() { imageCreatedStateChange(request, url); };
		request.open('GET', url, true);
		request.send(null);
	}
}

function popRasterizerUpload(ticket)
{
	document.location = "#top";
	showLoader("Creating image for upload, please wait..");

	url = "uploadr.php?ticketid=" + ticket;

	request = createRequestObject();
	if (request)
	{
		request.onreadystatechange = function() { imageCreatedStateChange(request, url); };
		request.open('GET', url, true);
		request.send(null);
	}
}
*/

function pleaseWait(message)
{
	var d = elm("pleasewait_div");
	var v = "";

	v = v + '<table style="width: 522; font-size: 10; background-color: #fff; margin: 8px; padding: 8px;" cellpadding=0 cellspacing=0 border=0>';
	v = v + '<tr style="height: 66">';
	v = v + '<td valign="middle" align="center">';

	v = v + message;

	v = v + '</td>';
	v = v + '</tr>';
	v = v + '</table>';

	d.innerHTML = v;
	d.style.visibility = "visible";
}

function pleaseWaitProcessing()
{
	pleaseWait('Please wait while <i>dumpr</i> is processing..<br><img src="/images/progress_bar2.gif" alt="">');
}

function pleaseWaitUploading()
{
	pleaseWait('Please wait while <i>dumpr</i> is uploading..<br><img src="/images/progress_bar2.gif" alt="">');
}

function hidePleaseWait()
{
	elm("pleasewait_div").style.visibility = "hidden";
}

function getPageSize() 
{
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function showModalMessage(text)
{
	var w = 256;
	var h = 80;

	var v = "";
	v = v + '<table cellpadding=0 border=0 cellspacing=0 style="width:'+w+';">';
	v = v + '<tr style="height: 3px;">';
	v = v + '<td style="width: 3px;"><img src="/images/tc_yellow_tl.gif"></td>';
	v = v + '<td style="background-color:#ffcc00;"></td>';
	v = v + '<td style="width: 3px;"><img src="/images/tc_yellow_tr.gif"></td>';
	v = v + '</tr>';
	v = v + '<tr style="height: 3px;">';
	v = v + '<td style="background-color:#ffcc00;"></td>';
	v = v + '<td valign="middle" style="background-color:#ffcc00; color: #33f; padding-left: 8px; padding-right: 8px;">' + text + '</td>';
	v = v + '<td style="background-color:#ffcc00;"></td>';
	v = v + '</tr>';
	v = v + '<tr style="height: 3px;">';
	v = v + '<td style="width: 3px;"><img src="/images/tc_yellow_bl.gif"></td>';
	v = v + '<td style="background-color:#ffcc00;"></td>';
	v = v + '<td style="width: 3px;"><img src="/images/tc_yellow_br.gif"></td>';
	v = v + '</tr>';
	v = v + '</table>';

	var newdiv = document.createElement('div');
	newdiv.setAttribute("id", "modalMessageDiv");
	newdiv.style.display = "none";
	newdiv.innerHTML = v;

	var size = getPageSize(); 
	var top = size[3] / 2;
	var left = (size[2] - w) / 2;

	newdiv.setAttribute("style", "position: absolute; top: " + top + "px; left: " + left + "px; display: block;");
	elm('modalMessageParentDiv').appendChild(newdiv);
}

function hideModalMessage(text)
{
	var div = elm('modalMessageDiv');
	elm('modalMessageParentDiv').removeChild(div);
}

function selectFavorite(photoid)
{
	new Effect.Pulsate(elm('divthumb' + photoid)); 
	document.location = '?photoid=' + photoid;
} 

function findFavoritesDone(xh)
{
	result = xh.parseJSON();

	var status = result.status;
	if (status == "ok")
	{
		var v = "";
		v = v + "<div align='center'>";
		v = v + '<table style="width: 450px;" border=0 cellpadding=0 cellspacing=2>';

		for (i=0; i<result.items.length; i++)
		{
			if (i % 8 == 0)
			{
				if (i > 0)
				{
					v += "<"+"/tr>";
				}
			
				v += '<tr style="height: 75px;">';
			}
	
			var thumbnail = result.items[i].img;
			var alt = result.items[i].alt;
			var photoid = result.items[i].id;

			v += "<td style=\"width: 75px;\"><a href=\"?photoid=" + photoid + "\" onclick=\"selectFavorite('" +  photoid + "'); return false;\"><span id='divthumb" + photoid + "'><img src='" + thumbnail + "' width=75 height=75 border=0 alt='"+alt+"' title='"+alt+"'><"+"/span><"+"/a><"+"/td>";
		}

		if (i > 0)
		{
			while (i % 8 > 0)
			{
				v += "<td style='width: 75px;'>&nbsp;<"+"/td>";
				i++;
			}

			v += "<"+"/tr>";
		}

		v += "<"+"/table>";
		v += "<"+"/div>";

		elm("results").innerHTML = v;
		show("results");

		fader = new Fadomatic(elm("loader"), 10, 100);
		fader.fadeOut();
	}
	else if (status == "fail")
	{
		if (result.error == "user has no favorites")
		{
			showError("User has no favorites, please try a different user");
		}
		else
		{
			showError("Server error, please try again later");
		}
	}
}

function selectDifferentUser()
{
	elm("username").value = "";
	hide("loader");
	hide("userinformation");
	hide("results");
	elm("results").innerHTML = "";
	show("userform");
}

function phase2()
{
	showLoader("Loading user profile");

	username = elm("username").value;
	if (trim(username) == "")
	{
		showError("Please fill the user name below");
		return;
	}

	var xhConn = new XHConn();
	xhConn.connect('dumpr.finduser.php', "GET", "username=" + username,
		function(xh)
		{
			var response = xh.responseText.parseJSON();

			if (response.status == "ok")
			{
				icon = response.icon;
				userid = response.userid;
				username = response.username;
				realname = response.realname;

				if (realname.length == 0)
				{
					realname = username;
				}
	
				v = "<table style=\"width: 598px;\" border=0><tr valign=\"middle\"><td style=\"width: 48px;\"><img src=\"" + icon + "\" alt=\"you!\" width=48 height=48><"+"/td><td align=\"left\">" + realname + "<small>'s favorites</"+"small><br>";
				v = v + "<span id=\"switch_user_button\"><a href=\"#\" onclick=\"javascript: selectDifferentUser(); return false;\"><small>Switch User</"+"small><"+"/a><"+"/span><"+"/td><"+"/tr>";
				v = v + "<"+"/table>";
				elm("userinformation").innerHTML = v;

				if (elm("userform").style.visibility != "hidden")
				{
					f1 = new Fadomatic(elm("userform"), 5, 100);
					f1.fadeOut();
				}

				f2 = new Fadomatic(elm("userinformation"), 5, 0);
				f2.fadeIn();

				showLoader("Looking for favorites..");

				var xhConn2 = new XHConn();
				xhConn2.connect('dumpr.findfavorites.php', "GET", "userid=" + userid + "&username=" + username + "&callback=selectFavorite",
					function(xh2)
					{
						findFavoritesDone(xh2.responseText);
					}
				);
			}
			else
			{
				if (response.error == "user not found")
				{
					showError("User not found, please try again");
					elm("username").value = "";
				}
				else
				{
					showError("Server error, please try again later");
				}
			}
		}
	);
}

var addsInProgress = 0;
function addFave(id)
{
	if (addsInProgress >= 3)
	{
		return;
	}

	var e = elm('favimg' + id);

	var args = "id=" + id;
	var adding = true;
	var textMessage = "Adding to favorites";

	addsInProgress++;
	if (addsInProgress == 1)
	{
		showModalMessage("<div align='center'>" + textMessage + "&nbsp;&nbsp;&nbsp;<img src='/images/yellowprogress.gif' alt=''><" + "/div>");
	}

	var xhConn = new XHConn();
	xhConn.connect("/dumpr.addfave.php", "GET", args,
		function(xh) {
			addsInProgress--;
			if (addsInProgress == 0)
			{
				hideModalMessage();
			}
		}
	);

	new Effect.Puff(elm('favimg' + id)); 
}

function safe_string(s)
{
	var p = s.replace(/'/g, '&apos;');
	p = p.replace(/"/g, '&quot;');
	p = p.replace(/<{1}/g, '&lt;');
	p = p.replace(/>/g, '&gt;');
	return p;
}

var similrResult = null;

function createResultTable(t)
{
	if (t.nresults == 0) {
		$('top_right').innerHTML = 'Unfortunately, no other people favored this image. Please try another image';
		return;
	}

	// update status
	var desc = safe_string(t.original_photo_description);
	var v = '<a href="' + t.original_photo_link + '"><img src="' + t.original_photo_thumbnail + '" border=0 width=75 height=75 alt="' + desc +'"><'+'/a>';
	$('top_left').innerHTML = v;

	// show favorites table below
	var v0 = '<table border=0 cellpadding=4 cellspacing=1>';
	var v = v0;
		var v1;

	for (var i=0; i<t.data.length; i++) {
		if (i % 8 == 0) {
			if (i > 0) {	
				v += '<'+'/tr>';
			}

			if (i == 8) {
				v1 = v + '<'+'/table>';
				v = v0;
			}

			v += '<tr>';
		}	

		v += '<td width="92" align="left">';
		
		var _id = t.data[i].id;
		var _href = t.data[i].href;
		var _img = t.data[i].img;
		var _alt = safe_string(t.data[i].alt);
		v += '<img src="/images/addfave.gif" alt="Add to favorites" title="Add to favorites" id="favimg' + _id + '" style="z-index: 2; position: absolute; cursor: pointer;" onclick="addFave(' + _id + ');">';
		v += '<a href="' + _href + '"><img style="border: 1px solid #888;" src="' + _img + '" alt="' + _alt + '" title="' + _alt + '" height=75 width=75><'+'/a>';
		v += '<'+'/td>';
	}

	v += '<'+'/tr><'+'/table>';
	$('result_table_1').innerHTML = v1;
	$('result_table_2').innerHTML = v;
	$('top_right').innerHTML = 'People who favored this photo, also favored the photos shown below.';
}

function similrProcess(photoid)
{
	var xhConn = new XHConn();
	xhConn.connect('dumpr.findsimilr.php', "GET", "photoid=" + photoid,
		function(xh)
		{
			var response = xh.responseText.parseJSON();
			if (response.status == "ok")
			{
				createResultTable(response.ticket);
				similrResult = response.ticket;
				$('processing').style.display = "none";
				$('result').style.display = "block";
			}
		}
	);
}

function closeModal() {
	if (Windows.windows.length == 1) {
		// no more windows open
		$("overlay").style.visibility = "hidden";
	}
}

function enableOverlay() {
	var sizes = getPageSize();
	$("overlay").style.width = sizes[0] + "px";
	$("overlay").style.height = sizes[1] + "px";
	$("overlay").style.visibility = "visible";
}

function createSimilrCollage()
{
	var ids = '';
	for (var i=0; i<similrResult.data.length; i++) {
		if (ids != '') {
			ids += ',';
		}

		ids += similrResult.data[i].id;
	}

	enableOverlay();
	var win = createUploadWindow();

	// create collage remotely
	var xhConn = new XHConn();
	xhConn.connect('dumpr.similr.collage.php', "GET", "photoids=" + ids,
		function(xh)
		{
			var response = xh.responseText.parseJSON();
			if (response.status == "ok")
			{
				var path = response.result;
				$('UploadWindowPreviewImg').src = "/dumpr.upload.preview.php?fn=" + path;
				$('UploadWindowProgressPreviewImg').src = "/dumpr.upload.preview.php?fn=" + path;
				$('uploadr_fn').value = path;
			}
		}
	);

	win.showCenter();
	
	//alert(ids);
}

// Fade interval in milliseconds
// Make this larger if you experience performance issues
Fadomatic.INTERVAL_MILLIS = 50;

// Creates a fader
// element - The element to fade
// speed - The speed to fade at, from 0.0 to 100.0
// initialOpacity (optional, default 100) - element's starting opacity, 0 to 100
// minOpacity (optional, default 0) - element's minimum opacity, 0 to 100
// maxOpacity (optional, default 0) - element's minimum opacity, 0 to 100
function Fadomatic (element, rate, initialOpacity, minOpacity, maxOpacity) {
  this._element = element;
  this._intervalId = null;
  this._rate = rate;
  this._isFadeOut = true;

  // Set initial opacity and bounds
  // NB use 99 instead of 100 to avoid flicker at start of fade
  this._minOpacity = 0;
  this._maxOpacity = 99;
  this._opacity = 99;

  if (typeof minOpacity != 'undefined') {
    if (minOpacity < 0) {
      this._minOpacity = 0;
    } else if (minOpacity > 99) {
      this._minOpacity = 99;
    } else {
      this._minOpacity = minOpacity;
    }
  }

  if (typeof maxOpacity != 'undefined') {
    if (maxOpacity < 0) {
      this._maxOpacity = 0;
    } else if (maxOpacity > 99) {
      this._maxOpacity = 99;
    } else {
      this._maxOpacity = maxOpacity;
    }

    if (this._maxOpacity < this._minOpacity) {
      this._maxOpacity = this._minOpacity;
    }
  }
  
  if (typeof initialOpacity != 'undefined') {
    if (initialOpacity > this._maxOpacity) {
      this._opacity = this._maxOpacity;
    } else if (initialOpacity < this._minOpacity) {
      this._opacity = this._minOpacity;
    } else {
      this._opacity = initialOpacity;
    }
  }

  // See if we're using W3C opacity, MSIE filter, or just
  // toggling visiblity
  if(typeof element.style.opacity != 'undefined') {

    this._updateOpacity = this._updateOpacityW3c;

  } else if(typeof element.style.filter != 'undefined') {

    // If there's not an alpha filter on the element already,
    // add one
    if (element.style.filter.indexOf("alpha") == -1) {

      // Attempt to preserve existing filters
      var existingFilters="";
      if (element.style.filter) {
        existingFilters = element.style.filter+" ";
      }
      element.style.filter = existingFilters+"alpha(opacity="+this._opacity+")";
    }

    this._updateOpacity = this._updateOpacityMSIE;
    
  } else {

    this._updateOpacity = this._updateVisibility;
  }

  this._updateOpacity();
}

// Initiates a fade out
Fadomatic.prototype.fadeOut = function () {
  this._isFadeOut = true;
  this._beginFade();
}

// Initiates a fade in
Fadomatic.prototype.fadeIn = function () {
  this._isFadeOut = false;
  this._beginFade();
}

// Makes the element completely opaque, stops any fade in progress
Fadomatic.prototype.show = function () {
  this.haltFade();
  this._opacity = this._maxOpacity;
  this._updateOpacity();
}

// Makes the element completely transparent, stops any fade in progress
Fadomatic.prototype.hide = function () {
  this.haltFade();
  this._opacity = 0;
  this._updateOpacity();
}

// Halts any fade in progress
Fadomatic.prototype.haltFade = function () {

  clearInterval(this._intervalId);
}

// Resumes a fade where it was halted
Fadomatic.prototype.resumeFade = function () {

  this._beginFade();
}

// Pseudo-private members

Fadomatic.prototype._beginFade = function () {

  this.haltFade();
  var objref = this;
  this._intervalId = setInterval(function() { objref._tickFade(); },Fadomatic.INTERVAL_MILLIS);
}

Fadomatic.prototype._tickFade = function () {

  if (this._isFadeOut) {
    this._opacity -= this._rate;
    if (this._opacity < this._minOpacity) {
      this._opacity = this._minOpacity;
      this.haltFade();
    }
  } else {
    this._opacity += this._rate;
    if (this._opacity > this._maxOpacity ) {
      this._opacity = this._maxOpacity;
      this.haltFade();
    }
  }

  this._updateOpacity();
}

Fadomatic.prototype._updateVisibility = function () {
  
  if (this._opacity > 0) {
    this._element.style.visibility = 'visible';
  } else {
    this._element.style.visibility = 'hidden';
  }
}

Fadomatic.prototype._updateOpacityW3c = function () {
  
  this._element.style.opacity = this._opacity/100;
  this._updateVisibility();
}

Fadomatic.prototype._updateOpacityMSIE = function () {
  
  this._element.filters.alpha.opacity = this._opacity;
  this._updateVisibility();
}

Fadomatic.prototype._updateOpacity = null;

