/*
@note again, please do not delete development code unless code is in
		version control and declared to be production
		you do not save (bandwidth or space) anything here, it is
		only making remembering things difficult during development.
@dependencies: prototype.js, cookie.js, scriptaculous.js
*/

// to avoid redundant mapping for the cookie object in functions that need it
function getFilterRequestCookieMap() {
	var frobj = {_lt:'lat',_lg:'long',_ml:'miles',_pn:'price_min',_px:'price_max',_bd:'beds',_bt:'baths',_fr:'for',_oh:'openhouse'};
	return frobj;
}

// to avoid redundant mapping for the cookie object in functions that need it
function getRequestShowingCookieMap() {
	var udobj = {_n:'name',_e:'email',_p:'phone',_r:'realtor',_k:'key'};
	return udobj;
}

function initCookieJar() {
	if ( typeof jar == 'undefined' ) {
		jar = new CookieJar({ expires:3600, path: '/' });
	}
}

/* start of imported js equivalent of php functions */
function function_exists( function_name ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Steve Clay
    // +   improved by: Legaev Andrey
    // *     example 1: function_exists('isFinite');
    // *     returns 1: true
 
    if ( typeof function_name == 'string' ) {
        return ( typeof window[function_name] == 'function' );
    } else {
        return ( function_name instanceof Function );
    }
}

function number_format( number, decimals, dec_point, thousands_sep ) {
	// http://kevin.vanzonneveld.net
	// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +	 bugfix by: Michael White (http://crestidg.com)
	// +	 bugfix by: Benjamin Lupton
	// +	 bugfix by: Allan Jensen (http://www.winternet.no)
	// +	revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// +	 bugfix by: Howard Yeend
	// *	 example 1: number_format(1234.5678, 2, '.', '');
	// *	 returns 1: 1234.57	 
 
	var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
	var d = dec_point == undefined ? "." : dec_point;
	var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
	var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
/* end of imported js equivalents of php functions */

function meter_to_mile( meter ) {
	// meter to miles conversion constant
	var mtomi = 0.00062137119; 

	return meter * 0.00062137119;
}

function activateListView() {
	$('link-tab-list').blur();
	$('link-tab-list').down('img').src = "img/button-tab-list-active.png";
	$('link-tab-item').down('img').src = "img/button-tab-item-inactive.png";
	$('property-view').hide();
	$('property-list').appear();

	return false;
}
	
function activateItemView() {
	$('link-tab-item').blur();
	$('link-tab-item').down('img').src = "img/button-tab-item-active.png";
	$('link-tab-list').down('img').src = "img/button-tab-list-inactive.png";
	$('property-list').hide();
	$('property-view').appear();

	return false;
}
	
function activateMapView() {
	$('link-tab-map').blur();
	$('link-tab-direction').down('img').src = "img/tab-directions-inactive.png";
	$('link-tab-map').down('img').src = "img/tab-map-active.png";
	$('property-map').appear();
	$('property-direction').hide();
	$('map-details').appear();
	setStatusFromCookie();

	return false;
}
	
function activateDirectionView() {
	$('link-tab-direction').blur();
	$('link-tab-direction').down('img').src = "img/tab-directions-active.png";
	$('link-tab-map').down('img').src = "img/tab-map-inactive.png";
	$('property-map').hide();
	$('property-direction').appear();
	$('map-details').hide();
	setStatusFromCookie();

	return false;
}

function activateCallButton() {
	if ( Prototype.Browser.WebKit ) {
		$('contact-number').setAttribute('href', 'tel:7038881505');
		$('contact-number').down('img').src = 'img/button-call.png';
	}
}

function hideFakeLoader() {
	$('fakeloader').hide();
}

function checkILRequestedView() {
	//hideFakeLoader();
	var a = document.location.hash;
	switch (a) {
		case '#top':
			break;
		case '#list_view':
			activateListView();
			break;
		case '#item_view':
		default:
			activateItemView();
			break;
	}
}

function checkDMRequestedView() {
	//hideFakeLoader();
	var a = document.location.hash;
	switch (a) {
		case '#top':
			break;
		case '#direction':
			activateDirectionView();
			break;
		case '#map':
		default:
			activateMapView();
			break;
	}
}

/*
This is the constructRoute function currently inside index.php

@note not yet used, being abstracted or recoded for general use.
		furthermore, jp, do not delete development notes unless
		code is in version control system and declared to be production
*/
function mapPointToPointRoute( map, source, destination ) {
	var route = new Array();
	route[0] = {lat: source.lt, lng: source.lg};
	route[1] = {lat: destination.lt, lng: destination.lg};

	for ( var i=0; i<route.length; i++ ) {
		var point = new GLatLng(route[i]['lat'], route[i]['lng']);
		var j = geocoords.length;
		geocoords[j] = point;
	}

	gDrxn = new GDirections(map, 'property-direction');
	gDrxn.loadFromWaypoints(geocoords, { getSteps:true, preserveViewport:true });
	GEvent.addListener(gDrxn, "error", function() {
		//$('buffer').update('Route Request failed: ' + gDrxn.getStatus().code);
	});
	GEvent.addListener(gDrxn, "load", function() {
		var directions;
		for (i=0; i<gDrxn.getNumRoutes(); i++) {
			var steps = '';
			var r = gDrxn.getRoute(i);
			var numsteps = r.getNumSteps(i);
			for(j=0; j<numsteps; j++) {
				var s = r.getStep(j);
				steps += '<li>' + s.getDescriptionHtml() + '</li>';
			}
			steps = '<ul class="route-instructions">' + steps + '</ul>';
	
			directions += steps;
		}
	});
}

function buildMapLocationURI( src_data, dst_data ) {
	var urivars = { o: src_data.listingkey, d: dst_data.listingkey };
	var lnk = '';

	for ( var i in urivars ) {
		if ( urivars[i] ) { lnk += i + '=' + urivars[i] + '&'; }
	}

	var maplink = 'map_direction.php?' + lnk;

	return maplink;
}

function buildPropertySummary( data ) {
	var head;
	var summary = '';
	var currency = '$';
	var is = ' / ';

	if ( !data.fullstreetaddress.empty() )
		head = '<h2>' + data.fullstreetaddress + ' <span class="mls-number">(' + data.listingid + ')</span></h2>';
	if ( !data.listprice.empty() )
		summary += currency + number_format(data.listprice, 2, '.', ',');
	if ( !data.beds.empty() )
		summary += is + number_format(data.beds, 0) + ' Beds';
	if ( !data.baths.empty() )
		summary += is + number_format(data.baths, 0) + ' Baths';
	if ( !data.type.empty() )
		summary += is + data.type;

	return head + '<p>' + summary + '</p>';
}

function buildPropertyDetails( data ) {
	var details = {listingid:'MLS #',heating:'Heating',cooling:'Cooling',community:'Community',county:'County',listofficename:'Listed By'};
	var content = '';
	for( var i in details ) {
		if ( data[i] ) {
			content += '<dt>' + details[i] + '</dt>';
			content += '<dd>' + data[i] + '</dd>';
		}
	}

	return '<dl>' + content + '</dl>';
}

function buildPropertyComments( data ) {
	var content = '';
	if ( data['internetremarks'] ) {
		content  = '<h3>Comments</h3>';
		content += '<p>' + data['internetremarks'] + '</p>';
	}

	return content;
}

function buildPropertyAdditionalInfo( data ) {
	var details = {yearbuilt:'Year Built',style:'Style',lotareaacre:'Lot Area (acre)'};
	var content = '<h3>Additional Info</h3><dl>';
	for ( var i in details ) {
		if ( data[i] ) {
			content += '<dt>' + details[i] + '</dt>';
			content += '<dd>' + data[i] + '</dt>';
		}
	}
	content += '</dl>';

	return content;
}

/* @todo deprecate */
function buildPropertyImage( data ) {
	var width = 280;
	var img = '<h3>Pictures</h3>';

	// listpicture2url appears to be a very small thumbnail
	if ( data['listpicture3url'] != '' ) {
		img += '<img src="'+data['listpicture3url']+'" width="'+width+'" />';
	}

	return img;
}

function updatePropertyInfo( _index ) {
	$('location-map').down('a').href = buildMapLocationURI( prop[0], prop[_index] );
	$('location-distance').update(prop[_index].distanceFromLocationMiles);
	$('item-summary').update(buildPropertySummary(prop[_index]));
	$('item-details').update(buildPropertyDetails(prop[_index]));
	$('item-comments').update(buildPropertyComments(prop[_index]));
	$('item-more_info').update(buildPropertyAdditionalInfo(prop[_index]));
	$('item-more_img').update(buildPropertyImage(prop[_index]));
}

function setItemCurrentIndex( id ) {
	activateItemView();

	crsl.scrollTo( id );
}

function setLocationStatus( placemark ) {
	$('status').update('<p>' + placemark.address + '</p>');

	initCookieJar();

	if ( typeof jar != 'undefined' ) {
		var stts = jar.get('stts');
		if ( stts != null ) {
			var new_stts = {loc: placemark.address, lt: stts.lt, lg: stts.lg};
		} else {
			var new_stts = {loc: placemark.address};
		}
		jar.put('stts', new_stts);
	}
}

function clearLocationStatus( x ) {
	$('status').update('<p>. . .</p>');
}

// use only where google map and reverse geocoder has been initialized 
function reverseLocationLookup( lat, lng ) {
	if ( !function_exists('GLatLng') ) { return false; }

	if ( !rg ) { return false; }
	var point = new GLatLng(lat, lng);
	rg.reverseGeocode(point);
	GEvent.addListener(rg, "load", setLocationStatus);
	GEvent.addListener(rg, "error", clearLocationStatus);
	if ( typeof jar != 'undefined' ) {
		var stts = jar.get('stts');
		if ( stts == null ) {
			stts = {lt:lat, lg:lng};
		} else {
			stts.loc = stts.loc;
			stts.lt = lat;
			stts.lg = lng;
		}
		jar.put('stts', stts);
	}
}

function updateOrientation() {
	var pagewrap = $('page-wrap');
	pagewrap.className = 'portrait';
	
	var orientation = window.orientation;
	switch(orientation) {
		case 0:
			pagewrap.className = 'portrait';
			break;	

		case 90:
		case -90:
			pagewrap.className = 'landscape';
			break;
	}
	if ( !setStatusFromCookie() ) {
		clearLocationStatus();
	}

	initCookieJar();

	if ( typeof jar != 'undefined' ) {
		var pathname = document.location.pathname;
		var inRequestShowing = pathname.match(/\/request_showing.php/,'');
		// google map is not initialized here hence reverse
		// geocoder is not available if we are in the request_showing.php page
		if ( inRequestShowing == null ) {
			var loc = jar.get('sc');
			if ( loc != null  ) {
				reverseLocationLookup( loc.lt, loc.lg );
			}
		}
	}
}

function loadRequestShowingCookie() {
	initCookieJar();

	var udobj = getRequestShowingCookieMap();
	var ud = jar.get('ud');
	if ( ud == null ) {
		// set form field values to null, since no cookie value is found
		for ( var i in udobj ) { $(udobj[i]).value = null; }
		return false;
	}

	for ( var i in udobj ) {
		var d = unescape(ud[i]);
		if ( d == 'undefined' ) { $(udobj[i]).value = null; }
		else { $(udobj[i]).value = d; }
	}

	return true;
}

function loadFilterSettings() {
	initCookieJar();

	var frobj = getFilterRequestCookieMap();
	var fr = jar.get('fr');
	if ( fr == null ) {
		// set form field values to null, since no cookie value is found
		for ( var i in frobj ) { $(frobj[i]).value = null; }
		return false;
	}

	for ( var i in frobj ) {
		var id = frobj[i];
		var val = unescape(fr[id]);
		if ( $(id).readAttribute == 'checkbox' ) {
			if ( val ) {
				$(id).writeAttribute('checked', 'checked');	
				$(id).writeAttribute('value', val);
			} else {
				$(id).writeAttribute('checked', null);	
			}
		}
		if ( val != 'undefined' ) {
			$(id).value = val;
		}
	}

	return true;
}

/* 
 * loads unique id of property being requested
 * out of the current index cookie information
 */
function setRequestShowingKey() {
	initCookieJar();

	var ci = jar.get('ci');
	if ( ci == null ) { return false; }

	$('key').value = ci.dst;
	return true;
}

function validateFilterRequestForm( form_id ) {
	var filterform = $(form_id);
	var submitbutton = filterform.down('button#submit-button');
	var frobj = getFilterRequestCookieMap();
	var err_class = 'hasError';
	var err_info = 'errInfo';
	var has_err = false;

	var fd = filterform.firstDescendant();
	if ( fd.hasClassName(err_info) ) { fd.remove(); }

	submitbutton.update('validating...');
	for ( var i in frobj ) {
		if ( $(frobj[i]).hasClassName(err_class) ) {
			$(frobj[i]).removeClassName(err_class); // clear error to avoid redudant class entry
		}
		if ( frobj[i] == 'for' ) { continue; }
		if ( frobj[i] == 'price_max' ) {
			var px = parseInt($('price_max').value);
			var pn = parseInt($('price_min').value);
			if ( px < pn ) {
				has_err = true;
				$('price_max').addClassName(err_class);
			}
		}
		if ( !$(frobj[i]).value ) {
			has_err = true;
			$(frobj[i]).addClassName(err_class);
		}

		var h = i;
	}

	if ( has_err ) {
		new Insertion.Top(form_id, '<p class="'+err_info+'">Problems were found with the highlighted items!</p>');
		submitbutton.update('ReSubmit');
		return false;
	}

	return true;
}

function validateRequestShowingForm( form_id ) {
	var requestform = $(form_id);
	var submitbutton = requestform.down('button#submit-button');
	var udobj = getRequestShowingCookieMap();
	var d = new Object();
	var err_class = 'hasError';
	var err_info = 'errInfo';
	var has_err = false;
	var emailRegEx = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	var fd = requestform.firstDescendant();
	if( fd.hasClassName(err_info) ) { fd.remove(); }

	submitbutton.update('validating...');
	for ( var i in udobj ) {
		if ( $(udobj[i]).value ) {
			if ( $(udobj[i]).hasClassName(err_class) ) {
				$(udobj[i]).removeClassName(err_class);
			}
		} else {
			has_err = true;
			$(udobj[i]).addClassName(err_class);
		}
		if ( udobj[i] == 'email' && !emailRegEx.exec($(udobj[i]).value) ) {
			has_err = true;
			$(udobj[i]).addClassName(err_class);
		}
	}

	if ( has_err ) {
		new Insertion.Top(form_id, '<p class="'+err_info+'">Items highlighted are required!</p>');
		submitbutton.update('ReSubmit');
		return false;
	}

	return true;
}

function setCookieAsMapped( ckey, obj ) {
	var obc = new Object();

	initCookieJar();

	jar.remove(ckey); // clear previous cookie
	for ( var i in obj ) {
		var val = $(obj[i]).value;
		if ( $(obj[i]).readAttribute('type') == 'checkbox' ) {
			if ( $(obj[i]).getValue() ) {
				obc[i] = escape(val);
			}
			continue;
		}
		if ( val ) {
			obc[i] = escape(val);
		}
	}

	return jar.put(ckey, obc);
}

function setRequestShowingCookie() {
	var obj = getRequestShowingCookieMap();
	return setCookieAsMapped( 'ud', obj );
}

function setFilterRequestCookie() {
	var obj = getFilterRequestCookieMap();
	return setCookieAsMapped( 'fr', obj );
}

function submitFilterRequestForm( form_id ) {
	setFilterRequestCookie();
	if ( validateFilterRequestForm(form_id) == false ) {
		return false;
	}
	
	this.submit();
	return true; // synchronous submit
}

function submitRequestShowingForm( form_id ) {
	var showreqform = $(form_id);
	var submitbutton = showreqform.down('button#submit-button');
	if ( validateRequestShowingForm(form_id) == false ) {
		submitbutton.update('ReSubmit');
		return false;
	}

	submitbutton.update('Submitting...');
	alert( form_id );
	return false;

	// construct ajax call parameters
	var frobj = getRequestShowingCookieMap();
	var frparams = new Array;
	for ( var i in frobj ) {
		var e = frobj[i];
		var val = $(e).value;
		if ( val != null ) { frparams[e] = val };
	}

	var url = showreqform.action;
	alert( url );
	new Ajax.Request(url, {
		method: 'post',
		parameters: frparams,
		onSuccess: function(transport) {
			msg = '<p>Successfully submitted your request! You can continue browsing other properties by hitting the "back button" above.</p><p>Thank you!</p>';
			showreqform.update(msg);
		},
		onFailure: function() {
			msg = '<p>An error occurred, we apologize for the inconvenience.</p><p>Please check your entry and try resubmit after a few minutes.</p>';
			showreqform.update(msg);
		}
	});

	return false; // prevent synchronous form submission
}

function setStatusFromCookie() {
	if ( typeof jar == 'undefined' ) { return false; }

	var status = jar.get('stts');
	if ( status == null ) { return false; }

	var placemark = {address: status.loc};
	setLocationStatus(placemark);
	return true;
}

function updateBackButton( where ) {
	var backbutton = $('button-back');

	if ( typeof jar == 'undefined' ) {
		backbutton.remove();
		return false;
	}

	if ( where == 'index' ) {
		var blink = constructFilterRequestLink();

		if ( blink ) {
			backbutton.href = blink;
		} else {
			backbutton.remove();
		}
	}
}

function constructFilterRequestLink() {
	var frobj = getFilterRequestCookieMap();
	var fr = jar.get('fr');
	if ( fr == null ) { return false; }

	var counter = 0; // counter
	var blink = '';
	for ( var i in frobj ) {
		var e = frobj[i];
		var c = escape(fr[e]);
		if ( c == 'undefined' ) { continue; }

		if ( counter > 0 ) { blink += '&'; } else { blink += '?'; }
		if ( c ) { blink += e + '=' + c; }
		counter++;
	}

	var frlink = '';
	if ( blink ) {
		frlink = 'index.php' + blink;
	}

	return frlink;
}

function initFilterRequestCookie( data ) {
	var frobj = getFilterRequestCookieMap();
	var d = new Object();
	for( var i in frobj ) {
		var e = frobj[i];
		if ( data[e] ) {
			d[e] = data[e];
		}
	}

	if ( typeof jar == 'undefined' ) {
		return false;
	}

	jar.put('fr', d);
}

function setListViewsDistanceFromLocation() {
	if ( prop == null ) { return false; }

	for ( var i in prop ) {
		$(prop[i]['listingkey']+'_dst').update(prop[i]['distanceFromLocationMiles']);
	}
}

function requestMoreMedia( listingkey ) {
	var mmediaholder = $('item-more_img');

	new Ajax.Request('mmedia.php', {
		method: 'post',
		parameters: {lk: listingkey},
		onSuccess: function(transport) {
			if ( transport.responseText != '' )
				mmediaholder.update('<h3>Pictures</h3>' + transport.responseText);
		},
		onFailure: function() {
			mmediaholder.remove();
		}
	});
}
