// should these be loaded dynamically?
dojo.require("dojo.dnd.Mover");
dojo.require("dojo.dnd.Moveable");
dojo.require("dojo.dnd.move");
dojo.require("dijit.Dialog");

// set the underlay object, make sure it is created after all dojo files are loaded
var gUnderlay = null;

var setUnderlay = function() {
	gUnderlay = new dijit.DialogUnderlay();
}

dojo.addOnLoad(setUnderlay);

function checkLoginForm(username,pword) {
	var regex = /^\s*$/;
	var msg   = "";
	
	if (regex.test(username)) {
		msg = "Please enter a user name.\n";
	}
	
	if (regex.test(pword)) {
		msg += "Please enter a password.";
	}
	
	if (msg) {
		alert(msg);
		return false;
	}

	return true;
}

function checkUsernameForm(form) {
	var regex = /^\s*$/;
	
	if (regex.test(form.email.value)) {
		alert("Please enter an email address.");
		return false;
	}
	
	return true;
}

function checkLocationForm(form) {

	return true;
}

function checkTestForm(form) {
	
	return true;
}

function checkRegForm(form) {

	return true;
}

function checkAccountForm() {
	
	return true;
}

function toggleHint(id) {
	var objid = "questionhint-"+id;
	
	var drawer = new Drawer(objid);
	drawer.toggleDrawer();
}

function confirmReset(form) {
	if (form && confirm("Are you sure you want to undo all of your changes?")) {
		form.reset();
		scrollTo(0,0);
		alert("Your changes have been reset.");
	}
}

function checkVerifierSearchForm(form) {
	var regex = /^\s*\d\d\d\d\d(-\d\d\d\d)?\s*$/;
	
	if (!regex.test(form.postcode.value)) {
		alert("Please enter a valid zip/postal code in the format of 12345 or 12345-1234.");
		return false;
	}
	
	return true;
}

function checkListingSearchForm(form) {
	return checkVerifierSearchForm(form);
}

function removeHome(id) {
	if (confirm("Are you sure you want to delete this home listing?")) {
		window.location = gLiveSite+"/gapsuser/myhome?act=del&id="+id;
	}
}

var gDrawer;
var gMaxStepsDef      = 20; // the default max steps
var gDrawerOpenSpeed  = 10;
var gDrawerCloseSpeed = 10;
var gFadeSpeed        = 10;
var gMaxSteps;
var gCounter;

function Drawer(id) {
	var obj = document.getElementById(id);
	
	this.objid         = id;
	this.obj           = obj;
	this.drawerHeight  = 0;
	this.heightCounter = 1;
	this.dateObj       = new Date();
	
	this.obj.style.display  = "block";
	this.obj.style.overflow = 'scroll';
	this.drawerHeight       = this.obj.scrollHeight;
	this.obj.style.overflow = 'hidden';
		
	this.toggleDrawer = function() {
		if (this.isOpen()) {
			this.closeDrawer();
		} else {
			this.openDrawer();
		}
		
		gMaxSteps = gMaxStepsDef;
	}
	
	this.closeDrawer = function() {
		this.heightCounter = this.drawerHeight;
		gMaxSteps = gMaxStepsDef - 10; // a little faster fade
		this.startTime = this.dateObj.getTime();
		gDrawer = this;
		fade('out',1,0,'CD();');
	}
	
	this.openDrawer = function() {
		this.obj.style.opacity = '0';
		this.obj.style.filter = 'alpha(opacity=0)';
		gMaxSteps = gMaxStepsDef; // reset steps
		this.startTime = this.dateObj.getTime();
		gDrawer = this;
		OD();
	}
	
	this.isOpen = function() {
		if (this.obj.offsetHeight > 0) {
			return true;
		} else {
			return false;
		}
	}
}

function OD() {
	var h = gDrawer.drawerHeight;
	
	// don't set height to higher than element's original height (h)
	gDrawer.obj.style.height = (gDrawer.heightCounter > h) ? h+"px" : gDrawer.heightCounter+"px";
	
	// stop if max end time is reached
	// have to create new date object because IE caches method results (i.e., getTime() is static! >:/ )
	var dateobj = new Date();
	if (dateobj.getTime() > (gDrawer.startTime + (gMaxSteps*gDrawerOpenSpeed))) {
		gDrawer.heightCounter = h+1;
	}
	
	if (gDrawer.heightCounter <= h) {
		gDrawer.heightCounter += 20;
		gCounter = setTimeout("OD()",gDrawerOpenSpeed);
	} else {
		clearTimeout(gCounter);
		gDrawer.heightCounter = 1;
		gDrawer.obj.style.height = h+"px";
		
		gDrawer.startTime = dateobj.getTime();
		fade('in',1,1,null);
	}
}

function CD() {
	gDrawer.obj.style.height = (gDrawer.heightCounter < 1) ? "0px" : gDrawer.heightCounter+"px";
	
	// stop if max end time is reached
	// have to create new date object because IE caches method results (i.e., getTime() is static! >:/ )
	var dateobj = new Date();
	if (dateobj.getTime() > (gDrawer.startTime + (gMaxSteps*gDrawerOpenSpeed))) {
		gDrawer.heightCounter = 0;
	}
	
	if (gDrawer.heightCounter >= 1) {
		gDrawer.heightCounter -= 20;
		gCounter = setTimeout("CD()",gDrawerCloseSpeed);
	} else {
		clearTimeout(gCounter);
		gDrawer.obj.style.height = "0px";
		gDrawer.heightCounter = 1;
	}
}

// fade 'in' or fade 'out', the current fade step, the target opacity (0-1), any code to eval at end of fade
function fade(inout,step,target,endcode) {
	var startop = 0;
	
	if (gDrawer.obj.style.opacity) {
		startop = gDrawer.obj.style.opacity;
	}
	
	var op = (inout == 'out') ? startop-(step/gMaxSteps) : step/gMaxSteps;
		
	gDrawer.obj.style.opacity = op;
	gDrawer.obj.style.filter = 'alpha(opacity=' + op*100 + ')';
		
	// stop if max end time is reached
	// have to create new date object because IE caches method results (i.e., getTime() is static! >:/ )
	var dateobj = new Date();
	if (dateobj.getTime() > (gDrawer.startTime + (gMaxSteps*gFadeSpeed))) {
		op = target;
	}

	if (op == target) {
		clearTimeout(gCounter);
		
		gDrawer.obj.style.opacity = target;
		gDrawer.obj.style.filter = 'alpha(opacity='+target*100+')';
		gDrawer.startTime = dateobj.getTime();

		if (endcode) {
			eval(endcode);
		}
		
	} else {
		step++;
		gCounter = setTimeout("fade('"+inout+"','"+step+"','"+target+"','"+endcode+"')",gFadeSpeed);
	}
}

// the following code generously offered by Richard Cornford at bytes.com
var windowState = (function() {
	var readScroll = {scrollLeft:0,scrollTop:0};
	var readSize = {clientWidth:0,clientHeight:0};
	var readScrollX = 'scrollLeft';
	var readScrollY = 'scrollTop';
	var readWidth = 'clientWidth';
	var readHeight = 'clientHeight';
	
	function otherWindowTest(obj) {
		if((document.compatMode) && (document.compatMode == 'CSS1Compat') && (document.documentElement)) {
			return document.documentElement;
		} else if (document.body) {
			return document.body;
		} else {
			return obj;
		}
	};
	
	if ((typeof this.innerHeight == 'number') && (typeof this.innerWidth == 'number')) {
		readSize = this;
		readWidth = 'innerWidth';
		readHeight = 'innerHeight';
	} else {
		readSize = otherWindowTest(readSize);
	}
	if ((typeof this.pageYOffset == 'number') && (typeof this.pageXOffset == 'number')) {
		readScroll = this;
		readScrollY = 'pageYOffset';
		readScrollX = 'pageXOffset';
	} else {
		readScroll = otherWindowTest(readScroll);
	}
	
	return {
		getScrollX:function() {
			return (readScroll[readScrollX]||0);
		},
		getScrollY:function(){
			return (readScroll[readScrollY]||0);
		},
		getWidth:function(){
			return (readSize[readWidth]||0);
		},
		getHeight:function(){
			return (readSize[readHeight]||0);
		}
	};
})();

// fade and open verifier info. Note element to be opened/closed must have no top or bottom padding
function verifierInfo(id) {
	var objid = "verifier-"+id;
	
	var drawer = new Drawer(objid);
	drawer.toggleDrawer();
}

// fade in area while dimming/disabling the rest of the viewport
// anim is a dojo animation object with appropriate properties set
function fadeInOverlay(anim) {
	var node = dojo.byId('overlaydialog');
	
	if (!anim) {
	    anim = dojo.fadeIn({
			node: node, delay: 200,
			duration: 400
		});
	}
	
	//dojo.connect(anim, "onBegin",  function() { centerOverlay(); });
	dojo.connect(anim, "onEnd", function() { var m = new dojo.dnd.Moveable("overlaydialog", {handle: "boxhead"}); });
	
	// disable form controls -- otherwise controls peek through overlayed containers in IE
	toggleControls(true);
		
    // fade out page
    gUnderlay.show();
    
    // fade in form container
	anim.play();
}

var contactVerifier = function(id) {    
    // create form container
    var node = dojo.byId('overlaydialog');
    var anim = dojo.fadeIn({
		node: node, delay: 200,
		duration: 400,
		beforeBegin: function() {
			// draw form synchronously before fade in
			xajax_contactVerifierForm(id);
		}
	});
	
	fadeInOverlay(anim);
}
//dojo.addOnLoad(contactVerifier);

function fadeOutOverlay(anim) {
	if (!anim) {
		var node = dojo.byId('overlaydialog');
		anim = dojo.fadeOut({
			node: node, delay: 0,
			duration: 400,
			onEnd: function() {
					node.style.visibility = 'hidden'
					node.innerHTML = ''
				}
		});
	}
	
	// fade out form container
	anim.play();
	
	// fade in page
	gUnderlay.hide();
	
	// put all controls back in place
	toggleControls(false);
}

function toggleControls(off) {
	// only need to do this with IE
	if (dojo.isIE) {
		var menus = document.getElementsByTagName("SELECT");

		for (i=0; i<menus.length; i++) {
			menus[i].style.visibility = (off) ? 'hidden' : 'visible';
		}
	}
}

function submitVContact() {
	disableButton('submitButton','');
	xajax_processVerifierForm(xajax.getFormValues("contactverifier-form"));
	return false;
}

function submitLocation(form) {
	//disableButton('submitButton','');
	xajax_processLocationForm(xajax.getFormValues("locationinfo-form"));
	return false;
}

function cancelLocationForm(form) {
	form.a.value = 'Cancel';
	xajax_processLocationForm(xajax.getFormValues("locationinfo-form"));
	return false;
}

function submitMessageReply(form) {
	disableButton('submitButton','');
	
	var regex = /^\s*$/;
	
	if (regex.test(form.subject.value) || regex.test(form.message.value)) {
		alert("Please enter a subject and a message.");
		enableButton('submitButton', 'Send');
		return false;
	}
	
	xajax_processMessageReply(xajax.getFormValues("messagereply-form"));
	
	return false;
}

function disableButton(id,msg) {
	if (!msg) {
		msg = "Please Wait...";
	}
	
	xajax.$(id).style.background = '#999';
	xajax.$(id).style.color = '#333';
	xajax.$(id).disabled=true;
	xajax.$(id).value=msg;
}

function enableButton(id,msg) {
	if (!msg) {
		msg = "Submit";
	}
	
	xajax.$(id).style.background = 'url(/images/main_02.gif) repeat';
	xajax.$(id).style.color = '#060';
	xajax.$(id).disabled=false;
	xajax.$(id).value=msg;
}

function centerOverlay() {
	var obj = dojo.byId('overlaydialog');
	
	if (obj) {
		// center alignment
		var divWidth = obj.offsetWidth;
		var divHeight = obj.offsetHeight;
		var viewPortWidth = windowState.getWidth();
		var viewPortHeight = windowState.getHeight();
		var horizontalScroll = windowState.getScrollX();
		var verticalScroll = windowState.getScrollY();
		var hPos = Math.round(horizontalScroll+((viewPortWidth-divWidth)/2));
		var vPos = Math.round(verticalScroll+((viewPortHeight-divHeight)/2));
		hPos = (hPos < 0) ? 0 : hPos;
		vPos = (vPos < 0) ? 0 : vPos;
	
		obj.style.left = hPos+"px";
		obj.style.top = vPos+"px";
		obj.style.visibility = 'visible';
	}
}

function pdfHomeReport(id) {
	var url = gLiveSite+'/pdfer.php?act=homereport&id='+id;
	alert("A PDF report of this home listing will now be downloaded to your computer. Please check your download folder after downloading is complete.");
	
	window.location = url;
}

function listHome(id) {
	//alert("This feature is still under development.");
	var url = gLiveSite+'/gapsuser/listhome?id='+id;
	if (confirm("Are you sure you want to list this home?")) {
		window.location = url;
	}
}

function delistHome(id) {
	var url = gLiveSite+'/gapsuser/listhome?id='+id+'&act=del';
	if (confirm("Are you sure you want to de-list this home?")) {
		window.location = url;
	}
}

function showMsg(id) {	
	var node = dojo.byId('overlaydialog');
    var anim = dojo.fadeIn({
		node: node, delay: 200,
		duration: 400,
		beforeBegin: function() {
			xajax_showMessage(id);
		}
	});
	
	// un-bold the message listing
	dojo.byId('msglink-'+id).style["font-weight"] = 'normal';
	// set last read date
	xajax_setDateText('lastread-'+id,0); // THIS IS CAUSING A SAFARI BUG -- FORM FIELDS CANNOT BE MOUSE-SELECTED
	
	// fade in the dialog
	fadeInOverlay(anim);
}

function replyToMsg(id) {
	var node = dojo.byId('overlaydialog');
    var anim = dojo.fadeIn({
		node: node, delay: 200,
		duration: 400,
		beforeBegin: function() {
			xajax_messageReply(id,1);
		}
	});
	
	// un-bold the message listing
	dojo.byId('msglink-'+id).style["font-weight"] = 'normal';
	// set last read date
	xajax_setDateText('lastread-'+id,0);
	
	// fade in the dialog
	fadeInOverlay(anim);
}

function showReplies(id) {
	xajax_showReplies(id);
}
