var delaytime=20000;
var searchheight=0;
var autoJumpActive=1;
var winHeight=1;
var actualHeight=0;


function stripHTML(oldString) {
   var newString = "";
   var inTag = false;
   for(var i = 0; i < oldString.length; i++) {
        if(oldString.charAt(i) == '<') inTag = true;
        if(oldString.charAt(i) == '>') {
              inTag = false;
              i++;
        }
        if(!inTag) newString += oldString.charAt(i);
   }
   return newString;
}

function stripSlashes(str) {
	return str.replace(/\\/g, '');
}

function popupViewer(index) {
	if (index==1) {
		window.open("http://image.minyanville.com/flash/ourtown/index.html","Book","width=800,height=600,resizable=yes,toolbar=no,scrollbars=no");
	} else if(index==2) {
		window.open("http://image.minyanville.com/flash/ourtown/scenicPopup.html","Viewer","width=640,height=400,resizable=yes,toolbar=no,scrollbars=no");
	}
}

// Sets the width of the Buzz and resize to width,708
function setBuzzWidth() {	
	switch (window_size) {
		case "s":
			buzzWidth=350;break;
		case "m":
			buzzWidth=500;break;
		case "l":
			buzzWidth=760; }
			
try {
  window.resizeTo(buzzWidth, 708);
		}catch(e) {}
}

function launchPage (url,name,fade) {
	if (fade==1) { // called from "view features" need to close that menu
		Effect.Fade('viewPopup');
		Event.stopObserving('content','click',toggleViewPopup);
	}
	var pars = 'width='+screen.availWidth+',height='+(screen.availHeight-60)+"toolbar=1, location=1, menubar=1, directories=1, scrollbars=1,resizable=1"
	window.open(url,name,pars);
	//return false;
}


//BOOKMARKS MODULE
function launchBookmark (id,  anchorname, context,sid,poptype) { // opens bookmark and search popups
	if(poptype==undefined || poptype==''){
		var url = "bookmark.php?poptype=buzz&id=" + id + "&s=" + text_size + "&context=" + context + "&chars=" + characters + "&sid=" + sid ;
	}else{
		// we are assuimg all posts are made by TD Users
		//context="Group Post Search";
		var url = "bookmark.php?poptype=grouppost&id=" + id + "&s=" + text_size + "&context=" + context + "&chars=" + characters + "&sid=" + sid  ;
	}
	var bookmark = new PopupWindow();
	bookmark.setSize(buzzWidth,400);
	bookmark.setUrl(url);
	bookmark.showPopup(anchorname);
    	if (context=="bookmark") {toggleBookmark();}
	return false;
}

function launchBookmarkFromURL (url) {
	var bookmark = new PopupWindow();
	bookmark.setSize(buzzWidth,400);
	bookmark.setUrl(url);
	bookmark.showPopupNoAnchor();
	return false;
}

function deleteBookmark(id) { // fired from bookmark popup
	var url = 'bookmark_delete.php';
	var pars = 'sid=' + sid + '&bbid=' + id;
	
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:refreshBookmarks});
}

function addBookmark(sid,id) { // fired from article - maybe add to search popup?

	var url = 'bookmark_add.php';
	var pars = 'sid=' + sid + '&bbid=' + id ;
	
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:finishAddBookmark});
}

function finishAddBookmark () {
	alert("Bookmark added."); // or something else to tell user the operation was successful
	refreshBookmarks();
}


// PRINTING MODULE
function printPostID (id,ss) {
	 
	var url = "print.php?id=" + id + "&s=" + text_size + "&chars=" + characters ; 
	var printJob = new PopupWindow();
	printJob.setSize(450,600);
	printJob.setUrl(url);
	printJob.setWindowProperties("resizable=1,toolbar=0, location=0, menubar=0, directories=0, scrollbars=1");
	printJob.showPopupNoAnchor();
	return false;
}

function printAllPosts () {
	var clientid = $('pref_clientid').value;
	var url = "print.php?s=" + text_size + "&chars=" + characters + "&clientid=" + clientid; 
	var printJob = new PopupWindow();
	printJob.setUrl(url);
	printJob.setWindowProperties("resizable=1,toolbar=0, location=0, menubar=0, directories=0, scrollbars=1");
	printJob.showPopupNoAnchor();
	return false;
}
	
/*
   ====================
   ALERTS MODULE 
   ====================
*/
function checkForBuzzbcinit()
{
	
		var clientid = $('pref_clientid').value;
		var url = '/data/latest_post.txt_'+clientid;
        var pars = null;
        var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:checkLatestTimeinitBC});

}
function checkLatestTimeinitBC (req) {
	 currentLatestbc = parseInt(req.responseText);
	 latestTimeStampbc = currentLatestbc;
	 var clientid = $('pref_clientid').value;
	 var url = 'get_latest.php';
	 var pars = 'sid=' + sid;
	 pars += '&clientid=' + clientid;
	 var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:processLatestBuzzinitBC});
	
}
function processLatestBuzzinitBC (req) {
 try {
	if (req.responseText.length > 0) {
		post = eval('('+req.responseText+')');
		latestIDbc = post.ID;
		//alert(latestIDbc);
	}
	
}
catch (e) {
}
}

function checkForNewBuzzBC() {
	if(autoJumpActive==1){ // means while u are on buzzTab
	var clientid = $('pref_clientid').value;
	var url = '/data/latest_post.txt_'+clientid;
	var pars = null;
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:checkLatestTimeStampBC});
	}else{
		return false;
	}
}

var currentLatestbc = 0;

function checkLatestTimeStampBC (req) {
	currentLatestbc = parseInt(req.responseText);
	if ((currentLatestbc > 0) && (currentLatestbc > latestTimeStampbc)) {
		var clientid = $('pref_clientid').value;
		var url = 'get_latest.php';
		var pars = 'sid=' + sid;
		pars += '&clientid=' + clientid;
		var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:processLatestBuzzBC});
	}
}


function processLatestBuzzBC (req) {
  try {
       if (req.responseText.length > 0) {
  	
    //  update latestTimeStamp
    latestTimeStampbc = currentLatestbc;
	// req is passed from checkForNewBuzz. Contains new postID, author, and type (post or article), and title. Parsed as JSON.
	post = eval('('+req.responseText+')');
	post.title = stripSlashes(post.title);
	var actionTaken = null;
	var postLink = null;
	if (latestIDbc == null) {
	
		// this is a first run, so set the latest post variable and exit
	if (nav.page != 1 && nav.lastPage != 1) {
			latestIDbc = post.ID;
			return;
	}
	}
	if (post.ID != latestIDbc || (nav.noPrev == true && nav.lastPage == 1)) {
		
		if (post.author=="null") post.author=null;
		if (post.title=="null") post.author=null;
		if (post.ID=="null") post.ID=null;
		latestIDbc = post.ID;
		// send info to the Flash movie and order it to flash new post alert
		var postText = "By " + post.author; 
		var postLink = null;
		if (post.type=="ARTICLE")
			{postLink = 'javascript:launchPage("http://www.minyanville.com/articles/index.php?a=' + post.articleID + '","articleLink",0);'} // if an article then the whole function call is built into the postID otherwise it's just a number
		else
				
			{postLink = "javascript:jumpToPostbuzzchannel(" + post.clientid + "," + post.ID + ",'snapto');";}
		if (alerts == 1) {
			var alertPopup = new PopupWindow();
			alertPopup.setSize(200,120);
			var alertText ='<html><head><style type="text/css">body{text-align:center;color:white;background-color:#e99c00;font:11px/16px Arial,Helvetica,sans-serif;font-weight:bold;margin:0 0 0 0;cursor:pointer;width:200px;height:90px;}';
			alertText += 'img {width:200px; height:23px; margin-bottom:15px;}</style><script type="text/javascript">setTimeout(\'self.close()\',15000);';
			if (post.type=="POST")
				alertText += 'function letsGo() {opener.focus();opener.jumpToPostbuzzchannel(' + post.clientid + ',' + post.ID + ',\'snapto\');self.close();}';
			else if (post.type=="ARTICLE")
				alertText += 'function letsGo() {opener.launchPage("http://www.minyanville.com/articles/index.php?a=' + post.articleID + '","articleLink",0);self.close();}';
			alertText += '</script></head>';
			alertText += '<body onclick="javascript:letsGo();">';
			alertText += '<img src="images/alert_header.gif" /><br />NEW ' + post.type + ' BY<br />' + post.author + ' <br />"' + post.title + '"</body></html>';
			alertPopup.populate(alertText);
			alertPopup.autoHide();
			alertPopup.showBuzzAlert();		
		} 	
		
		try {
	    	document.movie22.SetVariable("postText",postText); 
			document.movie22.SetVariable("postLink",postLink);
		} catch (e) {
		}

		// check for autojump and alert window prefs, do the necessary
		if (auto_jump == 1 || nav.page == 0) { 
		
			jump.gotoPos = null;
			jump.oldHeight = null;
            toggleBuzzTab();
			jumpToPostbuzzchannel(post.clientid,post.ID); 
			actionTaken=1; 
		} else if (nav.page == nav.lastPage && actionTaken!=1) {
		
			jump.gotoPos = $("articles").scrollTop;
			jump.oldHeight = $("articles").scrollHeight;
                        toggleBuzzTab();
			jumpToPostbuzzchannel(post.clientid,post.ID);
			actionTaken = 1;
		}
		if (actionTaken != 1) {loadNavigation(nav.page); refreshPostMenu();}
			
    }
   }
  } catch (e) {
  }
}

function checkforbuzzinit()
{
	// variable data_path defined in buzz.php
	var url = host+data_path+'latest_post.txt';	
        var pars = null;
        var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:checklatesttimeinit})
}
function checklatesttimeinit(req)
{
	currentLatest = parseInt(req.responseText);
	//alert("mvil" + currentLatest);
	latestTimeStamp = currentLatest;
        var clientid = 0;
        var url = 'get_latest.php';
	var pars = 'sid=' + sid;
	pars += '&clientid=' + clientid;
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:processLatestBuzzinit});
	
}
function processLatestBuzzinit (req) {
 try {
	if (req.responseText.length > 0) {
		post = eval('('+req.responseText+')');
		latestID = post.ID;
	}
	
}
catch (e) {
}
}

function checkForNewBuzz() {
	if(autoJumpActive==1){ // means while u are on buzzTab
	// variable data_path defined in buzz.php
	var url = host+data_path+'latest_post.txt';	
	var pars = null;
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:checkLatestTimeStamp});
	}else{
	return false;
	}
}

var currentLatest = 0;
function checkLatestTimeStamp (req) {
	
	currentLatest = parseInt(req.responseText);
	if ((currentLatest > 0) && (currentLatest > latestTimeStamp)) {
		var clientid = 0;
		var url = 'get_latest.php';
		var pars = 'sid=' + sid;
		pars += '&clientid=' + clientid;
		var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:processLatestBuzz});
	}
}

function processLatestBuzz (req) {
  try {
   if (req.responseText.length > 0) {
    //  update latestTimeStamp
    latestTimeStamp = currentLatest;
	// req is passed from checkForNewBuzz. Contains new postID, author, and type (post or article), and title. Parsed as JSON.
	post = eval('('+req.responseText+')');
	post.title = stripSlashes(post.title);
	var actionTaken = null;
	var postLink = null;
	//alert("processing latest buzz. latestID: " + latestID + " and post.ID: " + post.ID);
	if (latestID == null) {
		// this is a first run, so set the latest post variable and exit
		if (nav.page != 1 && nav.lastPage != 1) {
			latestID = post.ID;
			return;
		}
	}
	if (post.ID != latestID || (nav.noPrev == true && nav.lastPage == 1)) {
		if (post.author=="null") post.author=null;
		if (post.title=="null") post.author=null;
		if (post.ID=="null") post.ID=null;
		latestID = post.ID;
		// send info to the Flash movie and order it to flash new post alert
		var postText = "By " + post.author; 
		var postLink = null;
		if (post.type=="ARTICLE")
			{postLink = 'javascript:launchPage("http://www.minyanville.com/articles/index.php?a=' + post.articleID + '","articleLink",0);'} // if an article then the whole function call is built into the postID otherwise it's just a number
		else
						{postLink = "javascript:jumpToPostbuzzchannel(" + post.clientid + "," + post.ID + ",'snapto');";}
		if (alerts == 1) {
		//alert("go for the alert");
			var alertPopup = new PopupWindow();
			alertPopup.setSize(200,120);
			var alertText ='<html><head><style type="text/css">body{text-align:center;color:white;background-color:#e89c00;font:11px/16px Arial,Helvetica,sans-serif;font-weight:bold;margin:0 0 0 0;cursor:pointer;width:200px;height:90px;}';
			alertText += 'img {width:200px; height:23px; margin-bottom:15px;}</style><script type="text/javascript">setTimeout(\'self.close()\',15000);';
			if (post.type=="POST")
				alertText += 'function letsGo() {opener.focus();opener.jumpToPostbuzzchannel(' + post.clientid + ',' + post.ID + ',\'snapto\');self.close();}';
			else if (post.type=="ARTICLE")
				alertText += 'function letsGo() {opener.launchPage("http://www.minyanville.com/articles/index.php?a=' + post.articleID + '","articleLink",0);self.close();}';
			alertText += '</script></head>';
			alertText += '<body onclick="javascript:letsGo();">';
			alertText += '<img src="images/alert_header.gif" /><br />NEW ' + post.type + ' BY<br />' + post.author + ' <br />"' + post.title + '"</body></html>';
			alertPopup.populate(alertText);
			alertPopup.autoHide();
			alertPopup.showBuzzAlert(); 
			
			//alertWindow.focus();
		
		} 	
		
		try {
	    	document.movie22.SetVariable("postText",postText); 
			document.movie22.SetVariable("postLink",postLink);
		} catch (e) {
		}

		// check for autojump and alert window prefs, do the necessary
		if (auto_jump == 1 || nav.page == 0) { 
			jump.gotoPos = null;
			jump.oldHeight = null;
			toggleBuzzTab();
			jumpToPostbuzzchannel(post.clientid,post.ID); 
			actionTaken=1; 
		} else if (nav.page == nav.lastPage && actionTaken!=1) {
			jump.gotoPos = $("articles").scrollTop;
			jump.oldHeight = $("articles").scrollHeight;
			toggleBuzzTab();
			jumpToPostbuzzchannel(post.clientid,post.ID);
			actionTaken = 1;
		}
		if (actionTaken != 1) {loadNavigation(nav.page); refreshPostMenu();}
			//	alert("after refresh");
    }
   }
  } catch (e) {
  }
}

/*
   ====================
   TAB BAR MODULE 
   ====================
*/

// Since there are only two tabs, went with manual rather than generalized solution.
function toggleBuzzTab() {
	/*
		While click on buzzTab in that case activate the alerts else deactivate the alerts option 
		autoJumpActive = 0/1
		if autoJumpActive is 0 then don't update the content with new posts   
	 */
	disableclick();
	autoJumpActive=1;
	checkForNewBuzz();
	//checkForNewBuzzBC();

	var x=$("tabBuzz");
	if (x.className=="buzzOver") {
		if(groupActive=='1'){
		$("tabGroups").className="groupOff";
		}
		x.className="buzzOn";
		$("tabtools").className="toolsOff";
		Element.hide("groups");
		Element.hide("tools");
		//***new Effect.BlindDown("content", {duration: .2}); 
		Element.show("content");
		dropDownPos();
	}
	if (x.className=="buzzOff") {
		Element.hide("groups");
		Element.hide("tools");
		if(groupActive=='1'){
		$("tabGroups").className="groupOff";
		}
		$("tabtools").className="toolsOff";
		x.className="buzzOn";
		//***new Effect.BlindDown("content", {duration: .2}); was not working in IE-6
		Element.show("content");
		dropDownPos();
		
	}
	if(groupActive!=1 && showWelcomeScreen=="1"){
	//	displayWelcomeScreen();
	}
	// function defined in group.js, called for setting exit time of the active group if any
	//setGroupExitTime();
	activeGroup = null;
}

// Since there are only two tabs, went with manual rather than generalized solution.
function toggleToolsTab() {
	
	autoJumpActive=0;
	if(groupActive=='1'){
	$("tabGroups").className="groupOff";
	}
	$("tabBuzz").className="buzzOff";
	$("tabtools").className="toolsOn";
	if(groupActive=='1'){
	Element.hide("groups");	
	}
	Element.hide("content");
	Element.hide("welcome_screen");
	Element.hide("welcome_overlay");
	Element.hide("postMenu");
	$("jumpToPost").className="";
	Event.stopObserving('content','click',toggleJump);
	Element.hide("bookMenu");
	$("bookmark").className="";
	Event.stopObserving('content','click',toggleBookmark);

	new Effect.BlindDown("tools", {duration: .2});
	dropDownPos();
	// function defined in group.js, called for setting exit time of the active group if any
	//setGroupExitTime();
	activeGroup = null;
}

function showGroup(id){

	$("tabGroups").className="groupOn";
	$("tabBuzz").className="buzzOff";
	$("tabtools").className="toolsOff";
	Element.hide("content");
	Element.hide("tools");
	Element.show("groups");
	postListing(id);
	setScrollBarPosition();
	
	close_search_div();
}


function toggleSearchTab() {
	
	enableclick(); // Enable click for Groups tab
	if($("groups").style.display == '')
	{
		var insideGroupTab = true;
	}
	autoJumpActive=0;
	    if(groupActive=='1'){
		$("tabGroups").className="groupOn";
		}
		$("tabBuzz").className="buzzOff";
		$("tabtools").className="toolsOff";
		Element.hide("content");
		Element.hide("welcome_screen");
		Element.hide("welcome_overlay");
		Element.hide("tools");
		Element.hide("postMenu");
		$("jumpToPost").className="";
		Event.stopObserving('content','click',toggleJump);
		
		Element.hide("bookMenu");
		$("bookmark").className="";
		Event.stopObserving('content','click',toggleBookmark);		
		//dropDownPos();
		close_search_div();	
		Element.show("groups");
		
		// Variable defined in buzz.php
		if(!setScroll)
		{
			setScrollBarPosition();
			setScroll=1;
		}		
		//$('group_main_div').style.height = getGroupDivHeight()+"px"; // function defined in groups.js		
		//if($('nonregistred_user') && !(sucessRegistration) && displayRegistration)				
		if($('group_registration_overlay').style.display == '')
		{
			// if user does't opt for resend actvation email and click to other tab then screen should be removed if user comes back on group tab.
			if($("resend_email_td"))
			{
				Element.remove("registration_window");				
				$('group_registration_overlay').hide();				
				$('tools_moderator_overlay').hide();
				return;
			}
			if($("registration_window"))
			{
				Element.remove("registration_window");
				if($('groups').style.display == '')
				{
					$('tools_moderator_overlay').hide();
				}
			}
			$('group_registration_overlay').style.height = (getWindowHeight() - 91)+"px"
			var url = '_groups.php';
			var pars="action=getregwindow";	
			var myAjax4 = new Ajax.Request(url, {method: 'post',
										   		parameters: pars,
												onComplete:function(req)
													{
														$('nonregistred_user').innerHTML=req.responseText;	
														$('nonregistred_user').show();
														new Effect.SlideDown("registration_window",{duration:0.3});																												
														displayRegistration =  false;
													}
											});		
		}	
		else
		{
			if(insideGroupTab)
			{
				$('create_edit_post').innerHTML = '';
				$('create_edit_post_overlay').hide();
				categoryList();
			}
		}
		if(refreshPostPage)
		{
			postListing(currentViewingGroup);
			refreshPostPage = null;
		}
		//glowGroupTabsScript();				
	//}
}

function tabBuzzRollover () {
	var x = $('tabBuzz'); 
	if (x.className == "buzzOn") {return;}
	if (x.className == "buzzOff") {x.className = "buzzOver"; return;}
	if (x.className == "buzzOver"){x.className = "buzzOff";}
}

//tools tab mouse over and mouse out
function tabToolsRollover () {
	var x = $('tabtools'); 
	if (x.className == "toolsOn") {return;}
	if (x.className == "toolsOff") {x.className = "toolsOver"; return;}
	if (x.className == "toolsOver"){x.className = "toolsOff";}
}
function tabSearchRollover (e) {
	var x = $('tabGroups'); 
	var y = e.type;
	
	if (x.className == "groupOn") {return;}
	
	if ((x.className == "groupOff" || x.className == "groupOver") && y == "mouseover") {
		x.className = "groupOn1"; return;
	}
	
	if ( y == "mouseout" && x.className == "groupOn1") {
		x.className = "groupOff"; return;
	}
}
/*
   ====================
   DROPDOWN MENU MODULE 
   ====================
*/
// These functions help to place the menu where it belongs when the window size changes

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function getWindowHeight() {
	var windowHeight=0;
	if (typeof(window.innerHeight)=='number') {
		windowHeight=window.innerHeight;		
	} else {
		if (document.documentElement && document.documentElement.clientHeight) {			
			windowHeight=document.documentElement.clientHeight;
		} else {
			if (document.body&&document.body.clientHeight) {
				windowHeight=document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

function dropDownPos() {
	// then size the main content divs so they're the proper height
	var a = getWindowHeight();
	if(a!=actualHeight || winHeight==1){
		actualHeight=a;
		winHeight=2;
		$("articles").style.height = a - (91+40+78+50) +"px"; 
		$("innerOuterBorder").style.height = a-92+"px";	
		searchheight= a - (66+59+28+35+78) +"px"; 
	
	}
	if($("prof_list"))
	{
		$("prof_list").style.height = a - (91+40+78+58) +"px";
	}

	
	// 66 = 30+21+15 flash container+ scrolling area+loading area.
	//59 =30+29 search header + search tabs
	// 28 = padding for search div content
	// 35 = for paging
	// 78 = footer+search
	// first make sure the buttons and dropdown menus stay where they are supposed to be in the middle
	var id=$("postMenu");
	var id2=$("bookMenu");
	var id3=$("viewPopup");
	var rel=$("jumpToPost");
	var y=$("viewFeatures");
	var wid=$("bookmark");
	var x_top = findPosY(y) - 53;
	var x_left = findPosX(y) - 1;
	id3.style.top = x_top + "px";
	id3.style.left = x_left + "px";
	var xid=findPosX(rel)+3;//""
	var yid=findPosY(rel)+ 20;//16
	//var w=findPosX(wid) - xid + 157;
	var w=findPosX(wid) - xid + 128;//130
	w = w+"";
	yid = yid+"";
	id.style.left=xid + "px";
	id.style.top=yid + "px";
	id.style.width=w + "px";
	id2.style.left=xid + "px";
	id2.style.top=yid + "px";
	id2.style.width=w + "px";
	return;
}

function toggleJump() {
	if ($("postMenu").style.display == "none") {
		toggleBuzzTab();
		dropDownPos();
		new Effect.Appear("postMenu", {duration: .1});
		Event.observe('content','click',toggleJump);
		
	} else {
		new Effect.Fade("postMenu", {duration: .1});
		Event.stopObserving('content','click',toggleJump);
	}

}

function toggleBookmark() {
	var x = $('bookMenu').style.display;
	switch (x) {
		case "none":
			toggleBuzzTab();						
			dropDownPos();
			new Effect.Appear("bookMenu", {duration: .1});
			Event.observe('content','click',toggleBookmark);			
			
			break;
		default:
			new Effect.Fade("bookMenu", {duration: .1});
			Event.stopObserving('content','click',toggleBookmark);
	}
	
}

function toggleViewPopup() {
	var x = $('viewPopup');
	var y = $('viewFeatures');
	var x_top = findPosY(y) - 180;
	var x_left = findPosX(y) - 1;
	x.style.top = x_top + "px";
	x.style.left = x_left + "px";
	if (x.style.display=="none") {
		new Effect.Appear(x, {duration:.15});
		Event.observe('content','click',toggleViewPopup);
		//Event.observe('search','click',toggleViewPopup);
		//Event.observe('prefs','click',toggleViewPopup);
		} else {
		Event.stopObserving('content','click',toggleViewPopup);
		//Event.stopObserving('search','click',toggleViewPopup);
		//Event.stopObserving('prefs','click',toggleViewPopup);
		new Effect.Fade(x, {duration:.15}); 
		}
}

function refreshBookmarks() {
	var url = '_bookmarks.php';
	var clientid = $('pref_clientid').value;
	var pars = 'sid=' + sid;
	pars += '&clientid=' + clientid;
	var target = 'bookMenu';
	var myAjax = new Ajax.Updater(target, url, {method: 'post', parameters: pars});
	return false;
}

function refreshPostMenu() {
	var url = '_jump_to_post.php';
	var clientid = $('pref_clientid').value;
	var pars = 'sid=' + sid;
	pars += '&clientid=' + clientid;
	
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:finishRefreshingPostMenu});
	return false;
}

function finishRefreshingPostMenu(req) {
	
	if (req.responseText.length > 0) {
		$("postMenu").innerHTML = req.responseText;
	} else {
		var el = $("articles").innerHTML;
		if (el.indexOf("There are no posts to display") != -1)
			$("postMenu").innerHTML = "There are no posts.";
			else refreshPostMenu();
	}
}

/* =========================
	PREFERENCES MODULE
   ========================= */

function switchToEdit() {
	Element.show("prefsSubEdit");
	$("prefEdit").className="prefSelected";
	$("prefFilter").className="filterDeselected";
}

function switchToFilter() {
	Element.hide("prefsSubEdit");
	$("prefEdit").className="prefDeselected";
	$("prefFilter").className="filterSelected";
}

function getRadioButtonValue (radio) {   
	for (var i = 0; i < radio.length; i++) {
		if (radio[i].checked) { break }
	}
	return radio[i].value
}

function setSelectedRadioButton(radioArray, radioValue) {
	var found = 0;
    for (i = 0; radioArray[i]; i++) {
        if (radioArray[i].value == radioValue) {
            radioArray[i].checked = true;
            found = 1;
        }
    }
    if (found == 0) {
        alert("Error: Could not locate " + 
                thisValue + " in " + thisSelect + ".");
    }
}

function conformToPrefs() {
	switch (text_size) {
		case "s":
			document.body.className = "sizeSmall"; break;
		case "m":
			document.body.className = "sizeMedium"; break;
		case "l":
			document.body.className = "sizeLarge"; 
	}
	if (prefsObj.reload ==1)
		if (topPage) jumpToTimeStamp(topPage); //most reliable way of returning subscriber to post they were looking at before the prefs
		else jumpToLatestPost();		
}

function readPrefsForm() {
	var changed = 0;
	var reload = 0;
	var window_resized = 0;	
	var characters1 = $('pref_characters').value;	// characters
	var alerts1 = $('pref_alerts').value;	// alerts
	var window_size1 = $('pref_window_size').value; // window_size
	var text_size1 = $('pref_text_size').value;	// text_size
	var auto_jump1 = $('pref_auto_jump').value;	// auto_jump
	var posts_per_page1 = $('pref_posts_per_page').value; // posts_per_page
	if (characters != characters1) {characters = characters1; changed = 1; reload = 1;}
	if (alerts != alerts1) {changed = 1; alerts = alerts1;}
	if (window_size != window_size1) {changed = 1;window_resized = 1; window_size = window_size1;}
	if (text_size != text_size1) {changed = 1; text_size = text_size1;}
	if (auto_jump != auto_jump1) {changed = 1; auto_jump = auto_jump1;}
	if (posts_per_page != posts_per_page1) {changed = 1; reload = 1; posts_per_page = posts_per_page1;}
	return [changed, reload,window_resized];	
}

function submitPrefsForm() {
	
	prefsObj.changed = 0; 
	prefsObj.reload = 0;
	prefsObj.window_resized = 0;
	var x = readPrefsForm();
	
	prefsObj.changed = (x[0]==1) ? 1 : 0; // find out if anything changed
	prefsObj.reload  = (x[1]==1) ? 1 : 0; // find out if changes require reload
	prefsObj.window_resized  = (x[2]==1) ? 1 : 0; // find out if window size has been changed
	var cidString = "";
	var shString = "";
	var clientpref = "";
	var cidStringbc = "";
	var shStringbc = "";
	var clientprefbc = "";
	var clientid = $('pref_clientid').value;
	var pars = 'sid=' + sid;
	
	pars += '&characters=' + characters;
	
	/*pars += '&clientid=' + clientid;*/
	
	pars += '&alerts=' + alerts;
	pars += '&window_size=' + window_size;
	pars += '&text_size=' + text_size;
	pars += '&auto_jump=' + auto_jump;
	pars += '&posts_per_page=' + posts_per_page;

	if (prefsObj.changed == 1) {
		var myAjax = new Ajax.Request('scripts/updatepref_submit.php', {method: 'post', parameters: pars, onLoading:showBuzzProgress('Loading...'),onComplete:finishSubmit});
	}
	else{
	finishSubmit();}
}

function finishSubmit(req)
{
	finishBuzzProgress();
	if(prefsObj.window_resized == 1)
	{
		setBuzzWidth(); // set width
	}
	if(prefsObj.changed == 1)
	{		
		toggleBuzzTab();	
		conformToPrefs();
		setScroll = null;
		setAddEditPostWidth();
		if(currentViewingGroup != null)
		{
			refreshPostPage = true;
			
		}
	}
	else
	{
		//alert("No changes have done by you ")
	}		
}
//SEARCH MODULE
function finishSearchRequest (req) {
	if (req.responseText)
		$('searchResults').innerHTML = req.responseText;
	else 
		$('searchResults').innerHTML = "There was a problem with your request.";
}

//CONTENT MODULE 

function documentKeyDown(oEvent){ // controls keyboard navigation
	var oEvent = (typeof oEvent != "undefined")? oEvent : event;
	var oTarget = (typeof oEvent.target != "undefined")? oEvent.target : oEvent.srcElement;
	var intKeyCode = oEvent.keyCode;
	switch(intKeyCode){			
		//case 8: 
		//case 37:
		case oEvent.altKey && 37:
			oEvent.cancelBubble = true;
			oEvent.returnValue = false;
			if(oEvent.preventDefault){
				oEvent.preventDefault();
			}
			if (nav.prevPage && nav.noPrev==false) {
				//alert("loading page " + nav.prevPage);
				loadPage(nav.prevPage);
			}
			return false;
		case 13:
			// Enter Key enabled
			break;
			//if ($("search").style.display != "none")
			//	{submitSearchForm(); break;}
		//case 32: allow spacebar to trigger a page down
		case oEvent.altKey && 39:
			oEvent.cancelBubble = true;
			oEvent.returnValue = false;
			if(oEvent.preventDefault){
				oEvent.preventDefault();
			}
			if (nav.nextPage && nav.noNext==false) {
				//alert("loading page " + nav.nextPage);
				loadPage(nav.nextPage);
			}
			return false;
	}	
}

function cancelDefaultNavigationEvents(oEvent){ // no back button screwups
	var oEvent = (typeof oEvent != "undefined")? oEvent : event;
	var oTarget = (typeof oEvent.target != "undefined")? oEvent.target : oEvent.srcElement;
	var intKeyCode = oEvent.keyCode;
	switch(intKeyCode){			
		//case 8:
		case oEvent.altKey && 37:
		case oEvent.altKey && 39:
			oEvent.cancelBubble = true;
			oEvent.returnValue = false;
			if(oEvent.preventDefault){
				oEvent.preventDefault();
			}
			documentKeyDown(oEvent);
			break;
	}	
	
}

function callInProgress (xmlhttp) {
	switch (xmlhttp.readyState) {
		case 1: case 2: case 3:
			return true;
			break;
		// Case 4 and 0
		default:
			return false;
			break;
	}
}
function clearStatusMsg(seconds){
		setTimeout("$('loadingMessageDiv').innerHTML='<center><div class=errormesg></div></center>'", seconds);
	}
	
function showFailureMessage() {
	//showBuzzFail("It looks like the network is down. Try again shortly");
	//showBuzzFail(failuremsg);// defined in contant file called in buzz.php
	//clearStatusMsg(5000);
	//alert('uh oh, it looks like the network is down. Try again shortly');
	//window.refresh;
	//toggleBuzzTab();
}

// Register global responders that will occur on all AJAX requests

Ajax.Responders.register({
	onCreate: function(request) {
		request['timeoutId'] = window.setTimeout(
			function() {
				// If we have hit the timeout and the AJAX request is active, abort it and let the user know
				if (callInProgress(request.transport)) {
					request.transport.abort();
					showFailureMessage();
					// Run the onFailure method if we set one up when creating the AJAX object
					if (request.options['onFailure']) {
						request.options['onFailure'](request.transport, request.json);
						}
					}
				}, delaytime// was Ten seconds changed to 20000
			);
		},
		onComplete: function(request) {
		// Clear the timeout, the request completed ok
		window.clearTimeout(request['timeoutId']);
	}
});

function showProgress (id) { // puts spinner in specified div
	var x = $(id);
	x.innerHTML = '<div class="progress">Loading... <img src="images/spinner.gif" /></div>';
	
	// this would be a good place to include a timeout function
}

function showFailure (id) {
	var x = $(id);
	x.innerHTML = '<div class="progress">There has been an error accessing the server. Please check your Internet connection and try again.</div>';
}

function loadPage(page) {
	var url = host+'/buzz/_content.php';
	var pars = 'sid=' + sid + '&page=' + page + "&chars=" + characters + "&posts=" + posts_per_page; 
	var myAjax2 = new Ajax.Request(url, {method: 'post', parameters: pars, onLoading:showBuzzProgress('Loading...'), onComplete:finishLoadingPage});
}

function finishLoadingPage(req) {
  
  try {
   if (req.responseText.length>0) {
//	if (req.responseText.length>0) {
	finishBuzzProgress();
	$('articles').innerHTML = req.responseText;
	
//CG 6/28/06 attempt to fix security
//turned out to be too aggressive, I think because of multiple connections
//	if (req.responseText.indexOf("HTTP-EQUIV='Refresh'")) {
//		window.location.replace('http://www.minyanville.com/buzz/buzz.php');
//	}
	///////////////////////////////////////
	currentPage = $("pageNo").innerHTML;
	loadNavigation(currentPage);
	//////////////////////////////////////
	if (req.responseText.indexOf("There are no posts to display") == -1) {
		if (typeof($('pageNo')) == 'object'){
			currentPage = $("pageNo").innerHTML;
		}	
		if (typeof($('topPage')) == 'object'){
			topPage = $("topPage").innerHTML;
		}	
		$('articles').scrollTop = 0;
		makeLinksIntoPopups();
		//fixHeight();
		//alert("made it this far");
		loadNavigation(currentPage);
	} else {
		window.refresh();
	}
   } else
    latestTimeStamp = 0;
    latestTimeStampbc = 0;
  } catch (e) {
    latestTimeStamp = 0;
    latestTimeStampbc = 0;
  }
}

function loadNavigation(page) {
	//alert("attempting to load navigation");
	var url = '_navigation.php';
	var clientid = $('pref_clientid').value;
	var pars = 'sid=' + sid + '&page=' + stripHTML(page) + '&clientid=' + clientid + "&posts=" + posts_per_page;
	var target = 'navigation';
	//alert (pars);
	var myAjax3 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:finishLoadingNavigation});
	return;
}


function finishLoadingNavigation(req) {
	//alert('hil');
	if(latestID==null)
	{
		checkforbuzzinit();
	}
	/*if(latestIDbc==null)
	{
		checkForBuzzbcinit();
	}*/
	//alert(req.responseText);
	nav = eval('(' + req.responseText + ')');
	var navigation = '';
	navigation += '<a href="javascript:void(0);" onclick="jumpToLatestPost(); return false;" id="latestPost">Latest Post</a>';
	navigation += '<a href="javascript:void(0);" onclick="printAllPosts(); return false;" id="printAll" name="printAll"><img src="images/print_all.gif" /></a>';

	navigation += '<div id="navPages" style="padding-top:0px;">';
//	navigation += '<BR><a href="javascript:void(0);" class="noUnderline1" style="cursor:text ">Pages</a><BR>';
	if (nav.noPrev==true) {
		navigation += '<span class="noUnderline grayout">&lt;Back &nbsp;';
	} else {
		navigation += '<a href="javascript:void(0);" class="noUnderline" onclick="loadPage(' + nav.prevPage + '); return false;">&lt; Back </a>&nbsp; ';
	}
	if (nav.startPage > 0) {
		for (i=nav.startPage; i<=nav.endPage; i++) {
			navigation += '&nbsp;<a href="javascript:void(0);" onclick="loadPage(' + i + '); return false;"';
			if (i == nav.page) {navigation+= ' class="currentPage"';} 
			navigation += '>' + i + '</a>';
		}
	}
	if (nav.noNext==true) {
		navigation += '<span class="noUnderline grayout">&nbsp; Next &gt; ';
	} else {
		navigation += '&nbsp; <a href="javascript:void(0);" class="noUnderline" onclick="loadPage(' + nav.nextPage + '); return false"> Next &gt;</a>';
	}
	navigation +='<center><a style="text-decoration:underline;" href="javascript:void(0);" onclick="javascript:launchPage(\'/buzz/print.php?date='+nav.yesterdayPosts+'\',\'yesterday\',1);">Yesterday&rsquo;s Buzz</a></center>';
	navigation += '</div><div class="clear"></div>';
	
	$("navigation").innerHTML = navigation;
	dropDownPos();
	return;
}

function jumpToLatestPost() {
	var pars = 'sid=' + sid + '&latest=1&chars=' + characters + "&posts=" + posts_per_page;
	jumpToId = 'latest';
	//alert("jumping to latest post. pars: " + pars);
	jumpRequest(pars);
}

function jumpToPost(id,snap) {
	// first take the user to the place they can see the post
	//if (alertWindow && alertWindow.open && !alertWindow.closed) {alertWindow.close();}
	var snap = (snap == null) ? "nosnap" : snap;
	if (snap == "snapto") toggleBuzzTab();
	$("jumpToPost").className="";

	if ($("postMenu").style.display != "none") {Effect.Fade("postMenu");}
		Event.stopObserving('content','click',toggleJump);
	
	//toggleBuzzTab();
		
	jumpToId = 'post' + id; // then send a request for the post
	var pars = 'sid=' + sid + '&bbid=' + id  + "&chars=" + characters + "&posts=" + posts_per_page;
	jumpRequest(pars);
}

function jumpToPostbuzzchannel(clientid,id,snap) {
	// first take the user to the place they can see the post
	//if (alertWindow && alertWindow.open && !alertWindow.closed) {alertWindow.close();}
	var snap = (snap == null) ? "nosnap" : snap;
	if (snap == "snapto") toggleBuzzTab();
	$("jumpToPost").className="";
	if ($("postMenu").style.display != "none") {Effect.Fade("postMenu");}
		Event.stopObserving('content','click',toggleJump);
	//toggleBuzzTab();
	jumpToId = 'post' + id; // then send a request for the post
	var pars = 'sid=' + sid + '&bbid=' + id + '&clientid=' + clientid + "&chars=" + characters + "&posts=" + posts_per_page;
	jumpRequest(pars);
    // close jumptopost dropdown
	Element.hide("postMenu");
	$("jumpToPost").className="";
	Event.stopObserving('content','click',toggleJump);		
}

function jumpToTimeStamp(udate) {
	jumpToId = 'latest';
	var pars = 'sid=' + sid + '&udate=' + udate + "&chars=" + characters + "&posts=" + posts_per_page;
	jumpRequest(pars);
}

function reloadLastPage(id) {

}
//////////////////////////////////////////////////////////////////////
// send ajax request to the tools page
function toolRequest(){
	var url = '_tools.php';
	var pars = 'effecttype=divload&defultlink=1&tagsearch=';
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onLoading:showBuzzProgress('Loading...'), onComplete:finishTool});
}

function preferencerequest(){
	var url = '_tools.php';
	var pars = 'effecttype=loadpreference';
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onLoading:showBuzzProgress('Loading...'), onComplete:finishTool});
}
// load tools div with ajax response 
function finishTool(req){
		finishBuzzProgress();
		$('tools').innerHTML = req.responseText;
		changestyle("pre_jumppost");
		changestyle("pre_posts");
		changestyle("pre_fontsize");
        changestyle("pre_alert");
		changestyle("pre_windowsize");
		changestyle("pre_critter");
}
//////////////////////////////////////////////////////////////////////
function jumpRequest(pars) {
	var url = host+'/buzz/_content.php';
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onLoading:showBuzzProgress('Loading...'), onComplete:finishJump});
}

function finishJump(req) {
	
	//$("usergroupsbar").innerHTML=req.responseText;
    
	try { // on the first try Firefox returns errors on status, so run again
      var status;
      status = req.status;
    } catch (e) {
      //  caught error - try again in .5 seconds
      setTimeout('jumpToLatestPost()', 500);
      return;
    }
	
  
    //if (req.responseText.indexOf("There are no posts to display") == -1) {
		//if (jumpToId != "latest") $("content").style.visibility = "hidden";
		
		$('articles').innerHTML = req.responseText;
		
		//fixHeight();
		//alert("done fixing height");	
		currentPage = $('pageNo').innerHTML;
		
		if (typeof($('topPage')) == 'object')
			topPage = $('topPage').innerHTML;
		else
			topPage = null;
		
		if (typeof($('latestPostID')) == 'object')
			latestIDjump = $('latestPostID').innerHTML;
		//alert(latestID);	
		loadNavigation(currentPage);
		var obj=document.getElementById(jumpToId);
		if (jumpToId == "latest") $('articles').scrollTop=0;
		if (jumpToId != "latest") setTimeout("jumpScroll()",500);
	//} else {
	//	loadPage(currentPage);
	//}
	makeLinksIntoPopups();
	refreshPostMenu();
	finishBuzzProgress();
	return;
}

function fixHeight () {
	var h = null;
	var z = document.getElementsByClassName("articleBody"); 
	//alert(z.length);
	//alert("2**********"+text_size);
	if (characters == 0) {
		switch (text_size) {
			case "s": h = 90; break;
			case "m": h = 120; break;
			case "l": h = 140; break;
		}
	}
	else if (characters == 1) {
		switch (text_size) {
			case "s": h= 180; break;
			case "m": h= 210; break;
			case "l": h= 240; break;
		}
	}
	h = h + "px";
	//alert('calculated h:' + h);
	for (i=0;i<z.length;i++) {
		z[i].style.height = h;
	}
	//alert('done adjusting height');
}	

function jumpScroll() {
	if (jump.gotoPos != null) {
		var x = $("articles").scrollHeight - jump.oldHeight;
		if (x > 0) {
			$("articles").scrollTop = jump.gotoPos + x;
		} else {
			$("articles").scrollTop = 0;
		}
		
	} else {
		
		var x = eval("$('" + jumpToId + "')");
		$("articles").scrollTop = x.offsetTop;
	}
	
	Element.hide("welcome_screen");
	Element.hide("welcome_overlay");
	$("content").style.visibility = "visible";
	//new Effect.BlindDown("content",{duration:.2});
}	

function makeLinksIntoPopups() {
	var popup2 = document.getElementsByClassName("articleBody");
    for (var j=0; j<popup2.length; j++) {
		var links = popup2[j].getElementsByTagName('a');
	    for (var i=0; i<links.length; i++) {
		  var name= "link" + i + "";		
      	  var url = links[i].getAttribute('href');
	      if (url.indexOf("bookmark.php") == -1) {
	        args = "javascript:launchPage('" + url + "','" + name + "',0);void(0);";
	  	  } else {
	  	  	args = "javascript:launchBookmarkFromURL('" + url + "');void(0);";
	  	  }
          links[i].href = args;
		}
    }
}

function makeLinksIntoPopupsPr() {
	var popup2 = document.getElementsByClassName("articleBodyPr");
    for (var j=0; j<popup2.length; j++) {
		var links = popup2[j].getElementsByTagName('a');
	    for (var i=0; i<links.length; i++) {
		  var name= "link" + i + "";
      	  var url = links[i].getAttribute('href');
	      if (url.indexOf("bookmark.php") == -1) {
	        args = "javascript:launchPage('" + url + "','" + name + "',0);void(0);";
	  	  } else {
	  	  	args = "javascript:launchBookmarkFromURL('" + url + "');void(0);";
	  	  }
        links[i].href = args;
	  	}
	}
}


function yahooSubmit() {
	var url = "http://finance.yahoo.com/q?s=" + $F("s") + "&x=40&y=20&partner=mv";
	launchPage(url,"yahooSymbolSearch",0);
}
var inc = 1;

function docKeyDown1(oEvent){ // controls keyboard navigation
var oEvent = (typeof oEvent != "undefined")? oEvent : event;
var oTarget = (typeof oEvent.target != "undefined")? oEvent.target : oEvent.srcElement;
var intKeyCode = oEvent.keyCode;
 
if(intKeyCode==17)
{
	inc=0;
	 
}
if (inc==0)
{
	if(intKeyCode==65 || intKeyCode==97 )
	{			
		inc=1; // resolve issue for disabled a and A character on key board		
		return(false);   //in case of IE & firefox1.5					
	}		
}
	
} 
function disableclick()
{
	document.onmousedown=new Function("return false");void(0);
	document.oncontextmenu=new Function("return false");
}
function enableclick()
{
	document.onmousedown=new Function("return true");void(0);
	document.oncontextmenu=new Function("return true");
}

//BODY ONLOAD = INIT() MODULE

function init(id) {

	/***********************************************
	* Disable select-text script- © Dynamic Drive (www.dynamicdrive.com)
	* This notice MUST stay intact for legal use
	* Visit http://www.dynamicdrive.com/ for full source code
	***********************************************/

	//form tags to omit in NS6+:
	var omitformtags=["input", "textarea", "select"]

	omitformtags=omitformtags.join("|")

	function disableselect(e){
		if (omitformtags.indexOf(e.target.tagName.toLowerCase())==-1)
		return false
	}

	function reEnable(){
		return true
	}
	hideGroupTab();
	if(groupActive=='1'){
	groupRequest();
	}
	dropDownPos();		
	readPrefsForm();
	conformToPrefs();
	setBuzzWidth();
	jumpToLatestPost();
	refreshPostMenu();
	refreshBookmarks();		
	/*if error occur donot check session and existing user*/
	if(buzzCheckUserSession=='1'){
		checkExistingUser(id);
	}
	// calling at the time of initialisation
	//****** temporary toolRequest();
	preferencerequest();	

	var pe = new PeriodicalExecuter(checkForNewBuzz,buzzRefreshTime);
		
//	var pe = new PeriodicalExecuter(checkForNewBuzzBC, 300);	
	var pe = new PeriodicalExecuter(glowGroupTabsScript, 60);
	var pe = new PeriodicalExecuter(getGroupUpdates, 60);
    if(buzzCheckUserSession=='1'){
		var pe = new PeriodicalExecuter(getUserSession, 100);
	}
	document.onkeydown=docKeyDown1;
	Event.observe(document, "keypress", cancelDefaultNavigationEvents, true);
	Event.observe(document, "keydown", documentKeyDown, true);
	if(groupActive=='1'){
	Event.observe('tabGroups', 'click', toggleSearchTab);
	}
	Event.observe('tabBuzz', 'click', toggleBuzzTab, true);
	if(groupActive=='1'){
	Event.observe('tabGroups','mouseover',tabSearchRollover, true);
	Event.observe('tabGroups','mouseout',tabSearchRollover, true);
	}
	Event.observe('tabBuzz','mouseover',tabBuzzRollover, true);
	Event.observe('tabBuzz','mouseout',tabBuzzRollover, true);
	Event.observe('tabtools', 'click', toggleToolsTab, true);
	Event.observe('tabtools','mouseover',tabToolsRollover, true);
	Event.observe('tabtools','mouseout',tabToolsRollover, true);
	Event.observe('jumpToPost','click',toggleJump);
	Event.observe('bookmark','click',toggleBookmark);
	
	Event.observe(window,'resize',manualResizeBuzz);
	Event.observe('search_keywords','mouseover',enableclick,true);
	Event.observe('search_keywords','mouseout',disableSearchClick,true);	

}
function disableSearchClick()
{
	if($("tabBuzz").className=="buzzOn")
	{
		disableclick();
	}	
}
function logout(from)
{	
		var url = '/banter/logout.htm';
	var pars = ''
	if(from == 'buzz')
	{
		 pars ="logout_from=buzz"
	}
        var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars})
		pause(1000);
		if(from==undefined || from==''){
		window.location="/index.htm";
		}
	
}
function pause(millisecondi)
{
var now = new Date();
var exitTime = now.getTime() + millisecondi;

while(true)
{
now = new Date();
if(now.getTime() > exitTime) return;
}
}

/************** Functions defined : Aswini ********************/
/* This array stores the status that decides query firing*/
var selectedtabresults=new Array(3);
//*****avar tdBuzz_search_tabSelected='PREMIUM_CONTENT';
var tdBuzz_search_tabSelected='ALL_CONTENT';
//*****avar tdBuzz_search_pagination='pagination_PC';
var tdBuzz_search_pagination='pagination_AC';
var searchedtext='';
selectedtabresults['PREMIUM_CONTENT']=0;
selectedtabresults['GROUP_CONTENT']=0;
selectedtabresults['ALL_CONTENT']=0;
var paginationResults=new Array(3);
paginationResults['pagination_PC']=0;
paginationResults['pagination_GC']=0;
paginationResults['pagination_AC']=0;
function hidedisplay(n){
	switch(n)
	{
		case 1:
			$('prefe').style.fontWeight="normal";//style.font-weight='100';
			$('ser').style.fontWeight='bold';
			$('ser').style.cursor="";
			$('prefe').style.cursor="pointer";
			$('preferencediv').hide();
			$('searchdiv').show();
			//****$('pager').show();
			$(tdBuzz_search_tabSelected).show();
			
			if(tdBuzz_search_tabSelected=='PREMIUM_CONTENT'){
				if(paginationResults['pagination_PC']==1){
					$('pager').show();
					$('pagination_PC').show();
				}
			}
			
			if(tdBuzz_search_tabSelected=='GROUP_CONTENT'){
				if(paginationResults['pagination_GC']==1){
					$('pager').show();
					$('pagination_GC').show();
				}
			}
			if(tdBuzz_search_tabSelected=='ALL_CONTENT'){
			 if(paginationResults['pagination_AC']==1){
				$('pager').show();
				$('pagination_AC').show();
			 }
			}
			break;    
		case 2:
			$('ser').style.fontWeight='normal';
			$('ser').style.cursor="pointer";
			$('prefe').style.cursor="";
			$('prefe').style.fontWeight='bold';
			$('searchdiv').hide();
			//$('PREMIUM_CONTENT').hide();
			$('pager').hide();
			$('preferencediv').show();
			break;
	}
}

/*function for subtabbar of tools tab*/
function subtabactive(id){
		$('pager').hide(); // we are hiding the pagination div
		switch(id){
		case 'buzzposts': 
		{
			tdBuzz_search_tabSelected='PREMIUM_CONTENT';
			tdBuzz_search_pagination='pagination_PC';

			$('GROUP_CONTENT').hide();
			$('ALL_CONTENT').hide();
			$('PREMIUM_CONTENT').show();
			
			/* Pagination div show or hide */
			if(paginationResults['pagination_PC']==1){
				$('pager').show();
				$('pagination_PC').show();
				$('pagination_GC').hide();
				$('pagination_AC').hide();
			}
			/*Pagination div show/hide */
			document.getElementById(id).className="active";
			document.getElementById('decisiongrp').className="inactive";
			document.getElementById('allposts').className="inactive";
			// conditions checked for AJAX REQUEST
			if(searchedtext!='' && (selectedtabresults['PREMIUM_CONTENT']==0)){tabRequest('pagination_PC');}
			break;
		}
		case 'decisiongrp': 
		{
			tdBuzz_search_tabSelected='GROUP_CONTENT';
			tdBuzz_search_pagination='pagination_GC';
			$('PREMIUM_CONTENT').hide();
			$('GROUP_CONTENT').show();
			$('ALL_CONTENT').hide();
			/* Pagination div show/hide */
			if(paginationResults['pagination_GC']==1){
				$('pager').show();
				$('pagination_GC').show();
				$('pagination_AC').hide();
				$('pagination_PC').hide();
			}
			/* Pagination div show/hide */
			document.getElementById('buzzposts').className="inactive";
			document.getElementById(id).className="active";
			document.getElementById('allposts').className="inactive";
			// conditions checked for AJAX REQUEST
			if(searchedtext!='' && (selectedtabresults['GROUP_CONTENT']==0)){tabRequest('pagination_GC');}
			break;
		}
		case 'allposts': 
		{
			tdBuzz_search_tabSelected='ALL_CONTENT';
			tdBuzz_search_pagination='pagination_AC';
			$('ALL_CONTENT').show();
			$('GROUP_CONTENT').hide();
			$('PREMIUM_CONTENT').hide();
			/* Pagination div show/hide */
			if(paginationResults['pagination_AC']==1){
				$('pager').show();
				$('pagination_AC').show();
				$('pagination_GC').hide();
				$('pagination_PC').hide();
			}
			/* Pagination div show/hide */
			$('buzzposts').className="inactive";
			$('decisiongrp').className="inactive";
			$(id).className="active";
			// conditions checked for AJAX REQUEST
			if(searchedtext!='' && (selectedtabresults['ALL_CONTENT']==0)){tabRequest('pagination_AC');}
			break;
		}
	}
}

function tabRequest(paginationdiv){
	$('searchresultdiv').setStyle({
	display:"block"
	});
	$('searchdiv').setStyle({
	/*height:"440px",*/
	display:"block"
	});
	var rows_per_page = $('pref_posts_per_page').value;
	//alert(rows_per_page);
	if(selectedtabresults[tdBuzz_search_tabSelected]==0){
		//  step -1  Assign the previously searched text
		searchword=searchedtext;
		//  step -2  update the text searched
		selectedtabresults[tdBuzz_search_tabSelected]=1;
		//****alert("Sending the request for 1st time "+tdBuzz_search_tabSelected);
		var url = '_tools.php';
		var pars = 'effecttype=search&defultlink=1&keywordsearch='+searchword+'&incontent='+tdBuzz_search_tabSelected+'&start=0&limit='+rows_per_page;
		var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars,
			onLoading:showBuzzProgress("Loading..."),
			onComplete:function finishSearchkeyword(req){
			$(tdBuzz_search_tabSelected).setStyle({
			height: searchheight,
			overflow:'auto'								
			});
			$divcontent=req.responseText.split("##");
			$(tdBuzz_search_tabSelected).innerHTML = $divcontent[0];
			if($divcontent[1]==""){
				$(tdBuzz_search_tabSelected).setStyle({
				height: 35+parseInt(searchheight)+"px"
				});
			}
			switch(paginationdiv){
				case 'pagination_PC': 
				{
					if($divcontent[1].length!=0){
					paginationResults['pagination_PC']=1;
					$('pager').show();
					$('pagination_PC').innerHTML=$divcontent[1];//'PREMIUM PAGINATION 1'
					$('pagination_PC').show();
					$('pagination_GC').hide();
					$('pagination_AC').hide();
					}else{
					$('pager').hide();
					}
					break;
				}
				case 'pagination_GC': 
				{
					if($divcontent[1].length!=0){
					paginationResults['pagination_GC']=1;
					$('pager').show();
					$('pagination_GC').innerHTML=$divcontent[1];//'GROUP PAGINATION 1'
					$('pagination_GC').show();
					$('pagination_PC').hide();
					$('pagination_AC').hide();
					}else{
					$('pager').hide();
					}
					break;
				}
				case 'pagination_AC': 
				{
					if($divcontent[1].length!=0){
					paginationResults['pagination_AC']=1;
					$('pager').show();
					$('pagination_AC').innerHTML=$divcontent[1];//'ALL CONTENT PAGINATION 1'
					$('pagination_AC').show();
					$('pagination_PC').hide();
					$('pagination_GC').hide();
					}else{
					$('pager').hide();
					}
					break;
				}
			}
			
			finishBuzzProgress();
			$('searchdiv').setStyle({
			height:""
			});
		}});
	}	
}


/*
This function is called in every page no link
 */

function reloadPagecontents(tagsearch,pageno,rows_perpage,offset,buzztype,anotherid){
	if($(tdBuzz_search_tabSelected+'_viewpageno').value==pageno){
	//****alert("You are viewing the current page");
	return void(0);
	}else{
	// Call the function that reload 2 divs
	searchResults(tagsearch,pageno,rows_perpage,offset,buzztype,anotherid);
	}
}

function searchResults(tagsearch,pageno,rows_perpage,offset,buzztype,anotherid){
	//var currentpage=$('navPages').getElementsByClassName('currpage');
	prevsearchword=searchedtext;
	var re = /^\s{1,}$/g; //match any white space including space, tab, form-feed, etc.
	if((prevsearchword=='')||(prevsearchword.length==0) || (prevsearchword==null) || (prevsearchword.search(re) > -1)){
		alert("Serach field is blank")
		$('search_keywords').focus();
		return false;
	}
	// ***** $(tdBuzz_search_tabSelected).innerHTML=''; // for the time we have hided onLoading:showProgress(tdBuzz_search_tabSelected), so we hided this line also
// step -5 Make the AJAX REQUEST TO GET RECORDS		
	var url = '_tools.php';
	if(tagsearch=='tag'){
	var pars = 'effecttype=searchTagRes&defultlink=1&tagsearch='+prevsearchword+'&item_type=1&incontent='+tdBuzz_search_tabSelected+'&start='+offset+'&limit='+rows_perpage+'&selectedpage='+pageno+'&buzztype='+buzztype+'&anotherid='+anotherid;
	}else{
	var pars = 'effecttype=search&defultlink=1&keywordsearch='+prevsearchword+'&incontent='+tdBuzz_search_tabSelected+'&start='+offset+'&limit='+rows_perpage+'&selectedpage='+pageno;
	}
	// during search we are increaseing the value to 30seconds 
	delaytime=30000;
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars,
						//onLoading:showProgress(tdBuzz_search_tabSelected),
						onLoading:showBuzzProgress('Loading...'),
						onComplete:function finishSearchkeyword(req){
						$(tdBuzz_search_tabSelected).setStyle({
							height: searchheight,
							overflow:'auto'								
						});
					searchContents=req.responseText;//.split("##");
					$(tdBuzz_search_tabSelected).innerHTML = searchContents;//[0];
					$(tdBuzz_search_tabSelected).show();
					var viewpageno=$(tdBuzz_search_tabSelected+'_viewpageno').value;
					$(tdBuzz_search_tabSelected+'_link_'+viewpageno).removeClassName('currpage');
					$(tdBuzz_search_tabSelected+'_link_'+viewpageno).addClassName('pagelink');
					$(tdBuzz_search_tabSelected+'_link_'+pageno).addClassName('currpage');
					$(tdBuzz_search_tabSelected+'_viewpageno').value=pageno;
					finishBuzzProgress();
					delaytime=20000;
				}});
}

function showPrevious(tagsorkey,tabname,rows_perpage,buzztype,anotherid){
	var viewingpage=$(tabname+'_viewpageno').value; // current page u r viewing
	var pageno=parseInt(viewingpage)-1;				// Page that You want to view
	var startindex=$(tabname+'_statindex').value;	// Default Start PageNo stores in hidden field
	//alert("Current Viewing page :"+viewingpage+" Target Page :"+pageno+" HIDDEN VALUE "+startindex);
	 /*
	 when Target Page is equals to start Index and Target
	 Page is =1 Then disable the back link or when Target
	 Target Page is =1 Then disable the back link
	 */

	if(((pageno==startindex) && (pageno==1)) || (pageno==1) ){
		$(tabname+'_backlink').addClassName('dim');
	}
	/*
	When Target Page is not visible and we want to view that
	page We are displaying the Target page and hiding the last
	Page that was in the current display range
	*/
	if(pageno<startindex && startindex>1){
		$(tabname+'_link_'+pageno).show();
		var ll=pageno+5;
		$(tabname+'_link_'+ll).hide();
		//Resting the start index and last index of the current display
		$(tabname+'_statindex').value=pageno;
		$(tabname+'_lastIndex').value=pageno+4;
		$(tabname+'_nextlink').removeClassName('dim');
	}
	
	if(pageno!=0){
	offset=$(tabname+'_offeset_'+pageno).value;
	reloadPagecontents(tagsorkey,pageno,rows_perpage,offset,buzztype,anotherid);
	}
	$(tabname+'_nextlink').removeClassName('dim');
}

function showNextPage(tagsorkey,tabname,rows_perpage,buzztype,anotherid){
	var viewingpage=$(tabname+'_viewpageno').value;
	var pageno=parseInt(viewingpage)+1;
	// assigning the lastpage no to lastPageno for Pagination purpose in Nex > case
	var lastPageno=$(tabname+'_lastlink').value;
	//alert("seting the value to "+pageno);
	//alert("Current Viewing page :"+viewingpage+" Target Page :"+pageno+" LAST PAGE  "+lastPageno);
	// if the taget pageno is greter than last page then do nothing
	if(pageno>lastPageno){
		return false;
	}
	var lastindex=$(tabname+'_lastIndex').value;
	if((viewingpage==lastindex) && (pageno<=lastPageno))
	{
		var firstIndex=$(tabname+'_statindex').value;
		$(tabname+'_link_'+firstIndex).hide();
		$(tabname+'_statindex').value=parseInt($(tabname+'_statindex').value)+1;
		$(tabname+'_link_'+pageno).show();
		$(tabname+'_lastIndex').value=parseInt($(tabname+'_lastIndex').value)+1;
		offset=$(tabname+'_offeset_'+pageno).value;
		reloadPagecontents(tagsorkey,pageno,rows_perpage,offset,buzztype,anotherid);
		if(pageno==lastPageno){
		$(tabname+'_nextlink').addClassName('dim');
		}
		if($(tabname+'_statindex').value>1){
			$(tabname+'_backlink').removeClassName('dim');
		}
	}

	if((viewingpage!=lastindex) && (pageno<=lastPageno))
	{
		offset=$(tabname+'_offeset_'+pageno).value;
		reloadPagecontents(tagsorkey,pageno,rows_perpage,offset,buzztype,anotherid);
		if(pageno==lastPageno){
			$(tabname+'_nextlink').addClassName('dim');
		}
		if($(tabname+'_statindex').value>1){
			$(tabname+'_backlink').removeClassName('dim');
		}
	}

	if((parseInt(pageno))>(parseInt($(tabname+'_statindex').value))){
		$(tabname+'_backlink').removeClassName('dim');
	}
}

function lunchAdmintool(user_id,ismoderator){
	
	if(ismoderator==0){		
		// set height for the overlay div causing dark effect
		$('tools_moderator_overlay').style.height = (getWindowHeight() - 91)+"px";		
		$('tools_moderator_overlay').show();
		// get the conetent for moderator request
		var url = '_tools.php';
		var pars = 'effecttype=lunchadmintool&userid='+user_id;
		var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:function getContents(req){
			$('moderaroReqConent').innerHTML=req.responseText;
			$('moderaroReqConent').style.display="";
			new Effect.SlideDown("admincontents",{duration:1.0});
			}});
		}else{
			window.open(host+'/admin/home.htm','adminwindow');
		}
}
// load tools div with ajax response 
function finishadminTool(req){
	$('preferencediv').innerHTML = req.responseText;
}
function appliedforModerator(uid){
	var url = '_tools.php';
	var pars = 'effecttype=applyformoderator&uid='+uid;
	var myAjax4 = new Ajax.Request(url,
	{
	method: 'post',
	parameters: pars,
	onLoading:showBuzzProgress('Loading...'),
	onComplete:function finishModeratorRequest(req){
	if(parseInt(req.responseText)==2){	
	$('modmsgdiv_fail').innerHTML="Thanks for Your Request.";
	$('modmsgdiv_fail').show();
	}else if(parseInt(req.responseText)==3){
	$('modmsgdiv_fail').innerHTML="You Have Already Applied for Moderator.";
	$('modmsgdiv_fail').show();	
	}else if(parseInt(req.responseText)==4){
	$('modmsgdiv_fail').innerHTML="Please Register yourself....";
	$('modmsgdiv_fail').show();	
	}
	finishBuzzProgress();
	setTimeout("autoHideDiv('+uid+')", 5000);
	}});
}
function autoHideDiv(uid){
	if($('tools_moderator_overlay').style.display!='none'){
		cancelModeratorReq(uid);
	}
}
function cancelModeratorReq(uid){
	new Effect.SlideUp("admincontents",{duration:1.0});
	$('tools_moderator_overlay').hide();//('overlay');//hide();
}
function enablefield(id){
	$(id).focus();
	if (typeof document.onselectstart!="undefined")
		document.onselectstart=new Function ("return false")
	else {
			document.onmousedown=disableselects
			document.onmouseup=reEnables
	      }
}
var omitformtagss=["input", "textarea", "select"]
	omitformtagss=omitformtagss.join("|")
function disableselects(e){
	if (omitformtagss.indexOf(e.target.tagName.toLowerCase())==-1)
		return false
}
function reEnables(){return true}
/***************Aswini code ends *************/

function getLatestPostId(groupid,lastvisitpostid){	
	var objDiv=document.getElementById("usergroupsbar");	
	var pars='';
	var url=host+this.data_path+"data/group_latest_post_id_"+groupid+".txt";
	try{
	
		var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:function(req){
				
				// sent request for update only if user is not veiwing specific group rihgt now and post id in the server file is greater than the post id user has visited
				if(parseInt(req.responseText)!= NaN  && parseInt(req.responseText)>parseInt(lastvisitpostid) && groupid != activeGroup)
				{												
					var requestUrl=host+'/buzz/get_groups_update.php';
					var requestPars='lastvisitid='+lastvisitpostid+'&groupid='+groupid;
					var requestAjax=new Ajax.Request(requestUrl, {method: 'post', parameters: requestPars, onComplete:function(req){
						updates = eval('(' + req.responseText + ')');
						var strHTML='<a style="cursor:pointer;color:#a0833b;" onclick="showGroup('+updates.groupid+');" >'+updates.groupname;
						if(updates.update>0){
							strHTML+='(+'+updates.update+')';
						}
						strHTML+='<\/a>';
						$('group_'+groupid).innerHTML=strHTML;
					}
					});//requestAjax
				
				}
			}
		});//myAjax
	}
	catch  (e){
		return 0;
	}
	
}



function getGroupUpdates(){
	var userGroups=getUserGroupId();	
	
	for(i=0; i<userGroups.length; i++){
		lastVisitedPostId=groupVisitedPostIdArray[userGroups[i]];
		getLatestPostId(userGroups[i],lastVisitedPostId);		
	}
}

function showRevolvingGroups(){
	
	var url=host+"/buzz/user_groups_bar.php";
	var pars = "";
	var userGroups=getUserGroupId();	
	var parsString='';
	
	// if user is not in any group
	if (userGroups.length==0){		
		var emptyScroller=blankScroller();		
		$("usergroupsbar").innerHTML=emptyScroller;
		runScroller();
		return 0;
	}	
	for(i=0; i<userGroups.length; i++){
		
		if(userGroups[i]!=undefined){
			if(i>0){
				parsString+='~';
			}
			parsString+=userGroups[i];
		}
		
	}	

	if(parsString.length>0){
		pars+='&data='+parsString;
		var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:finishRevolvingGroups});
	}
}

function finishRevolvingGroups(req)
{
		if(req.responseText!=0)
		{
			var output=req.responseText;
			
			var rootElement=output.split(',');
			var Article = new Array();
			var Articleid = new Array();
			var groupname="";
			var updates="";	
			for(i=0; i<rootElement.length; i++)
			{
				
				var childElement=rootElement[i].split('~');	
				if(childElement[0]!="" && childElement[1]!="")
				{
					
					groupid=childElement[0];
					groupname=childElement[1];
					
					Article[i] = new Array (groupname);
					Articleid[i] = new Array (groupid);
					
				}
			}	
			scroller=buildScroller(Article,Articleid);	
			$("usergroupsbar").innerHTML=scroller;
			runScroller();			
		}
		else // Added By Rupinder in order to hide scroller if user has't join any group
		{
			var emptyScroller=blankScroller();
			$("usergroupsbar").innerHTML=emptyScroller;
			runScroller();
		}
}
function validateReportPost(badwords,subid,postid,post_version_id)
{	

	var reportcomment = trim($('txaReportAbuseComment').value);
	var foundedbadwords="";
	if(isNull(reportcomment))
	{
		alert('Abuse description required');
		$('txaReportAbuseComment').focus();
		return false;
	}
	foundedbadwords+=matchBadWords(badwords,reportcomment,foundedbadwords);
	if(foundedbadwords.length>0){
		alert('The following text is not allowed.\n'+foundedbadwords);
		return false;
	}
	else{
		reportAbuseComment(subid,postid,post_version_id);
	}
}
function setReportAbuseWidth()
{
	if($('create_edit_post_alert'))
	{
		var windowWidth = getWindowWidth();
		$('reportImagesDiv').style.width = windowWidth-30+"px";
	}
}

function openReportAbuse(subid,postid,post_version_id)
{
	url = host+'/buzz/reportAbuseBox.php';
	pars= "subid="+subid+"&postid="+postid+"&post_version_id="+post_version_id;
	
	var myAjax4 = new Ajax.Request(url, 
						{method: 'post',
						parameters: pars,																
						onComplete: finishOpenReportAbuse
		               });	
}

function finishOpenReportAbuse(req){
	$('create_edit_post_overlay').style.height = (getWindowHeight() - 91)+"px";
	$('create_edit_post_overlay').show();
	$('create_edit_post').innerHTML = req.responseText;
	setReportAbuseWidth();
	Effect.SlideDown('create_edit_post_alert',{duration:0.3});
}

function reportAbuseComment(subid,postid,post_version_id){
	var url=host+"/buzz/_reportabuse.php";
	var pars="subid="+subid+"&postid="+postid+"&post_version_id="+post_version_id;
	var divid="reportabuse"+postid;
	var txtComment=document.getElementById('txaReportAbuseComment');
	pars+='&comment='+txtComment.value;
	
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onLoading:showBuzzProgress("Loading..."),onComplete:finishReportAbuse});

}
function finishReportAbuse(req){
	var status=req.responseText;
	if(status!=""){
		var arrayStatus=status.split(',');
		var divid="reportabuse"+arrayStatus[1];
		cancelPost();
		if(arrayStatus[0]==1){
			$(divid).innerHTML="Abuse Report sent.";
		}
		else if(arrayStatus[0]==2){
			$(divid).innerHTML="Report already sent.";
		}
		else{
			$(divid).innerHTML="Report sending failed.";
		}
		finishBuzzProgress();	
	}
}

function checkExistingUser(id){
	var url=host+"/buzz/_checkuser.php";
	var pars="userid="+id;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:finishCheckUsers});
}

function finishCheckUsers(req){
	var strText="";
	var strOutput=req.responseText.split(',');
	jumpToLatestPost();
	if(strOutput[1]==0)
	{
		// set height for the overlay div causing dark effect
		$('welcome_overlay').style.height = (getWindowHeight() - 91)+"px";
		$('welcome_overlay').show();
		new Effect.SlideDown("welcome_screen",{duration:0.3});
		// welcomeStatus(strOutput[2]);
		if(groupActive!=1 && showWelcomeScreen=="1"){
			displayWelcomeScreen();	
		}
	}	
}

function setPreferenceValues(){
	$('pref_alerts').value=$('pre_alert').title;
	$('pref_window_size').value=$('pre_windowsize').title;
	$('pref_text_size').value=$('pre_fontsize').title;
	$('pref_auto_jump').value=$('pre_jumppost').title;
	$('pref_posts_per_page').value=$('pre_posts').title;
	$('pref_characters').value=$('pre_critter').title;
	//alert("Alerts window "+$('pref_alerts').value+" Window size "+$('pref_window_size').value+"  Text Size "+$('pref_text_size').value+"  Jump to post :"+$('pref_auto_jump').value+" post per page "+$('pref_posts_per_page').value)
	submitPrefsForm();
}

function postView(id){
	new Effect.SlideUp("welcome_screen",{duration:0.3});
	$('welcome_overlay').hide();
}

function welcomeStatus(id){
	var url="_welcome_status.php";
	var pars="userid="+id;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:finishWelcomeStatus});
	
}

function finishWelcomeStatus(req){
	if(req.responseText>0){
		$("dropdownBar").style.display="";
		$("loadingMessageDiv").innerHTML="";
	}
}

function goforseachTagsKeywords(){
	searchword=$('search_keywords').value;
	var re = /^\s{1,}$/g; //match any white space including space, tab, form-feed, etc.
	if((searchword=='')||(searchword.length==0) || (searchword==null) || (searchword.search(re) > -1)){
		alert("Search field is blank")
		$('search_keywords').focus();
		return false;
		}
	//$("searchresultdiv").style.display="block";
	var url = '_tools.php';
	var pars = 'effecttype=divload&defultlink=1&tagsearch=';
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars,onComplete:setsearchresults});
}

function setsearchresults(req){
	
	$('searchresultdiv').innerHTML='';
	$('searchresultdiv').innerHTML = req.responseText;
	$('searchdiv').setStyle({
	height:"",
	display:"none"				
	});
	subSearchTabActive();
	goforsearch();
}

function goforsearch(tagserach,buzz_post,item_type,buzztype,anotherid){
	if(arguments.length==0){
		tagsearch=0;
		tdBuzz_search_tabSelected="ALL_CONTENT";
	}else if(arguments.length == 5){
		tagsearch=1;
		tdBuzz_search_tabSelected="PREMIUM_CONTENT";
	}
// step -1 first set all values to 0
	selectedtabresults['GROUP_CONTENT']=0;
	selectedtabresults['PREMIUM_CONTENT']=0;
	selectedtabresults['ALL_CONTENT']=0;
	paginationResults['pagination_PC']=0;
	paginationResults['pagination_GC']=0;
	paginationResults['pagination_AC']=0;

//  step -2  store the text searched
	searchedtext=searchword;

//  step -3  update the text searched
	if(tagsearch==0){
		selectedtabresults[tdBuzz_search_tabSelected]=1;
	}else if(tagsearch==1){
		selectedtabresults[buzz_post]=1;
	}

// step -4 CLEAN THE CONTENTS OF EVERY RESULT DIV
	$('GROUP_CONTENT').innerHTML='';
	$('PREMIUM_CONTENT').innerHTML='';
	$('ALL_CONTENT').innerHTML='';
	$('pagination_PC').innerHTML='';
	$('pagination_GC').innerHTML='';
	$('pagination_AC').innerHTML='';
// step -5 Make the AJAX REQUEST TO GET RECORDS		
	var url = '_tools.php';
	var rows_per_page = $('pref_posts_per_page').value;
	if(tagsearch==0){
		var pars = 'effecttype=search&defultlink=1&keywordsearch='+searchword+'&incontent='+tdBuzz_search_tabSelected+'&start=0&limit='+rows_per_page;
	}else{
		var pars = 'effecttype=searchTagRes&defultlink=1&tagsearch='+searchword+'&item_type='+item_type+'&incontent='+buzz_post+'&start=0&limit='+rows_per_page+'&buzztype='+buzztype+'&anotherid='+anotherid;
	}
	var myAjax4 = new Ajax.Request(url, {method: 'post', parameters: pars,
		onLoading:showBuzzProgress("Loading..."),							   
		onComplete:function finishSearchkeyword(req){
		$(tdBuzz_search_tabSelected).setStyle({
		height: searchheight,
		overflow:'auto'								
		});
		
		var searchContents=req.responseText.split("##");
		$(tdBuzz_search_tabSelected).innerHTML = searchContents[0];
		//alert("results")

		$(tdBuzz_search_tabSelected).show();

		if(searchContents[1]==""){
			$(tdBuzz_search_tabSelected).setStyle({
			height: 35+parseInt(searchheight)+"px"
			});
		}
		
		switch(tdBuzz_search_tabSelected){
			case 'PREMIUM_CONTENT': 
			{
				if(searchContents[1].length!=0){
					paginationResults['pagination_PC']=1;	
					$('pager').show();
					$('pagination_PC').innerHTML=searchContents[1];
					$('pagination_PC').show();
					$('pagination_GC').hide();
					$('pagination_AC').hide();		
				}else{
					$('pager').hide();
				}
				break;
			}
			case 'GROUP_CONTENT': 
			{
				if(searchContents[1].length!=0){
					paginationResults['pagination_GC']=1;				
					$('pager').show();
					$('pagination_GC').innerHTML=searchContents[1];
					$('pagination_GC').show();
					$('pagination_PC').hide();
					$('pagination_AC').hide();
				}else{
					$('pager').hide();
				}
				break;
			}
			case 'ALL_CONTENT': 
			{
				if(searchContents[1].length!=0){
					paginationResults['pagination_AC']=1;
					$('pager').show();
					$('pagination_AC').innerHTML=searchContents[1];
					//alert("pagination")
					$('pagination_PC').hide();
					$('pagination_GC').hide();
					$('pagination_AC').show();
				}else{
					$('pager').hide();
				}
				break;
			}
		}
		slidePanel();	
	}});
}

function slidePanel(){
	$('searchresultdiv').setStyle({
		display:"block"				
	});
	$('searchdiv').setStyle({
	height:"",	
	display:"block"
	});
	//new Effect.SlideDown("search_subtab",{duration:1.0});
	finishBuzzProgress();
}

function close_search_div(){
	tdBuzz_search_tabSelected='ALL_CONTENT';
	$('searchresultdiv').innerHTML='';
	$('searchresultdiv').hide();
}

function toggleTagSearch(defaultlink,tag,item_type,buzz_post,buzztype,anotherid){
	$('search_keywords').value=tag;
	searchword=$('search_keywords').value;
	var re = /^\s{1,}$/g; //match any white space including space, tab, form-feed, etc.
	if((searchword=='')||(searchword.length==0) || (searchword==null) || (searchword.search(re) > -1)){
		alert("Search field is blank")
		$('search_keywords').focus();
		return false;
	}

	var url = '_tools.php';
	var pars = 'effecttype=seacrhTag&defultlink='+defaultlink+'&tagsearch='+tag+'&item_type='+item_type+'&incontent='+buzz_post+'&buzztype='+buzztype+'&anotherid='+anotherid;
	var myAjax4 = new Ajax.Request(url, {method: 'post',
		parameters: pars,
		onComplete:function finishTagDivLoad(req){
		//refresh tabs
		$("tabtools").className="toolsOff";
		$("tabBuzz").className="buzzOn";
		if(groupActive=='1'){
		$("tabGroups").className="groupOff";
		}
		// Here Loading the default view
		$("searchresultdiv").style.display="block";
		$('searchresultdiv').innerHTML='';
		$('searchresultdiv').innerHTML = req.responseText;
		goforsearch(tag,buzz_post,item_type,buzztype,anotherid);
	}});
}

function redirecttoGropsTab(userid,group_id,iscommunity,jointype){
if(iscommunity==0){
	alert("You have to be a community member \n Please click on My Groups Tab")
	return false;
}else{
	// defined in groups.js
	enterIntoChatFromSearch(userid,group_id,jointype);
}
}

function showBuzzProgress (message) { // puts spinner in specified div
	if(!message)
	{
		message = 'Loading...';
	}
	var x = $('loadingMessageDiv');
	x.innerHTML = '<center><div class="statusmesg">'+message+'</div></center>';
	// this would be a good place to include a timeout function
}
function finishBuzzProgress () { // puts spinner in specified div
	var x = $('loadingMessageDiv');
	x.innerHTML = '';
	// this would be a good place to include a timeout function
}
function showBuzzFail(message)
{
	var x = $('loadingMessageDiv');
	x.innerHTML = '<center><div class="errormesg">'+message+'</div></center>';
}
/* For TD-Tools Filter */
function showhide(showdiv,hidediv)
{
	$(showdiv).show();
	$(hidediv).hide();
}
function submitFilterPrefForm()
{
	prefsObj.changed = 1; 
	prefsObj.reload = 1;
	
	var allids = $('contribarray').value;
	var teacherID = new Array();
	teacherID = allids.split(';');
	var length = (teacherID.length)-1; 
	var cidString = "";
	
	for(i=0;i<length;i++)
	{
		var originalValue = teacherID[i].split("="); // 92=1				
		var elementid = eval($("contrirad_"+originalValue[0]));
		var newValue = Form.getInputs('filterform','radio',elementid.id).find(function(radio) { return radio.checked; }).value;		
		if(newValue  == 0)
		{
			cidString +=originalValue[0]+":"; // 92 cid
		}				
	}
	var clientid = $('pref_clientid').value;
	var pars = 'sid=' + sid;
	pars += '&mode=filterAuthor';
	pars += '&clientid=' + clientid;
	pars += '&cidString=' + cidString;	
	
	var myAjax = new Ajax.Request('scripts/updatepref_submit.php', {method: 'post', parameters: pars,onLoading:showBuzzProgress('Loading...') , onComplete:finishSubmit});	
	
}
function cancelSubmit()
{
	/*
	prefsObj.changed = 0; 
	prefsObj.reload = 0;
	var allids = $('contribarray').value;
	var teacherID = new Array();
	var teacherOrgSH = new Array();
	teacherID = allids.split(';');
	var length = (teacherID.length)-1; 
	for(i=0;i<length;i++)
	{
		var originalValue = teacherID[i].split("="); // 92=1
		teacherOrgSH[originalValue[0]]=originalValue[1];
		// check the new value of this element
		var elementid = eval($("contrirad_"+originalValue[0]));
		var newValue = Form.getInputs('filterform','radio',elementid.id).find(function(radio){ return radio.checked; }).value;
		if(originalValue[1]!=newValue)
		{
			$(elementid.id).checked=originalValue[1];
		}
	}
	*/
	prefsObj.changed = 0;
	toggleBuzzTab();
}

function getUserSession(){
	var pars='type=checkSession';
	var myAjax = new Ajax.Request(host+'/buzz/login.php', {method: 'post', parameters: pars, onComplete:function(req){
			post = eval('('+req.responseText+')');
			if(post.state=='false'){
				window.location=host+'buzz/buzz.php';
			}
		}
	});
}
function hideGroupTab(){
	if(groupActive!=1){
	   $('tabGroups').style.display='none';	
	   $("tabGroups").className="groupOff";
	   activateBuzzTab();
    }
}

function activateBuzzTab(){
	toggleBuzzTab();
}


function subSearchTabActive(){
	$('allposts').style.display='none';	
	$('buzzposts').style.display='none';	
	$('decisiongrp').style.display='none';	
}

function displayWelcomeScreen(){
	corpname=corpname.substr(0, 1).toUpperCase() + corpname.substr(1);
	welcomemessage=welcomemessage.replace(/corpname/g,corpname);
	welcomemessage=welcomemessage.replace('userid',sid);
	$('welcome_screen').style.display='block';

	$('welcome_message').innerHTML=welcomemessage;
	if(acceptTC=='1'){
		acceptTc();
	}
}

function acceptTc(){
	var termcondition='<div class="registerinputbox"><input type=checkbox name="regterms" id="regterms" >I accept <a href="/buzz/user_agreement.html" target="_blank" style="color:#FFFFFF;cursor:pointer;text-decoration:underline;" >Terms & Conditions</a></div>';
	$('acceptdisclaimer').innerHTML=termcondition;
}

function closeWelcomeScreen(id){
	if(acceptTC=='1'){
		if($('regterms').checked==false){
			$('regerrmsg').innerHTML='Please accept Terms and Conditions.';
			$('regterms').focus();
			return false;
		}
		acceptDisclaimer();
	}
	var url="_welcome_status.php";
	var pars="userid="+id;
	var myAjax = new Ajax.Request(url, {method: 'post', parameters: pars, onComplete:finishWelcomeStatus});

	new Effect.SlideUp("welcome_screen",{duration:0.3});
	$('welcome_overlay').hide();
}

function showErrorScreen(){
	$('error_screen').style.display='block';
	$('error_message').style.height='425px';
}
