/**
 * @author Daved
 */

/** 
 * Get the elements to work with
 */ 
getElements = function(tag, attribute, searchid){
	eArray = new Array();
	elemTest = document.getElementsByTagName(tag); // elements to test
	searchstring = new RegExp("\\b" + searchid + "\\b"); // get sliders by classname
	j = 0;
		for(i = 0; i < elemTest.length; i++){
			if(attribute == "class") {
				if(searchstring.test(elemTest[i].className)){
					eArray[j] = elemTest[i]; // Reminds me of C++
					j++; // increment, don't forget to increment the array
				}
			}
			else {
				att = elemTest[i].getAttribute(attribute);
				if (searchstring.test(att)){ // find the className
					// For each one that is a "slider", add a slider bar
					eArray[j] = elemTest[i]; // Reminds me of C++
					j++; // increment, don't forget to increment the array
				}
			}
		}
	return eArray;
};

/**
 * Get Elements From Elements
 */
getElementsFromElement = function(element, tag, attribute, searchid){
	searchstring = new RegExp("\\b" + searchid + "\\b");
	eArray = element.getElementsByTagName(tag);
	elems = [];
	j = 0;
	for(i = 0; i < eArray.length; i++){
		if(searchstring.test(eArray[i].getAttribute(attribute))) {
			elems[j] = eArray[i];
			j++;
		}
	}
	return elems; 
};

/* 
 * Returns the first element matching the search, if there is one.  If not, returns null.
 */
getElementFromElements = function(eArray, attribute, searchid){
	searchstring = new RegExp("\\b" + searchid + "\\b");
	var elem;
	for(i = 0; i < eArray.length; i++){
		att = eArray[i].getAttribute(attribute)
		if(searchstring.test(att)) {
			elem = eArray[i];
			return elem;
		}
	}
	return elem;
};

// Just toggles visability for categories
toggleVisCats = function(info){
	sar = info.split("|");
	id = sar[0];
	/* Get Child Elements that have this id for their parent */
	hidethechildren = false;
	childelems = getElements("li", "class", id);
	for(i = 0; i < childelems.length; i++){
		if(childelems[i].style.display == "none") {
			childelems[i].style.display = "";
		} else if (childelems[i].style.display == ""){
			hidethechildren = true;
		}
	}
	// It's quite a bit harder to hide the stuff...
	if (hidethechildren) {
		lft = parseInt(sar[1]);
		rgt = parseInt(sar[2]);
		cat_array = getElements("li", "class", "cat_link");
		for (i = 0; i < cat_array.length; i++) {
			n_lft = cat_array[i].getAttribute("id").split("_")[1];
			id = cat_array[i].getAttribute("id").split("_")[3];
			if( n_lft > lft && n_lft < rgt ) {
				cat_array[i].style.display = "none";
				getpic = "cat_link.cat" + id + "_excon";
				plusit = document.getElementById(getpic);
				if (plusit != null && plusit.title == "minus") {
					plusit.title = "plus";
					plusit.style.backgroundPosition = "0px 0";
				}
			}
		}
	}
};

// Changes the plusminus icon	
flipPlusMinus = function(id){
	element = document.getElementById(id+"_excon");
	if(element.title == "plus"){
		element.style.backgroundPosition = "-16px 0";
		element.title = "minus";
	} else if (element.title == "minus"){
		element.style.backgroundPosition = "0px 0"
		element.title = "plus";
	}
};

/* This clears the default text of a box */
clearText = function(element){
	if(element.name == element.value) {
		element.style.color = "black";
   		element.value = "";
	}
};

/* This restores the default text if the text box is still empty */
restoreText = function(element){
	if(trimString(element.value) == ""){
		element.style.color = "gray";
		element.value = element.name;
	}
};

/* Make text black in case it wasn't */
blacktext = function(element){
	element.style.color = "black";
	}

// 
lengthenReviewForm = function(element){
	count_line_array = element.value.split("\n"); // counts number of lines by the person
	count_wordwrap_lines = Math.round(element.value.length / (element.offsetWidth/8)) - 1;
	lines = count_line_array.length + count_wordwrap_lines;
		while(lines > element.rows-2) {
			element.rows++;
		}
		if(lines < 10 && element.rows > 11){
			element.rows = 10;	
		} // I want this to simply erase if the review is long and then they erase it all.
};

// Checks before registration can occur
checkPasswords = function(){
	entered_pass = $("input#reg_user_pass").val();
	_default = $("div#login_div input#reg_user_pass").attr("name");
	retyped_pass = $("div#login_div input#reg_user_pass_check").val();
	if(retyped_pass == _default) {
		return;
	}
	
	if(entered_pass != _default && retyped_pass != _default
		&& retyped_pass != entered_pass
	){
		$("div#reg_error").html("Passwords do not match. Good thing we check. (I guess everyone checks...)");
		$("div#reg_error").css("color", "#990000");
		$("div#reg_error").css("weight", "600");
		$("div#reg_error").css("font-size", "100%");
		$("div#reg_error").css("height", "auto");
		$("input#reg_user_pass_check").css("color", "#990000");
	} else {
		$("div#reg_error").html("_");
		$("div#reg_error").css("color", "#FFFFFF");
		$("input#reg_user_pass_check").css("color", "#000000");
	}
};

emailcheck = false;
checkEmail = function(){
	str = trimString($("input#reg_user_email").val());
	
	if($("input#reg_user_email").val() == $("input#reg_user_email").attr("name")){
		emailcheck = false;
		return;
	}
	
	filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(str)){
		checkEmailAjax();
	} else{
		emailcheck = false;
		$("div#reg_error").html("I tried and that e-mail is simply unacceptable.");
		$("div#reg_error").css("color", "#990000");
		$("div#reg_error").css("weight", "600");
		$("div#reg_error").css("font-size", "100%");
		$("input#reg_user_email").css("color", "#990000");
	}
} // Parts of this from http://www.javascriptkit.com/script/script2/acheck.shtml

/* Register */
/* This could be sent from the server */
login_container = "";
register = function(){
	login_container = $("div#login_div").html();
	$("div#login_div").css("border", "solid 1px #666");
	$("div#login_div").css("width", "99%");
$("div#login_div").html("<form action=\"javascript:regNew()\" method=\"post\">" +
"<div class=\"reg_user\"><input id=\"reg_user_name\" class=\"reg_text\" onfocus=\"javascript:clearText(this);\" onblur=\"javascript:restoreText(this); checkUserName(); \" value=\"user name\" name=\"user name\" title=\"Enter your desired user name\" style=\"color: gray; margin:2% 2% 0% 2%;text-align:right;\" maxlength=\"255\" ><label for=\"reg_user_name\">user name</label></input></div>"+
"<div class=\"reg_user\"><input id=\"reg_user_pass\" class=\"reg_text\" onfocus=\"javascript:clearText(this);\" onblur=\"javascript:restoreText(this);\" value=\"ottooctopus\" name=\"ottooctopus\" type=\"password\" title=\"Enter a password for logging into your account.\" style=\"color: gray; margin:2% 2% 0% 2%;text-align:right;\" maxlength=\"255\"><label for=\"reg_user_pass\">password</label></input></div>"+
"<div class=\"reg_user\"><input id=\"reg_user_pass_check\" class=\"reg_text\" onfocus=\"javascript:clearText(this);\" onblur=\"javascript:restoreText(this); checkPasswords();\" value=\"ottooctopus\" name=\"ottooctopus\" type=\"password\" title=\"Make sure you typed the right password.  If we didn't double check, you could be sad later.\" style=\"color: gray; margin:2% 2% 0% 2%;text-align:right;\" maxlength=\"255\"><label for=\"reg_user_pass_check\">confirm password</label></input></div>"+
"<div class=\"reg_user\"><input id=\"reg_user_email\" class=\"reg_text\" onfocus=\"javascript:clearText(this);\" onblur=\"javascript:restoreText(this); checkEmail();\" value=\"your email\" name=\"your email\" title=\"Enter your e-mail.  We won't share this with people and it will only be used for e-mailing a link to reset your password.\" style=\"color: gray; margin:2% 2% 0% 2%;text-align:right;\" maxlength=\"255\"><label for=\"reg_user_email\">your e-mail</label></input></div>"+
"<div class=\"reg_cancel_button\"><input id=\"reg_cancel_button\" type=\"button\" onclick=\"javascript:cancelRegister()\" value=\"cancel\" style=\"position:relative; left:30%; margin-top:2%;\" />"+
"<input id=\"reg_button\" type=\"submit\" value=\"register\"  style=\"position:relative; left:30%; margin-top:2%;\"/></div>"+
"<div id=\"reg_error\" style=\"color:white; float:left; font-size:100%; width:100%; margin:2%;\">_</div>"+
"<div id=\"pre_reg\" style=\"color:gray; font-size:90%; margin:2%;\">"+
"E-mail address is required. One e-mail address per user account. Your e-mail address will only be used for e-mailing you a link to reset your password or for your convience as a login name.  It will not be shared to any third-parties.  All rights are reserved.  Terms and User Agreement are pending -- until then: by signing up you must be over the age of 13, all DMCA laws applicable, and over 18 for areas with adult material, etc.  This site is a user-driven content website: user opinion is not the opinion of the website's or the website's owner.  Privacy:  Your right to privacy is protected to the extent that we will not post any information about you that you do not share yourself or wish to share with others.  Use chatrooms at your own risk.  Other people may be rude, insulting, dirty, annoying, etc.: beware of the dangers of online chatting.  Everything you type is joint custody - the site owns it and so do you (you own creative rights).  By registering, you agree with the preceding."+
"</div>"+
"</form>");
};

cancelRegister = function(){
	$("div#login_div").html(login_container);
}

trimString = function (str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}; // This was taken from http://blog.stevenlevithan.com/archives/faster-trim-javascript. Thanks.

function dbDebug(anything){
	testnode = document.createElement("div");
	testnode.innerHTML = "<h1>" + anything + "</h1>";
	document.body.insertBefore( testnode, document.getElementById("test"));
	}

firstdirect = false;
getLink = function(){
	loc = frames['page_iframe'].location.href;
	// The top one doesn't work with IE, the bottom one doesn't work with FF
	document.getElementById("get_link").innerHTML = loc;
	document.getElementById("get_link").innerText = loc;
	document.getElementById("get_link").href = loc;
	if (!firstdirect) {
		$("#get_link").after("<a href=\"javascript:getLink()\" style=\"float:right; font-size:90%; margin-right:1%\">Direct Link</a>");
		firstdirect = true;
	}
};

toggleMenu = function(menu_id) {
	$("ul#" + menu_id).toggle('fast');
}

hideMenu = function(menu_id) {
	$("ul#" + menu_id).hide('fast');
}

Shadowbox.loadSkin('classic', '../skins/');
Shadowbox.loadLanguage('en', 'build/lang');
Shadowbox.loadPlayer(['iframe', 'img'], 'build/player');

__init = function(){
	Shadowbox.init( {overlayColor:"#FFF", resizeDuration:0.35, handleOversize: 'drag' } );
	blankwin();
}

$(document).ready(function() {
	__init();
});

window.onload = function(){
	__init();
}

// From http://cssglobe.com/post/1281/open-external-links-in-new-window-automatically
blankwin = function(){
	var hostname = window.location.hostname;
	hostname = hostname.replace("www.","").toLowerCase();
	var a = document.getElementsByTagName("a");	
	this.check = function(obj){
		var href = obj.href.toLowerCase();
		return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false;				
	};
	this.set = function(obj){
		obj.target = "_blank";
		obj.className = "external";
	};	
	for (var i=0;i<a.length;i++){
		if(check(a[i])) set(a[i]);
	};		
};

// From http://guymal.com/mycode/iframe_size/
function calcHeight()
{
  //find the height of the internal page
  var the_height=
    document.getElementById('page_iframe').contentWindow.
      	document.body.offsetHeight;
	left_height = document.getElementById("left").offsetHeight;
	if(the_height < 500) {
		the_height = 500;
	}
	if(left_height > the_height){
		the_height = left_height;
	}
	the_height += 150;
  	document.getElementById('page_iframe').style.height = the_height + "px";
	document.getElementById("center").style.height = the_height+"px";
}

function addEventHandler(object,evnt,evntHandler) {
  typeof(attachEvent)=='undefined'?object.addEventListener(evnt,evntHandler,false):object.attachEvent('on'+evnt,evntHandler);
}

function removeEventHandler(o,evtName,evtHandler) {
  typeof(attachEvent)=='undefined'?object.removeEventListener(evnt,evntHandler):object.detachEvent('on'+evnt,evntHandler);
}


/* Get a target */
function getTarget(evnt){
		evnt = evnt?evnt:window.event;
		var targetelement;
		/* Get the right slider */
				if (evnt.target) { 
					targetelement = evnt.target; 
				} else if (evnt.srcElement) { 
					targetelement = evnt.srcElement; 
				}
				
				if (!isIE() && !isMozilla()){
					if (targetelement.nodeType == 3) // defeat Safari bug
						targetelement = targetelement.parentNode;
				}
		return targetelement;
	}
/* Ratings */
// I apologize for globals, I hate using globals, but these are necessary and I didn't do a ratings bar class
barid = 0;
drag = false;
percent = 0;
memory = 0;
barClick = function(id) {
	barid = id;
	bar = document.getElementById(id);
	drag = true;
	addEventHandler(document,"mousemove", move);
	addEventHandler(document, "mouseup", barUp);
};

barUp = function (evnt){
		evnt = evnt?evnt:window.event;
		document.removeEventListener?document.removeEventListener("mousemove", move, false):
				document.onmousemove = null;
		move(evnt);
		drag = false;
		if(percent != memory){
				memory = percent;
				document.getElementById(barid).setAttribute("title", percent.toFixed(5));
				document.getElementById(barid + " blank user").setAttribute("title", percent.toFixed(5));
				ajaxGet("/inc/Ratings.php?mode=rate&id=" + barid + "&score=" + percent, scoreHandler);
			}
};

scoreHandler = function(response){
	str = response.split(" ");
	score = parseFloat(str[0]);
	votes = str[1];
	blankbar = document.getElementById(barid + " blank average");
	scorebar = document.getElementById(barid + " scorebar");
	bwidth = blankbar.offsetWidth;
	swidth = score/100 * bwidth;
	scorebar.style.width = swidth + "px";
	scorebar.title = score;
	document.getElementById(barid + " blank average").title = score;
	document.getElementById(barid + " their score").innerHTML = score.toFixed(2);
	document.getElementById(barid + " their score").style.color = hotnessColor(score);
	document.getElementById(barid + " votes").innerHTML = votes;
	if (document.getElementById("traitaverage")) {
		getAverage();
	}
}

getAverage = function(){
	parent = getElements("div", "class", "ratings");
	if (parent.length > 0) {
		averages = getElementsFromElement(parent[0], "a", "id", "their score");
	}
	total = 0;
	for(i = 0; i < averages.length; i++){
		total += parseFloat(averages[i].innerHTML);
	}
	average = total/(averages.length);
	avecolor = hotnessColor(average);
	document.getElementById("traitaverage").innerHTML = average.toFixed(2);
	document.getElementById("traitaverage").style.color = avecolor;
}

function hotnessColor(heat){
			out = "#";
			colorarray = [
				"228822",
				"99AA33",
				"997733",
				"883344",
				"BB0000"
			];
			count = colorarray.length;
			for(i = 1; i <= count; i++){
				// Every X should be a different color, where X is a part of a score of 100
				upperbound = 100-i*(100/count);
				if (heat > upperbound) {
					out += colorarray[i-1];
					break;
				}
			}
			//dbDebug(out);
			return out;
		}

function move(evnt){
		evnt = evnt?evnt:window.event;
		if(drag){
			mousePos = mouseCoords(evnt);
			offset = findOffset(document.getElementById(barid));
			clickX = mousePos-offset;
			maxX = parseFloat(document.getElementById(barid + " blank user").offsetWidth);
			minX = 0;
			clickX = (clickX > maxX)? maxX: (clickX < minX)? minX:clickX;
			(document.getElementById(barid)).style.width = clickX + "px";
			//(document.getElementById(barid + " scorebar")).style.width = clickX + "px";
			if(document.getElementById(barid + " blank user").offsetWidth){
				percent = parseFloat(document.getElementById(barid).offsetWidth)/
								parseFloat(document.getElementById(barid + " blank user").offsetWidth)*100;
			} else{
				percent = parseFloat(clickX);
			}
			percent = (percent > 100)?100: (percent < 0)? 0 : percent;
			document.getElementById(barid + " your score").innerHTML = percent.toFixed(2);
			document.getElementById(barid + " your score").style.color = hotnessColor(percent);
		}
	}
	
	function mouseCoords(evnt){
		x = evnt.pageX?evnt.pageX:evnt.clientX + document.body.scrollLeft - document.body.clientLeft;
		return x;
	}
		

	function findOffset(elem){
		var currentOff = 0;
		if(elem.offsetParent){
			do{
				currentOff += elem.offsetLeft;
			} while(elem = elem.offsetParent);
		}
		return parseFloat(currentOff);
	}	
	

/* Reviews */
created = false;
ent = "";
cat = "";
act = "";
review = function(entity, category, action){
	if (!created && (action=="Write Review" || action=="Write Anonymous Review") || (!created && action=="Update Review")) {
		divelement = document.createElement("div");
		divelement.style.display = "none";
		divelement.id = "ReviewForm";
		divelement.style.marginLeft = "50px";
		ent = entity;
		cat = category;
		act = action;
		divelement.innerHTML = "<form action=\"\" method=\"post\">";
		if (action == "Write Anonymous Review") {
			divelement.innerHTML += "<div><input id=\"anonname\" type=\"text\" style=\"width:20%; margin-left:65%;\" name=\"name\" value=\"name\"  maxlength=\"255\" onfocus=\"javascript:clearText(this);\" onblur=\"javascript:restoreText(this);\" /><label for=\"anonname\"> your name </label></div>";
		//	divelement.innerHTML += "<div><input id=\"anonemail\" type=\"text\" class=\"reviewinput\" name=\"email\" value=\"email\"  maxlength=\"255\" onfocus=\"javascript:clearText(this);\" onblur=\"javascript:restoreText(this);\" /><label for=\"anonemail\"> email </label></div>";
		} 
		divelement.innerHTML += "<div><textarea id=\"review\" type=\"text\" name=\"text\" style=\"width:85%; margin-top:1%;\" rows=\"8\"  maxlength=\"8192\" onkeypress=\"javascript:lengthenReviewForm(this);\" ></textarea><label for=\"review\"> review </label></div>";
		divelement.innerHTML += "<div><input id=\"reviewtitle\" type=\"text\" name=\"tag line (one line summarizing your review)\" style=\"width:85%;\" value=\"tag line (one line summarizing your review)\" maxlength=\"255\" onfocus=\"javascript:clearText(this);\" onblur=\"javascript:restoreText(this);\" /><label for=\"reviewtitle\"> tag line </label></div>";
		divelement.innerHTML += "<input type=\"submit\" onclick=\"javascript:reviewSubmit();\" class=\"reviewbutton\" style=\"margin-left:35%; color:black;\" value=\"Submit\"></input>";
		//if (action != "Write Anonymous Review") {
		//	divelement.innerHTML += "<button type=\"button\" class=\"reviewbutton\" onclick=\"javascript:reviewSave();\">Save</button>";
		//}
		divelement.innerHTML += "<button type=\"button\" class=\"reviewbutton\" onclick=\"javascript:hideReview()\">Cancel</button>";
		divelement.innerHTML += "<div id=\"reviewerror\"></div></form>";
		created = true;
		document.getElementById("infobox").parentNode.insertBefore(divelement, document.getElementById("infobox"));
		$("#ReviewForm").show("fast");
	} else if(created && (action=="Write Review" || action=="Write Anonymous Review")){
		$("#ReviewForm").toggle("fast");
	}
};

REVIEWADDR = "/inc/Review.php?";
reviewSubmit = function(){
	reviewtitle = document.getElementById("reviewtitle").value;
	reviewname = document.getElementById("reviewtitle").name;
	reviewtext = document.getElementById("review").value;
	reviewtext = reviewtext.replace(/\n/g,'</p><p>');
	reviewtext = reviewtext.replace(/\n/g,'</p><p>');
	if (reviewtitle != "" && reviewtitle != reviewname &&
		reviewtext != "") {
		send = "mode=" + act + "&entity=" + ent + "&category=" + cat + "&";
		if (act == "Write Anonymous Review") {
			anonnameval = document.getElementById("anonname").value;
			anonname = document.getElementById("anonname").name;
			if(anonnameval == anonname && anonnameval != ""){
				anonnameval = "Anonymous";
			}
			send += "name=" + anonnameval + "&";
		}
		send += "title=" + reviewtitle + "&";
		send += "review=" + reviewtext;
		post = REVIEWADDR + send;
		$("#reviewerror").html("");
		ajaxPost(post, reviewHandler);
	} else {
		$("#reviewerror").html("Please enter a title and a review.  Why else would you try?");
		document.getElementById("reviewerror").style.color = "#990000";
	}
	return false;
};

reviewHandler = function(response){
	window.location=location.href;
}


hideReview = function(){
	$("#ReviewForm").hide("fast");
};
