var _NOSCROLL_POPUP_FEATURES = 'location=0,statusbar=0,menubar=0,resizable=no,scrollbars=no,top=100,left=100,screenX=100,screenY=100';
var _SCROLL_POPUP_FEATURES = 'location=0,statusbar=1,menubar=0,resizable=yes,scrollbars=yes,top=100,left=100,screenX=100,screenY=100';
var _DEFAULT_SEARCH_TEXT = 'enter location...';
var rotateImageInterval = 4000;
var imgHolders = new Array();

function raw_popup(url, target, can_scroll, w_width, w_height) {
  // define base set depending on whether the window can scroll or not
  var features = _SCROLL_POPUP_FEATURES;
  if (can_scroll==false) features = _NOSCROLL_POPUP_FEATURES;
  // define target attr
  if (typeof(target)=='undefined') target = '_blank';
  // add width and height to features
  if (typeof(w_width)=='undefined') w_width = 400;
  if (typeof(w_height)=='undefined') w_height = 300;
  features += ',width='+w_width+',height='+w_height;
  // call the window
  var theWindow = window.open(url, target, features);
  // setTimeout('theWindow.focus();',250);
  return theWindow;
}

function link_popup(src, can_scroll, w_width, w_height) {
  return raw_popup(src.getAttribute('href'), src.getAttribute('target') || '_blank', can_scroll, w_width, w_height);
}
function img_popup(src, can_scroll, w_width, w_height) {
  return raw_popup("image.php?i="+escape(src.getAttribute('href')), src.getAttribute('target') || '_blank', can_scroll, w_width, w_height);
}

function toggleDiv( idName )
{
	var el = $("#"+idName);
	
	if (el.css("display")=="block") el.hide();
	else el.show();
}

function confirmAction( checkMessage, theURL ) { if (confirm(checkMessage)) window.location = theURL; }

function imposeMaxLength(obj, maxLength) {
	if (obj.value.length>maxLength) obj.value = obj.value.substring(0,maxLength);
}

function onCollapsibleHeaderClick()
{
	var header = $(this);
	var body = header.next();
	var arrow = header.find("a img");
	
	body.slideToggle("fast", function(){
		var new_arrow_direction = ($(this).css("display")=="none") ? "left" : "down";
		arrow.attr("src", "images/tab_arrow_"+new_arrow_direction+".gif");
	});
	
	return false;
}

function onCommentsHeaderClick()
{
	$(this).prev().slideToggle();
	return false;
}

function searchFocus( el )
{
	if (el.value==_DEFAULT_SEARCH_TEXT) el.value = '';
}
function searchBlur( el )
{
	if (el.value=='') el.value = _DEFAULT_SEARCH_TEXT;
}

/****** financial functions for calculator ********/
function getFloat( s ) { return parseFloat(s.replace(/[^0-9.]/g,"")); }
		
function formatCurrency( v ) { return '$ ' + addCommas( roundTwo( v ) ); }

function formatPercent( v ) { return roundOne( v ) = '%'; }

function roundOne( v ) { 
	if (v.toFixed) return v.toFixed(1);
	return Math.floor( v*10 )/10;
}
function roundTwo( v ) { 
	if (v.toFixed) return v.toFixed(2);
	return Math.floor( v*100 )/100;
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function pmt( ir, np, pv ) { return ( pv * ir ) / (1-Math.pow( 1+ir,(-1 * np) ) ); }
function ipmt( ir, p, np, pv ) { return (pv * ir); }

function recalculate()
{
	var fm = document.pca_form;
	if (typeof(fm)=='undefined' || fm==null) return;
	
	// get data
	var pp = getFloat( fm.purchase_price.value );
	var maint = getFloat( fm.maintenance.value );
	var dp = getFloat( fm.downpayment.value );
	var tdm = getFloat( fm.td_maintenance.value ) / 100;
	var pt = getFloat( fm.property_tax.value );
	var mr = getFloat( fm.mortgage_rate.value ) / 100;
	var itb = getFloat( fm.tax_bracket.value ) / 100;
	
	// recalculate values
	var mortgage_payment = pmt( mr/12, 30*12, (pp-dp) );
	var mortgage_interest = ipmt( mr , 1, 360, (pp-dp) )/12;
	var total_expenses = mortgage_payment + maint + pt;
	var deductible_maintenance = maint * tdm;
	var total_tax_deductible = mortgage_interest + deductible_maintenance + pt;
	var total_tax_saving = total_tax_deductible * itb;
	var net_monthly_cost = total_expenses - total_tax_saving;
	var net_monthly_expense = net_monthly_cost + mortgage_interest - mortgage_payment;
	
	// assign them
	$('#mortgage_amount').html( formatCurrency( pp - dp ) );
	$('#mortgage_payment').html( formatCurrency( mortgage_payment ) );
	$('#mortgage_interest').html( formatCurrency( mortgage_interest ) );
	$('#maintenance_payment').html( formatCurrency( maint ) );
	$('#deductible_maintenance').html( formatCurrency( deductible_maintenance ) );
	$('#tax_payment').html( formatCurrency( pt ) );
	$('#property_taxes').html( formatCurrency( pt ) );
	$('#total_expenses').html( formatCurrency( total_expenses ) );
	$('#total_tax_deductible').html( formatCurrency( total_tax_deductible ) );
	$('#total_tax_saving').html( formatCurrency( total_tax_saving ) );
	$('#net_monthly_cost').html( formatCurrency( net_monthly_cost ) );
	$('#net_monthly_expense').html( formatCurrency( net_monthly_expense ) );
}
/********** end financial functions ***********/

$(function(){
	$("div.collapsible_header").click( onCollapsibleHeaderClick );
	$("h3.comment-header").click( onCommentsHeaderClick );
	recalculate();
	
	// handle front-page rotating images if relevant
	if (typeof(imgArray)!='undefined')
	{
		setTimeout( 'rotate_fp_image(1)', rotateImageInterval );
		setTimeout( 'rotate_fp_image(2)', rotateImageInterval );
	}
	
	// if the flash file is defined, try to fill it.
	if (typeof(fpVideoFile)!='undefined')
	{
	  var fpMovie = new SWFObject('flash/fpMovie.swf','teaser','283','185','8');
		fpMovie.addVariable('videoFile',fpVideoFile);
		fpMovie.write('fp_movie_div');
	}
});

function get_background_url( elt )
{
	var bgStr = elt.style.background;
	var a = bgStr.split(")");
	var fs = a[0];
	var b = fs.split("(");
	return b[1];
}

function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
	 var j = Math.floor( Math.random() * ( i + 1 ) );
	 var tempi = myArray[i];
	 var tempj = myArray[j];
	 myArray[i] = tempj;
	 myArray[j] = tempi;
   }
}

function rotate_fp_image( idx )
{	
	// console.log("rotating image "+idx);
	var i = $('#cb_image_'+idx)[0];
	
	var u = get_background_url( i );
	
	// go through the array, assigning the next one to each
	var n = imgArray.pop();
	imgArray.unshift( n );
	
	// load each into separate Image objects and switch them when they load.
	imgHolders[idx] = new Image();
	imgHolders[idx].onload = function() { replace_fp_image( idx ); };
	imgHolders[idx].onerror = function() { rotate_fp_image( idx ); };
	imgHolders[idx].src = n;
}

function replace_fp_image( idx )
{
	// console.log("replacing image "+idx);
	var i = $('#cb_image_'+idx)[0];
	
	var start = "transparent url('";
	var end = "') no-repeat scroll center center";
	
	i.style.background = start + imgHolders[idx].src + end;
	
	setTimeout( 'rotate_fp_image(' + idx +')', rotateImageInterval );
}