﻿var regexEmail = new RegExp("^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$");
function LTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}
function RTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}
function trim( value ) {
	return LTrim(RTrim(value));
}
function isNumberKey(evt)
{
	return true;
}
function isCurrencyKey(obj,evt)
{
	var charCode = (evt.which) ? evt.which : event.keyCode
	var mReturn = true 
	if(obj.value.indexOf('.')==-1){
		if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=46){
			mReturn = false;
		}
	}else{
		mReturn = isNumberKey(evt);
	}
	return mReturn;
}
function formatCurrency(num){
	return formatCurrency(num,true);
}
function formatCurrency(num,isCents) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)){
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10){
		cents = "0" + cents;
	}
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++){
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
	}
	if(isCents){
		return (((sign)?'':'-') + '$' + num + '.' + cents);
	}else{
		return (((sign)?'':'-') + '$' + num);
	}
}
function SafeInt(strValue){
	var mReturn =0;
	try
	{
		if(trim(strValue)!=""){
			var test = parseInt(trim(strValue));
			mReturn = parseFloat(trim(strValue)).toFixed(0);
			mReturn = eval(mReturn);
		}
	}catch(e){}
	return mReturn;  
}
function SafeFloat(strValue){
	return SafeFloat(strValue,2);  
}
function SafeFloat(strValue,digit){
	var mReturn =0.0;
	try
	{
		if(trim(strValue)!=""){
			mReturn = parseFloat(trim(strValue)).toFixed(digit);
			mReturn = parseFloat(mReturn);
		}
	}
	catch(e){}
	return mReturn;  
}
function RoundFloat(doubleVar,digit){
	return SafeFloat(doubleVar.toString(),digit);
}
function enterForm(elmButtonID,evt){
	var charCode = (evt.which) ? evt.which : event.keyCode;
	if (charCode==13)
	{
		var elmObj = document.getElementById(elmButtonID);
		elmObj.click();
		return false;
	} 
	else
	{
		return true;
	}
}
function SearchSite(val) {
	var txt = document.getElementById(val);
	if (txt != null && txt.value != '' && txt.value != txt.defaultValue) {
		window.location = "http://www.relocation.com/library/search_results.aspx?search=" + txt.value;
	}
}
function ChangePointer(ctrl, val) {
	ctrl.style.cursor = val;
}
var mid;
var submid;
var which; if (which == null) {which = "1";}
var tempClearText = "";
function clearField(thefield) {
	if (thefield.defaultValue == thefield.value) {
		thefield.value = ""
	}
}
function initFillField(obj, defaultTxt) {
	obj.defaultValue = defaultTxt;
	obj.style.color = '';
}
function fillField(thefield) {
	if (trim(thefield.value) == "") {
		thefield.value = thefield.defaultValue;
	}
}
function changeNav(mid) {
	var nav = 'navitem ' + mid + '-on';
	if (mid && document.getElementById(mid) != null) {
		document.getElementById(mid).className = nav;
		document.getElementById(mid).onmouseout = function() { };
	}
}
function subnav(submid) {
	return false;
	if(submid == '') { return false;}
	else if (submid && document.getElementById(submid) != null) {
		document.getElementById(submid).className = 'navselect';
	}
}
function startup(mid) {
	return false;
	if (submid == '') {return false;}
	else if (mid == "moving-nosq") {mid = "moving";}
	else if (mid == "mortgage-nosq") {mid = "mortgage";}
	else if (mid == "insurance-nosq") {mid = "insurance";}
	else if (mid == "int") {mid = "moving";}
	else if (mid == "uload") {mid = "moving";}
	else if (mid == "auto") {mid = "moving";}
	changeNav(mid)
}
function ShowHideElement(el, val) {
	var e = document.getElementById(el);
	if (e != null) {
		e.style.display = val;
	}
}
function OnGError(args) {
	alert(args.get_message());
}
function CheckField(c, errTxt, defTxt) {
	if (c.value == '' || c.value == c.defaultValue || c.value == errTxt) {            
		c.value = c.defaultValue = errTxt;
		c.style.color = "#FF0000";
		c.onblur = function() { initFillField(this, defTxt); fillField(this); }
		return false;
	}
	return true;
}
function CheckEmailField(c, errTxt, defTxt) {
	if (c.value == '' || c.value == c.defaultValue || regexEmail.exec(c.value) == null) {
		c.value = c.defaultValue = errTxt;
		c.style.color = "#FF0000";
		c.onblur = function() { initFillField(this, defTxt); fillField(this); }
		return false;
	}

	return true;
}
function AskExpert( name, email, question) {
	var n = document.getElementById(name);
	var e = document.getElementById(email);
	var q = document.getElementById(question);
	if (n != null & e != null && q != null) {
		var nf = CheckField(n, 'Please enter name', 'Enter your name');
		var ef = CheckField(e, 'Please enter e-mail address', 'Enter your e-mail (reply use only)');
		var ee = CheckEmailField(e, 'Enter a well-formed e-mail address', 'Enter your e-mail (reply use only)');
		var qf = CheckField(q, 'Please enter question', 'Type your Question');
		if (nf && ef && ee && qf) {
			var ret = AJAXHelper.AskExpert(n.value, e.value, q.value, OnCompleteExpert, OnGError);
		}
	}
}
function OnCompleteExpert(args) {
	var f = document.getElementById('divSubmitForm');
	var m = document.getElementById('divSubmitMessage');
	var b = document.getElementById('imgSubmit');
	var s = document.getElementById('spMsg');
	if (f != null && m != null && b != null && s != null) {
		b.style.display = 'none';
		f.style.display = 'none';
		m.style.display = '';
		s.innerHTML = args;
		s.style.color = "#FF0000";
	}
}
function SignupMoving(email, date) {
	var e = document.getElementById(email);
	var d = document.getElementById(date);
	if (e != null && d != null) {
		var ef = CheckField(e, 'Please enter e-mail address', 'Enter your e-mail address');
		var ee = CheckEmailField(e, 'Enter a well-formed e-mail address', 'Enter your e-mail address');
		var df = CheckField(d, 'Please enter a date', 'Enter move date mm/dd/yyyy');
		if (ef && ee && df) {
			var ret = AJAXHelper.SignUpMoving(e.value, d.value, OnCompleteSignupMoving, OnGError);
		}
	}
}
function OnCompleteSignupMoving(args) {
	var f = document.getElementById('divSignUpFrom');
	var m = document.getElementById('divSignFromMsg');
	var b = document.getElementById('imgSMSubmit');
	var s = document.getElementById('spSMMsg');
	if (f != null && m != null && b != null && s != null) {
		b.style.display = 'none';
		f.style.display = 'none';
		m.style.display = '';
		s.innerHTML = args;
		s.style.color = "#FF0000";
	}
}
function SubmitStory(email, story) {
	var e = document.getElementById(email);
	var s = document.getElementById(story);
	if (e != null && s != null) {
		var ef = CheckField(e, 'Please enter e-mail address', 'Enter your e-mail address');
		var ee = CheckEmailField(e, 'Enter a well-formed e-mail address', 'Enter your e-mail address');
		var sf = CheckField(s, 'Please enter your story', 'Submit your story here');
		if (ef && ee && sf) {
			var ret = AJAXHelper.SubmitStory(e.value, s.value, OnCompleteSubmitStory, OnGError);
		}
	}
}
function OnCompleteSubmitStory(args) {
	var f = document.getElementById('divTellUsForm');
	var m = document.getElementById('divTellUsMsg');
	var b = document.getElementById('imgTUSubmit');
	var s = document.getElementById('spTUMsg');
	if (f != null && m != null && b != null && s != null) {
		b.style.display = 'none';
		f.style.display = 'none';
		m.style.display = '';
		s.innerHTML = args;
		s.style.color = "#FF0000";
	}
}
function ChangeKindMove(val) {
	ShowHideElement('rrebuyer', 'none');
	ShowHideElement('rreseller', 'none');
	ShowHideElement('rftmover', 'none');
	ShowHideElement('rmovfam', 'none');
	ShowHideElement('rmovover', 'none');
	ShowHideElement('rmovpets', 'none');
	ShowHideElement('lrebuyer', 'none');
	ShowHideElement('lreseller', 'none');
	ShowHideElement('lftmover', 'none');
	ShowHideElement('lmovfam', 'none');
	ShowHideElement('lmovover', 'none');
	ShowHideElement('lmovpets', 'none');
	ShowHideElement('r' + val, 'block');
	ShowHideElement('l' + val, 'block');
}
//-- AMSA Popup --//
if (document.getElementById || document.all) {document.write('<div id="trailimageid" class="amsa"><img id="ttimg" src="http://www.relocation.com/files/amsa.jpg" style="border: solid 1px #D5DA97;" /></div>');}
function gettrailobj() {
	if (document.getElementById) {return document.getElementById("trailimageid").style;}
	else if (document.all) {return document.all.trailimagid.style;}
}
function truebody() {
	return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
function hidetrail() {
	document.onmousemove = "";
	document.getElementById('ttimg').src = 'http://www.relocation.com/files/amsa.jpg';
	gettrailobj().visibility = "hidden";
	gettrailobj().left = -1000;
	gettrailobj().top = 0;
}
hidetrail();
function showtrail(width, height, file) {
    if (navigator.userAgent.toLowerCase().indexOf('opera') == -1 && navigator.userAgent.toLowerCase().indexOf('safari') == -1) {
		wamsa = width;
		hamsa = height;
		gettrailobj().visibility = "visible";
		gettrailobj().width = width + "px";
		gettrailobj().height = height + "px";
		document.getElementById('ttimg').src = file;
		document.onmousemove = followmouse;
    }
}
function followmouse(e) {
	if (navigator.userAgent.toLowerCase().indexOf('opera') == -1 && navigator.userAgent.toLowerCase().indexOf('safari') == -1) {
		var xcoord = 20;
		var ycoord = 20;
		if (typeof e != "undefined") {
			xcoord += e.pageX;
			ycoord += e.pageY;
		}
		else if (typeof window.event != "undefined") {
			xcoord += truebody().scrollLeft + event.clientX;
			ycoord += truebody().scrollTop + event.clientY;
		}
		xcoord = xcoord - 200;
		ycoord = ycoord - 175;
		gettrailobj().left = xcoord + "px";
		gettrailobj().top = ycoord + "px";
	}
}
//-- Google API --//
var map, gdir;
function load(elmMapId,elmDirectionId,fromAddr,optionalAddr,toAddr) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById(elmMapId));
		map.addControl(new GLargeMapControl());
		gdir = new GDirections(map, document.getElementById(elmDirectionId));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
		setDirections(trim(fromAddr),trim(optionalAddr),trim(toAddr));
	}else{
		setDirections(trim(fromAddr),trim(optionalAddr),trim(toAddr));
	}
}
function setDirections(fromAddress,optionalAddr, toAddress) {
	var optional= (optionalAddr=="")? "":(optionalAddr=="Stop One Address, City, State, Zip (Optional)")? "":" to: "+optionalAddr;
	gdir.load("from: " + fromAddress + optional +" to: " + toAddress);
}
function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {alert("Invalid location.");}
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {alert("Please define source addresss and destination address.");}
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);}
	else if (gdir.getStatus().code == G_GEO_BAD_KEY) {alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);}
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);}
	else {alert("An unknown error occurred.");}

	try{
		map_OnErrorEvent();
	}catch(e){}
}
function onGDirectionsLoad(){ }
function Unload() {
	try {
		GUnload();
	} catch (e) { }
}
window.onunload=Unload;
/***********************************************
* Cool DHTML tooltip script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
var tipobj;
var isIE = false; var isNS6 = false; var enabletip = false;
function getObj() {
	isIE = document.all;
	isNS6 = document.getElementById && !document.all;
	enabletip = false;
	if (isIE || isNS6) {tipobj = document.all ? document.all["rsstooltip"] : document.getElementById ? document.getElementById("rsstooltip") : "";}
}
function ietruebody() {
	return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
function ddrivetip(thetext, thecolor, thewidth) {
	if(!tipobj) {
		getObj();
	}
	if (isNS6 || isIE) {
		if (typeof thewidth != "undefined") { tipobj.style.width = thewidth + "px"; }
		if (typeof thecolor != "undefined" && thecolor != "") { tipobj.style.backgroundColor = thecolor; }
		tipobj.innerHTML = thetext;
		enabletip = true;
		document.onmousemove = positiontip;
		return false;
	}
}
function positiontip(e) {
    if (enabletip) {
        var curX = (isNS6) ? e.pageX : event.clientX + ietruebody().scrollLeft;
        var curY = (isNS6) ? e.pageY : event.clientY + ietruebody().scrollTop;
        var rightedge = isIE && !window.opera ? ietruebody().clientWidth - event.clientX - 0 : window.innerWidth - e.clientX - 0 - 0;
        var bottomedge = isIE && !window.opera ? ietruebody().clientHeight - event.clientY - 0 : window.innerHeight - e.clientY - 0 - 0;
        var leftedge = (0 < 0) ? 0 * (-1) : 0;
        if (rightedge < tipobj.offsetWidth) { tipobj.style.left = isIE ? ietruebody().scrollLeft + event.clientX - tipobj.offsetWidth + "px" : window.pageXOffset + e.clientX - tipobj.offsetWidth + "px"; }
        else if (curX < leftedge) { tipobj.style.left = "0px"; }
        else { tipobj.style.left = curX + 0 + "px"; }
		if (bottomedge < tipobj.offsetHeight) { tipobj.style.top = isIE ? ietruebody().scrollTop + event.clientY - tipobj.offsetHeight - 0 + "px" : window.pageYOffset + e.clientY - tipobj.offsetHeight - 0 + "px"; }
        else { tipobj.style.top = curY + 0 + "px"; }
        tipobj.style.visibility = "visible";
    }
}
function hideddrivetip() {
    if (isNS6 || isIE) {
        enabletip = false;
        tipobj.style.visibility = "hidden";
        tipobj.style.position = "absolute";
        tipobj.style.left = "0px";
        tipobj.style.backgroundColor = '';
        tipobj.style.width = '';
		document.onmousemove = '';
    }
}

function TrackPartnerClick(pageName, serviceProvider, paramC1, paramC2, paramC3) {
	pic1 = new Image(1, 1);
	pic1.src = "/clicktrack.aspx?type=trackpartnerclick&url=" + pageName
	//pic1.src = "http://localhost:1701/relocationnew/clicktrack.aspx?type=trackpartnerclick&url=" + pageName
		+ "&serviceProv=" + serviceProvider
		+ "&param1=" + paramC1
		+ "&param2=" + paramC2
		+ "&param3=" + paramC3
		;
}
    
function SaveListing(a, b) {
	pic1 = new Image(1, 1);
	pic1.src = "/clicktrack.aspx?type=savelisting&uri=" + a
	//pic1.src = "http://localhost:1701/relocationnew/clicktrack.aspx?type=savelisting&uri=" + a
		+ "&display=" + b
		;
	alert("Listing saved.\n\nUpdated listings will be visible for the next page load.");
}

function SaveListingMetrics(listingKey, mlsNumber, eventType, ipAddress, userAgent, hitTime, feedID) {

    $.ajax({ type: "POST"
        , contentType: "application/json; charset=utf-8"
        , url: "/WebServices/AJAXHelper.asmx/SaveListingMetrics"
        , data: "{ 'listingKey' : '" + listingKey + "', 'mlsNumber' : '" + mlsNumber + "', 'eventType' : '" + eventType + "', 'ipAddress' : '" + ipAddress + "', 'userAgent' : '" + userAgent + "', 'hitTime' : '" + hitTime + "', 'feedID' : '" + feedID + "' }"
        , dataType: "text"
        , dataFilter: function(data) {
            var msg;
            if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function') {
                msg = JSON.parse(data);
            }
            else {
                msg = eval('(' + data + ')');
            }

            if (msg.hasOwnProperty('d')) {
                return msg.d;
            }
            else {
                return msg;
            }
        }
    });
}