﻿/* PHD Consulting MLS Script - 2009-02-17 */

/* Client-side access to querystring name=value pairs
	Version 1.3 - 28 May 2008
	
	License (Simplified BSD): http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};

	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2) ? decodeURIComponent(pair[1]) : name;
		this.params[name] = value;
	}
}

Querystring.prototype.get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}

// Cookie Functions for simple persistance
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 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 "";
}

// Random String Generator
function randomString(length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	
	if (length) { string_length = length; }
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

// IsNumeric function for MLS Search
function isNumeric(x) {
	var RegExp = /^(-)?(\d*)(\.?)(\d*)$/; // Note: this WILL allow a number that ends in a decimal: -452.
	return x.match(RegExp);
}

// Image Carousel for listings
var makeCarousel = function() {
	if($('imgprev')) {
		var searchImages = new noobSlide({
			box: $('imgset'),
			size: 340,
			items: $$('#imgset img'),
			interval: 3000,
			fxOptions: {
				duration: 500,
				transition: Fx.Transitions.Quint.easeOut,
				wait: false
			},
			addButtons: {
				previous: $('imgprev'),
				next: $('imgnext')
			}
		});
		var myButtons = $$('button img');
		$each(myButtons,function(item){
			item.addEvent('mouseover',function(){
				item.setStyle('cursor','pointer')
			});
			item.addEvent('mouseout',function(){
				item.setStyle('cursor','')
			});
		});
	}
}

// Class Type Matching
var getClassType = function(type)
{
	var classType = 1;
	var isWaterfront = '';
	switch (type)
	{
		case "residential":
			classType = 1;
			break;
		case "land":
			classType = 2;
			break;
		case "commercial":
			classType = 3;
			break;
		case "multi-family":
			classType = 4;
			break;
        case "multifamily":
            classType = 4;
            break;
		case "waterfront":
			classType = 1;
			isWaterfront = "true"
			break;
	}
	return [ classType, isWaterfront ];
}

// All search inits get the same setup
var setSearch = function(searchid)
{
	searchIter++;
	isSearching = true;
	searchid ? $('intMLSId').set('value',searchid) : 0;
	$('divResults').setStyle('display','none');
	$('divResults').set('html','');
	$('divError').setStyle('display','none');
	$('divWaitMessage').set('html','Please wait while we are retrieving the information...');
	$('divWaiting').setStyle('display','');
	var myRequest = $clear(myRequest);	// Stop the previous AJAX?
}

// All search success get the same setup
var setSuccess = function(html)
{
	searchIter++;
	isSearching = false;
 	$('divWaiting').setStyle('display','none'); 
	$('divError').setStyle('display','none');			
	$('divResults').set('html',html);
	$('divResults').setStyle('display','');
}

// All search error get the same setup
var setError = function()
{
	searchIter++;
	isSearching = false;
	$('divWaiting').setStyle('display','none'); 
	$('divError').setStyle('display','');
}

// Wait Message processor to make sure the current search is still happening.
var myWaitMessage=function(message,iteration){if(searchIter==iteration){$('divWaitMessage').set('html',message);}}

// Wait Message handler - takes an array of messages & seconds to wait between messages.
var handleWaitMessages = function(messList,seconds)
{
	var delay = 0;
	$each(messList,function(item){
		if (item != ''){ delay += seconds * 1000; setTimeout("myWaitMessage('" + item + "'," + searchIter + ")",delay); }
	});
}

// Homepage Search Function
var initSearch = function() {
    if ($('type'))	// Is the search box there (check "type" to find out)
    {
        var strURL = '/search.aspx?';
        strURL += 'search=' + encodeURI(($('searchtype') ? $('searchtype').get('value') : 'basic')); 	// If searchtype, use it. Otherwise, 'basic'

        // Only add parameters that matter
        if ($('city')) {
            var testingcity = (encodeURI(($('city').getSelected()[0].get('value') + '').replace(/ /g,""))); //Strip all spaces w/ replace
            strURL += $('city').getSelected()[0].get('value') != 'all' ? '&city=' + testingcity : '';
        }
        else { strURL += '&city='; }
        strURL += '&type=' + $('type').get('value');
        strURL += $('min_price').getSelected()[0].get('value') != 0 ? '&minprice=' + $('min_price').getSelected()[0].get('value') : '';
        strURL += $('max_price').getSelected()[0].get('value') != 0 ? '&maxprice=' + $('max_price').getSelected()[0].get('value') : '';
        strURL += $('min_bedrooms').getSelected()[0].get('value') != '' ? '&bed=' + $('min_bedrooms').getSelected()[0].get('value') : '';
        strURL += $('min_bathrooms').getSelected()[0].get('value') != '' ? '&bath=' + $('min_bathrooms').getSelected()[0].get('value') : '';
        strURL += $('lot_size').getSelected()[0].get('value') != '' ? '&lotsize=' + $('lot_size').getSelected()[0].get('value') : '';
        strURL += $('square_footage').getSelected()[0].get('value') != '' ? '&sqft=' + $('square_footage').getSelected()[0].get('value') : '';
        strURL += $('intMLSId').get('value') != '' ? '&id=' + $('intMLSId').get('value') : '';

        // Tack on the randomstring for cache management
        strURL += '&searchid=' + encodeURI(randomString(8));

        // Make it happen - change the page
        document.location = strURL;
    }
}

var handleSearch = function() {
    if ((document.location + '').search('contact.aspx') != -1)	// Are we on the contact page?
    {
        return true;
    }
    else {
        if ((document.location + '').search('search.aspx') != -1)	// Are we on the search page?
        {
            (qs.contains('agentid') && isNumeric(qs.get('agentid'))) ? hmSearchAgent(qs.get('agentid'), qs.get('record', 1)) : 0; // Agent Search
            (qs.contains('search') || qs.contains('id')) ? hmSearchProcess() : 0; // Basic or advanced Search
            if (!qs.contains('search') && !qs.contains('agentid') && qs.contains('type'))	// Type Search (sidebar link)
            {
                var typeArr = getClassType(qs.get('type'));
                hmSearchType(typeArr[0], typeArr[1], qs.get('record'));
            }
        }
        else {
            // Not the search page, initialize the search.
            if ($('agentid') && isNumeric($('agentid').value)) {
                hmSearchAgentPage($('agentid').value, qs.get('record', 1)); // Agent Page Search
            }
            else {

                if ($('intMLSId')) {
                    if ($('intMLSId').get('value') != '') {
                        if (isNumeric($('intMLSId').get('value'))) {
                            initSearch();
                        }
                        else	// ID has a value, but isn't a number - alert.
                        {
                            alert('Please enter a valid MLS Id.');
                        }
                    }
                    else {
                        initSearch();
                    }
                }
                
            }
        }
        return false;
    }
};

// Search Functions
var hmSearchProcess = function() {
    var classnum = 1;
    if (qs.contains('type') && qs.get('type') != '') {
        var typeArr = getClassType(qs.get('type'));
        classnum = typeArr[0];
    }

    //alert('/mls/c21nason.aspx?fn=search&broker=' + $('brokerid').value + '&id=' + qs.get('id','') + '&record=' + qs.get('record',1) + '&class=' + classnum + '&search=' + qs.get('search','basic') + '&city=' + encodeURI(qs.get('city','')) + '&type=' + qs.get('type','') + '&minprice=' + qs.get('minprice',0) + '&maxprice=' + qs.get('maxprice',0) + '&bed=' + qs.get('bed','') + '&bath=' + qs.get('bath','') + '&lotsize=' + qs.get('lotsize','') + '&sqft=' + qs.get('sqft','') + "&searchid=" + encodeURI(qs.get('searchid','')) );

    setSearch();
    var myfn = 'search';
    if (qs.get('id', '') != '') {
        myfn = 'getlistingbyid';
    }
    var myRequest = new Request
	({
	    method: 'get',
	    url: '/mls/c21nason.aspx',
	    onSuccess: function(html) {
	        setSuccess(html);
	        makeCarousel();
	    },
	    onFailure: function() {
	        setError();
	    }
	}).get({
	    'fn': myfn,
	    'search': qs.get('search', 'basic'),
	    'broker' : '' + $('brokerid').value,
	    'id': qs.get('id', ''),
	    'record': qs.get('record', 1),
	    'class': classnum,
	    'city': encodeURI(qs.get('city', '')),
	    'type': qs.get('type', ''),
	    'minprice': qs.get('minprice', 0),
	    'maxprice': qs.get('maxprice', 0),
	    'bed': qs.get('bed', ''),
	    'bath': qs.get('bath', ''),
	    'lotsize': qs.get('lotsize', ''),
	    'sqft': qs.get('sqft', ''),
	    'searchid': encodeURI(qs.get('searchid', ''))
	});

    handleWaitMessages(['Connecting to MLS Database...', 'Querying server...', 'Downloading results...'], 2);
}

var hmSearchAgent = function(agentid,record)
{
	//alert('/mls/c21nason.aspx?fn=getlistingsbyagent&broker=' + $('brokerid').value + '&agent=' + agentid + "&record=" + record);

	if(isSearching == false)
	{
		setSearch();
		var myRequest = new Request
		({
			method: 'get',
			url: '/mls/c21nason.aspx',
			onSuccess: function(html)
			{
				setSuccess(html);
			},
			onFailure: function()
			{
				setError();
			}
		}).get({
			 'fn' : 'getlistingsbyagent', 
			 'broker' : '' + $('brokerid').value,
			 'agent' : agentid,
			 'record' : record
		});
		handleWaitMessages([ 'Connecting to MLS Database...','Querying server...','Downloading results...' ],2);
	}
}

var hmSearchAgentPage = function(agentid, record) {
    //alert('/mls/c21nason.aspx?fn=getlistingsbyagentpage&broker=' + $('brokerid').value + '&agent=' + agentid + "&record=" + record);

    if (isSearching == false) {
        setSearch();
        var myRequest = new Request
		({
		    method: 'get',
		    url: '/mls/c21nason.aspx',
		    onSuccess: function(html) {
		        setSuccess(html);
		    },
		    onFailure: function() {
		        setError();
		    }
		}).get({
		    'fn': 'getlistingsbyagentpage',
		    'broker' : '' + $('brokerid').value,
		    'agent': agentid,
		    'record': record
		});
        handleWaitMessages(['Connecting to MLS Database...', 'Querying server...', 'Downloading results...'], 2);
    }
}

var hmSearchType = function(classType,isWaterfront,record)
{
	var recnum = record ? record : 1;
	
	//alert('/mls/c21nason.aspx?fn=getlistingsbyclass&broker=' + $('brokerid').value + '&class=' + classType + '&water=' + isWaterfront + '&record=' + recnum);
	
	if(isSearching == false)
	{
		setSearch();
		
		var myRequest = new Request
		({
			method: 'get',
			url: '/mls/c21nason.aspx',
			onSuccess: function(html)
			{
				setSuccess(html);
			 },
			 onFailure: function()
			 {
				 setError();
			 }
		}).get({
			 'fn' : 'getlistingsbyclass', 
			 'broker' : '' + $('brokerid').value,
			 'class' : classType + '',
			 'water' : isWaterfront,
			 'record' : recnum
		});
		handleWaitMessages([ 'Connecting to MLS Database...','Querying server...','Downloading results...' ],2);
	}
}

// Persistant Variables, functions
var qs = new Querystring();
var pros = 0;

// Variables for handling the search messages
var isSearching = false;
var searchIter = 0;
var myRequest = 0;

// DOM Ready
window.addEvent('domready', function() {

	// Do nothing unless there is a broker ID
	if ($('brokerid')) {

	    if ($('proflist')) {
	        pros = new Fx.Slide('proflist');
	        if (getCookie('profstate') != 'show') {
	            pros.hide();
	        }
	        $('proflink').addEvent('click', function() {
	            this.blur();
	            if (pros.open) { setCookie('profstate', 'hide', 1); }
	            else { setCookie('profstate', 'show', 1); }
	            pros.toggle();
	        });
	    }
	
	    if ($('basicsearch'))	// Look for search button (on home page)
	    {
	        $('basicsearch').addEvent('click', function() { handleSearch(); });
	    }
	
	    if ($('agentid')) {
	        handleSearch();
	    }
	
	    // If we're on the search page
	    if ((document.location + '').search('search.aspx') != -1) {
	        handleSearch();
	
	        if (!Browser.Engine.trident)	// Fix pagination around IE padding glitch
	        {
	            var oLink = document.createElement("link")
	            oLink.href = "/Stylesheets/circie.css";
	            oLink.rel = "stylesheet";
	            oLink.type = "text/css";
	            document.body.appendChild(oLink);
	        }
	    }
	}

});