var pageRef = this;

var catList = ["Architects","Builders","Interior Designer","Landscape Designer","Kitchen and Bath","Remodeling"];

var pathList = ["architects","builders","interior-designers","landscape-designers","kitchen-bath","remodeling"];

var imgList = [
               [{img:"duck1_0",cap:"Duckham Architecture &amp; Interiors"},		// Architects
				{img:"luna1",cap:"Luna Design Group"},
				{img:"mccloskey1",cap:"Michael McCloskey Design Group"},
				{img:"meyer1",cap:"Meyer &amp; Meyer Architecture & Interiors"},
				{img:"nold1",cap:"Noldesign"},
				{img:"PSD1",cap:"Polhemus Savery DaSilva Architects Builders"},
				{img:"TMS1",cap:"TMS Architects"}],
			   [{img:"TCG_1",cap:"The Classic Group"},		// Builders
				{img:"Fallon1",cap:"Fallon Custom Homes &amp; Renovations, Inc."},
				{img:"Sandford1",cap:"Sanford Custom Builders"},
				{img:"Wind1",cap:"Windover Construction, Inc."},
				{img:"Howell7",cap:"Howell Design and Build, Inc."},
				{img:"Wood1",cap:"Woodmeister Master Builders"}],
			   [{img:"benson1",cap:"Benson Interiors"},		// Interior Designers
				{img:"DD_5",cap:"Duffy Design Group"},
				{img:"Orpin3",cap:"The Orpin Group"},
				{img:"Kotzen1",cap:"Tappe &amp; Kotzen"}],
			   [{img:"Carter1",cap:"Carter Design Group"},		// Landscape Designers
				{img:"lombardi1",cap:"Gregory Lombardi Design"},
				{img:"Mac1",cap:"The MacDowell Company"},
				{img:"Sudbury1",cap:"Sudbury Design Group"},
				{img:"TPC1",cap:"The Patio Company"}],
			   [{img:"Arc1",cap:"Arclinea Boston"},		// Kitchens and Baths
				{img:"CC1",cap:"Classic Cabinetry"},
				{img:"Divine1_0",cap:"Divine Kitchens"},
				{img:"FBN1",cap:"FBNConstruction"},
				{img:"LK1",cap:"Lee Kimball"},
				{img:"PSV1",cap:"PSV Design Group"},
				{img:"Room1",cap:"Kitchen Concepts &amp; Roomscapes, Inc."},
				{img:"KM1",cap:"KMarshall Design"},
				{img:"kvc1a",cap:"Kitchen Views, A Division of National Lumber"},
				{img:"NSKP1",cap:"NorthShore Kitchens Plus"},
				{img:"Dodd1",cap:"Dodd Woodworking"}],
			   [{img:"TRC1",cap:"The Remodeling Company"},		// Remodeling
				{img:"LKimball_R1",cap:"Lee Kimball"},
				{img:"CAllen1",cap:"Charlie Allen Restorations, Inc."},
				{img:"Fein1",cap:"Feinmann, Inc."},
				{img:"FBN_R1",cap:"FBNConstruction"},
				{img:"SH2",cap:"S+H Construction Inc."},
				{img:"Howell1",cap:"Howell Design and Build, Inc."},
				{img:"DLCarpenter1",cap:"David L Carpenter, Inc.."} ]
			];

var nextCatNum = Math.floor(Math.random()*imgList.length) +1;
		// Category number of the next image to load.  In this case, 
		// number 1 represents the "Architects" category.

var indexList = [Math.floor(Math.random()*imgList[0].length),
				 Math.floor(Math.random()*imgList[1].length),
				 Math.floor(Math.random()*imgList[2].length),
				 Math.floor(Math.random()*imgList[3].length),
				 Math.floor(Math.random()*imgList[4].length),
				 Math.floor(Math.random()*imgList[5].length)];

	//
	// updateImageList()
	// Loops through anchor tags looking for 'selected-photos' references and applies onclick
	// events to appropriate links. Can be rerun after dynamically adding images w/ajax.
	//
	function updateImageList() {	
		// attach onclick function to any links with rel 'selected-photos'
		var thumbBasePath = '/homes/files/imagecache/thumb/files/images/leaders/portfolio/';
		var anchors = $('a');
		var index = 0;
		// loop through all anchor tags
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			var relAttribute = String(anchor.getAttribute('rel'));
			// use the string.match() method to catch 'selected-photos' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('nav-photo'))){
			    $( 'img', anchor ).attr( 'src', thumbBasePath+imgList[index][indexList[index]].img+'.jpg' );
			    anchor.setAttribute('href', '/homes/leaders/'+pathList[index] );
				anchor.onmouseover = bind_to_image_num(++index);
			}
		}
	}
	
	function bind_to_image_num( index )
	{
	    return function() { loadImage( index ); return false; };
	}


//function drawThumb(thumbNum) {
//	var index = thumbNum-1;
//	var thumbStr = '<a href="/homes/leaders/'+pathList[index]+'" onmouseover="javascript:loadImage('+thumbNum+');"><img src="/homes/files/imagecache/thumb/files/images/leaders/portfolio/';
//	thumbStr += imgList[index][indexList[index]].img+'.jpg" alt="'+catList[index]+'" id="thumb1" height="60" width="90" border="0" />';
//	document.write(thumbStr);
//}


function loadImage(imgNum) {
	if (imgNum==nextCatNum) return;
	nextCatNum = imgNum;
	$('#photoarea-caption').fadeOut( 'fast' );
	$('#photo').fadeOut( 'fast', loadNextImage);
}

function loadNextImage() {
	// Image has fully faded out - let's hide it completely.
	$('#photo').hide();
	// Show and position the loading graphic (positioned offstage initially).
	$('#loadIndicator').show();
	$('#loadIndicator').css('left','184px');

	
	// Then, start the preload of the next image.
    var imageLoader = new Image;
	// onunload() function forces onload() alerts in IE.
	imageLoader.onunload  = function() {};
	imageLoader.onload = pageRef.showNextImage;
	imageLoader.onabort = pageRef.handleAbort;
	imageLoader.onerror = pageRef.handleError;
	var index = nextCatNum - 1;
	var nextImage = "/homes/files/imagecache/img/files/images/leaders/portfolio/"+imgList[index][indexList[index]].img+".jpg";
	//alert(nextImage);
	imageLoader.src = nextImage;
}

function showNextImage() {
	// Now display the new image (we already have it preloaded).
	var index = nextCatNum - 1;
	var nextImage = "/homes/files/imagecache/img/files/images/leaders/portfolio/"+imgList[index][indexList[index]].img+".jpg";
	$('#photo').src( nextImage ).fadeIn('slow');
	// Hide the loading graphic
	$('#loadIndicator').hide();
	// We also want to show the next caption.
	setNextCaption();
}

function handleAbort() {
	alert("abort");
}
function handleError() {
	alert("error");
}

function setNextCaption() {
	var capContent = $('photoarea-caption');
	var index = nextCatNum - 1;
	$('#photoarea-caption').html( imgList[index][indexList[index]].cap ).show();
}

function selectIconRowRotation() {	
	// select one row of parterLogos to display

	var rows = $('#partnerLogos table tr');
    var selectedRowNum = Math.floor(Math.random()*rows.length);
    if( selectedRowNum >= rows.length ) {
        selectedRowNum = 0;  // safety, in case random() => 1.0
    }
	var index = 0;

	// loop through all rows
	for (var i=0; i<rows.length; i++) {
		var row = $(rows[i]);
		if( i != selectedRowNum ) {
		   row.css( 'display', 'none' );
	    } else {
		   row.removeAttr('style');
	    }
	}
}

function formatForBox( listings ) {     
    var htmlRet = "<ul style='padding-left:0px;'>";
    if( listings.rec.length == 0 ) {
       htmlRet += "No listings currently available."
    } else {
      $.each( listings.rec, function( i, listing ) {
           if( i < 8 ) {
               htmlRet +=  ("<li>$"+ (listing.pricecode/1000000).toFixed(1) + "M  - "+listing.city+", MA</li>" );
           }
         }
      );
    }
    return (htmlRet + "</ul>");
}

 function displayMostExpensive( ) {
  
    GDownloadUrl("/datasrv/cache/homesales/most_expensive.json",
	    function(doc, responseCode ) {

		// To ensure against HTTP errors that result in null or bad data,
		 // check that status code is equal to 200 before processing the data
		  if(responseCode == 200) {
		       var listings = eval('(' + doc + ')');//getRecentSalesList( myzip, 5 );
		       $( '#homeListings_box' ).html( formatForBox(listings) );
		  } else {
		     Alert( responseCode );
		  }
  
     } )

}


$(document).ready(
  function() {
     selectIconRowRotation();
     displayMostExpensive();
     updateImageList();
     loadNextImage();
  }
);

