
// --- Topics --- //

function Topic_showHide(o) {
	var summary = getElementsByClassName( o.parentNode , 'div', 'summary' )[0];
	if (summary) {		
		summary.style.display = (summary.style.display == 'block') ? 'none' : 'block';	
		o.innerHTML = '(' + ((summary.style.display == 'block') ? 'show less' : 'show more') + ')';	
	}
}


// --- Search --- //

function SearchToggle() {
	$i('search').style.display=$i('search').style.display=='block'?'none':'block'
}

function Search(o) {
	this.s = $i('s');
	this.ctn = $i('search_results');
	this.ul = $i('search_results_list');
	this.ex = $i('search_expand');
	
	this.emptyMsg = 'Enter some related keywords or part of an error message';
	this.url = '/support/x/search.php';	
	this.keyDelay = 250;
	
	this.o = o;
	
	this._init();
}
Search.prototype = {
	
	_init : function() {		
		var self = this;
		this.s.onkeyup = function() { self.typed(); }
		this.ex.onclick = function() { self.expand(); }
		
		// Search Field Display
		this.fieldBlur();
		this.s.onfocus = function() { self.fieldFocus(); }
		this.s.onblur = function() { self.fieldBlur(); }
	},
	
	fieldFocus : function() {
		if (this.s.value == this.emptyMsg) {
			this.s.value = '';
			Removeclass(this.s, 'empty');
		}
	},
	
	fieldBlur : function() {
		if (this.s.value.length == 0) {
			this.s.value = this.emptyMsg;
			Addclass( this.s, 'empty' );
		} else if (this.s.value != this.emptyMsg) {
			Removeclass( this.s, 'empty' );			
		}
	},
	
	typed : function() {
		var self = this;
		clearTimeout( this.TO );
		this.TO = setTimeout( function(){ self.query(); } , this.keyDelay );
	},
	
	query : function(f) {
		if (!this.searching && (this.s.value.length > 3 || f)) {	
			this.searching = true;
			
			//display search results
			this.ul.innerHTML = '<li><img src="/support/i/loading.gif" /> Searching...</li>';
			this.ctn.style.display = 'block';
			
			//send query
			if (this.s.value.length > 3 && this.s.value != this.emptyMsg) {
				var self = this;
				var A = new Ajax();
				A.fire( this.url , function(r){self.returnQuery(r);} , 's='+encodeURIComponent(this.s.value)+'&p='+this.o.p );
			} else {
				this.returnQuery(false, this.s.value == this.emptyMsg ? 2 : 1 );
			}
		}
	},
	
	returnQuery : function(r,er) {
		this.searching = false;
		if (r) {
			
			var data = JSON.parse(r);
			if (data.status == 1) {
				if (data.LIs) {
					this.ul.innerHTML = data.LIs;					
				} else {
					this.ul.innerHTML = '<li>No topics found for your search.  To submit a new topic, click one of the buttons above.</li>';
				}
				this.expandToggle();
				return;
			}
		}
		this.expandToggle();
		var msg;
		if (er==1) {
			msg = '<li>Your search phrase must be at least 4 characters long.  Please clairify your search.</li>';			
		} else if (er==2) {
			msg = '<li>You didn\'t enter a search term.</li>';			
		} else {
			msg = '<li>There was a problem when trying your search.</li>';
		}
		this.ul.innerHTML = msg;
	},
	
	// -- //
	
	expandToggle : function() {
		this.ex.style.display = this.ul.getElementsByTagName('LI').length > 5 ? 'block' : 'none';
	},
	
	expand : function() {
		if ( this.ctn.className.match('expanded') ) {
			this.ctn.className = this.ctn.className.replace('expanded','');
			this.ex.innerHTML = '<small>Expand / Show More</small>';
		} else {
			this.ctn.className += ' expanded';
			this.ex.innerHTML = '<small>Retract / Show Less</small>';
		}
	}
	
}


// -- Form -- //

function Reply(postId) {
	$i('post_form_reply').style.display = 'block';
	$i('post_form_h').innerHTML = 'Reply to ' + $i('post_'+postId).getElementsByTagName('cite')[0].innerHTML + '\'s Comment:';
	$i('post_form_h').innerHTML += ' &nbsp;<small>[<a onclick="ReplyCancel()">cancel reply</a>]</small>';
	$i('post_form_reply').innerHTML = $i('post_'+postId+'_msg').innerHTML;
	$i('r2').value = postId;
	location.hash = 'post';
}
function ReplyCancel() {
	$i('r2').value = '';
	$i('post_form_reply').style.display = 'none';
	$i('post_form_h').innerHTML = 'Reply to Topic:';
}

function CheckRequired(formId) {
	var error = false;
	requiredFields = getElementsByClassName(document.getElementById(formId), 'div', 'required');
	for(i=0; i<requiredFields.length; i++) {
		if (requiredFields[i] && requiredFields[i].style.display != 'none') {
			inputTypes = new Array('input', 'select', 'textarea');
			for(j=0; j<inputTypes.length; j++) {
				inputs = requiredFields[i].getElementsByTagName(inputTypes[j]);
				for(c=0; c<inputs.length; c++) {
					if (inputs[c]) {
						if ((inputs[c].value == null || inputs[c].value.length == 0)) {
							error = true;
							inputs[c].className = 'requiredEmpty';
						} else {
							inputs[c].className = 'requiredOkay';
						}
					}
				}			
			}
		}
	}
	if (error) { alert('Please complete the required fields that are in red'); } else {
		document.getElementById(formId).submit();	
	}
}




// -- General -- //

function $i(id) {
	return document.getElementById(id);
}
function Addclass(obj, c) {
	if (!obj.className.match(c)) {
		obj.className += ' ' + c;
	}
}
function Removeclass(obj, c) {
	obj.className = obj.className.replace(c, '');
}
function createNode(ty, attributes) {
	node = document.createElement(ty);
	for(ik in attributes) {
		switch(ik) {
			case('class'):
				node.className = attributes[ik];
				break;
			case('style'):
				if (typeof attributes[ik] == 'string') {
					its = attributes[ik].split(';');
					for(i=0; i<its.length; i++) {
						parts = its[i].split(':');
						node.style[parts[0]] = parts[1];
					}
				} else {
					for(i in attributes[ik]) {
						node.style[ i ] = attributes[ik][i];
					}
				}
				break;
			case('innerHTML'):
				node.innerHTML = attributes[ik];
				break;
			case('onclick'):
				if (typeof attributes[ik] == 'string') {
					node.setAttribute('onclick', attributes[ik]);
				} else {
					node.onclick = attributes[ik]
				}
			default:
				node.setAttribute(ik, attributes[ik]);
		}				
	}
	return node;
}



// --- Ajax --- //
function Ajax() {}
Ajax.prototype = {
	
	GetXmlHttp : function () {
		{var ajax=null;try{ajax=new XMLHttpRequest();}
		catch(e){ajax=null;}
		try{if(!ajax)ajax=new ActiveXObject("Msxml2.XMLHTTP");}
		catch(e){ajax=null;}
		try{if(!ajax)ajax=new ActiveXObject("Microsoft.XMLHTTP");}
		catch(e){ajax=null;}
		return ajax;}
	},
	
	fire : function (uri, callback, parameters) {
		this.callback = callback;
		this.transport = this.GetXmlHttp();
		this.osc(this);
		this.transport.open("POST",uri,true);
		this.transport.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		this.transport.send(parameters);
	},
	
	osc : function (ajaxObj) {
		ajaxObj.transport.onreadystatechange = function() {
			try {
				switch(ajaxObj.transport.readyState) {
					case(4): ajaxObj.callback(ajaxObj.transport.responseText);
				}
			}
			catch( e ) { //server error
			}
		}	
	}
}



// -- JSON -- //

if(!this.JSON){JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];if(typeof c==='string'){return c;}
return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(typeof value.length==='number'&&!value.propertyIsEnumerable('length')){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}})();


// -- Utility --- //

function getElementsByClassName(oElm, strTagName, oClassNames){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var arrRegExpClassNames = new Array();
    if(typeof oClassNames == "object"){
        for(var i=0; i<oClassNames.length; i++){
            arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
        }
    }
    else{
        arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
    }
    var oElement;
    var bMatchesAll;
    for(var j=0; j<arrElements.length; j++){
        oElement = arrElements[j];
        bMatchesAll = true;
        for(var k=0; k<arrRegExpClassNames.length; k++){
            if(!arrRegExpClassNames[k].test(oElement.className)){
                bMatchesAll = false;
                break; 
            }
        }
        if(bMatchesAll){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
};

