Event.observe( window, "load", startup );
var page_loaded = false;
function startup(){
	page_loaded = true;
	// check for mls change
	if($('mls')){
		// import on create only for now..
		if($('cp_create'))
			mls_watch();
		mls_events();
	}
}

var window_loader = Class.create();
window_loader.prototype = {
	initialize: function( div, url, options ) {
		this.div = div;
		this.url = url;
		if( options.eval_scripts ) this.eval_scripts = 1;
		this.after_finish = options.after_finish || Prototype.emptyFunction;
		this.params = options.params;
		this.load_busy();
	},
	load_busy: function(){
		new Ajax.Updater( this.div, "/cp/busy/", {
			method: "get",
			onComplete: this.show_window.bind(this)
		 });
	},
	show_window: function(){
		new Effect.Appear( this.div, { 
			duration: 0.3, 
			afterFinish: this.load_content.bind(this)				
		});
	},
	load_content: function(){
		new Ajax.Updater( this.div , this.url, {
			parameters: this.params,
			evalScripts: this.eval_scripts,
			onComplete: this.after_finish.bind(this)
		});
	}
}

Effect.BlindLeft = function(element) {
	element = $(element);
	var elementDimensions = element.getDimensions();

	return new Effect.Scale(element, 100, Object.extend({ 
		scaleContent: false, 
		scaleY: false, 
		scaleFrom: 0,
		scaleMode: 'box',
		scaleMode: {originalHeight: 30, originalWidth: 240},
		restoreAfterFinish: true,
		afterSetup: function(effect) {
			effect.element.makeClipping().setStyle({width: '0px'}).show(); 
		},  
		afterFinishInternal: function(effect) {
			effect.element.undoClipping();
		}
	}, arguments[1] || {}));
}

function listing_new( listing_type ){
	if( !listing_type ){ // cancel
		Effect.Fade( "steps_holder",{ duration: 0.3 });
		Effect.BlindDown( "add_buttons", { duration: 0.3 });
		Effect.BlindUp( "cp_create", { duration: 0.3 });
		return;
	}
	
	new Ajax.Updater( "cp_create_content", "/cp/new_format/", {
		parameters: "listing_type="+listing_type,
		method: "post",
		evalScripts: true, 
		onComplete: function(){
			Effect.BlindDown( "cp_create", { duration: 0.3 });
			mls_watch();
		}
	});
	new Effect.ScrollTo(this,{offset: -100, queue: 'end', duration: 0.5 });
	Effect.Appear( "steps_holder",{ duration: 0.3 });
	Effect.BlindUp( "add_buttons", { duration: 0.3 });
}

function listing_load_mls(){
	if(!confirm('Importing data works with MLS Listings (REIL) only at this time.'))
		return;
	mls = $('mls').value;
	new Ajax.Updater( "cp_create_content", "/cp/new_format/", {
		parameters: "listing_type=listing&mls_load="+mls,
		method: "post",
		evalScripts: true,
		onComplete: function(){
			mls_watch();
			mls_events();
		}
	});	
}

function mls_watch(){
	Event.observe($('mls'), 'keyup', 
			function(){
				mls_id = $('mls').value;
				mls_id_num = mls_id.replace(/[^0-9]/, '');
				if(	mls_id == mls_id_num && mls_id.length == 8)
					$('mls_import').show();
				else
					$('mls_import').hide();
			}
		);	
}

function mls_events(){
	mls_data = $$('.feed_data');
	mls_data.each(
		function(i){
			Event.observe(i, 'mouseover', function(){ mls_data_show(i)});
		}
	);
}

function mls_data_show(el){
	if($('clone_'+el.id)) return;
	_clone = el.cloneNode(false);
	$(el).insert({ after: _clone });
	_clone.innerHTML = el.innerHTML;
	el.hide();
	_clone.id = 'clone_'+_clone.id;
	Element.absolutize(_clone);
	el.show();
	new Effect.Scale(_clone.down(0), 200,
		{
			scaleContent: false,
			duration: .3,
			afterFinish: function(){
				_clone.down(0).style.overflowY = 'auto';
			}
		}
	);
	Event.observe(_clone, 'mouseout', function(){mls_data_hide(_clone)});

}

function mls_data_hide(_clone){
	if(_clone.going == true) return;
	_clone.going = true;
	new Effect.Parallel([
		new Effect.Scale(_clone.down(0), 25,
			{
				scaleContent: false
			}
		),
		new Effect.Fade(_clone)
	], { 
		duration: .1,
		afterFinish: function(){
			_clone.remove();
		}
	});
		
	
}

function listing_check_required(){
	window.onbeforeunload = null;
	allow_leave = true; // checked against for cancelBubble
	callback = arguments.length;
	if( $( "address" ).disabled ) {
		$( "listing_form" ).submit();
		return;
	}
	
	reg_error = "";
	if( $F( "city" ).replace(/\s+/g, "") == "" ) reg_error += "The city field is required.\n\n";
	if( $F( "state" ).replace(/\s+/g, "") == "" ) reg_error += "The state field is required.\n\n";
	if( $F( "address" ).replace(/\s+/g, "") == "" ) reg_error += "The address field is required.\n\n";
	if( reg_error ){
		new Effect.ScrollTo( "address", {duration: 0.3, offset: -100 });
		alert( reg_error );
		return;
	}
	
	if( $F( "domain" ) && $F( "domain_available" ) != "1" ){
		check_domain = reg_check_domain(true);
		if( !check_domain ) return;
	}
	if( reg_error ){
		if( !callback ) alert( reg_error );
		return;
	}
	$( "listing_form" ).submit();
}

function reg_check_domain(){
	callback = arguments.length;
	domain = $F("domain").toLowerCase() + "." + $F("domain_extension");
	if( domain.match(/[a-z0-9][a-z0-9.-]{0,61}[a-z0-9]\.[a-z.]{2,6}$/ ) && 
					 !$F("domain").match( /\./ ) && $F("domain").substring(0,1) != "-" 
					 && !$F("domain").match( / / )){
		$( "domain_status" ).style.display = "block";
		$( "domain_status" ).innerHTML = "";
		response_text = document.createElement( "span" );
		response_text = $( "domain_status" ).appendChild( response_text );
		response_text.innerHTML = "Checking if " + domain + " is available to register...";
		busy = document.createElement( "img" );
		busy = $( "domain_status" ).appendChild( busy );
		busy.src = "/img/cp/busy.gif";
		
		req_num = Math.round( Math.random() * 1000 );
		$( "domain_status" ).last_request = req_num;
		setTimeout("if($( \"domain_status\" ).last_request==req_num)alert(\"The server hasn't responded in the last 15 seconds, "+
					"you should retry your request.\")", 15000 );

		new Ajax.Request("/cp/check_domain/", { 
			parameters: "domain="+$F("domain")+"&extension="+$F("domain_extension"),
			method: "post", 
			onSuccess: function(v){
				$( "domain_status" ).last_request="";
				if( v.responseText == "1" ){
					$( "domain_status" ).innerHTML = domain + " is available! Activate now to secure this domain.";
					$( "domain_available" ).value = 1;
					if( callback == 1 ) listing_check_required(true);
					if( callback == 2 ) payment_check(true);
				} else {
					$( "domain_status" ).innerHTML = domain + " is NOT available. Please try a different domain.";
					$( "domain_available" ).value = 0;
					new Effect.ScrollTo( "cp_register_domain", {duration: 0.3 });
					if( callback ) alert( domain + " is NOT available. Please try a different domain." );
				}
			}, onFailure: function(v){ alert("We're sorry, there was a problem with your request. Please try again.");}
		});	
	} else {
		new Effect.ScrollTo( "cp_register_domain", {duration: 0.3 });
		alert( "That is not a valid domain name. Domains can contain only letters and numbers."+
			  "They may have hypens (-) in them, but not in the beginning or end of your domain "+
			  "name. Examples of valid domain names:\n\n123OceanStreet.com\n"+
			  "123-Ocean-Street.com\nOceanStreet.com" );
		return false;
	}
}

function make_bubble( div, text ){
	if( !page_loaded ) return; // prevent IE freak
	div = $(div);
	if( div.dragging ) return;
	bubble = document.createElement("div");
	bubble = document.body.appendChild( bubble );
	block = document.createElement("blockquote");
	block = $( bubble ).appendChild( block );
	para = document.createElement("p");
	para = $( block ).appendChild( para );
	cite = document.createElement("cite");
	cite = $( bubble ).appendChild( cite );
	bubble.addClassName( "bubble" );
	para.innerHTML = text;
	cite.innerHTML = "&nbsp;";
	div_pos = Position.cumulativeOffset( div );
	div_h = bubble.clientHeight;
	Element.setStyle( bubble, { 
		"left":( div_pos[0] - 10 )+"px", 
		"top": ( div_pos[1] - div_h - 15 )+"px" 
	});
	$(div).onmouseout =
		function(){ kill_bubbles(); $(div).onmouseout=null; };
	$(div).onmousedown =
		function(){ div.dragging=true; kill_bubbles(); $(div).onmousedown=null; };
	$(div).onmouseup =
		function(){ div.dragging=false; $(div).onmouseup=null; };
}

function kill_bubbles(){
	bubbles = $$( ".bubble" );
	for( i=0; i <= ( bubbles.length - 1 ); i++ ){
		bubbles[i].remove();	
	}
}

function highlight_remove_item ( div ) {
	setTimeout("new Effect.Highlight('"+div+"',{duration: 3})",500);
	setTimeout("new Effect.Fade('"+div+"',{duration: .75})",3500);
}

function check_empty ( input ) {
	if ($(input).value=="description") $(input).value= ""; // tour
}

function check_enter  ( e, id ) {
	if(window.event) {
		keynum = e.keyCode;
	} else if(e.which) {
		keynum = e.which;
	}
	keychar = String.fromCharCode(keynum);
	
	if (keynum==13) switch_desc_label ( id );
}

function highlight_this( div ){
	old_bg_color = div.style.backgroundColor;
	div.style.backgroundColor = "#fae5fa";
	div.onmouseout = function(){ div.style.backgroundColor = ( "transparent" || old_bg_color || "#ffffff" ); }
}

function confirm_location( msg, loc ){
	if( confirm( msg )) location.href=loc;	
}

function quick_fade ( div ) {
	new Effect.Fade(div, { duration: 0.2})
}

function quick_appear ( div ) {
	new Effect.Appear(div, { duration: 0.2})
}
function toggle_visible( div ){
	if(	Element.getStyle( div , "visibility" ) == "hidden" )
		set_visible( div );
	else
		set_hidden( div );	
}
function set_visible ( div ) {
	Element.setStyle(div ,{visibility: 'visible'})
}

function set_hidden ( div ) {
	Element.setStyle(div ,{visibility: 'hidden'})
}
function set_focus ( input ) {
	 setTimeout("Field.focus('"+input+"')",400);
}
function htmlspecialchars ( text ) {
	text = text.replace(/</,"&lt;");
	text = text.replace(/>/,"&gt;");
	return(text);
}

function full_box( uri ){
	w_h = window_dimensions();
	w = w_h[0]+"px";
	h = "";
	// if 2nd arg fit div to screen
	if( arguments.length > 1 )
		h = w_h[1]+"px";
	
	fade_bg = document.createElement("div");
	fade_bg = document.body.appendChild( fade_bg );
	hold = document.createElement("div");
	hold = fade_bg.appendChild( hold );
	hold.id = "preview_holder";
	fade_bg.id = "preview_bg";
	Element.setStyle( fade_bg, {
		position: "absolute",
		top: "0px", 
		left: "0px",
		width: w,
		height: h,
		backgroundColor: "#000000",
		padding: "20px",
		textAlign: "center"
	});
	Element.setStyle( hold, {
		padding: "10px",
		marginLeft: "auto",
		marginRight: "auto"
	});
	new Ajax.Updater( "preview_holder", uri );
	Event.observe( fade_bg, "click", function(){ fade_bg.remove(); });
}

function window_dimensions(){
	de = document.documentElement;
	w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	return [w,h];
}

function document_dimensions(){
	//	Lightbox v2.03
	//	by Lokesh Dhakar - http://www.huddletogether.com

	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function findPosX(obj) {
	var curleft = 0;
	if(obj.offsetParent)
		while(1) 
		{
		  curleft += obj.offsetLeft;
		  if(!obj.offsetParent)
			break;
		  obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	if (!obj || !obj.offsetParent) return 0;
	var curtop = 0;
	if(obj.offsetParent)
		while(1)
		{
		  curtop += obj.offsetTop;
		  if(!obj.offsetParent)
			break;
		  obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
	return curtop;
}


function clipboard_copy(inElement) {
	if (inElement.createTextRange) {
		var range = inElement.createTextRange();
		if (range)
		 range.execCommand('Copy');
	} else {
		var flashcopier = 'flashcopier';
		if(!document.getElementById(flashcopier)) {
			var divholder = document.createElement('div');
			divholder.id = flashcopier;
			document.body.appendChild(divholder);
		}
		document.getElementById(flashcopier).innerHTML = '';
		var divinfo = '<embed src="/src/_copy.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
	}
}

function add_custom_bullet () {
	bullet_num = $('desc_custom_bullets').getElementsByTagName('input');
	bullet_val = $('desc_custom_bullets').getElementsByTagName('textarea');
	val_arr = new Array();
	desc_arr = new Array();
	for (i=0; i < bullet_num.length; i++) {
		desc_arr[desc_arr.length] = bullet_num[i].value;
		val_arr[val_arr.length] = bullet_val[i].value;
	}
	num = bullet_num.length +1;
	$('desc_custom_bullets').innerHTML = $('desc_custom_bullets').innerHTML +
	'<div class="desc_tr"><div class="desc_td_left">&bull;<input name="custom_bullet_name_'+num+'" />:</div>'+
	'<div class="desc_td_right"><textarea name="custom_bullet_value_'+num+'"></textarea></div></div>';

	for (i=0; i < bullet_num.length; i++) {
		if (desc_arr[i]==undefined) continue;
		bullet_num[i].value = desc_arr[i];
		bullet_val[i].value = val_arr[i];
	}
}

function updater (div, call_function) {
	new Ajax.Updater(div,'/cp/busy/', { method: 'get', onComplete: call_function});
}