if (typeof hotpads == "undefined") var hotpads = {};

/***************** global vars **********************/
var fullViewShowing;
var fullViewType = ''; //listing or area or areaListings or customView
var openFullViewId;
var iframe = false;
var openFullViewsNewWindow = false;  //changed by the search filters

/****************** base hotpads functions **************/

hotpads.base = {
	resizeIframe : function(size) {
		//$.log("resizing iframe to " + size);
		if ($("#fullviewIframe").length)
			$("#fullviewIframe").css('height', size + 'px');
	},

	resizeParentIframe : function() {
		if (parent && parent.hotpads.base.resizeIframe && $('#all').height()) {	
			var height = $('#all').height() + 40;
			if (height < 850)
				height = 850;
			parent.hotpads.base.resizeIframe(height);			
		}
	},

	makeSpaceForRightSection : function(){
		var ie8 = $.browser.msie && $.browser.version == "8.0";
		if (!ie8) //ie8 scrolls to the top of the iframe when the iframe is location.replaced for some reason, temp fix to keep it from pingponging
			scroll(0,0);
			
		if(typeof(fullViewShowing)!="undefined" && fullViewShowing){
			document.title = "HotPads - Search for Real Estate, Apartments & Houses for Rent, Foreclosures and Homes for Sale";
		}
		
		if ($(".leftContainer").css("width") != "38%") {
			//set width of left/right containers if starting from fullscreen search
			var rightWidth = ($.browser.msie && $.browser.version == '6.0') ? '61.5%' : '62%';
			$(".rightContainer").width(rightWidth);
			$(".leftContainer").width('38%');
			/*if (rightAd) {
				$("#rightAd").hide();
				$("#mapperWrapper").css("margin-right", "0px");
			}*/
		}

		hotpads.base.hideFooter();	
	},

	loadIframe : function(url) {
		$.log("loading iframe");
		hotpads.base.makeSpaceForRightSection();
		hotpads.advancedFilterView.close();
		
		if ($("#fullview").length > 0 && $("#fullview").css("display") != "none") {
			$("#fullview").hide().html(""); 
		}

		//$("#fullviewIframe").css('visibility', 'hidden');//hide();
		$(frames['fullviewIframe'].document).find("#squaread").css('visibility', 'hidden');
		$(frames['fullviewIframe'].document).find("#all").css("opacity","0.3"); //fade out iframe
		$(frames['fullviewIframe'].document).find(".realAds").css("display","none");
		$("#loading").show();
		fullViewShowing = true;
		frames['fullviewIframe'].location.replace(url);
	},
	
	setFullViewShowing : function(id) {
		openFullViewId = id;
		$(function(){//onReady
			hotpads.base.loadResources(fullViewType, openFullViewId);
			hotpads.base.loadFooter(fullViewType, openFullViewId);
		});	
	} ,
	
	/* called by the iframe page when it has loaded enough to be shown */
	showIframe : function() {
		iframe = true;
		if ($("#fullviewIframe").css('display') == 'none')
			$("#fullviewIframe").show();
		//$("#fullviewIframe").css('visibility', 'visible');//show();//fadeIn("slow");
		$("#loading").hide();
		$("#fullviewIframe").focus().log("Iframe loading finished");
	},
	
	updateFullView : function(fullViewParams){
		if (typeof(fullViewParams) != 'undefined'){
			var fv = $.deserialize(fullViewParams);
			if (typeof(fv.detailsOpen) != 'undefined' && fv.detailsOpen == 'true'){
				var fvType = (typeof(fv.previewType) != 'undefined') ? fv.previewType : '';
				var fvId = (typeof(fv.previewId) != 'undefined') ? fv.previewId : '';
				if (fvType != '' && fvId != '' && (typeof(openFullViewId) == 'undefined' || fvId != openFullViewId)){
					if(fvType == 'advancedFilter'){
						$.log('opening advanced filter full view');
						hotpads.advancedFilterView.open();
						return;
					}
					else{
						hotpads.advancedFilterView.close();
					}
					if (fvType == 'area'){
						if (fvId.search(/\D/) == -1){
							$.log('opening area full view');
							loadAreaFullView(fvId);				
						} else {
							$.log('opening custom full view');
							loadCustomFullView(fvId);			
						}
					} 
					else {
						$.log('opening listing full view');
						loadFullView(fvId);
					}
				}
			} else {
				hotpads.base.closeFullView();
			}
		}		
	},
	
	
	//called by closeFullView and advancedFilterView.open
	closeRightHalf : function(){
		openFullViewId = '';
		
		hotpads.base.hideFooter();
		hotpads.base.hideResources();
		
		hotpads.advancedFilterView.close();
		
		if ($("#fullview").length && $("#fullview").css("display") != "none") {
			$.log("closing non-iframed fullview");
			$("#fullview").hide().html("");
		} else {
			$.log("closing iframe");
			
			if ($.browser.safari) {
				$("#fullviewIframe").height("1px"); //safari doesnt like iframes with display:none //width("1px").
			} else {
				$("#fullviewIframe").hide();
			}	
			frames["fullviewIframe"].location.replace("about:blank");
		}
	},
	
	closeFullView : function() {
		//close the full view
		
		hotpads.base.closeRightHalf();
		
		$(".leftContainer").css('width', '100%');
		if (rightAd) {
			$("#rightAd").show();
			$("#mapperWrapper").css("margin-right", "161px");
			hotpads.base.loadRightAd();
		}
		
		hotpads.map.resize();
		fullViewShowing = false;
			
		document.title = "HotPads - Search for Real Estate, Apartments & Houses for Rent, Foreclosures and Homes for Sale";
		
		$('#mapper').focus();
	},
	
	popoutFV : function(id) {
		hotpads.base.closeFullView();

		$("#openFullViewsNewWindow").attr('checked', true);
		hotpads.filter.updateFilter();
		
		if (fullViewType == 'listing')
			loadFullView(id);
		else if (fullViewType == 'area')
			loadAreaFullView(id);
		else if (fullViewType == 'areaListings')
			loadAreaFullView(id);
		else //if (fullViewType == 'custom')
			loadCustomFullView(id);

	},
	
	popinFV : function(id) {
		var parentWin = window.opener;
		if (parentWin != null && typeof(parentWin != 'undefined') && !parentWin.closed) {
			$(parentWin.document).find("#openFullViewsNewWindow").attr("checked", false);
			parentWin.hotpads.filter.updateFilter();
			if (fullViewType == 'listing')
				parentWin.loadFullView(id);
			else if (fullViewType == 'area' || fullViewType == 'areaListings')
				parentWin.loadAreaFullView(id); 
			else //if (fullViewType == 'custom')
				parentWin.loadCustomFullView(id);
			parentWin.hotpads.map.getMapper().setFullViewShowing(true);
		
			window.close();			
		} else {
			if (fullViewType == 'listing')
				window.location.pathname = LISTING_FULL_VIEW_BASE + id;
			else if (fullViewType == 'area' || fullViewType =='areaListings')
				window.location.pathname = AREA_FULL_VIEW_BASE + id;	
			else //if (fullViewType == 'custom')
				window.location.pathname = CUSTOM_FULL_VIEW_BASE + id;			
		}
	},
	
	hideFooter : function() {
		$("#footerSurround").hide();	
	},
	
	loadFooter : function(type, id) {		
		if ($("#footerAd").css('display') != 'none') {
			$("#footerAd").hide().html('');
			$("#footerAdIframe").show();
		}

		$.log("updating footerAdIframe");
		if (type == 'listing') {
			if(frames["footerAdIframe"] != null){
				frames["footerAdIframe"].location.replace("/search/footerAd?listingId=" + id);
			}
		} else if (type == 'area' && id) {		
			frames["footerAdIframe"].location.replace("/search/footerAd?areaId=" + id);
		} else {
			frames["footerAdIframe"].location.replace("/search/footerAd");
		}
		
		$("#footerSurround").show();
	},
	
	loadRightAd : function() {
		$("#rightAdIframe").show();
		$.log("updating rightAdIframe");
		frames["rightAdIframe"].location.replace("/search/rightAd");
	},
	
	hideResources : function() {
		if ($("#resources").length) {
			$("#resources").hide();
		}
	},
		
	loadResources : function(type, id) {
		if ($("#resources").length) {
			if (type == 'listing' && typeof id != 'undefined') {
				requestUrl = "/search/recommendedListings"
					+ "?listingId=" + id
					+ "&maxResults=3"
					+ "&offset=2"
					+ "&includeHtml=true";
				$("#resources").show();
				frames["resourcesIframe"].location.replace(requestUrl);
			} else {
				$("#resources").show();
				$.log("showing resources");
				frames["resourcesIframe"].location.replace("/search/resources");		
			}
			
		}
	
	/*
		if ($("#resources").length) {
			$("#resources").show();
			$.log("showing resources");
			frames["resourcesIframe"].location.replace("/search/resources");			
		}
	*/
	},
	
	loadingDiv : '<div style="padding: 50px 0; text-align:center; font-size: 12px;"><img src="/images/ajax-loader.gif" />loading results...</div>'
}

/************************ map ***********************/
	
hotpads.map = {
	
	loaded : false,
	
	insertMap : function(varsXml, flashProxyId, dev, noPermalink) {
		$.log('inserting map: ' + varsXml);
		
		//nopermalink for when we don't want to do # style linking 
	
		if ($.browser.msie && !noPermalink) //dont know why this works but it does, fixes changing anchors causing reload when page is result of redirect in ie
			window.location.hash = window.location.hash;
		
		$('#mapDiv').mousewheel(function(event) {
			return false;
		});
		
		$("#mapDiv").css("height", ""); //get rid of height:100% on mapdiv, breaks ie6
		$(window).resize(function(){
			hotpads.map.resize();
		});
		
		hotpads.map.resize();
		
		//get rid of line breaks and turn " into '
		varsXml = varsXml.replace(/\n/g, ""); 
		varsXml = varsXml.replace(/\"/g, "\'");

		var flashVars = "varsXml=" + varsXml + "&dev=" + dev;
		var so = new SWFObject(mapper_location, "mapper", "100%", "100%", "9", "#000");
		so.addParam("quality", "high");
		so.addParam("menu", "false");
		so.addParam("scale", "noscale");
		so.addParam("allowScriptAccess", "always");
		so.addParam("swLiveConnect", "true");
		if (hotpads.map.api && hotpads.map.api.fullViewsAbove == true)
			so.addParam("wmode", "opaque"); //for api to put fullviews above the map
		so.addParam("FlashVars", flashVars);
		so.useExpressInstall('http://hotpads.com/FlashJavascriptIntegration/expressInstall.swf');
		so.write("mapDiv");
				
		$.log("flash code written");
		
		if ($('#noflash').length) //if user has flash, SWFObject will overwrite the noflash div with the flash movie
		{
			$('#flashLoading').hide();
			var noflash = "In order to use the map-based real estate search on Hotpads.com, you need to have Adobe Flash Player installed.<br/><br/>" +
			  	"<a href='http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash'>download Flash Player now</a><br/>" +
			  	'or <br/><a href="#" onclick="hotpads.filter.setSearcher(\'text\',$.param($.deserialize(initialSearchStateVars, hotpads.filter.LOCATION_PARAMS)));">switch to text search</a>.';
			$('#noflash').html(noflash);
			$('#noflash').css('display', 'block');
			return;
		}
		
		$('#mapper').focus(); 
		
		mapDWR.mapLoaded();
		
	},
	
	resize : function() {
		if ($('#mapperWrapper').length){
			var resourcesHeight = ($("#resources").length && $("#resources").css('display') != 'none') ? 315 : 0;
			var mapHeight = hotpads.map.getTargetMapDimensions().height;
			$('#mapperWrapper').height(mapHeight);
			hotpads.advancedFilterView.resize();
		}			
	},
	
	getTargetMapDimensions : function() {
		var vOffset = $('#searchWindow').offset().top + 2;
		var dims = {
			width : $('#searchWindow').width(),
			height : $(window).height() - vOffset
		};
		return dims;
	}, 
	
	recenter : function() {
		hotpads.map.moveMapCenter(mapLat, mapLon, mapZoom);
	},

	moveMapToCity : function(latlonzoomid) {
		//latlonzoomid is in form lat_lon_zoom_id
		arr = latlonzoomid.split("_");
		lat = arr[0];
		lon = arr[1];
		zoom = Number(arr[2])-1;
		id = arr[3];
		hotpads.map.moveMapCenter(lat,lon,zoom);
	},
	moveMapCenter : function(lat, lon, zoom, shouldUpdatePermalink)
	{	
		if (typeof shouldUpdatePermalink == 'undefined') shouldUpdatePermalink = true;
		hotpads.map.getMapper().moveMapCenter(Number(lat), Number(lon), Number(zoom), shouldUpdatePermalink);
	}, 
	
	setAsFavorite : function(listingId, added) {
		$.log('setAsFavorite: ' + listingId + ', ' + added);
		hotpads.map.getMapper().setAsFavorite(listingId, added);
	},
	
	getMapper : function() { 
		return hotpads.map.getFlashMovie("mapper");
	},
	
	getFlashMovie : function(movieName) {
	   if (navigator.appName.indexOf("Microsoft") != -1) {
	        return window[movieName];
	   } else {
	        return document[movieName];
	   }
	},
	
	moveMapToAndPreview : function(listingId, lat, lon) {
		if (typeof (hotpads.map.getMapper()) != 'undefined' && hotpads.map.loaded){
			hotpads.map.getMapper().moveMapToAndPreview(listingId, lat, lon);
		}
		loadFullView(listingId);
	},
	
	moveMapToAndPreviewArea : function(areaId, lat, lon, zoom){
		if (typeof (hotpads.map.getMapper()) != 'undefined' && hotpads.map.loaded){
			hotpads.map.moveMapCenter(lat,lon,zoom);
			//hotpads.map.getMapper().moveMapToAndPreview(areaId, lat, lon); //TODO use this instead ********************************
		}
		loadAreaFullView(areaId);
	},
	
	locationParams : '',
	fullViewParams : '',
	
	load : function(listingFilterString, locationParams, fullViewParams, searcherParams, shouldUpdatePermalink){
		$.log('loading map: '+listingFilterString+'\n'+locationParams+'\n'+fullViewParams+'\n'+searcherParams);
		scroll(0,0);
		$('#searchWindow').html(hotpads.base.loadingDiv);
		
		var urlString = 'http://' + window.location.host + '/search?mapFragment=true'

		urlString += '&' + listingFilterString;
		urlString += isEmpty(locationParams) ? '' : '&' + locationParams;
		urlString += isEmpty(fullViewParams) ? '' : '&' + fullViewParams;
		urlString += isEmpty(searcherParams) ? '' : '&' + searcherParams;
		$.ajax({
			url : urlString,
			success : function(data){
				if (hotpads.filter.currentSearcher == 'map'){
					$('#searchWindow').html(data);
					hotpads.map.loaded = true;
				}
			}
		});
		hotpads.base.updateFullView(fullViewParams);
	},
	
	unload : function(){
		hotpads.map.loaded = false;
	},
	
	update : function(listingFilterString, locationParams, fullViewParams, searcherParams, shouldUpdatePermalink){
		$.log('updating map: '+listingFilterString+'\n'+locationParams+'\n'+fullViewParams+'\n'+searcherParams);
		
		hotpads.map.fullViewParams = fullViewParams;
		hotpads.map.locationParams = locationParams;
		
		
		hotpads.base.updateFullView(fullViewParams);
		
		if (hotpads.map.loaded){
			var loc = (!isEmpty(locationParams)) ? $.deserialize(locationParams) : {};
			var params = '';
			params += isEmpty(fullViewParams) ? '' : fullViewParams;
			params += isEmpty(searcherParams) ? '' : '&' + searcherParams;			
			params = params.replace(/&{1,}/g,'&');
			
			shouldUpdatePermalink =  typeof(shouldUpdatePermalink) == 'undefined' || shouldUpdatePermalink;
			
			if (typeof (hotpads.map.getMapper()) != 'undefined'){
				if (!isEmpty(loc.lat) && !isEmpty(loc.lon) && !isEmpty(loc.zoom)){
					hotpads.map.moveMapCenter(loc.lat, loc.lon, loc.zoom, shouldUpdatePermalink);
				}
				if (params != ''){
					hotpads.map.getMapper().setMapConfig(params, shouldUpdatePermalink);
				}
				var mapper = hotpads.map.getMapper();
				mapper.setListingFilter(listingFilterString, shouldUpdatePermalink);
			}
		}
	},
	
	changeLocation : function(newLocationName) {
		if (typeof (hotpads.map.getMapper()) != 'undefined' && hotpads.map.loaded){
			hotpads.map.getMapper().setLocation(newLocationName);
		}		
	},
	
	getLocation : function() {
		if (typeof (hotpads.map.getMapper()) != 'undefined' && hotpads.map.loaded){
			return $.param($.deserialize(hotpads.map.getMapper().getMapConfig(), hotpads.filter.LOCATION_PARAMS));
		} else {
			return hotpads.map.locationParams;
		}
	},

	getOrderParams : function() {
		if (typeof (hotpads.map.getMapper()) != 'undefined' && hotpads.map.loaded){
			return $.param($.deserialize(hotpads.map.getMapper().getListingFilter(), hotpads.filter.ORDER_PARAMS));
		} else {
			return '';
		}
	},
	
	getFullViewParams : function(){
		if (typeof (hotpads.map.getMapper()) != 'undefined' && hotpads.map.loaded){
			return $.param($.deserialize(hotpads.map.getMapper().getMapConfig(), hotpads.filter.FULL_VIEW_PARAMS));
		} else {
			return hotpads.map.fullViewParams;
		}
	},
	
	closeFullView : function(){
		if (typeof (hotpads.map.getMapper()) != 'undefined' && hotpads.map.loaded){
			hotpads.map.getMapper().setFullViewShowing(false);
		}
		hotpads.base.closeFullView();
	} 
};

isEmpty = function(str){
	return typeof(str) == 'undefined' || str == '';
};
/************** flash callable functions ******************/
loadNewWindowFullView = function(url) {
	if(!hotpads.filter.advancedFilterOpen){
		hotpads.base.closeFullView();
	}			
	var win = window.open(url);
	var blocked = win == null || typeof(win) == 'undefined';
	//TODO notify user that the popup was blocked?
	if (typeof (hotpads.map.getMapper()) != 'undefined' && hotpads.map.loaded){
		//let map open previews
		hotpads.map.getMapper().setFullViewShowing(false);
	}
};

var LISTING_FULL_VIEW_BASE = "/search/listing/";
var AREA_FULL_VIEW_BASE = "/search/area/";
var CUSTOM_FULL_VIEW_BASE = "/search/";
var OPFVNW_VARS = "?emptyType=true";
var FV_VARS = "?header=false&emptyType=true&iframe=true";

loadFullView = function(listingId)
{
	$.log('loading fullview: ' + listingId);
	openFullViewId = listingId;
	fullViewType = 'listing';	
	if (openFullViewsNewWindow) {
		loadNewWindowFullView(LISTING_FULL_VIEW_BASE + listingId + OPFVNW_VARS);
	} else {
		hotpads.base.loadIframe(LISTING_FULL_VIEW_BASE + listingId + FV_VARS);
	}
};

loadAreaFullView = function(areaId){
	openFullViewId = areaId;
	fullViewType = 'area';
	if (openFullViewsNewWindow) {
		loadNewWindowFullView(AREA_FULL_VIEW_BASE + areaId + OPFVNW_VARS);
	} else {
		hotpads.base.loadIframe(AREA_FULL_VIEW_BASE + areaId + FV_VARS);
	}
};

loadCustomFullView = function(fvId){
	openFullViewId = fvId;
	fullViewType = 'custom';
	if (openFullViewsNewWindow) {
		loadNewWindowFullView(CUSTOM_FULL_VIEW_BASE + fvId + OPFVNW_VARS);
	} else {
		hotpads.base.loadIframe(CUSTOM_FULL_VIEW_BASE + fvId + FV_VARS);
	}
};

setPermalink = function(plstring){
	if (_plstring != plstring)
	{
		_plstring = plstring;
		_plstringChanged = true;
	}
};

setLinkVars = function(plstring){
	if (plstring.substr(0,1) == "&")
		plstring = plstring.substr(1, plstring.length);
	if ($("#saveSearchLink").length)
		$("#saveSearchLink").attr("href", "/users/editSearch.htm?" + plstring);
	if ($("#feedSearchLink").length)
		$("#feedSearchLink").attr("href", "/searchRSS.xml?" + plstring);
	if ($("#kmlSearchLink").length)
		$("#kmlSearchLink").attr("href", "/syndicate/search.kml?" + plstring);
};

_plstring = '';
_plstringChanged = false;

historyChange = function(newLoc, historyData) {
	if (historyInitialized){
		hotpads.filter.init(initialSearchStateVars, newLoc, false);
	}
};

updatePermalink = function(plstring) {
	if (_plstringChanged == true) {
		_plstringChanged = false;
		if (plstring.substr(0,1) == "&")
			plstring = plstring.substr(1, plstring.length);
		dhtmlHistory.add(plstring, null);		
	} 
};

//called on any flash event
flashEvent = function(event) {
};

addToFavorites = function(id)
{
	$.log("adding favorite to dwr");
	mapDWR.toggleFavorite(id, addToFavoritesCallback);
};

addToHidden = function(id)
{
	$.log("adding hidden to dwr");
	mapDWR.toggleHidden(id, addToHiddenCallback);
};

addToHiddenCallback = function(added)
{
	$.log("addToHiddenCallback, adding to map");
	
	hotpads.map.getMapper().addToHiddenCallBack(added == "true" ? true : false);
};

addToFavoritesCallback = function(added)
{
	$.log("addToFavoritesCallback, adding to map");
	
	hotpads.map.getMapper().addToFavoritesCallBack(added == "true" ? true : false);
};

setFullViewShowing = function(open) {
	if (open == false) {
		hotpads.base.closeFullView();
	} else {
		//open the full view
		//does nothing right now, never called
		//loadFullView or loadAreaView are called instead
	}
};

/******************************************* listing view ********************************************/

hotpads.listing = {

	photosWidth : 72+6, //photos width in pixels + 6 pixels right padding
	
	init : function(listingId)
	{
		searchViewDWR.registerRealFullViewEvent(listingId);
		
		$.log("fullViewInit called");
		
		if (window.location.hash == '#notes') {
			//support #notes from userSearch pages
			hotpads.listing.showAddNote();
		}

		hotpads.listing.getRecommendedListings(listingId);
		
		//TODO do this onresize also		
		var numPhotosShown = Math.floor($("#photosUL").width() / hotpads.listing.photosWidth);
		if ((numPhotos - numPhotosShown) > 0) {
			//show more photos link if needed
			$("#showPhotosLink").show();
			$("#numberPhotos").text((numPhotos - numPhotosShown) + ' more');
		}	
		
		hotpads.listing.placeAds();
		$(window).resize(function(){
			hotpads.listing.placeAds();
		});
	},
	
	currentTab : 'information',
	
	openTabWithScoll : function(tab, listingId, divToScrollTo) {
		hotpads.listing.openTab(tab, listingId);
		try {
			window.scrollTo(0, $(divToScrollTo).offset().top - 75);
		} catch (e) { }
	},
	
	openTab : function(tab, listingId)
	{ 
		$.log("opening tab " + tab);
		
		if (tab != hotpads.listing.currentTab)
		{
			$("#" + hotpads.listing.currentTab + '-li').removeClass('selected');
			$("#" + hotpads.listing.currentTab + '-tab').hide();
			$("#" + tab + '-tab').show();
			hotpads.listing.currentTab = tab;
			$("#" + hotpads.listing.currentTab + '-li').addClass('selected');
			$("#" + hotpads.listing.currentTab + '-li a').blur();
			
			if (typeof(hs) != "undefined") { /* if any photos are open, close them so they don't show over new tab content */
				hs.close();
			}
		}
		
		//hide ads if moving to non-main tab, otherwise
		//replace them in the correct spot
		if (tab == 'information') {
			hotpads.listing.placeAds();
			$(".realAds").css("display", "block");
		} else {
			$(".realAds").css("display", "none");
		}
		
		if (tab == "mortgage-calculator") {
			parent.hotpads.base.resizeIframe(1600);	
		} else {
			hotpads.listing.resizeParentIframe();
		}
		
		if (tab == "floorplans") {
			$.get('/search/analytics?action=searchSwitchListingTabFloorplans&listingId='+ listingId +'&seed=' + Math.random());
		} else if (tab == "similar") {		
			$.get('/search/analytics?action=searchSwitchListingTabSimilar&listingId='+ listingId +'&seed=' + Math.random());
		} else if (tab == "statistics") {		
			$.get('/search/analytics?action=searchSwitchListingTabStatistics&listingId='+ listingId +'&seed=' + Math.random());
		} else if (tab == "mortgage-calculator") {		
			$.get('/search/analytics?action=searchSwitchListingTabMortgageCalculator&listingId='+ listingId +'&seed=' + Math.random());
		}
	},
	
	resizeParentIframe : function() {
		hotpads.base.resizeParentIframe();
	},
	
	/* returns largest number in given array */
	largest : function(array) {
		var large = 0;
		for (i in array) {
			if (array[i] > large)
				large = array[i];
		}
		return large;
	},
		
	moveMapToAndView : function(listingId, lat, lon) {
		if (parent && parent.hotpads.map.moveMapToAndPreview) {
			$.log("moveMapToAndViewing");
			parent.hotpads.map.moveMapToAndPreview(listingId, lat, lon);
		}
	},
	
	moveMapToAndViewArea : function(areaId, lat, lon, zoom){
		if (parent && parent.hotpads.map.moveMapToAndPreviewArea) {
			$.log("moveMapToAndViewingArea");
			parent.hotpads.map.moveMapToAndPreviewArea(areaId, lat, lon, zoom);
		}else{
			hotpads.map.moveMapToAndPreviewArea(areaId, lat, lon, zoom);
		}
	},
	
	moveMapToAndViewCustom : function(id, type, lat, lon, zoom){
		var params = "?header=false&emptyType=true&iframe=true";
		var splitId = id.split("\?");
		if(splitId.length>1){
			params = params+"&"+splitId[1];
		} 
		
		if(parent){
			if (typeof (parent.hotpads.map.getMapper()) != 'undefined' && parent.hotpads.map.loaded){
				parent.hotpads.map.moveMapCenter(lat,lon,zoom);
			}
			parent.openFullViewId = id;
			parent.fullViewType = type;
			parent.hotpads.base.loadIframe("/search/" + splitId[0] + params);
		}else{
			openFullViewId = id;
			fullViewType = type;
			hotpads.base.loadIframe("/search/" + splitId[0] + params);
		}
	},
	
	validateEmail : function(emailToTest) {
		//var regex = /^[A-Z][\w\.\+\-]+[A-Z0-9]@[A-Z0-9][\w\.-]*[A-Z0-9]\.[A-Z][A-Z\.]*[A-Z]/gi;
		var regex = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
		return regex.test(emailToTest);
	},
		
	showEmailFriend : function(adBelow){
		if ($("#emailFriendSurround:hidden").length)
		{
			if ($("#addNoteSurround").attr("display") != "block") {
				hotpads.listing.hideAddNote(adBelow);
			}
			if (adBelow == "true")
				$('#realSquaread').css('visibility', 'hidden'); 
			$("#emailFriendSurround").slideDown("fast");
		}
		else 
		{ 
			hotpads.listing.hideEmailFriend(adBelow);
		}
	},	
	
	hideEmailFriend : function(adBelow)
	{
		$(".emailFriendItem").slideUp("fast");
		if (adBelow)
			$('#realSquaread').css('visibility', 'visible'); 
	},
	
	trim : function(stringToTrim) {
		return stringToTrim.replace(/^\s+|\s+$/g,"");
	},
	
	sendEmailFriend : function(listingId)
	{
		var emailFriendBean = { "from" : null, "to" : null, "message" : null , "emailFriendUser" : false};
		emailFriendBean.from = $("#fromEmailFriend").val();
		if (hotpads.listing.validateEmail(emailFriendBean.from) == false) {
			alert("Oops.. it looks like the email address you entered for \"your email\" is not valid!");
			return;
		}
		emailFriendBean.to = $("#toEmailFriend").val();
		emailFriendBean.emailFriendUser = $("#emailFriendUser").attr('checked');
		if (hotpads.listing.validateEmail(emailFriendBean.to) == false) {
			//also need to validate for semicolon and comma delimited lists of email addresses
			var invalid = false;
			splitSemicolon = emailFriendBean.to.split(";");
			if (splitSemicolon.length > 1) {
				for (i = 0; i < splitSemicolon.length; i++) {
					if (hotpads.listing.validateEmail(trim(splitSemicolon[i])) == false)
						invalid = true;				
				}
			}
			splitComma = emailFriendBean.to.split(",");
			if (splitComma.length > 1) {
				for (i = 0; i < splitComma.length; i++) {
					if (hotpads.listing.validateEmail(hotpads.listing.trim(splitComma[i])) == false)
						invalid = true;
				}
			}
			if (invalid == true) {
				alert("Oops.. it looks like the email address(es) you entered for \"friend's email\" is not valid!");
				return;
			}
		}
		emailFriendBean.message = $("#messageEmailFriend").val();
		emailFriendBean.listingId = listingId;
		searchViewDWR.sendEmailFriend(emailFriendBean, hotpads.listing.emailFriendCallback);
		hotpads.listing.toggleLoadingEmailFriend();
	},
	
	toggleLoadingEmailFriend : function()
	{
		$("#emailFriendTable").toggle();
		$("#emailFriendDidYouKnow").toggle();
		$("#emailFriendLoading").toggle();
	},
	
	emailFriendCallback : function(success)
	{		
		$("#emailFriendSurround").fadeOut("fast");
		hotpads.listing.toggleLoadingEmailFriend();
		
		if (success == true) 
		{
			$("#successEmailFriendMsg").html("We emailed your message and a link to this listing.<br/><br/>Thanks for using HotPads!");
			$("#successEmailFriend").fadeIn("fast");
		}
		else
		{
			$("#failureEmailFriend").fadeIn("fast");
		}	
	},

	/*** add note ***/
	showAddNote : function(adBelow){
		if ($("#addNoteSurround:hidden").length)
		{
			if ($("#emailFriendSurround").attr("display") != "block") {
				hotpads.listing.hideEmailFriend(adBelow);
			}
			if (adBelow == "true")
				$('#realSquaread').css('visibility', 'hidden'); 
			$("#addNoteSurround").slideDown("fast");
		}
		else 
		{
			hotpads.listing.hideAddNote(adBelow);
		}
	},	
	
	hideAddNote : function(adBelow)
	{
		$(".addNoteItem").slideUp("fast");
		if (adBelow == "true")
			$('#realSquaread').css('visibility', 'visible'); 
	},
	
	addNote : function(listingId)
	{
		var message = $("#messageAddNote").val();
		searchViewDWR.saveNote(listingId, message, hotpads.listing.addNoteCallback);
		hotpads.listing.toggleLoadingAddNote();
	},
	
	toggleLoadingAddNote : function()
	{
		$("#addNoteTable").toggle();
		$("#addNoteDidYouKnow").toggle();
		$("#addNoteLoading").toggle();
	},
	
	addNoteCallback : function(success)
	{		
		$("#addNoteSurround").fadeOut("fast");
		hotpads.listing.toggleLoadingAddNote();
		
		if (success == true) 
		{
			$("#successAddNoteMsg").html("Your note has been added.  You can find it again later on the <a href='/userSearch/note/list' target='_blank'>Notes</a> section of your <a href='/userSearch/favorite/list'>Favorites</a>");
			$("#successAddNote").fadeIn("fast");
		}
		else
		{
			$("#failureAddNote").fadeIn("fast");
		}	
	},
	
	contactBoxTransfer : function(me) 
	{
		$(me).effect('transfer', 
					{ 
					  to:'#contact'
					}, 
					1000);
		setTimeout(function() {
						$("#contact").css('border','solid 1px #055C8A');
					},
					1000);

	},
	
	showContactInfo : function(listingId) {
		var eles = $(".showContactInfo");
		eles.html('<span id="contactLoader"><img src="/images/ajax-loader.gif" /> Loading...</span>');
		hotpads.listing.getContactInfoByListingId(listingId, eles);
	},
	
	getContactInfoByListingId : function(id, eles){
		searchViewDWR.getContactInfoByListingId(id, 
							function(msg) { 
								eles.html(msg); 
							});
	},
	
	toggleFavorites : function(id) {
		$("#favoritesCaption").html("<img src='/images/ajax-loader.gif' />");
		searchViewDWR.toggleFavorite(id, hotpads.listing.toggleFavoritesCallback);
	},
	
	toggleHidden : function(id) {
		$("#hiddenCaption").html("<img src='/images/ajax-loader.gif' />");
		searchViewDWR.toggleHidden(id, hotpads.listing.toggleHiddenCallback);
	},
	
	toggleFavoritesCallback : function(added)
	{	
		if (added == "true") {
			$("#favoritesCaption").html("unfavorite");
			$("#addToFavoritesIcon").removeClass("sprite-favoriteOff").addClass("sprite-favoriteOn");
			if (hotpads.fb && hotpads.fb.fbUID != null) {
				hotpads.fb.shareFavorite(listingType, listingName, listingLink);
			}
		} else {
			$("#favoritesCaption").html("add to favorites");
			$("#addToFavoritesIcon").removeClass("sprite-favoriteOn").addClass("sprite-favoriteOff");
		}
		if (parent) {
			parent.hotpads.searcher.setAsFavorite(listingId, added);
		} else {
			hotpads.searcher.setAsFavorite(listingId, added);
		}

	},
	
	toggleHiddenCallback : function(added)
	{	
		if (added == "true") {
			$("#hiddenCaption").html("unhide");
			$("#addToHiddenIcon").removeClass("sprite-hiddenOff").addClass("sprite-hiddenOn");
		} else {
			$("#hiddenCaption").html("hide");
			$("#addToHiddenIcon").removeClass("sprite-hiddenOn").addClass("sprite-hiddenOff");
		}
		if (parent) {
			parent.hotpads.searcher.setAsHidden(listingId, added);
		} else {
			hotpads.searcher.setAsHidden(listingId, added);
		}

	},
		
	showInquiryBox : function(origin,listingId,message){
		hotpads.listing.openTab('information',listingId);
		if(origin) hotpads.listing.contactBoxTransfer(origin);
		if(message) $("#messageEmailManager").val(message);
		
	},
		
	submitInquiry : function(strict,requireMovingDate)
	{
		if (inqs >= 4) {
			alert("Sorry, you've sent too many inquiries for the moment.  If you need to contact the manager again, please try again later.  If you feel you have received this message in error, please contact us at info@hotpads.com"); 
			return;
		}
		
		var nameRe = /^\w+\s\w+/;
		var dateRe = /^\d{2}\W\d{2}\W\d{2,4}$/;
		var usPhoneRe = /^\W*\d{0,1}\W*\d{3}\W*\d{3}\W*\d{4}.*$/;
		var formBean = { "listingId" : null, 
		"name" : null, 
		"email" : null, 
		"phone" : null, 
		"moveDate" : null, 
		"beds" : null, 
		"baths" : null, 
		"text" : null,
		"numAdults" : null,
		"numChildren" : null,
		"checkInDate" : null,
		"checkOutDate" : null,
		"emailUser" : null};
		formBean.listingId =  $("#hiddenListingId").val();
		formBean.name = $("#nameEmailManager").val();
		if (formBean.name == "your name*" || formBean.name == "") {
			alert("Oops.. it looks like you didn't put your name in.");
			return;
		}
		if (strict && !nameRe.test(formBean.name)){
			alert("Please enter your first and last name.");
			return;
		}
		formBean.email = $("#emailEmailManager").val();
		if (formBean.name == "your email*") {
			alert("Oops.. it looks you didn't put in an email address.");
			return;
		}
		if (formBean.email == '' || hotpads.listing.validateEmail(formBean.email) == false) {
			alert("Oops.. it looks like the email address you entered is invalid! It must be a valid email address in order to contact the manager.");
			return;
		}
		
		formBean.phone = $("#phoneEmailManager").val();
		if (!strict && formBean.phone == "your phone number") {
			formBean.phone = "";
		} else if((strict || formBean.phone!='') && !usPhoneRe.test(formBean.phone)){
			alert("Please enter your entire phone number, including area code.");
			return;
		}
		
		formBean.moveDate = $("#movingDateEmailManager").val();
		if (formBean.moveDate == "moving date") {
			formBean.moveDate = "";
		}
		if (requireMovingDate && !dateRe.test(formBean.moveDate)){
			alert("Please enter approximate moving date in the form mm/dd/yyyy");
			return;
		}
		
		if ($("#bedsEmailManager").length) {
			formBean.beds = $("#bedsEmailManager").val();
			if (formBean.beds == "# beds") {
				formBean.beds = "";
			}
		}
		if ($("#bathsEmailManager").length) {
			formBean.baths = $("#bathsEmailManager").val();
			if (formBean.baths == "# baths") {
				formBean.baths = "";
			}
		}
		
		var dateRegExp = /\d{1,2}\/\d{1,2}\/\d{4}/;
		
		if ($("#arriveDate").length) {
			formBean.checkInDate = $("#arriveDate").val();
			if (formBean.checkInDate == "check-in date") {
				formBean.checkInDate = "";
			}
			if(!dateRegExp.test(formBean.checkInDate)){
				alert("Oops.. it looks your check-in date is in the wrong format. Please use MM/DD/YYYY.");
				return;
			}
		}
		
		if ($("#departDate").length) {
			formBean.checkOutDate = $("#departDate").val();
			if (formBean.checkOutDate == "check-out date") {
				formBean.checkOutDate = "";
			}
			if(!dateRegExp.test(formBean.checkOutDate)){
				alert("Oops.. it looks your check-out date is in the wrong format. Please use MM/DD/YYYY.");
				return;
			}
		}
		
		if ($("#numAdults").length) {
			formBean.numAdults = $("#numAdults").val();
			if (formBean.numAdults == "# adults") {
				formBean.numAdults = "";
			}
		}
		
		if ($("#numChildren").length) {
			formBean.numChildren = $("#numChildren").val();
			if (formBean.numChildren == "# children") {
				formBean.numChildren = "";
			}
		}
		
		formBean.text = $("#messageEmailManager").val();
		if (formBean.text == "your questions go here!") {
			formBean.text = "I'm interested - please contact me!"; //put a default message
		}
		formBean.emailUser = $("#emailUser").attr('checked');
		$("#inqForm").hide();
		$("#loadingEmailManager").show();
		
		frames["afterInquiry"].location.href = "/pages/afterInquiry.htm";

		searchViewDWR.submitInquiry(formBean, hotpads.listing.inquiryCallback);
	},
		
	inquiryCallback : function(success)
	{
		$("#loadingEmailManager").hide();
		if (success == true) 
		{
			inqs++;
			if($("#similar-li".length) && $('#similar-li').is(':visible')){
				$("#recommendedListings").slideUp();
			}
			$("#successEmailManager").slideDown("normal", hotpads.listing.placeAds);
		}
		else
		{
			$("#failureEmailManager").show("normal", hotpads.listing.placeAds);
		}

	},
	
	closeSuccessEmailManager : function()
	{
		$("#successEmailManager").hide();
		$("#inqForm").show();
	},
	
	closeFailureEmailManager : function()
	{
		$("#failureEmailManager").hide();
		$("#inqForm").show();
	},
		
	saveNote : function(listingId)
	{
		$("#saving-note").toggle();
		searchViewDWR.addNote(listingId, $("#noteTextArea").val(), function(){ $("#saving-note").toggle();  $("#note-saved").show(); });
	},
	
	showModel : function(modelId) {
		var alreadyShowing = false;
		if ($("#" + modelId + "-info").css("display") != "none")
			alreadyShowing = true;
			
		$('.modelshowing').hide().removeClass('modelshowing'); 
	
		if (!alreadyShowing)
			$('#'+ modelId +'-info').toggle().addClass('modelshowing');
		hotpads.listing.resizeParentIframe();
	},	
	
	sharePosting : function(listingId, uid, sessionKey) { 
		var comments = $("#hpfbComments").val();
		var privacy = $("#hpfbPrivacy").val();
		var postToProfile = $("#hpfbPostToProfile").val();
		$("#savingFBPost").show();
		fbShareListing.shareListing(listingId, comments, privacy, postToProfile, uid, sessionKey, sharePostingCallback);
	},
	
	sharePostingCallback : function(success) {
		$("#savingFBPost").hide();
		if (success == true) {
			$("#failureFBPost").hide();
			$("#successFBPost").show();
		}
		else {
			$("#successFBPost").hide();
			$("#failureFBPost").show();
		}
	},
	
	getRecommendedListings : function(listingId) {
		if ($("#recommendedListings").length && typeof listingId != 'undefined') {
			requestUrl = "/search/recommendedListings"
				+ "?listingId=" + listingId
				+ "&maxResults=2";
            var url = window.location.href;

            if (url.indexOf("emptyType=true") != -1 && url.indexOf("iframe=true") == -1) {
            	requestUrl += "&emptyType=true";
            }
				
			$.ajax({
				async:	false,
				url: 	requestUrl,
				success:function(data){
							$('#recommendedListings').fadeOut('fast', function () {
								$('#recommendedListings').html(data);
								$('#recommendedListings').fadeIn('fast', function() {
									hotpads.listing.placeAds();
								});
							});
						}
			});	
		}
	},
	
	//place absolutely positioned ads in the correct spot
	//#belowContactBoxAd and #squaread changes position based on recommended listings, available contact info, etc
	placeAds : function() {
		if ($("#squaread").length != 0) {
			var squareOffset = $("#squaread").offset().top + 9;
//			$.log("squareOffset: " + squareOffset + ", iframe: " + iframe + ", header:" + header + ", emptyType:" + emptyType);
			if (iframe) {
				$("#realSquaread").css('top', squareOffset);
			} else if (header && emptyType) {
				$("#realSquaread").css('top', squareOffset-69);
			} else {
				$("#realSquaread").css('top', squareOffset-120);
			}
	
	        $("#realSquaread").css("left", ($("#squaread").offset().left + 8) + "px" );
	        $("#realSquaread").css("right", "auto");
		
		}
		
		if ($("#belowContactBoxAd").length != 0) {
		var offset = $("#belowContactBoxAd").offset().top;
		if (iframe) {
			$("#realBelowContactBoxAd").css('top', offset);
		} else if (header && emptyType) {
			$("#realBelowContactBoxAd").css('top', offset-50);
		} else {
			$("#realBelowContactBoxAd").css('top', offset-115);
		}

        $("#realBelowContactBoxAd").css("left", $("#belowContactBoxAd").offset().left + "px");
        $("#realBelowContactBoxAd").css("right", "auto");
		}
	}
};

/************** custom view ******************/

hotpads.customView = {
	resizeParentIframe : function() {
		hotpads.base.resizeParentIframe();
	}	
}

/************** advanced filter view ********************/
	
hotpads.advancedFilterView = {

	isOpen : false,

	open : function(){
		if (hotpads.filter.currentSearcher == 'map'){
			//hotpads.map.getMapper().setFullViewShowing(false);
		}
		fullViewType = "advancedFilter";
		fullViewShowing = true;
		hotpads.base.closeRightHalf();
		hotpads.base.makeSpaceForRightSection();
		$("#advancedFilterDiv").show();
		$('#minBedrooms').focus();
		$('#toggleAdvancedLink').html('less&laquo;');
		$('#toggleAdvancedLink2').html('less&laquo;');
		$("#filterBasic").hide();
		hotpads.advancedFilterView.resize();
		hotpads.filter.advancedFilterOpen = true;
		$("#loading").hide();
	},
	close : function(){
		$('#toggleAdvancedLink').html('advanced&raquo;');
		$('#toggleAdvancedLink2').html('advanced&raquo;');
		$("#advancedFilterDiv").hide();
		$("#filterBasic").show();
		hotpads.filter.advancedFilterOpen = false;
	},
	resize : function(){
		if(!hotpads.filter.advancedFilterOpen){
			return
		}
		if($("#mapperWrapper").length){
			$("#advancedFilter").css("height","");
			var contentHeight = 0;
			$(".filterFieldGroup").each(function (i){
			        if ($(this).height() > contentHeight) {
			          contentHeight = $(this).height();
			        }
			});
			contentHeight+=30;
			var mapHeight = $("#mapperWrapper").height();
			$("#advancedFilter").css("height", mapHeight < contentHeight?contentHeight:mapHeight + "px");
			
			var contentWidth = 0;
			$(".filterFieldGroup").each(function (i){
				contentWidth += $(this).width();
			});
			
			contentWidth += 20;
			
			var totalWidth = $("#container").width();
			var rightWidthPercent = Math.ceil(contentWidth/totalWidth*100);
			var leftWidthPercent = Math.floor((totalWidth - contentWidth)/totalWidth*100);
			$(".leftContainer").css("width", leftWidthPercent + "%");
			$(".rightContainer").css("width", rightWidthPercent + "%");
		}
	}
};

/************** area view ********************/

hotpads.areaView = {

	resizeParentIframe : function() {
		hotpads.base.resizeParentIframe();
	},
	
	openTab : function (tab)
	{
		$.log("opening tab to " + tab);
		if (tab != currentTab)
		{
			$("#" + currentTab + '-li').removeClass('selected');
			$("#" + currentTab).hide();
			$("#" + tab).show();
			currentTab = tab;
					
			$("#" + currentTab + '-li').addClass('selected');
			$("#" + currentTab + '-li a').blur();
			
			hotpads.areaView.resizeParentIframe();
		}
		
		if (currentTab == 'info') {
			hotpads.areaView.loadWikiArticle();
		}
	},
	
	wikiArticleLoaded : false,
	
	loadWikiArticle : function() {
		$.log("loadWikiArticle called");
		if (hotpads.areaView.wikiArticleLoaded == false) {
			$.log("loading wikipedia article");
			searchViewDWR.getWikipedia(areaId, function(data) {
				$("#wikiarticle").log("adding wikipedia article").html(data);
				$("#wikiarticle a").attr("target", "_wiki"); //make links open new window
				$("#wikiarticle a[href^=#]").click(function(event) { //make table of content links scroll without messing up permalink
					var href = $(this).attr("href");
					href = href.substring(1, href.length); //get rid of #
					var toLink = $("#wikiarticle a[name=" + href + "]");
					var offset = toLink.offset();
					
					window.scrollTo(0, offset.top);
					return false;
				});	
				hotpads.areaView.resizeParentIframe();
			});
			hotpads.areaView.wikiArticleLoaded = true;
		}
	},
	
	MAX_BIRDSEYE_TIMEOUT : 4000, //wait 4 seconds to let it load, otherwise assume no bird's eye view available
	currentBirdsEyeTimeout : 500,
	map : '',
	
	loadBirdsEye : function () {
		if ($('#birdseye').css("display") != 'none' && areaLabelLat != 0 && areaLabelLon != 0)
		{
			map = new VEMap('myMap');
			
			map.LoadMap(new VELatLong(areaLabelLat, areaLabelLon), 1 /* zoom lvl - 1-19, default is 4*/,'o' /*type of map- o for birds eye, a aerial, h hybird, r road*/,false /*fixed map*/); 
			setTimeout('hotpads.areaView.checkBirdsEyeAvailable()', 500); //have to wait till the map is loaded before we can see bird's eye view is available
		}
	},
	
	checkBirdsEyeAvailable : function()
	{
		if (map.IsBirdseyeAvailable())
		{
			$('#birdseye-loading').css("display", 'none');
			map.SetCenter(new VELatLong(areaLabelLat, areaLabelLon));
			$('#myMap').css("width", '100%');
			$('#myMap').css("margin", '0 0 0 5px');
			$('#myMap').css("visibility", 'visible');
		}
		else
		{ 
			if (hotpads.areaView.currentBirdsEyeTimeout > hotpads.areaView.MAX_BIRDSEYE_TIMEOUT)
			{ //give up
				$('#birdseye-loading').css("display", 'none');
				$('#myMap').css("display", 'none');
				$('#noBirdseye').css("display", 'block');
			}
			else
			{ //dont give up yet
				hotpads.areaView.currentBirdsEyeTimeout += 500;
				setTimeout('hotpads.areaView.checkBirdsEyeAvailable()', 500);
			}
		}
	}
};

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

