BUZZSCRIPT_JS=CDN_HOST+"assets/cssjs/_buzzscript.js";

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=="id")
			obj.id=attrs[e];
		else if(attr=="class" || attr=="classname")
			obj.className=attrs[e];
		else
			obj.setAttribute(e,attrs[e]);
	}
	return obj;
}

/*========= 
			be careful not to use scriptOnDemand() too much. 
			it's intended to load in other scripts that may not get used and aren't critical to the initial page load
			should be used for elements that may *not* be clicked on every page.
			if it's used for something other than that, just load the regular _buzzscript.js file instead
=========*/
function scriptOnDemand(scripturl,handler){
	var sid="dscript-"+scripturl;
	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();
	}
}

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

//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 setVis(lObj,vis){
	if(!(lObj=getDomObj(lObj)))return 0;
	lObj.style.visibility=(vis=="hidden"?"hidden":"visible");
	return 1;
}
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 findObj(obj){return getDomObj(obj);}
function $d(obj){return getDomObj(obj);}
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;
}

/*loaded on every page*/
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;
			});
		}
	}
}

/* loaded on every page */
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);
	}
}
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;}
	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 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 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 isSignedIn(){
	return (ReadCookie("USERNAME")!='' && ReadCookie("USERNAME")!='0' && ReadCookie("USERNAME"))
}
function getUrlContents(url){//synchronous
	if(!url)return;
	ret="";
	dojo.io.bind({
		"url":url,
		"mimetype": "text/html",
		"method":"GET",
		"sync":true,
		"load":function(t,html,e){ret=html;}
	});
	return ret;
}
function getUrl(url, loadCallBack, errorCallBack){//--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);}
	dojo.io.bind({
		"url":url,
		"mimetype": "text/html",
		"method":"GET",
		"load":loadCallBack,
		"error":errorCallBack
	});
}

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 stristr(needle,haystack){
	needle=needle.toString().toLowerCase();
	haystack=haystack.toString().toLowerCase();
	if(haystack.indexOf(needle)>-1)return 1;
	return 0;
}
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;
	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 setInnerHTML(lObj, txt){
	if(!(lObj=getDomObj(lObj)))return 0;
	if(typeof(txt)=="undefined")txt="";
	lObj.innerHTML=txt;
	return 1;
}
function intval(str){
	str=parseInt(str);
	if(isNaN(str))str=0;
	return str;
}

function reloadAdFrames(){
	var frms=getElementsByAttribute(getDomObj("bodycontainer"), "iframe", "class", "bnadframe");
	for(i=0;i<frms.length;i++){
		//trying to just reload or re'src=' each frame won't work and will throw security errors 
		//reload by "re-render": re-inject the frame's container with the frame html
		frms[i].parentNode.innerHTML=frms[i].parentNode.innerHTML;
	}
}

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 toggleNavSearchOptions(optionId) {
	var optionElement = document.getElementById(optionId);
	if (optionElement) {
		if (optionElement.style.display == 'block') {	
			optionElement.style.display = 'none';
		} else {
			optionElement.style.display = 'block';
		}
	}
}

/*needed on every page*/
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 submitVote(type,typeval,button,buttonObj,counterObj,keepStatus,successHandler){
	scriptOnDemand(BUZZSCRIPT_JS,function(){
		submitVote(type,typeval,button,buttonObj,counterObj,keepStatus,successHandler);
	})
}

function submitcomform(formobj,loggedin,profilepic){
	scriptOnDemand(BUZZSCRIPT_JS,function(){
		submitcomform(formobj,loggedin,profilepic);
	});
}

function submitmincommentform(formobj,loggedin){
	scriptOnDemand(BUZZSCRIPT_JS,function(){
		submitmincommentform(formobj,loggedin);
	});
}

modalLogin={
	"open":function(arg){
		scriptOnDemand(BUZZSCRIPT_JS,function(){
			modalLogin.open(arg);
		})
	}
}