function createupload(theid, user){
	new AjaxUpload(theid, {
		action: './php/upload-handler.php',
		data: {
			username: user
		},
		onSubmit : function(file , ext){
			// Allow only images. You should add security check on the server-side.
			if (ext && /^(jpg|png|jpeg|gif)$/i.test(ext)){
				/* Setting data */
				//this.setData({
				//});					
				$.jGrowl('Uploading ' + file);
//				$('#'+theid+'text').text('Uploading ' + file);	
			} else {					
				// extension is not allowed
				$.jGrowl('Error: only images are allowed');
//				$('#'+theid+'text').text('Error: only images are allowed');
				// cancel upload
				return false;
			}		
		},
		onComplete : function(file,ext){

			if(ext == 'success'){
			$.jGrowl('Uploaded ' + file);
			var newfilename = file.replace(/^(.+)?(\..+$)/, readCookie('username')+'$2');
//			document.getElementById(theid+'text').innerHTML = '<center><img id="uploadedimage" height="100" class="profilepic"></center>';	
				$(".profilethumb").each(function(){
					$(this).attr('src','./pics/' + readCookie('username') + '_thumb.jpg?' + Date.parse(new Date().toString()));	
				});
			}else{
			$.jGrowl(file+' failed to upload.  May be a corrupt image');
			}
		}		
	});
}

function readCookie(nam) {
	var tC = document.cookie.split('; ');
	for (var i = tC.length - 1; i >= 0; i--) {
		var x = tC[i].split('=');
		if (nam == x[0]) return decodeURIComponent(x[1]);
	}
	return null;
}

function writeCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+encodeURIComponent(value) + expires;
}

function updatecookies(vartoreplace, newvalue){
	var re = new RegExp('(\\?|&)'+vartoreplace+'=.*?&&*|(\\?|&)'+vartoreplace+'=.*?$');
	var tC = document.cookie.split('; ');
	for (var i = tC.length - 1; i >= 0; i--) {
		var x = tC[i].split('=');
		if (x[0].match(/^c_/) && x[1].indexOf(vartoreplace) != -1) {
			var decodeURIComponentd = decodeURIComponent(x[1]);
			var contentidd = x[0].substring(2);
			decodeURIComponentd=decodeURIComponentd.replace(re,'&'+vartoreplace+'='+newvalue+'&');
			writeCookie(x[0], decodeURIComponentd);
			connector(decodeURIComponentd, contentidd, 'no');
		}
	}
//	//alert(document.cookie);
}

function eraseCookie(name) {
    writeCookie(name,"",-1);
}

function eraseCookies(){
	var tC = document.cookie.split('; ');
	for (var i = tC.length - 1; i >= 0; i--) {
		var x = tC[i].split('=');
		eraseCookie(x[0]);
	}
}

function cleanArray(someArray, filter) {
    var newArray = [];
    for(var index = 0; index < someArray.length; index++) {
        if(filter(someArray[index]) == false) {
            newArray.push(someArray[index]);
        }
    }
    return newArray;
}

function ShowPopup(hoveritem,text){
		var parent = hoveritem.parentNode;
		var hoverer = document.createElement('div');
		var id = parent.firstChild.id;
		hoverer.setAttribute('id', id+"P");
		hoverer.style.top = (pageY - 5)+"px";
		hoverer.style.left = (pageX + 10)+"px";
		hoverer.style.backgroundColor = 'black';
		hoverer.style.color = 'white';
		hoverer.style.position = 'absolute';
		hoverer.style.zIndex = '2000';
		hoverer.innerHTML = text;
		document.body.appendChild(hoverer);
}

function HidePopup(hoveritem){
var parent = hoveritem.parentNode;
var id = parent.firstChild.id;
document.body.removeChild(document.getElementById(id+'P'));
}

function isNullOrUndefined(item) {
    return (item == null || typeof(item) == "undefined");
}

function isBlank(item) {
    return (item == "");
}

function newline(){
return "\n";
}

function closeformwindow(){
	$('#formy').fadeOut(500);$('#formy2').fadeOut(500);setTimeout("document.getElementById('formpop').innerHTML = '&nbsp;';", 750);
}

function resetpage(){
	if(document.location.href.indexOf("?")){
		document.location = document.location.href.substring(0,document.location.href.indexOf("?"));
	}
	window.location.reload(true);
}

function refreshstuff(varb){
createformtabs(varb);
	if(document.getElementById('useroremail')){
		$('#useroremail, #pw').keypress(function(e) {
//		$('#useroremail, #pw').keypress(function(e) {
			if(e.keyCode == 13) {
				e.preventDefault();				
				alerts=[]; alerts.push(checkusrpw('', 'Username/Email and Password incorrect', 'pass', cleanuser(document.getElementById('useroremail').value), document.getElementById('pw').value)); if(alerts<1){ login(cleanuser(document.getElementById('useroremail').value),document.getElementById('pw').value);}else{alerts=cleanArray(alerts,isBlank);for(var i in alerts){$.jGrowl(alerts[i]);}; } 		
			}
		});
	}
refreshbuttons();
}

function refreshbuttons(variable){
	$(".buttonset").buttonset();
	$("button").button();
	$("button").click(function(){
			return false;
		});
	$('button.leftbutton').removeClass('ui-corner-all').addClass('ui-corner-left');
	if($('#uploadbutton').length){createupload('uploadbutton', readCookie('username'));}

}

function genform(addedstring, contentid, forms, seqortabs, language, username, pageforward, fadein, passvar){
//alert(passvar);
	url="./php/genform.php";
	urlstring="?forms="+forms+"&seqortabs="+seqortabs+"&language="+language+"&username="+username+"&contentid="+contentid+"&pageforward="+pageforward+"&fadein="+fadein+"&"+addedstring;
	if((seqortabs == 'seq' || seqortabs == 'perm' || seqortabs == 'onchange') || readCookie('iedetect') == 'yes'){
		connector(url+urlstring,contentid,'',refreshstuff);
		if(fadein != "no"){
			$('#formy2').fadeTo(500, .8);$('#formy').fadeIn(500);
		}else{
			$(contentid).show();
//			$(contentid).css( { opacity: 1}); 
		}
	}
	if(seqortabs == 'notice' && readCookie('iedetect') != 'yes'){
		$.jGrowl(connectorreturn(url+urlstring));
	}
	if(seqortabs == 'longnotice' && readCookie('iedetect') != 'yes'){
		$.jGrowl(connectorreturn(url+urlstring), { life: 20000 });
	}
	if(seqortabs == 'tabs'){
		connector(url+urlstring,contentid,'',refreshstuff, passvar);
		if(fadein != "no"){
			$('#formy2').fadeTo(500, .8);$('#formy').fadeIn(500);
		}else{
			$(contentid).show();
//			setOpacity(contentid, 1);
		}
	}

/* Sample 1
$.jGrowl("Hello world!");
// Sample 2
$.jGrowl("Stick this!", { sticky: true });
// Sample 3
$.jGrowl("A message with a header", { header: 'Important' });
// Sample 4
$.jGrowl("A message that will live a little longer.", { life: 10000 });
// Sample 5
$.jGrowl("A message with a beforeOpen callback and a different opening animation.", {
    beforeClose: function(e,m) {
        alert('About to close this notification!');
    },
    animateOpen: {
        height: 'show'
    }
}); 	
	}*/
//	setTimeout(refreshstuff, 2000);
}

function submitform(contorclose, alltables, sessionvar, contentid, forms, seqortabs, language, currentform, skip, tablename, updateinsert,username,check,pageforward,theform,fadeout){
	url="./php/genform.php";
	urlstring="?alltables="+alltables+"&sessionvar="+sessionvar+"&forms="+forms+"&seqortabs="+seqortabs+"&language="+language+"&skip="+skip+"&currentform="+currentform+"&tablename="+tablename+"&updateinsert="+updateinsert+"&username="+username+"&contentid="+contentid+"&pageforward="+pageforward;
	if(check){urlstring+="&check="+check;}
	if(theform){connectorpostreturn(url,create_request_string(theform));}
	if(seqortabs != "tabs"){
		if(contorclose == "close"){
			if(pageforward){
				if(pageforward.indexOf("PPP")){
					page=pageforward.split("PPP");
					genform('sessionvar='+sessionvar, 'formpop', page[0], page[1], readCookie('language'), readCookie('username'));
				}else{
					genform('sessionvar='+sessionvar, 'formpop', pageforward, 'seq', readCookie('language'), readCookie('username'), '', 'no');
				}
			}
				if(fadeout != "no"){
					closeformwindow();
				}
		}else{
			connector(url+urlstring,contentid, '', refreshstuff);
		}
//		setTimeout(refreshstuff, 2000);	
	}
}

function addslashes(str) {
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\0/g,'\\0');
	return str;
}


function isset(varname)  {
  if(typeof( window[ varname ] ) != "undefined") return true;
  else return false;
}

function autoToDoEdit(oldTaskObject, oldCommentsObject, entryid){
	var r = randomString();
	writeCookie(r+'temptaskvaluecook', oldTaskObject.innerHTML);
	writeCookie(r+'tempcommentsvaluecook', oldCommentsObject.value);
	window[r+"entryid"] = entryid;
	window[r+"newTaskObject"] = changeType(oldTaskObject, 'textarea');
	window[r+"newCommentsObject"] = changeType(oldCommentsObject, 'textarea');
		window[r+"checkmark"] = document.createElement('a');
		window[r+"checkmark"].setAttribute('id', 'checktodos'+window[r+"entryid"]);
		window[r+"checkmark"].setAttribute('class', 'lowerrightcheck');
		window[r+"checkmark"].innerHTML = "V";
		document.getElementById('commandtodos'+window[r+"entryid"]).replaceChild(window[r+"checkmark"], document.getElementById('commandtodos'+window[r+"entryid"]).firstChild);		
		
		$(document.getElementById('checktodos'+window[r+"entryid"])).click(function() {
		
			if(window[r+"newTaskObject"].value != readCookie(r+'temptaskvaluecook') || window[r+"newCommentsObject"].value != readCookie(r+'tempcommentsvaluecook')){
				window[r+"newvalue"] = connectorreturn('./php/updatevalue.php?tabletoupdate=todos&comments='+window[r+"newCommentsObject"].value+'&entryid='+window[r+"entryid"]+'&task='+window[r+"newTaskObject"].value+'&username='+readCookie('username'));
				if($.trim(window[r+"newvalue"]) == ""){
					window[r+"newbTask"] = changeType(window[r+"newTaskObject"], 'a');
					window[r+"newbComments"] = changeType(window[r+"newCommentsObject"], 'hidden');
				}else{
					window[r+"newbTask"] = changeType(window[r+"newTaskObject"], 'a', readCookie(r+'temptaskvaluecook'));
					window[r+"newbComments"] = changeType(window[r+"newCommentsObject"], 'hidden', readCookie(r+'tempcommentsvaluecook'));
				}
			}else{
				window[r+"newbTask"] = changeType(window[r+"newTaskObject"], 'a');
				window[r+"newbComments"] = changeType(window[r+"newCommentsObject"], 'hidden');
			}		
			eraseCookie(r+'temptaskvaluecook');
			eraseCookie(r+'tempcommentsvaluecook');
				
				
			window[r+"newcheckmark"] = document.createElement('a');
			window[r+"newcheckmark"].setAttribute('id','completetodo');
			window[r+"newcheckmark"].innerHTML = "X";
			document.getElementById('commandtodos'+window[r+"entryid"]).replaceChild(window[r+"newcheckmark"], document.getElementById('commandtodos'+window[r+"entryid"]).firstChild);
			$(window[r+"newcheckmark"]).click(function() {
				if($.trim(connectorreturn('./php/completetodo.php?id='+window[r+'entryid']+'&username='+readCookie('username'))) == 'success')
					{document.getElementById('todorow'+window[r+'entryid']).parentNode.removeChild(document.getElementById('todorow'+window[r+'entryid']));}
			});
			
			if(window[r+"newCommentsObject"].value != ''){
					$(window[r+"newbTask"]).click(function() {
						HidePopup(window[r+"newbTask"]);
						autoToDoEdit(window[r+"newbTask"], window[r+"newbComments"], window[r+"entryid"]);			
					});
			}else{
					$(window[r+"newbTask"]).click(function() {
						autoToDoEdit(window[r+"newbTask"], window[r+"newbComments"], window[r+"entryid"]);			
					});
			}

			if(window[r+"newCommentsObject"].value != ''){
				$(window[r+"newbTask"]).mouseover(function() {
					ShowPopup(window[r+"newbTask"], window[r+"newCommentsObject"].value);
				});
				$(window[r+"newbTask"]).mouseout(function() {
					HidePopup(window[r+"newbTask"]);
				});
			}
		});	
}

function changeType(oldObject, oType, newvalue) {
  if(oType=='a' || oType=='textarea'){
	if(oType=='a')var newObject = document.createElement('a');
	if(oType=='textarea'){
		var newObject = document.createElement('textarea');
		newObject.style.width = parseInt($(oldObject.parentNode).css('width')) - 25;
	}
}else{
	var newObject = document.createElement('input');
	newObject.type = oType;
	if(oldObject.size) newObject.size = oldObject.size;
	if(oldObject.name) newObject.name = oldObject.name;
 }
    if((oType=='text' || oType=='textarea') && (oldObject.tagName == "a" || oldObject.tagName == "A")){
		newObject.value = oldObject.innerHTML;
	}
    if((oType=='text' || oType=='textarea') && oldObject.type == "hidden"){
		newObject.value = oldObject.value;
	}

	if(oType=='a'){
		if(isset(newvalue)){
			newObject.innerHTML=newvalue;
		}else{
			newObject.innerHTML = oldObject.value;
		}
	}
	if(oType=='hidden'){
		if(isset(newvalue)){
			newObject.value=newvalue;
		}else{
			newObject.value = oldObject.value;
		}
	}
  if(oldObject.id) newObject.id = oldObject.id;
  if(oldObject.className) newObject.className = oldObject.className;
  oldObject.parentNode.replaceChild(newObject,oldObject);
  return newObject;
}

function settoexpnd(){
	$('#chanexpander').unbind('click');
	$('#chanexpander').click(function() {
		$("#ifrm").css({ width: "77%" });
		$("#chanselector").animate({ width: "20%"},500,function(){
			$("#chanslctcontent").fadeIn(200);
			document.getElementById('chanexpander').innerHTML = "<<";
			settocllps();
		});
	});
}

function settocllps(){
	$('#chanexpander').unbind('click');
	$('#chanexpander').click(function() {
		$("#chanslctcontent").fadeOut(200, function(){
			$("#chanselector").animate({ width: "2%" }, 500, function(){
			$("#ifrm").css({ width: "95%" });
				document.getElementById('chanexpander').innerHTML = ">>";
				settoexpnd();	
			});
			
		});
	});
}

function jopenchat(){
//	if(readCookie('channelstring') != ''){
//		document.getElementById('ifrm').src = "http://dev.thenext.us:9090/?nick="+readCookie('username')+"&channels="+readCookie('channelstring')+"&password="+decode64(readCookie('password'));
//		writeCookie('channelstring', '');
//	}
	$("#outsider").css( { width: "95%"});
	$("#outsider").css( { left: "2.5%"});
	$("#ifrmholder").animate({opacity:1},{duration: 1000});
	$("#ifrmholder").animate( { height: "200px" }, {duration: 1000, queue: "widein", complete: function(){
			$("#ifrm").css( { display: "block"});	
			$("#chanselector").css( { display: "block"});
			$("#chanselector").animate({opacity:1},{duration: 300});
			settoexpnd();
		}
	});
	$("#ifrm").animate({opacity:1},{duration: 300, queue: "widein", complete: function () {
		$('#outsider').mouseout(function(e) { 
			if(!e) var e = window.event; 
			var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement; 
			while (reltg.tagName != 'BODY'){ 
				if (reltg.id == "outsider"){return;} 
				reltg = reltg.parentNode; 
			}
			$('#outsider').fadeTo( 300,.8 );	
		});

		$('#outsider').mouseover(function(e){ 
			if(!e) var e = window.event; 
			var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement; 
			while (reltg.tagName != 'BODY'){ 
				if (reltg.id == "outsider"){return;} 
				reltg = reltg.parentNode; 
			} 
			$('#outsider').fadeTo( 300,1 );	
		});
		
	}});
	$('#chatbutton').button('option', 'label', 'vvCHATvv');
	$('#chatbutton').unbind('click');
	$('#chatbutton').click(function() {
		jclosechat();
	});
}

function jclosechat(){
	$('#outsider').unbind('mouseover');
	$('#outsider').unbind('mouseout');
	$('#outsider').css( { opacity: 1} );

	$("#chanselector").animate({opacity:0},{duration: 300, complete: function(){
			$("#chanselector").css( { display: "none"});
	}});

	$("#ifrm").animate({opacity:0},{duration: 300, queue: "u", complete: function() {
			$("#ifrm").css( { display: "none"});
			$("#ifrmholder").animate({opacity: 0},{duration: 1000, queue: "r"});
			$("#ifrmholder").animate( { height: "0px" }, {duration: 1000, queue: "u", complete: function() {
					$("#outsider").css( { width: "10%"});
					$("#outsider").css( { left: "45%"});
				}
			});
		}
	});
	$('#chatbutton').button('option', 'label', '^^CHAT^^');
	$('#chatbutton').unbind('click');
	$('#chatbutton').click(function() {
		jopenchat();
	});
}

function checkformat(checkid, valuer, legalchar, alerts){
	var legalChars = legalchar;
	if (legalChars.test(document.getElementById(checkid).value)) {
		return '';
    }else{
		return valuer+": "+alerts+"\n";
	}
}

function userclean(valuer){
return valuer.replace(/_/, ' ');
}
function cleanuser(valuer){
 return valuer.replace(/\s+/, '_');
}

function refreshchat(){
	document.getElementById('ifrm').setAttribute("src", "");
		document.getElementById('ifrm').setAttribute("src", "http://dev.thenext.us:9090/?nick="+readCookie('username')+"&channels="+readCookie('channelstring')+"&password="+readCookie('password'));
}

function checkImages(){
	if(document.body.clientWidth < 800){
//		$('#bottomleft', '#bottomright').fadeOut("fast");
		$('#bottomleft').fadeOut("fast");
		$('#bottomright').fadeOut("fast");
//		$('#bottomleft').fadeOut("fast");
//		$('#bottomright').fadeOut("fast");
	}
	if(document.body.clientWidth > 800){
//		$('#bottomleft', '#bottomright').fadeIn("fast");
		$('#bottomleft').fadeIn("fast");
		$('#bottomright').fadeIn("fast");
//		$('#topleft').fadeIn("fast");
//		$('#topright').fadeIn("fast");
	}
//	alert(w_width);
}

function setMax(){
/*		$('.contents').css("max-height", (document.body.clientHeight*.7)+"px");
			if(document.body.clientHeight>500){
				$('#dockContainer').css( "margin-top", ((document.body.clientHeight/2)-300)+"px");
				$('#dockContainer').css( "position", "fixed");
//				$('#dockContainer').css( "min-height", (580-((document.body.clientHeight/2)-300))+"px");
			}else{
//				$('#dockContainer').css( "min-height", "580px");
				$('#dockContainer').css( "margin-top", "0px");		
				$('#dockContainer').css( "position", "absolute");
			}

			if(document.body.clientWidth>1100){
				$('#main').removeClass('mainspec').addClass('mainauto');			
			}else{
				$('#main').removeClass('mainauto').addClass('mainspec');
			}
			
//		$('.contents').css("width", (w_height*.7)+"px");
*/
if($('#main').width()>document.body.clientWidth){
	var bilbo = (($('#main').width()/2)-245);
}else{
	var bilbo = (($('#main').width()/2)-245)+((document.body.clientWidth-$('#main').width())/2);
}
	$('#dockContainer').css( "margin-left", bilbo);
	var blah = document.getElementById('BIGTABIMAGE').parentNode;	
	$(blah).css('min-width', '111px');
}

function getIndexForId( tabsDivId, searchedId )
{
var index = -1;
var i = 0, els = $("#" + tabsDivId).find("a");
var l = els.length, e;

while ( i < l && index == -1 )
{
e = els[i];

if ( "#" + searchedId == $(e).attr('href') )
{
index = i;
}
i++;
};

return index;
}

function closemaintab(tab){
	$("#"+tab).click( function(e){
		e.preventDefault();
	});
	$("#main").tabs('remove', (getIndexForId("main", tab)) );
}

function todolist(){
	if($('#todotab')[0]){
		$('#main').tabs( 'select' , (getIndexForId( 'main', 'todotab')) );			
	}else{
		$('#main').tabs( 'add' , '#todotab' , '<span id=\"closetodotab\" class=\"ui-icon ui-icon-close\" style=\"float:right; clear:none;color:white;\"></span><img class=\"profilethumb\" height=\"25\" src=\"pics/'+readCookie('username')+'_thumb.jpg?'+Date.parse(new Date().toString())+'\">Tasks' );

		var listcontainer = document.createElement('div');
		listcontainer.setAttribute('id', "todoitself");
		$('#todotab').append(listcontainer);
		$('#todoitself').addClass("ui-datepicker-inline ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all");

		//create todo list
		writeCookie('activetodotab', 'Personal');
		connector('./php/todolist.php?username='+readCookie('username')+'&groupstring='+readCookie('groupstring'),'todoitself','',createtodotabs,0);
		//get mouse cursor position for todo comments
		$('#todoitself').mousemove(function(e){
			pageX = e.pageX; //- gives you X position
			pageY = e.pageY; //- gives you Y position
		});
	}
}

function login(useroremail,password){
	writeCookie('username', checkusrpw('no', '', '', useroremail));
	if(readCookie('username') != ''){writeCookie('loggedin', 'yes');}
	if(readCookie('loggedin')=='yes'){

		//get cookies of userprefs, etc
		var cooks = checkusrpw('yes','','pass',useroremail, password);
		first = cooks.split('&');
		for (var i = first.length - 1; i >= 0; i--) {
			var x = first[i].split('=');
			writeCookie(x[0], decodeURIComponent(x[1]));
		}

		//clean up page
		document.getElementById('topleft').parentNode.removeChild(document.getElementById('topleft'));
		document.getElementById('bottomleft').parentNode.removeChild(document.getElementById('bottomleft'));
		document.getElementById('bottomright').parentNode.removeChild(document.getElementById('bottomright'));
		$('#splash').css( 'background-image', 'none');
		$('#splash').hide();
		
		$('#loginbox').hide();
		/*
		//change loginbox into loggedin righthand widget
		genform('', 'loginboxform', 'loggedinform', 'perm', readCookie('language'), readCookie('username'), '', 'no');

		//create todo list
		writeCookie('activetodotab', 'Personal');
		connector('./php/todolist.php?username='+readCookie('username')+'&groupstring='+readCookie('groupstring'),'todoitself','',createtodotabs,0);
		$("#todo").show();
*/
		//create calendar
//		$('#datepicker').datepicker({
//			inline: true
//		});
		
		//create main content tabs
		var $tabs = $('#main').tabs({
			add: function(event, ui) {
				$tabs.tabs('select', '#' + ui.panel.id);
				$(ui.tab).addClass('tab');
				$('.ui-icon-close', ui.tab).click(function(e){e.preventDefault();closemaintab(ui.panel.id);});
			}
		});
		$('#main').show();

		//create dock
		 var opts = { align: 'top', size:50, distance: 75, coefficient :1.5, labels: 'bc', duration: 300, source: false };
		 $('#jqDock').jqDock(opts);
		$('#dockContainer').show();

		//create profile image
		$('#BIGPROFILEIMAGE').attr('src', './pics/'+readCookie('username')+'_thumb.jpg?' + Date.parse(new Date().toString()));		
		//greetings
		$('#SPECIAL').append('Welcome, '+readCookie('username')+'!');

		$('#DONATEBUTTON').click(function(){
	        window.open( 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=DJVFGTH6K6AZC' );
			refreshbuttons();
			return false;	
		});

		$('#BIGPROFILEBUTTON').click(function(){
			openuser(readCookie('username'));
		});
		
		$('#EDITPROFILEBUTTON').click(function(){
			if($('#EDIT'+readCookie('username'))[0]){
//				$('#main').tabs( 'select' , (getIndexForId( 'VIEW'+readCookie('username'), 'main' )) );			
				$('#main').tabs( 'select' , (getIndexForId( 'main', 'EDIT'+readCookie('username'))) );			
			}else{

				$('#main').tabs( 'add' , '#EDIT'+readCookie('username') , '<span class=\"ui-icon ui-icon-close\" style=\"float:right; clear:none;color:white;\"></span><img class=\"profilethumb\" height=\"25\" src=\"pics/'+readCookie('username')+'_thumb.jpg?' + Date.parse(new Date().toString())+'\">'+readCookie('username') );
				genform('', 'EDIT'+readCookie('username'), 'basics,yourvision,personalsettings', 'tabs', readCookie('language'), readCookie('username'), '', 'no');
				//$('#main').tabs( 'select' , ($('#main').tabs('length')-1) );
			}
			refreshbuttons();
			return false;
		});
		
		//bind slide event
//		$('#BIGTABBUTTON').unbind('mouseenter');
		$('#BIGTABBUTTON').mouseenter(function(){
				if($('#MAINBUTTONS').css("display") == 'none'){
						if($('#MAINPROFILEBUTTONS').css("display") != 'none'){		
							$('#MAINPROFILEBUTTONS').hide("slide", {direction: "right" }, 150, function(){
								$('#BIGTABBUTTON').removeClass('ui-corner-all').addClass('ui-corner-left ui-corner-tr');						
								$('#BIGPROFILEBUTTON').removeClass('ui-corner-right ui-corner-tl').addClass('ui-corner-all');
								$('#MAINBUTTONS').show("slide", { direction: "left" }, 500);
							});
						}else{
							$('#BIGTABBUTTON').removeClass('ui-corner-all').addClass('ui-corner-left ui-corner-tr');						
							$('#BIGPROFILEBUTTON').removeClass('ui-corner-right ui-corner-tl').addClass('ui-corner-all');
							$('#MAINBUTTONS').delay(150).show("slide", { direction: "left" }, 500);
						}
				}
				$('#BIGTABIMAGE').removeClass('spin');
		});
				
		//bind slide event
//		$('#BIGPROFILEBUTTON').unbind('mouseenter');
		$('#BIGPROFILEBUTTON').mouseenter(function(){
				if($('#MAINPROFILEBUTTONS').css("display") == 'none'){		
						if($('#MAINBUTTONS').css("display") != 'none'){
							$('#MAINBUTTONS').hide("slide", {direction: "left" }, 150, function(){
								$('#BIGPROFILEBUTTON').removeClass('ui-corner-all').addClass('ui-corner-right ui-corner-tl');				
								$('#BIGTABBUTTON').removeClass('ui-corner-left ui-corner-tr').addClass('ui-corner-all');
								$('#MAINPROFILEBUTTONS').show("slide", { direction: "right" }, 500);							
							});
						}else{
							$('#BIGPROFILEBUTTON').removeClass('ui-corner-all').addClass('ui-corner-right ui-corner-tl');				
							$('#BIGTABBUTTON').removeClass('ui-corner-left ui-corner-tr').addClass('ui-corner-all');
							$('#MAINPROFILEBUTTONS').delay(150).show("slide", { direction: "right" }, 500);
						}
				}
		});


		$('#BIGTABLABEL').mouseleave( function(){
			if($('#MAINBUTTONS').css("display") == 'block'){
				$('#MAINBUTTONS').hide("slide", { direction: "left" }, 150, function(){
					$('#BIGTABBUTTON').removeClass('ui-corner-left ui-corner-tr').addClass('ui-corner-all');
				});
			}
			if($('#MAINPROFILEBUTTONS').css("display") == 'block'){
				$('#MAINPROFILEBUTTONS').hide("slide", { direction: "right" }, 150, function(){
					$('#BIGPROFILEBUTTON').removeClass('ui-corner-right ui-corner-tl').addClass('ui-corner-all');				
				});
			}			
			$('#BIGTABIMAGE').addClass('spin');
		});
				
		//create chat button, preload iframe		
		var newlink = document.createElement('button');
		newlink.setAttribute('id', 'chatbutton');
		newlink.innerHTML = "^^CHAT^^";
		document.getElementById('wannachat').appendChild(newlink);		
		$('#chatbutton').click(function() {jopenchat();});
		var ifrm = document.createElement('iframe');
		ifrm.setAttribute("id", "ifrm");
		ifrm.setAttribute("frameborder", 0);
		ifrm.setAttribute("src", "http://dev.thenext.us:9090/?nick="+readCookie('username')+"&channels="+readCookie('channelstring')+"&password="+readCookie('password'));
		ifrmholder.appendChild(ifrm);

		//check if user has a profile or not yet
		if(readCookie('userprofiles') == ''){
			genform('', 'formpop', 'basics,yourvision,personalsettings', 'seq', readCookie('language'), readCookie('username'), 'thankyoumainPPPlongnotice', ''); 	
		}else{
		//if does, then pop notice saying WELCOME
			addedstring='dateaccessed='+readCookie('dateaccessed')+'&amp;datecreated='+readCookie('datecreated');
			genform(addedstring, 'formpop', 'loggedin', 'notice', readCookie('language'), readCookie('username'), '', ''); 	
		}		

		$('#MAINHEADER').removeClass('ui-corner-all');

		section('Heart of the Matter');
	}
}

function openuser(username){
	if($('#VIEW'+username)[0]){
		$('#main').tabs( 'select' , (getIndexForId( 'main', 'VIEW'+username)));
	}else{
		$('#main').tabs( 'add' , '#VIEW'+username , '<span class=\"ui-icon ui-icon-close\" style=\"float:right; clear:none;color:white;\"></span><img class=\"profilethumb\" height=\"25\" src=\"pics/'+username+'_thumb.jpg?' + Date.parse(new Date().toString())+'\">'+username );
		genform('page='+username, 'VIEW'+username, 'profilebasics,yourvision', 'tabs', readCookie('language'), readCookie('username'), '', 'no', username);
	}
}

function section(thesection){
	switch (thesection){
		case "The Nexchange":
			var imgsrc = "img/cells/nexchange.png";
			var contentsrc = "./php/nexchange.php?username="+readCookie('username')+"&language="+readCookie('language');
		break;
		
		case "The Incubator":
			var imgsrc = "img/cells/inucubator.png";
			var contentsrc = "./php/incubator.php?username="+readCookie('username')+"&language="+readCookie('language');
		break;
		
		case "Forum":
			var imgsrc = "img/cells/forum.png";
			var contentsrc = "./php/forum.php?username="+readCookie('username')+"&language="+readCookie('language');
		break;
		
		case "Global Eyes":
			var imgsrc = "img/cells/earth.png";
			var contentsrc = "./php/globaleyes.php?username="+readCookie('username')+"&language="+readCookie('language');
		break;
		
		case "Heart of the Matter":
			var imgsrc = "img/cells/dashboard%20icon.png";
			var contentsrc = "./php/heartofthematter.php?username="+readCookie('username')+"&language="+readCookie('language');
		break;
		
		case "The Academy":
			var imgsrc = "img/cells/academy.png";
			var contentsrc = "./php/academy.php?username="+readCookie('username')+"&language="+readCookie('language');
		break;
		
		case "Community Central":
			var imgsrc = "img/cells/communities.png";
			var contentsrc = "./php/communities.php?username="+readCookie('username')+"&language="+readCookie('language');
		break;
	}
	
	if(typeof(imgsrc) == 'undefined'){
		return;
	}	

	$('#BIGTABIMAGE, #MAINTABIMAGE').attr('src',imgsrc);
	$('#BIGTABBUTTON').unbind('click').click(function(){
		section(thesection);
	});
	
	if(readCookie('language') != 'English'){
//		thesection = translate(thesection, readCookie('language'));
	}
	$('#theaction').html(thesection);
	connector(contentsrc, 'ACTIONTAB', '', refreshbuttons);
	$('#main').tabs( 'select' , 0 );
}


function createtodotabs(selection){
	$("#todolist").tabs({ 
		  type:"top",
		  navigationClass:"header",
		  contentsClass:"contents",
		  activeClass:"active",
		  closable:false,
		  selected: selection
  });

$('#todolist').bind('tabsselect', function(event, ui) {

    // Objects available in the function context:
 //   ui.tab     // anchor element of the selected (clicked) tab
   // ui.panel   // element, that contains the selected/clicked tab contents
    //ui.index   // zero-based index of the selected (clicked) tab
		writeCookie('activetodotab', document.getElementById('thetodoindex'+ui.index).innerHTML);
//		alert(document.getElementById('thetodoindex'+ui.index).innerHTML);
		  connector('./php/todolist.php?username='+readCookie('username')+'&groupstring='+readCookie('groupstring')+'&active='+document.getElementById('thetodoindex'+ui.index).innerHTML,'todoitself','',createtodotabs,ui.index);

});
		$('.tabtop').each(function(){
			$(this).removeClass('ui-corner-all').addClass('ui-corner-top');
		});	  
}

function createformtabs(page){
	var r = randomString();
 page = typeof(page) != 'undefined' ? page : '';	
if(page != 'heart' && page != ''){
	$('#'+page+'tabularform').tabs({ 
		  type:"top",
		  navigationClass:"header",
		  contentsClass:"contents",
		  activeClass:"active",
		  closable:false
	}); 
	$('#'+page+'tabularform').bind('tabsselect', function(event, ui) {
		// Objects available in the function context:
	 //   ui.tab     // anchor element of the selected (clicked) tab
	   // ui.panel   // element, that contains the selected/clicked tab contents
		//ui.index   // zero-based index of the selected (clicked) tab
	
			writeCookie(page+'activeformtab', document.getElementById(page+'theformindex'+ui.index).innerHTML);
			window['pelement'+r] = document.getElementById('p'+page+rmstar(document.getElementById(page+'theformindex'+ui.index).innerHTML)).id;
				if(document.getElementById(window['pelement'+r]).innerHTML == ''){
					connector('./php/genform.php?page='+page+'&type=section&index='+ui.index+'&active='+rmstar(document.getElementById(page+'theformindex'+ui.index).innerHTML)+'&forms='+document.getElementById('theforms').innerHTML+'&seqortabs=tabs&language='+readCookie('language')+'&username='+readCookie('username'), window['pelement'+r], '', refreshbuttons);
				}
	});		
		}else{  
	$('.tabularform').tabs({ 
		  type:"top",
		  navigationClass:"header",
		  contentsClass:"contents",
		  activeClass:"active",
		  closable:false
	});
	$('.tabularform').bind('tabsselect', function(event, ui) {
		// Objects available in the function context:
	 //   ui.tab     // anchor element of the selected (clicked) tab
	   // ui.panel   // element, that contains the selected/clicked tab contents
		//ui.index   // zero-based index of the selected (clicked) tab
			writeCookie('activeformtab', rmstar(document.getElementById('theformindex'+ui.index).innerHTML));
			window['pelement'+r] = document.getElementById('p'+rmstar(document.getElementById('theformindex'+ui.index).innerHTML)).id;
				if(document.getElementById(window['pelement'+r]).innerHTML == ''){
					connector('./php/genform.php?page='+page+'&type=section&index='+ui.index+'&active='+rmstar(document.getElementById('theformindex'+ui.index).innerHTML)+'&forms='+document.getElementById('theforms').innerHTML+'&seqortabs=tabs&language='+readCookie('language')+'&username='+readCookie('username'), window['pelement'+r], '', refreshbuttons);
				}
		
//				if(document.getElementById('uploadbutton')){createupload('uploadbutton', readCookie('username'));}	
	});		
		}

//		if(document.getElementById('uploadbutton')){createupload('uploadbutton', readCookie('username'));}
		setMax();
}

function rmstar(text){
 return text.replace(/\*/, '');
}

function checkusrpw(login, alerts, userorpass, useroremail, password){
	urlstring = '?useroremail='+useroremail;
	if(userorpass=="pass"){
		urlstring += '&userorpass=pass&password='+password;
	}
	if(login){
		urlstring += '&login='+login;
	}
	returned = connectorreturn('./php/checkusrpw.php'+urlstring);
	returned = $.trim(returned);

	if(returned.match(/^no$/)=='no'){
		return alerts;
	}
	if(returned.match(/^yes$/)=='yes'){
		return '';
	}
	return returned;
}

function checkduplicate(checkid, valuer, alerts, tabletocheck, sessionvar, username, byuser){
returned = connectorreturn('./php/checkdup.php?checkid='+checkid+'&value='+valuer+'&tabletocheck='+tabletocheck+'&sessionvar='+sessionvar+'&username='+username+'&byuser='+byuser);
		if(returned.match(/yes/)=='yes'){
			return alerts;
		}else{
			return '';
		}
}

function connector(urlstring, contentid, cookierefresh, callback,callbackvariable){
//alert(urlstring); 
		var r = randomString();
		setTimeout('if(!window["blow'+r+'"]){document.getElementById(\''+contentid+'\').innerHTML="<span style=\'position:relative;top:45%\' <center><img src=\'img/loading.gif\'></center>";}', 500);
		window[contentid+r] = contentid;
		window["xmlhttp"+r]=GetXmlHttpObject();
		window["xmlhttp"+r].onreadystatechange=function(){
			if (window["xmlhttp"+r].readyState==4 && window[contentid+r]){
				window["blow"+r]='yes';
				var target = document.getElementById(window[contentid+r]);
				while (target.hasChildNodes()) target.removeChild(target.lastChild);
				var temp = document.createElement('div');
				if(cookierefresh=='yes')writeCookie('c_'+window[contentid+r], urlstring);
//					target.innerHTML=window["xmlhttp"+r].responseText;
				temp.innerHTML=window["xmlhttp"+r].responseText;
				temp.setAttribute('style', 'height:inherit;');
				target.appendChild(temp);
				if(callback){callback(callbackvariable);}
			}
		}
		window["xmlhttp"+r].open("GET",urlstring+'&'+Math.floor(Math.random()*10001)+'=!_RANDOM_!',true);
		window["xmlhttp"+r].send(null);
	}

function connectorreturn(urlstring){
		var r = randomString();
		window["xmlhttp"+r]=GetXmlHttpObject();
		window["xmlhttp"+r].onreadystatechange=function(){
			if (window["xmlhttp"+r].readyState==4){
			}
		}
		window["xmlhttp"+r].open("GET",urlstring+'&'+Math.floor(Math.random()*10001)+'=!_RANDOM_!',false);
		window["xmlhttp"+r].send(null);
		return window["xmlhttp"+r].responseText;
}

function connectorpost(url, params){
//alert(url+params);
	var r = randomString();
	window["xmlhttp"+r]=GetXmlHttpObject();
	window["xmlhttp"+r].open("POST",url,true);
	window["xmlhttp"+r].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	window["xmlhttp"+r].setRequestHeader("Content-length", params.length);
	window["xmlhttp"+r].setRequestHeader("Connection", "close");
	window["xmlhttp"+r].send(params);
}

function connectorpostreturn(url, params){
//alert(url+params);
	var r = randomString();
	window["xmlhttp"+r]=GetXmlHttpObject();
	window["xmlhttp"+r].open("POST",url,false);
	window["xmlhttp"+r].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	window["xmlhttp"+r].setRequestHeader("Content-length", params.length);
	window["xmlhttp"+r].setRequestHeader("Connection", "close");
	window["xmlhttp"+r].send(params);
}

function GetXmlHttpObject(){
	if (window.XMLHttpRequest){
	  // code for IE7+, Firefox, Chrome, Opera, Safari
	  return new XMLHttpRequest();
	}

	if (window.ActiveXObject){
	  // code for IE6, IE5
	  return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return null;
}


function create_request_string(theForm) 
{ var thereturn = $(theForm).serialize();
return thereturn;
} 

function randomString() {
	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function genfilters(searchtype, contendid){
  contentid = typeof(contentid) != 'undefined' ? contentid : 'searchfilters';
//  $('#ACTIONTAB').html('');
  $('#ACTIONTAB').html("<div id='searchfilters'></div><div id='searchresults'></div>");
  connector('./php/filters.php?searchtype='+searchtype, contentid, 'no', genfilters2);  
}

function genfilters2(){
	$(".buttonset").buttonset();
  //foreach child of searchfilterbuttons, use id to affect mouseenter/mouseleave to show() or hide() options__[id]
			$("#searchfilters").mouseleave(function(){
				$("#searchfilterbuttons").children().each(function(){
					if(this.tagName != "INPUT"){
						$("#option"+this.id).hide();
					}
				});
			});
	$("#searchfilterbuttons").children().each(function(){
		if(this.tagName != "INPUT"){
			$(this).mouseenter(function(){
				$("#searchfilterbuttons").children().each(function(){
					if(this.tagName != "INPUT"){
						$("#option"+this.id).hide();
					}
				});
				$("#option"+this.id).show();
			});
			$("#option"+this.id).mouseleave(function(){
				var blah = this.id;
				$("#"+blah.substring(6)).removeClass('ui-state-hover');
				$(this).hide();
			});
			$("#option"+this.id).mouseenter(function(){
				var blah = this.id;
				$("#"+blah.substring(6)).addClass('ui-state-hover');
				$(this).show();
			});
			$(this).click(function(){
				var blah = this.id;
				if ($("#"+blah.substring(3)).attr('checked')){
					$("#searchfilterbuttons").children().each(function(){
						if(this.tagName != "INPUT"){
							$("#option"+this.id).hide();
							$(this).removeClass('ui-state-hover');
						}
					});
				}else{
						if(this.tagName != "INPUT"){
							$("#option"+this.id).show();
							$(this).addClass('ui-state-hover');
						}
				}
			});
		}
	});
}

function updatefilterquery(searchtype){
	var newcookie="";
	$("input", "#searchfilterbuttons").each(function(){
//		if(this.tagName == "INPUT"){
			if($(this).attr('checked')){
				$(".searchinputs_"+this.id).each(function(){
					if(this.value){
						newcookie += "&"+this.id+'='+this.value;
					}
				});
				$("span img", this.nextSibling).attr('src', './img/led_on.png');
			}else{
				$("span img", this.nextSibling).attr('src', './img/led_off.png');
			}
//		}
	});
	connector('./php/search.php?searchtype='+searchtype+newcookie, 'searchresults');
}

