var daWidgets = [];
var widg = 0;
var disWindow = null;
var daTimer = null;
var moveTimer = null;

window.addEvent('domready', function(){

	// Now only contains popup window functions
	initControls();

	// Activate all date pickers
	$$('input.DatePicker').each( function(el){
		new DatePicker(el);
	});
	$$('#breadcrumbs .bookmarks').each( function(el){ insertBookmarks(el); });

	// Neighborhood and MyPlace pages
	$$('.widget').each( function(el){
		daWidgets[widg] = new Widget(el);
		widg++;
	});

	// Bookmark links on property page
	if($('morelist') && $$('#propTop .more')){
		moreBookmarks();
	}

	if($$('.tooltip')){
		makeTips('.tooltip');
	}

	// Recent Newsletter on Property Overview
	// And Send Text for Managers
	if($('ajaxme')){
		var target = $('ajaxme');
		var url = target.getAttribute('title');
		target.setAttribute('title', '');
		new Ajax(url, {
			method: 'get',
			update: target,
			evalScripts: true
		}).request();
	}

	if($('snagimages')){
		var snagger = new ImageSnagger($('snagimages'));
	}

	if($('multiPropMap')){
		multiPropMap('multiPropMap');
	}

	// Property Track
	$$('meta').each( function(el){
		if (el.getProperty('name') == 'track'){
			PropertyTracking(el);
		}
	});

	// Google Analytics
	if(typeof urchinTracker == "function"){
		_uacct = "UA-356557-4";
		urchinTracker();
	}
	
});

// Uses mootools

function insertBookmarks(el){
	var url = escape(window.location.href);
	var title = escape(document.title);
	new Ajax('/bookmarkme.html', {
		method: 'get',
		update: el,
		onComplete: function(){
			el.getElements('a').each( function(link){
				link.href = link.href.replace('[[[url]]]', url).replace('[[[title]]]', title);
			});
		}
	}).request();
}


function PropertyTracking(el){

	var params = {}

	// give it the base track type
	params['t'] = 'v';

	// add in the property id
	if (el.getProperty('content')) {
		params['p'] = el.getProperty('content');
	}

	// check for cookie tokens, and add them in
	if (Cookie.get('visitor')) {
		params['cv'] = Cookie.get('visitor');
	}

	// tack on the adwords tracking token
	if (queryString('ut') != 'false') {
		params['ut'] = queryString('ut');
	}

	// throw in the referrer
	if (document.referrer != '') {
		params['ref'] = document.referrer;
	}

	// send the POST request
	new Ajax(('/apartment_finder/track.aspx'), { method: 'post', data: params }).request();
}


function reloadDefault(w){
	daWidgets[w].loadDefaults();
}

var Timer = new Class({

	initialize: function(dis){
		// set target as the input field
		this.target = $(dis);
		// Get the move-out date from the p
		var origin = $('moveOutTime');
		var dthen = new Date(origin.innerHTML);
		var dnow = new Date();
		// the time is only figured once, then counts down
		var ddiff = new Date(dthen-dnow);
		var secs = Math.floor(ddiff.valueOf()/1000);
		// shows/hides the content
		if (!origin.hasClass('hideme')) origin.addClass('hideme');
		if (this.target.hasClass('hideme')) this.target.removeClass('hideme');
		this.update(secs);
	},


	update: function(secs){
		// subtract one second
		secs = (secs - 1);
		// check if the times up
		if (secs < 0) {
			this.target.value = 'Now!';
			return;
		}
		// create text string
		var dd = this.calcNum(secs,86400,100000);
		var dh = this.calcNum(secs,3600,24);
		var dm = this.calcNum(secs,60,60);
		var ds = this.calcNum(secs,1,60);

		var displayStr = dd + ' days, ' + dh + ':' + dm + ':' + ds;
		this.target.value = displayStr;

		// 990ms to allow for processor time
		moveTimer = setTimeout("daTimer.update(" + secs + ")", 990);
	},


	calcNum: function(secs, num1, num2){
		// makes a string of the calculated number
		var s = ( (Math.floor(secs/num1)) % num2 ).toString();
		// add zero if necessary
		if (s.length < 2){
			s = "0" + s;
		}
		return s;
	}

});


var Widget = new Class({


	initialize: function(dis){
		// Set the element it refers to
		this.ref = dis;

		// If it's the map widget, send it elsewhere
		if (this.ref.hasClass('locations')){
			this.privacyLinks();
			new MapWidget(this.ref);

		}
		else if (this.ref.hasClass('viewer'))
		{
			var target = this.ref.getElementsBySelector('.content')[0];

			if (window.location.hash) {

				window.scroll(0, 500);

				var url = '/fun/' + window.location.hash.split('#')[1] + '.html';
				new Ajax(url, {
					method: 'get',
					update: target,
					evalScripts: true
				}).request();
			}
		}
		else
		{
			this.activate();
			this.loadDefaults();
		}
	},


	// for things in the head and foot divs
	activate: function(){
		// Sets the current date in the Live For Fun section
		if (this.ref.hasClass('viewer')){
			this.ref.getElementsBySelector('.date')[0].innerHTML = showDate();
		}
		this.tabLinks();
		this.startLinks('.addme a');
		this.changeLinks();
		this.privacyLinks();

		// Live for Fun links
		if($$('.library')){
			this.startLibrary('.library a');
		}
	},


	// for things inside the content div
	activateContent: function(){
		this.startLinks('.paging td a');
		this.startLinks('.calendar a');
		this.startLinks('.in');

		this.sendAndReload();

		// editing mode submit button
		this.editSubmit();

		// General popup links, like for images
		this.popupLinks();

		// Select where you live popup
		this.selectProp();

		// for deleteme class - confirm and reload
		this.deleteLinks();

		this.doTips();
		this.labelHovering();

		// activate all date pickers
		this.ref.getElementsBySelector('input.DatePicker').each( function(el){
			new DatePicker(el);
		});

		this.ref.getElementsBySelector('.charcount').addEvent('keyup', function(event){
			event = new Event(event).stop();
			charCount('text_new', 'text_countbox', 150);
		});

		// The countdown move-out timer
		if(this.ref.getElementById('moveTimer')){
			var dat = this.ref.getElementById('moveTimer');
			if( moveTimer || moveTimer != null ){
				clearTimeout(moveTimer);
				daTimer = null;
				moveTimer = null;
			}
			daTimer = new Timer(dat);
		}
	},



	// grabs the href and loads it in the content
	startLinks: function(selector){
		var pa = this;
		this.ref.getElementsBySelector(selector).each(function(el){
			el.removeEvents();
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				var url = el.getProperty('href');
				pa.grabJunk(url);
			});
		});
	},


	// sends the link and reloads the defaults
	sendAndReload: function(){
		var pa = this;
		this.ref.getElementsBySelector('.reload').each(function(el){
			el.removeEvents();
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				var url = el.getProperty('href');
				url = addRandomStuff(url);
				new Ajax(url, {
					method: 'get',
					onComplete: function(){
						pa.loadDefaults();
					}
				}).request();
			});
		});
	},


	tabLinks: function(){
		var pa = this;
		this.ref.getElementsBySelector('.head li a').each(function(el){
			el.removeEvents();
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				// Check if foot link is missing
				pa.ref.getElementsBySelector('.foot .hideme').removeClass('hideme');
				// move the active tab
				pa.ref.getElementsBySelector('.head .active').removeClass('active');
				el.parentNode.addClass('active');
				// Get the address to pull the information
				var url = el.getProperty('href');
				// Make the call
				pa.grabJunk(url);
			});
		});
	},


	popupLinks: function(){
		var pa = this;
		this.ref.getElementsBySelector('.popup').each(function(el){
			el.removeEvents();
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				var url = el.getProperty('href');
				url = addRandomStuff(url);
				makeAvgPopup(url);
			});
		});
	},


	privacyLinks: function(){
		var pa = this;
		// send ajax to change status and switch active class if successful
		this.ref.getElementsBySelector('.foot .privacy a').each(function(el){
			// Send request
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				var url = el.getProperty('href');
				url = addRandomStuff(url);
				new Ajax(url, {
					method: 'get',
					onComplete: function(){
						// changes the status if successful
						pa.ref.getElementsBySelector('.foot .privacy li.active').removeClass('active');
						el.getParent().addClass('active');
					}
				}).request();
			});
		});
	},


	// "change this" links in the myplace footers
	changeLinks: function(){
		var pa = this;
		var target = this.ref.getElementsBySelector('.content')[0];
		// send ajax to change status and switch active class if successful
		this.ref.getElementsBySelector('.foot .edit').each(function(el){
			// Send request
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				var url = el.getProperty('href');
				url = addRandomStuff(url);
				new Ajax(url, {
					method: 'get',
					update: target,
					evalScripts: true,
					onComplete: function(){
						pa.activateContent();
						el.addClass('hideme');
					}
				}).request();
			});
		});
	},


	// buttons on the editing mode of myplace widgets
	editSubmit: function(){
		var pa = this;
		var target = this.ref.getElementsBySelector('.content')[0];
		var formTarget = this.ref.getElementsBySelector('.content form')[0];

		if( formTarget ){
			// Fix for .Net removing my freakin directory
			var formAction = formTarget.getProperty('action');
			if(formAction.indexOf('/myplace/') != -1){
				formAction.replace(/myplace/,"my_place");
			}
			else if (formAction.indexOf('/my_place/') == -1){
				formAction = '/my_place/' + formAction;
			}
			formTarget.setProperty('action', formAction)
		}

		// send ajax to change status and switch active class if successful
		this.ref.getElementsBySelector('.content .submit').each(function(el){
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				el.disabled = true;
				pa.ref.getElementsBySelector('.spinner').setHTML('<img src="/images/widget/loading.gif" alt="Loading..." />');
				if(el.hasClass('send')){
					formTarget.send({
						onComplete: function(){
							pa.loadDefaults();
						}
					});
				}else if(el.hasClass('stay')){
					formTarget.send({
						update: target,
						onComplete: function(){
							pa.ref.getElementsBySelector('.foot .hideme').removeClass('hideme');
							pa.ref.getElementsBySelector('spinner').empty();
							pa.labelHovering();
						}
					});
				}else{
					pa.loadDefaults();
				}
			});
		});
	},


	// Opens a new window with property selection form
	selectProp: function(){
		var pa = this;
		this.ref.getElementsBySelector('.selectprop').each(function(el){
			el.removeEvents();
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				var url = el.getProperty('href');
				if(disWindow == null || disWindow.closed){
					disWindow = window.open(url, null, "height=500,width=700,menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=yes");
				}else{
					disWindow.location.href = url;
					disWindow.focus();
				}
			});
		});
	},


	// Confirms, sends the get, then reloads default
	deleteLinks: function(){
		var pa = this;
		this.ref.getElementsBySelector('.deleteme').each(function(el){
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				if(window.confirm("This item will be removed. Are you sure?")){ 
					var url = el.getProperty('href');
					url = addRandomStuff(url);
					new Ajax(url, {
						method: 'get',
						onComplete: function(){
							pa.loadDefaults();
						}
					}).request();
				}else{
					return false;
				}
			});
		});
	},


	labelHovering: function(){
		var pa = this;
		this.ref.getElementsBySelector('.textsend label').each(function(el){
			var field = $(el.getProperty('for'));
			if (field.value === ""){
				el.removeClass('hideme');
			}
			field.addEvent('focus', function(event){ el.addClass('hideme'); });
			field.addEvent('blur', function(event){
				if(field.value === ""){
					el.removeClass('hideme');
				}
			});
		});
	},


	// This is for the Live for Fun section
	startLibrary: function(selector){
		var target = $$('.viewer .content')[0];
		this.ref.getElementsBySelector(selector).each(function(el){
			el.removeEvents();
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				var url = el.getProperty('href');
				url = addRandomStuff(url);
				new Ajax(url, {
					method: 'get',
					update: target,
					evalScripts: true,
					onComplete: function(){
						var index = url.lastIndexOf('/');
						var hash = url.substring((index + 1));
						var hash = hash.split('.html')[0];
						window.location.hash = '#' + hash;
					}
				}).request();
			});
		});
	},


	loadDefaults: function(){
		var pa = this;
		// Load the default content
		this.ref.getElementsBySelector('.head li').each( function(el){
			if (el.hasClass('default')){
				pa.ref.getElementsBySelector('.head .active').removeClass('active');
				el.addClass('active');
				var link = el.getElementsByTagName('a')[0];
				var url = $(link).getProperty('href');
				pa.grabJunk(url);
			}
		});
		pa.ref.getElementsBySelector('.foot .hideme').removeClass('hideme');
	},


	grabJunk: function(url, target){
		var pa = this;
		var target = this.ref.getElementsBySelector('.content')[0];
		url = addRandomStuff(url);
		new Ajax(url, {
			method: 'get',
			update: target,
			evalScripts: true,
			onComplete: function(){
				// enables all links for new content
				pa.activateContent();
			}
		}).request();
	},


	doTips: function(){
		var pa = this;
		pa.ref.getElementsBySelector('.calendar .event a').each( function(el){
			new Tips(el, {
				timeOut: 700,
				maxTitleChars: 255,
				maxOpacity: 1
			});
		});
	}


}); // close Widget




var MapWidget = new Class({


	initialize: function(daWidget){
		this.ref = daWidget;
		dis = this;
		var locoptions = $('locoptions')
		var loclink = this.ref.getElementsBySelector('.foot p a')[0];
		document._ymapset=1;

		// activate tab links
		this.ref.getElementsBySelector('.head li a').each(function(el){
			el.removeEvents();
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				dis.ref.getElementsBySelector('.head .active').removeClass('active');
				el.getParent().addClass('active');
				var url = el.getProperty('href');
				target = url.split('#')[1];
				// Hide all content boxes
				dis.ref.getElementsBySelector('.content').addClass('hideme');
				// show the target
				$(target).removeClass('hideme');
				// show the options
				if( target == 'loclist' ){
					locoptions.removeClass('hideme');
					locoptions.style.position = 'static';
					if (loclink && loclink.hasClass('hideme')) loclink.removeClass('hideme');
				} else if( target == 'locmap' ){
					locoptions.removeClass('hideme');
					locoptions.style.position = 'relative';
					if (loclink && loclink.hasClass('hideme')) loclink.removeClass('hideme');
				} else {
					loclink.addClass('hideme');
				}
			});
		});

		// create map - will have to wait for geocoded home to come back
		if(this.ref.getElementById('mapContainer')){
			daMap = null;
			map = null;
			daMap = this.ref.getElementById('mapContainer');
			map = new YMap(daMap);
			// get the info from the list of user-submitted locations
			// should supply the this.homedot
			this.grabLocationData();
			// if they have a home location, send request
			if(this.homedot){

				$('loadme').innerHTML = '<img src="/images/widget/loading.gif" alt="Loading..." />';

				if (this.homedot.latitude && this.homedot.longitude) {
					this.homeloc = new YGeoPoint(this.homedot.latitude, this.homedot.longitude);
					map.drawZoomAndCenter(this.homeloc, 4);
					map.addPanControl();
					map.addZoomLong();
					map.addTypeControl();
					map.disableKeyControls();
					this.createUserMarkers();
					this.activateYahooSearch();
					$('loadme').empty();

				} else {
					var dot = this.homedot;
					adr = dot.streetAddress + ', ' + dot.locality + ', ' + dot.region + ' ' + dot.postalCode;
					map.geoCodeAddress(adr);
					YEvent.Capture( map, EventsList.onEndGeoCode, dis.setHomeLoc );
				}
			}
		}
		this.privacyLinks();
	},

	// Fires after we geocode the address
	setHomeLoc: function(e){
//YLog.print(e.GeoPoint);
		if (e.GeoPoint) {
			dis.homeloc = e.GeoPoint;
			map.drawZoomAndCenter(dis.homeloc, 4);
			map.addPanControl();
			map.addZoomLong();
			map.addTypeControl();
			map.disableKeyControls();
			dis.createUserMarkers();
			dis.activateYahooSearch();
			$('loadme').empty();
		}
	},


	privacyLinks: function(){
		var pa = this;
		// send ajax to change status and switch active class if successful
		this.ref.getElementsBySelector('.foot .privacy a').each(function(el){
			// Send request
			el.addEvent('click', function(event){
				event = new Event(event).stop();
				var url = el.getProperty('href');
				new Ajax(url, {
					method: 'get',
					onComplete: function(){
						// changes the status if successful
						pa.ref.getElementsBySelector('.foot .privacy li.active').removeClass('active');
						el.getParent().addClass('active');
					}
				}).request();
			});
		});
	},


	grabLocationData: function(){
		dis.dots = [];
		this.ref.getElementsBySelector('.content .list li').each( function(el){
			var dot = {};
			el.getElements('*').each( function(newEl){
				switch(newEl.className)
				{
				case 'fn':
					dot.fn = newEl.innerHTML;
					break
				case 'tel':
					dot.tel = newEl.innerHTML;
					break
				case 'street-address':
					dot.streetAddress = newEl.innerHTML;
					break
				case 'extended-address':
					dot.extendedAddress = newEl.innerHTML;
					break
				case 'locality':
					dot.locality = newEl.innerHTML;
					break
				case 'region':
					dot.region = newEl.innerHTML;
					break
				case 'postal-code':
					dot.postalCode = newEl.innerHTML;
					break
				case 'latitude':
					dot.latitude = newEl.innerHTML;
					break
				case 'longitude':
					dot.longitude = newEl.innerHTML;
					break
				case 'cat':
					dot.cat = newEl.innerHTML;
					break
				default:
					break
				}
			});
			if(el.hasClass('home')){
				dis.homedot = dot;
			}else{
				dis.dots.push(dot);
			}
		});
	},


	// only for user-submitted markers
	createMarkerText: function(obj){
		var ttl, phn, adr, zip;
		if(obj.fn){ var ttl = '<h3>' + obj.fn + '</h3>'; }
		if(obj.tel){ var phn = '<p class="phone">' + obj.tel + '</p>'; }
		if(obj.streetAddress){ adr = obj.streetAddress; }
		if(obj.extendedAddress){ adr += ', ' + obj.extendedAddress; }
		if(obj.postalCode){ zip = ' ' + obj.postalCode; }
		return ttl + phn + '<p>' + adr + '</p><p>' + obj.locality + ', ' + obj.region + zip + '</p>';
	},


	createUserMarkers: function(){
		// home location
		var t = this.createMarkerText( this.homedot );
		var m = dis.addNewMarker( this.homeloc, 'house_zone', t);
		map.addOverlay(m);
		// submitted locations
		dis.dots.each( function(el){
			if(el.latitude && el.longitude){
				var p = new YGeoPoint(el.latitude, el.longitude);
			}
			if(el.cat){
				var icon = el.cat;
			}else{
				var icon = 'flag_zone';
			}
			var t = dis.createMarkerText(el);
			var m = dis.addNewMarker( p, icon, t);
			map.addOverlay(m);
		});
	},


	addNewMarker: function(geopoint, icon, win){
		var myImage = new YImage();
		myImage.src = '/images/icons/' + icon + '.png';
		myImage.size = new YSize(30,30);
		myImage.offset = new YCoordPoint(-15,15);
		myImage.offsetSmartWindow = new YCoordPoint(15,15);
		var m = new YMarker(geopoint,myImage);
		m.setSmartWindowColor("blue");
		YEvent.Capture(m, EventsList.MouseClick, function() { m.openSmartWindow(win) });
		return m;
	},


	activateYahooSearch: function(){
		this.ref.getElementsBySelector('.options select').each( function(el){
			el.addEvent('change', function(){
				dis.doYahooSearch();
			});
		});
		dis.doYahooSearch();
	},


	doYahooSearch: function(){
		var query = $('qs').value;
		var radius = $('qr').value;
		map.searchLocal( this.homeloc, query, radius, '10');
		$('loadme').innerHTML = '<img src="/images/widget/loading.gif" alt="Loading..." />';
		YEvent.Capture( map, EventsList.onEndLocalSearch, dis.handleYahooResults );
	},


	handleYahooResults: function(e){
		if (e.Data) {
			// clear old data
			map.removeMarkersAll();
			dis.ref.getElementsBySelector('.content .ys').each( function(el){
				el.getParent().remove();
			});
			// replace the static markers
			dis.createUserMarkers();
			$('loadme').empty();
			// start looping through results
			var n = 0;
			for (var a in e.Data.ITEMS) {
				var l = e.Data.ITEMS[a];
				//YLog.print(l);
				if (l.TITLE) {
					dis.createYahooSearchMarker(l);
					dis.createListItem(l, n);
					n++;
				}
			}
		}
	},


	createListItem: function(l, n){
	// make text
		var ttl = '', phn = '', adr = '', geo = '', cat = '';
		if(l.URL){
			var ttl = '<strong class="fn"><a href="' + l.URL + '" target="_new">' + l.TITLE + '</a></strong>';
		}else{
			var ttl = '<strong class="fn">' + l.TITLE + '</strong>';
		}
		if(l.PHONE){ phn = '<em class="tel">' + l.PHONE + '</em>'; }
		if(l.ADDRESS){ adr += '<span class="street-address">' + l.ADDRESS + '</span>'; }
		if(l.CITY){ adr += ', <span class="locality">' + l.CITY + '</span>'; }
		if(l.STATE){ adr += ', <span class="region">' + l.STATE + '</span>'; }
		if(l.LATITUDE && l.LONGITUDE){ geo = '<div class="geo"><span class="latitude">' + l.LATITUDE + '</span>, <span class="longitude">' + l.LONGITUDE + '</span></div>'; }

/*
		var cats = new Array();
					for (var i = 0; i < l.CATEGORIES.length; i++) {
						if(typeof l.CATEGORIES[i] == 'object'){
							cats.push(l.CATEGORIES[i].ID);
							cats.push(l.CATEGORIES[i].CDATA);
						}
					}
					var cat = cats.join(" : ");
*/
		var t = '<div class="vcard ys">' + ttl + phn + '<div class="adr">' + adr + '</div>' + geo + '</div>';


	// make element
		var unorderedList = this.ref.getElementsBySelector('.content .list')[0];
		if(n % 2 == 0){
			var newLi = new Element('li').setHTML(t).injectInside(unorderedList);
		}else{
			var newLi = new Element('li', {'class': 'alt'}).setHTML(t).injectInside(unorderedList);
		}
	},


	createYahooSearchMarker: function(l){
		var p = new YGeoPoint(l.LATITUDE,l.LONGITUDE);
		if(l.URL){ var ttl = '<h3><a href="' + l.URL + '" target="_new">' + l.TITLE + '</a></h3>'; } else { var ttl = '<h3>' + l.TITLE + '</h3>'; }
		if(l.PHONE){ var phn = '<p class="phone">' + l.PHONE + '</p>'; } else { var phn = ''; }
		var t = ttl + phn + '<p>' + l.ADDRESS + '</p><p>' + l.CITY + ', ' + l.STATE + '</p>';
		var icon = 'flag_zone';
		for (var i = 0; i < l.CATEGORIES.length; i++) {
			if(typeof l.CATEGORIES[i] == 'object'){
				var g = l.CATEGORIES[i].ID;
					if(g == '96925947') icon = 'bank';
					if(g == '96934301') icon = 'bank';
					if(g == '96928068') icon = 'bank';

					if(g == '96926236') icon = 'restaurant';
					if(g == '96926164') icon = 'chinese';
					if(g == '96929155') icon = 'mexican';

					if(g == '96925828') icon = 'movie';
					if(g == '96612100') icon = 'movie';
					if(g == '96927240') icon = 'movie';

					if(g == '96925816') icon = 'nightclub';
					if(g == '96927238') icon = 'nightclub';
					if(g == '96926061') icon = 'nightclub';
					if(g == '96926057') icon = 'nightclub';

					if(g == '96925782') icon = 'school';
					if(g == '96928445') icon = 'school';
					if(g == '96928447') icon = 'school';
					if(g == '96928448') icon = 'school';
					if(g == '96928449') icon = 'school';
					if(g == '96925786') icon = 'school';
					if(g == '96928481') icon = 'school';

					if(g == '96926169') icon = 'coffee';

			}
		}
		var m = dis.addNewMarker( p, icon, t);
		map.addOverlay(m);
	}


}); // close LocalMap


function addRandomStuff(url){
	if (url.indexOf('?') != -1){
		url = url + '&ran=' + Math.floor(Math.random()*1001);
	}else{
		url = url + '?ran=' + Math.floor(Math.random()*1001);
	}
	
	return url;
}

function showDate(){
	var now = new Date();
	var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
	var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
	function fourdigits(number)	{
		return (number < 1000) ? number + 1900 : number;
	}
	return days[now.getDay()] + ", " +
              months[now.getMonth()] + " " +
               date + ", " +
                (fourdigits(now.getYear())) ;
}



// buttons on the editing mode of myplace widgets
function cellitSend(){
	var pa = this;
	var formTarget = this.ref.getElementsBySelector('.content form')[0];

	// send ajax to change status and switch active class if successful
	this.ref.getElementsBySelector('.content .done .submit').each(function(el){

		el.addEvent('click', function(event){
			event = new Event(event).stop();

			if(el.hasClass('send')){
				formTarget.send({
					onComplete: function(){
						pa.loadDefaults();
					}
				});
			}else{
				pa.loadDefaults();
			}

			var dat = pa.ref.getElementsBySelector('.foot .edit')
			if ( dat.hasClass('hideme') ){
				dat.removeClass('hideme');
			}

		});
	});
}


function moreBookmarks(){

	$$('#propTop .more').each( function(el){
		el.removeEvents();
		el.addEvent('click', function(event){
			event = new Event(event).stop();
			var target = $('morelist');
			if(target.style.display == 'none'){
				target.style.display = 'block';
				if(!el.hasClass('active')){
					el.addClass('active');
				}
			}else{
				target.style.display = 'none';
				if(el.hasClass('active')){
					el.removeClass('active');
				}
			}
		});
	});
}



function makeTips(selector){
	new Tips($$(selector), {
		timeOut: 700,
		maxTitleChars: 255,
		maxOpacity: 1
	});
}



function makeAvgPopup(url){
	if(disWindow == null || disWindow.closed){
		disWindow = window.open(url, null, "height=500,width=700,menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=yes");
	}else{
		disWindow.location.href = url;
		disWindow.focus();
	}
}


function multiPropMap(target){

	function addNewMarker(p, t){
		var myImage = new YImage();
		myImage.src = '/images/icons/flag_zone.png';
		myImage.size = new YSize(30,30);
		myImage.offset = new YCoordPoint(-15,15);
		myImage.offsetSmartWindow = new YCoordPoint(15,15);
		var m = new YMarker(p,myImage);
		m.setSmartWindowColor("blue");
		YEvent.Capture(m, EventsList.MouseClick, function() { m.openSmartWindow(t) });
		return m;
	}

	document._ymapset=1;

	var dis = $(target);
	var map = new YMap(dis);
	map.disableKeyControls();

	// geoPoints should be set in the page
	var zoom_center = map.getBestZoomAndCenter(geoPoints);
	map.drawZoomAndCenter( (new YGeoPoint(zoom_center.YGeoPoint.Lon, zoom_center.YGeoPoint.Lat)), zoom_center.zoomLevel);

	for (var i=0; i<locs.length; i++)
	{
		// locations and window texts set in the page
		map.addOverlay(addNewMarker( locs[i], txts[i] ));
	}

	map.addPanControl();
	map.addZoomLong();
	map.addTypeControl();

}


// Previous stuff - does not use mootools


// I stole this
function findPosition( oLink ) {
  if( oLink.offsetParent ) {
    for( var posX = 0, posY = 0; oLink.offsetParent; oLink = oLink.offsetParent ) {
      posX += oLink.offsetLeft;
      posY += oLink.offsetTop;
    }
    return [ posX, posY ];
  } else {
    return [ oLink.x, oLink.y ];
  }
}


function initControls(){
	allThings = document.getElementsByTagName('*') || document.all;
	for (var i=0; i<allThings.length; i++){
		var dis = allThings[i];
		if(dis.getAttribute("control")){

// popupwindow - to make link appear in sized popup
			if(dis.getAttribute("control") == "popupwindow"){
				dis.onclick = makePopup;
			}

// demopopup - for the flash demos window
			if(dis.getAttribute("control") == "demopopup"){
				dis.onclick = makeDemoPopup;
			}

// demopopup - for the flash demos window
			if(dis.getAttribute("control") == "jeffpopup"){
				dis.onclick = makeJeffPopup;
			}

// sendToOpener - for a link in a popup, to affect opener and kill itself
			if(dis.getAttribute("control") == "sendToOpener"){
				dis.onclick = sendToOpener;
			}

// membercard - the popup member card on dashboard
			if(dis.getAttribute("control") == "membercard"){
				dis.onclick = makeMemberCard;
			}

		}
	}
}

// this is called on the dashboard.aspx page
function initMemberCard(){
	allThings = document.getElementsByTagName('*') || document.all;
	for (var i=0; i<allThings.length; i++){
		var dis = allThings[i];
		if(dis.getAttribute("control")){

// membercard - the popup member card on dashboard
			if(dis.getAttribute("control") == "membercard"){
				dis.onclick = makeMemberCard;
			}

		}
	}
}

// ------------------------------- Behaviors -------------------------------

// Global window reference for standard popup
var daWindow = null;

function makePopup(){
	if(this.getAttribute("href")){
		var disRef = this.getAttribute("href");
		if(daWindow == null || daWindow.closed){
			daWindow = window.open(disRef, null, "height=400,width=400,menubar=no,toolbar=no,location=no,status=yes,resizable=yes,scrollbars=yes");
		}else{
			daWindow.location.href = disRef;
			daWindow.focus();
		}
		return false;
	}else{
		return true;
	}
}

function makeDemoPopup(){
	if(this.getAttribute("href")){
		var disRef = this.getAttribute("href");
		if(daWindow == null || daWindow.closed){
			daWindow = window.open(disRef, null, "height=625,width=750,menubar=no,toolbar=no,location=no,status=yes,resizable=yes,scrollbars=yes");
		}else{
			daWindow.location.href = disRef;
			daWindow.focus();
		}
		return false;
	}else{
		return true;
	}
}

function makeJeffPopup(){
	if(this.getAttribute("href")){
		var disRef = this.getAttribute("href");
		if(daWindow == null || daWindow.closed){
			daWindow = window.open(disRef, null, "height=350,width=440,menubar=no,toolbar=no,location=no,status=yes,resizable=yes,scrollbars=yes");
		}else{
			daWindow.location.href = disRef;
			daWindow.focus();
		}
		return false;
	}else{
		return true;
	}
}


function sendToOpener(){
	if(this.getAttribute("href")){
		var disRef = this.getAttribute("href");
		if(!opener.closed){
			opener.location.href = disRef;
			window.close();
			return false;
		}
	}else{
		return true;
	}
}

// Global window reference for member card
var daCard = null;

function makeMemberCard(){
	if(this.getAttribute("href")){
		var disRef = this.getAttribute("href");
		if(daCard == null || daCard.closed){
			daCard = window.open(disRef, null, "height=525,width=580,menubar=no,toolbar=no,location=no,status=yes,resizable=yes,scrollbars=yes");
		}else{
			daCard.location.href = disRef;
			daCard.focus();
		}
		return false;
	}else{
		return true;
	}
}


// --------------- ahlweb.css --------------------



// Some of these aren't needed
function hideTabs(tabclass){
	$$('.' + tabclass).setStyle('display', 'none');
}
function activateTab(imhere){
	document.getElementById(imhere).style.display = "block";
	document.getElementById('tab'+(imhere)).className = "active";
}
function setActive(thistab){
	document.getElementById(thistab).className = "active";
}
function removeClass(daclass){
	$$('.' + daclass).removeClass(daclass);
}
function hideDiv(target){
	document.getElementById(target).style.display = "none";
}
function showDiv(target){
	document.getElementById(target).style.display = "";
}
function alternate(hideDiv, showDiv){
	document.getElementById(hideDiv).style.display = "none";
	document.getElementById(showDiv).style.display = "block";
}
function toggleDiv(target){
	var myDiv = document.getElementById(target);
	if(myDiv.style.display == "none"){
		myDiv.style.display = "block";
	}else{
		myDiv.style.display = "none";
	}
}

// --------------- ahlmng.css --------------------


// Used in editing property information
function charCount(formline, countBox, max) {
	formline = $(formline);
	if (formline.value.length > max){
		formline.value = formline.value.substring(0, max);
	}else{
		$(countBox).empty().setHTML(formline.value.length + " / " + max);
	}
}

// Manager Amenities
function justCount(formline, countBox, max){
	formline = document.getElementById(formline);
	document.getElementById(countBox).innerHTML = formline.value.length + " / " + max;
}

//This comes from http://www.eggheadcafe.com/articles/20020107.asp
//It parses the query string
function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q && this.q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }	
}
function queryString(key){
	var page = new PageQuery(window.location.search); 
	return unescape(page.getValue(key)); 
}

// From the amdprop.js file

//Displays confirmation box and on true will submit form
//on predefined location and on false redirect to predefined URL

var changed = false; //this variable will be set to true if any field on any form is changes
function valChange()
{
    changed = true;
};
function confirmSave()
{
    if (changed)
    {
        var result = confirm("Do you want to save changes?");
        if (result)
        {
            __doPostBack('btnSubmit','OnClick');
        }
    }
   
}
function pause(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} 


function jah(url,target) {
  
    // native XMLHttpRequest object
    document.getElementById(target).innerHTML = "<img src='/images/load.gif'>";
   
          
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {jahDone(target);};
        req.open("GET", url, true);
        req.send(null);
    // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {jahDone(target);};
            req.open("GET", url, true);
            req.send();
        }
    }

}    

function jahDone(target) {
    // only if req is "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            results = req.responseText;
            document.getElementById(target).innerHTML = results;
        } else {
            document.getElementById(target).innerHTML="jah error:\n" +
                req.statusText;
        }
    }    
}
