var disappeardelay=500, horizontaloffset=0, verticaloffset=0, topclearance=20, ie4=document.all, ns6=document.getElementById&&!document.all, hhmap, bounds;

function browser_ie6() {
	if (window.XMLHttpRequest) {
		// IE 7, mozilla, safari, opera 9
		return false;
	} else {
		// IE6, older browsers
		return true;
	}
/*
	var browser=navigator.appName;
	var b_version=navigator.appVersion;
	var version=parseFloat(b_version);
	alert(browser + " " + version);
	if ((browser=="Microsoft Internet Explorer") && (version<=6)) {
		return true;
  	}
	return false;
*/
}

document.write('<div  class="popupFixWindow" id="popupFixWindow" style="z-index:1000;position:absolute;visibility:hidden;width: 395px" ></div>')
document.write('<div  class="popupWindow" id="popupWindow" style="z-index:1000;position:absolute;visibility:hidden;width: 395px" onMouseover="clearhidepopup()" onMouseout="dynamichide(event)"></div>')
document.write('<div  class="popupTailTopLeft" id="popupTailTopLeft" style="z-index:1001;position:absolute;visibility:hidden;width:33px;height:42px;" onMouseover="clearhidepopup()" onMouseout="dynamichide(event)"></div>')
document.write('<div  class="popupTailBottomLeft" id="popupTailBottomLeft" style="z-index:1001;position:absolute;visibility:hidden;width:33px;height:42px;" onMouseover="clearhidepopup()" onMouseout="dynamichide(event)"></div>')
document.write('<div  class="popupTailTopRight" id="popupTailTopRight" style="z-index:1001;position:absolute;visibility:hidden;width:33px;height:42px;" onMouseover="clearhidepopup()" onMouseout="dynamichide(event)"></div>')
document.write('<div  class="popupTailBottomRight" id="popupTailBottomRight" style="z-index:1001;position:absolute;visibility:hidden;width:33px;height:42px;" onMouseover="clearhidepopup()" onMouseout="dynamichide(event)"></div>')


function getposOffset(what, offsettype){
	var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
	var parentEl=what.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}


function showhide(obj, e, visible, hidden, popupwidth){
	if (ie4||ns6)
		popupobj.style.left=popupobj.style.top=-500

	popupobj.widthobj=popupobj.style
	popupobj.widthobj.width=popupwidth
	if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover")
		obj.visibility=visible
	else if (e.type=="click")
		obj.visibility=hidden
}

function iecompattest(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge){
	var edgeoffset=-5
	if (whichedge=="rightedge"){
		var windowedge=ie4 && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
		popupobj.contentmeasure=popupobj.offsetWidth
		if (windowedge-popupobj.x-obj.offsetWidth < popupobj.contentmeasure)
			edgeoffset=popupobj.contentmeasure+obj.offsetWidth
	}
	else{
		var topedge=ie4 && !window.opera? iecompattest().scrollTop : window.pageYOffset
		var windowedge=ie4 && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
		popupobj.contentmeasure=popupobj.offsetHeight
		if (windowedge-popupobj.y < popupobj.contentmeasure){ 
			edgeoffset=popupobj.contentmeasure-obj.offsetHeight
			if ((popupobj.y-topedge)<popupobj.contentmeasure) 
				edgeoffset=popupobj.y

		}
		if( edgeoffset>300) {
			edgeoffset = -5;
		}
	}
	return edgeoffset
}

function populatepopup(what){
	if (ie4||ns6)
		popupobj.innerHTML=what.join("")
}

function popupinfo_fixlocation(obj, e, popupcontent, popupwidth){

	jQuery('div.popupFixWindow').html(popupcontent);

	//if (window.event) event.cancelBubble=true
	//else if (e.stopPropagation) e.stopPropagation()

	clearhidepopup()
	popupobj=document.getElementById? document.getElementById("popupFixWindow") : popupFixWindow

	document.getElementById("popupTailTopLeft").style.visibility="hidden";
	document.getElementById("popupTailBottomLeft").style.visibility="hidden";
	document.getElementById("popupTailTopRight").style.visibility="hidden";
	document.getElementById("popupTailBottomRight").style.visibility="hidden";

	//populatepopup(popupcontents)

	if (ie4||ns6){

		//showhide(popupobj.style, e, "visible", "hidden", popupwidth);

		popupobj.x=getposOffset(obj, "left")
		popupobj.y=getposOffset(obj, "top")

		var rightedge = clearbrowseredge(obj, "rightedge");
		var bottomedge = clearbrowseredge(obj, "bottomedge");
		
		var left = document.body.clientLeft + (document.body.clientWidth/2) - (popupobj.offsetWidth/2);
		var top = document.body.clientTop + topclearance;
	
		if(!browser_ie6())
			popupobj.style.position = "fixed";
		popupobj.style.left=left+"px";
		popupobj.style.top=top+"px";

	}

	popupobj.style.visibility="visible";
	//popuptailobj.style.visibility="visible";


	return clickreturnvalue()
}


function popupinfo(obj, e, popupcontent, popupwidth){

	jQuery('div.popupWindow').html(popupcontent);

	if (window.event) event.cancelBubble=true
	else if (e.stopPropagation) e.stopPropagation()

	clearhidepopup()
	popupobj=document.getElementById? document.getElementById("popupWindow") : popupWindow

	document.getElementById("popupTailTopLeft").style.visibility="hidden";
	document.getElementById("popupTailBottomLeft").style.visibility="hidden";
	document.getElementById("popupTailTopRight").style.visibility="hidden";
	document.getElementById("popupTailBottomRight").style.visibility="hidden";

	//populatepopup(popupcontents)

	if (ie4||ns6){
		showhide(popupobj.style, e, "visible", "hidden", popupwidth)
		popupobj.x=getposOffset(obj, "left")
		popupobj.y=getposOffset(obj, "top")

		var rightedge = clearbrowseredge(obj, "rightedge");
		var bottomedge = clearbrowseredge(obj, "bottomedge");

		//alert(rightedge+" , "+bottomedge);
		var left = popupobj.x-rightedge+obj.offsetWidth+horizontaloffset;
		var top = popupobj.y-bottomedge;


		if(bottomedge <0 ) {
			top=top+20
			if(rightedge <0 ) {
				left=left-20
				popupobj.style.left=left+"px";
				popupobj.style.top=top+"px";

				popuptailobj=document.getElementById? document.getElementById("popupTailTopLeft") : popupTailTopLeft;
				popuptailobj.style.left=left-28 + "px";
				popuptailobj.style.top=top+15 + "px";
			} else {
				left=left+20
				popupobj.style.left=left+"px";
				popupobj.style.top=top+"px";

				popuptailobj=document.getElementById? document.getElementById("popupTailTopRight") : popupTailTopLeft;
				popuptailobj.style.left=left+popupwidth+20 + "px";
				popuptailobj.style.top=top+15 + "px";
			}
		} else {
			top=top-60
			if(rightedge <0 ) {
				left=left-20
				popupobj.style.left=left+"px"
				popupobj.style.top=top+"px"

				popuptailobj=document.getElementById? document.getElementById("popupTailBottomLeft") : popupTailTopLeft;
				popuptailobj.style.left=left-28 + "px";
				popuptailobj.style.top = top +bottomedge+80+ "px";
			} else {
				left=left+20
				popupobj.style.left=left+"px"
				popupobj.style.top=top+"px"

				popuptailobj=document.getElementById? document.getElementById("popupTailBottomRight") : popupTailTopRight;
				popuptailobj.style.left=left+popupwidth+20 + "px";
				popuptailobj.style.top = top +bottomedge+80+ "px";
			}
		}


	}

	popupobj.style.visibility="visible";
	popuptailobj.style.visibility="visible";


	return clickreturnvalue()
}


function clickreturnvalue(){
	if (ie4||ns6) return false
	else return true
}

function contains_ns6(a, b) {
	while (b.parentNode)
		if ((b = b.parentNode) == a)
			return true;
	return false;
}

function dynamichide(e){
	if (ie4&&!popupobj.contains(e.toElement))
		delayhidepopup()
	else if (ns6&&e.currentTarget!= e.relatedTarget&& !contains_ns6(e.currentTarget, e.relatedTarget))
	delayhidepopup()
}

function hidepopup(e){
	if (typeof popupobj!="undefined"){
	if (ie4||ns6) {
		popupobj.style.visibility="hidden";
		//popuptailobj.style.visibility="hidden";
	}
}
}

function delayhidepopup(){
	if (ie4||ns6)
		delayhide=setTimeout("hidepopup()",disappeardelay)
}

function clearhidepopup(){
	if (typeof delayhide!="undefined")
		clearTimeout(delayhide)
}

function quickview(obj)
{
	var $this = $(obj);
	var $parent = $this.parent().parent().parent();
	var $content = $parent.siblings('div.listingDetail');
	
	popupinfo_fixlocation($parent, 
		null, 
		$content.html(), 395);
}

function createLabel(point, url, obj) {
	var title = obj.code,	label = new BpLabel(point,title,'myLabelClass','center');
	label.setUserData({
		url: url
	});
	label.setCursor('pointer');
	return label;
}

function addAllLabels() {
	var ploted = {}, zipcc_length = zipcc.length, zoom;
	if(zipcc_length != 0) {
		for ( var i=0; i<zipcc_length; i++) {
			var id = zipcc[i].code;
			if(!ploted[id]) {
				ploted[id] = true;
				var point = new GLatLng( zipcc[i].lat, zipcc[i].lng ), $a = jQuery('td.avgzp_zip a:contains("'+id+'")');
				var label = createLabel( point, $a.attr('href'), zipcc[i] );
				hhmap.addOverlay(label);
				var target = label.getEventTarget();
				GEvent.bindDom(target,'click',label,function(){
					window.location = this.getUserData().url;
				});
				$a.data('target', label).hover(
					function(){
						var lbl = jQuery(this).data('target');
						lbl.setClassName('myOtherLabelClass');
					},
					function(){
						var lbl = jQuery(this).data('target');
						lbl.setClassName('myLabelClass');
					}
				);
				bounds.extend(point);
			}
		}
		zoom = hhmap.getBoundsZoomLevel(bounds);
		if (zipcc_length<=2){
			zoom = zoom-(6-zipcc_length);
		}
		hhmap.setCenter(bounds.getCenter(), zoom);
	}
}

function getCityAgentBio() {
	jQuery.ajax({
		url: 'http://www.househunt.com/pages/hhorg/cgi-bin/househunt/new-page/city_agent_bio_xml.cgi',
		data: {id: city_id},
		success: function(xml){
			var $xml = jQuery(xml),
			sCity1 = $xml.find('city_bio1').text(),
			sCity2 = $xml.find('city_bio2').text(),
			sCity3 = $xml.find('city_bio3').text(),
			sAgt1 = $xml.find('agent_bio1').text(),
			sAgt2 = $xml.find('agent_bio2').text(),
			sAgt3 = $xml.find('agent_bio3').text(),
			aLines = [], subCity = '';
			if (sCity1 !== '') {
				aLines = sCity1.split('<br/>');
				subCity = aLines.shift();
				if(aLines.length > 0) {
					subCity += '<br/>';
					subCity += aLines.shift();
					subCity = subCity.replace(/<br\/>$/, '');
					sCity1=aLines.join('<br/>');
					sCity1 = sCity1.replace(/^<br\/>/, '');
				} else {
					sCity1 = '';
				}
			}
			var sClass = (sCity1 === '' && sCity2 === '') ? 'hide' : '';
			var sHtml = [
				subCity,
				'<span id="more-city-bio" class="hide">',
				'<br/><br/>',
				sCity1,
				sCity2,
				sCity3,
				'</span>',
				'<a class="', sClass, '" href="#" id="city-bio-adjust">[ More ]</a>'
			].join('');
			jQuery('#city_bio').html(sHtml);
			
			sClass = (sAgt2 === '') ? 'hide' : '';
			sHtml = [
				sAgt1,
				'<span id="more-agent-bio" class="hide">',
				sAgt2,
				sAgt3,
				'</span>',
				'<a class="', sClass, '" href="#" id="agent-bio-adjust">[ More ]</a>'
			].join('');
			jQuery('#agent_bio').html(sHtml);
		},
		complete: function(){
			jQuery('#city-bio-adjust').toggle(
				function(){
					jQuery('#more-city-bio').show().parents('.featFrameLg').addClass('show-more-city-bio');
					jQuery(this).text('[ Less ]');
				},
				function(){
					jQuery('#more-city-bio').hide().parents('.featFrameLg').removeClass('show-more-city-bio');
					jQuery(this).text('[ More ]');
				}
			);
			jQuery('#agent-bio-adjust').toggle(
				function(){
					jQuery('#more-agent-bio').show();
					jQuery(this).text('[ Less ]');
				},
				function(){
					jQuery('#more-agent-bio').hide();
					jQuery(this).text('[ Less ]');
				}
			);
		}
	});
}

function getSchoolsPlactes(){
	jQuery.ajax({
		url: 'http://www.househunt.com/pages/hhorg/cgi-bin/househunt/new-page/amenity_xml.cgi',
		data: {
			city_name: city_name,
			st: st,
			terr_zipcode: terr_zipcode
		},
		success: function(xml){
			var $xml = jQuery(xml), aSchools=[], aPlaces=[], sCitySt = '';
			sCitySt = $xml.find('amenity_info').attr('city_state');
			var sSchoolUrl = home_page+'/schools/'+sCitySt+'/', sPlaceUrl = home_page+'/places/'+sCitySt+'/';
			$xml.find('school category').each(function(){
				var $this = $(this);
				aSchools.push('<div class="cellItem"><a href="'+sSchoolUrl+$this.find('url').text()+'/">'+$this.find('name').text()+'</a> ('+$this.find('num').text()+')</div>');
			});
			$xml.find('places category').each(function(){
				var $this = $(this);
				aPlaces.push('<div class="cellItem"><a href="'+sPlaceUrl+$this.find('url').text()+'/">'+$this.find('name').text()+'</a> ('+$this.find('num').text()+')</div>');
			});
			jQuery('#more-school').html(aSchools.join(''));
			jQuery('#more-place').html(aPlaces.join(''));
		}
	});
}

(function init() {
	getCityAgentBio();
	getSchoolsPlactes();
	if (GBrowserIsCompatible()) {
		hhmap = new GMap2(document.getElementById("hhmap"));
		hhmap.addControl(new GSmallMapControl());
		hhmap.addControl(new GMenuMapTypeControl());
		hhmap.setCenter(new GLatLng(43.907787,-79.359741), 14);
		bounds = new GLatLngBounds;
		addAllLabels();
	}
})();