// Global Variables

var debug = false;

// The url of the web service that provides the xml for the topic summary asynchronous preview.  
// This url must be the exact domain name of the requesting website
var TOPIC_SUMMARY_WEBSERVICE_URL = "";
var CURRENT_LINK;
var submitcount=0;
var lastQR=0;
window.name='MainWindow';
var http_request = false;
var callback = null;
var debug_fh = "domutils.js";


/* file:ajax */

// Author: Alexander Bibighaus
// Created: 12/24/2005
function ajax_makeRequest(url, callbackFunction) {
		
        http_request = false;
		callback = callbackFunction;
		
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
            
            	// cause mozilla to report errors
                http_request.overrideMimeType('text/xml');
               
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
       
        http_request.onreadystatechange = ajax_recvresponse;
          
        http_request.open('GET', url, true);
      
        http_request.send(null);
	
}
    
function ajax_recvresponse() {

	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			eval(callback + '()');
		} else {
			alert('Request too long. code:' + http_request.status);
		}
	}
	
}
    


/* file:visual */

function disableSubmit()
{
    if (typeof(Page_ClientValidate)=='function')
    {
        if (Page_ClientValidate() == true)
        {
            return checkSubmit();
        }
        else
        {
            return true;
        }
	}
    else
    {
        return checkSubmit();
	}
}

function checkSubmit()
{
    if (submitcount == 0)
    {
        submitcount++; return true;
	}
    else
    {
        alert('Please wait.. the post has already been submitted.'); return false;        
	}
}


function doHover(tbl, idx, cls)
{
	var t = document.getElementById(tbl);
	if (t == null) return;
	var d = t.getElementsByTagName("TD");
	if (d == null) return;
	if (d.length <= idx) return;
	d[idx].className = cls;
}

function openWindow(url, name) {
		popupWin = window.open(url,name,'width=430,height=400,scrollbars=yes,resizable=yes')
	}

function openWindowAlert(url, name) {
		popupWin = window.open(url,name,'width=200,height=160,scrollbars=auto')
	}	

function bName() {
		// return 1 for Internet Explorer
		if (navigator.appName == "Microsoft Internet Explorer")
			return 1;

		// return 2 for Navigator
		if (navigator.appName == "Netscape")
			return 2;

		// return 0 for other browsers
		return 0;
	}

function bVer() {
		// return version number (e.g., 5.5)
		return parseFloat(navigator.appVersion)
	}

	var nameCode = bName();
	var versionCode = bVer();
	var okayForRichTextEditor = false;
	
	if ((nameCode == 1) && (versionCode >= 4)) {
		okayForRichTextEditor = true;		
	} 
	
/* Shows or hides the item by setting the display on the CSS class. */
function toggleView(){
	var element;
	for (var i=0; i<=toggleView.arguments.length; i++) {
    
		element = document.getElementById(toggleView.arguments[i]);
		if(element == null) { 
			continue 
		};
    
		element.style.display=='' ?  element.style.display='none' : element.style.display='';
	}
 }
 
 function qtoggle(id){ 
	// toggles without cookies
	var element;

	element = document.getElementById(id);
	if(element != null){
		if(element.style.display == ''){
			element.style.display = 'none';
		} else {
			element.style.display = '';
		}
		//element.style.display=='' ?  element.style.display='none' : element.style.display='';
	}
 }
 
function toggleview(id){ 
	var element;
	var expdate = new Date();
	expdate.setTime(expdate.getTime() +  (24 * 60 * 60 * 1000 * 365)); 
	
	element = document.getElementById(id);
	if(element != null){
		if(element.style.display == ''){
			element.style.display = 'none';
			setcookie('category' + id,'0',expdate,null,false);			
		} else {
			element.style.display = '';
			setcookie('category' + id,'1',expdate,null,false);			
		}
			
		//element.style.display=='' ?  element.style.display='none' : element.style.display='';
	}
	
 }
 
 function toggleview(id){ 
	var element;
	var expdate = new Date();
	expdate.setTime(expdate.getTime() +  (24 * 60 * 60 * 1000 * 365)); 
	
	element = document.getElementById(id);
	if(element != null){
		if(element.style.display == ''){
			element.style.display = 'none';
			setcookie('category' + id,'0',expdate,null,false);			
		} else {
			element.style.display = '';
			setcookie('category' + id,'1',expdate,null,false);			
		}
	}
	
 }
 
 function loadview(categoryID){
	
	var element;
	if(!(catCookie = getcookie('category' + categoryID)))
		catCookie = 1;
	element = document.getElementById(categoryID);
	if(catCookie == 0){		
		element.style.display = 'none';			
	} else {
		element.style.display = '';				
	}
		
 }
 
function getcookie(name) {
    if(name=='') {return null};
    var start = document.cookie.indexOf(name+"=");
    var len = start + name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

function setcookie(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") +
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}

function rmLeft(txtBox,maxLen)
	{	 
		var charTotal = maxLen-txtBox.value.length;
		
		if (charTotal >= 0)
		{
			document.getElementById("counter").innerHTML = 'chars remaining: ' + charTotal;
				
		}
		else
		{
			document.getElementById("counter").innerHTML = '<span style="color: #8D162E; font-weight: bold">chars over limit: ' + (-charTotal) + '</span>'; 
		}
		return true;
	}

	
function setFocus()
	{				var subj = document[0].postForm_skin_subject;
					var body = document.forms[0].postForm_skin_body;

					// Set focus on the post subject or body
					if (subj) {
						if (subj.value.length == 0) {	
							// new post set focus on "subject" box
							subj.focus();
						}
						else {
							// Is a reply, so set focus on the body
							if (body) {						
								body.focus();
							}
						}
					}
					else {
						// Default to focus on the body
						if (body) {						
							body.focus();
						}
					}
	}
	
function buildQR(iPostID)
	{
		clearlastQR();
		document.all('qr'+iPostID).innerHTML='max 200 chars.<br><table width="100%"><tr><td><textarea id="qrtext" rows="8" cols="80"></textarea></td></tr></table><button id="subqrform" type="button" OnClick="submitQR()">Submit</button>';
		lastQR=iPostID;
		document.all('qrtext').focus();
	}
	
function submitQR()
{	
	// start with the URL<A HREF="http://localhost/ibb/js/ajax.js">http://localhost/ibb/js/ajax.js</A>
	var text = document.all('qrtext');

	if (text.value.length==0)
	   { return false; }
	
	// before the request is made, hide the text/submit button
	hideQRSubmit();
	
	var url=TOPIC_SUMMARY_WEBSERVICE_URL+'xml/xqreply.aspx?postid='+lastQR+'&text='+escape(text.value);		
	CURRENT_LINK=url;
	ajax_makeRequest(url, 'qreplyCallback');	
	
	return true;
	/*
	document.all('qr'+lastQR).innerHTML='Your reply has been recorded.';
	*/
}

function clearlastQR()
    {
		if (lastQR > 0)
		{
			document.all('qr'+lastQR).innerHTML='';
			lastQR=0;
		}
    }
  
function hideQRSubmit()
{
	document.all('subqrform').style.display='none';
}
  
  // the call back function for the qreply
function qreplyCallback()
{
	
	var xmldoc = http_request.responseXML;
	
	//alert('Entering Callback');
	if(!CURRENT_LINK)
		return;
	
	// update the div with the dynamic contents
	var postid=finditem(xmldoc,'postid');
	var postlink=finditem(xmldoc,'postlink');
	var posterr=finditem(xmldoc,'posterror');
	
	if (postid=='0')
	{
		alert(posterr);
		return false;
	}
	
	
	// window.location.href = sURL;
	
	document.all('qr'+lastQR).innerHTML='Your reply has been submitted. You will be redirected shortly.';
	var sURL = unescape(window.location.pathname);
	sURL=sURL+'?postID='+postid;
	window.location.href = sURL;
	
	

	//alert('Exiting Callback');
}

/* file: xtitle */
// Author: Alexander Bibighaus
// Created: 12/24/2005

// Main Javascript File for Xtitle
// Requires:  ajax.js, domutils.js, positioning.js to be included

// this functions makes an async request to get topic data and show the summary
function showTopicSummary(link) 
{    
	// save our link for positioning
	CURRENT_LINK = link;
	var url = link.toString();
	url = url.replace('posts.aspx','xml/xpost.aspx');	
	setTimeout("ajax_makeRequest('" + url + "', 'showTopicSummaryCallback')",1000);	
	return true;
	
}

function hideTopicSummary()
{
	hideHtmlElement("xtitle");
	CURRENT_LINK = null;
	
}

// the call back function for the show topic summary async request
// this function updates the html elements 
function showTopicSummaryCallback()
{
	var xmldoc = http_request.responseXML;
	
	//alert('Entering Callback');
	if(!CURRENT_LINK)
		return;
		
	// update the div with the dynamic contents
	
	updateSpanById("xtitle_publicname", finditem(xmldoc,'publicname'));
	updateSpanById("xtitle_userinfo", finditem(xmldoc,'userinfo'));
	updateSpanById("xtitle_topic_summary", finditem(xmldoc,'summary'));
	updateSpanById("xtitle_postdate", finditem(xmldoc,'postdate'));
	
	var isTruncated = findTopicSummaryIsTruncated(xmldoc);
	if( isTruncated == "true" )
	{
		displayHtmlElement("xtitle_topic_summaryIsTruncated");
	}
	else 
	{
		hideHtmlElement("xtitle_topic_summaryIsTruncated");
	}
	
	updateImgSrcById("xtitle_avatar", finditem(xmldoc,'avatarLink'));
	positionTopicSummary("topicRepeater1__ctl1__ctl0_hSubject");
	
	displayHtmlElement("xtitle");
	
	//alert('Exiting Callback');
}

function positionTopicSummary(linkId)
{
	var elem = document.getElementById(linkId);
	if( elem == null )
	{	
		if( debug ) alert('Could not get html element by id ' + id);
		return;
	}
	
	var div = document.getElementById("xtitle");
	if( div == null )
	{
		if( debug ) alert('Could not get the html element for the xtitle div');
		return;
	}
	
	div.style.top = getTopPositionForTopicSummary() + "px";
	div.style.left = getLeftPositionForTopicSummary() + "px";		
	
}

function getTopPositionForTopicSummary()
{
	var pos = getAnchorPosition(CURRENT_LINK.id).y;
	pos += 30;
	return pos;
}

function getLeftPositionForTopicSummary()
{
	var pos = getAnchorPosition(CURRENT_LINK.id).x;
	pos += 10;
	
	return pos;
}

function displayHtmlElement(id)
{
	var elem = document.getElementById(id);
	if( elem == null )
	{	
		if( debug ) alert('Could not get html element by id ' + id);
		return;
	}
	elem.style.display = "block";
}		



function hideHtmlElement(id)
{
	var elem = document.getElementById(id);
	if( elem == null )
	{	
		if( debug ) alert('Could not get html element by id ' + id);
		return;
	}
	elem.style.display = "none";
}	

function updateSpanById(spanId, text)
{
	var span = document.getElementById(spanId);
	if( span == null )
	{
		if( debug ) alert('Could not find span with id ' + spanId);
		return null;
	}
	span.innerHTML = text;
}

function updateImgSrcById(spanId, text)
{
	var img = document.getElementById(spanId);
	if( img == null )
	{
		if( debug ) alert('Could not find span with id ' + spanId);
		return null;
	}
	img.src = text;
}




function findTopicSummaryIsTruncated(xmldoc)
{
	var node = dom_findUniqueElement(xmldoc, 'summary');
	if( node == null )
	{
		if( debug ) alert('Could not find summary node');
		return null;
	}
		
	var isTruncated = node.getAttribute("truncated");
	return isTruncated;
}

function finditem(xmldoc,item)
{
	var node = dom_findUniqueElement(xmldoc, item);
	
	return dom_getNodeTextData(node);
}



/* file:domutils */
// Author: Alexander Bibighaus
// Created: 12/24/2005

function dom_findUniqueElement(xmldoc, elementName)
{
	if( xmldoc == null )
	{
		if( debug ) alert(debug_fh + ': illegal dom argument, document is null');
		return null;
	}
		
	var node = xmldoc.getElementsByTagName(elementName).item(0);
	if( node == null )
	{
		if( debug )  alert(debug_fh +  ': could not find element with tag name ' + elementName);
		return null;
	}
	
	return node;

}

function dom_getNodeTextData(node)
{
	if( node == null )
	{
		if( debug ) alert(debug_fh + ': illegal dom argument, node is null');
		return '';
	}
	
	if ( node.firstChild == null )
	{
		if( debug ) alert(debug_fh + ': node child is null');
		return '';
		
	}
	return node.firstChild.data;

}

/* file: positioning */



// getAnchorPosition(anchorname)
//   This function returns an object having .x and .y properties which are the coordinates
//   of the named anchor, relative to the page.
function getAnchorPosition(anchorname) {
	// This function will return an Object with x and y properties
	var useWindow=false;
	var coordinates=new Object();
	var x=0,y=0;
	// Browser capability sniffing
	var use_gebi=false, use_css=false, use_layers=false;
	if (document.getElementById) { use_gebi=true; }
	else if (document.all) { use_css=true; }
	else if (document.layers) { use_layers=true; }
	// Logic to find position
 	if (use_gebi && document.all) {
		x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
		y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
		}
	else if (use_gebi) {
		var o=document.getElementById(anchorname);
		x=AnchorPosition_getPageOffsetLeft(o);
		y=AnchorPosition_getPageOffsetTop(o);
		}
 	else if (use_css) {
		x=AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
		y=AnchorPosition_getPageOffsetTop(document.all[anchorname]);
		}
	else if (use_layers) {
		var found=0;
		for (var i=0; i<document.anchors.length; i++) {
			if (document.anchors[i].name==anchorname) { found=1; break; }
			}
		if (found==0) {
			coordinates.x=0; coordinates.y=0; return coordinates;
			}
		x=document.anchors[i].x;
		y=document.anchors[i].y;
		}
	else {
		coordinates.x=0; coordinates.y=0; return coordinates;
		}
	coordinates.x=x;
	coordinates.y=y;
	return coordinates;
}


function getAnchorWindowPosition(anchorname) {
	var coordinates=getAnchorPosition(anchorname);
	var x=0;
	var y=0;
	if (document.getElementById) {
		if (isNaN(window.screenX)) {
			x=coordinates.x-document.body.scrollLeft+window.screenLeft;
			y=coordinates.y-document.body.scrollTop+window.screenTop;
			}
		else {
			x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
			y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
			}
		}
	else if (document.all) {
		x=coordinates.x-document.body.scrollLeft+window.screenLeft;
		y=coordinates.y-document.body.scrollTop+window.screenTop;
		}
	else if (document.layers) {
		x=coordinates.x+window.screenX+(window.outerWidth-window.innerWidth)-window.pageXOffset;
		y=coordinates.y+window.screenY+(window.outerHeight-24-window.innerHeight)-window.pageYOffset;
		}
	coordinates.x=x;
	coordinates.y=y;
	return coordinates;
}

// Functions for IE to get position of an object
function AnchorPosition_getPageOffsetLeft (el) {
	var ol=el.offsetLeft;
	while ((el=el.offsetParent) != null) { ol += el.offsetLeft; }
	return ol;
}

function AnchorPosition_getWindowOffsetLeft (el) {
	return AnchorPosition_getPageOffsetLeft(el)-document.body.scrollLeft;
}	

function AnchorPosition_getPageOffsetTop (el) {
	var ot=el.offsetTop;
	while((el=el.offsetParent) != null) { ot += el.offsetTop; }
	return ot;
}

function AnchorPosition_getWindowOffsetTop (el) {
	return AnchorPosition_getPageOffsetTop(el)-document.body.scrollTop;
}


function parseGetVars() {
	var getVars = new Array();
	var qString = unescape(top.location.search.substring(1));
	var pairs = qString.split(/\&/);
	for (var i in pairs) {
		var nameVal = pairs[i].split(/\=/);
		getVars[nameVal[0]] = nameVal[1];
		}	
	return getVars;
}

// Replaces a query string variable with a new value.
function replaceQueryString(a,k,v) {
   var re = new RegExp("([?|&])" + k + "=.*?(&|$)","i");
   alert(a.match(re));
   if (a.match(re))
       return a.replace(re,'$1' + k + "=" + v + '$2');
   else
       return a + '&' + k + "=" + v;
}

// Used in the topics.aspx page to manage the filter.
function chooseNewRatingsFilter(){

    //var iRating = document.topicslistingForm.ratingsThreshold.value;
    //var newUrl = replaceQueryString(document.location.href,"ratingsThreshold",iRating);
    //document.location.href = newUrl;    
    document.topicsListingForm.submit();
}
