// misc_util.js

var date_Days = new Array();
date_Days[0] = "Sunday";
date_Days[1] = "Monday";
date_Days[2] = "Tuesday";
date_Days[3] = "Wednesday";
date_Days[4] = "Thursday";
date_Days[5] = "Friday";
date_Days[6] = "Saturday";

var date_Months = new Array();
date_Months[0] = "January";
date_Months[1] = "February";
date_Months[2] = "March";
date_Months[3] = "April";
date_Months[4] = "May";
date_Months[5] = "June";
date_Months[6] = "July";
date_Months[7] = "August";
date_Months[8] = "September";
date_Months[9] = "October";
date_Months[10] = "November";
date_Months[11] = "December";

function GetRand(min,max)
	{
	return min + Math.floor(Math.random()* ((max-min)+1));
	}

function addCommas(numStr)
	{
	numStr += '';
	x = numStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
	}
//------------------------------------------------
function RandColor()
	{
	return '#'+Math.floor(Math.random()*16777215).toString(16);
	}

//------------------------------------------------
function getMemoryStr(num)
	{
	if (num < 1000) // bytes
	{
		return num + " bytes";
	}
	else {
		num = Math.round(num / 1000); // kb
		if (num < 1000) {
			return num + " kb";
		}
		else {
			num = Math.round(num / 10) / 100; // mb
			if (num < 1000) 
				{
				return num + " mb";
				}
			else 
				{
				num = Math.round(num / 10) / 100; // gb
				return addCommas(num);
				}
			}
		}
	}

//------------------------------------------------
function AlertError(msg, url, linenumber)
	{
	alert('Error message= '+msg+'\nURL= '+url+'\nLine Number= '+linenumber)
	return true
	}

function GetElemStyleByID(objectId)
	{
    // cross-browser function to get an object's style object given its
    if(document.getElementById && document.getElementById(objectId)) 
		{
		// W3C DOM
		return document.getElementById(objectId).style;
	    } 
	else if (document.all && document.all(objectId)) 
		{
		// MSIE 4 DOM
		return document.all(objectId).style;
		}
	else if (document.layers && document.layers[objectId]) 
		{
		// NN 4 DOM.. note: this won't find nested layers
		return document.layers[objectId];
		}
	return false;
	}


function GetElemByID(id)
	{
	return document.getElementById(id);
	}

function GetElemValue(id)
	{
	return GetElemByID(id).value;
	}
function SetElemValue(id, value)
	{
	GetElemByID(id).value = value;
	}
function SetElemInnerHTML(id, value)
	{
	GetElemByID(id).innerHTML = value;
	}

function ShowElem(elem)
	{
	elem.style.display = "inline";
	}
function HideElem(elem)
	{
	elem.style.display = "none";
	}
function ShowElemID(id)
	{
	ShowElem(GetElemByID(id));
	}
function HideElemID(id)
	{
	HideElem(GetElemByID(id));
	}
function GetIndexFromValueInSelect(selectElem, val)			// returns -1 if doesn't find
	{
	for (var idx = 0; idx < selectElem.options.length; idx++)
		{
		if (val == selectElem.options[idx].value)
			{
			return idx;
			}
		}
	return -1;
	}

function IsOptionValueInSelect(selectElem, val)
	{
	var idx = GetIndexFromValueInSelect(selectElem, val);
	return (idx != -1);
	}

function CapFirstLetterOnly(s)
	{
	var rtnStr = "";
	if (s.length > 0)
		{
		rtnStr = s.charAt(0).toUpperCase();
		if (s.length > 1)
			{
			rtnStr += s.substr(1).toLowerCase();
			}
		}	
	return rtnStr;
	}

function ValidateFirstName(elem)
	{
	elem.value = CapFirstLetterOnly(elem.value);
	}

function ValidateLastName(elem)
	{
	elem.value = CapFirstLetterOnly(elem.value);
	}
function RemoveElement(id)
	{
	var elem = document.getElementById(id);
	if (elem) elem.removeChild(elem.childNodes[0]);
	}    

function goto_admin_chat()
	{
	document.location = "admin_chat.php";
	}
function goto_mug_upload_page()
	{
	document.location = "index.php?mug";
	}

function goto_debug_page()
	{
	document.location = "debug_pg.php";
	}
function goto_index_page()
	{
	document.location = "index.php";
	}
/*
function goto_index_page(data)
	{
	if (data)
		{
		document.location = "index.php?"+data;
		}
	else document.location = "index.php";
	}
 */
function goto_desktop()
	{
	document.location = "pg_desktop.php?desktop";
	}
function goto_zik()
	{
	document.location = "pg_desktop.php?zik";
	}

function goto_users_page()
	{
	document.location = "users_pg.php";
	}

function jsMakePhotoFilename(user_id, photo_id, suffix)
	{
	return "p"+str_right("0000000000"+user_id,10)
			  +str_right("0000000000"+photo_id,10)
			  + "." + suffix;
	}
function date_GetDayName(day_idx)
	{
	return date_Days[day_idx];
	}
function date_GetDayNameAbbrev(day_idx)
	{
	return date_Days[day_idx].substr(0,3);
	}
function date_GetMonthName(month_idx)
	{
	return date_Months[month_idx];
	}
function date_GetMonthNameAbbrev(month_idx)
	{
	return date_Months[month_idx].substr(0,3);
	}
function str_left(str, chars)
	{
	if (str.length >= chars ) return str.substr(0,chars);
	return str;
	}
function str_right(str, chars)
	{
	if (str.length >= chars ) return str.substr(str.length-chars,chars);	
	return str;
	}
	
//--------------------------------------------
function today()
	{
	var d = new Date();
	return date_GetMonthNameAbbrev(d.getMonth())+" "
		+ d.getDate()+", "+d.getFullYear();
	}

function zero_pad_left(value, total)
	{
	return str_right("00000000000000000000"+value, total);
	}

function getStr_HMMampm(hour, minute)
	{
	var ap = "am";
	if (hour > 11) ap = "pm";
	if (hour > 12) hour -= 12;
	if (!hour) hour = 12;
	return hour+":"+str_right("0"+minute, 2)+ap;
	}
	
function donothing()
	{
	return false;
	}	

function get_elem_by_name(div_id, name)
	{
	var div = document.getElementById(div_id);
	return document.getElementsByName(name)[0].id;
	}

//------------------------------------------------------------------
function CenterElemInElem(src, dest)
	{
	var r = new Rect(0, 0, $(src).height(), $(src).width());
	var s = new Rect(0, 0, $(dest).height(), $(dest).width());

	r.centerInRect(s);
	$(src).css({left:r.left-s.left, top:r.top-s.top, width:r.width, height:r.height});
	delete r, s;
	}
//------------------------------------------------------------------
function CopyElemPos(src, dest, vOff, hOff)
	{
	dest.css("top", parseInt(src.css("top"))+vOff);
	dest.css("left", parseInt(src.css("left"))+hOff);
	delete pos;	
	}
//------------------------------------------------------------------
function KeepElemInPar(elem, padding)
	{
	var par = new Rect().getElem(elem.parent());
	if (padding) par.inset(padding,padding);
	var r = new Rect().getElem(elem).keepInRect(par).setElem(elem);
	delete r;
	delete par;
	}
//------------------------------------------------------------------
function CenterElemInElemID(srcID, destID)
	{
	CenterElemInElem($("#"+srcID), $("#"+destID));
	}


function VCenterElemInParent(elem)
	{
	$(elem).css({
		position:"relative",
		top: "50%",
		"margin-top":(-parseInt($(elem).height())/2)+"px"
	});
	}
	
function HCenterElemInParent(elem)
	{
	$(elem).css({
		position:"relative",
		left:"50%",
		"margin-left":(-parseInt($(elem).width())/2)+"px"
		});
	}
	

function CenterElemInParent(elem)
	{
	$(elem).css({
		position:"relative",
		top: "50%",
		left:"50%",
		"margin-top":(-parseInt($(elem).height())/2)+"px",
		"margin-left":(-parseInt($(elem).width())/2)+"px"
	});
	}

function basename(path)
	{
	if (path) return trimQ(path.replace( /.*\//, "" ));
	}
	
function basenameNoExt(path)
	{
	var f = basename(path).toLowerCase();
	var s = getsuffix(f);
	if (s && s.length>0)
		{
		var pos = f.lastIndexOf("."+s);
		return str_left(f, f.lastIndexOf("."+s));
		}
	return f;
	}

function dirname(path)
	{
	return path.match( /.*\// );
	}
	
function getsuffix(path)
	{
	var pdpos = path.lastIndexOf(".");
	return str_right(path, path.length-pdpos-1);
	}
	
function trimQ(path)
	{
	var newPath = path;
	var pdpos = newPath.lastIndexOf("?");
	while (pdpos>-1)
		{
		newPath = str_left(newPath, pdpos);
		pdpos = newPath.lastIndexOf("?");
		}
	return newPath;
	}


function trimmer(s)
	{
	return s.replace(/^\s+|\s+$/g, '');
	}
function isBlank(val)
	{
	return !validate_any_nonspace_char(val);
	}

function enable_elem(jElem, true_false)
	{
	if (true_false) jElem.removeAttr('disabled');
	else jElem.attr('disabled', "disabled");
	}

//----------------------------------------------------------------
function isloggedin()
	{
	return _SESS.logged_in;	
	}
//----------------------------------------------------------------
function getusername()
	{
	return _SESS.username;
	}
//----------------------------------------------------------------
function getuserlastname()
	{
	return _SESS.lastname;
	}
//----------------------------------------------------------------
function getuserfirstname()
	{
	return _SESS.firstname;
	}
//----------------------------------------------------------------
function getuseremail()
	{
	return _SESS.email;
	}
//----------------------------------------------------------------
function getusersex()
	{
	return _SESS.sex;
	}
//----------------------------------------------------------------
function getuserbirthday()
	{
	return _SESS.birthday;
	}
//----------------------------------------------------------------
function getusermotto()
	{
	return _SESS.motto;
	}
//----------------------------------------------------------------
function getdeskimg()
	{
	return _SESS.deskimg;
	}

//----------------------------------------------------------------
function getmugcroprect()
	{
	return new Rect(_SESS.mug_top,_SESS.mug_left,_SESS.mug_height,_SESS.mug_width);
	}
//----------------------------------------------------------------
function getmugorigrect()
	{
	return new Rect(0, 0, _SESS.mugorig_height, _SESS.mugorig_width);
	}

//----------------------------------------------------------------
function getfirstname_or_username()
	{
	var name = getuserfirstname();
	if (isBlank(name)) name = getusername();
	return name;
	}

var _xSESS;
//----------------------------------------------------------------
function getuserid()
	{
	return _SESS.user_id;
	}
//----------------------------------------------------------------
function setuserid(user_id)
	{
	_SESS.user_id = user_id;
	}
//----------------------------------------------------------------
function isadmin()
	{
	return (getuserid() < 3);
	}
//----------------------------------------------------------------
function stripquotes(s)
	{
	return s.replace(/['"]/g,'');
	}
//----------------------------------------------------------------
function trim(stringToTrim) 
	{
	return stringToTrim.replace(/^\s+|\s+$/g,"");
	}
//----------------------------------------------------------------
function ltrim(stringToTrim) 
	{
	return stringToTrim.replace(/^\s+/,"");
	}
//----------------------------------------------------------------
function rtrim(stringToTrim) 
	{
	return stringToTrim.replace(/\s+$/,"");
	}
//----------------------------------------------------------------
function date_fromISO(s){
    var i= 0, A= s.split(/\D+/);
    while(i++<7){
        if(!A[i]) A[i]= 0;
        else A[i]= parseInt(A[i], 10);
    }
    --A[1];
    return new Date(Date.UTC(A[0], A[1], A[2], A[3], A[4], A[5]));      
}

//----------------------------------------------------------------
function getArrayIndex(arr, target)
	{
	for (var idx = 0; idx < arr.length; ++idx)
		{
		if (arr[idx].toLowerCase()==target.toLowerCase())
			{
			return idx;
			}
		}
	return -1;
	}

//----------------------------------------------------------------
function GetFileFmt(path)
	{
	var suff = getsuffix(path);
	if (getArrayIndex(_photoFmts, suff) != -1) return _fmtPhoto;
	if (getArrayIndex(_videoFmts, suff) != -1) return _fmtVideo;
	if (getArrayIndex(_audioFmts, suff) != -1) return _fmtAudio;
	if (getArrayIndex(_otherFmts, suff) != -1) return _fmtOther;
	return false;
	}
//----------------------------------------------------------------
function GetFileExtStr(arr)
	{
	var s = "";
	for (var idx = 0; idx < arr.length; ++idx)
		{
		s += "*."+arr[idx]+";";
		}
	return s;
	}
//----------------------------------------------------------------
function GetFilesExtStr()
	{
	return GetFileExtStr(_videoFmts)
	+GetFileExtStr(_audioFmts)
	+GetFileExtStr(_otherFmts)
	+GetFileExtStr(_photoFmts);
	}
//----------------------------------------------------------------
function isMediaFile(path)
	{
	var suff = getsuffix(path);
	if (getArrayIndex(_videoFmts, suff) != -1) return true;
	if (getArrayIndex(_audioFmts, suff) != -1) return true;
	if (getArrayIndex(_otherFmts, suff) != -1) return true;
	return false;
	}
//----------------------------------------------------------------
function isImage(path)
	{
	switch(getsuffix(path))
		{
		case "jpeg":
		case "jpg":
		case "gif":
		case "png":
		case "bmp":
			return true;
		}
	return false;
	}
//----------------------------------------------------------------
function GetMediaIcon(path)
	{
	switch(GetFileFmt(path))
		{
		case _fmtVideo:
			return "ui_images/media_video.jpg";
			break;
		case _fmtAudio:
			return "ui_images/media_audio.jpg";
			break;
		case _fmtOther:
			switch(getsuffix(path))
				{
				case "pdf":
					return "ui_images/media_pdf.jpg";
				case "html":
					return "ui_images/media_html.jpg";
				default:
					return "ui_images/media_unknown.jpg";
				}
		case _fmtPhoto:
			
		}
	return false;
	}
//----------------------------------------------------------------
function js_arraytostring(arr)
	{
	if (arr)
		{
		if (arr.length > 0) return arr.join(",");
		}
	return null;
	}
//----------------------------------------------------------------
function js_stringtoarray(str)
	{
	if (str) return str.split(',');
	return "";
	}
//----------------------------------------------------------------
function getMugPath(userID, sizestr)
	{
	return _path_mugs+"/"+sizestr+"/mug_"+zero_pad_left(userID, 10)+".jpg";
	}
//------------------------------------------------------------------
function LocalToParent(elem, pos)
	{
	pos.top += parseInt(elem.css("top"));
	pos.left += parseInt(elem.css("left"));
	}

//------------------------------------------------------------------
function ParentToLocal(elem, pos)
	{
	pos.top -= parseInt($(elem).css("top"));
	pos.left -= parseInt($(elem).css("left"));
	}

//------------------------------------------------------------------
function makePossesive(s)
	{
	if (!isBlank(s))
		{
		if (str_right(s,1).toLowerCase()=="s") return s+"'";
		return s+"'s";
		}
	}

//----------------------------------------------------------------------------------------------------------------
function getMillisec()
	{
	var d = new Date();
	var arg = d.getMilliseconds();
	delete d;
	return arg;
	}
//----------------------------------------------------------------------------------------------------------------
function flattenIntArray(arr)
	{
	var s = "";
	if (arr)
		{
		if (arr.length > 0)
			{
			for (var i = 0; i < arr.length; ++i)
				{
				s += arr[i]+"^";
				}
			s = str_left(s, s.length-1);
			}
		}
	return s;
	}
//----------------------------------------------------------------------------------------------------------------
function isnumber(val)
	{
	if (isNaN(val)) return false;
	return true;
	}
	
//------------------------------------------
function getUrlArg()
	{
	var s = window.location.search;
	if (s.substr(0,1) == "?") return s.substr(1);
	}
//----------------------------------------------------------------
function stripfile(path)
	{
	if (!path) return;
	var pos = path.indexOf("?");
	if (pos>0) return str_left(path, pos);
	return path;
	}
//----------------------------------------------------------------
function nbsp(cnt)
	{
	var s="";
	for (i=0;i<cnt;++i) s += "&nbsp;";
	return s;
	}
	