/* ******************************PREVIOUSLY IN _SCRIPT.JS************************************************** */
function inArray(str,arr){
	for(i=0;i<arr.length;i++){
		if(arr[i]==str)return 1;
	}
	return 0;
}
function intval(str){
	str=parseInt(str);
	if(isNaN(str))str=0;
	return str;
}

// ======================================================================= Begin Input Field Scripts
// JB: Notes
// swapInputBg and resetInputBg are switches the background image of example text within a form input field 
// when that field gets "focus" (triggered by the onFocus() call), 
// thus onFocus() the bg is changed to white and onBlur() the 
// "if" the field remained empty the bg will reset to the bg of the text, 
// "if" the field has any data it is left alone.

function swapInputBg(elemId) {
	
	var elemID = elemId.toString();
	var elemVal = document.getElementById(elemID).value;
	var elemClassName = document.getElementById(elemID).className.toString();

	var s = elemClassName.replace('_on',"");
	document.getElementById(elemID).className = elemClassName = s;

	if(elemClassName.indexOf('_on'))  {
		if(elemVal.length >= 0) {
			document.getElementById(elemID).className = elemClassName + "_on";
		}
	} else {
	document.getElementById(elemID).className = elemClassName + "_on";
	}
}

function resetInputBg(elemId) {

	var elemID = elemId.toString();
	var elemVal = document.getElementById(elemID).value;
	var elemClassName = document.getElementById(elemID).className.toString();
	
	var s = elemClassName.replace('_on',"");
	document.getElementById(elemID).className = elemClassName = s;
	
	if(elemVal.length > 0)  {
		document.getElementById(elemID).className = elemClassName + "_on"
	}
}
// ======================================================================= End Input Field Scripts


function MM_findObj(n, d) { //v4.01
  var p,i,x;if(!n)return;  if(!d) d=document; 
  if(d.contentDocument)d=d.contentDocument;
  if(d.document)d=d.document;
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) x=d.all[n]; 
  if(d.forms){for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];}
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function getIframeDocument(ifrId){
	var oIframe = document.getElementById(ifrId);
    var oDoc = oIframe.contentWindow || oIframe.contentDocument;
    if (oDoc.document) {
        oDoc = oDoc.document;
    }
	return oDoc;
}
function findObj(n,d){
	return MM_findObj(n,d);
}
function WM_netscapeCssFix() {
    document.location = document.location;
}
 
function WM_netscapeCssFixCheckIn() {
  if ((navigator.appName == 'Netscape') && (parseInt(navigator.appVersion) == 4)) {
   if (typeof document.WM == 'undefined'){
      document.WM = new Object;
    }
    if (typeof document.WM.WM_scaleFont == 'undefined') {
      document.WM.WM_netscapeCssFix = new Object;
    }
    window.onresize = WM_netscapeCssFix;
  }
}
 
WM_netscapeCssFixCheckIn();

function winop(filename,width,height){
	params = "height="+height
		   + " ,width="+width
		   + " ,top=0"
		   + " ,left=0"
		   + " ,scrollbars=1"
		   + ", resizable=1"
	window.open(filename,"preview",params);
}
function openFullScreen(url){
	var dims=getWindowDims();
	winop(url,dims[0],dims[1]);
}
function getWindowDims(){
	var w; var h
	if(window.screen.width){
		return [window.screen.width,window.screen.height];
	}
	if(window.innerWidth){
		return [window.innerWidth,window.innerHeight];
	}else if(document.getElementsByTagName('body')[0].clientWidth){
		return [document.getElementsByTagName('body')[0].clientWidth, document.getElementsByTagName('body')[0].clientHeight]
	}
	return [0,0];
} 
function getDocDims(){
	return [document.body.clientWidth,document.body.clientHeight];
}
function preload() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=preload.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function rollOut(){
	MM_swapImgRestore();
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function rollOver(imgName,imgSrc,reset){
	if(reset){//this will allow for later natural resizing of the image onload
		if(getDomObj(imgName)){
			getDomObj(imgName).removeAttribute("width");
			getDomObj(imgName).removeAttribute("height");
		}
	}
	MM_swapImage(imgName,'',imgSrc,1);
}

function stristr(needle,haystack){
	needle = new String(needle).toLowerCase();
	haystack = new String(haystack).toLowerCase();
	return haystack.indexOf(needle)>-1?1:0;
}

function endswith(str,substr){
	if(typeof(str)!="string")str=new String(str);
	if(typeof(substr)!="string")substr=new String(substr);
	if(!str || !substr)
		return 0;
	if(str.substring(str.length-substr.length).toLowerCase() == substr.toLowerCase())
		return 1;
	return 0;
}
function startswith(str,substr){
	if(typeof(str)!="string")str=new String(str);
	if(typeof(substr)!="string")substr=new String(substr);
	if(!str || !substr)
		return 0;
	if(str.substring(0,substr.length).toLowerCase() == substr.toLowerCase())
		return 1;
	return 0;
}
function strto(str,subs){//--return all of $str up to $substr non-inclusive
	if(!stristr(subs,str)){
		return str;
	}
	return str.substring(0,str.indexOf(subs));
}
function strfrom(str,subs){//--return all of $str after $substr non-inclusve
	if(!stristr(subs,str)){
		return "";
	}
	return str.substring(str.indexOf(subs)+subs.length);
}
function strfromto(str, from, to){
	if(!(subs=strfrom(str,from)))return "";
	return strto(subs,to);
}

function valid_email(val){
	return val.match(/^[\w\-\.]{1,255}@[\w\-\.]{2,255}\.\w{2,5}$/)
}
function input_hidden(name,value){
	if(!value)value="";
	value=value.replace(/"/g,"&quot;");
	return '<input type="hidden" name="'+name+'" value="'+value+'" />';
}
function refer(return_str){
	if(return_str)
		return location.href.toString().base64_encode();
	return input_hidden("refer",refer(1));
}
function input_text(name,value,size,maxlength,addl){
	if(!value)value="";
	if(!size)size="20";
	if(!maxlength)maxlength="255";
	if(!addl)addl="";
	var params=new Array(
		'type="text"', 'name="'+name+'"','id="'+name+'"',
		'value="'+value+'"','maxlength="'+maxlength+'"',
		'size="'+size+'"',	'class="textinput"',
		addl
		);
	return '<input '+params.join(" ")+'/>';
}
function getVal(frmObj,getSelVal){
	if(!frmObj)return;
	if(typeof(frmObj.type)=="undefined"){
		if(typeof(frmObj.length)!="undefined"){
			frmObj.type="radio";
		}
	}
	var t=frmObj.type;
	if(stristr("text",t)||stristr("password",t))
		return trim(frmObj.value);
	if(stristr("radio",t)){
		for(i=0;i<frmObj.length;i++)
			if(frmObj[i].checked) return frmObj[i].value;
		return false;
	}
	
	if(stristr("checkbox",t))
		return frmObj.checked;
		
	if(stristr("select",t)){
		if(getSelVal)
			return selectedValue(frmObj.name);
		else
			return selectedText(frmObj.name);
	}
	
	return trim(frmObj.value);
}

function getValByName(frmObjName,targFormName){
	var obj=findObj(frmObjName);
	if(targFormName){
		var tf=findObj(targFormName);
		if(tf.elements)
			if(tf.elements[frmObjName])
				obj=tf.elements[frmObjName];
	}
	return getVal(obj);
}
function setValByName(frmObjName,value){
//sets, checks or selects a value on any form field type
	value=new String(value);
	var frmObj=findObj(frmObjName);
	if(!frmObj)return;
	if(typeof(frmObj.type)=="undefined")
		if(typeof(frmObj.length)!="undefined")
			frmObj.type="radio";
	var t=frmObj.type;
	if(stristr("file",t)){
		try{
			frmObj.value=value;
			return;
		}catch(e){
			return;
		}
	}
	if(stristr("checkbox",t)){
		if(!value.length)value=false;
		if(value=="0")value=false;
		frmObj.checked=value?true:false;
		return;
	}
	if(stristr("radio",t)){
		selectRadio(frmObjName,value);
		return;
	}
	if(stristr("select",t)){
		selectValue(frmObjName,value);
		return;
	}
	if(typeof(frmObj.value)!="undefined"){
		frmObj.value=value;
		return;
	}
}
function radioVal(frmObjName){
	frmObj=findObj(frmObjName);
	for(i=0;i<frmObj.length;i++){
		if(frmObj[i].checked)
			return frmObj[i].value;
	}
	return false;
}
function selectRadio(frmObjName,value){
	frmObj=findObj(frmObjName);
	if(!frmObj)return;
	if(typeof(frmObj.length)=="undefined")return;
	for(i=0;i<frmObj.length;i++){
		if(frmObj[i].value==value){
			frmObj[i].checked=true;
			return;
		}
	}
}
function checkBox(frmObj){
	selectCheck(frmObj);
}
function unCheckBox(frmObj){
	selectCheck(frmObj,1);
}
function selectCheck(frmObj,uncheck){
	if(typeof(frmObj)!="object")
		frmObj=findObj(frmObj);
	if(!frmObj)return;
	frmObj.checked=(!uncheck);
}
function toggleCheck(frmObj){
	if(typeof(frmObj)!="object")
		frmObj=findObj(frmObj);
	if(!frmObj)return;
	frmObj.checked=!frmObj.checked;
}
function isChecked(checkObj){
	if(typeof(checkObj)!="object")
		checkObj=findObj(checkObj);
	if(!checkObj)return 0;
	if(typeof(checkObj.checked)=="undefined")return 0;
	return checkObj.checked;
}
function selectedValue(fieldName){
	fieldName=findObj(fieldName);
	if(typeof(fieldName)=="undefined")return "";
	if(typeof(fieldName.selectedIndex)=="undefined")return "";
	return fieldName[fieldName.selectedIndex].value;
}
function selectedText(fieldName,ignoreDash){
	fieldName=findObj(fieldName);
	if(typeof(fieldName)=="undefined")return "";
	if(typeof(fieldName.selectedIndex)=="undefined")return "";
	if(ignoreDash && fieldName[fieldName.selectedIndex].text.charAt(0)=="-")return "";
	return fieldName[fieldName.selectedIndex].text;
}

function selectedValue(fieldName){
	if(typeof(fieldName)!="object")
		fieldName=findObj(fieldName);
	if(typeof(fieldName)=="undefined")return "";
	if(typeof(fieldName.selectedIndex)=="undefined")return "";
	if(fieldName.selectedIndex==-1)return "";
	return fieldName[fieldName.selectedIndex].value;
}
function selectedText(fieldName,ignoreDash){
	if(typeof(fieldName)!="object")
		fieldName=findObj(fieldName);
	if(typeof(fieldName)=="undefined")return "";
	if(typeof(fieldName.selectedIndex)=="undefined")return "";
	if(fieldName.selectedIndex==-1)return "";
	if(ignoreDash && fieldName[fieldName.selectedIndex].text.charAt(0)=="-")return "";
	return fieldName[fieldName.selectedIndex].text;
}
function selectValue(fieldName,value){
	fieldName=findObj(fieldName);
	if(typeof(fieldName)=="undefined")return ;
	if(typeof(fieldName.selectedIndex)=="undefined")return;
	for(i=0;i<fieldName.options.length;i++){
		if(typeof(value)=="object"){//list of values
			if(in_array(fieldName.options[i].value,value)){
				fieldName.options[i].selected=true;
				continue;
			}
		}
		if(fieldName.options[i].value==value){
			fieldName.options[i].selected=true;
			return;
		}
	}
}
function selectText(fieldName,value){//chooses an option in a select list
	fieldName=findObj(fieldName);
	if(typeof(fieldName)=="undefined")return ;
	if(typeof(fieldName.selectedIndex)=="undefined")return;
	for(i=0;i>fieldName.options.length;i++){
		if(typeof(value)=="object"){//list of values
			if(in_array(fieldName.options[i].text,value)){
				fieldName.options[i].selected=true;
				continue;
			}
		}
		if(fieldName.options[i].text==value){
			fieldName.options[i].selected=true;
			return;
		}
	}
}

function insertTextToInput( input, insText ) {//---this will insert text into an input at the current curosr position
	if(!(input=getDomObj(input)))return;
	input.focus();
	if( input.createTextRange ) {
		document.selection.createRange().text += insText;
	} else if( input.setSelectionRange ) {
		var len = input.selectionEnd;
		input.value = input.value.substr( 0, len )	+ insText + input.value.substr( len );
		input.setSelectionRange(len+insText.length,len+insText.length);
	} else { 
		input.value += insText; 
	}
}

function scrollToSelected(fieldName){//--doesn't work
	fieldName=findObj(fieldName);
	if(typeof(fieldName)=="undefined")return ;
	if(typeof(fieldName.selectedIndex)=="undefined")return;
	if(typeof(fieldName.options)=="undefined")return;
	for(i=0;i<fieldName.options.length;i++){
		if(fieldName.options[i].selected==true){
			fieldName.options[i].selected=false;
			fieldName.options[i].selected=true;
		}
	}
}
function checkAll(formname,checkUnChecked,strMatch){
	frm=findObj(formname);
	for(i=0;i<frm.elements.length;i++){
		var el=frm.elements[i];
		if(typeof(el.name)=="undefined")continue;
		if(typeof(el.type)=="undefined")continue;
		if(!el.name || !el.type)continue;
		if(el.type.toLowerCase().indexOf("check")==-1)continue;
		if(strMatch){
			if(el.name.indexOf(strMatch)==-1)
				continue;
		}
		el.checked=checkUnChecked?true:false;
	}
}
function getSelectedCheckCount(frmObj,strMatch){
	if(typeof(frmObj)!="object")
		frmObj=findObj(frmObj);
	if(!frmObj)return;
	var ret=0;
	for(i=0;i<frmObj.elements.length;i++){
		var el=frmObj.elements[i];
		var type=el.type;
		var name=el.name;
		if(!type || !name)continue;
		if(type.toLowerCase().indexOf("check")==-1)continue;
		if(typeof(el.checked)=="undefined")continue;
		if(strMatch){
			if(name.indexOf(strMatch)==-1){
				continue;
			}
		}
		if(el.checked)ret++;
	}
	return ret;
}
function getSelectedCheckIds(frmObj,strMatch){
		if(typeof(frmObj)!="object")
		frmObj=findObj(frmObj);
	if(!frmObj)return;
	var ret=new Array();
	for(i=0;i<frmObj.elements.length;i++){
		var el=frmObj.elements[i];
		var type=el.type;
		var name=el.name;
		if(!type || !name)continue;
		if(type.toLowerCase().indexOf("check")==-1)continue;
		if(typeof(el.checked)=="undefined")continue;
		if(strMatch){
			if(name.indexOf(strMatch)==-1){
				continue;
			}
		}
		if(el.checked)ret[ret.length]=el.name;
	}
	return ret;
}
function validEmail(emStr){
	return valid_email(emStr);
}
function validEmailValue(fieldname){
	return valid_email(getValByName(fieldname));
}

function lc(str){
	if(typeof(str)!="string")return str;
	return str.toLowerCase();
}


function ucfirst(str){
	var ret = "";
	var let=str.substring(0,1).toUpperCase();
	return let+str.substring(1,str.length);
}

function ucwords(str){
	var ret = new Array();
	words = str.split(" ");
	for(i=0;i<words.length;i++)
		ret[ret.length]=ucfirst(words[i]);
	return ret.join(" ");
}

function uspace(str){
	return str.replace(/_/g," ");
}

function stripSlashes(str){
	return str.replace(/\\/g,"");
}
function strip_tags(str){
	if(!str)return "";
	var reg=/<([^>])+>/g;
	return str.replace(reg,"");
}
function stristr(needle,haystack){
	needle=needle.toString().toLowerCase();
	haystack=haystack.toString().toLowerCase();
	if(haystack.indexOf(needle)>-1)return 1;
	return 0;
}

function trim(str){
	if(typeof(str)=="undefined")return "";
	return str.toString().replace(/(^\s+|\s+$)/g,"");
}

function numsonly(str){
	return str.replace(/[^\d\.]+/g,"");
}

function nobadchars(str){
	return str.replace(/\W+/g,"");
}
function alphanum(str){
	return nobadchars(str);
}

function limitCharLength(str,len){
	return str.substring(0,len);
}

function wordsonly(str){
	return str.replace(/[^a-zA-Z-\s]+/g,"");
}
function email_format(str){
	return str.replace(/[^_a-zA-Z\-0-9@\.]+/g,"");
}
function array_diff(arr1, arr2){ //returns array w/ all values of arr1 not in arr2
	var ret = new Array();
	for(var i=0;i < arr1.length;i++){
		if(!in_array(arr1[i], arr2)) ret[ret.length]=arr1[i];
	}
	return ret;
}

function array_keys(arr){
	var ret = new Array();
	for(e in arr)
		ret[ret.length]=e;
	return ret;
}

function array_search(needle,haystack){
	for(var i=0;i< haystack.length;i++){
		if(needle==haystack[i])return i;
	}
	return false;
}

function array_sum(arr){
	ret = 0;
	for(var i=0;i< arr.length;i++){
		var item = parseFloat(arr[i]);
		ret+=item;
	}
	return ret;
}
function array_unique(arr){
	var ret = new Array();
	for(var i=0;i< arr.length;i++)
		if(!in_array(arr[i],ret)) ret[ret.length]=arr[i];
	return ret;
}
function array_values(arr){
	var ret = new Array();
	for(e in arr)
		ret[ret.length]=arr[e];
	return ret;
}
function array_append(oldarr,appendarr){
	for(i=0;i<appendarr.length;i++){
		oldarr[oldarr.length]=appendarr[i];
	}
	return oldarr;
}
function in_array(needle,haystack){
	for(var i=0;i< haystack.length;i++)
		if(needle==haystack[i])return 1;
	return 0;
}
function trim_arr(arr){
	var tmp=new Array();
	for(i=0;i<arr.length;i++){
		if(arr[i])tmp.push(arr[i]);
	}
	return tmp;
}
function isPartialPath(path){//eg filename
	if(!path)
		return 0;
	if(stristr("/",path))
		return 0;
	if(stristr("\\",path))
		return 0;
	if(path.match(/\.\w+$/))
		return 1;
	return 0;
}
function cleanfilename(path){
	path=path.replace("/[^\w\.\-_]/g",'_');
	return trim(path);
}
function basename(path){
	var sep="";
	if(!path)
		return "";
	if(stristr("/",path))
		sep="/";
	if(stristr("\\",path))
		sep="\\";
	if(!sep){
		//--could be just a partial filename. opera does this
		if(path.match(/\.\w+$/))
			return path
		return "";
	}
	path=path.substring(path.lastIndexOf(sep)+1);
	return path;
}
function bbasename(path){
	if(!path)
		return "";
	if(!stristr(".",path)){
		if(path)
			return path
		return "";
	}
	path=basename(path);
	if(!stristr(".",path)){
		if(path)
			return path
		return "";
	}
	return path.substring(0,path.lastIndexOf("."))
}
function dirname(path){
	var tmp=path.split("/");
	if(tmp[0]=="http:"){
		for(i=0;i<3;i++){
			tmp.shift();//kill scheem&hostname parts
		}
	}
	tmp.pop();
	return "/"+tmp.join("/");
}
function validateCCNum(cardType,cardNum){
	cardType = cardType.toUpperCase();
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType){
		case "VISA":
			return ( (cardLen == 16) && (firstdig == "4"));
		case "AMEX":
			var validNums = "47";
			return ((cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0));
		case "MASTERCARD":
			var validNums = "12345";
			return ((cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0));
		case "DISCOVER":
			return  ((cardLen == 16) && (first4digs == "6011"));
		case "DINERS":
			var validNums = "068";
			return ((cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0));
	}
	return 0;
}

function isValidExpDate(mmyy){
	mmyy=mmyy.split("/");
	if(mmyy[0].charAt(0)=="0")mmyy[0]=mmyy[0].substring(1);
	mo=parseInt(mmyy[0]);yr=parseInt("20"+mmyy[1]);
	if(!mo||isNaN(mo) || !yr ||isNaN(yr) || (mo<1||mo>12))
		return 0;
	var thisYear=new Date().getYear();
	var thisMo=new Date().getMonth();
	if(thisYear>yr)return 0;
	return 1;
}
function isValidExpDate2(mm,yyyy){
	var d=mm+"/"+yyyy.substring(2,4);
	return isValidExpDate(d);
}
function validZip(zipObj){
	if(findObj(zipObj).value.length<5)
		return 0;
	return 1;
}
function validPhone(phoneObj){
	if(findObj(phoneObj).value.length<10)
		return 0
	return 1;
}


function getDateTime(){
	var d = new Date();
	var s="";
	s+=(d.getMonth() + 1) + "/";
	s+=d.getDate() + "/";
	s+=(d.getYear()+(d.getYear()<1000?1900:0))+" ";
	hrs=d.getHours();
	if(hrs>12){
		hrs-=12;
		if(hrs<10)hrs="0"+hrs;
		ampm="PM";
	}else{
		ampm="AM";
	}
	s+=hrs+":" 
	mins=d.getMinutes();
	if(mins<10)mins="0"+mins
	s+=mins+" "+ampm;
	return(s);
}


function gohref(loc,replace){
	if(!replace)location.href=loc;
	else location.replace(loc);
}


function rand(max,min){
	return Math.round((max-min) * Math.random() + min);
}

function input_button(val,eonclick,addl){
	if(!val)val="Submit";
	if(!eonclick)eonclick="void()";
	if(!addl)addl="";
	if(addl)addl=" "+addl;
	return "<input type=\"button\" value=\""+val+"\" class=\"buttoninput\" onclick=\""+eonclick+"\""+addl+" />" ;
}
function createEl(type,attrs){
	var obj=document.createElement(type);
	for(e in attrs){
		attr=e.toLowerCase();
		if(attr=="innerhtml")
			obj.innerHTML=attrs[e];
		else if(attr=="value")
			obj.value=attrs[e];
		else if(attr=="id")
			obj.id=attrs[e];
		else if(attr=="class" || attr=="classname")
			obj.className=attrs[e];
		else
			obj.setAttribute(e,attrs[e]);
	}
	return obj;
}
function getElementsByClassName(oElm,theClass){
	return getElementsByAttribute(getDomObj(oElm),"*","class",theClass);
}
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
    var oCurrent;
    var oAttribute;
    for(var i=0; i<arrElements.length; i++){
        oCurrent = arrElements[i];
		if(strAttributeName.toLowerCase()=="class"){//ie fix for class name
			if(typeof oCurrent.className == "undefined")
				continue;
			else
				oAttribute=oCurrent.className;
		}else{
	        oAttribute = oCurrent.getAttribute(strAttributeName);
		}
        if(typeof oAttribute == "string" && oAttribute.length > 0){
            if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                arrReturnElements.push(oCurrent);
            }
        }
    }
    return arrReturnElements;
}

function getDomObj(lObj){
//accepts a string or actual dom object. will always return dom obj on success or false on failure
	if(typeof(lObj)!="object"){
		if(document.getElementById){
			if((lObj=document.getElementById(lObj)))
				return lObj;
		}
		lObj=findObj(lObj);
	}
	if(typeof(lObj)!="object")return 0;
	if(!lObj)return 0;
	if(typeof(lObj.style)=="undefined")return 0;
	return lObj;
}
function $d(obj){return getDomObj(obj);}
function setInnerHTML(lObj, txt){
	if(!(lObj=getDomObj(lObj)))return 0;
	if(typeof(txt)=="undefined")txt="";
	lObj.innerHTML=txt;
	return 1;
}
function getInnerHtml(lObj){
	if(!(lObj=getDomObj(lObj)))return 0;
	return lObj.innerHTML;
}
function appendHTML(lObj,txt){//--this throws runtime errors in ie with tables. don't know about other elements
	if(!(lObj=getDomObj(lObj)))return 0;
	if(typeof(txt)=="undefined")txt="";
	txt=lObj.innerHTML+txt;
	setInnerHTML(lObj,txt);
	txt="";
}
function getDisp(lObj){
	if(!(lObj=getDomObj(lObj)))return 0;
	var disp=lObj.style.display;
	return (disp=="none"?"none":"block");
}
function setDisp(lObj,disp){
	if(!(lObj=getDomObj(lObj))){return 0;}
	//lObj.style.display=disp;
	
	var nonblocks="a span td tr tbody label select".split(" ");
	var show=(in_array(lObj.tagName.toLowerCase(),nonblocks)?"":"block");
	lObj.style.display=(disp=="none"?"none":show);//set to empty string. doesn't control blocking of element
	return 1;
}
function getVis(lObj){
	if(!(lObj=getDomObj(lObj)))return 0;
	var disp=lObj.style.visibility;
	return (disp=="hidden"?"hidden":"visible");
}
function setVis(lObj,vis){
	if(!(lObj=getDomObj(lObj)))return 0;
	lObj.style.visibility=(vis=="hidden"?"hidden":"visible");
	return 1;
}
function setXY(lObj,x,y){
	if(!(lObj=getDomObj(lObj)))return 0;
	lObj.style.left=x+"px";
	lObj.style.top=y+"px";
}
function setWH(lObj,w,h){
	if(!(lObj=getDomObj(lObj)))return 0;
	lObj.style.height=h+"px";
	lObj.style.width=w+"px";
}
function getOffsetTop(lObj){
	return getOffsetProperty(lObj, 'Top');
}
function getOffsetLeft(lObj){
	return getOffsetProperty(lObj, 'Left');
}
function getOffsetCoords(lObj){
	var x=getOffsetLeft(lObj);
	var y=getOffsetTop(lObj);
	if(!x || isNaN(x))x=0;
	if(!y || isNaN(y))y=0;
	return new Array(x,y);
}
function getOffsetProperty(lObj, property){
	if(!(lObj=getDomObj(lObj)))return 0;
	offsetProperty = 'offset' + property;
	if(typeof(lObj[offsetProperty])=="undefined")return;
	var offsetValue = 0;
	do {
		offsetValue += lObj[offsetProperty];
		lObj = lObj.offsetParent;
	} while (lObj != document.body && lObj != null);
	return offsetValue;
}
function getBorderHeight(lObj){//get height of top+bottom borders
	if(!(lObj=getDomObj(lObj)))return 0;
	if(typeof(lObj.style.borderTopWidth)=="undefined")return 0;
	var ret=0;
	if(!isNaN(height=parseInt(lObj.style.borderTopWidth)))
		ret+=height;
	if(!isNaN(height=parseInt(lObj.style.borderBottomWidth)))
		ret+=height;
	return ret;
}
function getBorderWidth(lObj){//get height of right+left borders
	if(!(lObj=getDomObj(lObj)))return 0;
	if(typeof(lObj.style.borderLeftWidth)=="undefined")return 0;
	var ret=0;
	if(!isNaN(width=parseInt(lObj.style.borderLeftWidth)))
		ret+=width;
	if(!isNaN(width=parseInt(lObj.style.borderRightWidth)))
		ret+=width;		
	return ret;
}
function getOffsetHeight(lObj){//gets offset height and includes border height
	if(!(lObj=getDomObj(lObj)))return 0;
	if(typeof(lObj.offsetHeight)=="undefined")return 0;
	return (lObj.offsetHeight+getBorderHeight(lObj));
}
function getOffsetWidth(lObj){//get offsetWidth and include borders
	if(!(lObj=getDomObj(lObj)))return 0;
	if(typeof(lObj.offsetWidth)=="undefined")return 0;
	return (lObj.offsetWidth+getBorderWidth(lObj));	
}
function setToOffsetSize(lObj){//set the object hard to it's offset height and width so when content changes it doesnt
	if(!(lObj=getDomObj(lObj)))return 0;
	var h=getOffsetHeight(lObj);
	var w=getOffsetWidth(lObj);
	setWH(lObj,w,h);
}
function cimg(src,link_url,addlimg,addllink){
	if(!addlimg)addlimg="";
	if(!addllink)addllink="";
	var ret='<img src="'+src+'" border="0" '+addlimg+' />';
	if(link_url)
		ret='<a href="'+link_url+'" '+addllink+'>'+ret+'</a>';
	return ret;
}
function img(src,link_url,addlimg,addllink){return cimg(src,link_url,addlimg,addllink);}
function resizeImages(containerObj,setWidth,setHeight){
	//resize all imges inside containerObj to be expr(containerObj.offsetWidth-widthOffset)
	//setWidth will override the offset size of containerObj and force images/embeds larger to be this width
	//setHeight will override the offset size of containerObj and force images/embeds larger to be this height
	//also resizes embeds like youtube videos etc.
	containerObj=getDomObj(containerObj);
	if(!containerObj)return;
	if(!setWidth && !setHeight)return;
	var imgs=containerObj.getElementsByTagName("img");
	for(i=0;i<imgs.length;i++){
		if(setWidth){
			if(imgs[i].width>setWidth){
				imgs[i].width=setWidth;
				imgs[i].style.width=setWidth+"px";
			}
		}else{
			imgs[i].style.height='auto';
		}
		if(setHeight){
			if(imgs[i].height>setHeight){
				imgs[i].height=setHeight;
				imgs[i].style.height=setHeight+"px";
			}
		}else{
			imgs[i].style.height='auto';
		}
	}
	var embs=containerObj.getElementsByTagName("embed");
	for(i=0;i<embs.length;i++){
		if(!embs[i].height || !embs[i].width)continue;
		if(setWidth && embs[i].width>setWidth){
			embs[i].height*=Math.round(embs[i].width/setWidth);
			embs[i].width=setWidth;
			if(embs[i].style){
				embs[i].style.height=embs[i].height+"px";
				embs[i].style.width=embs[i].width+"px";
			}
		}
		if(setHeight && embs[i].height>setHeight){
			embs[i].width*=Math.round(embs[i].height/setHeight);
			embs[i].height=setHeight;
			if(embs[i].style){
				embs[i].style.height=embs[i].height+"px";
				embs[i].style.width=embs[i].width+"px";
			}
		}
	}
	var embs=containerObj.getElementsByTagName("object");
	for(i=0;i<embs.length;i++){
		if(!embs[i].height || !embs[i].width)continue;
		if(setWidth && embs[i].width>setWidth){
			embs[i].height*=Math.round(embs[i].width/setWidth);
			embs[i].width=setWidth;
			if(embs[i].style){
				embs[i].style.height=embs[i].height+"px";
				embs[i].style.width=embs[i].width+"px";
			}
		}
		if(setHeight && embs[i].height>setHeight){
			embs[i].width*=Math.round(embs[i].height/setHeight);
			embs[i].height=setHeight;
			if(embs[i].style){
				embs[i].style.height=embs[i].height+"px";
				embs[i].style.width=embs[i].width+"px";
			}
		}
	}
}
/**
 * resize image to best fit in a full screen window
*/
function resizeImageFullScreen(imgObj,restrictWidth,restrictHeight,callBack){
	if(!restrictWidth)restrictWidth=0;
	if(!restrictHeight)restrictHeight=0;
	var maxHeight=(getWindowHeight()-restrictHeight);
	var maxWidth=(getWindowWidth()-restrictWidth)
	if(imgObj.width<maxWidth && imgObj.height<maxHeight)return;
	if(imgObj.height>maxHeight){
		imgObj.height=maxHeight;
	}
	if(typeof(callBack)=="function")callBack();
}

//resize an image; e.g. used at onload event
function resizeImageModif(reff, to_width, to_height) {
	var width, height, to_width, to_height;
	
	width = reff.width;
	height = reff.height;
		
	if(width > 0) {
		if(width >= height) {
			if (to_height>0) {
				//make resize for width and height with fix height to "to_height" and width keep aspect ratio
				reff.height = to_height;
				img_ratio = (to_height / height);
				new_width = (width * img_ratio);
				reff.width = new_width;
				reff.style.marginLeft = (to_width - new_width) / 2 + "px";
			} else {
				//if a new value of height is 0 or less (nothing) then make picture with a fix width to "to_width" and height keep aspect ration.
				//This happen when real width of image is bigger from "to_weight"
				if (to_width < width) {
					reff.width = to_width;
					img_ratio = (to_width / width);
					new_height = (height * img_ratio);
					reff.height = new_height;
				}
			}
		} else {
			reff.width = to_width;
			img_ratio = (to_width / width);
			new_height = (height * img_ratio);
			reff.height = new_height;
			reff.style.marginTop = (to_height - new_height) / 2 + "px";
		}
	} else {
		reff.width = to_width;
		reff.height = to_height;
	}
}
function resizeImage(ref,w,h){return resizeImageModif(ref, w, h);}
function nl(){return String.fromCharCode(10);}
function nl2br(str){
	if(!str)return "";
	if(stristr("<br",str))return str;//already has linebreaks
	if(stristr("<p",str))return str;
	if(stristr("<div",str))return str;
	if(stristr("<table",str))return str; 
	var re=/[\r\n]/g;        
	str=str.replace(re,"<br>");
	return str;
}
function br2nl(str){
	if(!str)return "";
	var re=/<br\s?\/?>[\n\r]?/g;
	return str.replace(re,"\n");
}
function getScrollTop(){//cross browser way to get scrollX/Y property
	if(typeof(window.scrollY)!="undefined")
		return window.scrollY;
	if(typeof(document.body)!="undefined")
		if(typeof(document.body.scrollTop)!="undefined")
			return document.body.scrollTop;
	return 0;
}
function getScrollLeft(){
	if(typeof(window.scrollX)!="undefined")return window.scrollX;
	if(typeof(document.body)!="undefined")
		if(typeof(document.body.scrollLeft)!="undefined")
			return document.body.scrollLeft;
	return 0;
}
function getWindowHeight(){
	var height=0;
	if(document.body){
		if(document.body.clientHeight)
			return document.body.clientHeight;
		if(document.body.scrollHeight)
			return document.body.scrollHeight;
	}
	if(document.documentElement){
		if(document.documentElement.clientHeight)
			return document.documentElement.clientHeight;
		if(document.documentElement.scrollHeight)
			return document.documentElement.scrollHeight;
	}
	return 0;
}
function getWindowWidth(){
	var width=0;
	if(document.body){
		if(document.body.clientWidth)
			return document.body.clientWidth;
		if(document.body.scrollWidth)
			return document.body.scrollWidth;
	}
	if(document.documentElement){
		if(document.documentElement.clientWidth)
			return document.documentElement.clientWidth;
		if(document.documentElement.scrollWidth)
			return document.documentElement.scrollWidth;
	}
	return 0;
}

function getFullWindowSize(){//return width:$w,height:$h
    var xScroll = 0;
    var yScroll = 0;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) { // all except Explorer
        windowWidth = (document.documentElement.clientWidth) ? document.documentElement.clientWidth : self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    // for small pages with total height less then height of the viewport
    var docHeight = (yScroll < windowHeight) ? windowHeight : yScroll;
    // for small pages with total width less then width of the viewport
    var docWidth = (xScroll < windowWidth) ? xScroll : windowWidth;
    // return arrayPageSize;
    return {"width": docWidth, "height": docHeight};
} 


function setXpos(lObj,x){
	if(!(lObj=getDomObj(lObj)))return 0;
	if(isNaN(x))return 0;
	lObj.style.left=x+"px";
}
function setYpos(lObj,y){
	if(!(lObj=getDomObj(lObj)))return 0;
	if(isNaN(y))return 0;
	lObj.style.top=y+"px";
}
function moveTo(lObj,x,y){
	if(typeof(lObj.style)!=="undefined")lObj.style.position="absolute";
	setXpos(lObj,x);
	setYpos(lObj,y);
}
function centerOnPage(lObj){
	if(!(lObj=getDomObj(lObj)))return 0;
	var wheight=getWindowHeight();
	var wwidth=getWindowWidth();
	var lObjHeight=getOffsetHeight(lObj);
	var lObjWidth=getOffsetWidth(lObj);
	left=(wwidth/2)-(lObjWidth/2);
	top=(wheight/2)-(lObjHeight/2);
	moveTo(lObj,left,top);
}
function moveToObj(lObj,targObj,alignment){
	//move lObj to just below targObj same left+top
	//alignment can be forced
	if(!(lObj=getDomObj(lObj)))return 0;
	if(!(targObj=getDomObj(targObj)))return 0;
	var xy=getOffsetCoords(targObj);
	var x=xy[0];
	var y=xy[1];
	var targHeight=getOffsetHeight(targObj);
	var targWidth=getOffsetWidth(targObj);
	var lObjHeight=getOffsetHeight(lObj);
	var lObjWidth=getOffsetWidth(lObj);
	var scrtop=getScrollTop();
	var wheight=getWindowHeight();
	var wwidth=getWindowWidth();
	if(!alignment){
		//try to auto-determine alignment
		if((scrtop+wheight)<(y+targHeight+lObjHeight) && lObjHeight<wheight)
			alignment="above";
		else
			alignment="below";
		
	}
	//--move menu below target object
	if(alignment=="right"){//align lobj to the right below targObj
		x+=targWidth;
		x-=lObjWidth;
	}else if(alignment=="rightof"){//top right corner of lObj aligned with bottom right corner of targobj
		x+=targWidth;
	}else if(alignment=="above"){
		y-=lObjHeight;
	}else if(alignment=="belowleft"){
        x+=(targWidth-lObjWidth);
        y=(targHeight+y);
    }else if(!alignment || alignment=="below"){//--default to below, bottom left corner of targobj
		y=(targHeight+y);
	}else if(alignment == "belowcenter"){
		if(targWidth<lObjWidth){
			x-=((lObjWidth-targWidth)/2);
		}
        y=targHeight+y;
	}
	//if((x+2+lObjWidth)>wwidth){
	//	x-=(lObjWidth-targWidth);
	//}
	moveTo(lObj,x,y);
}

function hideOtherMenus(curMenu){
	//hides all menus modified by toggleMenu()
	addMenu(curMenu);
	for(i=0;i<THE_MENUS.length;i++){
		if(THE_MENUS[i]==curMenu)continue;
		if(!THE_MENUS[i])continue;
		if(!THE_MENUS[i].style)continue;
		THE_MENUS[i].style.visibility="hidden";
	}
}
function addMenu(menuObj){
	if(!menuObj)return;
	if(typeof(THE_MENUS)=="undefined")
		THE_MENUS=new Array();
	if(!THE_MENUS)
		THE_MENUS=new Array();
	THE_MENUS[THE_MENUS.length]=menuObj;
}
function toggleMenu(menuObj,targObj,alignment,forceVis){
//menuObj is the "menu" layer, targObj is the object to display the menu next to
//menuObj is assumed to be hidden by default
//forceVis is boolean that forces the menu object open or closed
	if(!(menuObj=getDomObj(menuObj)))return 0;
	if(!(targObj=getDomObj(targObj)))return 0;
	if(typeof(forceVis)=="undefined"){
		var newvis=(menuObj.style.visibility=="visible"?"hidden":"visible");
    }
	else{
		var newvis=(forceVis?"visible":"hidden");
    }
	//---code to deal w/ other menus
	hideOtherMenus(menuObj);
	menuObj.style.visibility=newvis;
	menuObj.style.display=(newvis=="visible"?"":"none");
	menuObj.style.position="absolute";
	moveToObj(menuObj,targObj,alignment);
	if(typeof(quitReload)=="function")quitReload();
}
function hideMenu(menuObj){
	if(!(menuObj=getDomObj(menuObj)))return 0;
	menuObj.style.visibility="hidden";
	menuObj.style.display="none";
}
function toggleDisp(lObj,forceto){//returns the new state none|block
	if(typeof(forceto)!='undefined'){
		var res=setDisp(lObj,forceto);
		return (res?forceto:0);
	}
	var state=getDisp(lObj);
	if(!state)return 0;
	var targ=(state=="none"?"block":"none");
	if(!setDisp(lObj,targ))return 0;
	return targ;
}
function showAll(){
	args=arguments;
	if(!args.length)return;
	if(typeof(args[0])=="object")args=args[0];
	if(!args.length)return;
	for(i=0;i<args.length;i++)
		toggleDisp(args[i],"block");
}
function hideAll(){
	args=arguments;
	if(!args)return;
	if(typeof(args[0])=="object")args=args[0];
	if(!args.length)return;
	for(i=0;i<args.length;i++)
		toggleDisp(args[i],"none");
}

function toggleDispLabel(lObj,txtObj,ontxt,offtxt){
//--toggles display of lObj
//--changes txtObj text to ontxt when display is on, offtxt when display is off (e.g. "more"|"less", "bigger"|"smaller")
	var toggleState=toggleDisp(lObj);
	if(!toggleState)return 0;
	var txt=(toggleState=="none"?offtxt:ontxt);
	return setInnerHTML(txtObj, txt);
}

function openCVV2(){
	window.open('/lib/cvv2.html','cvv2','width=560,height=500,resizable=1,scrollbars=1');
}
function addListener(targObjName,eventName,func){
	var targObj=findObj(targObjName);
	if(!targObj)return;
	if(typeof(targObj["on"+eventName])=="undefined"){
		if(targObj.addEventListener){
			targObj.addEventListener(eventName,func,true);
			return;
		}
	}else{
		targObj["on"+eventName]=func;
	}
}

function addListener2(targObjName,eventName,func){
	if (typeof(targObjName) == "object")
		var targObj = targObjName;
	else
		var targObj=findObj(targObjName);
	eventName = eventName.toLowerCase();
	if (eventName =="onclick") eventName = eventName.substring(2);
	if(!targObj)return;
	if(targObj.addEventListener){
		targObj.addEventListener(eventName,func,true);
		return;
	}else{
		targObj.attachEvent("on"+eventName,func);
		return;
	}
}
function linkobj(targObjName,url){
	//turns an object into a clickable link
	var targObj=findObj(targObjName);
	if(!targObj){return;}
	document.write("<style>#"+targObjName+"{cursor:pointer;cursor:hand;}</style>");
	oldonload=window.onload;
	window.onload=function(){
		if(typeof(oldonload)=="function")
			oldonload();
		doLinkObj(targObjName,url);
	}
}

function doLinkObj(objName,url){//same as above but doesn't write out style tag
	addListener(objName,"click",function(){location.href=url;});
}
function cursorwait(){
	if(document.body)
		if(document.body.style)
			document.body.style.cursor="wait";
	window.status="Please wait...";
}
function cursornormal(){
	if(document.body)
		if(document.body.style)
			document.body.style.cursor="default";
	window.status="";
}
function disableForm(elform){
	if(typeof(elform.disabled)!="undefined")elform.disabled=true;
	for(i=0;i<elform.elements.length;i++)
		elform.elements[i].disabled=true;
}
function enableForm(elform){
	if(typeof(elform.disabled)!="undefined")elform.disabled=false;
	for(i=0;i<elform.elements.length;i++)
		elform.elements[i].disabled=false;
}
function postTo(url,formname){
	if(formname)formname="theform";
	findObj("theform").action=url;
	findObj("theform").submit();
}

function getGet(url){
	var qs=strfrom(url,"?");
	if(!qs)return {};
	qs=qs.split("&");
	var ret={};
	for(i=0;i<qs.length;i++){
		var key=strto(qs[i],"=");//--can't use split because value may have an '=' sign like /w base64encoding
		var val=strfrom(qs[i],"=");
		ret[key]=val;
	}
	return ret;
}

function qsa(params){
	var ret=new Array();
	for(e in params){
		ret.push(e+"="+params[e]);
	}
	if(ret.length)
		return "?"+ret.join("&");
	return "";
}

var Base64 = {
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        input = Base64._utf8_encode(input);
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },
    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = Base64._utf8_decode(output);
        return output;
    },
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}
String.prototype.base64_encode=function(){return Base64.encode(this);}
String.prototype.base64_decode=function(){return Base64.decode(this);}

function handleLoginKeyPress(){
	if(typeof(event)=="undefined")return;
	if(!event)return
	if(!event.keyCode)return
	if(event.keyCode!=13)return
	findObj("signinForm").submit();
}


function openImageWindow(imgUrl,width,height){
	var imgUrl=cimg(imgUrl,"javascript:window.close()",'alt="Close Window"');
	var wnd=window.open("about:blank","_iwnd","width="+width+",height="+height+",scrollbars=1,resizable=1");
	wnd.document.write("<body style='margin:0px;border:0px'><center>"+imgUrl+"</center></body>");
}


/*******************************PREVIOUSLY IN _BUZZLIB.JS***************************************************/

function ReadCookie (name) {
      var namearg = name + "=";
      var nlen = namearg.length;
      var clen = document.cookie.length;
      var i = 0;
      while (i < clen) {
        var j = i + nlen;
        if (document.cookie.substring(i, j) == namearg) {
           var endpos = document.cookie.indexOf (";", j);
           if (endpos == -1) endpos = document.cookie.length;
           return unescape(document.cookie.substring(j, endpos));
	  }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
      }
      return null;
    }


function WriteCookie(name, value,expireAtSession,domain) {
	var expstr="";
	var vals=new Array(name+"="+escape(value));
	if(!domain)domain=DBD;
	if(!expireAtSession){
		var expdate=new Date();
		// expire cookie in 10 years by default
		expdate.setTime(expdate.getTime()+10*365*24*60*60*1000);
		vals[vals.length]="expires="+expdate.toGMTString();
	}
	vals[vals.length]="path=/";
	vals[vals.length]="domain=."+domain;
	document.cookie=vals.join("; ");
}
function SetCookie(name,val){WriteCookie(name,val);}
function DeleteCookie (name,domain) {
  var expdate = new Date();
  if(!domain)domain=DBD;
  expdate.setTime (expdate.getTime() - 1);  // Already gone!
  var cval = ReadCookie (name);
  document.cookie = name + "=" + cval + "; expires=" + expdate.toGMTString()+"; path=/; domain=."+domain;
}

function doSignUp(){
	setValByName("users[user_name]",getValByName("username"));
	setValByName("password","");	
	findObj("signform").action=URLPREFIX+"/www/subscribe/";
	return true;
}
function doSignIn(){
	var qs=getGet(new String(location.href));
	if(typeof(qs["refer"])!='undefined')
		setValByName("refer",qs["refer"]);
	findObj("signform").action="/user/login/";
	return true;
}
function isSignedIn(){
	return (ReadCookie("USERNAME")!='' && ReadCookie("USERNAME")!='0' && ReadCookie("USERNAME"))
}
function clearLoginCookies(){
	DeleteCookie("USERNAME");
	DeleteCookie("PASSWORD");
	DeleteCookie("UP");
	DeleteCookie(JS_SESSION_NAME);
	getUrlContents("/interface/post/clearlogin/");
}
function toggleSearch(showBox){
	if(!showBox)showBox="squick";
	var boxes="squick speople".split(" ");
	for(i=0;i<boxes.length;i++){
		toggleDisp(boxes[i],"none");
	}
	toggleDisp(showBox,"block");
}
function selSearch(type,linkObj,frm){
	frm=getDomObj(frm);
	frm.elements["stype"].value=type;
	var lnks=linkObj.parentNode.parentNode.getElementsByTagName("a");
	for(i=0;i<lnks.length;i++)
		if(lnks[i])lnks[i].className="";
	linkObj.className="on";
	frm.action=linkObj.href;
	if(frm.elements["stype"].value=="people"){
		toggleDisp('headersearchfield','none');
		toggleDisp('peoplesearchfields','block');
	}else{
		toggleDisp('headersearchfield','block');
		toggleDisp('peoplesearchfields','none');
	}
}

function klik(aObj,key){//--pipe everything through click logger
	href=aObj.href;
	if(!key)key="";
	href="/redir/?key="+key+"&url="+escape(href)+"&src="+escape(location.href);
	/*if(aObj.getAttribute("target")!="")
		window.open(href,"blank");
	else*/
		location.href=href;
	return false;
}
function getOutClickTrackerLink(destUrl,key,linktxt){
	if(!destUrl || !key){
		alert("Please provide a destination url and a tracking key");
	}
	if(!linktxt)linktxt="---linked content goes here---";
	key=key.replace('["&?\'\s]/g',"");
	if(startswith(destUrl,URLPREFIX+"/"))
		destUrl=strfrom(destUrl,URLPREFIX);
	return linktxt.link(URLPREFIX+"/redir/?key="+key+"&url="+escape(destUrl));
}
function getInClickTrackerLink(destUrl,key,linktxt){
	if(!destUrl || !key){
		alert("Please provide a destination url and a tracking key");
	}
	if(!linktxt)linktxt="---linked content goes here---";
	key=key.replace('["&?\'\s]/g',"");
	if(startswith(destUrl,URLPREFIX+"/"))
		destUrl=strfrom(destUrl,URLPREFIX);
	return '<a href="'+destUrl+'" track="'+key+'">'+linktxt+'</a>';
}
function getSwfFeedTag(type,feedurl,bgcolor,addl){
	var ret="";
	if(!addl)addl="";
	var urlprefix=URLPREFIX;
	if(!type || !feedurl)return;
	if(type=="vert"){
      var ret='<div style="text-align:center;width:102px;"><embed src="'+urlprefix+'/assets/rss_img_vert.swf" width="110" height="326" quality=high pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" flashvars="feed='+escape(feedurl)+'" wmode="transparent"></embed><div style="margin-top:-9px;margin-left:2px;">'+addl+'</div></div>';
	}else if(type=="horiz"){
		ret='<div style="text-align:center;width:411px;"><embed src="'+urlprefix+'/assets/rss_img_horiz.swf" width="420" height="80" quality=high pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" flashvars="feed='+escape(feedurl)+'" wmode="transparent"></embed><div style="margin-left:2px;">'+addl+'</div></div>';
	}else if(type=="mini"){
		ret='<div style="text-align:center;width:222px;"><embed src="'+urlprefix+'/assets/rss_img_mini.swf" width="225" height="354" quality=high pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" flashvars="feed='+escape(feedurl)+'" wmode="transparent"></embed><div style="margin-left:3px;">'+addl+'</div></div>';
	}
	return ret;
}
function getVideoTag(theurl, width, height,noautostart,previewImg){
	var autostart=(noautostart?"&autoStart=false":"");
	var clip=(previewImg?"&clip="+previewImg:"");
	if(!width)width="470";
	if(!height)height="352";
	var ret= '<embed src="'+URLPREFIX+'/assets/bnflvplayer2.swf?file='+theurl+clip+autostart+'&site='+SERVICE_ABBR+'&tag=0" width="'+width+'" height="'+height+'" quality="best" scale="noScale" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" wmode="transparent"></embed>';
	return ret;
}
function getAudioTag(xmlUrl,type,autoStart,limitPlaytime){
	if(!type)type="pop";
	autoStart=autoStart?"yes":"no";
	limit=(limitPlaytime?"limitPlaytime="+limitPlaytime+"&":"");
	if(type=="button"||type=="squarebutton"){
		width=60;height=60;
	}else{
		width=202;height=120;
	}
	return '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,47,0" width="'+width+'"  height="'+height+'" align="center"><param name="movie" value="http://www.'+DBD+'/assets/wimpy/wimpy.swf?'+limit+'forceXMLplaylist=yes&wimpyApp='+escape(xmlUrl)+'&wimpySkin=http%3A//www.'+DBD+'/assets/wimpy/skins/skin_'+type+'.xml&defaultVisualExt=jpg&theVolume=100&bufferAudio=0&infoDisplayTime=3&scrollInfoDisplay=yes&startPlayingOnload='+autoStart+'&autoAdvance=no&popUpHelp=yes" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="high" /><param name="scale" value="noscale" /><param name="salign" value="lt" /><param name="wmode"value="transparent" /><embed src=http://www.'+DBD+'/assets/wimpy/wimpy.swf?'+limit+'forceXMLplaylist=yes&wimpyApp='+escape(xmlUrl)+'&wimpySkin=http%3A//www.'+DBD+'/assets/wimpy/skins/skin_'+type+'.xml&defaultVisualExt=jpg&theVolume=100&bufferAudio=0&infoDisplayTime=3&scrollInfoDisplay=yes&startPlayingOnload='+autoStart+'&autoAdvance=no&popUpHelp=yes" loop="false" menu="false" quality="high" width="'+width+'" height="'+height+'" scale="noscale" salign="lt" align="center" allowScriptAccess="yes" type="application/x-shockwave-flash" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
}
function getAudioTagTrack(entryId,autoStart,limitPlaytime){
	if(!entryId)return "";
	return getAudioTag(URLPREFIX+"/www/singleplayer/"+entryId+"/","button",autoStart,limitPlaytime);
}
function encaud(encUrl,type,autoStart){
	return getAudioTag(encUrl.base64_decode(),type,autoStart);
}
function encaudbutton(encUrl,autostart){
	return encaud(encUrl,'button',autostart);
}
function validateSignIn(){
	var err="";
	if(!getValByName("username")){
		err+="Please enter your username and password.\n";
    }
	//if(!getValByName("password")){
	//	err+="Please enter your password\n";
    //}
	if(err){
		alert(err);
		return;
	}
	findObj("signinForm").submit();
}
function isValidBnDomainName(name){
	if(!name)return 0;
	var reg=/[^a-zA-Z0-9]/;
	if(ms=name.match(reg))return 0;
	return 1;
}

function isValidGalleryName(name){
	if(!name)return 0;
	var reg=/[^a-zA-Z0-9_]/;
	if(ms=name.match(reg))return 0;
	return 1;
}

function isValidVideoPath(path){
	var types=".mov .mpg .mpeg .mp4 .avi .3gp .3g2 .wmv .flv .m4v".split(" ");
	for(i=0;i<types.length;i++){
		if(endswith(path,types[i])){
			return 1;
		}
	}
	return 0;
}
function isValidPhotoPath(path){
	var types=".jpg .jpeg .gif".split(" ");
	for(i=0;i<types.length;i++){
		if(endswith(path,types[i])){
			return 1;
		}
	}
	return 0;
}
function isValidAudioPath(path){
	var types=".mp3".split(" ");
	for(i=0;i<types.length;i++){
		if(endswith(path,types[i])){
			return 1;
		}
	}
	return 0;
}
function validateComments(forgetNameEmail){
	var err="";
	if(!forgetNameEmail){
		if(!getValByName("com[name]").length){
			findObj("com[name]").value="Anonymous";
			err+=" Please enter your name\n";
		}
		if(!valid_email(getValByName("com[email]")) ){
			err+=" Please enter your email address\n";
		}
	}
	if(!getValByName("com[comments]").length){
		err+=" Please enter a comment\n";
	}
	if(err.length){
		alert(err);
		return false;
	}
	return true;
}

function validateMessage(forgetNameEmail){
	var err="";
	if(!getValByName("com[message]").length){
		err+=" Please enter a message\n";
	}
	if(err){
		alert(err);
		return;
	}
	findObj("messageform").submit();
}


function progressimg(){
	return cimg(URLPREFIX+"/assets/pages/indicator-grey.gif");
}

function progresstable(themsg){
	if(!themsg)themsg="Please wait...";
	var msg="<table class=\"progresstable\"><tr><td class=\"loading\"></td><td>"+themsg+"</td></tr></table>";
	return msg;
}

function bn_progresstable(themsg){
 	if(!themsg)themsg="Please wait...";
 	var msg="<div class='loginProgress'>"+progressimg()+" "+themsg+"</div>";

	return msg;
}

HTML_CHUNKS=new Array();//---memory cache for reload area return...ugly i know
function reloadArea(lObj,contentUrl,progressTxt,errTxt,cacheWithUrl){
	if(!(lObj=getDomObj(lObj)))return false;
	if(!progressTxt)progressTxt="";
	if(!errTxt)errTxt="";
	if(!window.dojo)return false;
	if(!contentUrl)return false;
	if(progressTxt){
		setInnerHTML(lObj,progressTxt);
	}
	if(cacheWithUrl){
		if(typeof(HTML_CHUNKS[contentUrl])!='undefined'){
			setInnerHTML(lObj,HTML_CHUNKS[contentUrl]);
			return false;
		}
	}
	dojo.io.bind({
		"url":contentUrl,
		"mimetype":"text/html",
		"load":function(tp,html,e){
			setInnerHTML(lObj,html);
			HTML_CHUNKS[contentUrl]=html;
			return;
		},
		"error":function(tp,html,e){
			setInnerHTML(lObj,errTxt+"<br>"+html);
			return;
		}
	});
	return true;
}

function addBuzz(frmObj){
	var val=lc(findObj("tags").value);
	if(!val){
		alert("Please enter a Tag to add to this post");
		return false;
	}
	var words=val.split(",");
	for(i=0;i<words.length;i++){
		words[i]=trim(words[i]);
		if(words[i].split(" ").length>6){
			alert("Too many words. Make sure you separate your tags with commas");
			return false;
		}
	}
	findObj("tags").value=words.join(", ");
	return true;
}

function checkEnterInput(e,formObj) {
    if (window.event) {
        keynum = e.keyCode;
    } else if(e.which) {
        keynum = e.which;
    }
    if (keynum==13) {
        return submitBuzz(formObj);
    }
    return true;
}

function getTagDirname(tag){
	return tag.replace(/[\W_]/g,"").toLowerCase();
}
function getDirnameFromTitle(title){
	title=title.replace(/[!\?\.\,"']/g,"").toLowerCase();
	title=title.replace(/\s{2,}/g," ");
	title=title.replace(/\-{2,}/g,"-");
	title=title.replace(/\W/g,"-");
	title=title.replace(/\W{2,}/g,"-");
	return title;
}

/**
 * generic function to add tags
 * entryId - unique id of post (not post_id)
 * type - user,cat,profile,link,journal,video,poll etc
 * successFunc - called on successful completion of tag addition
 * waitForSuccess - will only call successFunc after completed, otherwise, successfunc will get called immediately.
*/
function addTags(entryId,type,tags,successFunc,waitForSuccess){
	if(!entryId || !type || !tags)return 0;
	if(!isSignedIn())return 0;
	if(typeof(successFunc)!="function")successFunc=0;
	waitForSuccess=(waitForSuccess?1:0);
	var url="/interface/post/tags/?lmode="+type+"&id="+entryId+"&tags="+tags;
	if(!waitForSuccess && successFunc)
		successFunc();
	getUrl(url,function(){if(waitForSuccess)successFunc();});
}
function submitBuzz(formObj){
	/* referenced document elements in this function:
		addtagsmenu  - the pop-up layer containing the tag form
		buzztable    - the table containing the tag form
		buzzstatus   - the layout outside the buzztable that appears telling the user it's thinking
		taglist - the list of links where the tags fill in
		tags    - the form object containing the tags the user is submitting
		addtagsbut   - the toolbar button the user clicks to open the menu w/ the form
	*/
	if(!addBuzz())return false;
	eid=formObj.elements["id"].value;
	lmode=formObj.elements["lmode"].value;
	setToOffsetSize("addtagsmenu");
	toggleDisp("buzztable","none");
	setInnerHTML("buzzstatus",progresstable("Please wait while Tags are added"));
	var kw = {
		mimetype: "text/plain",
		formNode: formObj,
		load: function(t,txt,e){
			var msg=txt.split(":");
			if(msg[0]=="false" || !msg[0]){
				var error="Error adding tags: "+msg[1];
				setInnerHTML("buzzstatus",error);
				toggleDisp("buzztable","block");
				return;
			}
			if(msg[0]=="true"){
				reloadTags("taglist",eid,lmode);
				setInnerHTML("buzzstatus","Tags added!");
				formObj.elements["tags"].value="";
				var funcs=new Array("toggleDisp('buzztable','block')");
				funcs[funcs.length]="toggleMenu('addtagsmenu','addtagsbut')";
				funcs[funcs.length]="setInnerHTML('buzzstatus','')";
				setTimeout(funcs.join(";"),750);
			}
		},
	
		error: function(t,e){
			//toggleDisp("buzztable","block");
			//setInnerHTML("buzzstatus","There was an error adding your tags");
			return;
		}
	};
	dojo.io.bind(kw);
	return false;
}

function editPost(postId,postTitle,postBody,tags,successFunc,failFunc,altUser,time){
	dojo.require("dojo.io.IframeIO");
	if(typeof(successFunc)!="function")
		successFunc=function(msg,postId){void(0);};
	if(typeof(failFunc)!="function")
		failFunc=function(msg,postId){void(0);};
	if(!isSignedIn()){
		failFunc("You must be signed in",postId);
		return;
	}
	if(!postId || !(postTitle||postBody||tags)){
		failFunc("Didn't supply any information on the post to edit",postId);
		return;
	};
	if(!altUser)altUser="";
	//iframeio doesn't work if not on ie referencing a real form for some reason.
	//also must use POST method. action cannot have querystring
	var frm=createEl("form",{"action":"http://"+EBD+"/interface/post/editpost/","method":"post","id":"frm"+postId,"name":"frm"+postId});
	var hiddens=input_hidden("post_id",postId)+input_hidden("message_domain",location.hostname);
	if(altUser) hiddens+=input_hidden("user",altUser);
	if(postTitle) hiddens+=input_hidden("post[title]",postTitle);
	if(postBody) hiddens+=input_hidden("post[body]",postBody);
	if(tags) hiddens+=input_hidden("tags",tags);
	if(time) hiddens+=input_hidden("post[time]",time);
	
	frm.appendChild(createEl("span",{"innerHTML":hiddens}));//doing in this weird way b/c ie won't set 'name' attr through dom
	document.body.appendChild(frm);//for some reason ie throws permission denied if the thing isn't in the document.
	dojo.io.bind({
		"formNode":frm,
		"transport":"IframeTransport",
		"mimetype":"text/json",
		"load":function(t,html,e){
			if(!html.ok){
				failFunc(html.message,postId);
				return;
			}
			successFunc(html.message,postId);
			return;
		},
		"error":function(t,html,e){
			failFunc(html.message,postId);
		}
	});
	
}
function removePost(postId,successFunc,failFunc){
	if(typeof(successFunc)!="function")successFunc=function(){void(0);}
	if(typeof(failFunc)!="function")falFunc=function(){void(0);}
	if(!postId){
		failFunc("No id given");
		return;
	}
	dojo.require("dojo.io.IframeIO");//not reliable right now..
	//iframeio+ie needs to use a form that's in the document for some reason...
	var frm=createEl("form",{"action":"http://"+EBD+"/interface/post/editpost/remove/","method":"post"});
	document.body.appendChild(frm);
	params={"post_id":postId,"message_domain":location.hostname};
	dojo.io.bind({
		"formNode":frm,
		"content":params,
		"transport":"IframeTransport",
		"mimetype":"text/json",
		"load":function(t,html,e){
			if(!html.ok){
				failFunc(html.message, postId);
			}else{
				successFunc(html.message,postId);
			}
		},
		"error":function(t,html,e){
			failFunc(html.message,postId);
		}
	})
}

/*======== tag registration =======*/
function updateAvail(res){
	/*
		document objects:
		usernamestatus - div that displays error text for user availability check
		usernamerow    - table row containing the username
	*/
	if(typeof(username_error)=="undefined")username_error=0;
	if(!res["result"] && res["error"]){
		setInnerHTML("usernamestatus",'<span class="small error">*'+res["error"]+"*</span>");
		getDomObj("usernamerow").className="errorfield";
		username_error=1;
	}else{
		username_error=0;
		getDomObj("usernamerow").className="";
		setInnerHTML("usernamestatus",DBD);
	}
}
function checkAvail(userval){
	if(typeof(username_inited)=="undefined")username_inited=0;
	if(!userval)return;
	if(!username_inited)return;
	isUserNameAvailAsync(userval, updateAvail);
}
/* given a source text field where keypresses are happening and a dest field to display messages, this will check the availability of a username in realtime */
function checkAvailWithStatus(srcField,destField){
	if(!(destField=getDomObj(destField)))return;
	var user=getValByName(srcField);
	if(typeof(user)==undefined || !user || user.length<3)return;
	var aurl="/interface/post/checkavail/"+user+"/";
	getUrl(aurl,function(t,html,e){
			var stat=strfromto(html,'stat="','"');
			if(stat=="ok"){
				setInnerHTML(destField,"*available*");
				getDomObj(destField).className="good";
			}else{
				setInnerHTML(destField,"*name not available*");
				getDomObj(destField).className="error";
			}
		}
	);
}
username_error=0;
function validateBuzzSignup(mustAgree){
	/*
		document objects:
		file - file upload field
		users[user_name] - form field
		users[email]     - form field
		users[user_password] - form field
		postformcotnainer - div that contains the entire post form
		postformmsg       - hidden div that appears and gives a status/progress message
		postform    - the form that's being submitted
	*/
	var thisyear=new Date().getYear();
	if(thisyear<1900)thisyear+=1900;
	if(!mustAgree)mustAgree=0;
	var err="";
	//---validate file
	var path=getValByName("file");
	if(!isValidPhotoPath(path) && !isValidVideoPath(path))
		err+="The file posted is not a valid file type\n";
	if(username_error || !isValidBnDomainName(getValByName("users[user_name]")))
		err+="Please enter a different username. The name you chose may have invalid characters in it, or it may already be taken\n";
	if(getValByName("users[user_password]").length<4)
		err+="Please enter a password with at least 4 characters\n";
	if(!validEmailValue("users[email]"))
		err+="Please enter a valid email address\n";
	var dob=getValByName("users[dob2]");
	var dreg=/(\d{4})\-\d{2}\-\d{2}/;
	if(!(reg=dob.match(dreg)))
		err+="Please enter your birth date\n";
	else{
		if(ReadCookie("ty") || (thisyear-reg[1])<13){
			WriteCookie("ty",1);
			err+="You're too young to sign up for this website.\n";
		}
	}
	if(mustAgree){
		if(!isChecked("agreed_terms")){
			var agreetxt=getInnerHtml("agree_terms_title")
			if(!agreetxt){
				agreetxt="Terms of Use";
			}
			err+="You must agree to the "+agreetxt+"\n";
		}
	}
	if(err.length){
		alert(err);
		return;
	}
	toggleDisp("postformcontainer","none");
	toggleDisp("postformmsg","block");
	setInnerHTML("postformmsg",progresstable("Please wait while your file uploads..."));
	findObj("postform").submit();
}
/*======== end tag registration =======*/

function sendToFriend(){
	var err="";
	if(!validEmailValue("fromemail"))
		err+="Please enter your email address\n";
	if(!getValByName("toemail"))
		err+="Please enter your friend's email address or "+SERVICE_NAME+" user names\n";
	if(err.length){
		alert(err);
		return false;
	}
	return true;
}
function submitSendFriend(formObj) {
	if(!sendToFriend(formObj))return false;
	setToOffsetSize("sharemenu");
	toggleDisp("sharecontainer","none");
	var msg="<table><tr><td>"+cimg("/assets/indicator.gif")+"</td>"
		   +"<td>Please while we send this photo.</td></tr></table>"
	setInnerHTML("sharestatus",msg);
	var kw = {
		mimetype: "text/plain",
		formNode: formObj,
		load: function(t,txt,e){
			var msg=txt.split(":");
			if(msg[0]=="false" || (msg[0]!="true"&&msg[0]!="false")){
				var error="Error sending: "+msg[1];
				setInnerHTML("sharestatus",error);
				toggleDisp("sharecontainer","block");
				return;
			}
			if(msg[0]=="true"){
				setInnerHTML("sharestatus","Message Sent!");
				findObj("toemail").value="";
				var funcs=new Array("toggleDisp('sharecontainer','block')");
				funcs[funcs.length]="toggleMenu('sharemenu','sharebut')";
				funcs[funcs.length]="setInnerHTML('sharestatus','')";
				setTimeout(funcs.join(";"),750);
			}
		},
		error: function(t,e){
			toggleDisp("sharecontainer","block");
			setInnerHTML("sharestatus","There was an error sending the message");
			return;
		}
	};
	dojo.io.bind(kw);
	return false;
}



function removeComment(comment_id,linkobj){
	var msg="Are you sure you want to remove this comment?";
	if(!confirm(msg)){
		return false;
	}
	lObjName="com"+comment_id;
	if(!(lObj=getDomObj(lObjName)) || !(listObj=getDomObj("commentlist"))){
		location.replace(linkobj.href);
		return false;
	}
	statusdiv=lObjName+"data";
	//setInnerHTML(statusdiv,progresstable("Please wait while the comment is removed"));
	toggleDisp(lObj,"none");
	dojo.io.bind({
		"url":"/interface/post/comments/remove/?id="+comment_id,
		"mimetype":"text/html",
		"load":function(tp,html,e){
			var msg=html.split(":");
			if(msg[0]=="false"){
				setInnerHTML(statusdiv,"ERROR:"+(msg[1]?msg[1]:""));
				return;
			}
			toggleDisp(lObj,"none");
			if((cc=getDomObj("commentcount"))){
				val=parseInt(cc.innerHTML);
				if(!isNaN(val)){
					setInnerHTML("commentcount",(val-1));
				}
			}
			return;
		},
		"error":function(tp,html,e){
			var msg=html.split(":");
			setInnerHTML(statusdiv,"There was an error removing the comment");
			return;
		}
	});
}

function removeGeneralComment(comment_id,linkobj){
	var msg="Are you sure you want to remove this comment?";
	if(!confirm(msg)){
		return false;
	}
	lObjName="com"+comment_id;
	if(!(lObj=getDomObj(lObjName)) || !(listObj=getDomObj("gcommentlist"))){
		location.replace(linkobj.href);
		return false;
	}
	statusdiv=lObjName+"data";
	toggleDisp(lObj,"none");
	dojo.io.bind({
		"url":"/interface/post/generalcomments/remove/?id="+comment_id,
		"mimetype":"text/json",
		"load":function(tp,html,e){
			if(!html["ok"]){
				var msg=html["message"];
				setInnerHTML(statusdiv,msg);
				return;
			}
			toggleDisp(lObj,"none");
			if((cc=getDomObj("gcommentcount"))){
				val=parseInt(cc.innerHTML);
				if(!isNaN(val)){
					setInnerHTML("gcommentcount",(val-1));
				}
			}
			return;
		}
	});
}


function submitcomform(formobj,loggedin,profilepic){
	
	if(!validateComments(loggedin)){
		return false;
	}
	//validate message: message must be different by default message
	if (document.getElementById("comDefMess")) {
		var defMess =  document.getElementById("comDefMess").value;
		if (findObj("com[comments]").value == defMess) return false;
	}
	if(!window.dojo){
		formobj.submit();
		return;
	}
	if(!findObj("commentlisttbody")){
		formobj.submit();
		return;
	}
	//--get username and user url from from elements
	var myname="";var myurl="";
	if(findObj("myname").value){
		myname=findObj("myname").value;
	}else if(findObj("com[name]")){
		myname=findObj("com[name]").value;
	}
	if(findObj("myurl").value){
		myurl=findObj("myurl").value
	}
	if(findObj("com[email]")){
		myurl="mailto:"+findObj("com[email]").value;
	}
	toggleDisp("commentbuttons","none");
	toggleDisp("addcommentstable","none");
	toggleDisp("commentstatus","block");
	msg=progresstable("Please wait while your comment is posted");
	setInnerHTML("commentstatus",msg);
	dojo.io.bind({
		"url":"/interface/post/comments/",
		"mimetype":"text/html",//---IE seems to be returned an empty object. ghetto sting parsing instead. gay
		"formNode":formobj,
		"load":function(tp,html,e){
			var error="";
			var stat=strfromto(html,'stat="','"');
			if(stat=="ok"){				
				setValByName("com[parent_id]","");
				logOmniture({"events":"event6"},"Comment");//event6 is comments
				setInnerHTML("commentstatus","");
				toggleDisp("commentstatus","none");
				toggleDisp("commentbuttons","block");
				var comment_id=strfromto(html,"<id>","</id>");
				var removecomment="/_removecomment/?id="+comment_id+"&bounceback="+escape(location.href);
				var image=(profilepic?cimg(profilepic):cimg(JS_EMPTY_PROFILE_IMG));
				//--create the new comment row
				var tr=document.createElement("tr");
				tr.setAttribute("valign","top");
				tr.id="com"+comment_id;
				//label with avatar
				var td=createEl("td",{"class":"label"});
				td.setAttribute("style","text-align:center");
				td.innerHTML='<a class="comthumb" rel="nofollow" href="'+myurl+'">'+image+'</a>'+(loggedin?'<br>[<a class="small" href="'+removecomment+'" onclick="removeComment(\''+comment_id+'\',this);return false">delete</a>]':"");

				tr.appendChild(td);
				//quoted comments

				var body=nl2br(findObj("com[comments]").value);
				var reg=/\[(\/)quote\]/g;
				body=body.replace(reg,"<$1blockquote>");
				body=body.replace(/<img/g,'<img style="width:auto;height:auto"');
				
				reg=/\[quote=(\w+)\]/gi;
				body=body.replace(reg,'<blockquote><div class="saidline"><a href="http://$1.'+DBD+'/user/">$1</a> said:</div>');
				//--comment data
				var td=createEl("td",{"class":"data","valign":"top","id":"com"+comment_id+"data"})
				var cbody='<div class="combyline"><span class="comname" id="com'+comment_id+'name">'+myname.link(myurl)+'</span>:'+'<span class="comtime">'+getDateTime()+'</span></div>'
				         +'<div id="com'+comment_id+'body" class="combody">'+body+'</div>'
						 +'<br><div class="small error" style="margin-top:1em">NOTE: Your comment take a few minutes to appear permanently</div>';
				td.innerHTML=cbody;
				//---display in list
				tr.appendChild(td);
				getDomObj("commentlisttbody").appendChild(tr);
				
				tr=td=ltxt=0;
				findObj("com[comments]").value="";
				toggleDisp("addcommentstable","block");
				//---update list count
				if((cc=getDomObj("commentcount"))){
					val=parseInt(cc.innerHTML);
					if(!isNaN(val)){
						setInnerHTML("commentcount",(val+1));
					}
				}
				return;
			}else if(stat=="fail"){
				var error=strfromto(html,"<err>","</err>");
				if(!error)error="There was an error posting your comment";
			}else{
				error="There was an error. Your comment may not have been posted";
			}
			if(error){
				setInnerHTML("commentstatus",error);
				toggleDisp("commentbuttons","block");
				toggleDisp("addcommentstable","block");
				return false;
			}
			return false;
		}
	});
	return false;
}

/* used for submit a new comment in slideshows pages */
function submitmincommentform(formobj,loggedin){
	if(!validateComments(loggedin)){
		return false;
	}

	//validate message: message must be different by default message
	if (document.getElementById("comDefMess")) {
		var defMess =  document.getElementById("comDefMess").value;
		if (findObj("com[comments]").value == defMess) return false;
	}

	//hide conatainer who contain box comment and POST button
	toggleDisp("addcommmincon","none");


	toggleDisp("commentstatus","block");
	msg=progresstable("Please wait while your comment is posted");
	setInnerHTML("commentstatus",msg);

	dojo.io.bind({
		"url":"/interface/post/comments/",
		"mimetype":"text/html",//---IE seems to be returned an empty object. ghetto sting parsing instead. gay
		"formNode":formobj,
		"load":function(tp,html,e){
			var error="";
			var stat=strfromto(html,'stat="','"');
			if(stat=="ok"){
					var url = getDomObj("viewcomurl").href;
					var comcount = getDomObj("comcommentscount").value;
					comcount = intval(comcount);
					comcount++;
					if (comcount==1)
						msg = comcount+" Comment";
					else
						msg = comcount+" Comments";
					getDomObj("viewcomurl").innerHTML = msg;
					getDomObj("viewcomurl").title = msg;
					getDomObj("comcommentscount").value = comcount;
					msg = 'Thanks for posting. <a href="'+url+'">Click here to view your comment</a>';
					setInnerHTML("commentstatus",msg);
					logOmniture({"events":"event6"},"Comment");//event6 is comments
					return;
			}else if(stat=="fail"){
				var error=strfromto(html,"<err>","</err>");
				if(!error)error="There was an error posting your comment";
			}else{
				error="There was an error. Your comment may not have been posted";
			}
			if(error){
				setInnerHTML("commentstatus",error);
				toggleDisp("addcommmincon","block");
				return false;
			}
			return false;
		}
	});
return false;
}


function submitgeneralcomform(formobj,profilepic){
	if(!validateComments(1)){
		return false;
	}
	if(!window.dojo){
		formobj.submit();
		return;
	}
	if(!findObj("gcommentlisttbody")){
		formobj.submit();
		return;
	}
	var myname=ReadCookie("USERNAME");
	var myurl="http://"+myname+"."+DBD+"/user/";
	toggleDisp("gcommentbuttons","none");
	toggleDisp("gaddcommentstable","none");
	toggleDisp("gcommentstatus","block");
	msg=progresstable("Please wait while your comment is posted");
	setInnerHTML("gcommentstatus",msg);
		showAll("gcommentsheader");
	dojo.io.bind({
		"url":"/interface/post/generalcomments/add/",
		"mimetype":"text/json",
		"formNode":formobj,
		"load":function(tp,html,e){
			var error="";
			if(html["ok"]){
				logOmniture({"events":"event6"},"Comment");
				setValByName("com[parent_id]","");
				setInnerHTML("gcommentstatus","");
				toggleDisp("gcommentstatus","none");
				toggleDisp("gcommentbuttons","block");
				var comment_id=html["data"]["id"];
				var removecomment="/interface/post/generalcomments/remove/?id="+comment_id+"&refer="+escape(location.href);
				var image='<div class="thumb-outer"><a href="#" class="comthumb">'+(profilepic?cimg(profilepic):cimg(JS_EMPTY_PROFILE_IMG))+'</a></div>';
				//--create the new comment row
				var tr=document.createElement("tr");
				tr.setAttribute("valign","top");
				tr.id="com"+comment_id;
				//label with avatar
				var td=createEl("td",{"class":"label","width":"1%"});
				td.setAttribute("style","text-align:center");
				td.innerHTML=image+'<a class="small" href="'+removecomment+'" onclick="removeGeneralComment(\''+comment_id+'\',this);return false">[delete]</a>';
				tr.appendChild(td);
				//quoted comments
				var body=nl2br(findObj("com[comments]").value);
				var reg=/\[(\/)quote\]/g;
					body=body.replace(reg,"<$1blockquote>");
				reg=/\[quote=(\w+)\]/gi;
				body=body.replace(reg,'<blockquote><div class="saidline"><a href="http://$1.'+DBD+'/user/">$1</a> said:</div>');
				//--comment data
				var td=createEl("td",{"class":"data","valign":"top","id":"com"+comment_id+"data","width":"98%"});
				var cbody='<div class="combyline"><span class="comname">'+myname.link(myurl)+'</span> wrote: <span class="comtime">Less than a minute ago</span></div>'
				         +'<div class="combody">'+body+'</div>'
						 +'<br><div class="small error" style="margin-top:1em">NOTE: Your comment may take a few minutes to appear permanently</div>';
				td.innerHTML=cbody;
				//---display in list
				tr.appendChild(td);
				if(getDomObj("gcomform").getAttribute("commentfirst")){
					var gbody=getDomObj("gcommentlisttbody");
					gbody.insertBefore(tr,gbody.firstChild);
				}else{
					getDomObj("gcommentlisttbody").appendChild(tr);
				}
				tr=td=ltxt=0;
				findObj("com[comments]").value="";
				toggleDisp("gaddcommentstable","block");
				//---update list count
				if((cc=getDomObj("gcommentcount"))){
					val=parseInt(cc.innerHTML);
					if(!isNaN(val)){
						setInnerHTML("gcommentcount",(val+1));
					}
				}
				return;
			}else if(typeof(html["ok"])!="undefined" && html["ok"]==0){
				var error=html["message"];
			}else{
				error="There was an error. Your comment may not have been posted";
			}
			if(error){
				setInnerHTML("gcommentstatus",error);
				toggleDisp("gcommentbuttons","block");
				toggleDisp("gaddcommentstable","block");
				return false;
			}
			return false;
		}
	});
	return false;
}

function quoteComment(comment_id){
	if(!comment_id)return;
	if(!(combody=findObj("com[comments]")))return;
	var quoted=findObj("com"+comment_id+"body").innerHTML;
	//get person's name
	var user_name;
	if(obName=getDomObj("com"+comment_id+"name")){
		if(a=obName.getElementsByTagName("a")){
			a=a[0];
			if(a.getAttribute("username")){
				user_name=a.getAttribute("username");
			}
		}
	}
	var reg=/<blockquote>.*<\/blockquote>/g;
	quoted=quoted.replace(reg,"");
	var reg=/<br\s?\/?>/g;
	quoted=quoted.replace(reg,"");
	var quote="[quote"+(user_name?"="+user_name:"")+"]"+quoted+"[/quote]\n";
	insertTextToInput(combody,strip_tags(quote));
	setValByName("com[parent_id]",comment_id)
	combody.scrollIntoView();
}
function removeUserNote(note_id,linkobj,username){
	var msg="Are you sure you want to remove this note?";
	if(!confirm(msg)){
		return false;
	}
	lObjName="note"+note_id;
	if(!(lObj=getDomObj(lObjName)) || !(listObj=getDomObj("commentlist"))){
		location.replace(linkobj.href);
		return false;
	}
	statusdiv=lObjName+"data";
	setInnerHTML(statusdiv,progresstable("Please wait while the note is removed"));
	dojo.io.bind({
		"url":"/interface/post/notes/delete/?id="+note_id+(username?"&user_name="+username:""),
		"mimetype":"text/html",
		"load":function(tp,html,e){
			var stat=strfromto(html,'stat="','"');;
			if(stat=="fail"){
				var err=strfromto(html,'<err>','</err>');
				setInnerHTML(statusdiv,"ERROR: "+err);
				return;
			}
			toggleDisp(lObj,"none");
			if((cc=getDomObj("notecount"))){
				val=parseInt(cc.innerHTML.replace(/[^\d]+/,""));
				if(!isNaN(val)){
					setInnerHTML("notecount",(val-1));
				}
			}
			return;
		},
		"error":function(tp,html,e){
			setInnerHTML(statusdiv,"There was an error removing the note");
			return;
		}
	});
}

function addUserNote(formobj,username,profilepic){
	//--'notelistbody' - <tbody> object containing list of notes
	//--'commentlist'  - <table> object containing notelistbody 
	//--'notescontainer' - contains the form field and the buttons
	//--'notestatus'   - hidden layer containing status message while note is posting
	if(!username){
		alert("Couldn't determine your username. Maybe you need to sign in.");
		return false;
	}
	if(!getValByName("note[message]")){
		alert("You didn't write anything!");
		return false;
	}
	if(!window.dojo){
		formobj.submit();
		return;
	}
	if(!findObj("notelistbody")){
		formobj.submit();
		return false;
	}
	//--username stuff
	myname=username;
	myurl="http://"+username+"."+DBD+"/";
	toggleDisp("notescontainer","none");
	toggleDisp("notestatus","block");
	msg=progresstable("Please wait while your note is posted");
	setInnerHTML("notestatus",msg);
	dojo.io.bind({
		"url":"/interface/post/notes/?dojo_transport=1",
		"mimetype":"text/html",//---IE seems to be returned an empty object. ghetto sting parsing instead. gay
		"formNode":formobj,
		"load":function(tp,html,e){
			var error="";
			var stat=strfromto(html,'stat="','"');
			if(stat=="ok"){
				setInnerHTML("notestatus","");
				toggleDisp("notestatus","none");
				toggleDisp("notescontainer","block");
				var note_id=strfromto(html,"<id>","</id>");
				var removenote="/_note/delete/?id="+note_id+"&bounceback="+escape(location.href);
				var image=(profilepic?cimg(profilepic):"&nbsp;");
				//--create the new comment row
				var tr=document.createElement("tr");tr.setAttribute("valign","top");
				//label with avatar
				var td=document.createElement("td");td.className="label";
				td.setAttribute("style","text-align:center");
				td.innerHTML=image+'<br>[<a class="small" href="'+removenote+'">delete</a>]';
				tr.appendChild(td);
				//--comment data
				var td=document.createElement("td");td.className="data";td.setAttribute("valign","top");
				var cbody=myname.link(myurl)+" "+getDateTime()
				         +"<br>"+nl2br(findObj("note[message]").value)
						 +'<div class="error" style="font-style:italic">Your note may take a minute to show up permanently</div>';
				td.innerHTML=cbody;
				tr.appendChild(td);
				var notebody=getDomObj("notelistbody");
				notebody.insertBefore(tr,notebody.firstChild);
				tr=td=ltxt=0;
				findObj("note[message]").value="";
				//--jump to top of notes list
				if(!endswith(location.href,"#notes"))
					location.href=location.href+"#notes"
				else
					location.href=location.href;
				//---update list count
				if((cc=getDomObj("notecount"))){
					val=parseInt(cc.innerHTML.replace(/[^\d]+/,""));
					if(!isNaN(val)){
						setInnerHTML("notecount",(val+1));
					}
				}
				return false;
			}else if(stat=="fail"){
				var error=strfromto(html,"<err>","</err>");
				if(!error)error="There was an error posting your note";
			}else{
				error="There was an error. Your note may not have been posted";
			}
			if(error){
				setInnerHTML("notestatus",error);
				toggleDisp("notescontainer","block");
				toggleDisp("commentlist","block");
				return false;
			}
			return false;
		}
	});
	if(typeof(containsPromoTrigger)=="function"){//make sure this won't throw error
	    if (containsPromoTrigger(getValByName("note[message]"))) {
    	    executeUserNotePromoImmediate();
		}
    }
	return false;
}
function clearUnreadNotes(hideLayer){
	if(!confirm("Are you sure you want to clear your unread notes?"))return ;
	getUrl("/interface/post/notes/clearmine/");
	toggleDisp(hideLayer,"none");
	return true;
}
function clearUnreadMessages(hideLayer){
	if(!confirm("Are you sure you want to mark all your messages as 'read'?"))
		return false;
	getUrl("/user/messages.mod/?folder=n&selectfolder=1&markas=r");
	if(hideLayer)
		toggleDisp(hideLayer,"none");
}
function clearUnreadBulletins(hideLayer){
	if(!confirm("Are you sure you want to ignore all your new bulletins?"))
		return false;
	getUrl("/interface/post/bulletins/clearunread/");
	if(hideLayer)
		toggleDisp(hideLayer,"none");
}
function shoutoutEditSetup(containerId,contentDivId,user_name){
	var url="/interface/post/profile/"+(user_name?"?user_name="+user_name:"");
	setUpEditableObject(url, "profile[shoutout]", containerId, contentDivId);
}

function setUpEditableObject(postUrl, fieldName, containerId, contentId, fonok,fonerr){
	/*
		posturl - url to send the contents of contentObject to
		fieldName - what to name the field that gets posted to posturl
		containerObject - object that contains the contentObject (should have dojoType and mode attrs)
		contentObject - editable text
	*/
	dojo.require("dojo.widget.*");
	dojo.require("dojo.widget.InlineEditBox");
	dojo.require("dojo.event.*");
	
	djConfig["searchIds"].push(containerId);//object that contains the actual shoutout layer
	var onSaveFuncName=fieldName+"_onSave";
	var onLoadFuncName=fieldName+"_onLoad";
	if(typeof(fonok)!="function")fonok=function(){return;}
	if(typeof(fonerr)!="function")fonerr=function(err){alert(err);} 
	window[onSaveFuncName]=function(newval, oldval){
		if(newval==oldval)
			return;
		var ioargs= {
			"url": postUrl,
			"mimetype": "text/html",
			"method": "POST",
			"content": {},
			"load": function(tp, html, e){
				var stat=strfromto(html,'stat="','"');
				if(stat!='ok'){
					var err=strfromto(html,'<err>','</err>');
					fonerr(err)
					return;
				}else{
					fonok(tp,html,e);
				}
			},
			"error":function(){fonerr("Could't connect. Try again later.");}
		};
		ioargs.content[fieldName] = newval;
		dojo.io.bind(ioargs);
	}
	window[onLoadFuncName]=function(){
		dojo.widget.byId(contentId).onSave=window[onSaveFuncName];
	}
	dojo.addOnLoad(window[onLoadFuncName]);
}
function reloadTags(lObj, entry_id,type){
	if(!entry_id)return 0;
	if(!type)return 0;
	if(!(lObj=getDomObj(lObj)))return 0;
	if(!window.dojo)return;
	setInnerHTML(lObj,"<i>Refreshing</i>...");
	dojo.io.bind({
		"url":"/interface/post/gettags/?id="+entry_id+"&type="+type,
		"mimetype":"text/html",
		"load":function(tp,html,e){
			setInnerHTML(lObj,html);
		}
	});
}


function addAsFriend(linkObj,userName,errTxt){
	//--return true will just cause user to navigate to link
	//--cannot rely on IE xml parsing so doing lame string parsing. ghet-toh
	
	if(!confirm("Add "+userName+" as a friend?"))return false;
	if(!(linkObj=getDomObj(linkObj)))return true;
	if(!userName)return true;
	if(!window.dojo)return true;
	if(!errTxt)errTxt="there was an error";
	linkObj.href="#";
	setInnerHTML(linkObj,progressimg());
	linkObj.onclick=function(){return false;}
	dojo.io.bind({
		"url":"/interface/post/addfriend/?user="+userName,
		"mimetype":"text/html",
		"load":function(tp,txt,e){
			var status=strfromto(txt,'stat="','"');
			if(status=="ok"){
				logOmniture({"events":"event9"},"Friend");//event9 is friend
				var msg=strfromto(txt,"<msg>","</msg>");
				setInnerHTML(linkObj,"<i>"+msg+"</i>");
				if(linkObj.id){
					setTimeout("toggleDisp('"+linkObj.id+"','none')",1500);
				}
				return;
			}else if(status=="fail"){
				var msg=strfromto(txt,"<err>","</err>");
				setInnerHTML(linkObj,"<i>"+msg+"</i>");
				return;
			}else{
				setInnerHTML(linkObj,"<i>"+errTxt+"</i>");
				return;
			}
		}
	});
	return false;
}
function removeFromFriends(linkObj,userName){
	if(!userName)return;
	if(!confirm("Remove "+userName+" from your friends list?"))return;
	setInnerHTML(linkObj,"removed!");
	linkObj.onclick=function(){return false;}
	dojo.io.bind({
		"url":"/interface/post/removefriend/?user="+userName,
		"mimetype": "text/html",
		"load":function(t,html,e){
			if(getRspStat(html)=="ok"){
				toggleDisp(linkObj,"none");
				return;
			}else{
				err=getRspError(html);
				if(!err)err="Error!";
				setInnerHTML(linkObj,err);
			}
		}
	});
}
function addAsFavorite2(type,typeval,successFunc,errorFunc){
	getUrl("/interface/post/addfav/?type="+type+"&typeval="+typeval,successFunc,errorFunc);
}
function addFavArtist(tag,successFunc,errorFunc){
	if(!tag)return;
	getUrl("/interface/post/addfav-qloud/?artist_name="+tag,successFunc,errorFunc);
}

function addAsFavorite(linkObj,type,typeval,errTxt,okTxt){
	//--return true will just cause user to navigate to link
	//--cannot rely on IE xml parsing so doing lame string parsing. ghet-toh
	reloadAdFrames();
	if(!confirm("Add to your favorites?"))return false;
	if(!(linkObj=getDomObj(linkObj)))return true;
	if(!type)return true;
	if(!typeval)return true;
	if(!window.dojo)return true;
	if(!errTxt)errTxt="there was an error";
	if(!okTxt)okTxt="";
	linkObj.href="#";
	setInnerHTML(linkObj,progressimg());
	linkObj.onclick=function(){return false;}
	dojo.io.bind({
		"url":"/interface/post/addfav/?type="+type+"&typeval="+typeval,
		"mimetype":"text/html",
		"load":function(tp,txt,e){
			var status=strfromto(txt,'stat="','"');
			if(status=="ok"){
				var msg=strfromto(txt,"<msg>","</msg>");
				if(okTxt){
					setInnerHTML(linkObj,okTxt);
				} else {
					setInnerHTML(linkObj,"<i>"+msg+"</i>");
					alert("Favorite added");
					toggleDisp(linkObj,"none");
				}

				
				return;
			}else if(status=="fail"){
				var msg=strfromto(txt,"<err>","</err>");
				setInnerHTML(linkObj,"<i>"+msg+"</i>");
				return;
			}else{
				setInnerHTML(linkObj,"<i>"+errTxt+"</i>");
				return;
			}
		}
	});
	return false;
}
function removePhoto(linkObj,eid,callBackfunc,username){//--meant to just be a link. not a lot of UI
	if(!(linkObj=getDomObj(linkObj)))return true;
	if(!eid)return true;
	if(!window.dojo)return true;
	var errtxt="There was an error";
	var url="/interface/post/removephoto/?entry_id="+eid;
	setInnerHTML(linkObj,progressimg());
	linkObj.onclick=function(){return false;}
	dojo.io.bind({
		"url":url,
		"mimetype":"text/html",
		"load":function(tp,txt,e){
			var status=strfromto(txt,'stat="','"');
			if(status=="ok"){
				var msg="The photo was removed";
				setInnerHTML(linkObj,"<i>"+msg+"</i>");
				if(typeof(callBackfunc)=="function"){
					callBackfunc(eid);
				}
				return;
			}else if(status=="fail"){
				var msg=strfromto(txt,"<err>","</err>");
				setInnerHTML(linkObj,"<i>"+msg+"</i>");
				return;
			}else{
				setInnerHTML(linkObj,"<i>"+errtxt+"</i>");
				return;
			}
		}
	});
	return false;
}

function sendPrivateMessage(panelobj,formname,linkobj){
//--return true will just cause user to navigate to link
	//--cannot rely on IE xml parsing so doing lame string parsing. ghet-toh
	if(!window.dojo)return true;
	if(!(panelobj=getDomObj(panelobj)))return true;
	if(!(formname.elements))return true;
	if(!(linkobj=getDomObj(linkobj)))return true;
	//--get vals from form | to_id, subject, body
	setToOffsetSize(panelobj);
	linkobj.onclick=function(){return false;}
	dojo.io.bind({
		"url":"/interface/post/sendmessage/",
		"mimetype":"text/html",
		"formNode":formname,
		"load":function(tp,txt,e){
			var status=strfromto(txt,'stat="','"');
			toggleDisp(panelobj,'none');
			if(status=="ok"){
				var msg=strfromto(txt,"<msg>","</msg>");
				setInnerHTML(linkobj,"<i>"+msg+"</i>");
				return;
			}else if(status=="fail"){
				var msg=strfromto(txt,"<err>","</err>");
				setInnerHTML(linkobj,"<i>"+msg+"</i>");
				return;
			}else{
				setInnerHTML(linkobj,"<i>error sending message</i>");
				return;
			}
		}
	});
	//---swap out panel area with progress while it sends the request. 
	setInnerHTML(panelobj,progresstable());
	return false;
}



//---------------------upload from tags page
function cancelTagsUpload(){
	toggleMenu('postpanel','postbutton');
}
function doTagsUpload(mustAgree){
	if(!mustAgree)mustAgree=0;
	var filetypes=".jpg .jpeg .wmv .mov .mpg .mpeg .avi .3gp .mp4 .m4v".split(" ");
	var err="";
	if(!getValByName("new[caption]"))
		err+="Please give your post a title\n";
	var thefile=getValByName("file").toLowerCase();
	var typeok=0;
	if(thefile){
		for(i=0;i<filetypes.length;i++){
			if(endswith(thefile,filetypes[i])){
				typeok=1;
				break;
			}
		}
		if(!typeok)
			err+="The file you're posting is not a supported filetype\n";
	}else{
		err+="Please choose a file to upload\n";
	}
	if(mustAgree){
		if(!isChecked("agreed_terms")){
			var agreetxt=getInnerHtml("agree_terms_title")
			if(!agreetxt){
				agreetxt="Terms of Use";
			}
			err+="You must agree to the "+agreetxt+"\n";
		}
	}
	if(err.length){
		alert(err);
		return;
	}
	//---error check okay. show processing screen
	toggleDisp('postformcontainer','none');
	setInnerHTML("postformmsg",progresstable("Please wait while your file uploads."));
	toggleDisp('postformmsg','block');
	findObj("postform").submit();
}
function isRegisteredUser(username){//synchronous
	if(!username)return false
	if(!isValidBnDomainName(username))return false;
	var url="/interface/post/checkavail/"+username+"/";
	var res=getUrlContents(url);
	if(!res)return false;
	var stat=strfromto(res,'stat="','"');
	if(stat=="ok")return false;
	return true;
}
/**
 * check if an email is of a registered username
 * @param email - email to be verified
 * 
*/
function isRegisteredEmail(email){
	if(!email)return 0;
	if(!valid_email(email))return 0;
	var url="/interface/post/emailtaken/?email="+email;
	eval("ret="+getUrlContents(url));
	if(typeof(ret.ok)!="undefined")
		return ret.ok;
	return 0;
	
}
function getUserIdByName(username){//synchronous
	if(!username)return 0
	if(!isValidBnDomainName(username))return 0;
	var url="/interface/post/getuseridbyname/"+username+"/";
	var res=getUrlContents(url);
	if(!res)return 0;
	if(stristr(res,"<err"))return 0;
	var id=strfromto(res,'>','</rsp>');
	return id;
}
function isUserNameAvailAsync(username,callBackFunc){//
	//returns hash {result:[true|false],error:'error message'}. error emtpy, of course if result key is true
	//callback func should accept the result has as an arg
	if(typeof(callBackFunc)!='function' && typeof(callBackFunc)!='object')
		callBackFunc=false;
	if(!username){
		res={result:false,error:"no args"};
		if(callBackFunc)
			callBackFunc(res);
		return 
	}
	//--check name format
	if(!isValidBnDomainName(username)){
		res={
			result:false,
			error:"name should have letters and numbers only"
		};
		callBackFunc(res);
		return res;
	}
	dojo.io.bind({
		"url":"/interface/post/checkavail/"+username+"/",
		"method":"GET",
		"mimetype":"text/html",
		"load":function(t,html,e){
			var stat=strfromto(html,'stat="','"');
			if(stat=="ok"){
				if(callBackFunc){
					res={result:true}
					callBackFunc(res);
				}
				return;
			}else{
				if(callBackFunc){
					var err=strfromto(html,"<err>","</err>");
					res={result:false,"error":err};
					callBackFunc(res);
				}
				return 
			}
		},
		"error":function(t,html,e){}
		
	});
	
}


/*===== for rigthside friends list ======*/
function getChangeFriendViewUrl(posttype,altstyle,pageno) {
	return "/interface/post/rightfriends/"+posttype+"/?altstyle="+altstyle+"&pageno="+pageno;
}

function changeFriendView(posttype,altstyle,pageno){
	/*
		document objects:
		rightsidefriendposts - layer that will fill in with posts
		lvideos, lphotos, ljournals lall - ids of href links that get bolded when a given list is turned on
	*/
	if(!posttype)posttype="all";
	if(!altstyle)altstyle="";
	if(!pageno)pageno=0;
	var msgmap={
		 "videos":"getting videos...",
		 "photos":"getting photos...",
		 "journals":"getting journals...",
		 "all":"getting posts..."
	};
	if(!msgmap[posttype])posttype="all";
	var msg=msgmap[posttype];
	var url=getChangeFriendViewUrl(posttype,altstyle,pageno);
	msg='<center style="padding:0px 10px 10px 10px">'+progresstable(msg)+'</center>';
	reloadArea("rightfriendposts",url,msg,"socket error",true);//last arg tells it to put url contents in mem
	SetCookie("rshow",posttype);
	//---make current link bold
	var idnames="lvideos lphotos ljournals lall".split(" ");
	for(i=0;i<idnames.length;i++){
		if(findObj(idnames[i]))
			findObj(idnames[i]).className="";
		if(findObj("l"+posttype))
			findObj("l"+posttype).className="on";
	}
}

function togRTab(obj,showWhat){
	if(showWhat=="cpl"){
		SetCookie("rtshow","cpl");
		togTab(obj,'r-cpl',['r-cpl','r-frnd']);
	}else{
		SetCookie("rtshow","frnd");
		togTab(obj,'r-frnd',['r-cpl','r-frnd']);
		var t=ReadCookie("rshow");
		if(!t)t="all";
		changeFriendView(t,'user-friends-list-postgrid');
	}
}

function ignoreFriend(user_id,posttype,altstyle,pageno) {
	if(!(lObj=getDomObj('rightfriendposts'))) return false;
	var url="/interface/post/ignorefriend/"+user_id+"/";
	
	contentUrl = getChangeFriendViewUrl(posttype,altstyle,pageno);
	if(typeof(HTML_CHUNKS[contentUrl])!='undefined'){
		delete HTML_CHUNKS[contentUrl];
	}
	
	setInnerHTML(lObj,'<center style="padding:0px 10px 10px 10px">'+progresstable('Ignoring...')+'</center>');
	dojo.io.bind({
		"url":url,
		"mimetype":"text/html",
		"load":function(tp,html,e){
			changeFriendView(posttype,altstyle,pageno);
		},
		"error":function(tp,html,e){
			setInnerHTML(lObj,'Socket error');
		}
	});
	
	return true;
}

/*========= for rightside favorites list =======*/
function toggleFriendsFavs(ltype, user_url){
	/*
		document objects: 
		rightfriends and favs: shows the entire right friends/favorites area
		friendslatestlabel: label that says "friends' latest"
		favslatestlabel: label that says "favorites"
		rightsidefriendposts - layer that will fill in with posts
	
	*/
	if(ltype=="favs"){
		SetCookie("rshow","favs");
		setInnerHTML("rightfollowlists",'<div class="data">'+progresstable("Getting favorites...")+'</div>');
		findObj("friendslatestlabel").className="";
		findObj("favslatestlabel").className="on";
		findObj("morelink").href=user_url+'/favorites/';
		var favonload=function(t,html,e){
			if(startswith(html,'<rsp stat="fail">')){
				setInnerHTML("rightfollowlists",strfromto(html,'<err>','</err>'));
				return;
				
			}
			setInnerHTML("rightfollowlists",html)
			return;
		}
		getUrl("/interface/post/rightfavs/",favonload);
		return;
	}
	SetCookie("rshow","all");
	setInnerHTML("rightfollowlists",'<div class="data">'+progresstable("Getting friends' latest...")+'</div>');
	findObj("friendslatestlabel").className="on";
	findObj("favslatestlabel").className="";
	findObj("morelink").href=user_url+'/friends/posts/';
	var friendonload=function(t,html,e){
		if(startswith(html,'<rsp stat="fail">')){
			setInnerHTML("rightfollowlists",strfromto(html,'<err>','</err>'));
			return;
		}
		setInnerHTML("rightfollowlists",html);
		return;
	}
	getUrl("/interface/post/rightfriendswithnav/",friendonload);
}



/*========= generic get url =====*/
function getUrlContents(url,cacheOutput,useJSON){//synchronous
	if(!url)return;
	if(cacheOutput && typeof(getUrlContents.cache[url])!="undefined"){
		return getUrlContents.cache[url];
	}
	ret="";
	var type=(useJSON?"text/json":"text/html");
	dojo.io.bind({
		"url":url,
		"mimetype": type,
		"method":"GET",
		"sync":true,
		"load":function(t,html,e){ret=html;}
	});
	getUrlContents.cache[url]=ret;
	return ret;
}
getUrlContents.cache=[];

function getUrl(url, loadCallBack, errorCallBack,cacheOutput,useJSON){//--asynchronous
	if(!url)return "";
	if(typeof(loadCallBack)!='function' && typeof(loadCallBack)!='object')
		loadCallBack=function(t,html,e){void(0);}
	if(typeof(errorCallBack)!='function' && typeof(errorCallBack)!='object')
		errorCallBack=function(t,html,e){void(0);}
	if(cacheOutput && typeof(getUrlContents.cache[url])!="undefined"){
		loadCallBack(0,getUrlContents.cache[url],0)
		return ;
	}
	lc=function(t,html,e){
		getUrlContents.cache[url]=html;
		loadCallBack(t,html,e);
		
	}
	type=(useJSON?"text/json":"text/html");
	dojo.io.bind({
		"url":url,
		"mimetype": type,
		"method":"GET",
		"load":lc,
		"error":errorCallBack
	});
}

function getRspStat(txt){
	if(!txt)return "";
	return strfromto(txt,'<rsp stat="','"');
}
function getRspError(txt){
	if(!txt)return "";
	return strfromto(txt,"<err>","</err>");
}
function getRspOk(txt){
	if(!txt)return "";
	return strfromto(txt,'<rsp stat="ok">',"</rsp>");
}

function loadRightFollowBar(){
	var loadcallback=function(t,html,e){
		setInnerHTML("rightside",html);
	}
	getUrl("/interface/post/followbar/?_rui_="+escape(location.href),loadcallback);
	
}


/*============================= forums =========================*/
function SubmitNewReply(formObj){
	var err="";
	if(!getValByName("reply[body]")){
		err+="Please enter a reply body\n";
	}
	if(err.length){
		alert(err);
		return false;
	}
	return true;
}
function DeleteReply(reply_id){
	if(!reply_id)return;
	if(!confirm("Are you sure you want to delete this reply?"))return;
	var theurl="/interface/post/forum/deletereply/?id="+reply_id;
	var rrow="reply-"+reply_id+"-row";
	var rcell="reply-"+reply_id+"-cell";
	var rtable="replylist";
	
	setInnerHTML(rcell,progresstable("Deleting reply..."));
	
	function drerror(errmsg){
		if(!errmsg)errmsg="";
		setInnerHTML(rcell,"There was a problem removing the reply. "+errmsg);
		return;
	}
	function drsuccess(t,html,e){
		var stat=getRspStat(html);
		if(stat=="ok"){
			document.getElementById(rtable).removeChild(document.getElementById(rrow));
		}else{
			drerror(getRspError(html));
		}
	}
	getUrl(theurl,drsuccess,drerror);
}
function QuoteReply(reply_id,user_name){
	if(!reply_id)return;
	if(!(repbody=findObj("reply[body]")))return;
	var quoted=findObj("reply-"+reply_id+"-body").innerHTML;
	var reg=/<blockquote>.*<\/blockquote>/g;
	quoted=quoted.replace(reg,"");
	var reg=/<br\s?\/?>/g;
	quoted=quoted.replace(reg,"");
	var quote="[quote"+(user_name?"="+user_name:"")+"]"+quoted+"[/quote]\n";
	insertTextToInput(repbody,strip_tags(quote));
	repbody.scrollIntoView();
}
function ReportTopic(formObj){
	if(!(formObj=getDomObj(formObj)))return true;
	if(!window.dojo)return true;
	if(!getValByName("report[description]")){
		alert("Please tell us why you think this topic should be removed");
		return false;
	}
	setInnerHTML("reportstatus",progresstable("Please wait while your report is submitted"));
	toggleDisp("reportstatus","block");
	toggleDisp("reportform","none");
	dojo.io.bind({
		formNode:formObj,
		"mimetype":"text/html",
		"load":function(t,html,e){
			var stat=getRspStat(html);
			if(stat=="ok"){
				setInnerHTML("reportstatus","Report Submitted");
				setValByName("report[description]","");
				findObj("reportlink").onclick=function(){};
				setTimeout("toggleMenu('reportpanel','reportlink')",1000);
				return false;
			}else{
				var err=getRspError(html);
				if(!err)err="there was a problem submitting your report";
				setInnerHTML("reportstatus",'<div class="error">'+err+'</div>');
				toggleDisp("reportform","block");
				return false;
			}
		}
	});
	return false;	
}
function SubmitNewTopic(){
	var err="";
	if(!getValByName("newtopic[subject]")){
		err+="Please enter a subject for your topic\n";
	}
	if(!getValByName("newtopic[body]")){
		err+="Please enter a body for your topic\n";
	}
	if(err.length){
		alert(err);
		return;
	}
	findObj("theform").submit();
}
function insertForumPic(path,destfieldname){
	if(!isValidPhotoPath(path)){
		alert("Invalid photo url");
		return;
	}
	html='<img src="'+path+'" border="0" />'+"\n\n";
	insertTextToInput(destfieldname,html);
}
function hbmImages(imgs,lnks){
	if(location.hostname.indexOf("."+DBD)!=-1){
		alert("Can't do this inside "+SERVICE_NAME+" pages. The idea is to get pics INTO "+SERVICE_NAME+" from outside :)");
		history.back();
		return;
	}
	var reg=/\.jpe?g$/i;
	document.write('<html><head><title>Post Images To '+SERVICE_NAME+'</title>',
					'</head><body style="width:50%">',
					'<form method="post" action="'+URLPREFIX+'/user/webupload/" name="webuploadform">');
	document.write('<input type="hidden" name="refpage" value="'+location.href+'" />');
	for(i=0;i<imgs.length;i++){
		if(!imgs[i].match(reg))continue;
		document.write('...<input type="hidden" name="webimages[]" value="'+imgs[i]+'" />'+"\n");
	}
	if(typeof(lnks)!="undefined"){
		for(i=0;i<lnks.length;i++){
			if(!lnks[i].match(reg))continue;
			document.write('...<input type="hidden" name="weblinks[]" value="'+lnks[i]+'" />'+"\n");
		}
	}
	document.write("  &nbsp;&nbsp;  &nbsp;&nbsp;    &nbsp;&nbsp;");
	document.write("</form>");
	document.write("Please wait while these images are sent to "+SERVICE_NAME+"...");
	document["webuploadform"].submit();
	document.write("</body></html>");
	//document.webuploadform.submit();
}

function trackLinkClick(linkObj,link_id,samewindow){
	//wasnt passed link id. just follow link
	var clickurl=URLPREFIX+"/linkview/"+link_id+"/";
	if(stristr("."+DBD,linkObj.href))
		samewindow=1;
	windowtarget=window;
	if(linkObj.target || document.getElementsByTagName("base").length){
		if(!linkObj.target && document.getElementsByTagName("base").length){
			if(document.getElementsByTagName("base")[0].getAttribute("target"))
				if(!linkObj.target)
					linkObj.target=document.getElementsByTagName("base")[0].getAttribute("target");
		}
		wndName=linkObj.target;
		if(lc(wndName)=="_top")
			windowtarget=top;
	}
	else wndName="wlink";
	if(!link_id){
		if(samewindow)
			windowtarget.location.href=linkObj.href;
		else
			window.open(linkObj.href,wndName);
		return;
	}
	if(samewindow)
		windowtarget.location.href=clickurl;
	else
		window.open(clickurl,wndName);
}


function addClickTrackers(){
        if(!document.getElementById)return;//can't get dom so most likely can't manipulate it.
        for(i=0;i<document.links.length;i++){
                var ln=document.links[i];
                ct="";
                if((ct=ln.getAttribute("track")))
                {
                        dojo.event.connect(ln, "onclick", function(evt){
                           assignClickTrackers(evt.target);
                           return false;
                        });
                }
				if(ln.getAttribute("track2")!=null)
				{
					dojo.event.connect(ln, "onclick", function(evt)
														{
		                           							assignOmnitureClickTrackers(evt.target);
		                           							return false;
		                        						}
		                        	);
                }
        }
}

function assignClickTrackers(aObj){
	if(aObj.parentNode){
		if(aObj.parentNode.tagName)
			if(aObj.parentNode.tagName.toLowerCase()=="a")
				aObj=aObj.parentNode;
	}
	if(aObj.tagName.toLowerCase()!="a"){
		return false;
	}else if(aObj.href!='#' && aObj.href!=''){
		if(stristr(DBD,aObj.href)){
			SetCookie("_t_", aObj.getAttribute("track"));
			TRACK_NEXT_PAGE=true;//this is so the clicktracker doesn't happen on the source page
			return false;
		}else{
			klik(aObj, aObj.getAttribute("track"));
			return false;
		}
	}
}
/*=====================================Start Omniture click tracker=============================*/
function assignOmnitureClickTrackers(aObj)
{
	if(aObj.parentNode){
		if(aObj.parentNode.tagName)
			if(aObj.parentNode.tagName.toLowerCase()=="a")
				aObj=aObj.parentNode;
	}
	if(aObj.href!='#' && aObj.href!='')
	{
		var s_trackInlineStats=true;
		var s=s_gi(s_account);
		s.prop1=aObj.getAttribute("track2");
		s.tl(aObj,'o',aObj.innerHTML);
	}
}
/*=====================================End Omniture click tracker=============================*/
/*============================================= ranking =================================*/

function setUpRanking(){
	star_on = new Image();
	star_on.src = URLPREFIX+"/assets/star-filled.gif";
	
	star_off = new Image();
	star_off.src = URLPREFIX+"/assets/star-empty.gif";
	
	rankTimer = null;
	rankCount = 0;
}

function showStars(rankNum) {
	clearRankTimer();
	blankStars();
	lightStars(rankNum);
}

function lightStars(rankNum) {
	for (var i=1; i <= rankNum; i++)
		document.getElementById('rank_' + i).src = star_on.src;
}

function blankStars() {
	for (var i=1; i <= 5; i++)
		document.getElementById('rank_' + i).src = star_off.src;
}

function setRank(rankNum) {
	rankform=document.getElementById("rank");
	rankform["entry_rank"].value=rankNum;
	submitRank(rankform);
}

function drawStars(rankNum) {
	clearRankTimer();
	showStars(rankNum);
}

function clearStars() {
	rankTimer = setTimeout("resetStars()", 300);
}

function resetStars() {
	clearRankTimer();
	if (rankCount)
		drawStars(rankCount);
	else
		blankStars();
}

function clearRankTimer() {
	if (rankTimer) {
		clearTimeout(rankTimer);
		rankTimer = null;
	}
}

function drawCurrentRank(rank) {
	if(rank>0){
		for (var i=1; i <= 5; i++){
			document.getElementById('crank_' + i).src = star_off.src;
		}

		for (var i=1; i <= rank; i++){
			document.getElementById('crank_' + i).src = star_on.src;
		}
	}
}

function submitRank(formObject){
	setInnerHTML("yourranktxt","<i>Submitting your rank...</i>");
	var kw = {
		mimetype: "text/plain",
		formNode: formObject,
		load: function(t,txt,e){
			var ret=txt.split(":");
			var rank=ret[0];
			var votes=ret[1];
			var score=ret[2];
			var yourrank=ret[3];
			drawCurrentRank(rank);
			setInnerHTML("ranktxt","Current Rank ("+votes+" votes)");
			setInnerHTML("yourranktxt","Your Rank");
			setInnerHTML("ystars"," <img src='"+URLPREFIX+"/assets/star-empty.gif' id='rank_1' border='0'> <img src='"+URLPREFIX+"/assets/star-empty.gif' id='rank_2' border='0'> <img src='"+URLPREFIX+"/assets/star-empty.gif' id='rank_3' border='0'> <img src='"+URLPREFIX+"/assets/star-empty.gif' id='rank_4' border='0'> <img src='"+URLPREFIX+"/assets/star-empty.gif' id='rank_5' border='0'>");
			drawStars(yourrank);
		},
		error: function(t,e){}
	};
	dojo.io.bind(kw);
	return false;
}


function toggleGroupsMenu(menuObj,linkObj,post_id){
	if(!menuObj || !linkObj || !post_id)return;
	var url="/interface/post/groups/getsendtogrouplist/?post_id="+post_id;
	toggleMenu(menuObj,linkObj);
	if(typeof(MENU_ITEMS_GRABBED)!="undefined"){
		if(MENU_ITEMS_GRABBED)
			return;
	}
	setInnerHTML(menuObj,progresstable("Please wait while we get your groups"));
	var doLoad=function(t,txt,e){
		if(getRspStat(txt)=="ok"){
			setInnerHTML(menuObj,getRspOk(txt));
			hcode="";
		}else{
			alert(txt);
			setInnerHTML(menuObj,"Error: "+getRspError(txt));
		}
		MENU_ITEMS_GRABBED=1;
	}
	var doError=function(t,txt,e){
		setInnerHTML(menuObj,"There was an error");
	}
	getUrl(url, doLoad, doError);
}

function sendToGroup(postId,groupId, setId){
	/*
		document objects:
			addgroupmenu - div that gets filled in with user's group listing
			addgroupbut   - button that opened the menu
	*/
	if(!postId || !groupId)return 0;
	if(!setId)setId=0;
	MENU_ITEMS_GRABBED=0;
	var url="/interface/post/groups/sendtogroup/?post_id="+postId+"&group_id="+groupId+"&set_id="+setId;
	setInnerHTML("addgroupmenu",progresstable("Please wait while we add the post..."));
	var doLoad=function(t,txt,e){
		if(getRspStat(txt)=="ok"){
			setInnerHTML("addgroupmenu","The post was added!");
			setTimeout("toggleMenu('addgroupmenu','addgroupbut')",2000);
		}else{
			setInnerHTML("addgroupmenu","Error: "+getRspError(txt));
			setTimeout("toggleMenu('addgroupmenu','addgroupbut');",2000);
		}
	}
	var doError=function(t,txt,e){
		setInnerHTML("addgroupmenu","Unspecified error");
		setTimeout("toggleMenu('addgroupmenu','addgroupbut')",1500);
	}
	getUrl(url, doLoad, doError);
}


function removeFromGroup(postId,groupId){
	/*
		document objects:
			addgroupmenu - div that gets filled in with user's group listing
			addgroupbut   - button that opened the menu
	*/
	if(!postId || !groupId)return 0;
	MENU_ITEMS_GRABBED=0;
	var url="/interface/post/groups/removefromgroup/?post_id="+postId+"&group_id="+groupId
	setInnerHTML("addgroupmenu",progresstable("Please wait while we remove the post..."));
	var doLoad=function(t,txt,e){
		if(getRspStat(txt)=="ok"){
			setInnerHTML("addgroupmenu","The post was removed!");
			setTimeout("toggleMenu('addgroupmenu','addgroupbut')",2000);
		}else{
			setInnerHTML("addgroupmenu","Error: "+getRspError(txt));
			setTimeout("toggleMenu('addgroupmenu','addgroupbut');",2000);
		}
	}
	var doError=function(t,txt,e){
		setInnerHTML("addgroupmenu","Unspecified error");
		setTimeout("toggleMenu('addgroupmenu','addgroupbut')",1500);
	}
	getUrl(url, doLoad, doError);
}

function submitVote(type,typeval,button,buttonObj,counterObj,keepStatus,successHandler,permalink){
	reloadAdFrames();
	//keepstatus makes it not hide the "buzzed" text.
	//successHandler gets called on successful buzz
	if(typeof(permalink)=="undefined")permalink=0;
	var url="/interface/post/vote/?type="+type+"&typeval="+typeval+(permalink?"&permalink="+escape(permalink):"");
	if(!type || !typeval){
		return;
	}
	if(buttonObj)
		buttonObj=getDomObj(buttonObj);
	if(counterObj)
		counterObj=getDomObj(counterObj);
	//warn user they gotta be signed in
	if(!isSignedIn()){
		modalLogin.open("You must be signed in to "+VOTE_NAME);
		return false;
	}
	//null out click action on buzz button
	if(buttonObj)
		button.onclick=function(){void(0);}
	//increment counter
	if(counterObj.innerHTML){
		oldcount=parseInt(counterObj.innerHTML.replace(/[^\d]+/g,""));
		if(!isNaN(oldcount)){
			setInnerHTML(counterObj,(oldcount+1));
		}else{
			oldcount="";
		}
	}
	//hide hide buzz button to note the action was done 
	if(buttonObj){
		if(typeof(successHandler)!="function")
			setInnerHTML(buttonObj,VOTE_NAME_PLEURAL);
		if(!keepStatus && buttonObj.id){
			setTimeout("toggleDisp('"+buttonObj.id+"','none')",1000);
		}
	}
	//run custom success handler
	if(typeof(successHandler)=="function"){
		successHandler(type,typeval,button,buttonObj,counterObj);
	}
	var sLoad=function(t,txt,e){
		if(getRspStat(txt)=="ok"){
			//not doing any default actions now...
		}else{
			//roll back what was changed
			var err=getRspError(txt);
			//decrement counter
			if(counterObj && counterObj.innerHTML && typeof(oldcount)!="undefined"){//roll back counter
				setInnerHTML(counterObj,oldcount);
			}
			//redisplay buzz text if no custom handler
			if(buttonObj && typeof(successHandler)!="function")
				setInnerHTML(buttonObj,VOTE_NAME_PLEURAL);
			//alert user why buzz wasn't accepted
			if(err && buttonObj){
				richAlert(err,buttonObj)
			}else{
				err=(err?err:"There was an error. Please try again later.");
				alert(err);
			}
			return;
		}
	}
	getUrl(url,sLoad);
	return;
}

function VoteOnFaceBookGeneral(title,url,medium_body,thumb,bundle_id){
	if(title && url && medium_body && thumb && bundle_id){
		title = unescape(title);
		medium_body = unescape(medium_body);
		var template_data = {"playlist":'<a href="'+url+'" target="_blank">'+title+'</a>',
                    "service_name":'<a href="'+URLPREFIX+'" target="_blank">'+SERVICE_NAME+'</a>',
                    "playlist_body":'<a href="'+url+'" target="_blank">'+medium_body+'</a>',
                    "images":[{'src':thumb, 'href':url}]};
        FB.ensureInit(function() {
			FB.Connect.showFeedDialog(bundle_id, template_data);
		});
	}
}

function removeTag(base64_tag,entry_id,entry_type){
	if(!base64_tag || !entry_id || !entry_type)return;
	if(!confirm("Remove this tag?"))return;
	//doc object: tag-base64_tag
	var url="/interface/post/removetag/?tag="+base64_tag+"&entry_id="+entry_id+"&type="+entry_type;
	cont="tag-"+base64_tag+entry_id+entry_type;
	toggleDisp(cont,"none");
	var doLoad=function(t,txt,e){
		if(getRspStat(txt)=="ok"){
			return;
		}else{
			toggleDisp(cont,"inline")
			var err=getRspError(txt);
			if(err){
				alert(err);
			}else{
				alert("Problem removing tag");
			}
		}
	}
	getUrl(url,doLoad);
	return;
}
function removeTagByPostId(base64_tag,postId,elToHide){
	if(!base64_tag || !postId)return;
	var url="/interface/post/removetag/?tag="+base64_tag+"&post_id="+postId;
	toggleDisp(elToHide,"none");
	getUrl(url,function(){void(0);});
}
function removeTagByEntryId(base64_tag,entryId,type,elToHide){
	if(!base64_tag || !entryId || !type)return;
	var url="/interface/post/removetag/?tag="+base64_tag+"&entry_id="+entryId+"&type="+type;
	toggleDisp(elToHide,"none");
	getUrl(url,function(){void(0);});
}
function addToPlayList(audio_file_id,linkObj,ptxt,callBack){
	if(!audio_file_id)return;
	linkObj=dojo.byId(linkObj);
	var url="/interface/post/audio/playlist/additem/?id="+audio_file_id;
	if(!ptxt)ptxt="Playlist";
	if(linkObj){
		if(ptxt=="Playlist"){//only do "-Playlist" if the text is "playlist"
			setInnerHTML(linkObj,"-"+ptxt);
		}else{
			setInnerHTML(linkObj,ptxt);
		}
		linkObj.onclick=function(){void(0);}
	}
	getUrl(url,function(t,txt,e){
		if(getRspStat(txt)=="ok"){
			if(linkObj){
				linkObj.onclick=function(){
					removeFromPlaylist(audio_file_id,linkObj);
				}
				linkObj.title="Remove from playlist";
			}
			if(typeof(callBack)=="function")
					callBack(audio_file_id,linkObj);
		}
	});
}
function removeFromPlaylist(audio_file_id,linkObj){
	if(!audio_file_id)return;
	linkObj=dojo.byId(linkObj);
	var url="/interface/post/audio/playlist/removeitem/?id="+audio_file_id;
	if(linkObj){
		setInnerHTML(linkObj,"+Playlist");
		linkObj.onclick=function(){void(0);}
	}
	getUrl(url,function(t,txt,e){
		if(getRspStat(txt)=="ok"){
			if(linkObj){
				linkObj.onclick=function(){
					addToPlayList(audio_file_id,linkObj);
				}
				linkObj.title="Add to playlist";
			}else{
				//alert("no link obj");
			}
		}else{
			alert("Problem removing that from your playlist");
		}
	});
}
function popUserAudioPlayer(username){
	if(!username)return;
	window.open("http://"+username+"."+DBD+"/user/audio/popup/",'pwindow','width=300,height=122,scrollbars=no,resizable=yes,location=no,status=no');
}
function delicious(titleObj,bodyObj){
	var title="";var body="";
	if(titleObj && (titleObj=getDomObj(titleObj))){
		if(titleObj.innerHTML)
			title=strip_tags(titleObj.innerHTML);
	}
	if(!title)title=document.title;
	if(bodyObj && (bodyObj=getDomObj(bodyObj))){
		if(bodyObj.innerHTML){
			body=strip_tags(bodyObj.innerHTML);
			if(body){
				if(body.length>250)body=body.substring(0,340);
			}
		}
	}
	if(getDomObj("taglist")){
		var tags=getElementsByAttribute(getDomObj("taglist"),"a","rel","tag");
		for(i=0;i<tags.length;i++){
			tags[i]=tags[i].innerHTML.replace(" ","");
		}
		tags=tags.join(" ");
	}else{
		tags="";
	}
	tags+=" "+SERVICE_NAME;
	window.open("http://del.icio.us/post?url="+escape(location.href)+";title="+escape(title)+";notes="+escape(body)+";tags="+escape(tags));
}
function diggIt(titleObj,bodyObj){
	var title="";var body="";
	if(titleObj && (titleObj=getDomObj(titleObj))){
		if(titleObj.innerHTML)
			title=strip_tags(titleObj.innerHTML);
	}
	if(!title)title=document.title;
	if(bodyObj && (bodyObj=getDomObj(bodyObj))){
		if(bodyObj.innerHTML){
			body=strip_tags(bodyObj.innerHTML);
			if(body){
				if(body.length>250)body=body.substring(0,340);
			}
		}
	}
	window.open("http://digg.com/submit?phase=2&url="+escape(location.href)+"&title="+escape(title)+"&bodytext="+escape(body));
}
function linkPostIt(username, titleObj,bodyObj){
	//submit as link post to buzznet. tries to grab thumbnail out of content as well
	if(!username)return;
	var title="";var body=""; var theimage="";
	var url=location.href;
	if(stristr('/photo',url) || stristr("/featured",url) || stristr("/cat",url)){//try to pull main image to post as a thumbnail
		for(i=0;i<document.images.length;i++){
			if(stristr("large-",document.images[i].src)){
				theimage=escape(document.images[i].src);
				break;
			}
		}
	}
	if(stristr("/video",url)){//try to pull the thumbnail out of the buzznet embed tag
		var id=document.getElementById("vembed").getAttribute("vidid");
		if(id){
			var dirs=id.split("").join("/");
			theimage="http://cdn.buzznet.com"+JS_VIDEO_DIR+"/"+dirs+"/thumb-"+id+".jpg";
		}
	}
	if(getDomObj("itembody")){//pull image out of a blog post
		var imgs=getDomObj("itembody").getElementsByTagName("img");
		if(imgs.length){
			theimage=imgs[0].src;
		}
	}
	//post metadata
	if(titleObj && (titleObj=getDomObj(titleObj))){
		if(titleObj.innerHTML)
			title=strip_tags(titleObj.innerHTML);
	}
	if(!title)title=document.title;
	if(bodyObj && (bodyObj=getDomObj(bodyObj))){
		if(bodyObj.innerHTML){
			body=strip_tags(bodyObj.innerHTML);
			if(body){
				if(body.length>250)body=body.substring(0,340);
			}
		}
	}
	if(getDomObj("taglist")){
		var tags=getElementsByAttribute(getDomObj("taglist"),"a","rel","tag");
		for(i=0;i<tags.length;i++){
			tags[i]=tags[i].innerHTML;
		}
		tags=tags.join(", ");
	}else{
		tags="";
	}
	var durl="http://"+username+"."+DBD+"/user/links/edit/?thelink[url]="+escape(url)+"&thelink[title]="+escape(title)
			+"&thelink[body]="+escape(body)+"&imgurl="+theimage+"&newtags="+tags;
	window.open(durl);
}
function myspaceIt(titleObj,bodyObj){
	//submit as link post to buzznet. tries to grab thumbnail out of content as well
	if(!confirm("You must already be signed in to MySpace in order for this to work.\nContinue?"))return;	
	var title="";var body=""; var theimage="";
	var url=location.href;
	if(stristr('/photo',url) || stristr("/featured",url) || stristr("/cat",url)){//try to pull main image to post as a thumbnail
		for(i=0;i<document.images.length;i++){
			if(stristr("large-",document.images[i].src)){
				theimage=escape(document.images[i].src);
				break;
			}
		}
	}
	var id=document.getElementById("vembed");
	if(id){
		if(id.getAttribute("vidid")){
			id=id.getAttribute("vidid");
			var dirs=id.split("").join("/");
			theimage="http://cdn.buzznet.com/assets/videox/"+dirs+"/thumb-"+id+".jpg";
		}
	}
	//post metadata
	if(titleObj && (titleObj=getDomObj(titleObj))){
		if(titleObj.innerHTML)
			title=strip_tags(titleObj.innerHTML);
	}
	if(!title)title=document.title;
	if(bodyObj && (bodyObj=getDomObj(bodyObj))){
		if(bodyObj.innerHTML){
			body=strip_tags(bodyObj.innerHTML);
			if(body){
				if(body.length>250)body=body.substring(0,340);
				body=nl2br(body);
			}
		}
	}
	var bodytext="";
	if(theimage)
		bodytext="<center>"+cimg(theimage,url,'alt="Hosted on '+SERVICE_NAME+'"')+"</center>";
	else
		bodytext=title.link(url)+"\n<br /><br />";
	bodytext+=body;
	myspacePrefillBlogForm(title,bodytext);
}
function myspacePrefillBlogForm(title,body){
	var posturl="http://blog.myspace.com/index.cfm?fuseaction=blog.create&editor=true&safe=0";
	var frm=document.createElement("form");
	frm.action=posturl;
	frm.method="post";
	frm.target="_blank";
	var hid=document.createElement("input");
	hid.type="hidden";hid.name="subject";
	hid.value=title?title:"Untitled Post from Buzznet";
	frm.appendChild(hid);
	hid=document.createElement("input");hid.type="hidden";hid.name="body";
	hid.value=body?body:"";
	frm.appendChild(hid);
	document.body.appendChild(frm);
	frm.submit();
}
function createVoteToolTip(typeval,browserIsHome){
	return;
	if(typeof(DOJO_TOOLTIP_INIT)=="undefined"){//find dojo property for this
		dojo.require("dojo.widget.Tooltip");
		DOJO_TOOLTIP_INIT=1;
	}
	document.write('<div id="tt'+typeval+'"><div dojoType="tooltip" connectId="votetotal'+typeval+'" toggle="explode" toggleduration="150" class="tooltip"><div class="tooltipc"><b>'+ucwords(VOTE_NAME)+'</b> means you like this and would recommend it to someone');
	if(browserIsHome)
		document.write('<div class="small" style="margin-top:.5em">Disable '+VOTE_NAME+' in Settings &raquo; Account Info</div>');
	document.write('</div></div></div>');
	djConfig["searchIds"].push("tt"+typeval);
}
function addEntryLabels(formObj,counter){
	/*
		assumed dom objects: labelform, labelmsg, addlabelssmenu,addlabelsbut
	*/
	toggleDisp(formObj,"none");
	var lmsg="labelmsg"+counter;
	var lbut="addlabelsbut"+counter;
	var lmen= "addlabelssmenu"+counter;
	setInnerHTML(lmsg,progresstable("Please wait..."));
	dojo.io.bind({
		"formNode":formObj,
		"mimetype": "text/html",
		"load":function(tp,html,e){
			if(getRspStat(html)=="ok"){
				setInnerHTML(lmsg,"Labels for the entry were saved");
				setTimeout("hideOtherMenus('');toggleDisp('"+formObj.id+"','block')",1000);
				return;
			}else{
				setInnerHTML(lmsg,getRspError(html));
				toggleDisp(lbut,"block");
				return;
			}
		},
		"error":function(){
			setInnerHTML(lmsg,"There was an error in editing that entry's labels");
			return;
		}
		
	});
	return false;
}
function openLabelChildren(lbl,lcounter){
	var childs=getElementsByAttribute(getDomObj("labels"+lcounter),"tr","childof",lbl);
	for(i=0;i<childs.length;i++){
		toggleDisp(childs[i],"block");
	}
}
function addEmailUpdate(formObj){
	/*
		assumed dom objects: eupdates, eupdatesform, eupdatesbut, eupdatesmsg,eupdates[email]
	*/
	if(!validEmailValue("eupdates[email]")){
		alert("Please enter a valid email address");
		return false;
	}
	toggleDisp(formObj,"none");
	setInnerHTML("eupdatesmsg",progresstable("Please wait..."));
	dojo.io.bind({
		formNode:formObj,
		"mimetype": "text/html",
		load:function(type,html,e){
			if(getRspStat(html)=="ok"){
				setInnerHTML("eupdatesmsg","Subscription added!");
				setTimeout("toggleDisp('eupdates','none');",1000);
			}else{
				var err=getRspError(html);
				setInnerHTML("eupdatesmsg",err);
				toggleDisp(formObj,"block");
			}
			return false;
		},
		error:function(){
			setInnerHTML("eupdatesmsg","There was a problem...");
			return false;
		}
	});
	return false;
}

function richAlert(msg,relativeObj,hideClose){
	if(!getDomObj("AlertBox")){
		var abox=document.createElement("div");
		abox.id="AlertBox";
		abox.className="clickmenu";
		abox.style.border="1px #000 solid";
		abox.style.borderRightWidth="3px";
		abox.style.borderBottomWidth="3px";
		abox.style.width="250px";
		abox.style.padding="8px";
		abox.innerHTML='<table width="100%" cellpadding="0" cellspacing="0"><tbody><tr>'
					  +'<td width="99%" id="AlertBoxText">&nbsp;</td>'
					  +(hideClose?'':'<td width="1%" id="AlertBoxCloseCol"><input type="button" class="buttoninput" id="AlertBoxClose" value="X" onclick="toggleMenu(\'AlertBox\',this,\'\',0)" title="Close" /></td>')
					  +'</tr></tbody></table>';
		document.body.appendChild(abox);
	}
	setInnerHTML("AlertBoxText",msg);
	toggleMenu('AlertBox',relativeObj,"",1);
}
function altText(msg,relativeObj){
	richAlert(msg,relativeObj,true);
}
function hideAltText(){
	hideOtherMenus();
}
/**
 * dynamically load a script and optionally run an event handler when action completed.
 * 
*/
function scriptOnDemand(scripturl,handler){
	var sid="dscript-"+scripturl;
	if(typeof(handler)!="function")
		handler=function(){void(0);}
	if(!document.getElementById(sid)){
		var scr=createEl("script",{"src":scripturl,"id":sid,"type":"text/javascript"});
		if(document.all){
			scr.onreadystatechange=function(){
				if(this.readyState=="complete" || this.readyState=="loaded"){
					handler();
				}
			}
		}else{
			scr.onload=handler;
		}
		document.getElementsByTagName("head")[0].appendChild(scr);
	}else{
		handler();
	}
}

/**
 * creates a modal dialog window. object will be reused if called a second time. 
 * @param str dialogId - id of the dialog window. after created getDialog(dialogId).show() and getDialog(dialogId).hide() methods will exist
 * @param mixed contents - what's inside the dialog window. if a string will fill the login with the string, if a DOM obj that will be the contents of the dlg
 * @param bool defaultOpen - optional - that'll tell it to open the dialog by default 
 * @param str cssUrl - optional - url of a css that will get dynamically loaded before the dialog window
*/
function createDialog(dialogId,contents,defaultOpen,cssUrl){
	var dlg, container, css, ret;
	if(dlg=getDialog(dialogId)){
		dlg.setContent(contents);
		//dlg.refresh();
		if(defaultOpen){
			dlg.show();
			var cl=getElementsByClassName(dialogId,"dlg-close");
			if(cl && typeof(cl[0])!=="undefined"){
				dlg.setCloseControl(cl);
			}
		}
		return dlg;
	}
	//optionally load in a stylesheet to format the dialog
	if(cssUrl){
		addStyleSheet(cssUrl);
	}
	//set up the object that's going to be the contents of the dialog window
	if(typeof(contents)=="object"){
		container=contents;
	}else{
		container=createEl("div",{"id":"dlgContainer"+dialogId});
		container.innerHTML=contents;
		document.getElementsByTagName("body")[0].appendChild(container);
	}
	//creaturn the dialog window
	ret = dojo.widget.createWidget("Dialog",{
		"id":dialogId,
		"bgColor":"#000000","bgOpacity":"0.85","toggle":"fade","toggleDuration":100
	}, container);
	var cl=getElementsByClassName(dialogId,"dlg-close");
	if(cl && typeof(cl[0])!=="undefined"){
		ret.setCloseControl(cl);
	}
	//if dialog is open by default then allow esc key to close it
	if(defaultOpen){
		ret.show();
		onkeyevent("escape",function(){
			if((dlg=getDialog(dialogId)))dlg.hide();
		});
	}
	return ret;
}
function skinDialog(title,content,contentId){
	if(!contentId)contentId="";
	return '<div class="dlg-title"><a href="#" class="dlg-close" onclick="return false"></a>'+title+'</div>'
		  +'<div class="dlg-content"'+(contentId?'id="'+contentId+'"':"")+'>'+content+'</div>';
}
function getDialog(dialogId){
    var dlg=dojo.widget.byId(dialogId);
	return (dlg?dlg:0);
}
function addStyleSheet(url){
	var cssid="css_"+getTagDirname(url);
	if(getDomObj(cssid)){return;}
	var css=createEl("link",{"rel":"stylesheet","type":"text/css","id":cssid,"href":url});
	document.getElementsByTagName("head")[0].appendChild(css);
}
function popLoginBox(relativeObj){
	if(!getDomObj("loginbox")){
		var lbox=document.createElement("div");
		lbox.id="loginbox";
		lbox.className="clickMenu";
		lbox.style.border="1px #000 solid";
		lbox.style.borderRightWidth="3px";
		lbox.style.borderBottomWidth="3px";
		lbox.style.width="250px";
		lbox.style.padding="8px";
		lbox.style.paddingTop="6px";
		lbox.style.paddingRight="4px";
		lbox.innerHTML='<div style="float:right">'
					  +'<a href="#" onclick="toggleDisp(\'loginbox\',\'none\');return false" class="buttoninput">&nbsp;x&nbsp;</a></div>'
					  +'<div id="loginboxmsg" style="display:none"></div>'
					  +'<div id="loginboxfields" style="margin-top:0.5em">'
					  +'<form method="post" action="/interface/post/login/" onsubmit="return doPopupSignIn(this)">'
					  +refer()
					  +'<table cellspacing="0" cellpadding="2" width="97%"><tr valign="bottom">'
				      +'<td style="padding-bottom:0px" width="50%"><label for="username">Username:</label></td>'
					  +'<td style="padding-bottom:0px" width="50%"><label for="password">Password:</label></td>'
					  +'</tr><tr>'
					  +'<td><input type="text" name="username" style="width:100%" class="textinput" /></td>'
					  +'<td colspan="2"><input type="password" name="password" style="width:100%" class="textinput" /></td>'
					  +'</tr><tr>'
					  +'<td colspan="3">'
					  +'<input type="submit" value="Sign In" class="buttoninput" />'
					  +'<a href="'+URLPREFIX+'/www/forgotpass/" style="padding-left:1em;white-space:nowrap">Forget your password?</a>'
					  +'</td></tr></table></form>'
					  +'</div>';
		document.body.appendChild(lbox);
	}
	toggleMenu("loginbox",relativeObj,"",1);
}

function popStatusBox(relativeObj){
	if(!getDomObj("loginbox")){
		var lbox=document.createElement("div");
		lbox.id="loginbox";
		lbox.className="clickMenu";
		lbox.style.border="1px #000 solid";
		lbox.style.borderRightWidth="3px";
		lbox.style.borderBottomWidth="3px";
		lbox.style.width="250px";
		lbox.style.padding="8px";
		lbox.style.paddingTop="6px";
		lbox.style.paddingRight="4px";
		lbox.innerHTML='<div style="float:right">'
					  +'<a href="#" onclick="toggleDisp(\'loginbox\',\'none\');return false" class="buttoninput">&nbsp;x&nbsp;</a></div>'
					  +'<div id="loginboxmsg" style="display:none"></div>'
					  +'<div id="loginboxfields" style="margin-top:0.5em">'
					  +'<form method="post" action="/interface/post/login/" onsubmit="return doPopupSignIn(this)">'
					  +refer()
					  +'<table cellspacing="0" cellpadding="2" width="97%"><tr valign="bottom">'
				      +'<td style="padding-bottom:0px" width="50%"><label for="username">Username:</label></td>'
					  +'<td style="padding-bottom:0px" width="50%"><label for="password">Password:</label></td>'
					  +'</tr><tr>'
					  +'<td><input type="text" name="username" style="width:100%" class="textinput" /></td>'
					  +'<td colspan="2"><input type="password" name="password" style="width:100%" class="textinput" /></td>'
					  +'</tr><tr>'
					  +'<td colspan="3">'
					  +'<input type="submit" value="Sign In" class="buttoninput" />'
					  +'<a href="'+URLPREFIX+'/www/forgotpass/" style="padding-left:1em;white-space:nowrap">Forget your password?</a>'
					  +'</td></tr></table></form>'
					  +'</div>';
		document.body.appendChild(lbox);
	}
	toggleMenu("loginbox",relativeObj,"",1);
}

function changeLoginColor(color){
    var login_btn = document.getElementById("login_btn");
    login_btn.style.backgroundColor="";
}

function bn_popLoginBox(relativeObj){ // login overlay for buzznet
	var btn = document.getElementById("login_btn");
	btn.style.backgroundColor="#868686";
		
	if(!getDomObj("loginbox")){
		var lbox=document.createElement("div");
		bn_buildLoginBox(lbox);
		document.body.appendChild(lbox);
	} else {
		bn_buildLoginBox(getDomObj("loginbox"));
	}
	toggleMenu("loginbox",relativeObj,"belowleft",1);
}

function bn_popLoginBoxCustom(relativeObj, style) {
	if(!(lbox=getDomObj("loginbox"))){
		var lbox=document.createElement("div");
		bn_buildLoginBox(lbox);
		document.body.appendChild(lbox);
	} else {
		bn_buildLoginBox(lbox);
	}
	
	for (var i in style) {
		if (lbox.style[i]) {
			lbox.style[i] = style[i];
		}
	}
	toggleMenu("loginbox",relativeObj,"belowleft",1);
}

function bn_buildLoginBox(lbox) {
	lbox.id="loginbox";
	lbox.className="clickMenu";
	lbox.style.width="283px";
	lbox.style.height="140px";
	lbox.style.border="none";
	lbox.style.margin="0px 0px 0px 0px";
	lbox.style.background="url(http://cdn.buzznet.com/assets/pages/bn_popLogin/signin_bg_center.png)";
	lbox.style.padding="5px 18px 0 18px";
	lbox.style.zIndex=2000;
	lbox.innerHTML=           '<div id="loginboxmsg" style="display:none"></div>'
							  +'<div id="loginboxfields" style="margin-top:0.5em">'
							  +'<form method="post" name="popLogin" action="/interface/post/login/" onsubmit="return bn_doPopupSignIn(this)">'
							  +refer()
							  +'<table cellspacing="0" cellpadding="5" style="font-weight:bold; text-transform:uppercase;"><tr valign="bottom">'
							  +'<td style="padding-bottom:0px; font-size:10px;z-index:2000;" width="127">'
							  +'<label for="username" style="color:#FFF">Username:</label></td>'
							  +'<td style="padding-bottom:0px; font-size:10px;" ><label for="password" style="color:#FFF">Password:</label></td>'
							  +'</tr><tr>'
							  +'<td><input type="text" name="username" style="width:110px;" class="textinput" /></td>'
							  +'<td><input type="password" name="password" style="width:110px;" class="textinput" /></td>'
							  +'</tr><tr>'
							  +'<td><a href="'+URLPREFIX+'/www/forgotpass/" style="color:#fff; font-size:9px; font-weight:bold;'
							  +'letterspacing:1px; border-bottom:solid 1px #878787;" onmouseover="this.style.color=\'#a4a4a4\'"'
							  +'onmouseout="this.style.color=\'#fff\'">Forget Login Info?</a></td>'
							  +'<td style="font-size:9px; font-weight:bold; letterspacing:1px;">&nbsp;</td>'
							  +'</tr><tr>'
							  +'<td colspan="2"><input type="submit" value="SIGN IN"'
							  +'style="color:#FFF; background-color:#a4a4a4; font-size:9px; font-weight:bold;'
							  +'height:21px; width:59px; border:none; outline:none; " onmouseover="this.style.background=\'#7b7b7b\'"'
							  +'onmouseout="this.style.background=\'#a4a4a4\'" /></td>'
							  +'</tr><tr><td colspan=2 style="padding-top:17px; text-align:right;">'
							  +'<div>'
							  +'<a href="#" style="color:#fff; font-size:9px; font-weight:normal; position:absolute; bottom:8px; right:5px;"'
							  +'onmouseover="this.style.color=\'#a4a4a4\'" onmouseout="this.style.color=\'#fff\'"'
							  +'onclick="changeLoginColor(\'#fff\'); toggleDisp(\'loginbox\',\'none\');return false;">CLOSE&nbsp;'
							  +'<img src="http://cdn.buzznet.com/assets/pages/02_close.gif" border="0"'
							  +'style="margin-bottom:-3px;" /></a></div></td>'
							  +'</tr></table></form>'
							  +'</div>';
}

function bn_doPopupSignIn(formObj){	
	//doc objects: loginbox, loginboxmsg, loginboxfields
	var err="";
	if(!formObj.elements["username"].value || !formObj.elements["password"].value)
		err+="Invalid username/password";
	if(err.length){
		toggleDisp("loginboxmsg","block");
		setInnerHTML("loginboxmsg","<div class='loginMsg'>"+err+'</div>');
		return false;
	}
	toggleDisp("loginboxfields","none");
	toggleDisp("loginboxmsg","block");
	setInnerHTML("loginboxmsg", bn_progresstable(" Signing in..."));
        dojo.io.bind({
		"formNode":formObj, 
		"mimetype": "text/html",
		"load":function(typ,html,e){
			if(getRspStat(html)=="ok"){
				setInnerHTML("loginboxmsg","<div style='font-size:12px;color:#fff;position:absolute;top:45;left:105;'>Signed in!</div>");
				setTimeout("toggleDisp('loginbox','none'); location.replace(location.href);",1000);
				return;
			}else{  
				setInnerHTML("loginboxmsg","<div class='loginMsg'>Invalid login</div>");
				toggleDisp("loginboxfields","block");
				formObj.elements["password"].value="";
				return false;
			}
		}
	});
	return false;
}

function doPopupSignIn(formObj){	
	//doc objects: loginbox, loginboxmsg, loginboxfields
	var err="";
	if(!formObj.elements["username"].value || !formObj.elements["password"].value)
		err+="Invalid username/password";
	if(err.length){
		toggleDisp("loginboxmsg","block");
		setInnerHTML("loginboxmsg",'<div class="error">'+err+'</div>');
		return false;
	}
	toggleDisp("loginboxfields","none");
	toggleDisp("loginboxmsg","block");
	setInnerHTML("loginboxmsg", progresstable("Signing in..."));
	dojo.io.bind({
		"formNode":formObj, 
		"mimetype": "text/html",
		"load":function(typ,html,e){
			if(getRspStat(html)=="ok"){
				setInnerHTML("loginboxmsg","<b>Signed in!</b>");
				setTimeout("toggleDisp('loginbox','none');location.replace(location.href);",1000);
				return;
			}else{
				setInnerHTML("loginboxmsg",'<div class="error">Invalid login</div>');
				toggleDisp("loginboxfields","block");
				formObj.elements["password"].value="";
				return false;
			}
		}
	});
	return false;
}

function bn_getSignInOutLink(signInText,signOutText){ // generates buzznet nav
        if(!signInText)signInText="Sign In";
        if(!signOutText)signOutText="Sign Out";
        if(isSignedIn()){
                return '<a href="/user/logout/?refer='+refer(1)+'" class="JoinButton">'+signOutText+'</a>';
        }else{
                return '<a href="/user/login/?refer='+refer(1)+'" id="login_btn" class="SigninButton" onclick="bn_popLoginBox(this);return false">'+signInText+'</a>';
        }
}
modalLogin={
	"inited":0,
	"dlgId":"mlogin",
	"fwdUrl":"",
	"htmlurl":"/interface/post/modalloginbox/",
	"cssurl":CDN_HOST+"/assets/cssjs/modal-login.css",
	"customMessage":"",
	"init":function(){
		if(isSignedIn())return false;
		if(this.inited)return true;
		this.createDialog();
		this.inited=1;
		return true;
	},
	"createDialog":function(){
		if(this.inited)return;
		var hideSignUp=($d("users[user_name]")?1:0);
		createDialog(this.dlgId,getUrlContents(this.htmlurl),false,this.cssurl);
		if(hideSignUp)hideAll("mlogin-signupnow","mlogin-footer");
	},
	"close":function(){	
		this.message("");
		hideAll("mlogin-wrap");
		getDialog(this.dlgId).hide();
		modalLogin.fwdUrl="";
	},
	"open":function(headerText,fwdUrl){
		if (!headerText) headerText = "You must be signed in to do that";	
		if(!this.init())
			return false;
		if(fwdUrl)this.fwdUrl=fwdUrl;
		getDialog(this.dlgId).show();
		setInnerHTML("mlogin-header-text",headerText);
		showAll("mlogin-form","mlogin-wrap","mlogin-footer-text");
		if(typeof(this.onload)=="function"){
			this.onload();
		}
		window.setTimeout(function(){
							e=document.getElementById("mlusername");
							if (e) e.focus();
						},500);
	},
	"message":function(text){//this is for progresstext
		setInnerHTML("mlogin-progress",text);
	},
	"setCustomMessage":function(text){//only supported by custom login box tmpl
		if(text && this.htmlurl.indexOf("/custom")>-1){
			setInnerHTML("mlogin-message",text);
		}
	},
	"signon":function(formNode){
		this.message("Signing In...");
		hideAll("mlogin-form","mlogin-footer-text");
		if(!isValidBnDomainName(formNode.elements["username"].value) || !formNode.elements["password"].value.length){
			this.onloginfail("Please enter your username and password");
			return false;
		}
		dojo.io.bind({
			"formNode":formNode,
			"mimetype":"text/html",
			"load":function(typ,html,ev){
				if(getRspStat(html)=="ok"){
					modalLogin.message("Signed in!");
					var afterLogin=(modalLogin.fwdUrl?"location.href='"+modalLogin.fwdUrl+"'":"location.reload()");
					setTimeout('modalLogin.close();'+afterLogin,500);
				}else{
					modalLogin.onloginfail("Invalid login. Try again.");
				}
			},
			"error":this.onloginfail
		});
		return false;
	},
	"onloginfail":function(text){
		if(!text)text="Login failed";
		this.message(text);
		showAll("mlogin-form","mlogin-footer-text");
	},
	"onload":function(){
		this.setCustomMessage(this.customMessage);
	}
};

modalRegistration={
	"inited":0,
	"dlgId":"mreg",
	"fwdUrl":"",
	"cssurl":CDN_HOST+"assets/cssjs/modal-registration.css",
	"scripturl":CDN_HOST+'assets/cssjs/modal-registration.js',
	"htmlurl":'/interface/post/modalregistrationbox/',
	"customcode":"",
	"init":function(){
		if(isSignedIn())return false;
		if(this.inited)return true;
		this.createDialog();
		this.inited=1;
		return true;
	},
	"createDialog":function(){
		if(this.inited)return;
		var htmlurl=this.htmlurl+(this.fwdUrl?'?fwd_url='+this.fwdUrl:'');
		createDialog(this.dlgId,getUrlContents(htmlurl),false,this.cssurl);
		scriptOnDemand(this.scripturl);
	},
	"addCustomCode":function(){
		if(!this.customcode)return 0;
		var inp=createEl("input",{"type":"hidden","name":"users[token]","value":this.customcode});
		getDomObj("mregistration").getElementsByTagName("form")[0].appendChild(inp);
	},
	"open":function(fwdUrl){
		if(fwdUrl)this.fwdUrl=fwdUrl;
		if(!this.init())return false;
		if(getDialog(modalLogin.dlgId)){//close sign in window if it's there
			getDialog(modalLogin.dlgId).hide();
		}
		if(typeof(this.onload)=="function"){
			this.onload();
		}
		var id = this.dlgId;
		window.setTimeout(function(){
				var objReff = getDomObj("captcha");
				if (objReff){
					getDialog(id).show();
					modalRegistration.onload();
				}else{
					window.setTimeout(function(){
						getDialog(id).show();
						modalRegistration.onload();
					},300)
				}
		},300);
		
	},
	"close":function(){
		getDialog(this.dlgId).hide();
	},
	"onload":function(){
		this.addCustomCode();
	}
};

createGallery={
	"inited":0,
	"dlgId":"cGallery",
	"fwdUrl":"",
	"htmlurl":"/interface/post/createnewgallery/",
	"cssurl":CDN_HOST+"/assets/cssjs/create-gallery.css",
	"customMessage":"",
	"init":function(){
		if(this.inited)return true;
		if(!isSignedIn())return false;
		this.inited=1;
		return true;
	},
	"close":function(){	
		this.message("");
		hideAll("mlogin-wrap");
		getDialog(this.dlgId).hide();	
		createGallery.fwdUrl="";},
	"open":function(headerText, username, fwdUrl, htmlurl){
		if(!this.init())return false;
		if(fwdUrl)this.fwdUrl=fwdUrl;
		if(htmlurl)this.htmlurl=htmlurl;
		createDialog(this.dlgId,getUrlContents(this.htmlurl),false,this.cssurl);
		document.getElementById('uploaderApplet').style.display='none';
		document.getElementById('uploaderWrapper').style.display='block';
		if (!headerText) headerText = "Create a New Gallery";		
		getDialog(this.dlgId).show();
		setInnerHTML("mlogin-header-text",headerText);
		showAll("mlogin-form","mlogin-wrap","mlogin-footer-text");
		if(typeof(this.onload)=="function"){
			this.onload();
		}
		window.setTimeout(function(){
			e=document.getElementById("newgallname");
			if (e) e.focus();
		},500);
	},
	"message":function(text){//this is for progresstext
		setInnerHTML("mlogin-progress",text);
	},
	"createGallery":function(formNode){
		this.message("Creating Gallery...");
		hideAll("mlogin-form","mlogin-footer-text");
		if(!isValidGalleryName(formNode.elements["gallname"].value)){
			this.onloginfail("Please Enter a valid Gallery Name");
			return false;
		}		
		dojo.io.bind({
			"formNode":formNode,
			"mimetype":"text/html",
			"load":function(typ,html,ev){
				if(getRspStat(html)=="ok"){
					createGallery.message("Gallery Created!");
					var afterLogin=(createGallery.fwdUrl?"location.href='"+createGallery.fwdUrl+"'":"location.reload()");
					setTimeout('createGallery.close();'+afterLogin,500);
				}else{
					createGallery.oncreatefail("Invalid Gallery Name (must be alphanumeric but may contain dashes). Try Again.");
				}
			},
			"error":this.onloginfail
		});
		return false;
	}
};

function getSignInOutLink(signInText,signOutText){
	if(!signInText)signInText="Sign In";
	if(!signOutText)signOutText="Sign Out";
	if(isSignedIn()){
		return '<a href="/user/logout/?refer='+refer(1)+'">'+signOutText+'</a>';
	}else{
		return '<a href="/user/login/?refer='+refer(1)+'"  onclick="popLoginBox(this);return false;">'+signInText+'</a>';
	}
}
var UserMessage={
	//doc objects referenced
	panelId : "msgpanel",
	formId  : "msgform",
	linkId  : "msglink",
	popBox : function(relativeObj,toUserId){
		if(!getDomObj("msgpanel")){
			var mp=document.createElement("div");
			mp.id=this.panelId;
			mp.className="clickMenu";
			mp.style.width="300px";
			mp.style.padding="8px";
			mp.style.zIndex="3";
			mp.innerHTML='<form name="'+this.formId+'" id="'+this.formId+'" action="" method="post">'
						+refer()
						+input_hidden("msg[to_id]",toUserId)
						+'<b>Subject</b>:<br>'
						+input_text("msg[subject]","",20,255,'style="width:100%"')+'<br>'
						+'<b>Message</b><br>'
						+'<textarea name="msg[body]" class="textinput" style="width:100%;height:120px;"></textarea>'
						+'<center>'+input_button("Cancel","toggleDisp('"+this.panelId+"')")
						+input_button("Send","sendPrivateMessage('"+this.panelId+"',this.form,'"+this.linkId+"')")+'</center>'
						+'</form>';
			document.body.appendChild(mp);
		}
		toggleMenu(this.panelId,relativeObj);
	},
	getLink : function(toUserId,toUserName,addl){
		if(!addl)addl="";
		else addl=" "+addl;
		return '<a href="http://'+toUserName+'.'+DBD+'/user/sendmessage/?refer='+refer(1)+'" '
			  +'onClick="UserMessage.popBox(this,\''+toUserId+'\');return false;" id="'+this.linkId+'" name="'+this.linkId+'"'+addl+'>Send Message</a>';
	}
}

function quitReload(){_NO_RELOAD=1;}
function canReload(){return (_NO_RELOAD?0:1);}
function InitRefresh(){
	_NO_RELOAD=0;
	var objs=["comcomments note[message]", "newtopic[subject]" ,"newtopic[body]",
		      "topic[reply]","topic[subject]","topic[body]"];
	for(i=0;i<objs.length;i++){
		if(typeof(d=getDomObj(objs[i]))!="undefined")
			d.onkeypress=quitReload;
	}
	if(window["dojo"]){
		dojo.addOnLoad(function(){
			setTimeout("if(canReload())location.replace(location.href);",180000);
		})
	}
	
}

function updateA9Tracker() {
	dojo.io.bind({
		"url":"/interface/post/a9tracking/",
		"mimetype":"text/html",
		"load":function(tp,html,e){
		}
	});
}
function bindHandler(kwArgs){//this attaches to all dojo.io.bind() calls
	var url=kwArgs["url"]?kwArgs["url"]:"";
	if(!url && kwArgs["formNode"] && typeof(kwArgs["formNode"].action)!="undefined")
		url=kwArgs["formNode"]["action"];
	logAjaxReq(url);
	return true;
}
function logAjaxReq(url){
	var params=new Array(), act="general", label="",val="",qry="" ;
	if(typeof(pageTracker)=="undefined"){
		//try again in later
		setTimeout('logAjaxReq("'+url+'")',3000);
		return true;
	}
	if(startswith(url,"http://")){//kill full url from ajax req
		url=url.substring("http://".length);
		url="/"+strfrom(url,"/");
	}
	if(url.indexOf("?")>-1){//separate querystring
		url=strto(url,"?");
		qry=strfrom(url,"?");
		qry=qry.replace(/&|\?dojo_transport=1/,"").replace(/&/g,"|");
	}
	if(startswith(url,"/interface/post")){//kill general ajax endpoint dir
		url=url.substring("/interface/post/".length);
	}
	url=url.replace(".php","");
	if(startswith(url,"/"))url=url.substring(1);//kill leading slash
	params=url.split("/");//use dirs to create action,label,value
	act=params[0];
	if(params[1])label=params[1];
	//val=(params[2]?params[2]:qry);
	if(!label)label="general";
	//alert("_trackEvent(act+","+label+")");
	pageTracker._trackEvent(act,label);//stopped logging label and value arguments. was making calls fail
	return true;

}
function scriptTracker(theurl){//will gracefully try to make urchin calls 
	if(typeof(urchinTracker)=="undefined")return;
	if(typeof(theurl)=="undefined")
		theurl="/ajax"+location.pathname+location.search;
	urchinTracker(theurl);
}
function logOmniture(props,linkName){//allow logging of omniture within ajax/dhtml 
	if(!props)return;
	if(typeof(props)!="object")return;
	if(typeof(s_account)=="undefined")return;
	if(!linkName)linkName="ajax";
	var x=s_gi(s_account);
	var propnames=new Array();
	var eventnames=new Array();
	for(e in props){
		if(startswith(e,"event")){
			eventnames.push(props[e]);
		}
		propnames.push(e);
	}
	x.linkTrackEvents=(eventnames.length?eventnames.join(","):"None");
	x.linkTrackVars=(propnames.length?propnames.join(","):"None");
	for(e in props){
		x[e]=new String(props[e]);
	}
	x.tl(true,"o",linkName);
}
function submitPartnerMailForm(formObj){
	if(!valid_email(formObj["email"].value)){
		alert("Invalid email address");
		return false;
	}
	toggleDisp("downloadform","none");
	setInnerHTML("downloadprogress",progresstable("Please wait..."));
	dojo.io.bind({
		"formNode":formObj,
		"mimetype": "text/html",
		"load":function(typ,html,e){
			if(getRspStat(html)=="ok"){
				var url="";
				if(!formObj["thanks"]){
					url="/error/?error="+escape("Thank you!");
				}else{
					url=formObj["thanks"].value;
				}
				setTimeout("location.href='"+url+"'",1500);
				WriteCookie("okfile",formObj["desturl"].value);
				location.href=dl=formObj["desturl"].value;
				return;
			}else{
				toggleDisp("downloadform","block");
				toggleDisp("downloadprogress","none");
				alert("There was an error with your submission. Please check your email is correct");
				return;
			}
		}
	});
	return false;
}
function drawPartnerMailinglistDownloadForm(tag,dlUrl,thanksUrl,emlTxt,buttonText){
	if(!tag){
		alert("Partner mail form must have a tag");
		return false;
	}
	if(!dlUrl){
		alert("Partner download form must have a destination url");
		return false;
	}
	if(!thanksUrl)thanksUrl="";
	if(!buttonText)buttonText="Download&raquo;";
	if(!emlTxt)emlTxt="Email:";
	if(!stristr("downloaded=1",location.href)){
   str='<style>#email{width:8em}</style><div id="downloadprogress"></div><div id="downloadform"><form method="post" action="/interface/post/partnermailinglist/add/" onsubmit="return submitPartnerMailForm(this);">'
      +input_hidden("tag",tag)
	  +input_hidden("desturl",dlUrl)
	  +input_hidden("thanks",thanksUrl)
	  +'<table><tr>'
	  +'<td><label for="email">'+emlTxt+'</label></td>'
	  +'<td>'+input_text("email",'',20,255)+'</td>'
	  +'</tr><tr><td>&nbsp;</td>'
	  +'<td colspan="2" id="dlbutton"><input type="submit" value="'+buttonText+'" class="buttoninput" /></td>'
	  +'</tr></table></form></div>';
	 }else{
	 	str="Thanks for downloading!";
	 }
	document.write(str);

		
}
var jgallery={//pulls images from a document element and creates a pop-up window gallery
	fill : function(srcObj,titleObj){
		if(getDomObj(titleObj))
			this.title=getDomObj(titleObj).innerHTML;
		else
			this.title.document.title;
		this.imgs=getDomObj(srcObj).getElementsByTagName("img");
		this.gimages=new Array();
		for(i=0;i<this.imgs.length;i++){
			if(!this.imgs[i].src)continue;
			pnode=this.imgs[i].parentElement?this.imgs[i].parentElement:this.imgs[i].parentNode;
			if(pnode.tagName.toLowerCase()=="a")continue;
			thesrc=this.imgs[i].src;
			if(!thesrc.match(/\.jpe?g$/i))continue;
			if(thesrc.match(/\-msg\-\d+\-(2|3)\.jpg/))//large versions of small buzz images
					thesrc=thesrc.replace(/(thumb|feat|gallery|synd|mob)(.*\.jpg$)/i,"large$2");
			this.gimages[this.gimages.length]=thesrc;
			this.imgs[i].style.cursor="pointer";this.imgs[i].style.cursor="hand";
			this.imgs[i].setAttribute("idx",(this.gimages.length-1));
			this.imgs[i].setAttribute("useSrc",thesrc);
			dojo.event.connect(this.imgs[i],"onclick",function(e){
				var wnd=window.open("about:blank","xwnd","width=530,height=500,scrollbars=1,resizable=1,status=1");
				wnd.document.open();
				wnd.gimages=jgallery.gimages;				
				wnd.document.write(
					"<html><head><title>"+jgallery.title+"</title>",
					'<style>body{margin:0px;border:0px;padding:0px;text-align:center;background-color:#efefef;}',
					'#theimage{border:2px #ccc solid;cursor:pointer;cursor:hand}',
					'#pcell,#tcell,#rcell{font:normal 12px arial;}',
					'#tcell{font-weight:bold;font-size:14px;}',
					'</style>',
					'<scr'+'ipt>curImage='+e.target.getAttribute("idx")+';nextImage='+jgallery.nextImage+';',
					'if(gimages.length<2)document.write("<style>#pcell,#rcell{display:none}</style>");',
					'window.focus();',
					'</scr'+'ipt>',
					'</head><body>',
					'<table width="100%"><tr>',
					'<td id="pcell" width="1"><a href="javascript:nextImage(1)">&laquo;&nbsp;Prev</a></td>',
					'<td id="tcell" align="center">'+jgallery.title+'</td>',
					'<td align="right" id="rcell" width="1"><a href="javascript:nextImage()">Next&nbsp;&raquo;</a></td>',
					'</tr></table>',
					'<table width="100%" height="92%"><tr valign="top"><td align="center">',
					'<img src="'+e.target.getAttribute("useSrc")+'" border="0" onclick="nextImage();" ',
					' id="theimage" name="theimage" />',
					'</td></tr></table>',
					"</body></html>");
				wnd.document.close();
			});
		}
	},	
	nextImage : function(gback){//used in the context of the new window
		if(gback)curImage--;
		else curImage++;
		if(curImage>(gimages.length-1))curImage=0;
		if(curImage<0)curImage=(gimages.length-1);
		document.images["theimage"].src=gimages[curImage];
	}
}

function removeBlockedSender(user_id,buttonObj){
	if(!user_id)return;
	buttonObj=getDomObj(buttonObj);
	var url="/interface/post/blockedsenders/remove/?user_id="+user_id;
	setInnerHTML(buttonObj,"Please wait...");
	dojo.io.bind({
		"url":url,
		"mimetype": "text/html",
		"load":function(t,html,e){
				if(getRspStat(html)=="ok"){
					if(buttonObj.id){
						setTimeout("toggleDisp('"+buttonObj.id+"','none');",750);
					}else{
						toggleDisp(buttonObj,"none");
					}
				}else{
					setInnerHTML(buttonObj,getRspError(html));
				}
		},
		"error":function(t,e){
			setInnerHTML(buttonObj,"Connection error");
		}
	});
}
function addBlockedSender(user_id,deleteAll, buttonObj, progressObj,doneFunc){
	if(!user_id)return;
	if(!deleteAll)deleteAll=0;
	var url="/interface/post/blockedsenders/add/?user_id="+user_id+"&delete_all="+deleteAll;
	setInnerHTML(buttonObj,"Please wait...");
	dojo.io.bind({
		"url":url,
		"mimetype": "text/html",
		"load":function(t,html,e){
			if(getRspStat(html)=="ok"){
				toggleDisp(progressObj,"none");
				toggleDisp(buttonObj,"block");
				setInnerHTML(buttonObj,"Done!");
				if(buttonObj.id){
					setTimeout("toggleDisp('"+buttonObj.id+"','none');",1000);
				}else{
					toggleDisp(buttonObj,"none");
				}
				if(typeof(doneFunc)=="function")doneFunc();
			}else{
				var err=getRspError(html);
				toggleDisp(progressObj,"none");
				toggleDisp(buttonObj,"block");
				setInnerHTML(buttonObj,err);
			}
		},
		"error":function(t,e){
			setInnerHTML(progressObj,"Connection error");
		}
	});
}

function fullScreenVideo(){
	var emb=getDomObj("vembedobj");
	var vbg=getDomObj("vembg");
	var vc;
	//create close button
	if(!getDomObj("vidclose")){
		vc=createEl("input",{
			type:"button",id:"vidclose","class":"buttoninput error",value:"<< exit",
			"style":"position:absolute;top:2px;left:3px;z-index:12"
		});
		vc.onclick=returnFullScreenVideo;
		document.body.appendChild(vc);
	}else{
		vc=getDomObj("vidclose");
	}
	//create dimmed background layer
	if(!getDomObj("vidbg")){
		vbg=createEl("div",{
			id:"vidbg",
			"style":"position:absolute; left:0px; top:0px; width:100%;height:100%;"+
					"background-color:#111111; z-index:9;opacity:0.8"
		}
		);
		document.body.appendChild(vbg);
	}else{
		vbg=getDomObj("vidbg");
	}
	toggleDisp(vbg,"block");
	toggleDisp(vc,"block");
	//size and position the elements based on avail doc dimensions
	emb.style.zIndex=10;
	var factor=(document.body.clientHeight/emb.getAttribute("height"));
	emb.style.height=document.body.clientHeight;
	emb.style.width=Math.floor(parseInt(emb.getAttribute("width")*factor));
	emb.style.position="absolute";
	emb.style.top="0px";
	emb.style.left="0px";
	vc.style.left=parseInt(emb.style.width)+4+"px";
	document.body.scrollTop=0;
	//emb.style.left=(Math.floor(emb.style.width/2));
	//emb.style.left=Math.floor((document.body.clientWidth/2)-(parseInt(emb.style.width)/4));
	
}
function returnFullScreenVideo(){
	var emb=getDomObj("vembedobj");
	toggleDisp("vidclose","none");
	toggleDisp("vidbg","none");
	emb.style.position="static";
	emb.style.width=emb.getAttribute("width");
	emb.style.height=emb.getAttribute("height");
}

function sendChannelMsg(channel,wckey,name,email,subject,message,success,fail,ec){
	if(!channel)return;
	if(!valid_email(email))return;
	if(!subject)return;
	if(!message)return;
	if(!wckey)return;
	var bparams={
		"mimetype": "text/html",
		content :{
			"contact[subject]":subject,
			"contact[message]":message,
			"contact[name]":name,
			"contact[email]":email,
			"wckey":wckey,
			"ec":(ec?ec:"")
		},
		url:"/web/"+channel+"/contact/mod/",
		method:"POST",
		mimetype:"text/html",
		"load": function(t,html,e) {
			html=strfromto(html,'class="medlink">',"</div>");
			if(stristr("message sent",html)){
				if(typeof(success)=="function")success();
			}else{
				if(typeof(fail)=="function")fail();
			}
		}
	};
	if(typeof(fail)=="function")bparams["error"]=fail;
	dojo.io.bind(bparams);
}
function doOnLoad(){//runs at the bottom of the page
	if(typeof(dojo)=="undefined")return;
	if(document.all){//scale down images for ie. mozilla just need css max-width
		if(findObj("shoutout")){
			dojo.addOnLoad(function(){
				resizeImages("shoutout",290);
			});
		}
		if(findObj("userjournal")){
			dojo.addOnLoad(function(){
				resizeImages("userjournal",600);
			});
		}
		if(findObj("journalentry")){
			dojo.addOnLoad(function(){
				resizeImages("journalentry",600);
			});
		}
		if(findObj("commentlist")){
			dojo.addOnLoad(function(){
				resizeImages("commentlist",400);
			});
		}		
	}
	dojo.addOnLoad(clearFooter);
	if(0){
		//logging for new rightbar state
		dojo.addOnLoad(function(){
			if(typeof(urchinTracker)!="undefined"){
				urchinTracker("/rightbar/"+ReadCookie("sbar"));
			}
		})
	}
}
function clearFooter(){
	return;
	if( findObj("leftside") && findObj("rightside") && findObj("bodycontainer")){
		var tw=807;
		var aw=getOffsetWidth("leftside");
		if(aw>tw){
			var add=(aw-tw);
			var mw=getOffsetWidth("bodycontainer");//need to figure this out for moz!
			findObj("bodycontainer").style.width=(mw+add)+"px";
			if(findObj("maincontent"))findObj("maincontent").style.width=aw+"px";
			if(findObj("bodycontent"))findObj("bodycontent").style.width=aw+"px";
			if(findObj("header"))findObj("header").style.width=aw+"px";
			if(findObj("topad"))findObj("topad").style.width=aw+"px";
		}
		var tr=184;
		var atw=getOffsetWidth("rightside");
		if(atw>tr){
			var add=(atw-tr);
			var mw=getOffsetWidth("bodycontainer");
			findObj("bodycontainer").style.width=(mw+add)+"px";
		}
	}
}
function toggleRightBar(lObj){
	return;
	if(typeof(_site_max)=="undefined")_site_max=0;
	if(!_site_max){
		toggleDisp("rightside","none");
		findObj("maincontent").style.width="100%";
		if(findObj("headercontainer"))
			findObj("headercontainer").style.width="100%";
		if(findObj("subnetheader"))
			findObj("subnetheader").style.width="100%";
		setInnerHTML(lObj,"Show Right Bar&raquo;");
		WriteCookie("sm",1);
		_site_max=1;
	}else{
		findObj("maincontent").style.width="807px";
		if(findObj("headercontainer"))
			findObj("headercontainer").style.width="807px";
		toggleDisp("rightside","block");
		setInnerHTML(lObj,"&laquo;Hide Right Bar");
		_site_max=0;
		WriteCookie("sm",0);
	}
}
function toggleRightBarLink(){
	if(typeof(_site_max)=="undefined")_site_max=0;
	var out="";
	document.write('<span id="minmaxlink">|<a href="#" id="minmaxlink" onclick="toggleRightBar(this);return false">'+(_site_max?"Show Right Bar&raquo;":"&laquo;Hide right bar")+'</a></span>');
}

function changeRightBar(version){
	if(version=="old")version="v1";
	if(version=="new")version="v4";
	if(!in_array(version,"v1 v4 v5".split(" ")))version="v1";
	setMiscConfig("sidebarstyle",version);
	location.reload();
}
function closeChangeRightBar(){
	setMiscConfig("sidebar_ignore_old",1);
	toggleDisp("changerightbar","none");
}
function answerPoll(pollId){
	/*
		expects 
		form - p-$poll_id-form
		progress - p-$poll_id-progress
		answers - p-$poll_id-ans
		checkbox tds class="answer-input"
	*/
	var frm="p-"+pollId+"-form";
	var prog="p-"+pollId+"-progress";
	var ans="p-"+pollId+"-ans";
	if(!getValByName("answer",frm)){
		alert("You didn't pick an answer");
		return;
	}
	//hide answers and show progress
	toggleDisp(ans,"none");
	setInnerHTML(prog,progresstable("Submitting your vote..."));
	dojo.io.bind({
		"formNode":getDomObj(frm),
		"mimetype":"text/plain",
		"load":function(t,ret,e){
			var stat=getRspStat(ret);
			var err=getRspError(ret);
			if(stat=="ok" || stristr("already voted",err)){
				setInnerHTML(prog,"");
				toggleDisp(prog,"none");
				toggleDisp(ans,"block");
				reloadArea(ans,"/interface/post/polls/getresults/"+pollId+"/","Refreshing","",1);
			}else{
				setInnerHTML(prog,err);
				toggleDisp(ans,"block");
			}
			if(typeof(onAnswerPoll)=="function"){
				onAnswerPoll();
			}
		},
		"error":function(typ,html,e){
			setInnerHTML(prog,'<div class="error">There was an error submitting your vote. Try again</div>');
			toggleDisp(ans,"block");
			return;
		}
		
	});
}
/**
 * Flags a comment/note/post as spam for later review
 * @param int id
 * @param int type
 * @param int user_id - id of the reporting user
 * @param int owner_id - id of the item owner
 */
function markAsSpam(id,type,user_id,owner_id) {
	var url = '/interface/post/spam/?subaction=mark&id='+id+'&type='+type+'&user_id='+user_id+'&owner_id='+owner_id;
 	dojo.io.bind({
		"url":url,
		"mimetype":"text/json",
		"load":function(t,json,e){
			alert('Thank you for your submission.\nWe will review this '+type+' shortly');
		 }
	 });
}
/**
 * hack for safari 2.0 for dealing with nav bar width
 */
function resizeNetheader() {
	if(navigator.userAgent.indexOf('Safari') > 0 && navigator.userAgent.indexOf('419.3') > 0) {
		var nh = document.getElementById('netheader');
//		nh.style.width = '795px';
//		nh.style.height = '120px';
	}
}


/*===================== toggle tab elements ====================*/
function togTab(curTabObj,showTab,hideTabs){
	//turn off other tabs
	oTabs=getDomObj(curTabObj).parentNode.getElementsByTagName("a");
	for(i=0;i<oTabs.length;i++){
		if(oTabs[i].className.indexOf("lasttab")>-1)
			oTabs[i].className="lasttab off";
		else 
			oTabs[i].className="off";
	}
	if(getDomObj(curTabObj).className.indexOf("lasttab")>-1)
		getDomObj(curTabObj).className="on lasttab";
	else
		getDomObj(curTabObj).className="on";
	for(i=0;i<hideTabs.length;i++){
		toggleDisp(hideTabs[i],"none");
	}
	toggleDisp(showTab,"block");
	//sgetDomObj(showTab).className="tabcontent on";
}

function shSearch(tfield){/*submit search term in header*/
	var frm=getDomObj(tfield).form;
	if(frm.elements["stype"].value=="people"){
		if(typeof(frm.elements["city"])!="undefined"){//using top nav search bar
			setValByName(tfield,"");
			if(frm.elements["city"].value.toLowerCase()=="city")
				frm.elements["city"].value="";
			if(frm.elements["city"].value){
				return true;
			}else{
				richAlert("Please enter a city from which you'd like to find people.",frm,false);
				return false;
			}
		}
	}
	return (trim(getValByName(tfield)) && getValByName(tfield).toLowerCase()!='search')?true:false;
}


function displaySigninMsg(button){
if(!isSignedIn()){
                var msg="To email you must <a href=\""+URLPREFIX+"/www/subscribe/\">Sign Up</a> or <a href=\""+URLPREFIX+"/user/login/\">Sign In</a>";
                richAlert(msg,button);
                return;
        }

}


function installSkin(skinId,mainDiv,msgDiv){
	var err;
	toggleDisp(mainDiv,"none");
	toggleDisp(msgDiv,"block");
	setInnerHTML(msgDiv,progresstable("Please wait while your skin is installed"));
	dojo.io.bind({
		"url":"/interface/post/addskin/?skin_id="+skinId,
		"load":function(t,html,e){
			if(getRspStat(html)=="ok"){
				logOmniture({"prop12":"skin|"+skinId},"Skin Install");//prop12 is click tracker
				var userurl="http://"+ReadCookie("USERNAME")+"."+DBD+"/user/";
				setInnerHTML(msgDiv,"<br>&nbsp;<b>The skin was installed.</b><br><br><a href=\""+userurl+"\"><b>Click here</b></a> to see it on your page!");
			}else{
				err=getRspError(html);
				if(!err)err="There was a problem installing the skin. Try again.";
				setInnerHTML(msgDiv,err);
				toggleDisp(mainDiv,"block");
			}
		}
	})
}
function clearMyPageCustomizations(hideDiv, msgDiv,callBack){
	var err;
	toggleDisp(hideDiv,"none");
	toggleDisp(msgDiv,"block");
	setInnerHTML(msgDiv,progresstable("Please wait..."));
	dojo.io.bind({
		"url":"/interface/post/addskin/clearall/",
		"load":function(t,html,e){
			if(getRspStat(html)=="ok"){
				setInnerHTML(msgDiv,"All skins and color customizations removed!");
				if(typeof(callBack=="function")){
					callBack();
				}
			}else{
				err=getRspError(html);
				if(!err)err="There was a problem removing your customizations. Please try again";
				setInnerHTML(msgDiv,err);
				toggleDisp(hideDiv,"block");
			}
		}
	})
}
function installWallpaper(bgimg,mainDiv,msgDiv){
	var err;
	toggleDisp(mainDiv,"none");
	toggleDisp(msgDiv,"block");
	setInnerHTML(msgDiv,progresstable("Please wait while your wallpaper is installed"));
	dojo.io.bind({
		"url":"/interface/post/addskin/wallpaper/?bgurl="+bgimg,
		"load":function(t,html,e){
			if(getRspStat(html)=="ok"){
				var userurl="http://"+ReadCookie("USERNAME")+"."+DBD+"/user/";
				setInnerHTML(msgDiv,"<br>&nbsp;<b>The wallpaper was installed.</b><br><br><a href=\""+userurl+"\"><b>Click here</b></a> to see it on your page!");
			}else{
				err=getRspError(html);
				if(!err)err="There was a problem installing the wallpaper. Try again.<br>";
				setInnerHTML(msgDiv,err);
				toggleDisp(mainDiv,"block");
			}
		}
	})
}


/*------------------------------------------------*/
/*   GLOBAL NAV PACKAGE                           */
/*------------------------------------------------*/

function swapNavSearchType(optionId, parentId, searchFields, searchType, onSelectEl) {
	var parentElement = document.getElementById(parentId);
	if (parentElement) {
		for (var i in searchFields) {
			if (element = document.getElementById(i)) {
				for (var j in searchFields[i]) {
					element[j] = searchFields[i][j];
				}
			}
		}
	
		parentElement.parentNode.getElementsByTagName('span')[0].firstChild.nodeValue = searchType;
        parentElement.focus();
		toggleNavSearchOptions(optionId);

		if(typeof(onSelectEl)=="function" && typeof(parentElement.value)!="undefined"){
			if(parentElement.value)
				onSelectEl();
		}
	}
}

function toggleNavSearchOptions(optionId) {
	var optionElement = document.getElementById(optionId);
	if (optionElement) {
		if (optionElement.style.display == 'block') {	
			optionElement.style.display = 'none';
		} else {
			optionElement.style.display = 'block';
		}
	}
}


function getMouseCoordinates(event){
	var mouseX = 0;
	var mouseY = 0;
	try{
		if (document.layers){
        	mouseX = event.pageX;
        	mouseY = event.pageY;
	    } else if (document.all) {
	        mouseX = window.event.clientX + document.body.scrollLeft;
	        mouseY = window.event.clientY + document.body.scrollTop;
	    }else if(document.getElementById){
	    	mouseX = event.pageX;
        	mouseY = event.pageY;
	    } 
	}catch(e){
		return new Array();
	}
	return [mouseX,mouseY];
}

/*=========== what is this getmousexy stuff used for?? =============*/
if(getDomObj("topNavSearchTypeOptions") || getDomObj("BuzzWorthyOptions") || getDomObj("TagTopNavSearchTypeOptions")){
	function getMouseXY(e) {
		if(!getDomObj("topNavSearchTypeOptions") && !getDomObj("BuzzWorthyOptions") && !getDomObj("TagTopNavSearchTypeOptions"))return;
	    if(IE){
	        el = event.srcElement;
	    }
	    else{
	        el = e.target;
	    }
	    var optionElement = document.getElementById('topNavSearchTypeOptions');
	    if(optionElement.style.display == 'block'){
	        if(el.className != 'SearchDropDown' && el.id != 'SearchDropDown'){
	            optionElement.style.display = 'none';
	        }
	    }
	    
	    if(getDomObj("BuzzWorthyOptions"))
	    {
		    var optionElement = document.getElementById('BuzzWorthyOptions');
		    if(optionElement.style.display == 'block'){
		        if(el.className != 'TagSearchDropDown' && el.id != 'TagSearchDropDown'){
		            optionElement.style.display = 'none';
		        }
		    }
	    }
	    
	    if(getDomObj("TagTopNavSearchTypeOptions"))
	    {
		    var optionElement = document.getElementById('TagTopNavSearchTypeOptions');
		    if(optionElement.style.display == 'block'){
		        if(el.className != 'TagSearchDropDown' && el.id != 'TagSearchDropDown'){
		            optionElement.style.display = 'none';
		        }
		    }
	    }
	}
	var IE = document.all?true:false;
	if(!IE) document.captureEvents(Event.CLICK);
	document.onclick = getMouseXY;
}
/*--------------------- end getmousexy misnamed function ---------------*/
/*------------------------------------------------*/
/*   AUTO SUGGEST PACKAGE                         */
/*------------------------------------------------*/

var suggestionObjects = {};
var oldSuggestUrl="";

function suggestCity(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/city/lookup/single/', minInputChars, maxOutputResults, loadingAlert, onSelect, null, preventEnterSubmit);
}

function suggestTag(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/tags/lookup/single/', minInputChars, maxOutputResults, loadingAlert, onSelect, null, preventEnterSubmit);
}

function suggestTagAuthor(tag, e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/tags/lookup-authors/'+tag+'/', minInputChars, maxOutputResults, loadingAlert, onSelect, null, preventEnterSubmit);	
}

function suggestTagMulti(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/tags/lookup/multi/', minInputChars, maxOutputResults, loadingAlert, onSelect, ', ', preventEnterSubmit);
}

function suggestUsername(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/users/lookup/single/', minInputChars, maxOutputResults, loadingAlert, onSelect, null, preventEnterSubmit);
}

function suggestUsernameMulti(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/users/lookup/multi/', minInputChars, maxOutputResults, loadingAlert, onSelect, ', ', preventEnterSubmit);
}

function suggestFriend(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/friends/lookup/single/', minInputChars, maxOutputResults, loadingAlert, onSelect, null, preventEnterSubmit);
}

function suggestFriendMulti(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/friends/lookup/multi/', minInputChars, maxOutputResults, loadingAlert, onSelect, ', ', preventEnterSubmit);
}

function suggestVenue(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/venuelookup/single/', minInputChars, maxOutputResults, loadingAlert, onSelect, null, preventEnterSubmit);
}

function suggestEvent(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/events/lookup/single/', minInputChars, maxOutputResults, loadingAlert, onSelect, null, preventEnterSubmit);
}

function suggestSchool(e, textObj, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	return suggestGeneric(e, textObj, '/interface/post/elections/lookup/schools/', minInputChars, maxOutputResults, loadingAlert, onSelect, null, preventEnterSubmit);
}

function suggestGeneric(e, textObj, suggestUrl, minInputChars, maxOutputResults, loadingAlert, onSelect, termDelimiter, preventEnterSubmit) {
	if (oldSuggestUrl != suggestUrl) {
		oldSuggestUrl=suggestUrl;
		suggestionObjects={};
	}
	if (textObjId = textObj.getAttribute('id')) {
		if (!suggestionObjects[textObjId]) {
			suggestionObjects[textObjId] = new AutoSuggest(textObj, suggestUrl, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit);
			if (termDelimiter) {
				suggestionObjects[textObjId].termDelimiter = termDelimiter;
			}
			suggestionObjects[textObjId].init();
		}
		
		suggestionObjects[textObjId].handleKeyEvent(e || window.event);
	}
	
	return false;
}

/*------------------------------------------------*/

function AutoSuggest(textObj, suggestUrl, minInputChars, maxOutputResults, loadingAlert, onSelect, preventEnterSubmit) {
	this.lastEventTime = new Date();
	
	//set from constructor args
	this.textObj = textObj;
	this.suggestUrl = suggestUrl;
	this.minInputChars = minInputChars ? minInputChars : 2;
	this.maxOutputResults = maxOutputResults ? maxOutputResults : 10;
	this.loadingAlert = (loadingAlert == true ? true : false);
	this.onSelect = onSelect;
	this.preventEnterSubmit = preventEnterSubmit;
	
	//optional parameters
	this.termPrefix = '';
	this.termSuffix = '';
	this.termDelimiter = '';
	
	//used within class 
	this.suggestObj;
	this.loadingObj;
	this.textObjId;
	this.term;
	this.highlight;
	this.pending = 0;
	this.suggestions;
	this.focus = true;
	this.pause;
	
	
	//setup the focus and blur handlers to show/hide the dropdown; stop enter key from submitting the form
	this.init = function() {
		dojo.event.browser.addListener(this.textObj, 'focus', handleTextboxFocusEvent);
		dojo.event.browser.addListener(this.textObj, 'blur', handleTextboxBlurEvent);
		dojo.event.browser.addListener(this.textObj, 'keypress', function(e) {
			e = e || window.event;
			if (e.keyCode == 13) {
				e.preventDefault();
				e.stopPropagation();
			}
		});
		
		this.textObjId = this.textObj.getAttribute('id');
		this.createDropdown();
	}
	
	//submits the form
	this.submitForm = function() {
		if (!this.preventEnterSubmit) {
			try {
				this.textObj.form.submit();
			} catch(e) {
				//auto submit problem; fail silently
			}
		}
	}
	
	//handle the key up event that should be added to the input box; account for safari bug of onkeyup firing twice on up arrow by checking date
	this.handleKeyEvent = function(e) {
		var now = new Date();
		if (now.getTime() - this.lastEventTime.getTime() > 100) {
			this.lastEventTime = now;
			
			if (this.textObj.value.length >= this.minInputChars) {
				switch (e.keyCode) {
					case 38:	//up arrow
					case 33:	//up page
						this.pauseDropdown();
						this.showDropdown();
						this.highlightItem(this.highlight - 1);
						break;
					
					case 40:	//down arrow
					case 34:	//down page
						this.pauseDropdown();
						this.showDropdown();
						this.highlightItem(this.highlight + 1);
						break;
						
					case 13:	//enter
						this.pauseDropdown();
						if (this.highlight >= 0) {
							this.selectItem(this.suggestObj.childNodes[this.highlight]);
						}
						this.hideDropdown();
						this.submitForm();
						break;
						
					case 9:		//tab
					case 27:	//escape
						this.pauseDropdown();
						this.hideDropdown();
						break;
						
					case 37:	//left arrow
					case 39:	//right arrow
						break;
						
					case 8:		//backspace
					case 46:	//delete
					default:	//alpha-numeric
						this.startDropdown();
						this.loadDropdown();
						break;
				}
			} else {
				this.hideDropdown();
				this.hideLoading();
			}
		}
	}
	
	//build the dropdown shell and add the event handlers to it
	this.createDropdown = function() {
		var dropdown = document.createElement('div');	
		dropdown.setAttribute('id', 'suggest_' + this.textObjId);
		dropdown.className = 'autosuggest';
		//dropdown.style.width = this.textObj.offsetWidth + 'px';
		dropdown.style.width = this.textObj.parentNode.offsetWidth + 'px';
		
		var body = document.getElementsByTagName('body')[0];
		this.suggestObj = body.appendChild(dropdown);
		
		dojo.event.browser.addListener(this.suggestObj, 'mouseup', handleDropdownMouseEvent);
		dojo.event.browser.addListener(this.suggestObj, 'mousedown', handleDropdownMouseEvent);
		dojo.event.browser.addListener(this.suggestObj, 'mouseover', handleDropdownMouseEvent);
		
		if (this.loadingAlert) {
			var loading = document.createElement('div');
			loading.className = 'loading';
			this.loadingObj = body.appendChild(loading);
		}
		
		this.positionDropdown();
	}
	
	//move the dropdown (and the loading notification) underneath the textbox
	this.positionDropdown = function() {
		var position = {top: 0, left: 0};
		var nodeObj = this.textObj.parentNode;
		
		while (nodeObj.tagName != 'HTML') {
			position.top += nodeObj.offsetTop || 0;
			position.left += nodeObj.offsetLeft || 0;
			
			if (nodeObj.offsetParent) {
				nodeObj = nodeObj.offsetParent;
			} else {
				break;
			}
		}
		
		this.suggestObj.style.top = position.top + this.textObj.parentNode.offsetHeight + 'px';
		this.suggestObj.style.left = position.left + 'px';
        this.suggestObj.style.zIndex = '1000';
		
		if (this.loadingAlert) {
			this.loadingObj.style.top = position.top + (Math.ceil(this.textObj.parentNode.offsetHeight - this.loadingObj.offsetHeight) / 2) + 1 + 'px';
			this.loadingObj.style.left = position.left + this.textObj.parentNode.offsetWidth - this.loadingObj.offsetWidth - 3 + 'px';
		}
	}
	
	//load the suggestions for the dropdown (requires dojo)
	this.loadDropdown = function() {
		if (this.pending == 0) {
			this.pending++;
			this.highlight = -1;
			this.term = this.textObj.value;
			this.positionDropdown();
			this.showLoading();
			
			var textObjId = this.textObjId;	
			dojo.io.bind({
				'url': this.suggestUrl + (this.suggestUrl.indexOf('?') == -1 ? '?' : '&') + 'lookup=' + encodeURIComponent(this.term) + '&limit=' + this.maxOutputResults,
				'method': 'GET',
				'mimetype': 'text/json',
				'load': function(tp, json, e) {
					suggestionObjects[textObjId].populateDropdown(json);
				}
			});
		}
	}
	
	//populates the dropdown with the json data (if the user is still typing, loads up to date data)
	this.populateDropdown = function(json) {
		this.pending--;
		
		if (!this.pause) {
			this.suggestObj.innerHTML = '';
			for (var i in json) {
				itemObj = document.createElement('div');
				itemObj.appendChild(document.createTextNode(json[i]['name']));
				this.suggestObj.appendChild(itemObj);
			}
			
			this.suggestions = json;
			this.hideLoading();
			this.showDropdown();
			
			if (this.focus && !this.pause && this.term != this.textObj.value) {
				this.loadDropdown();
			}
		}
	}
	
	//allows the dropdown to change again
	this.startDropdown = function() {
		this.pause = false;
	}
	
	//stops the dropdown from changing (in case someone is selecting in it)
	this.pauseDropdown = function() {
		this.pause = true;
		this.hideLoading();
	}
	
	//show the dropdown if the textbox is focused
	this.showDropdown = function() {
		if (this.focus && !this.pause) {
			if (this.suggestObj.innerHTML.length) {
				this.suggestObj.style.display = 'block';
			} else {
				this.hideDropdown();
			}
		}
	}
	
	//hide the dropdown and move the cursor to the textbox if focused
	this.hideDropdown = function() {
		this.suggestObj.style.display = 'none';
		if (this.focus) {
			this.textObj.focus();
		}
	}
	
	//show the loading notification if it's turned on
	this.showLoading = function() {
		if (this.loadingAlert) {
			this.loadingObj.style.visibility = 'visible';
		}
	}
	
	//hide the loading notification if it's turned on
	this.hideLoading = function() {
		if (this.loadingAlert) {
			this.loadingObj.style.visibility = 'hidden';
		}
	}
	
	//highlight the item with the array key of the highlight arg
	this.highlightItem = function(highlight) {
		if (this.suggestions) {
			if (highlight < 0 || highlight >= this.suggestions.length) {
				highlight = 0;
			}
			
			if (this.highlight != highlight) {
				if (this.highlight >= 0 && this.suggestObj.childNodes[this.highlight]) {
					this.suggestObj.childNodes[this.highlight].className = '';
				}
				this.suggestObj.childNodes[highlight].className = 'active';
			}
			this.highlight = highlight;
		}
	}
	
	//populate the textbox with the passed item and put the cursor at the end of the value, if possible
	this.selectItem = function(itemObj) {
		if (this.suggestions) {
			this.textObj.value = ((this.termDelimiter.length && (delimPosition = this.textObj.value.lastIndexOf(this.termDelimiter)) != -1)) ? this.textObj.value.substring(0, (delimPosition + this.termDelimiter.length)) : '';
			this.textObj.value += this.termPrefix
			this.textObj.value += itemObj.firstChild.nodeValue
			this.textObj.value += this.termSuffix
			this.textObj.value += this.termDelimiter;
			
			if (this.textObj.createTextRange) {
				var textRange = this.textObj.createTextRange();
				textRange.moveStart('character', (this.textObj.value.length));
				textRange.collapse();
				textRange.select();
			}
			
			this.pauseDropdown();
			this.hideDropdown();
			
			this.suggestObj.innerHTML = '';	
			this.suggestions = '';
	
			if (this.onSelect && typeof(this.onSelect) == 'function') {
				this.onSelect(this.textObj.value, this.textObjId);
			}
		}
		this.hideLoading();
	}
	
	//flags the object as focused
	function handleTextboxFocusEvent(e) {
		e = e || window.event;
		if (textObj = (e.target || e.srcElement)) {
			if (textObj.getAttribute && (textObjId = textObj.getAttribute('id'))) {
				if (suggestionObjects[textObjId]) {
					suggestionObjects[textObjId].focus = true;
				}
			}
		}
	}
	
	//flags the object as unfocused and hides the dropdown
	function handleTextboxBlurEvent(e) {
		e = e || window.event;
		if (textObj = (e.target || e.srcElement)) {
			if (textObjId = textObj.getAttribute('id')) {
				if (suggestionObjects[textObjId]) {
					suggestionObjects[textObjId].focus = false;
					suggestionObjects[textObjId].hideDropdown();
				}
			}
		}
	}
	
	//handles any mouse events in the dropdown
	function handleDropdownMouseEvent(e) {
		e = e || window.event;
		if (targetObj = (e.target || e.srcElement)) {
			suggestObj = targetObj;
			while (suggestObj && !suggestObj.getAttribute('id')) {
				suggestObj = suggestObj.parentNode;
			}
			
			if (textObjId = suggestObj.getAttribute('id').substring(8)) {
				suggestionObjects[textObjId].pauseDropdown();
				switch (e.type) {
					case 'mousedown':
						suggestionObjects[textObjId].selectItem(targetObj);
						suggestionObjects[textObjId].submitForm();
						break;
						
					case 'mouseover':
						for (var item in suggestionObjects[textObjId].suggestions) {
							if (targetObj.firstChild.nodeValue == suggestionObjects[textObjId].suggestions[item].name) {
								suggestionObjects[textObjId].highlightItem(item);
								break;
							}
						}
						break;
						
					default:
						suggestionObjects[textObjId].textObj.focus();
						break;
				}
			}
		}
	}
}

/*------------------------------------------------*/


function createGigyaForm(){

//inject form
    if (document.getElementById('wildfire_Frm')==null) {
        var frm  = document.createElement('form');
        frm.id = "wildfire_Frm";
        frm.method = "post";
        frm.style.display = "none";
        frm.action = "http://www.gigya.com/wildfire/WFPop.aspx";
        frm.innerHTML = '<input type="hidden" name="module" id="wildfire_module"><input type="hidden" name="htmlContent" id="wildfire_htmlContent" /><input type="hidden" name="url" id="wildfire_url" value=""/><input type="hidden" name="partner" id="wildfire_partner"/><input type="hidden" name="partnerData" id="wildfire_partnerData"/><input type="hidden" name="subject" id="wildfire_subject" /><input type="hidden" name="contentIsLayout" id="wildfire_contentIsLayout" /><input type="hidden" name="networksToShow" id="wildfire_networksToShow" /><input type="hidden" name="FBURL" id="wildfire_FBURL" /><input type="hidden" name="flash" id="wildfire_flash" /><input type="hidden" name="offerTypes" id="wildfire_offerTypes" />';
        if (document.body != null) document.body.insertBefore(frm,document.body.firstChild);
    }
}

function gigyaPopup(wildfire_cid, partner, module, subject, contentIsLayout, networksToShow, fburl, flash, partnerData, offerTypes) {

        var $=function(id){return document.getElementById(id)};

        if (typeof($d('wildfire_Frm'))!='undefined') {
            $d('wildfire_Frm').target='WFPop' + module;
            $d('wildfire_module').value=module;
            if ($d(wildfire_cid) != null)
                $d('wildfire_htmlContent').value=$d(wildfire_cid).value;
            else
                $d('wildfire_htmlContent').value='';
            $d('wildfire_url').value=document.location.href;
            $d('wildfire_partner').value=partner;
            $d('wildfire_subject').value=subject;
            $d('wildfire_contentIsLayout').value=contentIsLayout;
            $d('wildfire_networksToShow').value=networksToShow;
            $d('wildfire_FBURL').value=fburl;
            $d('wildfire_flash').value=1;
            $d('wildfire_partnerData').value=partnerData;
            $d('wildfire_offerTypes').value=offerTypes;

            var w=window.open("about:blank", $d('wildfire_Frm').target, "width=440,height=320,resizable=1");

            $d('wildfire_Frm').submit();
            try {
                if (w.blur) w.focus();
            } catch(e) {}
        }
}

function syncRoadBlock(adTag){
        a = adTag.split(';');
        if (a.length>0)
        {            for (x=0; x<=a.length-1; x++)
                        {
                                if (a[x].indexOf('sz=') == 0)
                                {
                                        size = a[x].substring(3);
                    dims = size.split('x');
                    height = dims[0];
                    width = dims[1];
                                        loadRBs('bannerslot_300x250_3',height,width,adTag);
                }
            }
        }
}
function loadRBs(s,w,h,adTag){
    document.getElementById(s).innerHTML = '<iframe src="' + adTag + '" id="ifr_companion" width="'+w+'" height="'+h+'" marginwidth=0 marginheight=0 hspace=0 vspace=0 frameborder=0 scrolling=no>' + '</iframe>';
}

function loadDefaultAdFromFlash(defaultAd) {
    if(document.getElementById(defaultAd)) {
	// REMOVED CALL TO NOT SHOW THE INITIAL AD, SO THIS DOESN'T HAVE TO DO ANYTHING: KEVIN 
        //document.getElementById(defaultAd).innerHTML = eval(defaultAd);
    } else {
        // This was a hack to get the 728x90 to work
        //dojo.addOnLoad(function() {document.getElementById(defaultAd).innerHTML = eval(defaultAd);});
    }
}

function resizeVEmbedObj(w,h) {
        var vidembed = document.getElementById("vembedobj");
		w=parseInt(w);h=parseInt(h);

        if(w > 0) {
                vidembed.style.width = w+"px";
        }

        if(h > 0) {
                vidembed.style.height = h+"px";
        }
}

function getLocation() {
	return location.href;
}

function setMiscConfig(key,val,callBack){
	if(!isSignedIn())return;
	if(!key)return;
	var url="/interface/post/setmeta/?SITE_NAME="+ReadCookie("USERNAME")+"&user_metadata[misc_config]["+key+"]="+val;
	if(typeof(callBack)=="function"){
		getUrl(url, callBack);
	}else{
		getUrlContents(url);
	}
}
function getMiscConfig(key){
	var ret;
	if(!isSignedIn())return 0;
	if(!key)return 0;
	if(typeof(callBack)!="function")callBack=function(){void(0);}
	dojo.io.bind({
		"method":"GET","mimetype":"text/json","url":"/interface/post/getusermetadata/?key=misc_config&subkey="+key,
		"load":function(tp,data,e){ret=data;}, "sync":true
	});
	return ret;
}
/**
 * @name,value
 * @param callBack - pass func reference and will call it when ajax req done
 * @param synchronous - will run synchronously, js func will still run if defined but will still halt other operations until finished
*/
function setMetaAlt(name,value,callBack,synchronous){
	if(!name)return 0;
	if(typeof(callBack)!="function"){
		callBack=function(){void(0);}
	}
	var url="/interface/post/setmetaalt/?name="+name+"&value="+(value?value:"")
	if(synchronous){
		getUrlContents(url);
		callBack();
	}else{
		getUrl(url, callBack);
	}
}

function updateProfile(keyOrParams,val,onSuccess,onError){
	if(typeof(onSuccess)!="function")onSuccess=function(){void(0);}
	if(typeof(onError)!="function")onError=function(){void(0);}
	if(!isSignedIn){
		onError("Must be signed in");
		return;
	}
	var params={};
	if(typeof(keyOrParams)!="object"){
		params["profile["+keyOrParams+"]"]=val;
	}else{
		for(e in keyOrParams){
			params["profile["+e+"]"]=keyOrParams[e];
		}
	}
	dojo.io.bind({
		"url":"/interface/post/profile/?user_name="+ReadCookie("USERNAME"),
		"method":"POST",
		"content":params,
		"mimeType":"text/html",
		"load":function(t,html,e){
				if(getRspStat(html)!="ok"){
					onError(getRspError(html));
				}else{
					onSuccess(getRspOk(html));
				}
		},
		"error":onError
	});
}

function refreshImage(parentName)
{
	var expdate=new Date();
	var sep="";
	i=document.getElementById(parentName);
	old=i.src;
	if (old.lastIndexOf("&r=")>-1)
	{
		old=old.substring(0,old.lastIndexOf("&r="));
	}
	if(old.lastIndexOf("?")==-1)
	{
		sep="?";
	}
	else
	{
		sep="";
	}
	i.src=old+sep+"&r="+expdate.getTime();
}

function setStatus(status,loadCallback){
	getUrl("/interface/post/setstatus/?status="+status,loadCallback);
}
function setStatusHeader(statusheader,loadCallback){
	getUrl("/interface/post/setstatus/?statusheader="+statusheader,loadCallback);
}
function setStatusSuccess(status) {
	if(status == "") {;
		document.getElementById('status-text').innerHTML = "<span id='status-nostatus' style='font-size: 12px; color: #777777;'>What are you doing right now?</span>";
	} else {

		document.getElementById('status-text').innerHTML = status + '&nbsp;&nbsp;&nbsp;<a id="status-clear" href="javascript:void(0);" onclick="clearStatus();">clear</a>';
	}
	hideStatusUpdate();
}
function setStatusFailure() {
	alert('Error updating status, please try again later.');
}
function showStatusUpdate() {
	document.getElementById('status-text').style.display = "none";
	document.getElementById('status-update').style.display = "block";
	document.getElementById('status-update').style.verticalAlign = "middle";
	document.getElementById('status-input').value = "";
	document.getElementById('status-input').focus();
}
function hideStatusUpdate() {
	document.getElementById('status-text').style.display = "block";
	document.getElementById('status-update').style.display = "none";
}

function emailAvailable(e, showError){
    if (!e || !e.value) return false;
    res = getUrlContents("/interface/post/verifyemail/"+e.value);
   if(getRspStat(res)!="ok"){
        if (getRspError(res)){
            if (showError) alert("This email already in use!");
            e.value="";
			e.focus();
            return false;           
        }
    }
    return true;    
}

function onBuzzPlayerVideoStart(){
    logOmniture({"prop23":"Yes"});    
}


/** functions to make hover effect for buttons. Used when are more buttons and when hover one, we need hover all
    obj = input.
    suffix = suffix name of class.
    eg. if our elements are class="test buttonone" and suffix is "hover" then must be created in css file a new class
    testHover for hover effect. (first class + suffix)
    
   */
function hoverInMultipleButtons(obj,suffix) {
	var parent = obj.parentNode;
	if (!suffix) suffix="Hover";
	var className="";
	var buttons = parent.getElementsByTagName("input");
	for (var i=0;i<buttons.length; i++) {
		className = buttons[i].className
		className = className.split(" ");
		buttons[i].className+=" "+className[0]+suffix;
	}
}

function hoverOutMultipleButtons(obj,suffix) {
	var parent = obj.parentNode;
	if (!suffix) suffix="Hover";
	var buttons = parent.getElementsByTagName("input");
	var className="";
	for (var i=0;i<buttons.length; i++) {
			className = buttons[i].className;
			className = className.split(" ");
			for (var j=0;j<className.length;j++)
				if (className[j].indexOf(suffix) > 0) className[j]="";
			className = className.join(" ");
			buttons[i].className = className;
	}
}

function reloadAdFrames(){
	var frms=getElementsByAttribute(document.getElementsByTagName("body")[0], "iframe", "class", "bnadframe");
	for(i=0;i<frms.length;i++){
	    frms[i].setAttribute("src",frms[i].src);
	}
}

function loadDeferredAds(){
	var tfrms=new Array();//needed b/c as each item is replaced it removes it from the list and messes up the offset
	var frms=document.getElementsByTagName("bnxiframe")
	for(i=0;i<frms.length;i++){
		tfrms[tfrms.length]=frms[i];
	}
	for(i=0;i<tfrms.length;i++){
		tfrms[i].parentNode.innerHTML=tfrms[i].parentNode.innerHTML.replace(/bnxiframe/gi,"iframe");
	}
}

function handleRecorderSnapshot(recorderId,hiddenId){
	var rec=findObj(recorderId);
	if(!rec)return "";
	var pdata="";
	try{
		pdata=rec.getImageBytes();
		setValByName(hiddenId,pdata);
	}catch(e){
		alert(e);
		setValByName(hiddenId,"");
	}
	return pdata;
}
/**
 * assign key event to document or other object
*/
function onkeyevent(keyName,handler,altTarget){
	if(typeof(handler)!="function")handler=function(e){void(0);};
	var keyName=keyName.toUpperCase();
	var targ=(altTarget?$d(altTarget):document);
	dojo.event.browser.addListener(targ,"key",function(e){
		var key = e.keyCode || e.charCode; 
		if(key==dojo.event.browser.keys["KEY_"+keyName]){
			targ=0;
			if(typeof(event)!="undefined" && typeof(event.srcElement)!="undefined")targ=event.srcElement;
			if(typeof(e.target)!="undefined")targ=e.target;
			handler(e,key,targ);
		}
	});
}

/**
 * checks for existing ty cookie and calls ajax endpoint to verify
 * @param age yyyy-mm-dd
*/
function validateAge(ageDate){
	if(!ageDate){
		//alert("no argument");
		return 0;
	}
	if(!ageDate.match(/\d{4}\-\d+\-\d+/)){
		//alert("regex didn't match:"+ageDate);
		return 0;
	}
	if(ReadCookie("ty")){
		//alert(ReadCookie("ty"))
		return 0;//was alreayd checked
	}
	var age=intval(getUrlContents("/interface/post/validateage/?bdate="+ageDate));
	//alert(age)
	if(age>=13)return 1;
	//alert("age < 13");
	return 0;
}


function scrapeUrl(url){
	if(!startswith(url,"http://") || url=="http://")return 0;
	var ret=getUrlContents("/interface/post/scrapeurl/?url="+escape(url),1,1);
	if(!ret)return 0;
	if(typeof(ret["data"])=="undefined")return 0;
	if(typeof(ret["ok"])=="undefined")return 0;
	if(!ret["ok"])return 0;
	ret=ret["data"];
	if(ret["title"])ret["title"]=ret["title"].replace(/\s{2,}/g," ");
	return ret;
}

function addthis_sendto2(svc,srcObj){
	if(typeof(addthis_sendto)!="function")return;
	
	addthis_url = srcObj.getAttribute("at_url");	
	addthis_url = addthis_url.replace("www.", "");	
	addthis_title = srcObj.getAttribute("at_title");
	addthis_pub='celebuzz'; 
	addthis_brand=SERVICE_NAME;
	addthis_options='email, facebook, twitter, myspace, google'; 

	//after addthis called, hijack the window open call to produce a sized window instead of new browser tab or blank window
	dojo.event.connect("around",window,"open",function(inv){
		if(inv.args[1]=="addthis"){
			inv.args[2]="width=720,height=500,resizable=yes,scrollbars=yes";
		}
		inv.proceed();
	});
	return addthis_sendto(svc);
}

/**
 * @param postId
 * @param keyValHash - po
 * @param successFunc(message) - call func with  msg when success - optional
 * @param failFunc(message) - call func with message when failure - optional
 * @return null
*/
function setPostMetadata(postId,keyValHash,successFunc,failFunc){
	if(!postId)return 0;
	if(typeof(keyValHash)!="object")return 0;
	if(typeof(successFunc)!="function")successFunc=function(){void(0);}
	if(typeof(failFunc)!="function")failFunc=function(){void(0);}
	var cont={"post_id":postId};
	for(e in keyValHash){
		cont["meta["+e+"]"]=keyValHash[e];
	}
	dojo.io.bind({
		"url":"/interface/post/setpostmeta/",
		"mimetype":"text/json",
		"method":"POST",
		"content":cont,
		"load":function(t,js,e){
			if(typeof(js.ok)=="undefined"){
				failFunc("Problem saving options");
				return;
			}
			if(!js.ok){
				failFunc(js.message);
				return;
			}
			successFunc(js.message);
		},
		"error":function(t,e){
			failFunc(e.message);
		}
	});
}