// setup the google analytics queue
var _gaq = _gaq || [];
_gaq.push(
	['_setAccount', 'UA-11923649-1'],
	['_trackPageview']
);

// insert the analytics script into the DOM
(function() {
	var gq = new Element('script', {
		'type': 'text/javascript',
		'src': ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js',
		'async': true
	}).inject(document.getElement('head') || document.body);
})();


// setup the comscore stuff
var _comscore = _comscore || [];
_comscore.push(
	{ c1: "2", c2: "9873364" }
);

// insert the comscore script into the DOM
(function() {
	var s = new Element('script', {
		'type': 'text/javascript',
		'src': (document.location.protocol == "https:" ? "https://sb" : "http://b") + ".scorecardresearch.com/beacon.js",
		'async': true
	}).inject(document.getElement('head') || document.body);
})();

// who's on manual tracking
/* var trackWO = function( sWOPage )
{
	var sWOSession;
	var sWOUrl;
	var sWOGateway = 'hostedusa3.whoson.com';
	var sWOProtocol = document.location.protocol;
	var sWODomain = 'www.viewpoint.ca';
	var iWO = new Image(1,1);

	// create a unique session cookie for the visitor if not already created
	var dt = new Date();
	var sWOCookie = document.cookie.toString();
	if( sWOCookie.indexOf("whoson") == -1 ) {
		sWOSession = parseInt(Math.random() * 1000) + "-" + dt.getTime();
		document.cookie = "whoson=" + sWOSession + ";expires=Fri, 31-Dec-2010 00:00:00 GMT;";
	}

	sWOCookie = document.cookie.toString();

	if( sWOCookie.indexOf('whoson') == -1 ) {
		sWOSession = "";
	} else {
		var s = sWOCookie.indexOf("whoson=") + 7;
		var e = sWOCookie.indexOf(";", s);
		if( e == -1 ) { e = sWOCookie.length; }
		sWOSession = sWOCookie.substring(s, e);
	}

	if( sWOPage == "" ) { sWOPage = escape(document.location.href); }
	if( sWOProtocol == "file:" ) { sWOProtocol = "http:"; }
	sWOUrl = sWOProtocol + "//" + sWOGateway + "/stat.gif?u=" + sWOSession + "&d=" + sWODomain;
	sWOUrl += "&p='" + sWOPage + "'&r='" + escape(document.referrer) + "'";
	iWO.src = sWOUrl;
}; */
window.addEvent('domready', function()
{
	var errors = $('errors');
	if( errors ) {
		errors.getElements('li a').each(function( anchor )
		{
			var id = anchor.get('href').substr(1);
			var label = $('content').getElement('label[for=' + id + ']');

			if ( !id || !label ) { return; }	

			label.addClass('error');

			anchor.addEvent('click', function( e )
			{
				e.stop();
				$(id).select();
			});
		});
	}
	
	// Add a "js" class to the body so we know JavaScript is enabled
	$$('body').addClass('js');
	
	// Extend Number to allow for random numbers and random ranges excluding
	// a value
	Number.extend({
		mortgageCalculation: function(args) {
			// If args aren't available, or we're missing key values,
			// we can't continue and must return null.
			if (args == undefined || [args.downpayment, args.interest, args.principle, args.term].contains(undefined)) {
				return null;
			}
			
			// Maybe not use if there are no other args?
			var downpayment = args.downpayment.toFloat().round(2),
			inspectionCost = (args.inspectionCost != undefined) ? args.inspectionCost : 575,
			interest = args.interest,
			listingFees = (args.lFees != undefined) ? args.listingFees : 800,
			principle = args.principle.toFloat().round(2),
			term = args.term;
			
			var downPaymentAsPercentageOfPrinciple = ((downpayment / principle) * 100),
			mortgage = principle - downpayment;
			
			var monthlyPayment = (
				(mortgage) *
				(
					(Math.pow(1 + interest / 200, (1 / 6)) - 1) /
					(1 - Math.pow(Math.pow(1 + interest / 200, (1 / 6)), - 12 * term)) 
				)
			).round(2),
			principleTaxes = (principle * 0.0127 / 12);
			
			return {
				monthlyPayment: monthlyPayment
			}
		},
		
		random: function(min, max) {
			return Math.floor(Math.random() * (max - min + 1) + min);
		},
		
		randomExcluding: function(min, max, excluding) {
			var result = Number.random(min, max);
			
			if (excluding == undefined || result != excluding)
				return result;
			else
				return Number.randomExcluding(min, max, excluding);
		}
	});
	
	// Extend numerical objects to allow for currency formatting
	Number.implement({
		currencyFormat: function() {
			return this.numberFormat(0);
		},
		
		numberFormat: function(decimals, dec_point, thousands_sep) {
			decimals = Math.abs(decimals) + 1 ? decimals : 2;
			dec_point = dec_point || '.';
			thousands_sep = thousands_sep || ',';
			
			var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(this) ? 0 : this) + '');
			var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
			
			return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) + (decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
		}
	});
	
	String.implement({
		// Remove non-digit characters from a string so we can work with
		// it as a Float/Int should we choose to do so.
		asNumeric: function() {
			return this.replace(/^([^.]*)\.?.*$/, "$1").replace(/\D/g, '');
		},
		// Extend the String class so we can convert strings to currency too
		currencyFormat: function() {
			return this.asNumeric().toFloat().currencyFormat(0);
		},
		// Create an element object from a string (jQuery-style)
		toElement: function() {
			return new Element('div', {
				html: this
			}).getFirst();
		}
	});
	
	/*
		Common/generic event handlers to enable common JS functions
	*/
	
	// Toggle visibility of hidden divs -- hide all with
	// class in rel attribute and show the id in the href
	// attribute.
	$$('.js-toggle').addEvent('click', function(e) {
		// Don't toggle a visible element
		if ($$(this.getProperty('href')).getStyle('display') != 'none')
			e.stop();
		
		$$('.' + this.getProperty('rel')).each(function(e) {
			e.setStyle('display', 'none').removeClass('active');
		});
		
		$$(this.getProperty('href')).setStyle('opacity', '0').setStyle('display', 'block').fade('in').addClass('active');
		
		e.stop();
	});
	
	// Test an image's src attribute to ensure it exists, replacing
	// it with a sure-fire image if the URL returns a 404. Useful
	// for replacing something like a Street View URL with a generic
	// URL. Means we double-request the image though, so be careful
	// with things like Static Maps that are rate-limited.
	// 
	// Image should look like this:
	// <img
	// src="http://someunvettedurl.com/image.jpg"
	// class="js-src-check"
	// rel="url[http://trustedurl.com/fallback.jpg]"
	// />
	$$('img.js-src-check').each(function(element) {
		// AJAX-request, looking for a 404
		new Request({
			url: element.get('src'),
			method: 'GET',
			onSuccess: function(response, xml) {
				// If it worked, we're good
			},
			onFailure: function(request) {
				element.set('src', element.get('rel').toString().replace(/.*url\[([^\]]*)\].*/, "$1"))
			}
		}).send();
	});
	
	// Open a login box from anywhere on the site
	$$('a.open-modal-login').addEvent('click', function(e) {
		SqueezeBox.initialize({
			classWindow: 'help',
			closeBtn: false,
			size: { x: 400, y: Browser.Engine.trident ? 155 : 150 }
		});
		SqueezeBox.open('/api/v1/user/login.html', { 'handler': 'url' });
		$$('#sbox-content').setStyle('overflow', 'hidden');
		
		e.stop();
	});

	if( $('home_tellafriend') ) {
		var name = $('name');
		var body = $('body');
		var value;

		if( (value = name.get('value').trim()) ) {
			$$('span.taf_preview_name').set('text', value);
		}

		if( (value = body.get('value').trim()) ) {
			$$('p.taf_preview_body').setStyle('display', 'block').each(function( p )
			{
				var preview = p.getElement('span.taf_preview_body');

				if( preview ) {
					preview.set({
						'styles': { 'display': 'inline' },
						'text': value
					});
				}
			});
		}

		name.addEvent('keyup', function()
		{
			value = name.get('value').trim();
			$$('span.taf_preview_name').set('text', value ? value : '[Your Name Here]');
		});

		body.addEvent('keyup', function()
		{
			$$('p.taf_preview_body').each(function( p )
			{
				if( !(value = body.get('value').trim()) ) {
					p.setStyle('display', 'none');
				} else {
					p.setStyle('display', 'block');
					var preview = p.getElement('span.taf_preview_body');

					if( preview ) {
						preview.set({
							'styles': { 'display': 'inline' },
							'text': value
						});
					}
				}
			});
		});
	}

	if( $('home_bugs') ) {
		var textarea = $('client');

		$H(navigator).each( function( item, property )
		{
			var buffer, plugin, mime;
			if( property != 'opsProfile' && property != 'userProfile' && $type(item) != 'function' ) {
				if( property == 'plugins' && !Browser.Engine.trident ) {
					plugin = null;
					buffer = '';
					$H(item).each(function( value, index, plugins )
					{
						if( index != 'length' && $type(value) != 'function' ) {
							plugin = plugins[index];
							buffer += '\n' + plugin.name + ' (' + plugin.description + ') ' + plugin.filename + '\n';
						}
					});
					textarea.set('value', textarea.value + '\n' + property + ': \n' + buffer + '\n');
				} else if( property == 'mimeTypes' && !Browser.Engine.trident ) {
					mime = null;
					buffer = '';
					$H(item).each(function( value, index, mimeTypes )
					{
						if( index != 'length' && $type(value) != 'function' ) {
							mime = mimeTypes[index];
							buffer += mime.type + ' (' + mime.description + ') [' + mime.suffixes + ']\n';
						}
					});
					textarea.set('value', textarea.value + '\n' + property + ': \n' + buffer + '\n');
				} else {
					textarea.set('value', textarea.value + property + ': ' + item + '\n');
				}
			}
		});
	}

	if( $('home_featured') ) {
		var pid = window.location.pathname.slice(-8);
		var anchors = $$('a.pano');
		var panoramas = anchors.map(function( anchor ) { return anchor.getProperty('href'); });
		var currentPanorama = 0;

		// lightbox hooks
		var lb = new Lightbox();

		// subsets
		$$('table.rooms a[rel]').each(function( anchor )
		{
			var set = anchor.getProperty('rel').split(' ');
			var anchors = set.map(function( path )
			{
				return new Element('a', 
				{
					'rel': 'lightbox[' + set[0] + ']',
					'href': '/media/images/featured/' + pid + '/img_' + path + '.jpg', // TODO: pass the pid
					'styles': { 'display': 'none' }
				});
			});
			document.body.adopt(anchors);

			anchor.addEvent('click', function( e )
			{
				e.stop();
				anchors[0].fireEvent('click');
			});
		});

		// panorama hooks
		anchors.addEvent('click', function( e )
		{
			e.stop();
			currentPanorama = panoramas.indexOf(this.getProperty('href'));
			PanoBox.open('/media/swf/PanoViewer.swf', {handler: 'swf'});
		});

		PanoBox.initialize({
			closeBtn: false,
			size: {x: 840, y: 420},
			controlsHeight: 29,

			onPrevious: function()
			{
				if( panoramas.length && currentPanorama == 0 ) {
					currentPanorama = (panoramas.length - 1);
				} else {
					currentPanorama--;
				}
				$('panorama').loadPanorama(panoramas[currentPanorama]);
			},

			onNext: function()
			{
				if( panoramas.length && currentPanorama == (panoramas.length - 1) ) {
					currentPanorama = 0;
				} else {
					currentPanorama++;
				}
				$('panorama').loadPanorama(panoramas[currentPanorama]);
			}
		});

		PanoBox.handlers.swf = function( url ) {
			return new Swiff(url, {
				id: 'panorama',
				width: this.options.size.x,
				height: this.options.size.y,
				styles: { 'overflow': 'hidden' },
				vars: { 'type': 'Cylinder' },
				callBacks: {
					load: function()
					{
						this.loadPanorama(panoramas[currentPanorama]);
					}
				}
			}).toElement();
		};
	}

	if( $('home_index') ) {
		var twitter = $('twitter');
		var featured = $('featured');
		var featuredCount = 0;
		if( featured ) {
			var pids = [];
			var sold = [];
			var openHouse = [];
			var newPrice = [];
			var currentListing = Math.floor(Math.random() * pids.length);
			var anchor = featured.getElement('a');
			var soldbanner = featured.getElementById( 'banner-sold' );
			var newPriceBanner = featured.getElementById( 'banner-newPrice' );
			var openHouseBanner = featured.getElementById( 'banner-openHouse' );
			var rotate = function()
			{
				var pid = pids[currentListing];
				var classes = featured.get('class').split(' ');

				featured.fade('out').get('tween').chain(function()
				{
					featured.removeClass(classes.getLast()).addClass('p' + pid).fade('in');
					if ( soldbanner ) {
						soldbanner.setStyle( 'display', sold.contains( pid ) ? 'block' : 'none' );
					}
					if ( newPriceBanner ) {
						newPriceBanner.setStyle( 'display', newPrice.contains( pid ) ? 'block' : 'none' );
					}
					if ( openHouseBanner ) {
						openHouseBanner.setStyle( 'display', openHouse.contains( pid ) ? 'block' : 'none' );
					}
					anchor.set('href', '/featured/#p' + pid);
				});

				currentListing = currentListing >= (pids.length - 1) ? 0 : currentListing + 1;
				if(featuredCount < 199)rotate.delay(2500);
				featuredCount++;
			};

			var req = new Request.JSON({
				'url': '/featured/get',
				'method': 'post',
				'onSuccess': function( response )
				{
					if( response ) {
						$each( response, function ( r, pid ) {
							pids.push( pid );
							if ( r.sold ) { sold.push( pid ); }
							if ( r.newPrice ) { newPrice.push( pid ); }
							if ( r.openHouse ) { openHouse.push( pid ); }
						});
						rotate.delay(2500);
					}
				}
			}).send();
		}

		if( twitter ) {
			var container = twitter.getChildren('span')[0] || twitter;
			var status = new Request.JSONP({
				'url': 'http://twitter.com/statuses/user_timeline.json',
				'data': {
					'user_id': '55602339',
					'count': '1'
				},

				onComplete: function( response )
				{
					response.each(function( tweet )
					{
							if( tweet.text ) {
								var text = tweet.text.replace(/(https?:\/\/[\w\-:;?&=+.%#\/]+)/gi, '<a href="$1" target="_blank">$1</a>');
								container.set({'html': text});
							}
					});
				}
			}).send();
		}
	}

	if( $('user_index') ) {
		$$('#scheduleTable tbody tr').each( function ( tr ) {
			var id = tr.get('id');
			if ( !id ) return;
			var set = id.split('-');
			if ( set[0] == 'preSchedule' && set[1] ) {
				tr.addEvent( 'click', function ( ) {
					document.location.href = '/newmap#!/summary/' + set[1] + '/zoom/16';
				});
			}
		});
		
		var recent = $('recent');
		var favContainer = $('favourites');
		var counter = favContainer.getPrevious().getElement('span');
		var favourites = new Favourites(favContainer, {
			'onAdd': function( item, length )
			{
				var pid = item.el.get('class').slice(1);
				var anchors = recent.getElements('li.p' + pid + ' a.favourite');

				counter.set('text', length);
				anchors.each(function( a )
				{
					a.addClass('added').set({
						'href': '/map/favourite/set/' + pid + '/0',
						'title': a.get('title').replace('Add', 'Remove'),
						'text': a.get('text').replace('Add', 'Remove')
					});
				});

				// no favs yet, remove the default messaging
				var tip = $('favTip');
				if( tip ) { tip.dispose(); }
			},

			'onDelete': function( item, length )
			{
				var pid = item.el.get('class').slice(1);
				var anchors = recent.getElements('li.p' + pid + ' a.favourite');

				counter.set('text', length);
				anchors.each(function( a )
				{
					a.removeClass('added').set({
						'href': '/map/favourite/set/' + pid + '/1',
						'title': a.get('title').replace('Remove', 'Add'),
						'text': a.get('text').replace('Remove', 'Add')
					});
				});
			}
		});

		recent.getElements('a.favourite').addEvent('click', function( e )
		{
			if( $type(e) === 'event' ) { e.stop(); }

			var href = this.get('href');
			var add = href.slice(-1).toInt();
			var addrAnchor = this.getNext();
			var pid = addrAnchor.get('href').slice(-8);
			var address = addrAnchor.getElement('span').get('text');

			// was an add
			if( add ) { favourites.add({ 'pid': pid, 'address': address }); }

			// was a remove
			else { favourites.remove(pid); }
		});
	}

	///////////////////////////////////////////////////////////////////////////////////////

	// login auto focus
	if( $('user_login') ) { $('email').focus(); }

	// zebra striping
	$$('table.zebra tbody tr:nth-child(even)').addClass('zebra');
	$$('ul.zebra li:nth-child(even)').addClass('zebra');

	// make all external links open in a new window/tab
	$$('a[rel="external"]').set('target', '_blank');

	// show "Top" link if scrolled beyond fold
	var fold = window.getSize().y;
	var goTop = new Element('a', {
		'href': '#header',
		'text': 'Top',
		'id': 'goTop',
		'opacity': 0
	}).set('tween', {'duration': 'short', 'property': 'opacity'}).inject(document.body);

	document.addEvent('scroll', function() {
		var scroll = window.getScroll().y;
		if( scroll > fold ) {
			goTop.get('tween').start(1);
		} else if( scroll < fold ) {
			goTop.get('tween').start(0);
		}
	});

	// smooth scrolling links
	if (Fx.SmoothScroll)
		var smoothScroll = new Fx.SmoothScroll({ 'links': $$('ol.toc a', $('goTop')) });

	// propagate subject anchor behavior to the entire table row
	$$('table.mail td.subject a').each(function( anchor )
	{
		var tr = anchor.getParent('tr');
		var tds = tr.getElements('td');
		var hover = function() { tds.toggleClass('hover'); };
		tr.addEvents({
			'click': function() { document.location.href = anchor.get('href'); },
			'mouseover': hover,
			'mouseout': hover
		});
	});

	// TODO: replace this with another actionable method
	// pop a confirm dialogue for 'delete' anchors
	$$('a[rel=delete], button[rel=delete]').addEvent('click', function( e ) {
		if( !confirm('Are you sure?') ) { e.stop(); }
	});
	
	///////////////////////////////////////////////////////////////////////////////////////
	
	if($('property_show')){

		if ( $( 'ackSubmit' ) ) {
			$( 'ackSubmit' ).addEvent( 'click', function ( e ) {
				var btn = $( 'btnSubmit' );
				if ( btn.getProperty( 'disabled' ) ) { 
					btn.removeProperty( 'disabled' );
					btn.removeClass( 'btnDisabled' );
				} else {
					btn.set( 'disabled', 'disabled' );
					btn.addClass( 'btnDisabled' );
				}
			});
		}

		// Start of autocompleter input
		var realtor_autocomplete = jQuery('input#realtor_autocomplete');
		realtor_autocomplete.removeAttr('name');
		realtor_autocomplete.val( realtor_autocomplete.attr( 'placeholder' ));
		realtor_autocomplete.focus( function () {
			if ( realtor_autocomplete.attr( 'placeholder' ) == realtor_autocomplete.val() ) {
				realtor_autocomplete.val( '' );
			}
		});
		realtor_autocomplete.autocomplete({
			keypress: function(event, ui) {
				jQuery(this).val(ui.item.label);
				// Redirect the user to this agent's contact page
				window.location.href = '/property/show/' + $$('input[name=pid]')[0].value + '?realtor=' + ui.item.value;
				return false;
			},
			focus: function(event, ui) {
				jQuery(this).val(ui.item.label);
				return false;
			},
			select: function(event, ui) {
				jQuery(this).val(ui.item.label);
				// Redirect the user to this agent's contact page
				window.location.href = '/property/show/' + $$('input[name=pid]')[0].value + '?realtor=' + ui.item.value;
				return false;
			},
			source: function(request, formCallback) {
				new Request.JSON({
					url: '/api/v1/pipeline/agents.json',
					data: {
						name: request.term
					},
					onSuccess: function ( response ) {
						if (!response.agents)
							return [];
						
						realtorArray = [];
						$each(response.agents, function(agent, i) {
							realtorArray.push({
								label: agent.name + ' (' + agent.office_name + ')',
								value: agent.realtor_id
							});
						});
						
						formCallback(realtorArray);
					},
					onFailure: function(response) {
						return [];
					}
				}).get();
			}
		});
		// End of autocompleter input

		//validation variables
		var checkTimeSaved = false;	
		var timeBlocked = dateBlocked = dateTimeAddr = "";
		var availLower = parseInt($("availLower").value);
		var availHigher = parseInt($("availHigher").value);
		
		//validation functions
		surveyAnswered = calendarEventCancel = clearCalendar = displayDateTime = userPickedConflict = checkDateTime = $empty;
		
		new DatePicker('.demo_ranged', {
			inputOutputFormat: 'd-m-Y',
			yearPicker: false
		});

		//////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//Variables set to control the calendar
		//dateBlocked[0] is linked to timeBlocked[0] - The hold date/time that customer has reserved already
		timeBlocked = $('pastTimesHidden').value.split(',');
		dateBlocked = $('pastDatesHidden').value.split(',');
		hrCounter = minCounter = 0;
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//clear the input box with calendar date
		$$(".demo_ranged")[1].set("value", "");
		
		//label above datepicker shows legible date
		$$(".demo_ranged")[1].addEvent('click', function(){
			$$(".datepicker .days .day").each( function(calendarGroup){
				calendarGroup.addEvent('click', function(){
					setTimeout("displayDateTime()", 100);//delayed 100 for IE issues
				});
			});
		});

		
		//Catch the form during submission and prepare date/time as unix timestamp
		$("scheduleShowing").addEvent('submit', function(saveForm){
			var hr = parseInt($("hour").value);
			var min = parseInt($("minute").value);
			var side = ($("ampm").value).toUpperCase();
			var pickDate = $$(".demo_ranged")[1].value;
			
			//reverse date for creation of unix timestamp
			var pickDate = pickDate.split("-");
			pickDate = pickDate.reverse();
			pickDate = pickDate.join("-");
			
			//clear possible errors displayed to user
			$$("#phoneNumber input").each(function (phoneInput){
				phoneInput.setStyle("border", "none");
			});
			checkTimeSaved = true;
			//if the user has selected a date and time then we can proceed
			if($("firstTimeQues") && !surveyAnswered()){
				Event(saveForm).stop();
				$("firstTimeQues").focus;
				alert("Please fill out the questionaire at the top of the page.");
		 	/*}else if(!checkDateTime(hr, min, side, pickDate)){
				Event(saveForm).stop();
				$("showDateTime").focus;
				alert("Please recheck you date/time selection (STEP 1)");*/
			}else if($("phone1").value == "" || $("phone2").value == "" || $("phone3").value == ""){
				Event(saveForm).stop();
				$("phone1").focus;
				$$("#phoneNumber input").each(function (phoneInput){
					phoneInput.setStyle("border", "1px solid red");
				});
				alert("Please provide us with a phone number to contact you (STEP 2)");
			}else if(checkTimeSaved != false){
				var dateToSend = pickDate + " " + hr + ":" + min + ":" + "00 " + side; //e.g 2010-04-13 2:28:00 PM
				var phoneToSend = $("phone1").value +  $("phone2").value + $("phone3").value;
				$("rtt").set("value",dateToSend);
				$("phone").set("value", phoneToSend);
				if($("firstTimeQues")){
					$("q1").set("value",$("ques-1-text").get('html'));
					$("q2").set("value",$("ques-2-text").get('html'));
					$("q3").set("value",$("ques-3-text").get('html'));
				//	$("q4").set("value",$("ques-4-text").get('html'));
				}
			}else{
				$("showDateTime").focus;
				alert("Please Check for a valid Date & Time (STEP 1)");
				Event(saveForm).stop();
			}
		});	
		
		//this checks that first time users have completed the survey
		surveyAnswered = function(){
			if($("firstTimeQues")){
				
				//if( !($("opt1").checked  || $("opt2").checked) || !($("opt3").checked || $("opt4").checked) || !($("opt5").checked || $("opt6").checked) ){
				if( ($("opt1").checked  || $("opt2").checked) && ($("opt3").checked || $("opt4").checked) && ($("opt5").checked || $("opt6").checked) ){
					return true
				}
			}
			return false;
		}

		//This displays the calendars selected date in the label above the input box
		displayDateTime = function(){
			dateElected = $$(".demo_ranged")[1].value;
			var pickDate = dateElected.split("-");
			month = pickDate[1];
			day = pickDate[0];
			year = pickDate[2];
			newDateToRep = year + "/" + month + "/" + day;
			newDate = new Date(newDateToRep);
			$("calendarInputLabel").set('html', newDate.toUTCString().substring(0,16));
		}
		//checks current picked time against previously scheduled appointments
		userPickedConflict = function ( hr, min, side, pickDate) {
			var recordCount = timeBlocked.length;
			var currentTimeToCheck = new Date();
			currentHr = currentTimeToCheck.getHours();
			currentMin = currentTimeToCheck.getMinutes();
			todaysDate = currentTimeToCheck.getDate();
			specificDaySelected = parseInt(pickDate.substring(8, 10));
			var ampm = "AM";
			
			if (currentHr >= 12) {
			 ampm = "PM";
			 currentHr -= 12;
			}
			
			if (currentHr == 0)currentHr = 12;
			if (currentMin < 10) currentMin = "0" + currentMin;

			if(pickDate){
				for(i=0; i<recordCount; i++){
					if((pickDate == dateBlocked[i])){
						if(min == 0) min="00";//php generates "0" instead of what we need "00"
						
						userSelectedTime = hr + ":" + min + " " + side;

						if(userSelectedTime == timeBlocked[i]){//time already requested/scheduled
							return "<p>This date/time has already been scheduled</p>";
						}
						if((hr == currentHr)&&(ampm == side)){//minutes in the past
							if(min < (currentMin - 15)){
								return "<p>The minute part of your request is set in the past</p>";
							}
						}
						if((hr < currentHr) && (ampm == side)){//hr in the past
							return "<p>The hour you set is in the past</p>";
						}
						if( (side == "AM")&&(ampm == "PM") ){//User pick Am when current time is PM
							return "<p>Your am/pm setting is set to the past</p>";
						}
					}
					
					if(specificDaySelected < todaysDate){//ie calendar errors sometimes makes this possible
						return "<p>The date you have picked is in the past</p>";
					}
				}
			}else{
				return "</p>Please pick one of the available dates highlighted in grey on the calendar.</p>";
			}
			return false;//no issues found
		};

		//Validate time requested by customer
		checkDateTime = function (hr, min, side, pickDate) {
			checkTimeSaved = false;
			$('verificationMessage').setStyles({//This is set to display like an error since there are many ways to get an error
			    border: '1px solid #FF0000',
			    display: "block",
			    color : "#FF0000"
			});

			if((check = userPickedConflict(hr, min, side, pickDate))){
				$("verificationMessage").set('html', check);
				$("verificationMessage").setStyle("display","block");
			}else if( ((hr == 12)&&(side == "PM")) || ((hr >= availLower) && (side == "AM")) ||((hr < availHigher) && (side == "PM" )) )  {
				$("verificationMessage").setStyle("display","none");
				checkTimeSaved = true;
			}else{
				$("verificationMessage").set('html', '<p>Time must be between '+availLower+'AM &amp; '+availHigher+'PM</p>');
				$("verificationMessage").setStyle("display","block");
			}
			return checkTimeSaved;
		};
	}//end of if property_show
	
///////////////////////////////////////////////////////////////////////////////////////


		if($('user_info')){
			decision = function (message, url, params){
				if(confirm(message)) post_to_url(url, params);
			}
			
			post_to_url = function (path, params, method) {
			    method = method || "post"; // Set method to post by default, if not specified.

			    // The rest of this code assumes you are not using a library.
			    // It can be made less wordy if you use one.
			    var form = document.createElement("form");
			    form.setAttribute("method", method);
			    form.setAttribute("action", path);

			    for(var key in params) {
			        var hiddenField = document.createElement("input");
			        hiddenField.setAttribute("type", "hidden");
			        hiddenField.setAttribute("name", key);
			        hiddenField.setAttribute("value", params[key]);

			        form.appendChild(hiddenField);
			    }

			    document.body.appendChild(form);    // Not entirely sure if this is necessary
			    form.submit();
			}

			$('userRoleChange').addEvent('submit', function(e){ 
				e.stop();  
				
				newRoles = $('alterRole').getElements('input:checked').get('value');
				if(newRoles == (null || "")){
					var newRoles = new Array();
					newRoles[0] = "none";
				}

				id = $('idStore').value;
				var req = new Request({
					url: '/ajax/ui/alterRole/' + newRoles + "/" + id,
					onSuccess: function ( response )
					{
						if(response != false){location.reload( true );}
						else{$('alterRole').appendText(' There was an error with changing the user role!');}
					}
				}).get();
			});
			
			$('userNameChange').addEvent('submit', function(e){ 
				e.stop();  
				fname = $('fnameStore').value;
				lname = $('lnameStore').value;
				id = $('idStore').value;
				var req = new Request({
					url: '/ajax/ui/alterUser/' + fname + "/" + lname + "/" + id,
					onSuccess: function ( response )
					{
						if(response != false){location.reload( true );}
						else{$('userNameChange').appendText(' There was an error with changing the username!');}
					}
				}).get();
			});
			
			$('userEmailChange').addEvent('submit', function(e){ 
				e.stop();  
				email = $('emailStore').value;
				id = $('idStore').value;
				var req = new Request({
					url: '/ajax/ui/alterEmail/' + email + "/" + id,
					onSuccess: function ( response )
					{
						if(response != false){location.reload( true );}
						else{$('userEmailChangeError').set('html','This email address is used by another user (NOT UNIQUE)!');}
					}
				}).get();
			});

			$('userPhoneChange').addEvent('submit', function(e){ 
				e.stop();  
				email = $('phoneStore').value;
				id = $('idStore').value;
				var req = new Request({
					url: '/ajax/ui/alterPhone/' + email + "/" + id,
					onSuccess: function ( response )
					{
						if(response != false){location.reload( true );}
						else{$('userPhoneChangeError').set('html','There was an error saving your phone number');}
					}
				}).get();
			});

			$('userIsRealtorChange').addEvent('submit', function(e){ 
				e.stop();  
				realtor_id = $('realtor_id').value;
				id = $('idStore').value;
				var req = new Request({
					url: '/ajax/ui/alterIsRealtor/' + realtor_id + "/" + id,
					onSuccess: function ( response )
					{
						if(response != false){location.reload( true );}
						else{$('userIsRealtorChangeError').set('html','Problem setting Realtor ID.');}
					}
				}).get();
			});

			if ( $('isRealtorStore') ) {
				var ac_realtor = new Autocompleter.Request.JSON.VP.Lookup( $('isRealtorStore'), '/ajax/ui/l/nsarmember' );
				ac_realtor.addEvent( 'onSelection', function ( element, selected, value, input ) {
					$( 'realtor_id' ).set( 'value', ac_realtor.lookup( value ) );
				});
			}

			$('unsetIsRealtor').addEvent('click', function(e){ 
				e.stop();  
				id = $('idStore').value;
				var req = new Request({
					url: '/ajax/ui/alterIsRealtor/0/' + id,
					onSuccess: function ( response )
					{
						if(response != false){location.reload( true );}
						else{$('userIsRealtorChangeError').set('html','Problem unsetting Realtor ID.');}
					}
				}).get();
			});

			if ( $( 'activatePipeliner' ) ) {
				$('activatePipeliner').addEvent('submit', function(e){ 
					e.stop();
					var is_active = $$( 'input[name=inputPipelineActive]:checked' ).get( 'value' );
					var req = new Request({
						url: '/ajax/ui/activatePipeliner/' + is_active + '/' + $( 'idStore' ).value,
						onSuccess: function ( response )
						{
							if ( response ) {
								location.reload( true );
							} else {
								$( 'activatePipelinerError' ).set( 'html', 'There was an error during (de)activation' );
							}
						}
					}).get();
				});

				$('activatePipelinerLink').addEvent('click', function(){
					$('activatePipeliner').setStyle('display', 'block');
				});

				$('closeActivatePipeliner').addEvent('click', function(){
					$('activatePipeliner').setStyle('display', 'none');
					$('activatePipelinerError').set('html', '');
				});

				$('assignPipeliner').addEvent('submit', function(e) {
					e.stop();
					var realtorId = $( 'inputPipelineRealtorID' ).value;
					if ( realtorId ) {
						var req = new Request({
							url: '/ajax/ui/assignPipeliner/' + realtorId + '/' + $( 'idStore' ).value,
							onSuccess: function ( response )
							{
								if ( response ) {
									location.reload( true );
								} else {
									$( 'assignPipelinerError' ).set( 'html', 'There was an error during Realtor ID assignment' );
								}
							}
						}).get();
					} else {
						alert( 'Please select a Realtor from the list' );
					}
				});

				$('assignPipelinerLink').addEvent('click', function(){
					$('assignPipeliner').setStyle('display', 'block');
				});

				$('closeAssignPipeliner').addEvent('click', function(){
					$('assignPipeliner').setStyle('display', 'none');
					$('assignPipelinerError').set('html', '');
				});

				new Autocompleter.Request.JSON.VP.SetInput( $( 'inputPipelineAssign' ), '/ajax/ui/l/nsarmember', {
					inputId: 'inputPipelineRealtorID'
				});
			}

			$('alterRoleLink').addEvent('click', function(){
				$('alterRole').setStyle('display', 'block');
			});
			$('closeRoleEdit').addEvent('click', function(){
				$('alterRole').setStyle('display', 'none');
			});
			
			$('changeUsernameLink').addEvent('click', function(){
				$('changeUsername').setStyle('display', 'block');
			});
			
			$('closeUserEdit').addEvent('click', function(){
				$('changeUsername').setStyle('display', 'none');
			});

			$('changeEmailLink').addEvent('click', function(){
				$('changeEmail').setStyle('display', 'block');
			});
			
			$('closeEmailEdit').addEvent('click', function(){
				$('changeEmail').setStyle('display', 'none');
				$('userEmailChangeError').set('html', '');
			});

			$('changePhoneLink').addEvent('click', function(){
				$('changePhone').setStyle('display', 'block');
			});
			
			$('closePhoneEdit').addEvent('click', function(){
				$('changePhone').setStyle('display', 'none');
				$('userPhoneChangeError').set('html', '');
			});

			$('changeIsRealtorLink').addEvent('click', function(){
				$('changeIsRealtor').setStyle('display', 'block');
			});
			
			$('closeIsRealtorEdit').addEvent('click', function(){
				$('changeIsRealtor').setStyle('display', 'none');
				$('userIsRealtorChangeError').set('html', '');
			});

			$('tempPasswordLink').addEvent('click', function(){
				$('tempPassword').setStyle('display', 'block');
			});

			$('setUserComment').addEvent('click', function(){
				$('userComment').setStyle('display', 'block');
				$('comment').focus();
			});

			$('cancelUserComment').addEvent( 'click', function () {
				$('userComment').setStyle('display', 'none');
			});

			confirmVerification = function (message, url) {
				var answer = confirm("Are you sure you want to " + message + "?")
				if (answer){
					window.location = url;
				}
			}

		}

		if($('new_viewing')){
			//validation variables
			var checkTimeSaved = false;	
			var timeBlocked = dateBlocked = dateTimeAddr = "";
			
			//validation functions
			checkFormValid = displayDateTime = $empty;
			
			viewingPicker = new DatePicker('.demo_ranged', {
				inputOutputFormat: 'd-m-Y',
				yearPicker: false
			});

			//////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//Variables set to control the calendar
			//dateBlocked[0] is linked to timeBlocked[0] - The hold date/time that customer has reserved already
			hrCounter = minCounter = 0;
			//////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//clear the input box with calendar date
			$$(".demo_ranged")[1].set("value", "");
			
			//label above datepicker shows legible date
			$$(".demo_ranged")[1].addEvent('click', function(){
				$$(".datepicker .days .day").each( function(calendarGroup){
					calendarGroup.addEvent('click', function(){
						
						setTimeout("displayDateTime()", 100);//delayed 100 for IE issues
					});
				});
			});

			//This displays the calendars selected date in the label above the input box
			displayDateTime = function(){
				dateElected = $$(".demo_ranged")[1].value;
				var pickDate = dateElected.split("-");
				month = pickDate[1];
				day = pickDate[0];
				year = pickDate[2];
				newDateToRep = year + "/" + month + "/" + day;
				newDate = new Date(newDateToRep);
				$("calendarInputLabel").set('html', newDate.toUTCString().substring(0,16));
			}
			
			checkFormValid = function(hr, min, side, pickDate){
				if($("realtor_val").value == "") {	
					alert("Please select and APPLY a realtor");
					checkTimeSaved = false;
				}else if($("address_val").value == "" ){
					alert("Please select and APPLY an address");
					checkTimeSaved = false;
				}else if((hr !== "") && (min !== "") && (side !== "") && (pickDate !== "")){
						checkTimeSaved = true;
				}else{
					alert("the time selected is invalid");
					checkTimeSaved = false;
				}

				return checkTimeSaved;
			}
			
			//Catch the form during submission and prepare date/time as unix timestamp
			$("createViewing").addEvent('submit', function(saveForm){
				var hr = parseInt($("hour").value);
				var min = parseInt($("minute").value);
				var side = ($("ampm").value).toUpperCase();
				var pickDate = $$(".demo_ranged")[1].value;
				checkTimeSaved = false;
				
				//reverse date for creation of unix timestamp
				var pickDate = pickDate.split("-");
				pickDate = pickDate.reverse();
				pickDate = pickDate.join("-");
				
				if(checkFormValid(hr, min, side, pickDate)){
					var dateToSend = pickDate + " " + hr + ":" + min + ":" + "00 " + side; //e.g 2010-04-13 2:28:00 PM
					$("rtt").set("value",dateToSend);
					//realtor and address ids set in viewingacdiv.js
				}else{
					Event(saveForm).stop();
				}
			});	
		
		}//end of new viewing
		
		if($('loan_setup')){

			//functions
			fillLoanForm = $empty;
			
			fillLoanForm = function(){
				principle = $("principle").get('value');
				downpayment = $('dPay').get('value');
				downPaymentPercent = ((downpayment/principle) * 100).round(2);
				firstMorgtgage = principle - downpayment;
				switch(true){
					case (downPaymentPercent <= 5):
					  mInsPremP = 2.75;
					  break;
					case (downPaymentPercent <= 10):
					  mInsPremP = 2.00;
					  break;
					case (downPaymentPercent <= 15):
					  mInsPremP = 1.75;
					  break;
					case (downPaymentPercent <= 20):
					  mInsPremP = 1.00;
					  break;				
					case (downPaymentPercent <= 25):
					  mInsPremP = .60;
					  break;				
					case (downPaymentPercent <= 30):
					  mInsPremP = .50;
					  break;
					default:
					  mInsPremP = .50;
				}
				mInsPremD = ((firstMorgtgage/100) * mInsPremP).round(2);
				tfinance = firstMorgtgage + mInsPremD;
				interest = $('interest').get('value');
				term = $('term').get('value');
				inspCost = 575;
				lfees = 800;
				ltt = ((principle/100) * (1.5)).round(2);
				pInterest = calcPayment(principle, interest, term, downpayment).round(2);
				ptaxes = (principle * .0127 / 12).round(2);
				tPayments = (pInterest + ptaxes).round(2);
				
				$("pInterest").set("html",pInterest); 
				$("ptaxes").set("html",ptaxes);
				$("tPayments").set("html",tPayments);
				
				
				$("inspCost").set("html",inspCost);
				$("lfees").set("html",lfees);
				$("ltt").set("html",ltt);
			}
			calcPayment = function ( principle, interest, term, donwpayment ){
				return ( principle - downpayment ) * ( ( Math.pow( 1 + interest / 200, ( 1 / 6 ) ) - 1 ) / ( 1 - Math.pow( Math.pow( 1 + interest / 200, ( 1 / 6 ) ), -12 * term ) ) );
			}
			
			fillLoanForm();
			$('calculateLoan').addEvent('click', function(){
				fillLoanForm();
			});
		}
		
		if($('external_viewing')){
			//validation variables
			var checkTimeSaved = false;	
			var timeBlocked = dateBlocked = dateTimeAddr = "";
			
			//validation functions
			checkFormValid = displayDateTime = $empty;
			
			viewingPicker = new DatePicker('.demo_ranged', {
				inputOutputFormat: 'd-m-Y',
				yearPicker: false
			});

			//////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//Variables set to control the calendar
			//dateBlocked[0] is linked to timeBlocked[0] - The hold date/time that customer has reserved already
			hrCounter = minCounter = 0;
			//////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//clear the input box with calendar date
			$$(".demo_ranged")[1].set("value", "");
			
			//label above datepicker shows legible date
			$$(".demo_ranged")[1].addEvent('click', function(){
				$$(".datepicker .days .day").each( function(calendarGroup){
					calendarGroup.addEvent('click', function(){
						
						setTimeout("displayDateTime()", 100);//delayed 100 for IE issues
					});
				});
			});

			//This displays the calendars selected date in the label above the input box
			displayDateTime = function(){
				dateElected = $$(".demo_ranged")[1].value;
				var pickDate = dateElected.split("-");
				month = pickDate[1];
				day = pickDate[0];
				year = pickDate[2];
				newDateToRep = year + "/" + month + "/" + day;
				newDate = new Date(newDateToRep);
				$("calendarInputLabel").set('html', newDate.toUTCString().substring(0,16));
			}
			
			checkFormValid = function(hr, min, side, pickDate){
				if($("realtor_val").value == "") {	
					alert("Please select and APPLY a realtor");
					checkTimeSaved = false;
				}else if((hr !== "") && (min !== "") && (side !== "") && (pickDate !== "")){
						checkTimeSaved = true;
				}else{
					alert("the time selected is invalid");
					checkTimeSaved = false;
				}

				return checkTimeSaved;
			}
			
			//Catch the form during submission and prepare date/time as unix timestamp
			$("createViewing").addEvent('submit', function(saveForm){
				var hr = parseInt($("hour").value);
				var min = parseInt($("minute").value);
				var side = ($("ampm").value).toUpperCase();
				var pickDate = $$(".demo_ranged")[1].value;
				checkTimeSaved = false;
				
				//reverse date for creation of unix timestamp
				var pickDate = pickDate.split("-");
				pickDate = pickDate.reverse();
				pickDate = pickDate.join("-");
				
				if(checkFormValid(hr, min, side, pickDate)){
					var dateToSend = pickDate + " " + hr + ":" + min + ":" + "00 " + side; //e.g 2010-04-13 2:28:00 PM
					$("rtt").set("value",dateToSend);
					//realtor and address ids set in viewingacdiv.js
				}else{
					Event(saveForm).stop();
				}
			});	
		
		}//end of external viewing
});
 
//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.

MooTools.More={version:"1.2.4.2",build:"bd5a93c0913cce25917c48cbdacde568e15e02ef"};Fx.Scroll=new Class({Extends:Fx,options:{offset:{x:0,y:0},wheelStops:true},initialize:function(b,a){this.element=this.subject=document.id(b);
this.parent(a);var d=this.cancel.bind(this,false);if($type(this.element)!="element"){this.element=document.id(this.element.getDocument().body);}var c=this.element;
if(this.options.wheelStops){this.addEvent("start",function(){c.addEvent("mousewheel",d);},true);this.addEvent("complete",function(){c.removeEvent("mousewheel",d);
},true);}},set:function(){var a=Array.flatten(arguments);if(Browser.Engine.gecko){a=[Math.round(a[0]),Math.round(a[1])];}this.element.scrollTo(a[0],a[1]);
},compute:function(c,b,a){return[0,1].map(function(d){return Fx.compute(c[d],b[d],a);});},start:function(c,g){if(!this.check(c,g)){return this;}var e=this.element.getScrollSize(),b=this.element.getScroll(),d={x:c,y:g};
for(var f in d){var a=e[f];if($chk(d[f])){d[f]=($type(d[f])=="number")?d[f]:a;}else{d[f]=b[f];}d[f]+=this.options.offset[f];}return this.parent([b.x,b.y],[d.x,d.y]);
},toTop:function(){return this.start(false,0);},toLeft:function(){return this.start(0,false);},toRight:function(){return this.start("right",false);},toBottom:function(){return this.start(false,"bottom");
},toElement:function(b){var a=document.id(b).getPosition(this.element);return this.start(a.x,a.y);},scrollIntoView:function(c,e,d){e=e?$splat(e):["x","y"];
var h={};c=document.id(c);var f=c.getPosition(this.element);var i=c.getSize();var g=this.element.getScroll();var a=this.element.getSize();var b={x:f.x+i.x,y:f.y+i.y};
["x","y"].each(function(j){if(e.contains(j)){if(b[j]>g[j]+a[j]){h[j]=b[j]-a[j];}if(f[j]<g[j]){h[j]=f[j];}}if(h[j]==null){h[j]=g[j];}if(d&&d[j]){h[j]=h[j]+d[j];
}},this);if(h.x!=g.x||h.y!=g.y){this.start(h.x,h.y);}return this;},scrollToCenter:function(c,e,d){e=e?$splat(e):["x","y"];c=$(c);var h={},f=c.getPosition(this.element),i=c.getSize(),g=this.element.getScroll(),a=this.element.getSize(),b={x:f.x+i.x,y:f.y+i.y};
["x","y"].each(function(j){if(e.contains(j)){h[j]=f[j]-(a[j]-i[j])/2;}if(h[j]==null){h[j]=g[j];}if(d&&d[j]){h[j]=h[j]+d[j];}},this);if(h.x!=g.x||h.y!=g.y){this.start(h.x,h.y);
}return this;}});var SmoothScroll=Fx.SmoothScroll=new Class({Extends:Fx.Scroll,initialize:function(b,c){c=c||document;this.doc=c.getDocument();var d=c.getWindow();
this.parent(this.doc,b);this.links=$$(this.options.links||this.doc.links);var a=d.location.href.match(/^[^#]*/)[0]+"#";this.links.each(function(f){if(f.href.indexOf(a)!=0){return;
}var e=f.href.substr(a.length);if(e){this.useLink(f,e);}},this);if(!Browser.Engine.webkit419){this.addEvent("complete",function(){d.location.hash=this.anchor;
},true);}},useLink:function(c,a){var b;c.addEvent("click",function(d){if(b!==false&&!b){b=document.id(a)||this.doc.getElement("a[name="+a+"]");}if(b){d.preventDefault();
this.anchor=a;this.toElement(b).chain(function(){this.fireEvent("scrolledTo",[c,b]);}.bind(this));c.blur();}}.bind(this));}});//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.

MooTools.More={version:"1.2.3.1"};Request.JSONP=new Class({Implements:[Chain,Events,Options],options:{url:"",data:{},retries:0,timeout:0,link:"ignore",callbackKey:"callback",injectScript:document.head},initialize:function(a){this.setOptions(a);
this.running=false;this.requests=0;this.triesRemaining=[];},check:function(){if(!this.running){return true;}switch(this.options.link){case"cancel":this.cancel();
return true;case"chain":this.chain(this.caller.bind(this,arguments));return false;}return false;},send:function(c){if(!$chk(arguments[1])&&!this.check(c)){return this;
}var e=$type(c),a=this.options,b=$chk(arguments[1])?arguments[1]:this.requests++;if(e=="string"||e=="element"){c={data:c};}c=$extend({data:a.data,url:a.url},c);
if(!$chk(this.triesRemaining[b])){this.triesRemaining[b]=this.options.retries;}var d=this.triesRemaining[b];(function(){var f=this.getScript(c);
this.fireEvent("request",f);this.running=true;(function(){if(d){this.triesRemaining[b]=d-1;if(f){f.destroy();this.send(c,b);this.fireEvent("retry",this.triesRemaining[b]);
}}else{if(f&&this.options.timeout){f.destroy();this.cancel();this.fireEvent("failure");}}}).delay(this.options.timeout,this);}).delay(Browser.Engine.trident?50:0,this);
return this;},cancel:function(){if(!this.running){return this;}this.running=false;this.fireEvent("cancel");return this;},getScript:function(c){var b=Request.JSONP.counter,d;
Request.JSONP.counter++;switch($type(c.data)){case"element":d=document.id(c.data).toQueryString();break;case"object":case"hash":d=Hash.toQueryString(c.data);
}var e=c.url+(c.url.test("\\?")?"&":"?")+(c.callbackKey||this.options.callbackKey)+"=Request.JSONP.request_map.request_"+b+(d?"&"+d:"");if(e.length>2083){
}var a=new Element("script",{type:"text/javascript",src:e});Request.JSONP.request_map["request_"+b]=function(f){this.success(f,a);}.bind(this);return a.inject(this.options.injectScript);
},success:function(b,a){if(a){a.destroy();}this.running=false;this.fireEvent("complete",[b]).fireEvent("success",[b]).callChain();
}});Request.JSONP.counter=0;Request.JSONP.request_map={};
