//area.js requires list.js to be included first
var images = new Array();
var baseUrl;
var whsId;
var arId;
var mapImageId;
var defaultQuickAdImageId;
var defaultQuickAdLink;
var defaultQuickAd, defaultInfo, defaultQuickInfo;
//page elements
var quickAdHolder, infoHolder, mapHeader, map, mapHolder, infoListPreheader, advancedDlg, loadingDLG,pdfMapLink;
var quickAds = new Array();
var advSearchParam = new Array();//select contents
var advSearchCheck = new Array();//check boxes

function preLoadImages(){
	if (document.images){
		images[0] = new Image(470,437);
		images[4] = new Image(212,75);
		
		images[1] = new Image(16,16);
		images[1].src="/images/icons/icoover.gif";  
		
		images[2] = new Image(8,8);
		images[2].src="/images/icons/ico1000.gif";  
		images[3] = new Image(8,8);
		images[3].src="/images/icons/ico1000fade.gif";  
	}
	images[0].src="/jsp/cachedImageView.do?key="+mapImageId;  
	images[4].src="/jsp/cachedImageView.do?key="+defaultQuickAdImageId;
}

function fadeDots(){
	var bool = (floorplanList.length > 0);
	for (var i=0; i < communityList.length; i++){
		fadeDotGroup(i,bool);
	}
	for (var i=0; i < currentList.length; i++){
		fadeDotGroup(communityIndex[currentList[i]],false);
	}
}

function fadeDotGroup(i,bool){
	var popDot = getById("popdot_"+i);
	var dotOver = getById("ovr_"+i);
	var dot = getById("dot_"+i);
	popDot.maxOpacity = (bool)?(.75):(1);
	dot.src = (bool)?("/images/icons/ico"+communityList[i][4]+"fade.gif"):("/images/icons/ico"+communityList[i][4]+".gif");
}

function createAdvDlg(){
	//(re)format option arrays
	var reformat = new Array("countyName", "cityName", "schoolDistrictName");
	
	//setup communityCriteria
        // Fix for bug Id 70
		advSearchParam['communityName'] = new Array();
		advSearchParam['communityName'][0] = ["",""];
        if(communityList.length>0){
			for (var i=0; i < communityList.length; i++){
				advSearchParam['communityName'][i+1] = [communityList[i][1],communityList[i][0]];
			}
        }
	
        
	//reformat text-only arrays
        // Fix for bug Id 70
        if(communityList.length>0){
			for (var j=0; j < reformat.length; j++){
				for (var i=0; i < advSearchParam[reformat[j]].length; i++){
					advSearchParam[reformat[j]][i][0] = advSearchParam[reformat[j]][i][0];
					advSearchParam[reformat[j]][i][1] = advSearchParam[reformat[j]][i][0];
				}
			}
        }
	
	
	//assign option arrays to select boxes
	var elements = document.getElementsByTagName("select");
	for (i=0;i< elements.length;i++){
		try{
			for (var j=0; j < advSearchParam[elements[i].name].length; j++){
				elements[i].options[j] = new Option(advSearchParam[elements[i].name][j][1],advSearchParam[elements[i].name][j][0],false,false);
			}
		}
		catch(e){
			
		}
	}
	
	var s,shdr,tn;
	//add checkboxes to section 2
	s= getById("adv_dlg_section_2");
	shdr = document.createElement("h3");
	tn = document.createTextNode("Additional\n\rHome Features");
	shdr.appendChild(tn);
	s.appendChild(shdr);
        // Fix for bug Id 70
        if(communityList.length>0){
	for (var i=0; i<advSearchCheck['homefeatures'].length; i++){
		mkCheckBox(advSearchCheck['homefeatures'][i],2);
	}
        }
	
	//add checkboxes to section 3
	s= getById("adv_dlg_section_3");
	shdr = document.createElement("h3");
	tn = document.createTextNode("Community\n\rFeatures");
	shdr.appendChild(tn);
	s.appendChild(shdr);
        // Fix for bug Id 70
        if(communityList.length>0){
	for (var i=0; i<advSearchCheck['cmufeatures'].length; i++){
		mkCheckBox(advSearchCheck['cmufeatures'][i],3);
	}
        }
        

	//add buttons	
	s= getById("adv_dlg_section_4");
	var b1 = document.createElement("a");
	var b2 = document.createElement("a");
	var tn1 = document.createTextNode("Search For Homes...");
	var tn2 = document.createTextNode("Cancel & Return");
	b1.href = "#";
	b1.onmousedown = function(){hideSearch();doSearch(true);}
	b2.href = "javascript:hideSearch();";
	b1.appendChild(tn1);
	b2.appendChild(tn2);
	s.appendChild(b1);
	s.appendChild(b2);
       
}

function mkCheckBox(c,p){
	var d=document.createElement("div");
	d.className = "formLine";
	
	var l=document.createElement("span");
	var tn = document.createTextNode(c[1]);
	l.appendChild(tn);
	
	var b=document.createElement("input");
	b.type = "checkbox";
	b.value = "1";
	b.name = c[0];
	
	d.appendChild(b);
	d.appendChild(l);
	getById("adv_dlg_section_"+p).appendChild(d);
}

function advancedSearch(){
	advancedDlg.style.display = "block";
	quickAdHolder.style.display = "none";
	infoHolder.style.display = "none";
	mapHolder.style.display = "none";
}

function doSearch(bool){
	loadingDlg.style.visibility = "visible";
	
	if (bool){
		// build url
		var url = "/jsp/xmlFeed.do?advancedSearch.do?whsId="+whsId+"&plfArId="+arId;
		var sel = document.getElementsByTagName("select");
		for (i=0;i< sel.length;i++){
			if (sel[i].value != ""){
				url += "&"+sel[i].name+"="+sel[i].value;
			}
		}
		var inp = document.getElementsByTagName("input");
		for (i=0;i< inp.length;i++){
			if (inp[i].status){
				url += "&"+inp[i].name+"="+inp[i].value;
			}
		}
		getFloorplanList(url);
		
	}
	else{
		//reset Search
		floorplanList = new Array();
		createCommunityList();
		hideSearch();
	}
}

function handleFloorplanListParse(){
	if (floorplanList.length > 0){
		reIndexFloorplanList();
		createFloorplanList();
		/**/
		hideSearch();
	}
	else{
		loadingDlg.style.visibility = "hidden";
		alert ("Sorry, no results were found. Please change your search criteria and try again");
	}
}

function handleFloorplanListError(){
	//handle error
	floorplanList = new Array();
	reIndexFloorplanList();
	createCommunityList();
	alert("There was a problem retrieving the advanced search data:\n" +XMLData.statusText);
	hideSearch();
}

function hideSearch(){
		
	loadingDlg.style.visibility = "hidden";
	advancedDlg.style.display = "none";
	quickAdHolder.style.display = "block";
	infoHolder.style.display = "block";
	mapHolder.style.display = "block";
	createMapHeader();
	createListPreheader();
	fadeDots();
}

function createListPreheader(){
	//reset header
	try{
		infoListPreheader.removeChild(getById("info_list_preheader_contents"));
	}catch(e){}
	var ic = document.createElement("div");
	ic.id = "info_list_preheader_contents";
	var space = "          "
	var adv = document.createElement("a");
	var lbl = document.createElement("div");
	var tn;
	adv.className = "right";
	lbl.className = "label";
	
	//determine header contents
	if (floorplanList.length > 0){
		var adv2 = htmlTag("a","REFINE SEARCH");
		adv2.className = "right";
		adv2.href = "javascript:advancedSearch();";
		adv.href = "javascript:doSearch(false);";
		tn = document.createTextNode("CLEAR SEARCH");
		adv.appendChild(tn);
		ic.appendChild(adv2);
		
		lbl = htmlTag("span","<span class='text'>HOME LISTINGS</span><img class='qmi' alt='' src='/images/qmiicon.jpg' /><span class='text'>Quick Move-In Homes</span>");
		lbl.className = "label";
		
	}
	else{
		adv.href = "javascript:advancedSearch();";
		tn = document.createTextNode(space+"ADVANCED SEARCH"+space);
		adv.appendChild(tn);
		tn = document.createTextNode("COMMUNITY LISTINGS");
		lbl.appendChild(tn);
	}
	
	//add children
	ic.appendChild(adv);
	ic.appendChild(lbl);
	infoListPreheader.appendChild(ic);
}

function createMapHeader(){
	//reset header
	try{
		mapHeader.removeChild(getById("map_header_contents"));
	}catch(e){}
	var hc = document.createElement("div");
	hc.id = "map_header_contents";

	var adv = document.createElement("a");
	var pdf = document.createElement("a");
	var tn;
	adv.className = "left";
	
	pdf.className = "right";
	pdf.href = (pdfMapLink == "")?("javascript:alert('PDF map not available');"):(pdfMapLink);
	tn = document.createTextNode("Download PDF Map");
	pdf.appendChild(tn);
	
	//determine header contents
	if (floorplanList.length > 0){
		var adv2 = document.createElement("a");
		adv2.className = "left";
		adv2.href = "javascript:advancedSearch();";
		tn = document.createTextNode("Refine Search");
		adv2.appendChild(tn);
		adv.href = "javascript:doSearch(false);";
		tn = document.createTextNode("Clear Search");
		adv.appendChild(tn);
		hc.appendChild(adv2);
	}
	else{
		adv.href = "javascript:advancedSearch();";
		tn = document.createTextNode("Advanced Search");
		adv.appendChild(tn);
	}
	
	//add children
	hc.appendChild(adv);
	hc.appendChild(pdf);
	mapHeader.appendChild(hc);
}

function drawMap(){
	//add map background
	var mapBackground = document.createElement("img");
	mapBackground.className = "map";
	mapBackground.alt = "";
	mapBackground.src = images[0].src;
	map.appendChild(mapBackground);
	//add dots
	for (var i=0; i < communityList.length; i++){
		createDot(communityList[i],i);
		createPopup(communityList[i],i);
	}
}

function createDot(community, index) {
	var dotOver = document.createElement("img");
	var dot = document.createElement("img");
	
	dotOver.id = "ovr_"+index;
	dotOver.index = index;
	dotOver.className = "dotover";
	dotOver.alt = "";
	dotOver.src = "/images/icons/icoover.gif";
	dotOver.style.left = (community[8]-9)+"px";
	dotOver.style.top = (community[9]-9)+"px";
	dotOver.style.visibility = "hidden";
	map.appendChild(dotOver);

	dot.id = "dot_"+index;
	dot.index = index;
	dot.type = (community[7].length > 0)?("cmu"):("neigh");
	dot.className = "dot";
	dot.width = 8;
	dot.height = 8;
	dot.alt = "";
	dot.src = "/images/icons/ico"+community[4]+".gif";
	dot.style.left = (community[8]-5)+"px";
	dot.style.top = (community[9]-5)+"px";
	dot.onmouseover=function(){
		handleDotMouseOver(this.index);
	}
	dot.onmouseout=function(){
		handleDotMouseOut(this.index);
	}
	dot.onmousedown=function(){
		handleDotMouseDown(this.index,this.type);
	}
	map.appendChild(dot);
}

function createPopup(community, index) {
	var x_off = (community[8] > 310)?(-137):(10);
	var y_off = (community[9] > 310)?(-50):(10);
	
	var popup = document.createElement("div");
	var phdr = document.createElement("div");
	var pbdy = document.createElement("div");
	var tn,br;
	
	popup.id = "popdot_"+index;
	popup.maxOpacity = 1;
	popup.className = "mappopup";
	popup.style.left = (community[8]-5+x_off)+"px";
	popup.style.top = (community[9]-5+y_off)+"px";
	
	phdr.className = "header";
	tn = document.createTextNode(community[0]);
	phdr.appendChild(tn);

	pbdy.className = "body";
	tn = document.createTextNode(community[2]+", "+community[3]);
	pbdy.appendChild(tn);
	br = document.createElement("br");
	pbdy.appendChild(br);
	tn = document.createTextNode(community[6]+"-"+community[5]);
	pbdy.appendChild(tn);

	popup.appendChild(phdr);
	popup.appendChild(pbdy);
	map.appendChild(popup);
}

var popup, op;
function handleDotMouseOver(index){
	popup = getById("popdot_"+index);
	popup.style.visibility = "visible";
	popup.style.opacity = "0";
	popup.style.filter = 'alpha(opacity='+parseInt(0)+')';
	op = 0;
	fadeInPop();
	setQuickInfo(index);
}

function handleDotMouseOut(index){
	var popout = getById("popdot_"+index);
	popout.style.visibility = "hidden";
	setQuickInfo(-1);
}

function handleDotMouseDown(index,type){
	window.location.href = "/jsp/community.do?cmuCode="+communityList[index][1];
}

function fadeInPop(){
	op += .15;
	op = (op>popup.maxOpacity)?popup.maxOpacity:op;
	popup.style.opacity = op.toString();
	popup.style.filter = 'alpha(opacity='+parseInt(100*op)+')';
	if (op<1)
	 setTimeout("fadeInPop()",20);		
}

function handleListMouseOver(row,index){
	row.oldClass = row.className;
	row.className = row.className+"over";
	switch (row.hitType){
		case "cmu":
			var overdot = getById("ovr_"+index);
			overdot.style.visibility = "visible";
			setQuickInfo(index);
			break;
		case "neigh":
			var overdot = getById("ovr_"+index);
			overdot.style.visibility = "visible";
			setQuickInfo(index);
			break;
		case "fpl":
			var overdot;
			//var ALRT = "";
			for (var i=0; i<floorplanList[index][27].length; i++){
				//ALRT +=floorplanList[index][27][i]+" ";
				overdot = getById("ovr_"+communityIndex[floorplanList[index][27][i]]);
				overdot.style.visibility = "visible";
			}
			//alert(ALRT);
			if (floorplanList[index][27].length == 1)
				setQuickInfo(communityIndex[floorplanList[index][27][0]]);
			break;
	}

}

function handleListMouseOut(row,index){
	row.className = row.oldClass;
	switch (row.hitType){
		case "cmu":
			var overdot = getById("ovr_"+index);
			overdot.style.visibility = "hidden";
			setQuickInfo(-1);
			break;
		case "neigh":
			var overdot = getById("ovr_"+index);
			overdot.style.visibility = "hidden";
			setQuickInfo(-1);
			break;
		case "fpl":
			var overdot;
			for (var i=0; i<floorplanList[index][27].length; i++){
				overdot = getById("ovr_"+communityIndex[floorplanList[index][27][i]]);
				overdot.style.visibility = "hidden";
			}
			setQuickInfo(-1);
			break;
	}
}

function handleListMouseDown(row,index){
	switch (row.hitType){
		case "cmu":
			window.location.href = "/jsp/community.do?cmuCode="+row.code;
			break;
		case "neigh":
			window.location.href = "/jsp/neighborhood.do?nelNbCode="+row.code;
			//window.location.href = "/jsp/community.do?cmuCode="+communityList[index][1];//
			break;
		case "fpl":
			window.location.href = floorplanList[index][1];
			break;
	}
}

function setQuickInfo(index){

	infoHolder.removeChild(defaultInfo);
	for (var i=0; i<quickAds.length; i++){
		try{
			quickAds[i].style.visibility = "hidden";
		}
		catch(e){
		}
	}
	if (index >= 0){
		//community
		defaultQuickAd.style.visibility = "hidden";
		try{
			quickAds[index].style.visibility = "hidden";
		}
		catch(e){
			quickAds[index] = document.createElement("div");
			quickAdHolder.appendChild(quickAds[index]);
			quickAds[index].className='quickad';
			
			
			var img = document.createElement("img");
			if (communityList[index][14])
				img.src = "/jsp/docView.do?id="+communityList[index][14];
			else
				img.src = "/jsp/cachedImageView.do?key="+defaultQuickAdImageId;
			img.alt = "";
			quickAds[index].appendChild(img);
		}
		var hn, tn;
                /* Fix for Bud Id 23 - Reopened for formatting data for IE */
		var html = "<h2>"+communityList[index][0]+"</h2>"+"<h5><b>Community Summary</b></h5>";
		defaultInfo = htmlTag("div",html);

		var neighList = "";
		/* Fix for the bug Id 23 - Reopened for double line breaks */
		var linebreak = 0;
		for  (var i=0; i<communityList[index][7].length; i++){
			neighList += communityList[index][7][i][0]+", ";
		}
		if (neighList != ""){
            /*  Fix for Bud Id 23 - Reopened for formatting data for IE */
			/*hn = htmlTag("h4","Neighborhoods");
			defaultInfo.appendChild(hn);*/
            hn = htmlTag("div","<b>Neighborhoods: </b>");
			defaultInfo.appendChild(hn);
			tn = htmlTag("div", neighList.substr(0,neighList.length-2));
			defaultInfo.appendChild(tn);
            linebreak++;
		}
		if (communityList[index][11] != ""){
                /*      Fix for Bud Id 23 - Reopened for formatting data for IE  */
			/*hn = htmlTag("h4","Amenities:");
			defaultInfo.appendChild(hn);*/
                        if(linebreak>0){
                        hn = htmlTag("div","<b><br/>Amenities: </b>");
                        } else {
                        hn = htmlTag("div","<b>Amenities: </b>");
                        }
			defaultInfo.appendChild(hn);

			tn = htmlTag("div",communityList[index][11]);
			defaultInfo.appendChild(tn);
                        linebreak++;
                
		}
		
/*       Fix for Bug Id 23 community Summary missing Info   */
                // Fetching the school Districts from the communityList structure
                if (communityList[index][12] != ""){
                       // Fix for Bug Id 23 - reopened for look and feel
                       /* hn = htmlTag("h4","<b>School Districts :</b>"+"</p>"+communityList[index][12]);
			defaultInfo.appendChild(hn);*/
                       /* Fix for Bud Id 23 - Reopened for formatting data for IE  */
                        if(linebreak>0){
                        hn = htmlTag("div","<b><br>School Districts:</b>"+"  "+communityList[index][12]);
                        } else {
                        hn = htmlTag("div","<b>School Districts:</b>"+"  "+communityList[index][12]);
                        }
                        defaultInfo.appendChild(hn);
                        linebreak++;
			/*tn = htmlTag("div",communityList[index][12]);
			defaultInfo.appendChild(tn);*/
                }

/* Fix for the bug Id 23 - Community Summary missing Info */
                // Fetching the city Townships from the communityList structure
                if (communityList[index][2] != ""){
                        // Fix for Bug Id 23 - reopened for look and feel
                        /* hn = htmlTag("h4","<b>Cities and Townships :</b>"+"</p>"+communityList[index][2]);
			defaultInfo.appendChild(hn);*/
                       /* Fix for Bud Id 23 - Reopened for formatting data for IE */
                        if(linebreak>0){ 
                        hn = htmlTag("div","<b><br/>Cities and Townships:</b>"+"  "+communityList[index][2]);
                        } else {
                        hn = htmlTag("div","<b>Cities and Townships:</b>"+"  "+communityList[index][2]);
                        }
                        defaultInfo.appendChild(hn);
                        linebreak++;
                        // presents the city-Township on the next Line
			/*tn = htmlTag("div",communityList[index][2]);
			defaultInfo.appendChild(tn);*/
                }

/*          Fix for Bug Id 23 community Summary missing Info   */


		if (communityList[index][13] != ""){
                        if(linebreak>0){
			tn = htmlTag("div","<br>"+communityList[index][13]);
                        } else {
                        tn = htmlTag("div",communityList[index][13]);
                        }
			defaultInfo.appendChild(tn);
                        linebreak++;
		}
		hn = document.createElement("h4");
		tn = document.createTextNode(" ");
		hn.appendChild(tn);
		defaultInfo.appendChild(hn);
/*           Fix for Bug Id 74 - Community Biography duplicated */
/*		tn = htmlTag("div","<br/>"+communityList[index][13]);
		defaultInfo.appendChild(tn);
*/		
		quickAds[index].style.visibility='visible';

	}
	else{
		//default
		defaultQuickAd.style.visibility = "visible";
		defaultInfo = htmlTag("div",htmldecode(defaultQuickInfo));
		//tn = document.createTextNode(defaultQuickInfo);
		//defaultInfo.appendChild(tn);
	}
	infoHolder.appendChild(defaultInfo);

}

function init(){
        
	// init list script
	preLoadImages();
	initList();
	//get elements ========================================
	advancedDlg = getById("adv_dlg");
	loadingDlg = getById("loading_dlg");
	quickAdHolder = getById("mapquickad");
	infoHolder = getById("mapinfo");
	mapHolder = getById("map");
	map = getById("map_contents");
	mapHeader = getById("mapheader");
	infoListPreheader = getById("infolistpreheader");

	drawMap();
	
	//create advanced dlg =========================

	createAdvDlg();
	
	//create default quickAd ===============================
	defaultQuickAd = document.createElement("div");

	quickAdHolder.appendChild(defaultQuickAd);
	defaultQuickAd.className='quickad';
	defaultQuickAd.style.visibility = "visible";
	var qal = document.createElement("a");
        qal.href="javascript:sepWin('"+defaultQuickAdLink+"','450','500', '4')";
	var img = document.createElement("img")

	img.src=images[4].src;
        qal.appendChild(img);
	defaultQuickAd.appendChild(qal);
	
	//create default quickInfo ===============================
	defaultInfo = htmlTag("div",defaultQuickInfo);
	defaultInfo.style.display='block';
	infoHolder.appendChild(defaultInfo);
	//var dqi = document.createTextNode(defaultQuickInfo);
	//defaultInfo.appendChild(dqi);
	
	//create headers ==============================	
	createMapHeader();
	createListPreheader();

	//create list =================================
	if (floorplanList.length > 0){
		createFloorplanList();
		fadeDots();
	}
	else{
		createCommunityList();
         }
	
	if (queryString["planCriteria"] != null && queryString["planCriteria"] != "")
	{
			var sel = getById('planCriteria');
			 for (var j=0;j<sel.options.length;j++) 
			 {
          		if (sel.options[j].value == queryString["planCriteria"])
               		sel.options.selectedIndex=j;
			 }
			 if (sel.value == queryString["planCriteria"])
				doSearch(true);
			else
				alert("Floorplan not found!");	
	}
	

}

