// http://alex.dojotoolkit.org/shrinksafe/
// http://www.saltstorm.net/depo/esc/usage.wbm
// http://javascriptcompressor.com/

var scrollTimer, lastId;
var req = false;
var gExtra = false;
var failCount = 0;
var script = "/ajax.cgi";
var allCountries=new Array("USA","CANADA","UK");
var allCats=new Array("beauty","business","cars","clothing","computers","coupons","educational","electronics","email","financial","food","games","gifts","health","home","internet","kids","media","pets","phone","samples","software","sports","travel","webmaster");
var username = '';
var login_url = "/accounts.cgi?m=login&next=main";

window.onresize = doResize;

function sc(id, ref, commentData) {
	if (! document.getElementById("comment_" + id)) {
		var el, el2, com;
		if (! document.getElementById("comment_" + id + "_loading")) {
			if (! req == false) { doFail(); return; }
			el = document.createElement("DIV");
			el.id = "comment_" + id + "_loading";
			el.className = "commentLoadingDiv";
			el2 = document.createElement("IMG");
			el2.setAttribute("src", "/images/smallSpinner.gif");
			el.appendChild(el2);
			el.appendChild(document.createTextNode(" Loading, please wait..."));
			ref.parentNode.appendChild(el);
			
			sendServerRequest(script, processCommentGet, "id=" + id + "&mode=gc", new Array(id, ref));
		} else {
			if (! req == false) return;
			document.getElementById("comment_" + id + "_loading").parentNode.removeChild(document.getElementById("comment_" + id + "_loading"));
			cleanComments(id);
			el = document.createElement('DIV');
			el.className = "commentHeaderText";
			el.id = "comment_txt_" + id;
			el.appendChild(document.createTextNode("Below are comments about this freebie.  Scroll down to leave a comment.  "));
			el2 = document.createElement("SPAN");
			el2.className = "commentHeaderClose";
			el2.onclick = function(){sc(id, ref);};
			el2.appendChild(document.createTextNode("Click here to hide these comments."));
			el.appendChild(el2);
			ref.parentNode.appendChild(el);
			
			var d = document.createElement('DIV');
			d.id = "comment_" + id;
			d.className = "comment_div";
			
			if (commentData.split && commentData != "") { // It's a string
				var allC = commentData.split('||');
				username = allC[0];
				if (allC[1] && allC[1].length > 0) {
					for (var i = 1; i < allC.length; i++) {
						var parts = allC[i].split('(&)');
						if (parts.length > 1) {
							com = document.createElement('DIV');
							com.className = "comment";
							el2 = document.createElement('SPAN');
							el2.className = "comment_report";
							el2.commentId = parts[0];
							el2.onclick = sendCommentReport;
							el2.appendChild(document.createTextNode("Report inappropriate comment"));
							com.appendChild(el2);
							el = document.createElement("DIV");
							el.className = "comment_header";
							el.appendChild(document.createTextNode("Comment by "));
							if (parts[3] != "") {
								el2 = document.createElement("A");
								el2.setAttribute("href", parts[3]);
								el2.setAttribute("target", "_blank");
								el2.appendChild(document.createTextNode(parts[2]));
								el.appendChild(el2);
							} else {
								tn = document.createTextNode(parts[2]);
								if (parts[2] == 'Admin' || parts[2] == 'admin') {
									var b = document.createElement('B');
									b.appendChild(tn);
									el.appendChild(b);
								} else {
									el.appendChild(tn);
								}
							}
							el.appendChild(document.createTextNode(" on " + parts[4] + ":"));
							com.appendChild(el);
								el = document.createElement("DIV");
							el.className = "comment_body";
							el.innerHTML = parts[1];
							com.appendChild(el);
							d.appendChild(com);
						}
					}
				} else {
					d.appendChild(document.createTextNode("No comments yet.  You can be the first one!"));
				}
			} else {
				d.appendChild(document.createTextNode("Server error, please contact the site administrator!"));
			}
			
			if (username != '') { // User is logged in.
				d.appendChild(document.createElement("P"));
				d.appendChild(document.createTextNode("Leave a comment (no HTML please):"));
				d.appendChild(document.createElement("BR"));
				
				d.appendChild(document.createTextNode("Name: "));
				el = document.createElement("span");
				el.className = "post_username";
				el.appendChild(document.createTextNode(username));
				d.appendChild(el);
				
				el = document.createElement('SPAN');
				el.className = "logout_account_links";
				el.onclick = function(){
					if (document.getElementById("comment_TA_" + id) && document.getElementById("comment_TA_" + id).value != "") {
						if(! confirm("You have not submitted your comment.  You will lose any comment text that you have written if you continue.")) return;
					}
					window.location.href = '/accounts.cgi?m=account';
				};
				el.appendChild(document.createTextNode("Edit Account"));
				d.appendChild(el);
				
				el = document.createElement('SPAN');
				el.className = "logout_account_links";
				el.onclick = function(){doLogout(id);};
				el.appendChild(document.createTextNode("Logout"));
				d.appendChild(el);
				
				d.appendChild(document.createElement("BR"));
				
				/*
				d.appendChild(document.createTextNode("Name:"));
				el = document.createElement("INPUT");
				el.setAttribute("type", "text");
				el.id = "comment_name_" + id;
				d.appendChild(el);
				d.appendChild(document.createElement("BR"));
				*/
				/*
				d.appendChild(document.createTextNode("E-mail:"));
				el = document.createElement("INPUT");
				el.setAttribute("type", "text");
				el.id = "comment_email_" + id;
				d.appendChild(el);
				d.appendChild(document.createTextNode(" (Required.  Will not be displayed.)"));
				d.appendChild(document.createElement("BR"));
				
				d.appendChild(document.createTextNode("Homepage:"));
				el = document.createElement("INPUT");
				el.setAttribute("type", "text");
				el.id = "comment_url_" + id;
				d.appendChild(el);
				d.appendChild(document.createElement("BR"));
				*/
				
				el = document.createElement('TEXTAREA');
				el.setAttribute("rows", 5);
				el.setAttribute("cols", 40);
				el.id = "comment_TA_" + id;
				d.appendChild(el);
				d.appendChild(document.createElement('BR'));
				el = document.createElement("INPUT");
				el.setAttribute("type", "button");
				el.setAttribute("value", "Post Comment");
				el.commentId = id;
				el.commentParent = ref;
				el.onclick = sendComment;
				d.appendChild(el);
				el = document.createElement("INPUT");
				el.setAttribute("type", "button");
				el.setAttribute("value", "Cancel");
				el.onclick = function(){sc(id, ref);};
				d.appendChild(el);
			} else { // User is not logged in.
				d.appendChild(document.createElement("P"));
				el = document.createElement("A");
				el.setAttribute("href", login_url);
				el.setAttribute("target", "_top");
				el.appendChild(document.createTextNode("Login"));
				d.appendChild(el);
				d.appendChild(document.createTextNode(" or "));
				el = document.createElement("A");
				el.setAttribute("href", "/accounts.cgi?m=new");
				el.setAttribute("target", "_top");
				el.appendChild(document.createTextNode("register"));
				d.appendChild(el);
				d.appendChild(document.createTextNode(" to be able to post comments!"));
				el = document.createElement("P");
				el.appendChild(document.createTextNode(" "));
				d.appendChild(el);
			}
			ref.parentNode.appendChild(d);
		}
	} else {
		// Add check to see if they've written a comment.
		if (commentData != "close") {
			if (document.getElementById("comment_TA_" + id) && document.getElementById("comment_TA_" + id).value != "") {
				if(! confirm("Are you sure you wish to hide the comments?  You will lose any comment text that you have written.")) return;
			}
		}
		cleanComments(id);
	}
}

function cleanComments(id) {
	while (document.getElementById("comment_" + id)) document.getElementById("comment_" + id).parentNode.removeChild(document.getElementById("comment_" + id));
	while (document.getElementById("comment_txt_" + id)) document.getElementById("comment_txt_" + id).parentNode.removeChild(document.getElementById("comment_txt_" + id));
}

function sendComment() {
	var ta = document.getElementById("comment_TA_" + this.commentId).value;
	if (ta == "") {
		alert("If you would like to comment, please enter text in the comment field.");
		return;
	}
	if (! req == false) { doFail(); return; }
	sendServerRequest(script, processCommentSend, makePost(new Array("mode","pc","id",this.commentId,"comment",ta)), new Array(this.commentId, this.commentParent));
	this.parentNode.appendChild(document.createTextNode("  Thanks!  Sending your comment..."));
}

function sendCommentReport() {
	if (! req == false) { doFail(); return; }
	if(! confirm("Are you sure you wish to report this comment as inappropriate?")) return;
	sendServerRequest(script, processCommentReport, "mode=cr&id=" + this.commentId);
}

function processCommentReport() {
	if (req.readyState == 4) {
		if (req.status == 200) {
			if (req.responseText == "Error") {
				alert("Invalid input.  Please tell the site admin with specifics about what you did.");
			} else if (req.responseText == "Change Limit") {
				alert("Unable to report comment: you have already reported this comment.  If this is in error, please contact the site admin.");
			} else if (req.responseText == "Hour Limit") {
				alert("Unable to report comment: you have reported too many comments recently, please try again in a little while.  If this is in error, please contact the site admin.");
			} else {
				alert("Comment reported.  Thanks for the feedback!");
			}
		} else {
			alert("Server error, unable to send comment.  Please tell the site admin.");
		}
		req = false;
	}
}

function processCommentSend() {
	if (req.readyState == 4) {
		if (req.status == 200) {
			if (req.responseText == "Error") {
				alert("Invalid input.  Please tell the site admin with specifics about what you did.");
			} else if (req.responseText == "Change Limit") {
				alert("Unable to post comment: you have exceeded your alloted comments per hour or day.  Please try again later.");
			} else if (req.responseText == "Banned") {
				alert("I'm sorry, this account has been disabled due to one or more TOS violations.");
			} else {
				alert("Comment sent!  Thanks!");
				var cc = document.getElementById("ccount_" + gExtra[0]);
				if (cc) cc.innerHTML = parseInt(cc.innerHTML) + 1;
			}
			sc(gExtra[0], gExtra[1], "close");
		} else {
			alert("Server error, unable to send comment.  Please tell the site admin with specifics about what you did.");
		}
		req = false;
	}
}

function processCommentGet() {
	if (req.readyState == 4) {
		if (req.status == 200) {
			if (req.responseText == "Error") {
				alert("Invalid input.  Please tell the site admin with specifics about what you did.");
			}
			var tmp = new Array(gExtra[0], gExtra[1], req.responseText);
			req = false;
			sc(tmp[0], tmp[1], tmp[2]);
		} else {
			alert("Server error, unable to get comments.  Please tell the site admin.");
		}
		req = false;
	}
}

function doLogout(id) {
	if (! req == false) { doFail(); return; }
	sendServerRequest(script, processLogout, "mode=logout");
	cleanComments(id);
}

function processLogout() {
	if (req.readyState == 4) {
		if (req.status == 200) {
			if (req.responseText == "Error") {
				alert("Invalid input.  Please tell the site admin with specifics about what you did.");
			} else {
				alert("You have been logged out.");
			}
		} else {
			alert("Server error, unable to send comment.  Please tell the site admin.");
		}
		req = false;
	}
}

function getDocDim() {
	// Thanks http://www.quirksmode.org/ !
	var a = new Array(); // 0:x, 1:y, 2:yScroll
	if (self.innerHeight) // all except Explorer
	{
		a[0] = self.innerWidth;
		a[1] = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight)	// Explorer 6 Strict Mode
	{
		a[0] = document.documentElement.clientWidth;
		a[1] = document.documentElement.clientHeight;
	} else if (document.body) // other Explorers
	{
		a[0] = document.body.clientWidth;
		a[1] = document.body.clientHeight;
	}
	if (self.pageYOffset) { // all except Explorer
		a[2] = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
		a[2] = document.documentElement.scrollTop;
	} else if (document.body) { // all other Explorers 
		a[2] = document.body.scrollTop;
	}
	return a;
}

function so(id, code) {
	if (! req == false) { doFail(); return; }
	document.getElementById("floatDiv").style.display='';
	doResize();
			
	scrollTimer=setInterval('doMove();', 80);
	
	sendServerRequest(script, processDataReceive, "mode=g&id=" + id + "&r=" + Math.round(Math.random() * 100000));
	document.getElementById("pleaseWaitMsg").innerHTML = "Loading data, please wait...";
	document.getElementById("pleaseWait").style.display="";
	document.getElementById("floatDivContent").style.display="none";
	lastId = id;
	clearAllOptions();
	document.getElementById("desc").options.length = 0;
	if (code == 1) { // Unknown category link
		document.getElementById("topMessage").innerHTML = "Please help us find a category for this freebie by filling out this form!  Your feedback will be combined with that of other users to keep Freebie Finder accurate.";
	} else { // Fix Me link
		document.getElementById("topMessage").innerHTML = "Thank you for your help!  Your feedback will be combined with that of other users to keep Freebie Finder accurate.";
	}
}

function hideOptions(tmp) {
	if (tmp == 1) {
		var f = false;
		for(var a = 0; a < allCountries.length; a++) {
			if (document.getElementById(allCountries[a]).checked) f = true;
		}
		for(var a = 0; a < allCats.length; a++) {
			if (document.getElementById("sel_" + allCats[a]).checked) f = true;
		}
		if (document.getElementById("desc").selectedIndex > 0 || document.getElementById("brokenFreebie").selectedIndex > 0) f = true;
		if (f) {
			if(! confirm("Are you sure you wish to close the feedback window?  You will lose any feedback that you have not sent.")) return;
		}
	}
	
	document.getElementById("floatDiv").style.display="none";
	document.getElementById("floatDivContent").style.display="none";
	scrollTimer=clearInterval(scrollTimer);
}

function doFail() {
	alert("Server busy.  Please try again in just a second.");
	failCount++;
	if (failCount > 2) req = false;
}

function processDataReceive() {
	if (req.readyState == 4) {
		if (req.status == 200) {
			if (req.responseText == "Error") {
				alert("Ajax error.  Please report this to the site admin.");
				hideOptions();
			} else if (req.responseText == "Not found") {
				alert("Freebie not found in database.  Please report this to the site admin.");
				hideOptions();
			} else {
				var lines = req.responseText.split("\n");
				if (lines.length < 2) {
					alert("Parse error.  Please report this to the site admin.");
					hideOptions();
					return;
				}
				document.getElementById("freebieLink").setAttribute("href", lines[0]);
				var descs = lines[2].split('|');
				var d = document.getElementById("desc");
				d.options[d.options.length] = new Option("No Opinion",-1);
				for(var a = 0; a < descs.length; a++) {
					if (descs[a] != "") {
						var thisD = descs[a].split('(&)');
						if (a == 0) document.getElementById("inlineDesc").innerHTML = thisD[0];
						if (thisD[0].length > 95) thisD[0] = thisD[0].substring(0,95) + "...";
						d.options[d.options.length] = new Option(thisD[0], thisD[1]);
					}
				}
				document.getElementById("pleaseWait").style.display="none";
				document.getElementById("floatDivContent").style.display="";
			}
		} else {
			alert("Server error.  Please try again in a few minutes.");
			hideOptions();
		}
		req = false;
	}
}

function processDataSend() {
	if (req.readyState == 4) {
		if (req.status == 200) {
			if (req.responseText == "Error") {
				alert("Id error.  Please tell the site admin.");
			} else if (req.responseText == "Change Limit") {
				alert("Unable to save changes: you may only edit any given freebie twice.  If there is a problem, please contact us.");
			}
		} else {
			alert("Server error, unable to send feedback.  Please tell the site admin.");
		}
		document.getElementById("pleaseWait").style.display="none";
		document.getElementById("floatDivContent").style.display="";
		req = false;
		hideOptions();
	}
}

function doMove() {
	var a = document.getElementById("floatDiv");
	var dim = getDocDim();
	if (a.style.display == "none") { scrollTimer=clearInterval(scrollTimer); return; }
	if (parseInt(a.style.top) != parseInt(dim[2] + Math.max((dim[1] - Math.min(dim[1] - 40, 600)) / 2, 5))) {
		var dist = (dim[2] + Math.max((dim[1] - Math.min(dim[1] - 40, 600)) / 2, 5)) - parseInt(a.style.top);
		if (isNaN(dist)) dist = 0;
		a.style.top = (parseInt(a.style.top) + (dist / 4.0)) + "px";
		a.style.width = Math.min(dim[0] - 40, 700) + "px";
		a.style.height = Math.min(dim[1] - 40, 600) + "px";
		a.style.left=(dim[0] - (Math.min(dim[0] - 40, 700)))/2 + "px";
	}
}

function doResize() {
	var a = document.getElementById("floatDiv");
	if (a.style.display != "none") {
		var dim = getDocDim();
		var a = document.getElementById("floatDiv");
		a.style.top=(dim[2] + Math.max((dim[1] - Math.min(dim[1] - 40, 600)) / 2, 5)) + "px";
		a.style.width = Math.min(dim[0] - 40, 700) + "px";
		a.style.height = Math.min(dim[1] - 40, 600) + "px";
		a.style.left=(dim[0] - (Math.min(dim[0] - 40, 700)))/2 + "px";
	}
}

function sendFeedback() {
	if (! req == false) { doFail(); return; }
	var out = "";
	for(var a = 0; a < allCountries.length; a++) {
		if (document.getElementById(allCountries[a]).checked) out += "&" + allCountries[a] + "=true";
	}
	for(var a = 0; a < allCats.length; a++) {
		if (document.getElementById("sel_" + allCats[a]).checked) out += "&" + allCats[a] + "=true";
	}
	var d = document.getElementById("desc");
	out += "&desc=" + d.options[d.selectedIndex].value;
	out += "&broken=" + document.getElementById("brokenFreebie").selectedIndex;
	
	var rating = 0;
	for (var i=1;i<=5;i++) {
		if (document.getElementById("rating" + i).checked) rating = i;
	}
	out += "&rating=" + rating;
	
	sendServerRequest(script, processDataSend, "mode=s&id=" + lastId + out + "&r=" + Math.round(Math.random() * 100000));
	
	document.getElementById("pleaseWaitMsg").innerHTML = "Sending your feedback to the server.  Thanks!";
	document.getElementById("pleaseWait").style.display="";
	document.getElementById("floatDivContent").style.display="none";
}

function clearAllOptions() {
	for (var i = 0; i < allCountries.length; i++) {
		document.getElementById(allCountries[i]).checked = false;
	}
	
	for (var i = 0; i < allCats.length; i++) {
		document.getElementById("sel_" + allCats[i]).checked = false;
	}
	
	document.getElementById("brokenFreebie").selectedIndex = 0;
	document.getElementById("rating3").checked = true;
}

function makePost(ar)
{
	var pairs = new Array();
	for (var i = 0; i < ar.length; i+=2) {
		pairs.push(ar[i] + "=" + encodeURIComponent(ar[i+1]));
	}
	return pairs.join("&");
}

function sendServerRequest(url, pFunction, query, extra) {
	req = false;
	failCount = 0;
	if(window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
	} else if(window.ActiveXObject) {
		try {
			 req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}
	if(req) {
		req.open("post", url, true);
		req.onreadystatechange = pFunction;
		gExtra = false;
		if (extra) gExtra = extra;
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		req.send(query);
	}
}
