function gmapinit(myusername,mimg,mlat,mlong,userusername,uimg,ulat,ulong){
	function createMarker(point,html) {
		var marker = new GMarker(point);
		mload = function(){
			marker.openInfoWindowHtml(html);
		}
		GEvent.addListener(marker, "click", mload);
		return marker;
	}
	var map = new GMap2(document.getElementById("map_canvas"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	//set points
	map.setCenter(new GLatLng(mlat,mlong), 8);
	var bounds = new GLatLngBounds();
	var point = new GLatLng(mlat,mlong);
	bounds.extend(point);
	var mhtml = '<table border="0" cellspacing="0" cellpadding="2"><tr><td align="center"><div style="width:120px;" class="imageContainer"><div style="max-height:90px;overflow:hidden"><img border="0" src="'+mimg+'.120.jpg"></div></div></td></tr><tr><td class="tdHeader" align="center"><a class="rev" href="/'+myusername+'" target="_blank">'+myusername+'</a></td></tr></table>';
	var marker = createMarker(point,mhtml);
	map.addOverlay(marker);
	var point = new GLatLng(ulat,ulong);
	bounds.extend(point);
	var uhtml = '<table border="0" cellspacing="0" cellpadding="2"><tr><td align="center"><div style="width:120px;" class="imageContainer"><div style="max-height:90px;overflow:hidden"><img border="0" src="'+uimg+'.120.jpg"></div></div></td></tr><tr><td class="tdHeader" align="center"><a class="rev" href="/'+userusername+'" target="_blank">'+userusername+'</a></td></tr></table>';
	var marker = createMarker(point,uhtml);
	map.addOverlay(marker);
	map.setZoom(map.getBoundsZoomLevel(bounds) - 1);
	map.setCenter(bounds.getCenter());
	//GEvent.trigger(marker,"click");
}

function addRandomGET(reqURI){
	var peram = 'iefix=';
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 5;
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		peram += chars.substring(rnum,rnum+1);
	}
	if(reqURI.match(new RegExp(".*?\\.php\\?","gim"))){
		reqURI += '&'+peram;
	} else {
		reqURI += '?'+peram;
	}
	return reqURI;
}

function regexWhiteSpaceTrimmer(str) { 
	str.replace(/^\s*/, '').replace(/\s*$/, ''); 
	return str;
} 

function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
			c_start=c_start + c_name.length + 1;
			c_end=document.cookie.indexOf(";", c_start);
			if (c_end==-1){
				c_end=document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

function setCookie(c_name,value,expiredays){
	var exdate = new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function loadTinyMCE(isReadOnly){
	if(isReadOnly){
		tinyMCE.init({mode : "textareas",theme : "simple",editor_selector : "mceEditor",readonly : true});
	} else {
		tinyMCE.init({mode : "textareas",theme : "simple",editor_selector : "mceEditor"});
	}
}

function docMailChecker(){
	this.mailChecker = null;
	this.newMailCount = 0; //use this at some point!
	this.startMailChecker = function(){
		if(getCookie('doMailCheck')!='false'){
			this.mailChecker = new PeriodicalExecuter(mailcheck.checkMail, 10);
		}
	}
	this.stopMailChecker = function(){
		this.mailChecker.stop();
		setCookie('doMailCheck','false',1);
	}
	this.checkMail = function(){
		new Ajax.Request(addRandomGET('/ajax/hasMail.ajax.php'),
			{
				method:'GET',
				onSuccess: function(transport){
					var response = parseInt(transport.responseText) || 0;
					if(response>0){
						popup.doBool('You have new messages in your inbox, would you like to read them now?',{yes: function(){mailcheck.stopMailChecker();location.href='/mail/inbox';}},{no: function(){mailcheck.stopMailChecker();}});
					}
				},
				onFailure: function(){
					mailcheck.stopMailChecker();
				}
			});
	}
}

function doMsgDiv(id,msg,styleClass){
	this.elm = $(id);
	this.elm.style.display = "block";
	this.elm.style.opacity = 0;
	this.elm.style.MozOpacity = 0;
	this.elm.style.KhtmlOpacity = 0;
	this.elm.style.filter = "alpha(opacity=0)";
	this.elm.className = styleClass;
	if(msg!=''){
		this.elm.innerHTML = msg;
	}
	this.timer = 0;
	this.speed = 30; // 3 secs
	//First Fade In
	for(var i=1;i<=100;i++){
		setTimeout("opacityChange("+i+",'"+id+"')",(this.timer * this.speed));
		this.timer++;
	}
	//Now Fade Out
	for(var i=100;i>=0;i--){
		setTimeout("opacityChange("+i+",'"+id+"')",(this.timer * this.speed));
		this.timer++;
	}
}

function opacityChange(opacity, id) {
	this.elm = $(id);
	this.elm.style.opacity = (opacity / 100);
	this.elm.style.MozOpacity = (opacity / 100);
	this.elm.style.KhtmlOpacity = (opacity / 100);
	this.elm.style.filter = "alpha(opacity=" + opacity + ")";
	if(opacity==0){
		this.elm.style.display = "none";
	}
}

function docAjaxPostRequest(elementContainer,requestURI,formContainer,functionCall){
	var perams = $(formContainer).serialize(true);
	this.focuselm = $(elementContainer);
	this.focuselm.innerHTML = '<div style="padding:10px;text-align:center"><img border="0" src="/images/site_images/popup-ajax-loader.gif"></div>';
	new Ajax.Request(addRandomGET(requestURI),
		{
			parameters: perams,
			onSuccess: function(transport){
				var response = transport.responseText || null;
				if(response==null){
					this.focuselm.innerHTML = 'A problem has occured. [Response from server is NULL]';
				} else if(response=="nosession"){
					location.href = "/login.php?logout";
				} else {
					this.focuselm.innerHTML = response;
					if(functionCall){
						functionCall['fCall']();
					}
				}
			},
			onFailure: function(){
				this.focuselm.innerHTML = "A problem has occured [Ajax Post Request Failed]";
			}
		});
}

function docAjaxRequest(elementContainer,requestURI,functionCall){
	this.focuselm = $(elementContainer);
	this.focuselm.innerHTML = '<div style="padding:10px;text-align:center"><img border="0" src="/images/site_images/popup-ajax-loader.gif"></div>';
	new Ajax.Request(addRandomGET(requestURI),
		{
			method:'GET',
			onSuccess: function(transport){
				var response = transport.responseText || null;
				if(response==null){
					this.focuselm.innerHTML = 'A problem has occured. [Response from server is NULL]';
				} else if(response=="nosession"){
					location.href = "/login.php?logout";
				} else {
					this.focuselm.innerHTML = response;
					if(functionCall){
						functionCall['fCall']();
					}
				}
			},
			onFailure: function(){
				this.focuselm.innerHTML = "A problem has occured [Ajax Request Failed]";
			}
		});
}

Position.GetWindowSize = function(w) {
	var width, height;
	w = w ? w : window;
	this.width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
	this.height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
	return this;
}
function docPopup(){
	this.siteName = 'Datezu';
	this.popupContainer = $('popupContainer');
	this.popupMask = $('popupMask');
	this.popupTitleContainer = $('popupTitle');
	this.popupBodyContainer = $('popupBody');
	this.resetPopupStyle = function(){
		this.popupBodyContainer.style.padding = "6px 10px 6px 10px";
	}
	this.setTitle = function(popupTitle) {
		popupTitle = regexWhiteSpaceTrimmer(popupTitle);
		if((popupTitle=='')||(popupTitle==null)){
			this.popupTitleContainer.innerHTML = '&nbsp;';
		} else {
			this.popupTitleContainer.innerHTML = popupTitle;
		}
		this.popupTitleContainer.innerHTML += '<span style="position:absolute;right:15px;cursor:hand !important;cursor:pointer !important;" onClick="popup.hidePopup();">[ X ]</span>';
	}
	this.setSrcBody = function(requestURL,functionList){
		//do ajax request and update popup body...
		if(this.popupBodyContainer){
			this.popupBodyContainer.innerHTML = '<div style="padding:10px 100px 10px 100px;text-align:center"><img border="0" src="/images/site_images/popup-ajax-loader.gif"></div>';
			new Ajax.Request(addRandomGET(requestURL),
			{
				method:'GET',
				onSuccess: function(transport){
					var response = transport.responseText || null;
					if(response==null){
						popup.popupBodyContainer.innerHTML = "A problem has occured [#Popup Request Response IS NULL]";
						popup.recenterPopup();
					} else if(response=="nosession"){
						location.href = "/login.php?logout";
					}	else {
						popup.popupBodyContainer.innerHTML = response;
						popup.recenterPopup();
						functionList['fCall']();
					}
				},
				onFailure: function(){
					popup.popupBodyContainer.innerHTML = "A problem has occured [#Popup Request Failed]";
					popup.recenterPopup();
				}
			});
		}
	}
	this.setTextBody = function(popupBody){
		this.popupBodyContainer.innerHTML = popupBody;
	}
	this.showPopup = function(){
		this.recenterPopup();
		//this.popupMask.style.visibility = 'visible';
		//this.popupMask.style.display = 'block';
		this.popupContainer.style.visibility = 'visible';
		this.popupContainer.style.display = 'block';
	}
	this.hidePopup = function(){
		this.popupContainer.style.visibility = 'hidden';
		this.popupContainer.style.display = 'none';
		this.popupMask.style.visibility = 'hidden';
		this.popupMask.style.display = 'none';
	}
	this.recenterPopup = function(){
		this.popupBodyContainer.style.width = 'auto';
		this.popupBodyContainer.style.height = 'auto';
		var dim = Position.GetWindowSize();
		var docX = dim.width;
		var docY = dim.height;
		var viewPortX = document.viewport.getWidth();
		var viewPortY = document.viewport.getHeight();
		var scrollOffsets = document.viewport.getScrollOffsets();
		this.popupMask.style.width = viewPortX + scrollOffsets[0] + 'px';
		this.popupMask.style.height = viewPortY + scrollOffsets[1] + 'px';
		//alert(Position.realOffset(document)[1]);
		//if(viewPortX>docX){
		//	this.popupMask.style.width = viewPortX+'px';
		//} else {
		//	this.popupMask.style.width = docX+'px';
		//}
		//if(viewPortY>docY){
		//	this.popupMask.style.height = viewPortY+'px';
		//	//alert(viewPortY+'px - viewPort');
		//} else {
		//	this.popupMask.style.height = docY+'px';
		//	//alert(docY+'px - docY');
		//}
		var popX = this.popupContainer.getWidth();
		var popY = this.popupContainer.getHeight();
		if(popX>800){
			this.popupBodyContainer.style.width = '800px';
			popX = this.popupContainer.getWidth();
		}
		if(popY>500){
			this.popupBodyContainer.style.height = '500px';
			popY = this.popupContainer.getHeight();
		}
		//-> { left: 0, top: 0 }
		var newLeft = (docX/2) - (popX/2) + scrollOffsets[0];
		var newTop = (docY/2) - (popY/2) + scrollOffsets[1];
		if(newTop<0)
			newTop = 0;
		if(newLeft<0)
			newLeft = 0;
		this.popupContainer.style.left = newLeft+'px';
		this.popupContainer.style.top = newTop+'px';
	}
	this.createStaticPopup = function(title,text,functionList){
		this.resetPopupStyle();
		//Create a text/html based popup from var passed in.
		this.setTitle(title);
		this.setTextBody(text);
		if(functionList){
			functionList['fCall']();
		}
		this.showPopup();
	}
	this.createDynamicPopup = function(title,url,functionList){
		this.resetPopupStyle();
		//Create a text/html based popup from AJAX request.
		this.setTitle(title);
		this.showPopup();
		if(functionList){
			this.setSrcBody(url,functionList);
		} else {
			this.setSrcBody(url,{fCall: function(){}});
		}
	}
	this.doAlert = function(msg){
		this.resetPopupStyle();
		//Prompt user with alert displaying message (msg).
		this.setTitle(this.siteName + ' Alert');
		var buttonCode = '<div style="padding:10px;text-align:center;"><input type="button" value="OK" onClick="popup.hidePopup();"></div>'
		this.setTextBody(msg + buttonCode);
		this.showPopup();
	}	
	this.doBool = function(msg,yesFunc,noFunc){
		this.resetPopupStyle();
		this.yesFunc = yesFunc;
		this.noFunc = noFunc;
		this.setTitle(this.siteName + ' Prompt');
		var buttonCode = '<div style="padding:10px;text-align:center;"><input type="button" value="Yes" onClick="popup.yesClick();">&nbsp;<input type="button" value="No" onClick="popup.noClick();"></div>'
		this.setTextBody(msg + buttonCode);
		this.showPopup();
	}
	this.yesFunc = {yes: function(){}};
	this.noFunc = {no: function(){}};
	this.yesClick = function(){
		this.yesFunc['yes']();
		this.yesFunc = {yes: function(){}};
		this.hidePopup();
	}
	this.noClick = function(){
		this.noFunc['no']();
		this.noFunc = {no: function(){}};
		this.hidePopup();
	}
}
var popup = null;
function onLoad(){
	popup = new docPopup;
	mailcheck = new docMailChecker;
}
function onScroll(){
	popup.recenterPopup();
	//firefox seems to prefer two calls to readjust bmask again pbody.
	popup.recenterPopup();
}
function onResize(){
	popup.recenterPopup();
	//firefox seems to prefer two calls to readjust bmask again pbody.
	popup.recenterPopup();
}
//MENU FUNCTIONS
function menuOver(elm){
	elm.style.background = '#1D1D1D';
	if(elm.getElementsByTagName('div')[1]){
		this.elm = elm.getElementsByTagName('div')[1];
		this.elm.style.display = 'block';
		this.elm.style.visibility = 'visible';
	}
}
function menuOut(elm){
	elm.style.background = 'none';
	if(elm.getElementsByTagName('div')[1]){
		this.elm = elm.getElementsByTagName('div')[1];
		this.elm.style.display = 'none';
		this.elm.style.visibility = 'hidden';
	}
}
function itemOver(elm){
	elm.style.background = 'url(\'/images/site_images/90percentwhite.png\')';
	elm.style.color = '#2C2C2C';
}
function itemOut(elm){
	elm.style.background = 'none';
	elm.style.color = '#FFFFFF';
}
function linkOver(elm){
	elm.style.background = '#FBFBFB';
}
function linkOut(elm){
	elm.style.background = '#F7F7F7';
}

function doDeletePhoto(id, photocount){
	if (photocount == 20){
		docAjaxRequest('images', '/ajax/imageinfo.ajax.php?id=' + id + '&action=showuploader');
	}else{
		docAjaxRequest('pictures', '/ajax/imageinfo.ajax.php?id=' + id + '&action=delete', '');
	}
}

function doAddPhoto(photocount){
	photocount = parseInt(photocount)
	if (photocount > 18){
		docAjaxRequest('images', '/ajax/imageinfo.ajax.php?action=removeuploader', '');
	}else{
		docAjaxRequest('pictures', '/ajax/imageinfo.ajax.php?action=add', '');
	}
}

function updatePhotoCaption(id){
	elem = 'caption' + id;
	div = 'results' + id;
	caption = $(elem).value;
	msg = "Caption updated!";
	success = "notifySuccess";
	docAjaxRequest(div,'/ajax/imageinfo.ajax.php?id='+id+'&action=updatecaption&caption='+caption,{fCall: function(){doMsgDiv(div,msg,success);}});
}

function updatePhotoProfile(id){
	div = 'results' + id;
	msg = "Profile photo changed";
	success = "notifySuccess";
	docAjaxRequest(div, '/ajax/imageinfo.ajax.php?id=' + id + '&action=makeprofile', {fCall: function(){doMsgDiv(div,msg,success);}});
}

function jsAssocArray(key,val){
	this.key = key;
	this.val = val;
	this.getKey = function(){
		return this.key;
	}
	this.getValue = function(){
		return this.val;
	}
	this.setValue = function(val){
		this.val = val;
	}
}

function addAnotherInterest(){
	this.myInterests = new Array();
	this.interestContainer = document.getElementById('interestContainer');
	this.interestSubContainers = this.interestContainer.getElementsByTagName("div");
	this.nextPos = 0;
	if(this.interestSubContainers.length<20){
		for(var i=0;i<this.interestSubContainers.length;i++){
			var pos = parseInt(this.interestSubContainers[i].getAttribute('rel'));
			if(document.getElementById('myinterest'+pos)){
				this.myInterests[this.myInterests.length] = new jsAssocArray(pos,document.getElementById('myinterest'+pos).value);
			}
			if(pos>=this.nextPos){
				this.nextPos = pos + 1;
			}
		}
		this.interestContainer.innerHTML+='<div id="interestSubContainer'+this.nextPos+'" rel="'+this.nextPos+'" style="padding:2px"><input id="myinterest'+this.nextPos+'" class="userInput" name="interest'+this.nextPos+'" type="text" value="" size="40">&nbsp;<input type="button" value="Remove" onClick="$(\'interestSubContainer'+this.nextPos+'\').remove();"></div>';
		for(var j=0;j<this.myInterests.length;j++){
			var iKey = this.myInterests[j].getKey();
			var iValue = this.myInterests[j].getValue();
			document.getElementById('myinterest'+iKey).value = iValue;
		}
	} else {
		popup.doAlert('We only allow you to have up-to 20 interests listed in your profile');
	}
}

function $m(theVar){
	return document.getElementById(theVar)
}
function remove(theVar){
	var theParent = theVar.parentNode;
	theParent.removeChild(theVar);
}
function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	    obj.addEventListener(evType, fn, true)
	if(obj.attachEvent)
	    obj.attachEvent("on"+evType, fn)
}
function removeEvent(obj, type, fn){
	if(obj.detachEvent){
		obj.detachEvent('on'+type, fn);
	}else{
		obj.removeEventListener(type, fn, false);
	}
}
function isWebKit(){
	return RegExp(" AppleWebKit/").test(navigator.userAgent);
}
function ajaxUpload(form,url_action,id_element,html_show_loading,html_error_http){
	var detectWebKit = isWebKit();
	form = typeof(form)=="string"?$m(form):form;
	var erro="";
	if(form==null || typeof(form)=="undefined"){
		erro += "The form of 1st parameter does not exists.\n";
	}else if(form.nodeName.toLowerCase()!="form"){
		erro += "The form of 1st parameter its not a form.\n";
	}
	if($m(id_element)==null){
		erro += "The element of 3rd parameter does not exists.\n";
	}
	if(erro.length>0){
		alert("Error in call ajaxUpload:\n" + erro);
		return;
	}
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id","ajax-temp");
	iframe.setAttribute("name","ajax-temp");
	iframe.setAttribute("width","0");
	iframe.setAttribute("height","0");
	iframe.setAttribute("border","0");
	iframe.setAttribute("style","width: 0; height: 0; border: none;");
	form.parentNode.appendChild(iframe);
	window.frames['ajax-temp'].name="ajax-temp";
	var doUpload = function(){
		removeEvent($m('ajax-temp'),"load", doUpload);
		var cross = "javascript: ";
		cross += "window.parent.$m('"+id_element+"').innerHTML = document.body.innerHTML; void(0);";
		$m(id_element).innerHTML = html_error_http;
		$m('ajax-temp').src = cross;
		if(detectWebKit){
        	remove($m('ajax-temp'));
        }else{
        	setTimeout(function(){ remove($m('ajax-temp'))}, 250);
        }
	photocount = document.getElementById('count').getAttribute('rel');
	doAddPhoto(photocount);
    }
	addEvent($m('ajax-temp'),"load", doUpload);
	form.setAttribute("target","ajax-temp");
	form.setAttribute("action",url_action);
	form.setAttribute("method","post");
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("encoding","multipart/form-data");
	if(html_show_loading.length > 0){
		$m(id_element).innerHTML = html_show_loading;
	}
	form.submit();
}

function messageSelection(){
	this.selected = new Array();
	this.checkboxes = document.getElementsByTagName('input');
	this.toggleCheck = function(elm){
		this.selected = new Array();
		for(var i=0;i<this.checkboxes.length;i++){
			if(this.checkboxes[i].getAttribute('iname')=='tickbox'){
				if(elm.checked==true){
					this.checkboxes[i].checked = true;
					this.selected[this.selected.length] = new jsAssocArray(parseInt(this.checkboxes[i].getAttribute('rel')),true);
				} else {
					this.checkboxes[i].checked = false;
					this.selected[this.selected.length] = new jsAssocArray(parseInt(this.checkboxes[i].getAttribute('rel')),false);
				}
			}
		}
	}
	this.toggleInsert = function(elm){
		var found = false;
		var val = parseInt(elm.getAttribute('rel'));
		for(var i=0;i<this.selected.length;i++){
			if(this.selected[i].getKey()==val){
				if(elm.checked==true){
					this.selected[i].setValue(true);
				} else {
					this.selected[i].setValue(false);
				}
				found = true;
			}
		}
		if(!found){
			this.selected[this.selected.length] = new jsAssocArray(val,elm.checked);
		}
	}
	this.getSelected = function(){
		var selection = "";
		for(var i=0;i<this.selected.length;i++){
			if(this.selected[i].getValue()==true){
				selection += '-'+this.selected[i].getKey();
			}
		}
		return selection;
	}
	this.clear = function(){
		this.selected = new Array();
	}
}
var messagesSelected = new messageSelection;

function jsFieldValidator(velm,vcheck,vfunctioncall){
	this.vfunctioncall = vfunctioncall;
	this.velm = $(velm);
	this.vcheck = new RegExp(vcheck);
	if (this.velm.value.match(this.vcheck)) {
		this.vfunctioncall['ftrue']();
	} else {
		this.vfunctioncall['ffalse']();
	}
}

function jsAjaxFieldValidator(velm,vurl,vreg,vfcall){
	this.vreg = new RegExp(vreg);
	if($(velm).value.match(this.vreg)){
		new Ajax.Request(addRandomGET(vurl),
				{
					method:'GET',
					onSuccess: function(transport){
						var response = transport.responseText || null;
						if(response=="true"){
							vfcall['ftrue']();
						} else if(response=="false"){
							vfcall['ffalse']();
						}
					}
				});
	} else {
		vfcall['finfo']()
	}
}

function doCityMenu(telm){
	this.telm = telm;
	if(this.telm.value==1){
		$('locpref').value=$('locpref').getAttribute('city');
		$('locpref').disabled=true;
		$('temprem').style.display='none';
		$('changebutton').style.display='inline';
		//launch popup
		//popup.createDynamicPopup('Choose A City','/ajax/cityselect.ajax.php',{fCall: function(){$('cityentry').focus();}});
	} else {
		$('locpref').value=$('locpref').getAttribute('zip');
		$('locpref').disabled=false;
		$('temprem').style.display='inline';
		$('changebutton').style.display='none';
	}
}

var RecaptchaOptions = {theme : 'clean',tabindex : 2};
function recaptcha_re_init(){
	Recaptcha.create("6LcQfgcAAAAAAG2QizdUMiagnM4-n_vut613ZAVB","recaptcha_div",{theme:"clean",callback: Recaptcha.focus_response_field});
} 