//var favesList = new Array();
//var testList = new Array();
//var otherList = new Array();

var z = 0;

var margin = 10;
var trayWidth = 200 + margin;
var boxHeight = 200 + 20;
var thumbHeight = thumbWidth = 100;
var showNumber = 4;
var leftMargin = trayWidth + margin;
var topMargin  = 160;

//var code = "";
var user = new Array();

var HTTP = new Array();
HTTP._factories = [
                function() { return new XMLHttpRequest(); },
                function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
                function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
                ];
                
HTTP._factory = null;

HTTP.newRequest = function() {
if(HTTP._factory != null) return HTTP._factory();

for(var i = 0; i < HTTP._factories.length; i++) {
        try {
            var factory = HTTP._factories[i];
            var request = factory();
            if(request != null) {
                   HTTP._factory = factory;
                   return request;
            }
        }
        catch(e) {
                 continue;
        }
}

HTTP._factory = new function() {
              throw new Error("XMLHttpRequest not supported.");
}
HTTP._factory();
}

function id(x) {
	if(typeof x == "string") return document.getElementById(x);
	else return x;
}

function dropdown(element) {
id('feedback').style.display = 'none';
id('todo').style.display = 'none';
id('reglogbox').style.display = 'none';

id(element).style.display = 'inline';
//$('feedback').slideUp();
//$('todo').slideUp();
//$(element).slideDown("slow");
}

function addFave(element) {
  var xmlHttp = HTTP.newRequest();

    xmlHttp.onreadystatechange=function() {
    	if(xmlHttp.readyState==4) {//element.innerHTML=xmlHttp.responseText;
			element.setAttribute("favedby", Number(element.getAttribute("favedby")) + 1);
      	}
    }
    xmlHttp.open("GET","fave.php?op=add&c="+getCode()+"&pid="+element.id,true);
    xmlHttp.send(null);
  }
  
  function removeFave(element) {
  var xmlHttp = HTTP.newRequest();
    xmlHttp.onreadystatechange=function() {
      if(xmlHttp.readyState==4) {//}element.innerHTML=xmlHttp.responseText;
      //doCaption(element);
	  //debug("de-faved ");
	  	element.setAttribute("favedby", Number(element.getAttribute("favedby")) - 1);
    	}
	}
    xmlHttp.open("GET","fave.php?op=remove&c="+getCode()+"&pid="+element.id,true);
    xmlHttp.send(null);
  }
 
  function addCaption(element) {
  // create caption and add to document and preview
 
  if(element.childNodes.length == 1) {
	 var caption = document.createElement("div");
  	 //element.appendChild(document.createElement("br"));
  	 caption.setAttribute("class", "caption");
	 caption.className = "caption";
  	 element.appendChild(caption);
  }
  else caption = element.lastChild;

  var date = element.getAttribute('uploaddate');
 /*
  		    var year = date.substring(0, 4);
  		    var month = date.substring(5, 7);
  		    var day = date.substring(8, 9);
  		    var hour = date.substring(10, 11);
  		    var min = date.substring(12, 13);
  		    var sec = date.substring(14, 15);
  		    var ms = date.substring(16, 17);
  		    date = new Date(year, month, day, hour, min, sec, ms);
  	
  	*/	    
  		   var text = element.getAttribute('favedby') + " fave";
		   if(element.getAttribute('favedby') != '1') text += "s";
  		//   text += "<br />" + date.getHours() +":"+date.getMinutes() + " " 
			//   + date.getDate() + "/" + date.getMonth() + "/" + date.getFullYear() 
			   text += "<br />" + date
			   + "<br />by breeder #" + element.getAttribute('uploader');
			   
  caption.innerHTML = text;
  
  $(caption).fadeTo("slow", 0.7);
  
  element.style.zIndex = (z++);
  //debug("z="+element.firstChild.style.zIndex);
  
  // sneaky late loading of bigger image
  element.style.width = "200px";
  element.style.height = "200px";
  element.firstChild.width = "200";// blow up thumb first
  element.firstChild.height = "200";
  element.firstChild.src = "http://imagebreeder.com/previews/p"+element.getAttribute("image");
  caption.setAttribute("onmouseover", "debug('over caption')");
  
  //layout(); not needed if no flowing
  }

  
  function removeCaption(element) {
  	if(element.childNodes.length == 1) return;
	 element.removeChild(element.lastChild);
	// revert to thumbnail
	element.firstChild.width = "50";// shrink thumb first
  element.firstChild.height = "50";
  element.style.width = "50px";
  element.style.height = "50px";
  element.firstChild.src = "http://imagebreeder.com/thumbs/t"+element.getAttribute("image");
  
  //layout();  not needed if the positioning doesn't flow.
  }


function drag(elementToDrag, event) {
  var startX = event.clientX, startY = event.clientY;
  var origX = elementToDrag.offsetLeft, origY = elementToDrag.offsetTop;
  var deltaX = startX - origX, deltaY = startY - origY;
  
  if(document.addEventListener) {
  	document.addEventListener("mousemove", moveHandler, true);
  	document.addEventListener("mouseup", upHandler, true);
  	document.addEventListener("mousedown", downHandler, true);
  }
  else if(document.attachEvent) {
  	elementToDrag.setCapture();
	elementToDrag.attachEvent("onmousemove", moveHandler);
	elementToDrag.attachEvent("onmouseup", upHandler);
	elementToDrag.attachEvent("onmousedown", downHandler);
	elementToDrag.attachEvent("onlosecapture", upHandler);
  }
  
  if(event.stopPropagation) event.stopPropagation();
  else event.cancelBubble = true;
  
  if(event.preventDefault) event.preventDefault();
  else event.returnValue = false;
  
  function downHandler(e) {
         z++;
         //debug("z="+z);
		 //alert("downHandler");
  }

  function moveHandler(e) {
  		if(!e) e = window.event;
		
           elementToDrag.style.left = (e.clientX - deltaX) + "px";
           elementToDrag.style.top = (e.clientY - deltaY) + "px";
           elementToDrag.style.zindex = z;
           
           if(e.stopPropagation) e.stopPropagation();
  			else e.cancelBubble = true;
  }
  
  function upHandler(e) {
    if(!e) e = window.event; // IE model
	
	if(document.removeEventListener) {
	       document.removeEventListener("mousemove", moveHandler, true);
           document.removeEventListener("mouseup", upHandler, true);
  }
  else if(document.detachEvent) { // IE
  	elementToDrag.detachEvent("onlosecapture", upHandler);
	elementToDrag.detachEvent("onmouseup", upHandler);
	elementToDrag.detachEvent("onmousemove", moveHandler);
	elementToDrag.releaseCapture();
  }
  
	if(e.stopPropagation) e.stopPropagation();
	else e.cancelBubble = true;
  
           if(e.clientX < trayWidth && elementToDrag.getAttribute("name") == "other") {
                 addFave(elementToDrag);
				 elementToDrag.setAttribute("name", "fave");
           }
           else if(e.clientX > trayWidth && elementToDrag.getAttribute("name") == "fave"){
                removeFave(elementToDrag);
				elementToDrag.setAttribute("name", "other");
          }
  	layout();
  }
  }
  
 function getElementsByName_iefix(tag, name) {
     
     var elem = document.getElementsByTagName(tag);
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++) {
          att = elem[i].getAttribute("name");
          if(att == name) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }
	 //debug("in iefix we found " + arr.length + " elements");
     return arr; 
}

  function layout() {
	
  debug("doing layout");
  	//layoutPreviews();
	var xOffset = margin;
	var yOffset = 80;
	var favesList = getElementsByName_iefix("div", "fave");
	for(var i = 0; i < favesList.length; i++) {
   		var fave = favesList[i];
		fave.style.left = xOffset + "px";
		fave.style.top = yOffset + "px";
		xOffset += 70;
		if(xOffset > trayWidth) {
			xOffset = margin;
			yOffset += 70;
		}
	}
	
	var others = getElementsByName_iefix("div", "other");
	debug(others.length + " others");
	var othersList = new Array();
	
	// push into a sortable array
	for(var i = 0; i < others.length; i++) othersList.push(others[i]);
		
		// sort by faves
		othersList.sort(function(a, b) { 
		 return b.getAttribute("favedby") - a.getAttribute("favedby");
		 });
		
		var greats = 6

		xOffset = leftMargin + 60;
		yOffset = topMargin + 250;
		for(var i = 0; i < greats; i++) {
   			var other = othersList[i];
			//if(i < greats) {
			other.style.left = xOffset + "px";
			other.style.top = yOffset + "px";
			xOffset += 60;
			//if(xOffset > 600) {
				//xOffset = leftMargin + 60;
				//yOffset += 60;
			//} else other.style.display = "none";
			other.style.display = "inline";
		}		
		othersList.splice(0, greats);
		
	
		// sort by recency (from ids)
	othersList.sort(function(a, b) { 
		 return b.getAttribute("id") - a.getAttribute("id");
		 });
		 var recents = 18;
		 	var xOffset = leftMargin + 60;
	var yOffset = topMargin + margin;
	for(var i = 0; i < othersList.length; i++) {
   		var other = othersList[i];
		if(i < recents) {
			other.style.left = xOffset + "px";
			other.style.top = yOffset + "px";
			xOffset += 60;//other.style.width;
			//debug("width = " + other.style.width);
			if(xOffset > 600) {
				xOffset = leftMargin + 60;
				yOffset += 60;
			}
			other.style.display = "inline";
		}
		else other.style.display = "none";
	}
		
		// discount recents
		othersList.splice(0, recents);
		
  }
  /*
  function layoutPreviews() {
  
  debug("layoutPreviews()");
           var yOffset = 50;
		   var xOffset = margin;
           var usedList = new Array();
          
           // faves list
           for(var i = 0; i < favesList.length; i++) {
           var fave = favesList[i];
           		   fave.style.left = xOffset + "px";
           		   fave.style.top = yOffset + "px";
				   	
 					//thumbPreview(fave);
				   		  
                  // fave.setAttribute("onmouseover", "medPreview(this)");
                   //fave.setAttribute("onmouseout", "thumbPreview(this)");

           		   //pos += margin + thumbHeight;//fave.clientHeight; 
           		   
				   if(i % 2 == 1) {
				   	yOffset += margin + thumbHeight;
					xOffset = margin;
				   }
				   else xOffset += thumbHeight;
				   
				   usedList.push(favesList[i]);
           }
           
           // latest list
           var yOffset = 140 - margin - thumbHeight;
           var xOffset = trayWidth + 2 * margin + 50;
       
           var shown = new Array();
          
         otherList.sort(function(a, b) { 
		 return b.firstChild.getAttribute("uploaddate") - a.firstChild.getAttribute("uploaddate");
		 });
        
          // show latest
           for(var i = 0; i < otherList.length; i++) {
           		   if(shown.length < showNumber*2) {
           		   		otherList[i].style.left = xOffset+"px";
           		   		if(i % showNumber == 0) {
				   			yOffset += margin + thumbHeight;
							xOffset = trayWidth + 2 * margin + 50;
				   		}
				   			else xOffset += thumbWidth + margin;
           		   		otherList[i].style.top = yOffset + margin + "px";
           		   		shown.push(otherList[i]);
           		   		otherList[i].style.display = "inline";
           		   }
           		   else otherList[i].style.display = "none";//document.body.removeChild(otherList[i]);
           }
           
           yOffset += 100 + margin;
            var xOffset = trayWidth + 2 * margin + 50;
           
           // sort by faves
           otherList.sort(function(a, b) { 
		 return b.firstChild.getAttribute("favedby") - a.firstChild.getAttribute("favedby");
		 });
           // show by faves
           for(var i = 0; i < otherList.length; i++) {
           		   if(shown.length < showNumber*3 
					  && !objInList(otherList[i], shown)
					  ) {
           		   		otherList[i].style.left = xOffset + "px";
					    //xOffset += thumbWidth + margin;
						//debug("otherList[i]=" + otherList[i]);
						xOffset += (Number(otherList[i].style.width) + margin);
						//debug("xOffset=" + xOffset);
           		   		otherList[i].style.top = yOffset + margin + "px";
           		   		shown.push(otherList[i]);
           		   		otherList[i].style.display = "inline";
           		   }
           }
  }
*/
function loadAll() {
		 var favescript = document.createElement("script");
		 document.body.appendChild(favescript);
		 favescript.src="list.php?cat=faves&c="+getCode();		 
		 document.body.removeChild(favescript);
		 
		 var allscript = document.createElement("script");
		 document.body.appendChild(allscript);
		 allscript.src="list.php?cat=all&c="+getCode();
		 document.body.removeChild(allscript);
		 
		 // need to ensure this happens after the elements have been created
		 // Not so simple!
		 //window.setTimeout(layoutPreviews, 5000);
}

// list of *IDs* not objects
function idInList(id, list) {
		 for(var i = 0; i < list.length; i++) {
		 		 if(id == list[i].id) return true;
		 }
		 return false;
}

function objInList(obj, list) {
		 for(var i = 0; i < list.length; i++) {
		 		 if(obj == list[i]) return true;
		 }
		 return false;
}

function clearList(list) {
		 // remove from document
		 for(var i = 0; i < list.length; i++) {
		document.body.removeChild(list[i]);
		}
		 // finally renew
		 list = new Array();
}

function loadfaves(items) {
clearList(favesList);
for(var i = 0; i < items.length; i++) {
		addToList(makeDragbox(items[i]), favesList);
}
}


function loadall(items) {
clearList(otherList);
    for(var i = 0; i < items.length; i++) {
  		if(!idInList(items[i], favesList)) {
			addToList(makeDragbox(items[i]), otherList);
		}
	}
}

function loadUser() {
	debug("in loadUser()");
	var userscript = document.createElement("script");
	debug(userscript);
	userscript.src="user.php?c="+getCode();		 
	document.body.appendChild(userscript);
	//document.body.removeChild(favescript); causes non-excution in IE
}

function loadUserProperties(id, email, code, nick) {
	user['id'] = id;
	user['email'] = email;
	user['code'] = code;
	user['nick'] = nick;
	loggedinMode();
}

function getCode() {
   var name = "code";

   var allcookies = document.cookie;
   var cookies = allcookies.split('; ');
   var cookie = null;
   
   for(var i = 0; i < cookies.length; i++) {
      // does it match?
   	  if(cookies[i].substring(0, name.length + 1) == (name + "=")) {
		 var code =  cookies[i].substring((name.length+1), cookies[i].length);
       	//debug("finding code = " + code + " in getCode()");
			return code;
      }
   }
   return null;
}

function debug(message) {
		id('debug').innerHTML += message + "<br>\n";
}

window.onload = function() {
	//debug("cookie:"+document.cookie);
debug("onload(): getCode() = " + getCode())
//pleaseWait(5000);
if(getCode() == null) signupMode();
else loggedinMode();
loadUser();
//loadAll();
//alert("all loaded");
debug("you are " + user['email']);
}

var blurb_loginorsignup = "<h1>The ImageBreeder Project</h1><p align=\"right\" style=\"font-weight:bold; border: 3px solid #ff7733; padding: 2px; float:right\">NEW: <a href=\"http://imagebreeder.com/breeder.php?code=guest\">try out the breeder</a> as a guest.</p><br clear=\"both\"><p align=\"right\">ImageBreeder is a demonstration of interactive evolutionary art.  It lets you create original art by repeatedly selecting among alternatives. " 
	+"<p align=\"right\">As well as the online breeder, there is a gallery of user-submitted art (which you can rate) and a <a href=\"http://imagebreeder.com/blog\">blog</a> with news and background information."
	+ "<p/><p align=\"right\">Please <a href=\"javascript:signupMode()\">sign up</a> or <a href=\"javascript:loginMode()\">log in</a> to get started.</p>";
//var user = null;

function signupMode() {
debug("in signupMode()");
var signupform = "<h2>Sign up</h2>" + 
	"<form action='?regsent' method='post'>" +
	"<input onfocus=\"this.value=''\" type='text'" +
	"name='newemail' value='your@email.com'>" +
	"<br/><input type='submit' value='sign up'>" +
	//"<br>Already registered?  Then <a href=\"javascript:loginMode()\">log in</a>." +
	"</form>" +
	"<h3>Why do we need your e-mail?</h3>This site is entirely dependent on images produced and rated by genuine users. A valid e-mail is a indicator of a genuine user.<p>It also helps us deal with problems and gives us some idea of who is using this site.<p>We promise that your e-mail will never be made public nor used for any purpose other than for providing this service."
	$(reglogbox).fadeOut("fast", function() {id('reglogbox').innerHTML = signupform});
id('blurb').innerHTML = blurb_loginorsignup;
id('latestbanner').style.display = "none";
id('greatestbanner').style.display = "none";
$(reglogbox).fadeIn();
}

function loginMode() {
debug("in loginMode()");
var loginform = "<h2>log in</h2><form action='.' method='post'>" +
		 "<input onfocus=\"this.value=''\" type='text'" +
		 "name='email' value='your@email.com'><br />" +
		 "enter your password<br />" +
		 "<input type='password' name='password'>" +
		 "<br /><input type='submit' value='log in'>" +
	 	 //" Need to <a href=\"javascript:signupMode()\">sign up</a>?" +
		 "</form>" +
		 "<a href=\"\" onclick=\"$(reminder).slideDown();return false\">forgotten your password?</a>" + 
		  "<div id=\"reminder\">enter your registered e-mail<form method=\"post\" action=\"\">" + 
		  "<input name=\"reminderto\" value=\"\"><input type=\"submit\" value=\"send reminder\">" +
		  "</form></div>";
		 $(reglogbox).fadeOut("fast", function() {id('reglogbox').innerHTML = loginform});
//id('reglogbox').innerHTML = signupform;
id('blurb').innerHTML = blurb_loginorsignup;
$(reglogbox).fadeIn();
}


function loggedinMode() {
	var feedbackform = "<h2>Comments<h2><form method=\"POST\"  action=\".\"><textarea rows=\"3\" cols=\"20\" name=\"feedback\" onFocus=\"if(this.value == commentsPlease) this.value=''\" onBlur=\"if(this.value=='') this.value=commentsPlease;\"></textarea><script>document.forms[0].feedback.value = commentsPlease;</script><br /><input type=\"submit\" value=\"send\"></form>";
	var profileform = "<h2>Profile</h2><form name=\"profileform\" method=\"POST\" onSubmit=\"return profileChange();\" action=\".\">";
	profileform += "nickname <input type=\"textfield\" size=\"8\" name=\"nickname\" value=\""+user['nick']+"\">";
	profileform += "<br/>new password <input  size=\"10\" type=\"password\" name=\"password\">";
	profileform += "<br/>again to check <input size=\"10\" type=\"password\" name=\"pwagain\">";
	profileform += "<br/><input type=\"submit\" name=\"profile\" value=\"update\">";
	profileform += "</form>";
	var sectionsheader = "<div class=\"sections\"><b>Gallery</b> :: <a href=\"breeder.php?code="+user['code']+"\">Breeder</a> :: <a href=\"/blog\">Blog</a></div>";

//debug("in loggedinMode() user = " + user);
//if(user == null) loadUser(getCode());
debug("in loggedinMode()");
//debug(" : post loadUser() user = " + user);
id('tabbar').innerHTML = user['email'] + " <a href='?logout'>log out</a>";
id('tabbar').style.display = "inline";
id('blurb').innerHTML = sectionsheader+"These are some of the most recent and popular images that have been submitted via the breeder.</p><p>You can drag any that you like to the left to remember them and increase their rating.";
;
id('reglogbox').innerHTML = feedbackform+profileform;
id('reglogbox').style.display = "inline";
//id('feedback').style.display = "inline";
id('tray').style.display = "inline";
id('latestbanner').style.display = "inline";
id('greatestbanner').style.display = "inline";
id('showcase').style.display = "none";
}

function profileChange() {
//	alert("change:pwagain="+ profileform.pwagain.value);
if(profileform.password.value != profileform.pwagain.value) {
	alert('passwords don\'t match');
	return false;
}
else $.post("processform.php", { password: profileform.password.value})
	return true;
}

function pleaseWait(time) {
	waitbox = document.createElement("div");
	waitbox.setAttribute("id", "waitbox");
	waitbox.innerHTML = "please wait";
	waitbox.style.leftmargin = "auto";
	waitbox.style.rightmargin = "auto";
	document.body.appendChild(waitbox);
	setTimeout(function() {waitbox.style.display="none";}, time);
}
