// ng presentation
if( !window.listing_default_form_width ) {
	window.listing_default_form_width = 550;
}
window.default_form_height = 480;
window.listing_inquiry_form_height = 450;
window.listing_send_form_height = 480;
window.listing_mortgage_form_height = 460;

window.mrpAccountId = 16092;

if (typeof console == 'undefined') {
	window.console = {};
    window.console.log = function(msg) {
        return;
    };
}

// executes on outer embed side
function mrpInitEmbed()
{
	//console.log( "embed" );
	
	var presenter = null;
	
	var s = document.getElementById( "mrpscript" );
	var p = s.parentNode;
	
	var presenterScript = document.createElement( "script" );
	presenterScript.id = "__mrp_presenter_script";
	presenterScript.type = "text/javascript";
	
	if( typeof presenterScript.onreadystatechange != "undefined" ) {
		presenterScript.onreadystatechange = function() {
			if( this.readyState == 'loaded' || this.readyState == 'complete' ) {
				presenter = new mrp_presenter( {
					base_url : "http://www.coronadohoa.com"
				});
				window.mrp_presenter = presenter;
			}
		};
	}
	else {
		presenterScript.onload = function() {
			presenter = new mrp_presenter( {
				base_url : "http://www.coronadohoa.com"
			});
			window.mrp_presenter = presenter;
		};
	}
	if( typeof window.browser == "undefined" ) {
		window.browser = {};
	}
	//presenterScript.src = "http://www.coronadohoa.com/wps/js/ng/default-presentation.js";
	presenterScript.src = "http://res.myrealpage.com/wps/js/ng/default-presentation.js";
	p.appendChild( presenterScript );
	
	function monitorCommHash()
	{
		var idleHref = window.location.hash;
		var idleHrefIdx = idleHref.lastIndexOf( "#" );
		if( idleHrefIdx != -1 ) {
    		idleHref = idleHref.substring( 0, idleHrefIdx );
		}
		idleHref += "#idle";
			
		var p = __mrp_getParamStartingWith( "pres-photos-" );
		if( p  != null ) {
			//console.log( "got command: " + p );
			
			var index = 0;
			var fullhash = window.location.hash;
			if( fullhash ) {
				var tokens = fullhash.split( "," );
				index = parseInt( tokens[tokens.length-1] );
				if( isNaN( index ) ) {
					index = 0;
				}
			}
			
			// we are doing a .replace to wipe off history entry for lightbox
			window.location.replace( idleHref );
			
			window.location.hash = "#idle";
			var listingId = p.replace( "pres-photos-", "" );
			var tokens = listingId.split( "," );
			if( tokens.length > 1 ) {
				index = parseInt( tokens[1] );
				if( isNaN( index ) ) {
					index = 0;
				}
			}
			
			if( presenter ) {
				presenter.presentMedia( listingId, index );			
			}
			return;
		}
		
		p = __mrp_getParamStartingWith( "pres-map-" );
		if( p  != null ) {
			//console.log( "got command: " + p );
			
			// we are doing a .replace to wipe off history entry for lightbox
			window.location.replace( idleHref );
			
			var listingId = p.replace( "pres-map-", "" );
			
			if( presenter ) {
				presenter.presentMap( listingId, 500 );			
			}
			return;
		}
		
		p = __mrp_getParamStartingWith( "pres-form-" );
		if( p  != null ) {
			//console.log( "got command: " + p );
			
			// we are doing a .replace to wipe off history entry for lightbox
			window.location.replace( idleHref );
			
			var tokens = p.split( "|" );
			if( tokens.length < 2 ) {
				return;
			}
			var formURL = unescape( tokens[0].replace( "pres-form-", "" ) );
			var height = parseInt(tokens[1]) || 0;
			
			if( presenter ) {
				presenter.presentForm( formURL, height );			
			}
			return;
		}
		
		p = __mrp_getParamStartingWith( "pres-close" );
		if( p  != null ) {
		
			// we are doing a .replace to wipe off history entry for lightbox
			window.location.replace( idleHref );
			
			if( presenter ) {
				presenter.clear();
			}
			return;
		}
		
		p = __mrp_getParamStartingWith( "pres-resize-" );
		if( p  != null ) {
		
			// we are doing a .replace to wipe off history entry for lightbox
			window.location.replace( idleHref );
			
			var payload = p.replace( "pres-resize-", "" );
			var tokens = payload.split( "|" );
			if( tokens.length < 2 ) {
				return;
			}
			
			var w = parseInt( tokens[0] );
			var h = parseInt( tokens[1] );
			
			if( isNaN( w ) || isNaN( h ) ) {
				return;
			}
			
			if( presenter ) {
				presenter.resize( w, h );
			}
			return;
		}
	}
	
	setInterval( function() {
		try
		{
			monitorCommHash();
		}
		catch(e)
		{
			console.log( "error in comm: " + e.message );
		}
	}, 500 );
}


// executes on the listing content
function mrpInitListingsPres()
{
	var presenter = null;
	
	// install convenience hooks
	window.showMedia = function( listingId, what, where ) {
		if( what == "map" ) {
			publishToBus( "map.show", {
				listingId: listingId,
				height: 500
			}, false );
		}
		else {
			publishToBus( "image.lightbox", {
				listingId: listingId,
				index: 0
			}, false );
		}
	};
	
	window.showSlideshow = function( listingId ) {
		window.showMedia( listingId );
	};
	
	window.functionalForm = function( url, height ) {
		publishToBus( 'form.show', {
			url : url,
			whereId : "",
			width : listing_default_form_width,
			height : height
			}, false );
	};
	
	window.openIPhoneInquiry = function( url, height ) {
		publishToBus( 'form.show', {
			url : url,
			whereId : "",
			width : listing_default_form_width,
			height : 550
			}, false );
		return false;
	};
	
	window.onEditVowFavorite = function( listingId )
	{
		if( listingId ) {
			publishToBus( "vow.editfavorite", { "listingId" : listingId } );
		}
	};
	
	window.hoverIn = function() {
	};
	window.hoverOut = function() {
	};
	window.hoverInIE = function() {
	};
	window.hoverOutIE = function() {
	};
	
	
	function sendHashCommand( command )
	{
		try
		{
			parent.frames["__mrp_comm"].sendHashCommand( command );	
		}
		catch( e )
		{
		}
	}
	
	function mrpInstallPres()
	{
		var isEmbedded = false;
		var isTop = true;
		var isForFacebook = false;
		
		if( !isForFacebook ) {
			if( window.top && window.top != window ) {
				try
				{
					var src = parent.frames["__mrp_comm"].src;
					// if we are here, we are embedded, otherwise, will get an exception
					isEmbedded = true;
				}
				catch( e )
				{
					isTop = false;
				}
			}
		}
		
		// subscriptions
		
		if( !isEmbedded ) {
			var presenterScript = document.createElement( "script" );
			presenterScript.id = "__mrp_presenter_script";
			presenterScript.type = "text/javascript";
			
			if( typeof presenterScript.onreadystatechange != "undefined" ) {
				presenterScript.onreadystatechange = function() {
					if( this.readyState == 'loaded' || this.readyState == 'complete' ) {
						//console.log( "IE loaded" );
						presenter = new mrp_presenter();
						window.mrp_presenter = presenter;
					}
				};
			}
			else {
				presenterScript.onload = function() {
					//console.log( "regular loaded" );
					presenter = new mrp_presenter();
					window.mrp_presenter = presenter;
				};
			}
			
			if( isForFacebook ) {
				presenterScript.src = "http://res.myrealpage.com/wps/js/ng/popup-presentation.js";
			} 
			else if( isTop ) {
				presenterScript.src = "http://res.myrealpage.com/wps/js/ng/default-presentation.js";
			}
			else {
				presenterScript.src = "http://res.myrealpage.com/wps/js/ng/popup-presentation.js";
			}
			document.body.appendChild( presenterScript );
		}
		
		
		subscribeToBus( [ "image.lightbox", "mediacenter.show" ], null, function( s, m, d ) {
		
			var listingId = m["listingId"];
			var index = m["index"] || 0;
			if( !listingId ) {
				return;
			}
			if( isEmbedded ) {
				sendHashCommand( "pres-photos-" + escape( listingId ) + "," + index );
			}
			else {
				if( !presenter ) {
					return;
				}
				presenter.presentMedia( listingId, index );
			}
		});
		
		subscribeToBus( "map.show", null, function( s, m, d ) {
			
			var listingId = m["listingId"];
			var height = m["height"] || 0;
			
			if( !listingId ) {
				return;
			}
			
			if( isEmbedded ) {
				sendHashCommand( "pres-map-" + escape( listingId ) );
			}
			else {
				if( !presenter ) {
					return;
				}
				presenter.presentMap( listingId, height );
			}
		});
		
		subscribeToBus( "form.show", null, function( s, m, d ) {
			
			var url = m["url"];
			var height = m["height"] || 0;
			
			if( !url ) {
				return;
			}
			
			if( isEmbedded ) {
				sendHashCommand( "pres-form-" + escape(url) + "|" + height );
			}
			else {
				if( !presenter ) {
					return;
				}
				presenter.presentForm( url, height );
			}
		});
	}
	
	mrpInstallPres();
	
	publishToBus( "mrp_js_listings.load", {} );
	//  override
	
}

if( typeof onloads != "undefined" ) {
	onloads.push( mrpInitListingsPres );
}

function mrp_do_jsonp( url, callback, timeout ) {
	
	if( url.indexOf( '?' ) == -1 ) {
		url += '?';
	}
	else {
		url += '&';
	}
	var r = '' + Math.random();
	var idx = r .indexOf( '.' );
	r = r.substring( idx + 1 );
	r = 'cb' + r;
	url += 'callback=' + escape( r );
	
	//alert( url );
	
	window[r] = function( payload, error ) { callback( payload, error ), window[r] = null };
	
	if( ( typeof timeout == 'number' ) && timeout > 0 ) {
		setTimeout( function() {
			if( window[r] ) {
				window[r]( null, { "error" : "Timeout" } );
				window[r] = null;
			}
		}, timeout );
	}
	
	var s = document.createElement( "script" );
	s.type = "text/javascript";
	s.src = url;
	document.body.appendChild( s );
}

function mrpRotateImages( img, listingId )
{
	if( img.parentNode.offsetWidth == 0 ) {
		/* f**king IE */
		setTimeout( function() {
			mrpRotateImages( img, listingId );
		}, 1000 );
		return;
	}
	var jsonURL = "http://res.myrealpage.com/wps/rest/16092/l/" +
			listingId + "/json/photos";
	//var jsonURL = "http://www.coronadohoa.com/wps/rest/16092/l/" +
	//		listingId + "/json/photos";
			
	var container = img.parentNode;
	var cW = container.offsetWidth;
	var cH = container.offsetHeight;
	
	var stopped = true;
	
	var controlImg = null;
	
	var curImage = img;
	var origOnclick = img.onclick;
	var inTransition = false;
	var curIndex = 0;
	
	var curSeq = 0;
	
	function doInit( images )
	{
		controlImg = document.createElement( "img" );
		controlImg.style.width = "80px";
		controlImg.style.height = "80px";
		controlImg.src = "/wps/img/play.png";
		controlImg.style.position = "absolute";
		controlImg.style.zIndex = 100;
		controlImg.style.opacity = 0.7;
		controlImg.style.filter = "alpha(opacity=70)";
		controlImg.style.display = "none";
		controlImg.style.left = "50%";
		controlImg.style.top = "50%";
		controlImg.style.marginLeft = "-40px";
		controlImg.style.marginTop = "-40px";
		controlImg.style.cursor = "pointer";
		if( images.length < 2 ) {
			controlImg.style.visibility = "hidden";
		}
		
		controlImg.onclick = function() {
		
			if( stopped ) {
				if( inTransition ) {
					return;
				}
				stopped = false;
				this.src = "/wps/img/pause.png";
				curSeq = Math.random();
				showImage( images, curIndex + 1, curSeq );
			}
			else {
				curSeq = 0;
				stopped = true;
				this.src = "/wps/img/play.png";
			}
		};
		
		container.appendChild( controlImg );
		
		curImage.onmousemove = function() {
			controlImg.style.display = "block";
		};
		curImage.onmouseout = function() {
			controlImg.style.display = "none";
		};
		curImage.onmouseleave = function() {
			controlImg.style.display = "none";
		};
		controlImg.onmouseover = function() {
			controlImg.style.display = "block";
		};
	}
	
	function transition( prevImg, nextImg, step, totalSteps, incr, callback )
	{
		var diffSteps = totalSteps - step;
		
		var prevOpacity = incr * diffSteps;
		var nextOpacity = incr * step;
		
		prevImg.style.opacity = prevOpacity;
		nextImg.style.opacity = nextOpacity;
		prevImg.style.filter = "alpha(opacity=" + (prevOpacity * 100 ) + ")";
		nextImg.style.filter = "alpha(opacity=" + (nextOpacity * 100 ) + ")";
		
		if( step >= totalSteps ) {
			try
			{
				container.removeChild( prevImg );
			}
			catch( e )
			{
				debugger;
			}
			curImage = nextImg;
			inTransition = false;
			if( callback ) {
				callback();
			}
		}
		else {
			setTimeout( function() {
				transition( prevImg, nextImg, step+1, totalSteps, incr, callback );
			}, 50 );
		}
	}
	
	function showImage( images, index, seq )
	{
		if( images.length <= 1 ) {
			return;
		}
		
		if( index >= images.length ) {
			index = 0;
		}
		
		if( !images[index] ) {
			return;
		}
		
		if( inTransition ) {
			return;
		}
		
		if( seq != curSeq ) {
			return;
		}
		
		curIndex = index;
		
		var t = new Image();
		t.seq = seq;
		t.onload = function() {
		
			if( inTransition ) {
				return;
			}
			
			if( t.seq != curSeq ) {
				return;
			}
			
			var newImage = document.createElement( "img" );
			newImage.style.margin = curImage.style.margin;
			newImage.style.position = curImage.style.position;
			newImage.style.display = curImage.style.display;
			newImage.style.cursor = curImage.style.cursor;
			newImage.src = "";
			newImage.style.left = "-10000px";
			newImage.style.top = "-10000px";
			newImage.style.opacity = 0.0;
			newImage.onmouseover = curImage.onmouseover;
			newImage.onmousemove = curImage.onmousemove;
			newImage.onmouseout = curImage.onmouseout;
			newImage.onmouseleave = curImage.onmouseleave;
			
			newImage.src = this.src;
			container.appendChild( newImage );
			
			newImage["index"] = "" + index;
			mrpPositionImage( newImage, cW, cH, true );
			
			inTransition = true;
			
			transition( curImage, newImage, 1, 10, 0.1, function() {
				setTimeout( function() {
					if( stopped || inTransition ) {
						return;
					}
					showImage( images, curIndex + 1, seq );
				}, 3000 );
			} );
		};
		t.src = images[curIndex].url;
		
	}
	
	mrp_do_jsonp( jsonURL, function( data ) {
		doInit( data.photos );
	}, 0 );
	
	return true;
}

function mrpPositionImage( img, containerWidth, containerHeight, fill, autoHeight )
{
	var w = img.width;
	var h = img.height;
	var ratio = w/h;
	
	autoHeight = autoHeight || false;
	
	var imgW = 0;
	var imgH = 0;
	
	if( autoHeight || ratio >= 1 ) {
		// horizontal
		imgW = fill? containerWidth : Math.min( containerWidth, w );
		
		//img.style.width = imgW + "px";
		//img.style.height = "auto";
		
		imgH = Math.floor( imgW / ratio );
	}
	else {
		// vertical
		imgH = fill? containerHeight : Math.min( containerHeight, h );
		//img.style.height = imgH + "px";
		//img.style.width = "auto";
		
		imgW = Math.floor( imgH * ratio );
	}
	
	if( fill ) {
		if( autoHeight || imgW < containerWidth ) {
			imgW = containerWidth;
			imgH = Math.floor( imgW / ratio );
		}
		if( imgH < containerHeight ) {
			imgH = containerHeight;
			imgW = Math.floor( imgH * ratio );
		}
	}
	img.style.width = imgW + "px";
	img.style.height = imgH + "px";
	img.style.maxWidth = "10000px"; // counter-act some WP themes
	
	// center it
	img.style.left = Math.floor( ( containerWidth - imgW ) / 2	) + "px";
	if( autoHeight ) {
		img.style.top = "0";
	}
	else {
		img.style.top = Math.floor( ( containerHeight - imgH ) / 2	) + "px";
	}
}

function mrpAutoImage( img, margin, borderWidth, fill, autoHeight )
{

	if( img.parentNode.offsetWidth == 0 ) {
		setTimeout( function() {
			// f** IE
			mrpAutoImage( img, margin, borderWidth, fill, autoHeight );
		}, 100 );
		return;
	}
	
	img.style.margin = "0";
	img.style.position = "absolute";
	img.style.display = "block";
	img.style.visibility = "visible";
	
	var b = borderWidth || 1;
	
	var inner = img.parentNode;
	var outer = img.parentNode.parentNode;
	
	var outerW = outer.offsetWidth;
	var outerH = outer.offsetHeight;
	
	var containerWidth = outerW - margin*2 - b*2;
	var containerHeight = outerH - margin*2 - b*2;
	
	inner.style.width = containerWidth + "px";
	if( !autoHeight ) {
		inner.style.height = containerHeight + "px";
	}
	inner.style.position = "absolute";
	inner.style.left = margin + "px";
	inner.style.top = margin + "px";
	inner.style.overflow = "hidden";
	//inner.style.backgroundColor = "yellow";
	
	outer.style.position = "relative";
	
	if( img.src && img.src.indexOf( "/nophoto" ) != -1 ) {
		//img.onclick = null;
		//img.style.cursor = "default";
		fill = false;
	}
	
	mrpPositionImage( img, containerWidth, containerHeight, fill, autoHeight );
	
	if( autoHeight ) {
		var imgH = parseInt( img.style.height );
		inner.style.height = imgH + "px";
		outer.style.height = imgH + (margin*2) + "px";
	}
}
