var AJAX_SAVE_TIMEOUT = 45;
var ajaxpath = "ajax.php";
var iComment = 0;



/**********************************************************************************************************************
***********************************************************************************************************************
Common Functions
***********************************************************************************************************************
**********************************************************************************************************************/

function changepage(p) {
	window.location.hash = "#" + qs_replace("page", p, replace(window.location.hash, "#", ""));
}


function cancel(url) {
	if (!bConfirmCancel || confirm("Are you sure you want to cancel?")) {
		location.href = url;
	}
}

function resetsearch() {
	$("#formSearch input[type=text]").val("");
	$("#formSearch select").selectOptions("", true);
}


function sort(on, defaultsort, defaultdesc) {
	var hash = window.location.hash
	
	var cursort = qs_get("sort", hash);
	if (cursort=="") cursort = defaultsort;
	
	var curdesc = parseInt(qs_get("desc", hash));
	if (curdesc!=1 && curdesc!=0) curdesc = defaultdesc;
	
	var newdesc = defaultdesc;
	if (newdesc!=1 && newdesc!=0) newdesc = 0;
	
	if (cursort==on) {
		newdesc = Math.abs(curdesc-1);
	}
	
	hash = qs_replace("sort", on, hash);
	hash = qs_replace("desc", newdesc, hash);
	hash = qs_replace("page", 1, hash);
	
	window.location.hash = hash;
}


function checkall() {
	var checked = ($("#actionCheckAll:checked").get(0)!=null);
	if (checked) {
		$("input[name^=actionCheck]").attr("checked", "checked");
	} else {
		$("input[name^=actionCheck]").removeAttr("checked");
	}
}


function massaction(objtypeid, callbackfunc) {
	var action = $("#massaction").val();
	var pieceid = 0;
	var ids = "";
	$("#massaction option").removeAttr("selected");
	$("#massaction option:first").attr("selected", "selected");
	if (action!="") {
		if ($("input[name^=actionCheck]:checked").get(0) == null) {
			alert("You must select something to perform a mass action.");
			return(false);
		}
		if (action=="del") {
			if (!confirm("Are you sure you want to delete everything selected?")) return(false);
		} else if (action=="removeallcats") {
			if (!confirm("Are you sure you want to remove all categories from everything selected?")) return(false);
		} else {
			var aParts = action.split(";");
			if (aParts.length==2) {
				action = aParts[0];
				pieceid = aParts[1];
			}
		}
		
		// gather the ids
		$("input[name^=actionCheck]:checked").each(function() {
			ids += (ids=="" ? "" : ",") + replace($(this).attr("id"), "actionCheck", "");
		});
		
		$.post(ajaxpath, {
				method:			"massaction"
				, ids:			ids
				, massaction:	action
				, objtypeid:	objtypeid
				, subid:		pieceid
				, _ct:			new Date().getTime()
			}, function(xml) {
				oBoxInfo.hide();
				if (parseInt($("errorcode", xml).text())>0) {
					oBoxInfo.doall($("msg", xml).text() + closelink("oBoxInfo"), "infoBoxGreen", "infoBoxRed", 5000);
				} else {
					callbackfunc();
				}
			});
	}
}




/**********************************************************************************************************************
***********************************************************************************************************************
Utility Functions
***********************************************************************************************************************
**********************************************************************************************************************/

function replace(string, text, by) {
	// Replaces all occurances of text with by in string
    
	var strLength = string.length;
	var txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) {
		return string;
	}
    
	var i = string.indexOf(text);
	if ((!i) && (text != string.substring(0,txtLength))) {
		return string;
	}
    if (i == -1) {
		return string;
	}
    
	var newstr = string.substring(0,i) + by;
    if (i+txtLength < strLength) {
        newstr += replace(string.substring(i+txtLength,strLength),text,by);
	}

    return newstr;
}


function formatCurrency(num, colornegative) {
	num = num.toString().replace(/\$|\,/g,'');
	if (isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if (cents<10)
	cents = "0" + cents;
	for (var i=0; i<Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0, num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));
	return (((!sign && colornegative) ? '<span class="red">' : '') + ((sign) ? '' : '-') + '$' + num + '.' + cents + ((!sign && colornegative) ? '</span>' : ''));
}


function lpad(string, len, padchar) {
	try {
		while (string.length < len) {
			string = padchar + string;
		}
	}
	catch(e) {
		alert("Bad params to lpad("+string+","+len+","+padchar+")");
	}
	return(string);
}


function insertAtCursor(myField, myValue) {
	if (document.selection) {
		// IE support
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	} else if (myField.selectionStart || myField.selectionStart == '0') {
		// MOZILLA/NETSCAPE support
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
	} else {
		// no support, add at the end
		myField.value += myValue;
	}
}


function isDefined(o) {
	return (!(o==null || typeof o == "null" || o == undefined || typeof o == "undefined"));
}


function isEmail(e) {
	var regEmail = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
	return (regEmail.test(e));
}


function getKey(e) {
	return (e.which ? e.which : ((window.event) ? event.keyCode : e.keyCode));
}


function ctrlonly(e) {
	var kAlt = false;
	var kCtrl = false;
	var kShift = false;
	var kMeta = false;
    e = (e) ? e : (window.event) ? window.event : "";
    if (e) {
        if (e.modifiers) {
        	kAlt = e.modifiers & Event.ALT_MASK;
        	kCtrl = e.modifiers & Event.CONTROL_MASK;
        	kShift = e.modifiers & Event.SHIFT_MASK;
        	kMeta = e.modifiers & Event.META_MASK;
        } else {
        	kAlt = e.altKey;
        	kCtrl = e.ctrlKey;
        	kShift = e.shiftKey;
        	kMeta = false;
        }
    }
    return (!kAlt && kCtrl && !kShift && !kMeta);
}


function isPaste(e) {
    return (getKey(e)==118 && ctrlonly(e));
}


function isCopy(e) {
    return (getKey(e)==99 && ctrlonly(e));
}


function isCut(e) {
    return (getKey(e)==120 && ctrlonly(e));
}




/**********************************************************************************************************************
***********************************************************************************************************************
Framework Functions
***********************************************************************************************************************
**********************************************************************************************************************/

function closelink(boxname) {
	return("<br /><div align=\"center\"><a href=\"#\" onclick=\"" + boxname + ".hide();return(false);\">Close</a></div>");
}

var _loggingIn = false;
function login() {
	if (!_loggingIn) {
		$('#btnLogin').attr('disabled', 'disabled');
		_loggingIn = true;
		oBoxLogin.doall("Logging in...", "infoBoxRed infoBoxGreen", "", 10000);
		$.post(ajaxpath, {method: "login", login: $("#loginField").val(), password: $("#passwordField").val(), _ct: new Date().getTime()}, function(xml) {
			if ($("result", xml).text()=="1") {
				window.location.reload();
			} else {
				oBoxLogin.doall("Logging in... Invalid credentials.", "infoBoxGreen", "infoBoxRed", 2000);
				$('#btnLogin').removeAttr('disabled');
				_loggingIn = false;
			}
		});
	}
}


function logout() {
	$.post(ajaxpath, {method: "logout", _ct: new Date().getTime()}, function(xml) {
		window.location.reload();
	});
}


function workmodehelp() {
	if (isWorkMode()) {
		oBoxInfo.doall("Work Mode is ON.  Content that is flagged as NSFW (Not Safe For Work) will be hidden.<br /><div align=\"center\"><a href=\"#\" onclick=\"oBoxInfo.hide();return(false);\">Close</a></div>", "infoBoxRed infoBoxGreen", "infoBoxGreen", 10000);
	} else {
		oBoxInfo.doall("Work Mode is OFF.  Content that is flagged as NSFW (Not Safe For Work) will be visible.<br /><div align=\"center\"><a href=\"#\" onclick=\"oBoxInfo.hide();return(false);\">Close</a></div>", "infoBoxRed infoBoxGreen", "infoBoxRed", 10000);
	}
}


function toggleNSFW() {
	if (isWorkMode()) {
		// turn work mode off by setting a cookie with the value of 0
		var now = new Date();
		now.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 365)
		setCookie("workmode", 0, now, "/");
	} else {
		// turn work mode on by deleting the cookie
		deleteCookie("workmode");
	}
	window.location.reload();
}


function isWorkMode() {
	var workmode = true;
	if (getCookie("workmode")==0) {
		workmode = false;
	}
	return(workmode);
}




/**********************************************************************************************************************
***********************************************************************************************************************
Querystring Functions
***********************************************************************************************************************
**********************************************************************************************************************/

function qs_get(k, qs) {
	// return the value of the selected "querystring" key (usually from a hash)
	qs = replace(qs, "#", "");
	var r = "";
	var aQ = qs.split("&");
	var l = aQ.length;
	var bFound = false;
	for (var i=0; i<l; i++) {
		var aKV = aQ[i].split("=");
		if (aKV.length==2) {
			if (aKV[0] == k && !bFound) {
				r = aKV[1];
			}
		}
	}
	return(r);
}


function qs_add(kv, qs) {
	// appends the supplied key-value pair $kv to the querystring if it doesn't already exist
	qs = replace(qs, "#", "");
	return (qs=="" ? kv : qs + "&" + kv);
}


function qs_remove(k, qs) {
	// removes the key-value pair specified by the key $k from the querystring if it exists
	qs = replace(qs, "#", "");
	var newqs = "";
	if (k!="") {
		var aQ = qs.split("&");
		var l = aQ.length;
		for (var i=0; i<l; i++) {
			var aKV = aQ[i].split("=");
			if (aKV.length==2) {
				if (aKV[0] != k) {
					newqs = qs_add(aQ[i], newqs);
				}
			}
		}
	}
	return newqs;
}


function qs_replace(k, v, qs) {
	// replaces the specified querystring variable $k (if it exists) with a new value $v.  If it doesn't exist, it adds it
	qs = replace(qs, "#", "");
	var newqs = "";
	if (k!="") {
		var aQ = qs.split("&");
		var l = aQ.length;
		var bFound = false;
		for (var i=0; i<l; i++) {
			var aKV = aQ[i].split("=");
			if (aKV.length==2) {
				if (aKV[0] == k && !bFound) {
					newqs = qs_add(k + "=" + v, newqs);
					bFound = true
				} else {
					newqs = qs_add(aQ[i], newqs);
				}
			}
		}
		if (!bFound) {
			newqs = qs_add(k + "=" + v, newqs);
		}
	}
	return newqs;
}
