var likeArr = [];
var dislikeArr = [];
var logLike = [];

var curArray = [];
var tmp;
var pref;
var user='';

var isIE = (window.navigator.userAgent.indexOf("MSIE") > 0);

// tiny helper funcs
// findPosX and Y by Peter-Paul Koch and Alex Tingle 
function findPosX(obj) {
  var curleft = 0;
  if(obj.offsetParent)
      while(1) 
      {
	curleft += obj.offsetLeft;
	if(!obj.offsetParent)
	  break;
	obj = obj.offsetParent;
      }
  else if(obj.x)
      curleft += obj.x;
  return curleft;
}

function findPosY(obj) {
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
	curtop += obj.offsetTop;
	if(!obj.offsetParent)
	  break;
	obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop;
}

// tiny helper funcs
function getIndexOf(needle, haystack) {
	if(!Array.indexOf){
		Array.prototype.indexOf = function(obj){
			for(var i=0; i<this.length; i++){
				if(this[i]==obj){
				return i;
				}
			}
		return -1;
		}
		return haystack.indexOf(needle);
	}
	else {
		return haystack.indexOf(needle);
	}
}

function showHide(myID,type) {
	var domID = document.getElementById(myID);
	var classInfo;
	
	if (isIE) {
	 classInfo = domID.getAttribute('className');
	} else {
	 classInfo = domID.getAttribute('class');
	}
	
	if (classInfo == 'hidden') {
		if (myID == "instructioncontent") {
			document.getElementById('showinstructions').innerHTML = "Hide Instructions";
		}
		
		if (myID.search(/overflow/) > -1) {
			tmp = 'link' + myID;
			document.getElementById(tmp).innerHTML = '';
		}
		
		if (isIE) {  domID.setAttribute('className', type);
		} else {	  domID.setAttribute('class', type); }
	}
	
	else if ((classInfo == 'block') || (classInfo == 'inline') || (classInfo == 'smiley')) {
		if (myID == "instructioncontent") {
			document.getElementById('showinstructions').innerHTML = "Show Instructions";
		}
		
		if (isIE) {
		  domID.setAttribute('className', type);
		} else {
		  domID.setAttribute('class',type);
		}
	}
	else {
		if (isIE) {  domID.setAttribute('className', type);
		} else {	  domID.setAttribute('class', type); }
	}
}


function hideOverflow(cat) {
  var cats = ['overflowfood', 'overflowsports', 'overflowplaces', 'overflowinterests', 'overflowmusic'];
  cat = 'overflow' + cat;
	var link = "link" + cat;
  
  for (var i = 0; i < cats.length; i++) {
    if (cats[i] != cat) {
      showHide(cats[i], 'hidden');
			document.getElementById(link).innerHTML ="<span id=\"linkoverflow$category\" onclick=\"showHide('overflow$category', 'inline')\">Click for more pictures...</span>";
    }
  }
}

function myToggle(myID) {
	var domID = document.getElementById(myID);
	if ((domID.style.display=="block") || (domID.style.display=="")) {
		domID.style.display='none';
	}
	else { domID.style.display='block'; }
}

function remFrom(id, list) {
	return list.splice( list.indexOf(id), 1); 
}

function remChild(id) {
	var domID = document.getElementById(id);
	var parent = domID.parentNode;
	parent.removeChild(domID);
}

function addToCur(id,name,thumb,loc,cat) {
	var domID = document.getElementById(id);
	var imageInfo = id + ',' + name + ',' + thumb + ',' + loc + ',' + cat;
	var picID;
	var copyID = id + "copy";
	
	var likeIndex = getIndexOf(id, likeArr);
	var dislikeIndex = getIndexOf(id, dislikeArr);
	
	if (pref == 'like') {		
		picID = 'tup' + id;
		if(likeIndex > -1) {
			// unselect
			remFrom(id, likeArr);
			remChild(copyID);
			if (isIE) { domID.style.filter = 'alpha(opacity=100)'; }
			else { domID.style.opacity = 1; }
			showHide('tup' + id, 'hidden');
		}
		else if (dislikeIndex > -1) {
			//remFrom(id, dislikeArr);
			//if (isIE) { domID.style.filter = 'alpha(opacity=100)'; }
			//else { domID.style.opacity = 1; }
			//showHide('tdown' + id, 'hidden');	
			//remChild(copyID);
			//addToGroup(id, picID, pref);
			//copy(imageInfo, pref);
		}

		else {
			addToGroup(id, picID, pref);
			copy(imageInfo, pref);
		}
	}

	if (pref == 'dislike') {
		picID = 'tdown' + id;
		if(dislikeIndex > -1) {
			// unselect
			remFrom(id, dislikeArr);
			remChild(copyID);
			if (isIE) { domID.style.filter = 'alpha(opacity=100)'; }
			else { domID.style.opacity = 1; }
			showHide('tdown' + id, 'hidden');	
		}
		else if (likeIndex > -1) {
			//remFrom(id, likeArr);
			//if (isIE) { domID.style.filter = 'alpha(opacity=100)'; }
			//else { domID.style.opacity = 1; }
			//showHide('tup' + id, 'hidden');
			//remChild(copyID);
			//addToGroup(id, picID, pref);
			//copy(imageInfo, pref);
		}
		else {
			addToGroup(id, picID, pref);
			copy(imageInfo, pref);
		}
	}
	
	if (pref == 'review') {
		showHide('setpreferences', 'inline');
		if (dislikeIndex > -1) {
			picID = 'tdown' + id;
			remFrom(id, dislikeArr);
			if (isIE) { domID.style.filter = 'alpha(opacity=100)'; }
			else { domID.style.opacity = 1; }
			showHide('tdown' + id, 'hidden');
			remChild(copyID);
			countDown('dislike');
		}
		if (likeIndex > -1) {
			picID = 'tup' + id;
			remFrom(id, likeArr);
			if (isIE) { domID.style.filter = 'alpha(opacity=100)'; }
			else { domID.style.opacity = 1; }
			showHide('tup' + id, 'hidden');
			remChild(copyID);
			countDown('like');
		}
	}
	
	countDown(pref);
}

function addToGroup(id, picID, group) {
	var domID = document.getElementById(id);
	var picture = document.getElementById(picID);

	if (isIE) { 
    picture.style.top = findPosY(domID);
    picture.style.left = findPosX(domID);
        picture.style.filter = 'alpha(opacity=100)'; }
	else { 
	picture.style.top=domID.offsetHeight;
	picture.style.left=domID.offsetWidth;
        picture.style.opacity=1; }
	
	if (group == 'like') { likeArr.push(id); }
	if (group == 'dislike') { dislikeArr.push(id); }
	

	if (isIE) { picture.setAttribute('className', 'smiley');
    domID.style.filter = 'alpha(opacity=60)'; }
	else { picture.setAttribute('class', 'smiley');
        domID.style.opacity = 0.6; }
	
	fadeOut(picID, 0);
}

function fadeOut(id, done) {	
	picture = document.getElementById(id);

	if (done == 0) {
		if (isIE) {
			var val = picture.filters.alpha.opacity;
			if (val > 0) {
				picture.style.filter = 'alpha(opacity=' + (val - 10) + ')';
				setTimeout("fadeOut('" + id + "'," + "'" + done + "')", 60);
			}
			else if (val == 0) {
				done = 1;
				picture.style.filter = 'alpha(opacity=100)';
				return 0;
			}
		}
		
		else {
			if (picture.style.opacity > 0) {
				picture.style.opacity -= 0.1;
				setTimeout("fadeOut('" + id + "'," + "'" + done + "')", 60);
			}
			else if (picture.style.opacity == 0) {
				done = 1;
				picture.style.opacity = 1;
				return 0;
			}
		}
	}
}

function swapImg() {
	var div = document.getElementById("biggerImg");
	
	this.show=function(id, name, bigimg) {
	var img = new Image();
	img.src = bigimg;
		
	// define the boundaries where the tooltip shows
	//var thumb = document.getElementById(id);
	//var thumbx = thumb.offsetLeft;
	//var thumby = thumb.offsetTop;

	if (isIE) { div.setAttribute('className', 'tooltip'); }
	else { div.setAttribute('class', 'tooltip'); }

	div.innerHTML = "<img src=\"" + bigimg + "\"/><br />\n";
	div.innerHTML += name;

	document.onmousemove = this.move;
	}
	
	this.move=function(e) {
		var x; var y;
		if (isIE) {
			x = 1 + event.clientX;
			y = 1 + event.clientY;
		} else {
			x = 1 + e.pageX;
			y = 1 + e.pageY;
		}
		
		div.style.left = x + 'px';
		div.style.top = y + 'px';
	}
	
	this.hide=function() {
		//div.style.border = '0px';
		if (isIE) {
			div.setAttribute('className', 'hidden');
		} else {
			div.setAttribute('class', 'hidden');
		}
	}
}

// registration stuff
function countDown(val) {
	var domID = document.getElementById("instructions");
	pref = val;
	
	if (pref == 'like') {
		if (likeArr.length < 7) {
			domID.innerHTML = "Select " + (8-likeArr.length) + " things you like.";
		}
		else if(likeArr.length == 7) {
			domID.innerHTML = "Select 1 thing you like.";
		}

		if (likeArr.length == 8) {
			if (dislikeArr.length < 8) {
				domID.innerHTML = "Next you'll be selecting things you don't like.";
				popup("Done with likes! Now select what you don't like.",4);
				setTimeout('countDown(\'dislike\')', 500);
			}
			else {
			domID.innerHTML = '<p>Done! You can now review your choices.</p>';
			showHide('reviewtime', 'block');
			pref = "review";
			}
		}
	}

	if (pref == 'dislike') {
		if (dislikeArr.length <7) {
			domID.innerHTML = "Select " + (8-dislikeArr.length) + " things you dislike.";
		}
		else if(dislikeArr.length == 7) {
			domID.innerHTML = "Select 1 thing you dislike.";
		}

		if (dislikeArr.length == 8) {
			if (likeArr.length < 8) {
				domID.innerHTML = "Next you'll be selecting things you like.";
				setTimeout('countDown(\'like\')', 500);
			}
			else {
			domID.innerHTML = '<p>Done! You can now review your choices.</p>';
			pref = "review";
			showHide('reviewtime', 'block');
			}
		}
	}
	if ((likeArr.length == 8) && (dislikeArr.length == 8)) {
		showHide('setpreferences', 'hidden');
		showHide("guide", 'hidden');
		domID.innerHTML = '<p>Done! You can now review your choices.</p>';
		pref = "review";

		showHide('reviewtime', 'block');
	}
}

function copy(image, dest) {
	// [0] => id, [1] => name, [2] => thumb, [3] => url, [4] => cat
	image=image.split(',');
	var destID = document.getElementById(dest);
	var id = image[0]+'copy';
	
	destID.innerHTML += '<img src="' + image[3] + '" id="' + id + '" name="' + image[1] 
		+ '" width=90 height=90 onclick="addToCur(\'' + image[0] + '\', \'' + image[1] + '\', \'' + image[2] + '\', \'' 
		+ image[3] + '\', \'' + image[4] + '\');">\n';
		
}

function checkUser(username) {
	blur();
	var url = "userfuncs.php";
	var request = new XMLHttpRequest();
	
	if (request == null) {
		popup("Browser doesn't support HTTP request.",3);
		return;
		}
	
	var data = "action=userexists&username=" + username;
	request.open("POST", url, true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.send(data);

	request.onreadystatechange = function(){
		if(request.readyState == 4){
			document.getElementById("content").innerHTML = request.responseText;
			if (request.responseText.search(/already exists/) == -1) {
				user = username;
				showHide("chooseusername", 'hidden');
                submitRegistration();
			}
		}
	}
}

function changeUser() {
  showHide("chooseusername", 'block');
  document.getElementById("content").innerHTML = '';
  document.getElementById("registername").value = "Check Username Availibility";
  user = '';
}

// setup submission
function submitRegistration() {
	var like = likeArr.sort();
	var dislike = dislikeArr.sort();
	var url = "userfuncs.php";
	var request = new XMLHttpRequest();

	if (request == null) {
		popup("Browser doesn't support HTTP request.",3);
		return;
		}
	
	// first check if user typed in a name
	if (user.replace(/\s/gi,"") == '') {
	    var username = document.getElementById('username').value;
        if (username.replace(/\s/gi,"") == '') {
            popup("Please specify a valid username.",0);
        }
		else {
			if (checkUser(username) == 1) {
                submitRegistration();
            }
		}
	}
	
    
	
	// then check if they have selected the right number of things
	else if (likeArr.length < 8) {
		popup("You need 8 things that you like. You have " + likeArr.length + " items.",0);
	}
	else if (dislikeArr.length < 8) {
		popup("You need 8 things that you dislike. You have " + dislikeArr.length + " items.",0);
	}
	
	
	// finally, if those checks are passed, submit
	else {
		var data = "action=register&username=" + user + "&like=" + like + "&dislike=" + dislike;
		request.open("POST", url, true);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.send(data);
	
		request.onreadystatechange = function(){
			if(request.readyState == 4){
				document.getElementById("allcontent").innerHTML = request.responseText + 
				"<p>Redirecting to the next step... <br>" + 
				"Click <a href=\"prelogin.php?id=" + user + "\">here</a> to go directly.</p>";
				setTimeout("location.href = 'prelogin.php?id=" + user + "';",1500);
			}
		}
		// empty like and dislike arrays. 
		likeArr = [];
		dislikeArr = [];
	}
}


// login stuff
function showImages(username,which) {
	var url = "userfuncs.php";
	var request = new XMLHttpRequest();
	
	if (request == null) {
		popup("Browser doesn't support HTTP request.", 3);
		return;
		}
	
	var data = "action=getimages&username=" + username+"&which="+which;
	request.open("POST", url, true);
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.send(data);

	request.onreadystatechange = function(){
		if(request.readyState == 4){
			document.getElementById("content").innerHTML = request.responseText;
			if (request.responseText.search(/not exist/) == -1) {
				user = username;
			}
		}
	}
}

function loginChoose(id,which) {
	var domID = document.getElementById(id);
	var msgID = document.getElementById('loginselect');
	var tupID = document.getElementById('tup' + id);
	tupID.style.top=findPosY(domID) + "px";
	tupID.style.left=findPosX(domID) + "px";

	var indexLog;
	
	if (which == 1) {
		var tmpwhich = 'like';
	}
	else {
		var tmpwhich = 'dislike';
	}
	
	indexLog = getIndexOf(id, logLike);
	
	if(indexLog > -1) {
		// unselect
		remFrom(id, logLike);
		if (isIE) {
			domID.style.filter='alpha(opacity=100)';
		}
		else {
			domID.style.opacity=1;
			}
		showHide('tup' + id, 'hidden');
		msgID.innerHTML = 'Select ' + (8 - logLike.length) + ' things that you ' + tmpwhich + '.';
	}
	else {
		if (logLike.length == 7) {
			msgID.innerHTML = 'Select 1 thing that you ' + tmpwhich + '.';
			logLike.push(id);
			if (isIE) {
				domID.style.filter='alpha(opacity=60)';
				tupID.style.filter='alpha(opacity=100)';
				tupID.setAttribute('className', 'smiley');
				}
			else {
				domID.style.opacity=0.6;
				tupID.style.opacity=1;
				tupID.setAttribute('class', 'smiley');
			}
			msgID.innerHTML = 'Attempting login...';
			logIn(which);
		}
		else {
			logLike.push(id);
			if (isIE) {
				domID.style.filter='alpha(opacity=60)';
				tupID.style.filter='alpha(opacity=100)';
				tupID.setAttribute('className', 'smiley');
				}
			else {
				domID.style.opacity=0.6;
				tupID.style.opacity=1;
				tupID.setAttribute('class', 'smiley');
			}
			msgID.innerHTML = 'Select ' + (8 - logLike.length) + ' things that you ' + tmpwhich + '.';
		}
	}
}

function logIn(which) {
	var like = logLike.join(",");
	var url = "userfuncs.php";
	var request = new XMLHttpRequest();
	
	if (request == null) {
		popup("Browser doesn't support HTTP request.",3);
		return;
		}
	
	// first check if user typed in a name
	if (user.replace(/\s/gi,"") == '') {
		popup("Please specify a username.", 0);
	}
	else {
		var data = "action=verify&username=" + user + "&pass=" + like+ "&which=" + which;
		request.open("POST", url, true);
		request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		request.send(data);
	
		request.onreadystatechange = function(){
			if(request.readyState == 4){
				if (request.responseText.search(/Try again/) > -1) {
				    document.getElementById("messages").innerHTML = request.responseText;
				    showImages(user,which);
				}
				else { document.getElementById("messages").innerHTML = request.responseText + 
				"<p>Try <a href=\"index.php\">creating</a> a new user. You'll be redirected automatically...</p>"; 
				document.getElementById("content").innerHTML = '';
				setTimeout("location.href='index.php'", 10000);				
				}
			}
		}
		// empty arrays. 
		logLike = [];
	}
}

function popup(msg, duration) {
	var domID = document.getElementById("popup");
			
	var dynHTML = msg;
	
	if (duration > 0) {
	  dynHTML += "<p>(This window will close automatically in " + duration + " seconds.)</p>"
	}
	dynHTML += "<center><input type=\"submit\" name=\"close\" onclick=\"javascript:showHide('popup', 'hidden')\" value=\"Close Now\"></center>";
		
	document.getElementById("popup").innerHTML = dynHTML;
	
	domID.style.position = "fixed";
	if (isIE) {
		domID.style.top =  document.body.clientHeight/2 + 'px';
	} else {
			var height = window.pageYOffset;
			domID.style.top = window.innerHeight/2 + 'px';
	}
  //domID.style.top  = height + (window.innerHeight/2) - 80 + 'px';
	//domID.style.left = (width-300)*0.5 + 'px';
	
	showHide('popup', "block");
	if (duration > 0) {
		setTimeout('showHide("popup", "hidden")', duration * 1000);
	}
}
