var userID;
var savedUsername;
var ma_showing = false;
var isIE6 =  false/*@cc_on || @_jscript_version <= 5.7 @*/;
document.observe("dom:loaded",function() {
	if($('office1') != undefined) $('office1').hide();
	userID = Cookie.get('userID');
	savedUsername = Cookie.get('savedUsername');
	var sliderStart = Cookie.get('sliderStart');
	var theslider = $('ma_track');
	var fromtop;
	var ma_interface = (!userID || userID == "undefined") ? 'login' : 'main';
	loadMyAccount(ma_interface);
	if(ma_interface == "main") {
		loadMyAccountTabContent('ma_propertiestab');	
	}
	
	if(!sliderStart) {
		sliderStart = 115;
	} else {
		fromtop = sliderStart - 113;
		$('ma_tab').setStyle({top:fromtop+'px' });
	}
    new Control.Slider(theslider.down('.ma_handle'), theslider, {
      axis:'vertical', range: $R(0,332), sliderValue:sliderStart, 
	  onSlide: function(value) {
		  fromtop = value - 113;
		  $('ma_tab').setStyle({top:fromtop+'px' });
	  },
	  onChange: function(value) {
		  Cookie.set('sliderStart',value);
	  }
    }); 
	
});

function showHideMyAccount() {
	var ma_X = 549; 
	if(ma_showing) { ma_X = -550; }
	new Effect.Move('ma_wrapper', { x: ma_X, y: 0, mode: 'relative', transition: Effect.Transitions.sinoidal, 
		afterFinish: function() { if(!ma_showing) { ma_showing = true; toggleAbleForms("disabled"); } else { ma_showing = false; toggleAbleForms(false); } } });
}

function toggleAbleForms(which) {
	var f = document.forms;
	for(var i = 0; i < f.length; i++) {
		if(f[i].name != "maregister" && f[i].name != "maloginform" && f[i].name != "maconfirmation" && f[i].name != "maeditinfo" && f[i].name != "maagentform") {
			var e = f[i].elements;
			for(var j = 0; j < e.length; j++) {
				e[j].disabled = which;
				if(isIE6) {
					var k = (which == "disabled") ? "hidden":"visible";
					e[j].style.visibility = k;
				}
			}
		}
	}
}

function loadMyAccount(ma_interface) {
	if(arguments[1] == "out") {
		Cookie.set("userID","");	
	}
	eid = null;
	$('ma_loadcontent').innerHTML = "";
	$('ma_loader').style.display = "block";
	var loadUrl;
	switch(ma_interface) {
		case('login'): loadUrl = 'ma-login.php'; break;
		case('main'): loadUrl = 'ma-main.php'; break;
		case('register'): loadUrl = 'ma-register.php'; break;
		case('activate'): loadUrl = 'ma-confirmation.php'; break;
		case('editinfo'): loadUrl = 'ma-editinfo.php'; break;
		case('agentslist'): loadUrl = 'ma-agentslist.php'; break;
		default: loadUrl = 'ma-main.php';
	}
	new Ajax.Request('../include/ajax/myaccount/'+loadUrl, { method:'post',parameters: { username: savedUsername, uid:arguments[1] }, 
	onSuccess:function(transport){
	var response = transport.responseText || "no response text";
	if(response != "notloggedin") {
		$('ma_loadcontent').innerHTML = response;
		$('ma_loader').style.display = "none"; 
		if(ma_interface == "main") {
			ma_ontabflag = "loading";
			loadMyAccountTabContent("ma_propertiestab");
		}
	} else {
		Cookie.set("userID","");
		loadMyAccount('login'); 
	} },
	onFailure: function() { alert('Something went wrong'+response);}});
}

var Cookie = {
	set: function(name,value,seconds){
		if(seconds){
			var d = new Date();
			d.setTime(d.getTime() + (seconds * 1000));
			var expiry = '; expires=' + d.toGMTString();
		}else
			var expiry = '';
		document.cookie = name + "=" + value + expiry + "; path=/";
	},
	get: function(name){
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i = 0; i < ca.length; i++){
			var c = ca[i];
			while(c.charAt(0) == ' ')
				c = c.substring(1,c.length);
			if(c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
};

var eid;
function validateMyAccountForm(formid) {
	if(eid) {
		Effect.Fade(eid);	
		eid = null;
	}
	var loadUrl;
	var valid = new Validation(formid,{ onSubmit:true, stopOnFirst:true, useTitles:true });
	if(formid == "maregister") {
		Validation.add('validate-password', 'Must be 6-12 characters and not be \'password\' or same as email', { minLength : 6, maxLength : 12, notOneOf : ['password','PASSWORD','123456','012345'], notEqualToField : 'ma_email' });
		Validation.add('validate-confirmpw', 'Passwords Do Not Match', { equalToField: 'ma_password' });
	}
	var result = valid.validate();
	if(result) {
		switch(formid) { 
			case('maregister'): loadUrl = 'ma-createaccount.php'; break;
			case('maloginform'): loadUrl = 'ma-accountlogin.php'; break;
			case('maconfirmation'): loadUrl = 'ma-confirmationcheck.php'; break;
			case('maeditinfo'): loadUrl = 'ma-saveinfo.php'; break;
			case('maagentform'): loadUrl = 'ma-agentslist.php'; break;
		}
		new Ajax.Request('../include/ajax/myaccount/'+loadUrl, { method:'post',parameters: { fields: $(formid).serialize() }, 
		onSuccess:function(transport){
		var response = transport.responseText || "no response text";
		var checkerror = response.indexOf("***");
		var checklogin = response.indexOf("*$*");
		if(checkerror == -1 && checklogin == -1 ) {
			$('ma_loadcontent').innerHTML = response;
		} else {
			if(checklogin != -1) {
				response = response.replace("*$*","");
				var savestuff = response.split("|");
				var checkSaved = Cookie.get("saveTried");
				if(checkSaved) {
					actionMyAccountProperty(checkSaved,'save');
				}
				if(savestuff[0] == "username") {
					Cookie.set('savedUsername',savestuff[1],31536000);
					Cookie.set('userID',savestuff[3]);
				} else {
					Cookie.set('userID',savestuff[1]);
				}
				loadMyAccount('main');
			} else {
				displayMyAccountError(response);
			}
		}
		},
		onFailure: function() { alert('Something went wrong'+response);}});
	}
	return false;
	
}

function displayMyAccountError(response) {
	response = response.replace("***","");
	var errors = response.split("|");
	if(errors[0] == "ma_password2") $('ma_password2').value = "";
	var e = new Element('div', { 'class': 'validation-advice','style':'display:none' }).update(errors[1]);
	$(errors[0]).insert({'after' : e});
	eid = $(errors[0]).next().identify();
	if(errors[0] == "ma_errormsg") {
		$(eid).setStyle({ top: '-24px', width:'100%', paddingRight:'0px', paddingLeft:'0px' });	
	}
	Effect.Appear(eid);	
}

var ma_agentshowing = true;
function toggleMyAgent() {
	if(ma_agentshowing) {
		var contentheight = $('ma_tabcontent').offsetHeight;
		contentheight = contentheight - 20;
		Effect.BlindUp('ma_agentdisplay', { afterUpdate: function() {
			 var nextheight = contentheight+2;
			 $('ma_tabcontent').style.height = nextheight+"px";
			 contentheight = nextheight;
			 }});
		$('ma_tabcontent').style.height = "335px";
		ma_agentshowing = false;
		$('minmax_agent').innerHTML = "[+] Show";
	} else {
		var contentheight = $('ma_tabcontent').offsetHeight;
		contentheight = contentheight - 20;
		Effect.BlindDown('ma_agentdisplay', { afterUpdate: function() {
			 var nextheight = contentheight-2;
			 $('ma_tabcontent').style.height = nextheight+"px";
			 contentheight = nextheight;
			 }});
		ma_agentshowing = true;
		$('ma_tabcontent').style.height = "235px";
		$('minmax_agent').innerHTML = "[-] Hide";
	}
	return false;
}

function setMyAccountAgent(mlsid) {
	new Ajax.Request('../include/ajax/myaccount/ma-setagent.php', { method:'post',parameters: { id: mlsid }, 
	onSuccess:function(transport){
	var response = transport.responseText || "no response text";
	if(response != "notloggedin") {
		var checkerror = response.indexOf("***");
		if(checkerror == -1 ) {
			loadMyAccount('main');
		} else {
			displayMyAccountError(response);
		}
	} else {
		Cookie.set("userID","");
		loadMyAccount('login'); 
	} },
	onFailure: function() { alert('Something went wrong'+response);}});
}
var ma_ontabflag = "loading";
function loadMyAccountTabContent(displayme) {
	if(ma_ontabflag != displayme) {
		if(ma_ontabflag != "loading") {
			$('ma_tabcontent').innerHTML = "";
			$('ma_tabloader').style.display = "block";
			$(ma_ontabflag).className = "";
			$(displayme).className = "ma_ontab";
		}
		ma_ontabflag = displayme;
		var thepage;
		switch(displayme) {
			case('ma_propertiestab'): thepage = "ma-savedproperties.php"; break;
			case('ma_searchestab'): thepage = "ma-savedsearches.php"; break;
			case('ma_documentstab'): thepage = "ma-documents.php"; break;
			default: thepage = "ma-savedproperties.php";
		}
		new Ajax.Request('../include/ajax/myaccount/'+thepage, { method:'post', 
		onSuccess:function(transport){
		var response = transport.responseText || "no response text";
		if(response != "notloggedin") {
			var checkerror = response.indexOf("***");
			if(checkerror == -1 ) {
				$('ma_tabloader').style.display = "none";
				$('ma_tabcontent').innerHTML = response;
			} else {
				displayMyAccountError(response);
			}
		} else {
			Cookie.set("userID","");
			loadMyAccount('login'); 
		} },
		onFailure: function() { alert('Something went wrong'+response);}});
	}
}
function actionMyAccountProperty(propid,action) {
	var thepage;
	switch(action) {
		case("save"): thepage = "ma-saveproperty.php"; break;
		case("delete"): thepage = "ma-deleteproperty.php"; break;
	}
	new Ajax.Request('../include/ajax/myaccount/'+thepage, { method:'post',parameters: { id: propid }, 
	onSuccess:function(transport){
	var response = transport.responseText || "no response text";
	if(response != "notloggedin") {
		if(response != "success") {
			alert(response);
		} else {
			ma_ontabflag = "loading";
			loadMyAccountTabContent('ma_propertiestab');
			var msg = (action == 'save') ? 'Property Saved To Your Account' : 'Property Has Been Removed';
			alert(msg);	
		}
	} else {
		if(!ma_showing) {
			showHideMyAccount();	
		}
		Cookie.set("userID","");
		Cookie.set("saveTried",propid,86400);
		loadMyAccount('login','savetried');
	} },
	onFailure: function() { alert('Something went wrong'+response);}});
}
function actionMyAccountSearch(searchid,action) {
	var thepage;
	switch(action) {
		case("save"): thepage = "ma-savesearch.php"; break;
		case("delete"): thepage = "ma-deletesearch.php"; break;
	}
	new Ajax.Request('../include/ajax/myaccount/'+thepage, { method:'post',parameters: { id: searchid }, 
	onSuccess:function(transport){
	var response = transport.responseText || "no response text";
	if(response != "notloggedin") {
		if(response != "success") {
			alert(response);
		} else {
			ma_ontabflag = "loading";
			loadMyAccountTabContent('ma_searchestab');
			var msg = (action == 'save') ? 'Search Saved To Your Account' : 'Search Has Been Removed';
			alert(msg);	
		}
	} else {
		Cookie.set("userID","");
		if(!ma_showing) {
			showHideMyAccount();	
		}
		loadMyAccount('login','savetried');
	} },
	onFailure: function() { alert('Something went wrong'+response);}});
}
function openWin(url,windowName,options){
	var WindowHandle=window.open(url,windowName,options);
	WindowHandle.focus();
}

function autotab(original,destination){
if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
$(destination).focus()
}
//shell functions below
var showing;
function toggleLeftNav(whichone) {
if(whichone == "search") {
if(showing != "search") {
if(showing != "offices") {
Effect.BlindDown('quicksearch');
showing = "search";
} else {
Effect.BlindUp('localofficeinfo');
Effect.BlindDown('quicksearch');
showing = "search";
}}} else if(whichone =="offices") {
if(showing != "offices") {
if(showing != "search") {
Effect.BlindDown('localofficeinfo');
showing = "offices";
} else {
Effect.BlindUp('quicksearch');
Effect.BlindDown('localofficeinfo');
showing = "offices";
}}} else if(whichone == "closesearch") {
Effect.BlindUp('quicksearch');
showing = "";
} else {
Effect.BlindUp('localofficeinfo');
showing = "";
}}
function bookmarkMe() {
if (window.sidebar) {
window.sidebar.addPanel(booktitle, bookurl, "");
} else if(window.opera && window.print) {
var elem = document.createElement('a');
elem.setAttribute('href',bookurl);
elem.setAttribute('title',booktitle);
elem.setAttribute('rel','sidebar');
elem.click();
} else if(document.all) {
window.external.AddFavorite(bookurl, booktitle);
}
}

/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
* 
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* 
*/
var Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
}
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)}, 
	max : function(v,elm,opt) {return v <= parseFloat(opt)},
	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							new Insertion.After(elm, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['required', 'This is a required field.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Please enter a valid number in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-date', 'Please enter a valid date.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', 'Please enter a valid email address. For example fred@domain.com .', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) && 
							(parseInt(RegExp.$1, 10) == d.getDate()) && 
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
			}],
	['validate-selection', 'Please make a selection', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', 'Please select one of the above options.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}]
]);
