var jj = null;
var jj2 = null;
var menuModel = null;
var menuBar  = null;
var map = null;
var geocoder = null;
var tooltip1 = null;
var g_useremail   = "";
var g_userhash  = "";
var g_dmarker = null;
var g_mpoint  = null;
var g_pu_count=0;
var g_houses= new Array();
var g_himgs = new Array();
var g_icon  = new Array();
var g_selected_marker = null;
var g_ovcontrol = null;
var g_center_cityll = null;
var g_center_city_name = "";
var g_dir_update = false;
var g_cimg = 0;
var g_browser = null;
var g_registeredcities = new Array();
var g_scr_width = 1024;
var g_scr_height = 768;
var g_userads = null;
var g_approx_word = 'approximate';
var g_bmarker_dragged = false;
var g_icCity = null;
var g_icHouse = null;
var g_icHouse_s = null;
var g_icSelHouse = null;
var g_zoomStreet = 13;
var g_zoomCity   = 11;
var g_zoomState  = 7;
var g_zoomUSA    = 4;
var g_cities     = new Array();
var g_lastBox    = null;
var g_lastZoom   = 0;
var g_CitySkipList  = "";
var g_HouseSkipList = "";
var g_HMarkers = new Array();
var g_CMarkers = new Array();
var g_MaxHouseNumber = 160;
var g_MaxCityNumber = 160;
var g_mapedrag=0;
var g_mapezoom=0;
var g_marquee_ads = false;
var g_LastSearchPoint = new GLatLng(0,0);
var g_LastSearchZoom = g_zoomCity; 
var g_set  = new Array();g_set[0] = 0;
var g_lastPt = new Array(0,0);
var g_lastMs = 0;
var g_tbt1 = 0;
var g_cFL   = new Array("","","","");
var g_cFLP  = new Array(new GLatLng(0,0),new GLatLng(0,0),new GLatLng(0,0),new GLatLng(0,0));
var g_cFLZ  = new Array(g_zoomCity,g_zoomCity,g_zoomCity,g_zoomCity);
var g_cFLi  = 0;
var g_bSwitch2PostAd = false;
var g_MovingObj = null;
var OnPostSearch = null;
var g_paramstack = null;
var g_cw=0;
var g_hw=0;
var g_clickHelp = 0;
var g_replacemsg = "";
var g_lastHash = "";


var g_cvars_form1 = new Array('price_sale_min','price_sale_max','price_rent_min','price_rent_max','ad_type','bed','bath','bath2');

function SaveCookies(arr)
{
	for(var i=0;i<arr.length;i++)
		setCookie(arr[i],g(arr[i]).value,35);
}
						
function LoadCookies(arr)
{
	for(var i=0;i<arr.length;i++)
	{
		var c = getCookie(arr[i]);
		if(c.length>0)
			g(arr[i]).value = c;
	}
}

function OnFormChange()
{
	login_menuupdate();
	SaveCookies(g_cvars_form1);
}

function ToggleAutoHide()
{
	if (g_set[0]==1)
	{
		g_set[0]=0;
		g('autohide').innerHTML = 'On';
	}
	else
	{
		g_set[0]=1;
		g('autohide').innerHTML = 'Off';
	}
	setCookie('g_set0',g_set[0],365);
}


function blinkfor(maxi,objname)
{
	var obj = g(objname);
	var i=1;
	for(var i=1;i<=maxi;i++)
	{
		var str ="";
		if (i%2==0)
			str = "'opacity100'";//Hide(objname);
		else
			str = "'opacity50'";//Show(objname);

		setTimeout("g('"+objname+"').className="+str+";",1000*i);
	}
		
}

function blinkforColor(maxi,objname,bcolor,time)
{
	var obj = g(objname);
	var i=1;
	var str = new Array(bcolor,"#FFF");
	for(var i=0;i<maxi;i++)
	{
		setTimeout("g('"+objname+"').style.backgroundColor='"+str[i%2]+"';g('"+objname+"').style.color='"+str[(i+1)%2]+"';",time*i);
	}
		
}

function setOpacity(objname,value) 
{
	var obj = g(objname);
	obj.style.opacity = value/100.0;
	obj.style.filter = 'alpha(opacity=' + value + ')';
}
function GradualDegrade(objname,totalsec,until)
{
	
	for(var i=99;i>=until;i--)
	{
		var cmd = "";
		if (i==0)
			cmd = "g('"+objname+"').style.visibility = 'hidden';";
		else
			cmd = "setOpacity('"+ objname +"',"+ i +");" ;
		setTimeout(cmd,(100-i)*totalsec*10.0);
	}
}

function GradualApperance(objname,totalsec,until)
{
	/*if (IsIE())
	{
		setOpacity(objname,until);
		Show(objname);	
	}
	else*/
	{
		setOpacity(objname,0);
		Show(objname);	
		for(var i=1;i<=until;i++)
		{
			var cmd = "setOpacity('"+ objname +"',"+ i +");" ;
			setTimeout(cmd,i*totalsec*10.0);
		}
	}
}

function GlobalMessage(txt,delay)
{
	//<img id="gmessage_img"  style="visibility:hidden;margin-right:auto;margin-left:auto;display:block;text-align:center" src=""><br>
	Show('gmessage');
	g('gmessage_text').innerHTML = txt;
	
	CenterMeOnScreen(g('gmessage'));
	g('gmessage').style.visibility='visible';

	setOpacity('gmessage',100);
	setTimeout("GradualDegrade('gmessage',1,0);",delay);
}

function FindEmptyFav()
{
	for(var i=0;i<4;i++)
	{
		if (g_cFL0!="")
			return i;
	}
	return -1;
}

function GotoFavLoc(n)
{
	if (n<0||n>3)
		return;

	if (g_cFL[n].length>0)
	{
		ClearMap();
		map.setCenter(g_cFLP[n],g_cFLZ[n]);
		Search();
	}
}


function SaveFavLoc()
{
	if (g_cFLi<0||g_cFLi>3)
		return;

	var d = new Date();
	var dstr = d.toLocaleString();
	g_cFL[g_cFLi]  = "Saved on "+ dstr ;
	g_cFLP[g_cFLi] = map.getCenter();
	g_cFLZ[g_cFLi] = map.getZoom();
	g(('favloc'+g_cFLi)).innerHTML = g_cFL[g_cFLi];

	setCookie('g_cFL'+g_cFLi+'_P0',g_cFLP[g_cFLi].lat()	,365);
	setCookie('g_cFL'+g_cFLi+'_P1',g_cFLP[g_cFLi].lng()	,365);
	setCookie('g_cFL'+g_cFLi+'_Z', g_cFLZ[g_cFLi]		,365);
	setCookie('g_cFL'+g_cFLi,g_cFL[g_cFLi],365);
	g_cFLi = (++g_cFLi)%4;
	setCookie('g_cFLi',g_cFLi,365);
}

function  GetCookies()
{
	if (getCookie('g_cLastSearchLat').length>0)
	{
		g_LastSearchPoint = new GLatLng(getCookie('g_cLastSearchLat'),getCookie('g_cLastSearchLng'));
		g_LastSearchZoom  = parseInt(getCookie('g_cLastSearchZoom'));
	}
	if (getCookie('g_set0').length>0)
	{	
		for(var i=0;i<g_set.length;i++)
		{
			var v = 'g_set'+i;
			var c = getCookie(v);
			if (c.length>0)
				g_set[i] = parseInt(c);
		}
		g('autohide').innerHTML = ((g_set[0]==1)?'Off':'On');
	}


	if (getCookie('g_cFLi').length>0)
	{
		g_cFLi = getCookie('g_cFLi');

		if (getCookie('g_cFL0').length>0)
		{
		g_cFL[0]  = getCookie('g_cFL0');
		g_cFLP[0] = new GLatLng(getCookie('g_cFL0_P0'),getCookie('g_cFL0_P1'));
		g_cFLZ[0] = parseInt(getCookie('g_cFL0_Z'));
		g('favloc0').innerHTML = g_cFL[0];
		}
		if (getCookie('g_cFL1').length>0)
		{
		g_cFL[1]  = getCookie('g_cFL1');
		g_cFLP[1] = new GLatLng(getCookie('g_cFL1_P0'),getCookie('g_cFL1_P1'));
		g_cFLZ[1] = parseInt(getCookie('g_cFL1_Z'));
		g('favloc1').innerHTML = g_cFL[1];
		}
		if (getCookie('g_cFL2').length>0)
		{
		g_cFL[2]  = getCookie('g_cFL2');
		g_cFLP[2] = new GLatLng(getCookie('g_cFL2_P0'),getCookie('g_cFL2_P1'));
		g_cFLZ[2] = parseInt(getCookie('g_cFL2_Z'));
		g('favloc2').innerHTML = g_cFL[2];
		}
		if (getCookie('g_cFL3').length>0)
		{
		g_cFL[3]  = getCookie('g_cFL3');
		g_cFLP[3] = new GLatLng(getCookie('g_cFL3_P0'),getCookie('g_cFL3_P1'));
		g_cFLZ[3] = parseInt(getCookie('g_cFL3_Z'));
		g('favloc3').innerHTML = g_cFL[3];
		}
	}
	
	LoadCookies(g_cvars_form1);
	
	if (getCookie('g_center_citylat').length>0)
	{
		g_center_cityll 	= new GLatLng(getCookie('g_center_citylat'),getCookie('g_center_citylng'));
		g_center_city_name 	= getCookie('g_center_city_name');
	}
}
function page_load2()
{
	GetCookies();
	ChangeAdMode();
	
	if (!IsIE())
	{
		setTimeout('if (!g_marquee_ads)	PutAds();',100000);
		initMarquee();
		Show('dhtmlgoodies_marquee');
	}

	initContextMenu();


	if (!IsIE())
	{
		Show('ad_source');
		g_MaxHouseNumber = 300;
		g_MaxCityNumber  = 300;
	}
	
	Show('mainContent');
	
	if (!IsIE())
		setTimeout("PeriodicUpdate();",8000);
	else
	{
		setTimeout("g('firefoximg').src='images/firefox.png';Show('firefoximg');",8000);
		g('gadwt2').style.left = '10px';
		g('gadwt2').style.top  = '30px';
		Show('gadwt2');
	}
}


function page_load()
{
	Hide('mainContent');
	g_browser= navigator.appName;

	if (!GBrowserIsCompatible())
		GlobalMessage('I am sorry, your browser is not supported...<br>Please download latest Firefox!',8000);
	
	//if (!IsIntroDone())
	//	executeZoomScript();

	LoadIcons();
	
	map = new GMap2(g('map'));
	geocoder = new GClientGeocoder();
	tooltip1 = document.createElement("div");
	map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip1);
	tooltip1.style.visibility="hidden";
	map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(8,55)));
	g_ovcontrol = new GOverviewMapControl(new GSize(240,135));
    map.addMapType(G_PHYSICAL_MAP);
	map.addControl(g_ovcontrol);
	map.enableDoubleClickZoom();
	map.enableScrollWheelZoom();
	map.enableContinuousZoom();
	InitMapEvents();
	IsLoggedIn(InitNav);
	create_menu();
	g_scr_width  = g('map').clientWidth;
	g_scr_height = g('map').clientHeight;	

	page_load2();
	map.setMapType(G_PHYSICAL_MAP);
	
	ChangeAdMode();OnFormChange();
}

function onResize()
{
 	var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) 
	{
    	//Non-IE
	    myWidth = window.innerWidth;
    	myHeight = window.innerHeight;
	} 
	else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  	}

	g('map').style.width  = myWidth+'px';
	g('map').style.height = myHeight+'px';
	g('map').style.left   = '0px';
	g('map').style.top    = '0px';

	g_scr_width  = myWidth;
	g_scr_height = myHeight;
}

function CenterAndZoom(point,zoom)
{
	map.panTo(point);
	setTimeout("map.setCenter(new GLatLng("+point.x+","+point.y+"),"+zoom+");",800);
}

function GotoLastSearchSpot()
{
	if (g_LastSearchPoint.lat()!=0)
	{
		ClearMap();
		map.setCenter(g_LastSearchPoint,g_LastSearchZoom);
		Search();
	}
	else
		GotoUSA();
}

function OnMapMove()
{
	if (map.getZoom()<g_zoomCity)
		UpdateCities();
	else
		UpdateHouses();
	MapOverViewDirection();

	if (map.getZoom()>=g_zoomCity)
	{
		g_LastSearchPoint = map.getCenter();
		g_LastSearchZoom  = map.getZoom();
		setCookie('g_cLastSearchLat',g_LastSearchPoint.lat(),365);
		setCookie('g_cLastSearchLng',g_LastSearchPoint.lng(),365);
		setCookie('g_cLastSearchZoom',g_LastSearchZoom,365);
	}
	SetHash();
}



function InitMapEvents()
{
	GEvent.addListener(map,"dragstart", function() 
	{
		g_mapedrag = 1;
	});

	GEvent.addListener(map,"dragend", function() 
	{
		  HideItemView();
		if (InPostMode())
			return;
		OnMapMove();
		g_mapedrag = 0;
	});

	GEvent.addListener(map,"moveend", function() 
	{
		if (g_center_city_name!=null)
			MapOverViewDirection();

		if (InPostMode())
			return;

		if (!g_mapedrag&&!g_mapezoom)
		{
			OnMapMove();
		}
		if (g_mapezoom)
			g_mapezoom = 0;
	});

	GEvent.addListener(map,"zoomend", function(oldLevel, newLevel) 
	{
		g_mapezoom = 1;
		if (map.getZoom()<=g_zoomCity)
			HideItemView();
		
		if (InPostMode())
			return;

		if (newLevel<g_zoomCity && oldLevel>=g_zoomCity)
		{
			ClearMap();
			GetCities();
		}
		else if (newLevel>=g_zoomCity && oldLevel<g_zoomCity)
		{
			ClearMap();
			OnSearch();
			Search();
		}
		else if ((newLevel<g_zoomState && oldLevel>=g_zoomState)||
				 (newLevel>=g_zoomState && oldLevel<g_zoomState))
		{
			ClearMap();
			UpdateCities();
		}
		else
		{
			MapOverViewDirection();
			if (map.getZoom()<g_zoomCity)
				UpdateCities();
			else
				UpdateHouses();
		}
	
	});

}

function InitNav()
{
	if (init_zoom!=0)
		showAddress(init_dest,init_zoom,null);
	else if (init_housesrc!="")
	{
		GotoHouse(init_housesrc,true); 
		OnSearch();
	}
	else if (init_msg.length>0)
	{
		g_replacemsg = init_msg;
		GotoUSA();
	}
	else 
	{
		if (g_LastSearchPoint.lat()==0)
			GotoUSA();
		else
			GotoLastSearchSpot();
	}
}


function MyTxtTip(e,tip)
{
	showTooltip2(e.clientX+5,e.clientY+5,tip);
}


function IsIntroDone()
{
	var intro_done=getCookie('intro_done');
	if (intro_done!=null && intro_done!="")
	  	return true;
	else
		return false;
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
  	{
  		c_start=document.cookie.indexOf(c_name + "=");
  		if (c_start!=-1)
    	{ 
    		c_start=c_start + c_name.length+1; 
    		c_end=document.cookie.indexOf(";",c_start);
    		if (c_end==-1) c_end=document.cookie.length;
    		return unescape(document.cookie.substring(c_start,c_end));
    	} 
  	}
	return "";
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function MakeHistory(city)
{
  window.location.hash = city;
}
function HandleHistory()
{
  var hashtext = window.location.hash;
  hashtext = hashtext.replace('#','');
    
  if ( hashtext != g_center_city_name )
  {
    g_center_city_name = hashtext;
    GotoRegisteredCity( g_center_city_name );
  }
  
  setTimeout("HandleHistory();", 1000);
  return true;
}


function GotoRegisteredCity(city)
{
	if (city.length==0)
		GotoUSA();
	else
	{
	
		var index = -1;
		for (var i = 0; i < g_registeredcities.length &&index==-1 ; i++)
		{
			if (g_registeredcities[i] == city)
				index = i;
		}
		
		if (index != -1)
			GotoCity(g_registeredcities[index],g_registeredcities[index+1],g_registeredcities[index+2]);
	}
}

function GotoUSA()
{
	ClearMap();
	map.setCenter(new GLatLng(35.7071866568, -94.5703125), g_zoomUSA);
	GetCities();
}

function GotoArea(area,lat,long,level)
{
	if (level==0)
		GotoCity(area,lat,long);
	else
	{
		ClearMap();
		var point = new GLatLng(lat,long);
		map.setCenter(point,g_zoomState);
		g_center_cityll = point;
		g_center_city_name = area;
		setCookie('g_center_citylat',g_center_cityll.lat(),365);
		setCookie('g_center_citylng',g_center_cityll.lng(),365);
		setCookie('g_center_city_name',g_center_city_name,365);
		g_replacemsg = "";
		GetCities();
	}

}

function GotoCity(city,lat,long)
{
	ClearMap();
	var point = new GLatLng(lat,long);
	map.setCenter(point,g_zoomCity);
	g_selected_marker = null;
	g_center_cityll = point;
	g_center_city_name = city;
	setCookie('g_center_citylat',g_center_cityll.lat(),365);
	setCookie('g_center_citylng',g_center_cityll.lng(),365);
	setCookie('g_center_city_name',g_center_city_name,365);

	
	Search();
	OnSearch();
	HideItemView();
	
	
	g('omap_direction').innerHTML = "Welcome to <span style='color:#F00'>"+g_center_city_name.toUpperCase()+'</span>';
	
	Show('omap_direction'); 
	//g_ovcontrol.show();	
		
	//MakeHistory(city);
	//RegisterCity(city,lat,long);
}

function RegisterCity(city,lat,long)
{
	var index = -1;
	for (var i = 0; i < g_registeredcities.length &&index==-1 ; i++)
	{
		if (g_registeredcities[i] == city)
			index = i;
	}
	
	if (index == -1)
	{
		g_registeredcities.push(city);
		g_registeredcities.push(lat);
		g_registeredcities.push(long);		
	}
	
}

function KTranslate(objname,x,y,k,timediff)
{
	for(var i=1;i<=k;i++)
		setTimeout("Translate('"+objname+"',"+x+","+y+");",timediff*i);
}

function K2Translate(objname,x,y,k,timediff)
{
	for(var i=1;i<=k;i++)
		setTimeout("Translate('"+objname+"',"+(x*i)+","+(y*i)+");",timediff*i);
}

function Translate(objname,x,y)
{
	var obj = g(objname);
	var pos = getT(obj);
	setT(obj,x+pos[0],y+pos[1]);
}


function HSlideIn(objname,x_final,w1)
{
	var obj = g(objname);
	var y 	= getY(obj);
	var w	= w1!=0? w1:getW(obj);
	
	var x1 	= -10-w;
	var k	= 1;
	var steps 		= (x_final - x1)/20;
	var interval 	= 100;
	
	obj.style.width = w1+'px';
	
	Translate(objname,400,400);
		
	for(var i=x1;i<=x_final;i+=steps)
	{
		setTimeout("Translate('"+objname+"',"+i+","+y+");",interval*k++);
	}
		
	return (k-1)*interval;
}
	

function setT(obj,x,y)
{
	obj.style.left = x + 'px';
	obj.style.top  = y + 'px';
}

function setX(obj,x){obj.style.left  = x + 'px';}

function setW(obj,w)
{obj.style.width  = w + 'px';}
function getW(obj)
{
	var width1 = obj.style.width;
	var width  = width1.replace('px','');
	return parseInt(width);
}

function setH(obj,w){obj.style.height = h + 'px';}

function getH(obj)
{
	return parseInt(obj.style.height.replace('px',''));
}

function getX(obj)
{
	return parseInt(obj.style.left.replace('px',''));
}
function getY(obj)
{
	return parseInt(obj.style.top.replace('px',''));
}

function getT(obj)
{
	return new Array(getX(obj),getY(obj));
}

function MakeWidthHeight(obj,W,H)
{
	var w = parseInt(getW(obj));
	
	if ( w < W )
	{
		while(w<W)
		{
			setW(obj,++w);
		}
	}
	else
	{
		while(w>W)
			setW(obj,--w);
	}
	
	var h = getH(obj);
	
	if ( h< H )
	{
		while(h<H)
			setW(obj,++h);
	}
	else
	{
		while(h>H)
			setW(obj,--h);
	}
}



function g(name)
{
	return document.getElementById(name);
}


function MapOverViewDirection()
{
	if (map&&map.getZoom()>g_zoomCity)
		FigureOutMapWRTCity();
	else if (map&&map.getZoom()<g_zoomCity) 
		Hide('omap_direction');
}

function PeriodicUpdate() 	
{
	PollHash();
	setTimeout("PeriodicUpdate();",3000);
}


function DistApprox(x,y,x2,y2)
{
	return Math.abs(x-x2)+Math.abs(y-y2);
}

function FindClosestCity(lat,lng)
{
	var min = 10000;
	var index = -1;
	for(var i=0;i<g_cities.length;i++)
	{
		var cityll = g_cities[i];
		var dist = DistApprox(lat,lng,cityll[1],cityll[2]);
		if (dist<min)
		{
			min = dist;
			index = i;
		}	
	}
	return index;
}

function FigureOutMapWRTCity()
{
	if (g_center_city_name=="")
		return;
		
	var currentll = map.getCenter();
	var diff = Array(currentll.lat()-g_center_cityll.lat(),currentll.lng()-g_center_cityll.lng());
	var str = "";
	if (diff[0]<0)
		str+= "South ";
	else
		str+= "North ";
	
	if (diff[1]<0)
		str+= "West ";
	else
		str+= "East ";
	
	str += "of <span style='color:#F00'>"+g_center_city_name+"</span>";
	
	g('omap_direction').innerHTML = str;
	Show('omap_direction');
}





function IsIE()
{
	return (g_browser.indexOf("Microsoft",0)==0);
}



function NextImg()
{
	if (g_himgs.length==0)
		return;
	
	g_cimg++;
	
	if (g_cimg>=g_himgs.length)
		g_cimg = 0;

	var img = g('itemviewimg');
	img.src = g_himgs[g_cimg];
	var total = g_himgs.length;
	if (total==0)
		total = 1;
	g('imgnumber_s').innerHTML = (g_cimg+1) +'/'+ total;
	g('imgnumber').innerHTML = (g_cimg+1) +'/'+ total;
}
function PrevImg()
{
	if (g_himgs.length==0)
		return;
		
	g_cimg--;
	
	if (g_cimg<0)
		g_cimg = g_himgs.length-1;
		
	var img = g('itemviewimg');
	img.src = g_himgs[g_cimg];
	g('imgnumber_s').innerHTML = (g_cimg+1) +'/'+g_himgs.length;
	g('imgnumber').innerHTML = (g_cimg+1) +'/'+g_himgs.length;
}



function showAddress(address,zoomlevel,func) 
{
	
	geocoder.getLatLng(
		address,
		function(point) 
		{
		  if (!point) 
		  {
			alert(address + " not found");
		  } 
		  else 
		  {
			map.panTo(point);
			if (zoomlevel>=0)
				map.setCenter(point, zoomlevel);
				
			if (func)
				func();
		  }
		}
	  );
}
function showTooltip1(marker) 
{
	tooltip1.innerHTML = marker.tooltip1;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip1.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
	pos.apply(tooltip1);
	
	tooltip1.style.visibility="visible";
	
}


function login_menuupdate()
{	
	if (g_useremail != "")
	{
		var logouttext = g('logoutuser');
		logouttext.innerHTML = g_useremail;
		menuBar.showMenuItem(501500);
		menuBar.hideMenuItem(501000);
		menuBar.hideMenuItem(502000);
	}
	else
	{
		menuBar.hideMenuItem(501500);
		menuBar.showMenuItem(501000);
		menuBar.showMenuItem(502000);
	}

	var str = "<span style='color:white' onclick='OnSearch();'>"+MySearch2String()+"<img src='images/search2.png'></span> ";

	if (g_useremail.length>0)
	{
		//if (g_userads&&g_userads.length>0)	str += "<span style='color:red;'>ads(<span style='color:red'>"+g_userads.length+"</span>)  </span>, ";
	
		g('cm_login').style.display='none';
		g('logged_user').innerHTML = str + g_useremail ;
	}
	else
	{
		g('cm_login').style.display='block';
		g('logged_user').innerHTML = str +"<span style='color:white' onclick='SignIn(1);'> not logged in</span>";
	}
}	

function create_menu()
{
	menuModel = new DHTMLSuite.menuModel();
	DHTMLSuite.configObj.setCssPath('css/');
	menuModel.addItemsFromMarkup('menuModel');
	menuModel.setMainMenuGroupWidth(00);	
	menuModel.init();
	menuBar = new DHTMLSuite.menuBar();
	menuBar.addMenuItems(menuModel);
	menuBar.setTarget('menuDiv');
	menuBar.init();	
	login_menuupdate();
}

function ShowFor(obje,sec)
{
	Show(obje.id);
	setTimeout("Hide('"+ obje.id + "');",sec);
}
function createCityMarker(point, html,icon,name,level) 
{
	var marker = new GMarker(point,icon);
	marker.tooltip1 = html;
	GEvent.addListener(marker,"mouseover", function() {
		  showTooltip1(marker);
		});    
	GEvent.addListener(marker,"click", function() {
		  GotoArea(name,point.lat(),point.lng(),level);
		  });  
	GEvent.addListener(marker,"mouseout", function() {
		tooltip1.style.visibility="hidden"
		});    
	return marker;
}


function ExecuteHash()
{
	if (window.location.hash.length==0)
		return;

   var str = window.location.hash.replace('#','');
   var llz = str.split('_');
	
	map.panTo(new GLatLng(llz[0],llz[1]));
	if (map.getZoom()!=llz[2])
		map.setZoom(llz[2]);
}

function PollHash()
{
	if (window.location.hash==g_lastHash) 
       return;
	g_lastHash = window.location.hash;
	ExecuteHash();
}

function SetHash()
{
	if (IsIE())
		return;

	str = map.getCenter().lat()+"_"+map.getCenter().lng()+"_"+map.getZoom();
	window.location.hash = str; 
	g_lastHash = window.location.hash;
}


function SelectMarker(marker)
{
	if (g_selected_marker)
		g_selected_marker.setImage("images/h1_100s.png");					
	g_selected_marker = marker;
	g_selected_marker.setImage("images/h1_100sels.png");		
}

var g_temp1;
var g_temp2;
function CenterZoom2(point,zoom,postfunc)
{
	map.panTo(point);
	g_temp1 = point;
	g_temp2 = zoom;
	setTimeout("map.setCenter(g_temp1,g_temp2);eval('postfunc');",750);
}


function createMarker(point, html,icon,submarker) 
{
	var marker = new GMarker(point,icon);
	marker.tooltip1 = html;
	marker.submarker = submarker;
	GEvent.addListener(marker,"mouseover", function() 
		{
		  showTooltip1(marker);
		  marker.setImage("images/h1_100bigs.png");
		});    
	GEvent.addListener(marker,"click", function()
		{
 			  SelectMarker(marker);
              map.panTo(marker.getPoint());
			  if (map.getZoom()<g_zoomStreet-1)
				map.setCenter(marker.getPoint(),g_zoomStreet);
			  ShowItemView(marker,null);
			  tooltip1.style.visibility="hidden";
		}
	);  
	GEvent.addListener(marker,"mouseout", function() 
		{
		tooltip1.style.visibility="hidden";
		if (marker == g_selected_marker)
			marker.setImage("images/h1_100sels.png");
		else
			marker.setImage("images/h1_100s.png");
		});    
	
	return marker;
}


function ShowEmailPanel(sahibe)
{
	Hide('emailpanel');
	Hide('whole');

	g('emtodiv').style.visibility=sahibe?"hidden":"visible";
	g('emailmode').innerText = sahibe;
		
	PositionMeOnScreen(0.5,0.25,g('emailpanel'),false);
	
	var emailcookie = getCookie('email');

	if (g_useremail.length>0)
		g('EmFrom').value = g_useremail;
	else if (emailcookie.length>0)
		g('EmFrom').value = emailcookie;

	Show('emailpanel');
	Show('whole');
}

function BlinkObj(objname)
{
	setTimeout("g('"+objname+"').style.backgroundColor='red';g('"+objname+"').style.color='black'",50);
	setTimeout("g('"+objname+"').style.backgroundColor='black;g('"+objname+"').style.color='white'",500);
}

function MektupGonder()
{
	if (g('emailmode').innerText == '1')
		SahibineMektup();
	else if (g('emailmode').innerText == '2')
		ContactBOP();
	else
		ArkadasaMektup();
	
}

function ArkadasaMektup()
{
	
	var ok = true;
	
	if (!ValidateEmail(g('EmFrom').value))
	{
		g('EmFrom').style.backgroundColor='red';
		setTimeout("g('EmFrom').style.backgroundColor='white'",250);
		setTimeout("g('EmFrom').style.backgroundColor='red'",500);
		setTimeout("g('EmFrom').style.backgroundColor='white'",750);
		ok = false;
	}
	if (!ValidateEmail(g('EmTo').value))
	{
		g('EmTo').style.backgroundColor='red';
		setTimeout("g('EmTo').style.backgroundColor='white'",250);
		setTimeout("g('EmTo').style.backgroundColor='red'",500);
		setTimeout("g('EmTo').style.backgroundColor='white'",750);
		ok = false;
	}

	if (ok)
	{
		var house = GetSelectedHouse();
		
		if (house==null)
		{
			Hide('emailpanel');
			Hide('whole');;
			return;
		}
			
		jj = new sack();
		jj.requestFile = 'email.php5';
		jj.setVar('mode','normal');
		jj.setVar('from',g('EmFrom').value);
		jj.setVar('to',g('EmTo').value);
		jj.setVar('link',Encode(house[7]));
		jj.setVar('msg',g('EmMsg').value);
		
		
		jj.onCompletion = function()
		{ 
			jj= null;
			HideItemView();
			if (g_useremail.length==0)
				SignIn(0);
			return;
		};
		jj.runjj();
	
		K2Translate('emailpanel',5,0,10,30);
		setTimeout("Hide('emailpanel');",500);
		setTimeout("Hide('whole');",700);
	}
}

function ContactBOP()
{
	var ok = true;
	
	if (!ValidateEmail(g('EmFrom').value))
	{
		setTimeout("g('EmFrom').style.backgroundColor='red'",50);
		setTimeout("g('EmFrom').style.backgroundColor='white'",250);
		setTimeout("g('EmFrom').style.backgroundColor='red'",500);
		setTimeout("g('EmFrom').style.backgroundColor='white'",750);
		ok = false;
	}

	if (ok)
	{
		jj = new sack();
		jj.requestFile = 'email.php5';
		jj.setVar('mode','normal');
		jj.setVar('doublelink','0');
		jj.setVar('from',g('EmFrom').value);
		jj.setVar('to','kim@housingbymap.com');
		jj.setVar('msg',g('EmMsg').value);
		
		jj.onCompletion = function()
		{ 
			jj= null;
			HideItemView();
			if (g_useremail.length==0)
				SignIn(0);

			return;
		};
		jj.runjj();
		K2Translate('emailpanel',5,0,10,30);
		setTimeout("Hide('emailpanel');",1500);
		setTimeout("Hide('whole');",1700);
	
		
	}
	
}


function SahibineMektup()
{
	
	var ok = true;
	
	if (!ValidateEmail(g('EmFrom').value))
	{
		g('EmFrom').style.backgroundColor='red';
		setTimeout("g('EmFrom').style.backgroundColor='white'",250);
		setTimeout("g('EmFrom').style.backgroundColor='red'",500);
		setTimeout("g('EmFrom').style.backgroundColor='white'",750);
		ok = false;
	}

	if (ok)
	{
		var house = GetSelectedHouse();
		
		if (house==null)
		{
			Hide('emailpanel');
			Hide('whole');;
			return;
		}
			
		jj = new sack();
		jj.requestFile = 'email.php5';
		jj.setVar('mode','normal');
		jj.setVar('from',g('EmFrom').value);
		jj.setVar('to',house[9]);
		jj.setVar('link',Encode(house[7]));
		jj.setVar('msg',g('EmMsg').value);
		
		
		jj.onCompletion = function()
		{ 
			jj= null;
			HideItemView();
			if (g_useremail.length==0)
				SignIn(0);

			return;
		};
		jj.runjj();
	
		K2Translate('emailpanel',5,0,10,30);
		setTimeout("Hide('emailpanel');",500);
		setTimeout("Hide('whole');",700);
	}
}



function IsLoggedIn(func)
{
	jj = new sack();
	jj.requestFile = 'isloggedin.php?email=1';
	jj.onCompletion = function()
	{ 
		if (!jj||!jj.response)
			return;
			
		var results = jj.response.split(",");
		var returnv = false;
		g_useremail = "";
		if (results[0]==0)
		{
			g_useremail = results[1];
			setCookie('email',g_useremail,365);
		};
		login_menuupdate();

		jj= null;
		if (func)
			func(g_useremail);
	};
	jj.runjj();
}

function GetMode()
{
	
	if (IsVisible('descriptionrow'))
	{
		return 1;			
	}
	else if (IsVisible('addressrow'))
	{
		return 2;
	}
	else if (IsVisible('uploadrow'))
	{
		return 3;
	}
	else if (IsVisible('postresultsrow'))
	{
		return 4;
	}
	else
		return 0;	
}

function SetPostMode(m)
{
	if (m>4)	m=4;
		
	if (m<=0)	m=1;
		
	Show('boxtext');	
	g('boxtext').innerHTML = (m==4?' Results...':('Step '+m+'/3')); 
	
	if (m==1)
	{
		ChangeAdMode();
	
		Show('top_row');
		Hide('addressrow');
		Hide('uploadrow');
		Hide('searchbutton');
		Hide('prevbutton');
		Show('descriptionrow');	
		Show('nextbutton');
		Hide('postresultsrow');
		Show('whole');
		setOpacity('SearchBox',100);
	}
	else if (m==2)
	{
		Show('top_row');
		Hide('descriptionrow');
		Hide('uploadrow');
		Hide('searchbutton');
		
		HideAllMenuItems();
		
		Show('addressrow');
		Show('prevbutton');
		Show('nextbutton');
		Hide('postresultsrow');
		Hide('whole');
		setOpacity('SearchBox',75);
		
	}
	else if (m==3)
	{
		Show('top_row');
		Hide('descriptionrow');
		Hide('addressrow');
		Hide('nextbutton');
		
		HideAllMenuItems();

		for(var i=0;i<4;i++)
			g('img'+i+'keep').checked = true;

		document.form1.submit();
		
		Show('prevbutton');
		Show('uploadrow');
		Show('searchbutton');
		Hide('postresultsrow');
		ClearPictValues();
		Show('whole');
		setOpacity('SearchBox',100);
	
	}
	else if (m==4)
	{
		Hide('descriptionrow');
		Hide('addressrow');
		Hide('nextbutton');
		
		HideAllMenuItems();
		
		Hide('prevbutton');
		Hide('uploadrow');
		Hide('searchbutton');
		Show('postresultsrow');
		Hide('top_row');
		Hide('whole');	
	}
}


function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function PostIterate(forw)
{
	var m = GetMode() + forw;
	
	if (m>4)
		m=4;
		
	if ( m<=0 )
		m=1;
		
	if (m==2)
	{
		var price = g('price');
		
		price.value = trim(price.value);
		
		if (price.value.length==0||!IsNumeric(price.value))
		{
			price.style.backgroundColor = 'red';
			setTimeout("g('price').style.backgroundColor = 'white';",750);
			
			g('boxtext').innerHTML = "<span style='color:red;'>Please enter the price..(only numbers)</span>";
			Show('boxtext');
			m=1;
			return;
		}
		var descr = g('housedescr');
		descr.value = trim(descr.value);
				
		if (descr.value.length==0)
		{
			descr.style.backgroundColor = 'red';
			setTimeout("g('housedescr').style.backgroundColor = 'white';",750);
			g('boxtext').innerHTML = "<span style='color:red;'>Please enter some description..</span>";
			Show('boxtext');
			m=1;
			return;
		}
		ClearMap();
		if (g_dmarker)
		{
			map.addOverlay(g_dmarker);
			g_dmarker.show();
			g_dmarker.setPoint(map.getCenter());
			Hide('whole');
			g_bmarker_dragged = false;
		}
		else
			SetDraggableMarker(map.getCenter());
	}
	else
	{
		Show('whole');
	}

		
	if (m==3)
	{
		var addr = g('address').value; 
		if (addr.length==0)
		{
			alert('please enter an address, or city name, and drag the icon');
			m=2;
		}
		else
		{
			if (!g_bmarker_dragged)
				ShowAddressWMarker(addr,false);
			m=3;
		}
	}
	
	SetPostMode(m);
}

function BlinkVis(objname,n,t)
{
	for(var i=0;i<n*2;i++)
	{
		if (i%2==0)
			setTimeout("Show('"+objname+"');",t*i);
		else
			setTimeout("Hide('"+objname+"');",t*i);
	}
}

function OnSubmit12()
{
	var button = g('searchbutton');
	
	if (button.value == 'POST' )
	{
		OnSubmit_();
	}
	else
	{
		ClearMap();
		Search();
	}
		
}




function temptooltip()
{
	showTooltip1(g_dmarker);
	setTimeout('tooltip1.style.visibility="hidden"',2000);
}


function OnSubmit_()
{
	var ad_type = g('ad_type').value;
	jj = new sack();
	jj.requestFile = 'userdata_upload.php';
	jj.setVar('address',g('address').value);
	jj.setVar('descr',g('housedescr').value);
	jj.setVar('sourcepage',g('adid').value);

	if (g('adid').value==-1)
	{
		PostResults("Sorry, there is a problem in transaction... Please try again later!","images/sad.png",false);
		return;
	}
	
	
	if (ad_type==1||ad_type==2)
	{
		jj.setVar('bed',g('bed').value);
		jj.setVar('bath',g('bath').value);
	}
	else if (ad_type==3)
	{
		jj.setVar('bed','1');
		jj.setVar('bath',g('bath2').value);
	}
	else if (ad_type==4)
	{
		jj.setVar('bed','0');
		jj.setVar('bath','0');
	}
	jj.setVar('price',g('price').value);
	jj.setVar('type',ad_type);
	jj.setVar('sourcetype',"bop");
	jj.setVar('tel',g('adtel').value);
	if (g_dmarker!=null)
	{
		jj.setVar('lat',g_dmarker.getPoint().lat());
		jj.setVar('lng',g_dmarker.getPoint().lng());
	}
	else
	{
		g('postmessage').innerHTML = 'There is a problem in transaction. Please try later...';
		Hide('postloadingimg');
		Show('postmessage');
		return false;
	}

	jj.onCompletion = function()
	{
		if (!jj||!jj.response)
			return;
		var r 	= jj.response;
		jj		= null;

		if (r!='0')
			PostResults('There is a problem in transaction. Please try again later...',"images/sad.png",false);
		else
		{
			for(var i=0;i<4;i++)
				g('img'+i+'keep').checked = true;
			
			document.form1.action = 'imgupload.php?commit=1';
			document.form1.submit();
			document.form1.action = 'imgupload.php';
			
			var strAdd = "Congratulations! Your ad has been posted!<br>";
			strAdd += "<br><span style='color:green'>You can now click on the house icon below, and preview your ad!</span>";
			PostResults(strAdd,"images/happy.png",false);
			g_dmarker.hide();
			g_himgs = null;
			ClearPictValues();

			//GotoHouse(g('adid').value,true);			
		}
		
	};
	PostIterate(1);
	jj.runjj();
		
	return true;
}

function LoadIcons()
{
	var CitybaseIcon = new GIcon();
	CitybaseIcon.iconSize=new GSize(12,12);
	CitybaseIcon.iconAnchor=new GPoint(6,6);
	g_icCity   = new GIcon(CitybaseIcon, "images/target12.png", null, "");
		
	var baseIcon = new GIcon();
	baseIcon.iconSize=new GSize(32,32);
	//baseIcon.shadowSize=new GSize(19,14);
	baseIcon.iconAnchor=new GPoint(16,16);
	//g_icHouse   = new GIcon(baseIcon, "images/h1_100s.png", null, "images/h1_100bs.png");
	g_icHouse   = new GIcon(baseIcon, "images/h1_100s.png", null, "");
	//g_icSelHouse = new GIcon(baseIcon, "images/h1_100ssels.png", null, "images/h1_100s.png");
	g_icSelHouse = new GIcon(baseIcon, "images/h1_100sels.png", null, "");
	
	
	var baseIcon2 = new GIcon();
	baseIcon2.iconSize=new GSize(8,8);
	//baseIcon2.shadowSize=new GSize(9,7);
	baseIcon2.iconAnchor=new GPoint(4,4);
	g_icHouse_s = new GIcon(baseIcon2, "images/target8.png", null, "");
	
}

function ClearMap()
{
	map.clearOverlays();
	
	g_selected_marker = null;
	g_houses = new Array();
	g_cities = new Array();
	g_HMarkers = new Array();
	g_CMarkers = new Array();
	if (tooltip1)
		tooltip1.style.visibility="hidden";
	g_CitySkipList = "";
	g_HouseSkipList = "";
	if (g_dmarker)
		g_dmarker.hide();
	g_bmarker_dragged = false;
	jj = null;
	var g_cw=0;
	var g_hw=0;
}


function Search_Response(re)
{
	var houses = re.split('|||');
	
	if (houses[0]!=0)
		return false;

	var ad_type = g('ad_type').value;
	if (houses.length>1)
	{
		for (var i = 1; i < houses.length; i++) 
		{ 
			var houseinfo = houses[i].split('][');
			g_houses[i-1] = houseinfo;
			
			var images = null;
			if (houseinfo[6].indexOf('|',0)!=-1)
				images = houseinfo[6].split('|');
			else if (houseinfo[6].indexOf(',',0)!=-1)
				{images = houseinfo[6].split(',')}
			else if (houseinfo[6].length>0)
				images = Array(houseinfo[6]);			
			
			var point = new GLatLng(houseinfo[3],houseinfo[4]);
			var html = CreateMarkerDiv(houseinfo[0],houseinfo[1],houseinfo[2],houseinfo[5],images!=null?images[0]:null,ad_type);										
			var submarker = null;//new GMarker(point,g_icHouse_s);
			var marker = createMarker(point,html,g_icHouse,submarker);
			marker.hid = i-1; 
			g_HMarkers[i-1]= marker;
			map.addOverlay(marker);
			g_HouseSkipList += Encode(houseinfo[7])+"|";
		}
		var cityid = GetCurrentCityID();
			
		if (i>=150)
		{
			SetHouseTotal((i+"+"),"HOUSES","Can't show all. Zoom in to see more!",true);
		}
		else
			Hide('housetotal');
		//else SetHouseTotal((i-1),"HOUSES","All fit your search criteria!",false);

		
		//setTimeout("BlinkCriteria('#F00');",2000);
	}
	else
	{
		SetHouseTotal('0'," HOUSES","Sorry, no ads fit your search criteria.",false);
	}
		
	g_ovcontrol.show();
}

function BlinkCriteria(color)
{
	var ad_type = g('ad_type').value;
	blinkforColor(4,'ad_type',color,500);
	blinkforColor(4,'bed',color,500);			
	if (ad_type==1)
		blinkforColor(4,'bath',color,500);
	else if (ad_type==3)	
		blinkforColor(4,'bath2',color,500);
	if (ad_type==1)	
	{
		blinkforColor(4,'price_sale_min',color,500);
		blinkforColor(4,'price_sale_max',color,500);
	}
	else if (ad_type==2||ad_type==3)	
	{
		blinkforColor(4,'price_sale_min',color,500);
		blinkforColor(4,'price_sale_max',color,500);
	}
}

function GetAndSetHouseDescription(dec_addr,objname)
{
	jj2 = null;
	jj2 = new sack();
	jj2.requestFile = 'search.php?getdescr=1&src='+Encode(dec_addr);
	jj2.onCompletion = function()
	{
		var re =jj2.response;
		jj2= null;
		var r = re.split('|:|a|');
 
		g(objname).innerHTML =  r[0]+"<br>"+g('gadi').innerHTML+"<br>"+g('gadiimg').innerHTML;
		
		g('iv_tel').innerHTML = "";
		g('iv_addr').innerHTML = "";
		
		if (r.length>=3)
		{
			if (r[1].length >0 )
				g('iv_tel').innerHTML = r[1];
				
			if (r[2].length>0)
				g('iv_addr').innerHTML =  r[2];

			if (r[2].length>60)
				g('iv_addr').style.fontSize = '9px';
			else
				g('iv_addr').style.fontSize = '11px';
		
		
		}
		else
		{
			Hide('iv_line1a');
			Hide('iv_line1b');
		}
		var src = g('ad_source_a').href;
		if (src.lastIndexOf('www.craigslist')!=-1)
			g('ad_source_a').href = src.replace('www',r[3]);
	};
	jj2.runjj(); 
}



function ShowSelectedItemView()
{
	ShowItemView(g_selected_marker,null);
}

function SelectMarkerLL_()
{SelectMarkerLL(g_paramstack[0],g_paramstack[1]);}
function SelectMarkerLL(lat,lng)
{
	for(var i=0;i<g_HMarkers.length;i++)
	{
		var lat2 = g_HMarkers[i].getLatLng().lat();
		var lng2 = g_HMarkers[i].getLatLng().lng();
		if (lat==lat2&&lng==lng2)
		{
			SelectMarker(g_HMarkers[i]);
			return;
		}
	}
}

function AdjustMargins4Search(typet,bedt,batht,pricet)
{
	g('ad_type').value = typet;

	ChangeAdMode();
	
	var options = g('price_sale_max');
		
	if (typet==2||typet==3)
		options = g('price_rent_max');
		
		
	if (pricet>options.value)
	{
		for(var i=options.length-1;i>0;i--)
		{
			if (pricet>options[i].value)
			{
				options.selectedIndex = ((i==options.length-1)?options.length-1:i+1);
				break;
			}
		}
	}

	var options = g('price_sale_min');
		
	if (typet==2||typet==3)
		options = g('price_rent_min');
	
	if (pricet<options.value)
	{
		for(var i=0;i<options.length;i++)
		{
			if (pricet<options[i].value)
			{
				options.selectedIndex = ((i==0)?i:i-1);
				break;
			}
		}
	}

	g('bed').value = bedt;
	g('bath').value = batht;
	
	if (typet==3)
		g('bath2').value = batht;
	
	OnFormChange();
}

function GotoHouse(src,bAbrupt)
{
	jj = new sack();
	jj.requestFile = "search.php?getsummary=1&src="+Encode(src);
	jj.onCompletion = function()
	{ 		
		if (!jj) 
			return;
		if (jj.response.length==0)
		{
			GotoUSA();		
			return;	
		}
	
		var ll = jj.response.split('][');
		jj=null;
		if (ll&&ll[0]!=0)
		{
			g_paramstack = new Array(ll[0],ll[1]);
			OnPostSearch = SelectMarkerLL_;
			if (bAbrupt)
			{
				AdjustMargins4Search(ll[2],ll[3],ll[4],ll[5]);
				ClearMap();
				map.setCenter(new GLatLng(ll[0],ll[1]),g_zoomStreet+1);
				Search();
			}
			else
			{
				AdjustMargins4Search(ll[2],ll[3],ll[4],ll[5]);
				map.panTo(new GLatLng(ll[0],ll[1]));
				UpdateHouses();
			}
		}
		
	};
	jj.runjj();
}
function SetHouseTotal(str1,str2,str3,blink)
{
	if (IsVisible('omap_direction'))
	{
		g('housetotal').style.bottom = '152px';
		g('loadingimg').style.bottom = '150px';
	}
	else
	{
		g('housetotal').style.bottom = '135px';
		g('loadingimg').style.bottom = '133px';
	}

	Show('housetotal');
	g('housetotal').innerHTML = str1+"<span style='font-size:18px'>"+str2+"</span><span style='width:240px;text-align:center;left-margin:auto;display:block;font-size:12px;border:1px black dotted;color:black;background-color:white'>"+str3+"</span>";
	if (blink)
	{
		setTimeout("g('housetotal').style.color = 'red';",300);
		setTimeout("g('housetotal').style.color = 'black';",800);
	}
}

function HideInvisibleMarkers(bSilent)
{
	var SW = map.getBounds().getSouthWest();
	var NE = map.getBounds().getNorthEast();

	minlng = SW.lng();
	maxlng = NE.lng();

	if (minlng>maxlng)
		minlng = -180;

	var vi = 0;
if (map.getZoom()<g_zoomCity)
{		
	for(var i=0;i<g_CMarkers.length;i++)
	{
		var lat = g_CMarkers[i].getLatLng().lat();
		var lng = g_CMarkers[i].getLatLng().lng();
		if (lng<minlng||lng>maxlng||lat<SW.lat()||lat>NE.lat())
		{
			g_CMarkers[i].hide();
		}
		else
		{	
			g_CMarkers[i].show();
			vi++;
		}
	}

	if (!bSilent)
	{
		
		Show('housetotal');
		if (vi>150)
			SetHouseTotal((vi+"+"),(map.getZoom()<g_zoomState)?"States":"Cities","Please zoom in to see smaller cities!",false);
		else
			SetHouseTotal(vi,(map.getZoom()<g_zoomState)?"States":"Cities","visible in the area...",false);
	}	
}
else
{


	for(var i=0;i<g_HMarkers.length;i++)
	{
		var lat = g_HMarkers[i].getLatLng().lat();
		var lng = g_HMarkers[i].getLatLng().lng();
		if (lng<minlng||lng>maxlng||lat<SW.lat()||lat>NE.lat())
			g_HMarkers[i].hide();
		else
		{
			g_HMarkers[i].show();
			vi++;
		}	
	}

	if (!bSilent)
	{
		if (vi>150)
			SetHouseTotal((vi+"+"),'HOUSES',"Can't show all. Zoom in to see more.",true);
		else if (vi==0)
			SetHouseTotal(vi,'HOUSES',"Sorry, no ads fit your search criteria!",true);
		else
			Hide('housetotal');//SetHouseTotal(vi,'HOUSES',"All fit your search criteria!",false);

	}	
}
	
}

function SimilarArea(BB,z)
{
	return false;

	if (!g_lastBox)
		return false;

	var margin = 0.01;
	var similar = ( (Math.abs(BB.getSouthWest().lat()-g_lastBox.getSouthWest().lat())<margin)&&
					(Math.abs(BB.getSouthWest().lng()-g_lastBox.getSouthWest().lng())<margin)&&
					(Math.abs(BB.getNorthEast().lat()-g_lastBox.getNorthEast().lat())<margin)&&
					(Math.abs(BB.getNorthEast().lng()-g_lastBox.getNorthEast().lng())<margin)&&
					(z==g_lastZoom));
	
	return similar;
}


function UpdateHouses()
{
	if (InPostMode())
		return;
	var bounds 	  = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var minprice  = 0;
	var maxprice  = 100000;
	var ad_type   = g('ad_type').value;

	if (SimilarArea(bounds,map.getZoom()))
		return;

	if (g_hw==1)
		return;
	g_hw = 1;


	g_lastBox  = bounds;
	g_lastZoom = map.getZoom();
	Show('loadingimg');

		
	if (ad_type == 1)
	{
		minprice = g('price_sale_min').value;
		maxprice = g('price_sale_max').value;
	}
	if (ad_type >= 2 && ad_type <= 4)
	{
		minprice = g('price_rent_min').value;
		maxprice = g('price_rent_max').value;
	}
	jj = new sack();
	jj.requestFile = 'search.php?limited=1';

	var m = 0;
	
	jj.setVar('minlat',southWest.lat()+m);
	jj.setVar('maxlat',northEast.lat()-m);
	jj.setVar('minlng',southWest.lng()+m);
	jj.setVar('maxlng',northEast.lng()-m);
	jj.setVar('minbed' ,ad_type==4?'0':(ad_type==3?'1':g('bed').value));
	jj.setVar('minbath',ad_type==4?'0':(ad_type==3?g('bath2').value:g('bath').value));
	jj.setVar('minprice',minprice);
	jj.setVar('maxprice',maxprice);
	jj.setVar('type',ad_type);

	if (g_houses.length>g_MaxHouseNumber)
		g_HouseSkipList = "";

	if (g_HouseSkipList.length>0)
		jj.setVar('skiplist',g_HouseSkipList);

	jj.onCompletion = function()
	{
		Hide('loadingimg');	
		if (!jj||!jj.response||InPostMode())
		{
			HideInvisibleMarkers(false);	
			g_hw = 0;
			return;
		}
		var re = Decode(jj.response);
		jj=null;	
		var houses = re.split('|||');
	
		if (houses[0]!=0)
		{
			g_hw = 0;
			return false;
		}

		if (g_HMarkers.length>g_MaxHouseNumber)
			ClearMap();
	
		var ad_type = g('ad_type').value;
		if (houses.length>1)
		{
			var k = g_houses.length;
			for (var i = 1; i < houses.length; i++) 
			{ 
				var houseinfo = houses[i].split('][');
				g_houses[k+i-1] = houseinfo;
				var images = null;
				if (houseinfo[6].indexOf('|',0)!=-1)
					images = houseinfo[6].split('|');
				else if (houseinfo[6].indexOf(',',0)!=-1)
					{images = houseinfo[6].split(',')}
				else if (houseinfo[6].length>0)
					images = Array(houseinfo[6]);

				var point = new GLatLng(houseinfo[3],houseinfo[4]);
				var html = CreateMarkerDiv(houseinfo[0],houseinfo[1],houseinfo[2],houseinfo[5],images!=null?images[0]:null,ad_type);										
				var submarker = null;//new GMarker(point,g_icHouse_s);
				var marker = createMarker(point,html,g_icHouse,submarker);
				marker.hid = k+i-1;
				map.addOverlay(marker);
				g_HMarkers[k+i-1] = marker;
				g_HouseSkipList += Encode(houseinfo[7])+"|"; 
			}
		}
		HideInvisibleMarkers(false);	

		if (OnPostSearch)
		{
			OnPostSearch(g_paramstack);
			OnPostSearch = null;
		}
		g_hw = 0;
	};	
	
	jj.runjj();	
}



function MySearch2String()
{
	var str = '';

	var ad_type = g('ad_type').value;
	var strbed  = (ad_type==3)?'1':g('bed').value;
	var strbath = (ad_type==3)?g('bath2').value:g('bath').value;


	if (ad_type == 1)
	{
		minprice = (g('price_sale_min').value)/1000;
		maxprice = (g('price_sale_max').value)/1000;

		str+= 'For Sale '; 
		str+= strbed +"bed/"+strbath+"bath,";
		str+= minprice +"K - "+ maxprice+"K";
	}
	if (ad_type >= 2 && ad_type <= 3)
	{
		minprice = g('price_rent_min').value;
		maxprice = g('price_rent_max').value;

		str+= ad_type==2?'For Rent, ':'For Roomie, ';
		if (ad_type==2)
			str+= strbed +"bed/"+strbath+"bath,";
		str+= minprice +"-"+ maxprice;
	}
	return str+"  ";
}


function Search()
{
	if (InPostMode())	return;
	if (map.getZoom()<g_zoomCity)
	{
		ClearMap();
		GetCities();
		return;
	}
	if (g_hw==1)
		return;
	g_hw = 1;

	Show('loadingimg');
	
	HideItemView();
	
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var minprice  = 0;
	var maxprice  = 100000;
	var ad_type   = g('ad_type').value;

	g_lastBox  = map.getBounds();
	g_lastZoom = map.getZoom();
		
	map.clearOverlays();
	if (ad_type == 1)
	{
		minprice = g('price_sale_min').value;
		maxprice = g('price_sale_max').value;
	}
	if (ad_type >= 2 && ad_type <= 4)
	{
		minprice = g('price_rent_min').value;
		maxprice = g('price_rent_max').value;
	}
	
	jj = new sack();
	jj.requestFile = 'search.php?limited=1';


	var m = 0;
	
	jj.setVar('minlat',southWest.lat()+m);
	jj.setVar('maxlat',northEast.lat()-m);
	jj.setVar('minlng',southWest.lng()+m);
	jj.setVar('maxlng',northEast.lng()-m);

	jj.setVar('minbed' ,ad_type==4?'0':(ad_type==3?'1':g('bed').value));
	jj.setVar('minbath',ad_type==4?'0':(ad_type==3?g('bath2').value:g('bath').value));
	jj.setVar('minprice',minprice);
	jj.setVar('maxprice',maxprice);
	jj.setVar('type',ad_type);
	
	jj.onCompletion = function()
	{
		Hide('loadingimg');
		if (!jj||!jj.response||InPostMode())
		{
			HideInvisibleMarkers(false);	
			g_hw = 0;
			return;
		}
		var re = jj.response;
		jj=null;
		Search_Response(Decode(re));
		Hide('SearchBox');

		if (OnPostSearch)
		{
			OnPostSearch();
			OnPostSearch = null;
			g_paramstack = null;
		}
		g_hw = 0;
	};
	jj.runjj();
		
	return true;
}

function InPostMode()
{
	return (GetMode()!=4)&&IsVisible('SearchBox')&&g('searchbutton').value=='POST';
}

function Decode(response)
{
	response = response.replace(/\$c/g,".craigslist.org/");
	response = response.replace(/\$h/g,"http://");
	response = response.replace(/\$i/g,"http://images.craigslist.org/");
	response = response.replace(/\$o/g,"http://www.craigslist.org/");
	response = response.replace(/\$b/g,"http://www.housingbymap.com/");
	response = response.replace(/\$u/g,"http://www.housingbymap.com/uploads/");
	response = response.replace(/\$v/g,"http://www.haritadan.com/uploads/");	
	return response;
}

function Encode(response)
{
	response = response.replace("http://www.housingbymap.com/uploads/","$u");
	response = response.replace("http://www.haritadan.com/uploads/","$v");
	response = response.replace("http://www.housingbymap.com/","$b");
	response = response.replace("http://images.craigslist.org/","$i");
	response = response.replace("http://www.craigslist.org/","$o");
	response = response.replace(".craigslist.org/","$c");
	response = response.replace("http://","$h");
	return response;
}


function CreateCityDiv(name,cityimg,level)
{
	if (level>0||cityimg.length==0)
	{
		var html = "<div id='areaname' >AREA_NAME</div>";
		html = html.replace('AREA_NAME',name.toUpperCase());
	}
	else
	{
		var html = "<div id='cityname' >CITY_NAME<br><div style=\"width:240px;height:80px;\"><img src=\"CITY_IMG\" style='text-align:center;width:240px;height:80px'/></div></div>";
		html = html.replace('CITY_NAME',name.toUpperCase());
		html = html.replace('CITY_IMG',cityimg);
	}
	return html;
}

function Cities_Response(re)
{
	var cities = re.split('|||');
	if (cities.length>1)
	{
		g_CitySkipList = "";
		for (var i = 1; i < cities.length; i++) 
		{
			var cityinfo    = cities[i].split('][');
			var CityName = cityinfo[0];
			var point = new GLatLng(cityinfo[1],cityinfo[2]);
			var html = CreateCityDiv(cityinfo[0],cityinfo[3],cityinfo[4]);
			var marker = createCityMarker(point,html,g_icCity,CityName.toUpperCase(),cityinfo[4]);										
			map.addOverlay(marker);
			g_CMarkers[i-1] = marker;
			g_cities[i-1] = cityinfo;
 			g_CitySkipList += cityinfo[5]+"|";
		}

		if (cities.length>0)
		{
			var vi = cities.length-1;

			if (vi>150)
				SetHouseTotal((vi+"+"),(map.getZoom()<g_zoomState)?"States":"Cities","Please zoom in to see smaller cities!",false);
			else
				SetHouseTotal(vi,(map.getZoom()<g_zoomState)?"States":"Cities","visible in the area...",false);
		}
	}
}


function GetCurrentCityID()
{
	for (var i=0;i<g_cities.length;i++)
	{
		if (g_cities[i][1]==g_center_cityll.lat())
			return i;
	}
	return -1;
}

function UpdateCities()
{
	if (InPostMode())
		return;

	var bounds = map.getBounds();
	var SW = bounds.getSouthWest();
	var NE = bounds.getNorthEast();
	
	if (SimilarArea(bounds,map.getZoom()))
		return;

	if (g_cw==1)
		return;
	g_cw = 1;

	
	Show('loadingimg');
	g_lastBox  = bounds;
	g_lastZoom = map.getZoom();

	var str = (g_lastZoom<g_zoomState)?"&l=1":"";
	
	jj = new sack();
	jj.requestFile = "search.php?cities=1"+str;

	var minlng = SW.lng();
	var maxlng = NE.lng();

	if (minlng>maxlng)
		minlng = -180;

	jj.setVar('minlat',SW.lat());
	jj.setVar('maxlat',NE.lat());
	jj.setVar('minlng',minlng);
	jj.setVar('maxlng',maxlng);

	if (g_cities.length>g_MaxCityNumber)
		g_CitySkipList = "";

	if (g_CitySkipList.length>0)
		jj.setVar('skiplist',g_CitySkipList);
	
	jj.onCompletion = function()
	{
		Hide('loadingimg');
		if (!jj||!jj.response||InPostMode())
		{
			g_cw = 0;
			return;
		}

		var re = jj.response;
		jj=null;
		var cities = re.split('|||');
		if (g_cities.length>g_MaxCityNumber)
			ClearMap();

		var k = g_cities.length;
		if (cities.length>1)
		{
			for (var i = 1; i < cities.length; i++) 
			{
				var cityinfo    = cities[i].split('][');
				var CityName = cityinfo[0];
				var point = new GLatLng(cityinfo[1],cityinfo[2]);
				var html = CreateCityDiv(cityinfo[0],cityinfo[3],cityinfo[4]);
				var marker = createCityMarker(point,html,g_icCity,CityName.toUpperCase(),cityinfo[4]);										
				map.addOverlay(marker);
				g_CMarkers[k+i-1] = marker;
				g_cities[k+i-1] = cityinfo;
				g_CitySkipList += cityinfo[5]+"|";
			}
		}
		HideInvisibleMarkers(false);

		if (g_replacemsg.length>0||g_clickHelp<2)
		{
			if (g_replacemsg.length>0)
				GlobalMessage(g_replacemsg,1000);
			else 
			{
				GlobalMessage("Please click on a "+ ((map.getZoom()<g_zoomState)?"state":"city"),1000);
				g_clickHelp++;
			}

			g_replacemsg = "";
		}
		g_cw = 0;
	};
	jj.runjj();	
	return true;
}



function getsec()
{
	var d  = new Date();
	return d.getTime();
}


function GetCities()
{
	if (InPostMode())	
		return;
	if (g_cw==1)
		return;
	g_cw = 1;

	Show('loadingimg');
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	map.clearOverlays();

	g_lastBox  = map.getBounds();
	g_lastZoom = map.getZoom();
	var str = (g_lastZoom<g_zoomState)?"&l=1":"";
	
	jj = new sack();
	jj.requestFile = "search.php?cities=1"+str;

	var minlng = southWest.lng();
	var maxlng = northEast.lng();
	if (minlng>maxlng)
		minlng = -180;

	jj.setVar('minlat',southWest.lat());
	jj.setVar('maxlat',northEast.lat());
	jj.setVar('minlng',minlng);
	jj.setVar('maxlng',maxlng);

	jj.onCompletion = function()
	{
		Hide('loadingimg');
		if (!jj||!jj.response||InPostMode())
		{
			HideInvisibleMarkers(false);	
			return;
			g_cw = 0;			
		}
		var re = jj.response;
		jj=null;
		Cities_Response(re);
		if (g_replacemsg.length>0||g_clickHelp<2)
		{
			if (g_replacemsg.length>0)
				GlobalMessage(g_replacemsg,1000);
			else 
			{
				GlobalMessage("Please click on a "+ ((map.getZoom()<g_zoomState)?"state":"city"),1000);
				g_clickHelp++;
			}

			g_replacemsg = "";
		}
		g_cw = 0;
	};
	jj.runjj();
	
	return true;
}


function PositionMeOnScreen(xp,yp,Box,bcenter)
{
	var myscreen = g('map');
	
	g_scr_width  = myscreen.clientWidth;
	g_scr_height = myscreen.clientHeight;
	
	if (bcenter)
	{
		Box.style.left = (g_scr_width*xp-Box.clientWidth*0.5) + "px" ;
		Box.style.top  = (g_scr_height*yp-Box.clientHeight*0.5) + "px";
	}
	else
	{
		Box.style.left = g_scr_width*xp + "px" ;
		Box.style.top  = g_scr_height*yp + "px";
	}
}
function SetMyHeight(yp,Box)
{
	var scr_height 		= g('map').clientHeight;

	Box.style.height 	= scr_height*yp + "px" ;	
	return true;
}
function SetMyWidth(xp,Box)
{
	var scr_width  		= g('map').clientWidth;
	
	Box.style.width 	= scr_width*xp + "px" ;	
	return true;
}

function CenterMeOnScreen(Box)
{
	var myscreen = g('map');
		
	var scr_width  = myscreen.clientWidth;
	var scr_height = myscreen.clientHeight;

	Box.style.left = (scr_width-Box.clientWidth)/2 + "px" ;
	Box.style.top  = (scr_height-Box.clientHeight)/2 + "px";
	
	return true;
}

function ForcedGotoBox()
{
	var myscreen = g('whole');
	var fgoto    = g('ForcedGoTo');
	
	myscreen.style.display = 'inline';
	myscreen.style.visibility = "visible";
	fgoto.style.display = 'inline';
	fgoto.style.visibility = "visible";
	
	CenterMeOnScreen(fgoto);
	
	if (navigator.appName=="Microsoft Internet Explorer") 
	{
		g('forcedgotobutton').style.fontSize = '16px';
		fgoto.style.visibility = 'hidden';
		g('forcedgototext').style.visibility = 'visible';
		g('forcedgotobutton').style.visibility = 'visible';
	}
	
	g("forcedgototext").focus();
	g("forcedgototext").select();
}

function ForcedGoto_Submit()
{
	Hide('whole');
	Hide('ForcedGoTo');
	
	showAddress(g('forcedgototext').value,g_zoomStreet-2,function () { Search();OnSearch();} );
	
	
}

function executeZoomScript()
{
	g('zoomingTextContainer').style.display = 'inline';
	g('zoomingTextContainer').style.visibility = "visible";
	g('whole').style.display = 'none';
	var obj = g('zoomingText');
	if(textIndex<textArray.length)
	{
		
		obj.style.fontSize = '1px';
		obj.style.lineHeight = document.body.clientHeight + 'px';
		obj.innerHTML = textArray[textIndex] ;
		zoomText();	
	}
	else
	{
		setTimeout("Hide('zoomingTextContainer');GotoUSA();",delayAtEnd);
		setCookie('intro_done','1',365);
	}
}
	
function zoomText()
{
	var obj = g('zoomingText');
	var fontSize = obj.style.fontSize.replace('px','');
	fontSize = fontSize/1 + fontIncrementBy;
	obj.style.fontSize = fontSize + 'px';
	if(fontSize<maxFontSize)
	{
		setTimeout('zoomText()',zoomSpeed);
	}else
	{
		textIndex++;
		setTimeout('executeZoomScript();',delayBetweenWords[textIndex-1]);
	} 	
	
}
function button_onmouseover(elem,val)
{
	if (val)
	{
		elem.style.color = "white";
		elem.style.backgroundColor = "black";
	}
	else
	{
		elem.style.color = "white";
		elem.style.backgroundColor = "red";
	}
	return false;
}

function ShowTD(objname)
{
	g(objname).style.visibility = "visible";
	g(objname).style.display    = navigator.appName=="Netscape"?"table-row":"inline";
}

var num=1;
function SignIn(signin)
{
	var LBox  = g('loginBox2');
	Show('loginBox2');
	Show('whole');
	if (signin)
	{
		Hide('verifypass_row');
		Show('signuptext');
		Show('passwordhelp');
		Hide('signup_back');
		Hide('captcha_row');
	}
	else
	{
		var erow  = g('email_row');
		var vprow = g('verifypass_row');
		ShowTD('verifypass_row');
		Hide('signuptext');
		Hide('passwordhelp');
		Show('signup_back');
		ShowTD('captcha_row');
	}
	
	var p_email = getCookie('email');
	if (p_email.length >0)
		g('lbemail').value = p_email;
		
	HideItemView();
	g('signbutton').value = signin?"Sign In":"Sign Up";
	g('lbmessage').innerHTML = "";
	CenterMeOnScreen(LBox);
	return false;
}

function HideAllMenuItems()
{
	Hide('ad_type');
	Hide('price_rent_min');
	Hide('price_rent_max');
	Hide('price_sale_min');
	Hide('price_sale_max');
	Hide('bath');
	Hide('bath2');
	Hide('bed');
	Hide('enter_price');
}


function ChangeAdMode()
{
	var button = g('searchbutton');
	var post = (button.value =='POST');
 	var mode = g('ad_type').value;
 	
 	Show('ad_type');
 	
	if (mode == 1) 
	{
		Hide('price_rent_min');
		Hide('price_rent_max');
		if (post)
		{
			Hide('price_sale_min');
			Hide('price_sale_max');
		}
		else
		{
			Show('price_sale_min');
			Show('price_sale_max');
		}
		
		Show('bath');
		Hide('bath2');
		Show('bed');
	}
	else if (mode == 2) 
	{
		Hide('price_sale_min');
		Hide('price_sale_max');
		if (post)
		{
			Hide('price_rent_min');
			Hide('price_rent_max');
		}
		else
		{
			Show('price_rent_min');
			Show('price_rent_max');
		}
		Show('bath');
		Hide('bath2');
		Show('bed');
	}
	else if (mode == 3)
	{
		Hide('price_sale_min');
		Hide('price_sale_max');
		
		if (post)
		{
			Hide('price_rent_min');
			Hide('price_rent_max');
		}
		else
		{
			Show('price_rent_min');
			Show('price_rent_max');
		}
		
		Hide('bath');
		Show('bath2');
		Hide('bed');
	}
	
	if (post)
	{
		Show('enter_price');
	}
	else
	{
		Hide('enter_price');
	}
}


function IsVisible(objname)
{
	var obj = g(objname); 
	return 	obj && (obj.style.display!='none') && (obj.style.visibility !='hidden');
}

function Show(objname)
{
	if (g(objname)==null)
		return;
	
	g(objname).style.display    	= 'inline';
	g(objname).style.visibility 	= 'visible';
}


function Hide(objname)
{
	var obj = g(objname);
	if (obj==null)
		return;
	obj.style.display   	= 'none';
	obj.style.visibility 	= 'hidden';
}

function changeme(image)
{
	image.src="captcha.php?"+ (num++);
	return false;
}

function CreateMarkerDiv(bed,bath,price,descr,img,type)
{
	var html = "<div class=\"popup1\" id=\"markertext\" style=\"width:120px;height:105px\" ><div style=\"width:120px;height:90px;text-align:center\" ><img src=\"IMG_VAL\" alt=\"\" id=\"popupimg\" style=\"width:118px;height:88px;border: 1px white solid;\"/></div><div style=\"display:block;background-color:#F00;color:#FFF;text-align:center;left-margin:auto;right-margin:auto;width:120px;font-size:10px;height:15px;\" id=\"pv_line1\">$PRICE_VAL[[A]]BED_VAL[[B]]BATH_VAL[[C]]<br></div><span style='display:none;visibility:hidden;height:0px;width:0px;'></span></div>";

	
	if (type==1)
	{
		html = html.replace("PRICE_VAL",(price/1000.0).toFixed(1));
		html = html.replace("[[A]]","K|");
	}
	else
	{
		html = html.replace("PRICE_VAL",price);
		html = html.replace("[[A]]",type==4?"":"|");
	}
	
	if (type==4)
	{
		html = html.replace("BED_VAL","");
		html = html.replace("BATH_VAL","");
		html = html.replace("[[B]]","");
		html = html.replace("[[C]]","");
		
	}
	else if (type==3)
	{
		html = html.replace("BED_VAL","");
		html = html.replace("BATH_VAL",bath==1?"w/pri ":"w/sha ");
		html = html.replace("[[B]]","");
		html = html.replace("[[C]]","bath");
	}
	else
	{
		html = html.replace("BED_VAL",bed);
		html = html.replace("BATH_VAL",bath);
		html = html.replace("[[B]]","bed|");
		html = html.replace("[[C]]","bath");
	}
	
	html = html.replace("IMG_VAL",img==null?"images/noimage.gif":img);
	html = html.replace("DESCR_VAL",descr);
	return html;
}


function GetSelectedHouse()
{
	if (g_selected_marker)
		return g_houses[g_selected_marker.hid];
	return null;
}

function CreateThumbnailDiv(template,house)
{
	var html  = template;
	var bed   = house[2];
	var bath  = house[3];
	var price = house[4];
	var img   = house[6].length>0?g_himgs[0]:null;
	var type  = house[1];
	
	if (type==1)
	{
		html = html.replace("PRICE_VAL",(price/1000.0).toFixed(1));
		html = html.replace("[[A]]","K|");
	}
	else
	{
		html = html.replace("PRICE_VAL",price);
		html = html.replace("[[A]]",type==4?"":"|");
	}
	
	if (type==4)
	{
		html = html.replace("BED_VAL","");
		html = html.replace("BATH_VAL","");
		html = html.replace("[[B]]","");
		html = html.replace("[[C]]","");
		
	}
	else if (type==3)
	{
		html = html.replace("BED_VAL","");
		html = html.replace("BATH_VAL",bath==1?"w/pri ":"w/sha ");
		html = html.replace("[[B]]","");
		html = html.replace("[[C]]","bath");
	}
	else
	{
		html = html.replace("BED_VAL",bed);
		html = html.replace("BATH_VAL",bath);
		html = html.replace("[[B]]","bed|");
		html = html.replace("[[C]]","bath");
	}
	
	html = html.replace("IMG_VAL",img==null?"http://www.housingbymap.com/images/noimage.gif":img);
	return html;
}

function ShowItemView(marker,func)
{
	var id = marker.hid;

	if (!g_marquee_ads)	
		PutAds();
		
	
	if (id!=-1)
	{
		var IVImg    = g('itemviewimg');
		
		g('ad_source_a').href = g_houses[id][7];
			
		if  (g_houses[id][5].length>0)
		{
			g('iv_line2').innerHTML = g_houses[id][5]+ "<br>"+ g('gadi').innerHTML;
			g('iv_tel').innerHTML = g_houses[id][10];
			g('iv_addr').innerHTML = g_houses[id][11];
		}
		else
			GetAndSetHouseDescription( g_houses[id][7],'iv_line2');

		

		g_himgs = null;
		var housetext = g_houses[id][6];
		if (housetext.indexOf('|')!=-1)
		{
			g_himgs = housetext.split('|');
		}
		else if (housetext.indexOf(',',0)!=-1)
		{
			g_himgs = housetext.split(',');	
		}
		else
		{
			if (housetext.length>0)
				g_himgs = new Array(housetext);	
			else
				g_himgs = new Array();
		}
		
		IVImg.src    = g('popupimg').src;
		g('iv_line1').innerHTML = g('pv_line1').innerHTML;
		
		g('imgnumber').innerHTML = '1/'+g_himgs.length;
		g('imgnumber_s').innerHTML = '1/'+g_himgs.length;

		if (g_houses[id][8] =='bop')
			Hide('ad_source_a');
		else
			Show('ad_source_a');
		
		var data_str = 	"data by "
						+((g_houses[id][8] =='cl') ? "craigslist.org" : "housingbymap.com");

		g('iv_source').innerHTML = data_str;
		
			
		Show('itemview');
		
		var myscreen = g('map');
		var scr_width  = myscreen.clientWidth;
		var scr_height = myscreen.clientHeight;
	
		
		var startx = 4;
		var height = 296;
		var starty = parseInt(scr_height-296)/2;		

		//ItemView.style.left = startx + 'px';
		//ItemView.style.top  = starty+ 'px';
		
		//ItemView.style.height  = height+ 'px';;
		//ItemView.style.width   = '322px';
		
		var lp = g('leftpanel');
		lp.style.top    = (starty-35)+ 'px';
		lp.style.height = (height)+ 'px';
		
		if (getX(lp)<-20)
			MoveLeftPanel('leftpanel',true);
	}
}

function MoveLeftPanel(objname,open)
{
	var iter = 5;
	var o = g(objname);
	var wi = Math.round(getW(o)/iter);
	if (open)
	{
		var x1 = -(getW(o));
	
		for(var i=1;i<=iter;i++)
		{
			var cmd = "g('"+objname+"').style.left  = '"+(x1+wi*i)+"px';";
			setTimeout(cmd,i*50);
		}
	}
	else
	{
		var x1 = 0;
	
		for(var i=1;i<=iter;i++)
		{
			var cmd = "g('"+objname+"').style.left  = '"+(x1-wi*i)+"px';";
			setTimeout(cmd,i*50);
		}

	}
}


function PutAds()
{
	g('tm1').innerHTML = g('gadwt').innerHTML;
	g('tm2').innerHTML = g('gadwt2').innerHTML;
	g('tm3').innerHTML = g('gadwt').innerHTML;
	g('tm4').innerHTML = g('gadwt2').innerHTML;	
	g('tm5').innerHTML = g('gadwt').innerHTML;
	g('tm6').innerHTML = g('gadwt2').innerHTML;

	g_marquee_ads = true;
}

function AddMarkerTip(marker,html)
{
	marker.tooltip1 = html;
	GEvent.addListener(marker,"mouseover", function() {
		  showTooltip1(marker);
		});    
	GEvent.addListener(marker,"click", function() {
		  ShowItemView(marker,null);
		  tooltip1.style.visibility="hidden";
		});
	GEvent.addListener(marker,"click", function() 
	{
		  ShowItemView(marker,null);
		  tooltip1.style.visibility="hidden";
		});  
	GEvent.addListener(marker,"mouseout", function() {
		tooltip1.style.visibility="hidden";
		});  
}

function SetDraggableMarker(point)
{
	if (!g_dmarker)
	{
		g_dmarker = new GMarker(point, {draggable: true});
		
		GEvent.addListener(g_dmarker, "dragstart", function() 
		{
		  map.closeInfoWindow();
		  g_bmarker_dragged = true;
		  });
		GEvent.addListener(g_dmarker, "dragend", function() 
		{
		  map.panTo(g_dmarker.getPoint());
		  g_bmarker_dragged = true;
		  });
		  
		map.addOverlay(g_dmarker);
		g_dmarker.show();
	}
	g_dmarker.setPoint(point);
	g_dmarker.show();
	map.setCenter(point,g_zoomStreet);
	g_bmarker_dragged = false;
	
	return g_dmarker;
	
}

function ShowAddressWMarker(address,silent)
{
	geocoder.getLatLng(
		address,
		function(point) 
		{
		  if (!point&&!silent) 
		  	alert(address + " not found");
		  if (point)
		   	SetDraggableMarker(point)
		}
	  );

}

function LoginBox_SetText(str)
{
	var mbox  = g('lbmessage');
	mbox.innerHTML = str;
}


function Search2Post(ispost)
{
	var Box 	= g('SearchBox');
	var Button 	= g('searchbutton');
	
	Show('SearchBox');	
	if (ispost)
	{		
		Button.value = 'POST';
		g('SearchBoxTitle').innerHTML = ' POST ADS';
		g('SearchBox').style.height = 'auto';
		g('SearchBox').style.left = (g_scr_width-600)/2+'px';
					
		ChangeAdMode();
		SetPostMode(1);
		g('postmessage_img').src="images/ajax-loader.gif";
		g('postmessage').innerHTML = "Processing";
		g('okbutton').style.visibility = 'hidden';
		if (g_dmarker)
		{
			g_dmarker.hide();
			g_bmarker_dragged = false;
		}
	}
	else
	{
		g('SearchBox').style.height = '80px';
		var pos = getT(g('SearchBox'));
		if (pos[0]<330)
			g('SearchBox').style.left = '330px';
		
		Show('top_row');
		Hide('addressrow');
		Hide('uploadrow');
		Show('searchbutton');
		Hide('prevbutton');
		Hide('descriptionrow');	
		Hide('nextbutton');
		Hide('postresultsrow');
		Hide('boxtext');
		Button.value 		= 	'SEARCH';
		g('SearchBoxTitle').innerHTML = '  SEARCH';
		ChangeAdMode();
		Show('SearchBox');
	}
}
function OnSearch()
{
	Search2Post(0);
}
function emailcheckw(box,email)
{
	var result = emailCheck(email);
	
	if (!result)
		box.style.backgroundColor = 'red';
}


function emailCheck (str) 
{
	 return (str.indexOf(".") > 2) && (str.indexOf("@") > 0); 
}



function OnCaptchaValidResponse()
{
	/*var xml = GXml.parse(data);
	var markers = xml.documentElement.getElementsByTagName("marker");*/
}

function captchaCheckw(box,str)
{
	jj = new sack();
	jj.requestFile = 'is_captcha_valid.php';
	jj.setVar('key',str);
	jj.onCompletion = function(){ OnCaptchaValidResponse();  jj= null;};
	jj.runjj();
}

function Logout_response()
{
}

function OnLogout()
{
	g_useremail = "";
	
	//if (jj==null)
		jj = new sack();
	jj.requestFile = 'logout.php';
	jj.onCompletion = function(){ Logout_response(); jj= null;};
	jj.runjj();
	
	login_menuupdate();
}



function login_response()
{
	var messagebox = g('lbmessage');
	g_useremail = "";
	login_menuupdate();
	
	if (jj.response ==0)
	{
		Hide('loginBox2');
		g_useremail = g('lbemail').value;
		login_menuupdate();
	}
	else
	{
		var eo = g('lbemail');
		var po = g('lbpassword');
		eo.style.backgroundColor = 'red';
		po.style.backgroundColor = 'red';
		
		messagebox.innerHTML = "Wrong username and/or password...";
	}
}
function signup_response()
{
	var messagebox = g('lbmessage');
	g_useremail = "";
	login_menuupdate();
	
	if (jj.response==2)
	{
		messagebox.innerHTML = "retry entering the text in the image";
		var io = g('captchaimage');
		var to = g('captchatext');
		to.style.backgroundColor = 'red';
		io.style.border='2px yellow solid';
		changeme(io);
	}
	else if (jj.response==3)
	{
		messagebox.innerHTML = "The email address is already in use. Please use a different one...";
		var eo = g('lbemail');
		eo.style.backgroundColor = 'red';
	}
	else if (jj.response==0)
	{
		messagebox.innerHTML = "Please checkout your email for final confirmation!";
		setCookie('email',g('lbemail').value,365);
		setTimeout("Hide('loginBox2')",5000);
		login_menuupdate();
	}
	else if (jj.response==1)
	{
		messagebox.innerHTML = "There are system problems. Please <a href='mailto:help@housingbymap.com'>Report</a> ...";
		g_useremail = g('lbemail').value;
		login_menuupdate();
	}
}



function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
   { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
      {
         IsNumber = false;
      }
   }
   return IsNumber;
}





function ValidateEmail(str) 
{

	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	
	if (str.indexOf(at)==-1)
	   return false;

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	   return false;
	
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
		return false;
	
	 if (str.indexOf(at,(lat+1))!=-1)
		return false;
	
	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
		return false;
	
	 if (str.indexOf(dot,(lat+2))==-1)
		return false;
	
	 if (str.indexOf(" ")!=-1)
		return false;
	
	 return true;			
}

function CheckEmailBox(email,message)
{
	if ((email.value==null)||(email.value==""))
	{
		message.innerHTML = 'Email address is required...';
		email.style.backgroundColor = 'red';
		return false;
	}
	if (ValidateEmail(email.value)==false)
	{
		message.innerHTML = 'Please enter valid email...';
		email.style.backgroundColor = 'red';
		return false;
	}
	return true;
}
function CheckPasswords(pass1,pass2,mbox,mode)
{
	if ((pass1.value==null)||(pass1.value==""))
	{
		mbox.innerHTML = 'Empty password is not allowed...';
		pass1.style.backgroundColor = 'red';
		return false;
	}
	
	if( mode == 'Sign Up')
	{
		if ((pass2.value==null)||(pass2.value==""))
		{
			mbox.innerHTML = 'Empty password is not allowed...';
			pass2.style.backgroundColor = 'red';
			return false;
		}
		
		if ((pass1.value != pass2.value))
		{
			mbox.innerHTML = 'Please make sure passwords are the same...';
			pass1.style.backgroundColor = 'red';
			pass2.style.backgroundColor = 'red';
			return false;
		}
	}
	mbox.innerHTML = "";
	return true;
}

function CheckPasswords_()
{
	var pass1 = g('lbpassword');
	var pass2 = g('lbpassword2');
	var mbox  = g('lbmessage');
	var button = g('signbutton');
	
	return CheckPasswords(pass1,pass2,mbox,button.value);
}

function CheckEmail_()
{
	var email = g('lbemail');
	var mbox  = g('lbmessage');
	
	return CheckEmailBox(email,mbox);
}

function CheckLoginInput()
{
	return CheckEmail_()&&CheckPasswords_();
}

function SendPassword()
{
	if (CheckEmail_()&&
		confirm('Do you want me to email you your password?'))
	{
		g('lbmessage').innerHTML = '';
		jj = new sack();
		jj.requestFile = 'resetpwd.php?resend=1';
		jj.setVar('email',g('lbemail').value);
		jj.onCompletion = function()
		{ 
			if (jj.response==0)
				g('lbmessage').innerHTML = "Your password has been sent! Please check your email!";
			else
				g('lbmessage').innerHTML = "Your email is not in our system.";
			setTimeout("Hide('whole');Hide('loginBox2');",3000);
			jj= null;
			Hide('loginimg'); 
		};
		Show('loginimg');
		g('loginimg').src = "images/ajax-loader.gif";
		jj.runjj();
	}
	else
		Show('lbmessage');
}


function ResetPassword()
{
	if (confirm('Do you really want to reset your password?  If you do , you need to sign up again with the same email!'))
	{
		if (CheckEmail_())
		{
			jj = new sack();
			jj.requestFile = 'resetpwd.php';
			jj.setVar('email',g('lbemail').value);
			jj.onCompletion = function()
			{ 
				if (jj.response==0)
					g('lbmessage').innerHTML = "Please check your email!";
				else
					g('lbmessage').innerHTML = "Your email is not in our system.";
				setTimeout("Hide('whole');Hide('loginBox2');",3000);
				jj= null;
				Hide('loginimg'); 
			};
			Show('loginimg');
			g('loginimg').src = "images/ajax-loader.gif";
			jj.runjj();
		}
		else
			Show('lbmessage');
	}
}

function Login12()
{
	var button = g('signbutton');
	
	if (CheckLoginInput())
	{
		if (button.value=='Sign In')
		{
			//if (jj==null)
			jj = new sack();
			jj.requestFile = 'userlogin.php';
			jj.setVar('email',g('lbemail').value);
			jj.setVar('password',g('lbpassword').value);
			jj.onCompletion = function()
			{ 
				login_response();  
				Hide('whole');
				jj= null; 
				Hide('loginimg');
				if (g_bSwitch2PostAd)
				{
					g_bSwitch2PostAd = false;
					UpdateUserData(ShowPrePostMenu);
				}
			};
			Show('loginimg');
			g('loginimg').src = "images/ajax-loader.gif";
			jj.runjj();
		}
		else if (button.value == 'Sign Up')
		{	
			//if (jj==null)
				jj = new sack();
				
			jj.requestFile = 'usersignup.php';
			jj.setVar('email',g('lbemail').value);
			jj.setVar('password',g('lbpassword').value);
			jj.setVar('captchatext',g('captchatext').value);
			jj.onCompletion = function(){ signup_response();  Hide('whole'); Hide('loginimg');jj= null; };
			jj.runjj();
			Show('loginimg');
			g('loginimg').src = "images/ajax-loader.gif";
		}
	}
	setCookie('email',g('lbemail').value,365);

	return false;
}

function OnAbout()
{
	HideItemView();
	g('zoomingTextContainer').style.display = 'inline';
	g('zoomingTextContainer').style.visibility = "visible";
	g('whole').style.display = 'none';
	var obj = g('zoomingText');
	textArray = ['MindTech,LLC  2007-2008(c)'];
	textIndex=0;
	if(textIndex<textArray.length)
	{
		
		obj.style.fontSize = '1px';
		obj.style.lineHeight = document.body.clientHeight + 'px';
		obj.innerHTML = textArray[textIndex] ;
		zoomText();	
	}
	else
	{
		setTimeout("Hide('zoomingTextContainer')",delayAtEnd);
	}
}
function ShowFile(file) 
{
	Show('screen2');
	Show('whole');
	//if (jj==null)
		jj = new sack();
				
	jj.requestFile = file;
	jj.onCompletion = function(){ g('screen2text').innerHTML = jj.response; jj= null; };
	jj.runjj();
}


function OnTermsofuse()
{
	ShowFile('termsofuse.php');
}

function GetExt(path)
{
	var dot = path.lastIndexOf(".");
	if (dot>0)
		return (path.substring(dot+1)).toLowerCase();
	else
		return "";
}

function CheckFormat(ext)
{
	return (ext=='jpeg'||
			ext=='jpg'||
			ext=='gif'||
			ext=='png');
}

function CheckImgPath(path)
{
	if (path.length==0)
		return 2;
	
	var ext = GetExt(path);
	if (CheckFormat(ext))
		return 0;
	else
		return 1;
}
function UpdatePS(objname,val)
{
	if (val==0)
	{
		g(objname).innerHTML = "  OK!";
		g(objname).style.color = 'green';
	}
	else if (val==1)
	{
		g(objname).innerHTML = "[X]Check Format!";
		g(objname).style.color = 'red';
	}
	else if (val==2)
	{
		g(objname).innerHTML = "Empty!";
		g(objname).style.color = 'red';
	}
}

function lg(str){GLog.write(str);}

function AdType(i)
{
	if (i==1)
		return 'For Sale';
	else if (i==2)
		return 'For Rent';
	else if (i==3)
		return 'Roommate Search';
		
	return '';
}

function ClearList(listobj)
{
	listobj.options.length = 0;
}

function UpdateAdList()
{
	var list = g('adlist');

	ClearList(list);
	
	if (g_userads.length > 0 )
	{
		for(var i=0;i<g_userads.length;i++)
		{
			
			var text = 'Ad #'+(i+1)+' : '+ AdType(g_userads[i][0]) +' - $'+g_userads[i][3]+' - '+ g_userads[i][1] + '/' + g_userads[i][2];
			var opt = new Option(text,i);
			list.options[i] = opt;
		}
	}
	login_menuupdate();
}


function ShowPrePostMenu()
{
	g_usereditad = -1;
	
	Hide('SearchBox');
	
	if (g_userads.length > 0 )
	{
		Show('myadbox');
		g('myadbox').style.left = (g_scr_width-600)/2+'px';
		Show('whole');
	}
	else
		OnNewAd();
}
function SetAdId()
{
	jj = new sack();
	jj.requestFile = 'userdata_upload.php?getid=1';
	jj.onCompletion = function()
	{ 
		if (!jj||!jj.response)
			return;
		var r= jj.response;
		jj=null;
		g('adid').value = r;
	};
	jj.runjj();
}


function UpdateUserData(func)
{
	jj = new sack();
	jj.requestFile = 'userdata_download.php';
	jj.onCompletion = function()
	{ 
		if (!jj||!jj.response)
			return;
		var res= Decode(jj.response);
		jj=null;
		var r = res.split('|||');
		g_userads = new Array();
	
		for (var i=1;i<r.length;i++)
			g_userads[i-1] = r[i].split('][');
		
		UpdateAdList();
		
		if (func) 
			func();
	};
	jj.runjj();
}


function ShowAdsIfLoggedIn(email)
{
	if (email=="")
	{
		SignIn(1);
		g_bSwitch2PostAd = true;
		LoginBox_SetText('Please login or signup in order to post an ad...');
	}
	else
	{
		UpdateUserData(ShowPrePostMenu);
	}
}



function OnMyAds()
{IsLoggedIn(ShowAdsIfLoggedIn);}


var g_imgslots = new Array();




function ShowImgAtSlot(i,show)
{

	if (show)
	{
		Show('img'+i+'sel');
		g('img'+i+'keep').checked = true;
		Hide('pict'+i);
		var url = 'imgupload.php?getimg='+(g('adid').value*100+i)+'&r='+Math.round((Math.random()*9999999)+1);
		g('uiprevimg'+i).src = url; 
		g('uiprevimg'+i).style.height = '108px';		   
	}
	else
	{
		g('uiprevimg'+i).src = "images/ajax-loader.gif";
		g('img'+i+'change').checked = true;
		Hide('uiprevimg'+i);
		Hide('img'+i+'sel');
		Show('pict'+i);
		g('uiprevimg'+i).style.height = '20px';
	}
}

function OnImgDelete(i)
{
	var r = confirm('Do you really want to delete this image?');
	if (r)
		OnImgChange_Submit(i);
	else
	{
		g('img'+i+'keep').checked = true;
	}
}


function OnImgUpload(i)
{ 
	var r = CheckImgPath(g(('pict'+i)).value);
	UpdatePS(('p'+i+'s'),r); 
	if (r==0)
		OnImgChange_Submit(i);
}

function OnImgChange_Submit(i)
{
	g('uiprevimg'+i).src = "images/ajax-loader.gif";
	Show('uiprevimg'+i);
	g('uiprevimg'+i).style.height = '20px';
	document.form1.submit();
	
}

function OnHiddenIframeLoad()
{
	var iH = window["hiddeniframe"].document.body.innerHTML;

	if (iH.length==0)
		return;
		
	if (iH.length>4&&iH.charAt(4)=='c')
		GotoHouse(g('adid').value,true);
	else
	{
		for(var i=0;i<4;i++)
			ShowImgAtSlot(i,(iH.charAt(i)==1));
	}
}


function FillInAdForm(i)
{
	if (!g_userads||g_userads.length<i)
		return;
		
	g_usereditad = i;
		
	var r = g_userads[i];
	
	g('ad_type').value		 	= r[0];
	g('bed').value 				= r[1];
	g('bath').value 			= r[2];
	g('price').value 			= r[3];
	g('address').value 			= r[4];
	g('housedescr').value		= r[7];
	g('adid').value				= r[9];
	g('adtel').value			= r[10];

	var latlng = new GLatLng(r[5],r[6]);
	SetDraggableMarker(latlng);
	geocoder.getLatLng(
	r[4],
	function(point) 
	{
	  g_bmarker_dragged = (point.lat()!=r[5]);
	}
  	);

	if (r[8].length>0)
		g_himgs = r[8].split(',');
	else
		g_himgs = null;
		
	ClearPictValues();
}

function ClearPictValues()
{
	g('pict0').value = "";
	g('pict1').value = "";
	g('pict2').value = "";
	g('pict3').value = "";
	
	g('p0s').innerHTML = "";
	g('p1s').innerHTML = "";
	g('p2s').innerHTML = "";
	g('p3s').innerHTML = "";
}


function OnNewAd()
{
	g_userads = null;
	g_himgs = null;
	ClearPictValues();
	ClearMap();
	SetAdId(); 
	Hide('myadbox');
	Search2Post(1);
}

function PostResults(text,img,hideok)
{
	Search2Post(1);
	SetPostMode(4);
	g('postmessage').innerHTML = text;
	g('postmessage_img').src = img;
	g('okbutton').style.visibility = hideok?'hidden':'visible';
	Hide('myadbox');
}

function OnDeleteAd()
{
	if (!g_userads)
		return;
		
	if (confirm('Do you really want to delete this ad?'))
	{
		var i = g('adlist').selectedIndex;
		
		jj = new sack();
		jj.requestFile = 'userdata_delete.php';
		jj.setVar('sourcepage',g_userads[i][9]);
		jj.onCompletion = function()
		{ 
			var r= jj.response;
			jj=null;
			PostResults('Deleted requested record...',"images/happy.png",false);
			ClearMap();
			OnMapMove();
		};
		PostResults('Processing...','images/ajax-loader.gif',true);
		jj.runjj();
		g('deladbutton').value=="DELETE";
	}
}

function OnEditAd()
{
	FillInAdForm(g('adlist').selectedIndex);
	Hide('myadbox');
	Search2Post(1);
	ClearMap();
}

function HideItemView()
{
	if (getX(g('leftpanel'))>-10)
	{
		OnClick(g('iv_ovb'));
		MoveLeftPanel('leftpanel',false);
	}
}

function ShowTB(show)
{
	if (show)
	{
		Show('mainContent');
		if (!IsIE())
		{
			dhtmlgoodies_marqueeObj.style.top = '27px';
			dhtmlgoodies_marqueeObj.style.right = '0px';
		}

	}
	else
	{
		Hide('mainContent');
		if (!IsIE())
		{
			dhtmlgoodies_marqueeObj.style.top = '0px';
			dhtmlgoodies_marqueeObj.style.right = '150px';
		}
	}
}


function OnHideTB(event)
{
	if (event.clientY<50)
	{
		ShowTB(true);
		g_tbt1 = getsec()+4000;
	}
	else
	{		
		var t = getsec();
		if (t>g_tbt1&&g_tbt1!=0)
		{
			ShowTB(false);
			g_tbt1 = 0;
		}		
	}
}


function OnMouseDown(event)
{
	g_lastPt[0] = event.clientX;
	g_lastPt[1] = event.clientY;
	g_MovingObj = event.target;
	g_lastMs = 1;
}
function OnMouseUp(event)
{
	g_lastPt[0] = event.clientX;
	g_lastPt[1] = event.clientY;
	g_MovingObj = null;
	g_lastMs = 0;
}

function OnMouseMove(event)
{
	if (g_MovingObj!=null)
	{
		if (g_MovingObj.id=='SearchBox'||
			g_MovingObj.parentNode.id=='SearchBox'||
			g_MovingObj.parentNode.parentNode.id=='SearchBox')
			MovingBox_OnMM(g('SearchBox'),event);
	}
	
	if(g_set[0]==1)
		OnHideTB(event);
		
	g_lastPt[0] = event.clientX;
	g_lastPt[1] = event.clientY;
}


function MovingBox_OnMM(obj,event)
{
	if (g_lastMs!=1)
		return;
	obj.style.cursor = 'move';	
	var diffX =  event.clientX-g_lastPt[0];
	var diffY =  event.clientY-g_lastPt[1];
	var pos = getT(obj);
	setT(obj,diffX+pos[0],diffY+pos[1]);
}
function OnKeyDown(e)
{
	var keynum,key;
	
	if(window.event) // IE
	  keynum = e.keyCode;
	else if(e.which) // Netscape/Firefox/Opera
	  keynum = e.which;
	
	key = String.fromCharCode(keynum);

	//lg(keynum);

	if (keynum==27)
	{
		if (IsVisible('emailpanel'))
		{
			Hide('whole');
			Hide('emailpanel');
		}
		else
			ShowTB(true);
	}
	else if (keynum==113)
	{
		executeZoomScript();
	}
}

function OnClick(o)
{
	if (o.id=='iv_ovb')
	{
		g('iv_deb').style.backgroundColor = '#DDD';
		g('iv_deb').style.border="0px";
		g('iv_dib').style.backgroundColor = '#DDD';
		g('iv_dib').style.border="0px";
		o.style.backgroundColor = 'white';
		g('iv_line2').style.display = 'none';
		g('iv_line3').style.display = 'none';
		o.style.borderTop = "3px solid #F00";
	}
	else if (o.id=='iv_deb')
	{
		g('iv_ovb').style.backgroundColor = '#DDD';
		g('iv_ovb').style.border="0px";
		g('iv_dib').style.backgroundColor = '#DDD';
		g('iv_dib').style.border="0px";
		o.style.backgroundColor = 'white';
		g('iv_line2').style.display = 'inline';
		g('iv_line3').style.display = 'none';
		o.style.borderTop = "3px solid #F00";
	}
	else if (o.id=='iv_dib')
	{
		g('iv_ovb').style.backgroundColor = '#DDD';
		g('iv_ovb').style.border="0px";
		g('iv_deb').style.backgroundColor = '#DDD';
		g('iv_deb').style.border="0px";
		o.style.backgroundColor = 'white';
		g('iv_line2').style.display = 'none';
		g('iv_line3').style.display = 'inline';
		o.style.borderTop = "3px solid #F00";
		g('daddr').value = g('iv_addr').innerHTML;
		var html = g('iv_line3').innerHTML;
		if (html.search(/<script/i)==-1)
			g('iv_line3').innerHTML = html +"<br>"+g('gadi').innerHTML+"<br>"+g('gadiimg').innerHTML;
	}
}




/* Simple AJAX Code-Kit (SACK) */
/* �2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence, see documentation or authors website for more details */

function sack(file){
    this.jjFailedAlert = "Your browser does not support the enhanced functionality of this website, and therefore you will have an experience that differs from the intended one.\n";
    this.requestFile = file;
    this.method = "POST";
    this.URLString = "";
    this.encodeURIString = true;
    this.execute = false;
    
    this.onLoading = function(){
    };
    this.onLoaded = function(){
    };
    this.onInteractive = function(){
    };
    this.onCompletion = function(){
    };
    
    this.createjj = function(){
        try {
            this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (e) {
            try {
                this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (err) {
                this.xmlhttp = null;
            }
        }
        if (!this.xmlhttp && typeof XMLHttpRequest != "undefined") 
            this.xmlhttp = new XMLHttpRequest();
        if (!this.xmlhttp) {
            this.failed = true;
        }
    };
    
    this.setVar = function(name, value){
        if (this.URLString.length < 3) {
            this.URLString = name + "=" + value;
        }
        else {
            this.URLString += "&" + name + "=" + value;
        }
    };
    
    this.encVar = function(name, value){
        var varString = encodeURIComponent(name) + "=" + encodeURIComponent(value);
        return varString;
    };
    
    this.encodeURLString = function(string){
        varArray = string.split('&');
        for (i = 0; i < varArray.length; i++) {
            urlVars = varArray[i].split('=');
            if (urlVars[0].indexOf('amp;') != -1) {
                urlVars[0] = urlVars[0].substring(4);
            }
            varArray[i] = this.encVar(urlVars[0], urlVars[1]);
        }
        return varArray.join('&');
    };
    
    this.runResponse = function(){
        eval(this.response);
    }
    
    this.runjj = function(urlstring){
        this.responseStatus = new Array(2);
        if (this.failed && this.jjFailedAlert) {
            alert(this.jjFailedAlert);
        }
        else {
            if (urlstring) {
                if (this.URLString.length) {
                    this.URLString = this.URLString + "&" + urlstring;
                }
                else {
                    this.URLString = urlstring;
                }
            }
            if (this.encodeURIString) {
                var timeval = new Date().getTime();
                this.URLString = this.encodeURLString(this.URLString);
                this.setVar("rndval", timeval);
            }
            if (this.element) {
                this.elementObj = document.getElementById(this.element);
            }
            if (this.xmlhttp) {
                var self = this;
                if (this.method == "GET") {
                    var totalurlstring = this.requestFile + "?" + this.URLString;
                    this.xmlhttp.open(this.method, totalurlstring, true);
                }
                else {
                    this.xmlhttp.open(this.method, this.requestFile, true);
                }
                if (this.method == "POST") {
                    try {
                        this.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                    } 
                    catch (e) {
                    }
                }
                
                this.xmlhttp.send(this.URLString);
                this.xmlhttp.onreadystatechange = function(){
                    switch (self.xmlhttp.readyState) {
                        case 1:
                            self.onLoading();
                            break;
                        case 2:
                            self.onLoaded();
                            break;
                        case 3:
                            self.onInteractive();
                            break;
                        case 4:
                            self.response = self.xmlhttp.responseText;
                            self.responseXML = self.xmlhttp.responseXML;
                            self.responseStatus[0] = self.xmlhttp.status;
                            self.responseStatus[1] = self.xmlhttp.statusText;
                            self.onCompletion();
                            if (self.execute) {
                                self.runResponse();
                            }
                            if (self.elementObj) {
                                var elemNodeName = self.elementObj.nodeName;
                                elemNodeName.toLowerCase();
                                if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") {
                                    self.elementObj.value = self.response;
                                }
                                else {
                                    self.elementObj.innerHTML = self.response;
                                }
                            }
                            self.URLString = "";
                            break;
                    }
                };
            }
        }
    };
    this.createjj();
}



/************************************************************************************************************
 (C) www.dhtmlgoodies.com, October 2005
 
 This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.
 www.dhtmlgoodies.com
 Alf Magne Kalleland
 
 ************************************************************************************************************/
var dhtmlgoodies_marqueeSteps = 1; // Higher = Faster, Lower = slower and more smoothly
var dhtmlgoodies_marqueeSpeed = 40; // Lower value = Faster
var dhtmlgoodies_marqueeStopOnMouseOver = true; // Make the marquee stop moving when user moves his mouse over it
var dhtmlgoodies_marqueePosition = 'top'; // "top" or "bottom"
var p1 = '25px';

/* Don't change anything below here */
var dhtmlgoodies_marqueeObj;
var dhtmlgoodies_marqueeTextObj;
var dhtmlgoodies_marqueeTmpStep;
var dhtmlgoodies_marqueeTextObjects = new Array();
var dhtmlgoodies_marqueeHiddenSpans = new Array();

var dhtmlgoodies_marqueeIndex = 0;
function repositionMarquee(e, timeout){
    if (document.all) 
        e = event;
    if (dhtmlgoodies_marqueePosition.toLowerCase() == 'top') {
        dhtmlgoodies_marqueeObj.style.top = p1;
    }
    else {
        dhtmlgoodies_marqueeObj.style.bottom = '-1px';
    }
    if (document.all && !timeout) 
        setTimeout('repositionMarquee(false,true)', 500)
}

function marqueeMove(){
    var leftPos = dhtmlgoodies_marqueeTextObj.offsetLeft;
    leftPos = leftPos - dhtmlgoodies_marqueeTmpStep;
    var rightEdge = leftPos + dhtmlgoodies_marqueeHiddenSpans[dhtmlgoodies_marqueeIndex].offsetLeft;
    if (rightEdge < 0) {
        leftPos = document.documentElement.offsetWidth;
        dhtmlgoodies_marqueeTextObj.style.display = 'none';
        dhtmlgoodies_marqueeIndex++;
        if (dhtmlgoodies_marqueeIndex >= dhtmlgoodies_marqueeTextObjects.length) 
            dhtmlgoodies_marqueeIndex = 0;
        dhtmlgoodies_marqueeTextObj = dhtmlgoodies_marqueeTextObjects[dhtmlgoodies_marqueeIndex];
        dhtmlgoodies_marqueeTextObj.style.display = 'block';
        
    }
    dhtmlgoodies_marqueeTextObj.style.left = leftPos + 'px';
    
}

function stopMarqueeMove(){
    if (dhtmlgoodies_marqueeStopOnMouseOver) 
        dhtmlgoodies_marqueeTmpStep = 0;
}

function resumeMarqueeMove(){
    dhtmlgoodies_marqueeTmpStep = dhtmlgoodies_marqueeSteps;
}

function initMarquee(){
    dhtmlgoodies_marqueeObj = document.getElementById('dhtmlgoodies_marquee');
    
    var spans = dhtmlgoodies_marqueeObj.getElementsByTagName('DIV');
    for (var no = 0; no < spans.length; no++) {
        if (spans[no].className == 'textObj') {
            if (!dhtmlgoodies_marqueeTextObj) {
                dhtmlgoodies_marqueeTextObj = spans[no];
                spans[no].style.display = 'block';
            }
            else 
                spans[no].style.display = 'none';
            dhtmlgoodies_marqueeTextObjects.push(spans[no]);
            var hiddenSpan = document.createElement('SPAN');
            hiddenSpan.innerHTML = ' '
            spans[no].appendChild(hiddenSpan);
            dhtmlgoodies_marqueeHiddenSpans.push(hiddenSpan);
            
        }
    }
    if (dhtmlgoodies_marqueePosition.toLowerCase() == 'top') {
        dhtmlgoodies_marqueeObj.style.top = p1;
    }
    else {
        if (document.all) {
            dhtmlgoodies_marqueeObj.style.bottom = '0px';
        }
        else {
            dhtmlgoodies_marqueeObj.style.bottom = '-1px';
        }
    }
    
    
    
    
    dhtmlgoodies_marqueeObj.style.display = 'block';
    dhtmlgoodies_marqueeTextObj.style.left = document.documentElement.offsetWidth + 'px';
    dhtmlgoodies_marqueeObj.onmouseover = stopMarqueeMove;
    dhtmlgoodies_marqueeObj.onmouseout = resumeMarqueeMove;
    if (document.all) 
        window.onscroll = repositionMarquee;
    else 
        dhtmlgoodies_marqueeObj.style.position = 'fixed';
    
    dhtmlgoodies_marqueeObj.style.display = 'block';
    dhtmlgoodies_marqueeTmpStep = dhtmlgoodies_marqueeSteps;
    
    setInterval('marqueeMove()', dhtmlgoodies_marqueeSpeed);
}


//Zoom text
var textArray = ['<span id="intro_logo">FREE Ads!</span>', 'Buy, Sell, Rent...', '<span style="color:red;">housing</span>bymap.com'];
var maxFontSize = 50; // Maximum font size in pixels
var zoomSpeed = 3; // Lower = Faster
var fontIncrementBy = 4; // Step of font size incrementation ( Higher = faster)
var delayBetweenWords = [500, 500, 500]; // Microseconds between each word
var delayAtEnd = 100; // Microseconds delay after last word
var textIndex = 0; // Don't change this value
var dhtmlgoodies_tooltip = false;
var dhtmlgoodies_tooltipShadow = false;
var dhtmlgoodies_shadowSize = 2;
var dhtmlgoodies_tooltipMaxWidth = 350;
var dhtmlgoodies_tooltipMinWidth = 100;
var dhtmlgoodies_iframe = false;
var tooltip_is_msie = (navigator.userAgent.indexOf('MSIE') >= 0 && navigator.userAgent.indexOf('opera') == -1 && document.all) ? true : false;

function showTooltip(e, tooltipTxt){
    var bodyWidth = Math.max(document.body.clientWidth, document.documentElement.clientWidth) - 20;
    
    if (!dhtmlgoodies_tooltip) {
        dhtmlgoodies_tooltip = document.createElement('DIV');
        dhtmlgoodies_tooltip.id = 'dhtmlgoodies_tooltip';
        dhtmlgoodies_tooltipShadow = document.createElement('DIV');
        dhtmlgoodies_tooltipShadow.id = 'dhtmlgoodies_tooltipShadow';
        
        document.body.appendChild(dhtmlgoodies_tooltip);
        document.body.appendChild(dhtmlgoodies_tooltipShadow);
        
        if (tooltip_is_msie) {
            dhtmlgoodies_iframe = document.createElement('IFRAME');
            dhtmlgoodies_iframe.frameborder = '5';
            dhtmlgoodies_iframe.style.backgroundColor = '#FFFFFF';
            dhtmlgoodies_iframe.src = '#';
            dhtmlgoodies_iframe.style.zIndex = 100;
            dhtmlgoodies_iframe.style.position = 'absolute';
            document.body.appendChild(dhtmlgoodies_iframe);
        }
        
    }
    
    dhtmlgoodies_tooltip.style.display = 'block';
    dhtmlgoodies_tooltipShadow.style.display = 'block';
    if (tooltip_is_msie) 
        dhtmlgoodies_iframe.style.display = 'block';
    
    var st = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
    if (navigator.userAgent.toLowerCase().indexOf('safari') >= 0) 
        st = 0;
    var leftPos = e.clientX - 10;
    
    dhtmlgoodies_tooltip.style.width = null; // Reset style width if it's set 
    dhtmlgoodies_tooltip.innerHTML = tooltipTxt;
    dhtmlgoodies_tooltip.style.left = leftPos + 'px';
    dhtmlgoodies_tooltip.style.top = e.clientY + 10 + st + 'px';
    
    
    dhtmlgoodies_tooltipShadow.style.left = leftPos + dhtmlgoodies_shadowSize + 'px';
    dhtmlgoodies_tooltipShadow.style.top = e.clientY + 10 + st + dhtmlgoodies_shadowSize + 'px';
    
    if (dhtmlgoodies_tooltip.offsetWidth > dhtmlgoodies_tooltipMaxWidth) { /* Exceeding max width of tooltip ? */
        dhtmlgoodies_tooltip.style.width = dhtmlgoodies_tooltipMaxWidth + 'px';
    }
    
    var tooltipWidth = dhtmlgoodies_tooltip.offsetWidth;
    if (tooltipWidth < dhtmlgoodies_tooltipMinWidth) 
        tooltipWidth = dhtmlgoodies_tooltipMinWidth;
    
    
    dhtmlgoodies_tooltip.style.width = tooltipWidth + 'px';
    dhtmlgoodies_tooltipShadow.style.width = dhtmlgoodies_tooltip.offsetWidth + 'px';
    dhtmlgoodies_tooltipShadow.style.height = dhtmlgoodies_tooltip.offsetHeight + 'px';
    
    if ((leftPos + tooltipWidth) > bodyWidth) {
        dhtmlgoodies_tooltip.style.left = (dhtmlgoodies_tooltipShadow.style.left.replace('px', '') - ((leftPos + tooltipWidth) - bodyWidth)) + 'px';
        dhtmlgoodies_tooltipShadow.style.left = (dhtmlgoodies_tooltipShadow.style.left.replace('px', '') - ((leftPos + tooltipWidth) - bodyWidth) + dhtmlgoodies_shadowSize) + 'px';
    }
    
    if (tooltip_is_msie) {
        dhtmlgoodies_iframe.style.left = dhtmlgoodies_tooltip.style.left;
        dhtmlgoodies_iframe.style.top = dhtmlgoodies_tooltip.style.top;
        dhtmlgoodies_iframe.style.width = dhtmlgoodies_tooltip.offsetWidth + 'px';
        dhtmlgoodies_iframe.style.height = dhtmlgoodies_tooltip.offsetHeight + 'px';
        
    }
    
}

function showTooltip2(x, y, tooltipTxt){
    var bodyWidth = Math.max(document.body.clientWidth, document.documentElement.clientWidth) - 20;
    
    if (!dhtmlgoodies_tooltip) {
        dhtmlgoodies_tooltip = document.createElement('DIV');
        dhtmlgoodies_tooltip.id = 'dhtmlgoodies_tooltip';
        dhtmlgoodies_tooltipShadow = document.createElement('DIV');
        dhtmlgoodies_tooltipShadow.id = 'dhtmlgoodies_tooltipShadow';
        
        document.body.appendChild(dhtmlgoodies_tooltip);
        document.body.appendChild(dhtmlgoodies_tooltipShadow);
        
        if (tooltip_is_msie) {
            dhtmlgoodies_iframe = document.createElement('IFRAME');
            dhtmlgoodies_iframe.frameborder = '5';
            dhtmlgoodies_iframe.style.backgroundColor = '#FFFFFF';
            dhtmlgoodies_iframe.src = '#';
            dhtmlgoodies_iframe.style.zIndex = 100;
            dhtmlgoodies_iframe.style.position = 'absolute';
            document.body.appendChild(dhtmlgoodies_iframe);
        }
        
    }
    
    dhtmlgoodies_tooltip.style.display = 'block';
    dhtmlgoodies_tooltipShadow.style.display = 'block';
    if (tooltip_is_msie) 
        dhtmlgoodies_iframe.style.display = 'block';
    
    var st = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
    if (navigator.userAgent.toLowerCase().indexOf('safari') >= 0) 
        st = 0;
    var leftPos = x - 10;
    
    dhtmlgoodies_tooltip.style.width = null; // Reset style width if it's set 
    dhtmlgoodies_tooltip.innerHTML = tooltipTxt;
    dhtmlgoodies_tooltip.style.left = leftPos + 'px';
    dhtmlgoodies_tooltip.style.top = y + 10 + st + 'px';
    
    
    dhtmlgoodies_tooltipShadow.style.left = leftPos + dhtmlgoodies_shadowSize + 'px';
    dhtmlgoodies_tooltipShadow.style.top = y + 10 + st + dhtmlgoodies_shadowSize + 'px';
    
    if (dhtmlgoodies_tooltip.offsetWidth > dhtmlgoodies_tooltipMaxWidth) { /* Exceeding max width of tooltip ? */
        dhtmlgoodies_tooltip.style.width = dhtmlgoodies_tooltipMaxWidth + 'px';
    }
    
    var tooltipWidth = dhtmlgoodies_tooltip.offsetWidth;
    if (tooltipWidth < dhtmlgoodies_tooltipMinWidth) 
        tooltipWidth = dhtmlgoodies_tooltipMinWidth;
    
    
    dhtmlgoodies_tooltip.style.width = tooltipWidth + 'px';
    dhtmlgoodies_tooltipShadow.style.width = dhtmlgoodies_tooltip.offsetWidth + 'px';
    dhtmlgoodies_tooltipShadow.style.height = dhtmlgoodies_tooltip.offsetHeight + 'px';
    
    if ((leftPos + tooltipWidth) > bodyWidth) {
        dhtmlgoodies_tooltip.style.left = (dhtmlgoodies_tooltipShadow.style.left.replace('px', '') - ((leftPos + tooltipWidth) - bodyWidth)) + 'px';
        dhtmlgoodies_tooltipShadow.style.left = (dhtmlgoodies_tooltipShadow.style.left.replace('px', '') - ((leftPos + tooltipWidth) - bodyWidth) + dhtmlgoodies_shadowSize) + 'px';
    }
    
    if (tooltip_is_msie) {
        dhtmlgoodies_iframe.style.left = dhtmlgoodies_tooltip.style.left;
        dhtmlgoodies_iframe.style.top = dhtmlgoodies_tooltip.style.top;
        dhtmlgoodies_iframe.style.width = dhtmlgoodies_tooltip.offsetWidth + 'px';
        dhtmlgoodies_iframe.style.height = dhtmlgoodies_tooltip.offsetHeight + 'px';
        
    }
    
}

function hideTooltip(){
    dhtmlgoodies_tooltip.style.display = 'none';
    dhtmlgoodies_tooltipShadow.style.display = 'none';
    if (tooltip_is_msie) 
        dhtmlgoodies_iframe.style.display = 'none';
}

var DHTMLSuite = new Object();

var standardObjectsCreated = false; // The classes below will check this variable, if it is false, default help objects will be created
DHTMLSuite.eventElements = new Array(); // Array of elements that has been assigned to an event handler.
DHTMLSuite.createStandardObjects = function(){
    DHTMLSuite.clientInfoObj = new DHTMLSuite.clientInfo(); // Create browser info object
    DHTMLSuite.clientInfoObj.init();
    if (!DHTMLSuite.configObj) { // If this object isn't allready created, create it.
        DHTMLSuite.configObj = new DHTMLSuite.config(); // Create configuration object.
        DHTMLSuite.configObj.init();
    }
    DHTMLSuite.commonObj = new DHTMLSuite.common(); // Create configuration object.
    DHTMLSuite.variableStorage = new DHTMLSuite.globalVariableStorage();
    ; // Create configuration object.
    DHTMLSuite.commonObj.init();
    window.onunload = function(){
        DHTMLSuite.commonObj.__clearGarbage();
    }
    
    standardObjectsCreated = true;
    
    
}




/************************************************************************************************************
 *	Configuration class used by most of the scripts
 *
 *	Created:			August, 19th, 2006
 * 	Update log:
 *
 ************************************************************************************************************/
/**
 * @constructor
 * @class Store global variables/configurations used by the classes below. Example: If you want to
 *		 change the path to the images used by the scripts, change it here. An object of this
 *		 class will always be available to the other classes. The name of this object is
 *		"DHTMLSuite.configObj".	<br><br>
 *
 *		If you want to create an object of this class manually, remember to name it "DHTMLSuite.configObj"
 *		This object should then be created before any other objects. This is nescessary if you want
 *		the other objects to use the values you have put into the object. <br>
 * @version				1.0
 * @version 1.0
 * @author	Alf Magne Kalleland(www.dhtmlgoodies.com)
 **/
DHTMLSuite.config = function(){
    var imagePath; // Path to images used by the classes. 
    var cssPath; // Path to CSS files used by the DHTML suite.		
}


DHTMLSuite.config.prototype = {
    // {{{ init()
    init: function(){
        this.imagePath = '../images/images_dhtmlsuite/'; // Path to images		
        this.cssPath = '../css/'; // Path to images		
    }    // }}}
    ,
    // {{{ setCssPath()
    setCssPath: function(newCssPath){
        this.cssPath = newCssPath;
    }    // }}}
    ,
    // {{{ setImagePath()
      setImagePath: function(newImagePath){
        this.imagePath = newImagePath;
    }
    // }}}
}



DHTMLSuite.globalVariableStorage = function(){
    var menuBar_highlightedItems; // Array of highlighted menu bar items
    this.menuBar_highlightedItems = new Array();
    
    var arrayOfDhtmlSuiteObjects; // Array of objects of class menuItem.
    this.arrayOfDhtmlSuiteObjects = new Array();
}

DHTMLSuite.globalVariableStorage.prototype = {}


DHTMLSuite.common = function(){
    var loadedCSSFiles; // Array of loaded CSS files. Prevent same CSS file from being loaded twice.
    var cssCacheStatus; // Css cache status
    var eventElements;
    
    this.cssCacheStatus = true; // Caching of css files = on(Default)
    this.eventElements = new Array();
}

DHTMLSuite.common.prototype = {

    // {{{ init()
    /**
     * This method initializes the DHTMLSuite_common object.
     *
     * @public
     */
    init: function(){
        this.loadedCSSFiles = new Array();
    }    // }}}
    ,
    // {{{ loadCSS()
    /**
     * This method loads a CSS file(Cascading Style Sheet) dynamically - i.e. an alternative to <link> tag in the document.
     *
     * @param string cssFileName = New path to image files
     * @public
     */
    loadCSS: function(cssFileName){
    
        if (!this.loadedCSSFiles[cssFileName]) {
            this.loadedCSSFiles[cssFileName] = true;
            var linkTag = document.createElement('LINK');
            if (!this.cssCacheStatus) {
                if (cssFileName.indexOf('?') >= 0) 
                    cssFileName = cssFileName + '&';
                else 
                    cssFileName = cssFileName + '?';
                cssFileName = cssFileName + 'rand=' + Math.random(); // To prevent caching
            }
            linkTag.href = DHTMLSuite.configObj.cssPath + cssFileName;
            linkTag.rel = 'stylesheet';
            linkTag.media = 'screen';
            linkTag.type = 'text/css';
            document.getElementsByTagName('HEAD')[0].appendChild(linkTag);
            
        }
    }    // }}}
    ,
    // {{{ getTopPos()
    /**
     * This method will return the top coordinate(pixel) of an object
     *
     * @param Object inputObj = Reference to HTML element
     * @public
     */
    getTopPos: function(inputObj){
        var returnValue = inputObj.offsetTop;
        while ((inputObj = inputObj.offsetParent) != null) {
            if (inputObj.tagName != 'HTML') {
                returnValue += (inputObj.offsetTop - inputObj.scrollTop);
                if (document.all) 
                    returnValue += inputObj.clientTop;
            }
        }
        return returnValue;
    }    // }}}	
    ,
    // {{{ setCssCacheStatus()
    /**
     * Specify if css files should be cached or not.
     *
     *	@param Boolean cssCacheStatus = true = cache on, false = cache off
     *
     * @public
     */
    setCssCacheStatus: function(cssCacheStatus){
        this.cssCacheStatus = cssCacheStatus;
    }    // }}}	
    ,
    // {{{ getLeftPos()
    /**
     * This method will return the left coordinate(pixel) of an object
     *
     * @param Object inputObj = Reference to HTML element
     * @public
     */
    getLeftPos: function(inputObj){
        var returnValue = inputObj.offsetLeft;
        while ((inputObj = inputObj.offsetParent) != null) {
            if (inputObj.tagName != 'HTML') {
                returnValue += inputObj.offsetLeft;
                if (document.all) 
                    returnValue += inputObj.clientLeft;
            }
        }
        return returnValue;
    }    // }}}
    ,
    // {{{ cancelEvent()
    /**
     *
     *  This function only returns false. It is used to cancel selections and drag
     *
     *
     * @public
     */
    cancelEvent: function(){
        return false;
    }    // }}}	
    ,
    // {{{ addEvent()
     addEvent: function(whichObject, eventType, functionName){
        if (whichObject.attachEvent) {
            whichObject['e' + eventType + functionName] = functionName;
            whichObject[eventType + functionName] = function(){
                whichObject['e' + eventType + functionName](window.event);
            }
            whichObject.attachEvent('on' + eventType, whichObject[eventType + functionName]);
        }
        else 
            whichObject.addEventListener(eventType, functionName, false);
        this.__addEventElement(whichObject);
        delete (whichObject);
        // whichObject = null;
    }    // }}}	
    ,
    // {{{ removeEvent()
    /**
     *
     *  This function removes an event listener from an element on the page.
     *
     *	@param Object whichObject = Reference to HTML element(Which object to assigne the event)
     *	@param String eventType = Which type of event, example "mousemove" or "mouseup"
     *	@param functionName = Name of function to execute.
     *
     * @public
     */
    removeEvent: function(whichObject, eventType, functionName){
        if (whichObject.detachEvent) {
            whichObject.detachEvent('on' + eventType, whichObject[eventType + functionName]);
            whichObject[eventType + functionName] = null;
        }
        else 
            whichObject.removeEventListener(eventType, functionName, false);
    },
    // {{{ __clearGarbage()
    /**
     *
     *  This function is used for Internet Explorer in order to clear memory when the page unloads.
     *
     *
     * @private
     */
    __clearGarbage: function(){
        /* Example of event which causes memory leakage in IE 
         
         DHTMLSuite.commonObj.addEvent(expandRef,"click",function(){ window.refToMyMenuBar[index].__changeMenuBarState(this); })
         
         We got a circular reference.
         
         */
        if (!DHTMLSuite.clientInfoObj.isMSIE) 
            return;
        
        for (var no in DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects) {
            DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects[no] = false;
        }
        
        for (var no = 0; no < DHTMLSuite.eventElements.length; no++) {
            DHTMLSuite.eventElements[no].onclick = null;
            DHTMLSuite.eventElements[no].onmousedown = null;
            DHTMLSuite.eventElements[no].onmousemove = null;
            DHTMLSuite.eventElements[no].onmouseout = null;
            DHTMLSuite.eventElements[no].onmouseover = null;
            DHTMLSuite.eventElements[no].onmouseup = null;
            DHTMLSuite.eventElements[no].onfocus = null;
            DHTMLSuite.eventElements[no].onblur = null;
            DHTMLSuite.eventElements[no].onkeydown = null;
            DHTMLSuite.eventElements[no].onkeypress = null;
            DHTMLSuite.eventElements[no].onkeyup = null;
            DHTMLSuite.eventElements[no].onselectstart = null;
            DHTMLSuite.eventElements[no].ondragstart = null;
            DHTMLSuite.eventElements[no].oncontextmenu = null;
            DHTMLSuite.eventElements[no].onscroll = null;
            
        }
        window.onunload = null;
        DHTMLSuite = null;
        
    },
    // {{{ __addEventElement()
      __addEventElement: function(el){
        DHTMLSuite.eventElements[DHTMLSuite.eventElements.length] = el;
    },
    // {{{ getSrcElement()
     getSrcElement: function(e){
        var el;
        // Dropped on which element
        if (e.target) 
            el = e.target;
        else 
            if (e.srcElement) 
                el = e.srcElement;
        if (el.nodeType == 3) // defeat Safari bug
            el = el.parentNode;
        return el;
    }
    
}


DHTMLSuite.clientInfo = function(){
    var browser; // Complete user agent information
    var isOpera; // Is the browser "Opera"
    var isMSIE; // Is the browser "Internet Explorer"	
    var isFirefox; // Is the browser "Firefox"
    var navigatorVersion; // Browser version
}

DHTMLSuite.clientInfo.prototype = {



    init: function(){
        this.browser = navigator.userAgent;
        this.isOpera = (this.browser.toLowerCase().indexOf('opera') >= 0) ? true : false;
        this.isFirefox = (this.browser.toLowerCase().indexOf('firefox') >= 0) ? true : false;
        this.isMSIE = (this.browser.toLowerCase().indexOf('msie') >= 0) ? true : false;
        this.isSafari = (this.browser.toLowerCase().indexOf('safari') >= 0) ? true : false;
        this.navigatorVersion = navigator.appVersion.replace(/.*?MSIE (\d\.\d).*/g, '$1') / 1;
    }
    // }}}		
}

DHTMLSuite.menuModelItem = function(){
    var id; // id of this menu item.
    var itemText; // Text for this menu item
    var itemIcon; // Icon for this menu item.
    var url; // url when click on this menu item
    var parentId; // id of parent element
    var separator; // is this menu item a separator
    var jsFunction; // Js function to call onclick
    var depth; // Depth of this menu item.
    var hasSubs; // Does this menu item have sub items.
    var type; // Menu item type - possible values: "top" or "sub". 
    var helpText; // Help text for this item - appear when you move your mouse over the item.
    var state;
    var submenuWidth; // Width of sub menu items.
    var visible; // Visibility of menu item.
    this.state = 'regular';
}

DHTMLSuite.menuModelItem.prototype = {

    setMenuVars: function(id, itemText, itemIcon, url, parentId, helpText, jsFunction, type, submenuWidth){
        this.id = id;
        this.itemText = itemText;
        this.itemIcon = itemIcon;
        this.url = url;
        this.parentId = parentId;
        this.jsFunction = jsFunction;
        this.separator = false;
        this.depth = false;
        this.hasSubs = false;
        this.helpText = helpText;
        this.submenuWidth = submenuWidth;
        this.visible = true;
        if (!type) {
            if (this.parentId) 
                this.type = 'top';
            else 
                this.type = 'sub';
        }
        else 
            this.type = type;
        
        
    }    // }}}	
    ,
    // {{{ setState()
    /**
     *	Update the state attribute of a menu item.
     *
     *  @param String newState New state of this item
     * @public
     */
    setAsSeparator: function(id, parentId){
        this.id = id;
        this.parentId = parentId;
        this.separator = true;
        this.visible = true;
        if (this.parentId) 
            this.type = 'top';
        else 
            this.type = 'sub';
    }    // }}}	
    ,
    // {{{ setState()
    /**
     *	Update the visible attribute of a menu item.
     *
     *  @param Boolean visible true = visible, false = hidden.
     * @public
     */
    setVisibility: function(visible){
        this.visible = visible;
    }    // }}}	
    ,
    // {{{ getState()
    /**
     *	Return the state attribute of a menu item.
     *
     * @public
     */
    getState: function(){
        return this.state;
    }    // }}}	
    ,
    // {{{ setState()
    /**
     *	Update the state attribute of a menu item.
     *
     *  @param String newState New state of this item
     * @public
     */
    setState: function(newState){
        this.state = newState;
    }    // }}}	
    ,
    // {{{ setSubMenuWidth()
    /**
     *	Specify width of direct subs of this item.
     *
     *  @param int newWidth Width of sub menu group(direct sub of this item)
     * @public
     */
    setSubMenuWidth: function(newWidth){
        this.submenuWidth = newWidth;
    }    // }}}	
    ,
    // {{{ setIcon()
    /**
     *	Specify new menu icon
     *
     *  @param String iconPath Path to new menu icon
     * @public
     */
    setIcon: function(iconPath){
        this.itemIcon = iconPath;
    }    // }}}	
    ,
    // {{{ setText()
    /**
     *	Specify new text for the menu item.
     *
     *  @param String newText New text for the menu item.
     * @public
     */
    setText: function(newText){
        this.itemText = newText;
    }
}

/**
 * @version 1.0
 * @author	Alf Magne Kalleland(www.dhtmlgoodies.com)
 */
DHTMLSuite.menuModel = function(){
    var menuItems; // Array of menuModelItem objects
    var menuItemsOrder; // This array is needed in order to preserve the correct order of the array above. the array above is associative
    // And some browsers will loop through that array in different orders than Firefox and IE.
    var submenuType; // Direction of menu items(one item for each depth)
    var mainMenuGroupWidth; // Width of menu group - useful if the first group of items are listed below each other
    this.menuItems = new Array();
    this.menuItemsOrder = new Array();
    this.submenuType = new Array();
    this.submenuType[1] = 'top';
    for (var no = 2; no < 20; no++) {
        this.submenuType[no] = 'sub';
    }
    if (!standardObjectsCreated) 
        DHTMLSuite.createStandardObjects();
}

DHTMLSuite.menuModel.prototype = {
    // {{{ addItem()
    addItem: function(id, itemText, itemIcon, url, parentId, helpText, jsFunction, type, submenuWidth){
        if (!id) 
            id = this.__getUniqueId(); // id not present - create it dynamically.
        this.menuItems[id] = new DHTMLSuite.menuModelItem();
        this.menuItems[id].setMenuVars(id, itemText, itemIcon, url, parentId, helpText, jsFunction, type, submenuWidth);
        this.menuItemsOrder[this.menuItemsOrder.length] = id;
        return this.menuItems[id];
    },
    // {{{ addItemsFromMarkup()
     addItemsFromMarkup: function(ulId){
        if (!document.getElementById(ulId)) {
            alert('<UL> tag with id ' + ulId + ' does not exist');
            return;
        }
        var ulObj = document.getElementById(ulId);
        var liTags = ulObj.getElementsByTagName('LI');
        for (var no = 0; no < liTags.length; no++) { // Walking through all <li> tags in the <ul> tree
            var id = liTags[no].id.replace(/[^0-9]/gi, ''); // Get id of item.
            if (!id) 
                id = this.__getUniqueId();
            this.menuItems[id] = new DHTMLSuite.menuModelItem(); // Creating new menuModelItem object
            this.menuItemsOrder[this.menuItemsOrder.length] = id;
            // Get the attributes for this new menu item.	
            
            var parentId = 0; // Default parent id
            if (liTags[no].parentNode != ulObj) 
                parentId = liTags[no].parentNode.parentNode.id; // parent node exists, set parentId equal to id of parent <li>.
            /* Checking type */
            var type = liTags[no].getAttribute('itemType');
            if (!type) 
                type = liTags[no].itemType;
            if (type == 'separator') { // Menu item of type "separator"
                this.menuItems[id].setAsSeparator(id, parentId);
                continue;
            }
            if (parentId) 
                type = 'sub';
            else 
                type = 'top';
            
            var aTag = liTags[no].getElementsByTagName('A')[0]; // Get a reference to sub <a> tag
            if (!aTag) {
                continue;
            }
            if (aTag) 
                var itemText = aTag.innerHTML; // Item text is set to the innerHTML of the <a> tag.
            var itemIcon = liTags[no].getAttribute('itemIcon'); // Item icon is set from the itemIcon attribute of the <li> tag.
            var url = aTag.href; // url is set to the href attribute of the <a> tag
            if (url == '#' || url.substr(url.length - 1, 1) == '#') 
                url = ''; // # = empty url.
            var jsFunction = liTags[no].getAttribute('jsFunction'); // jsFunction is set from the jsFunction attribute of the <li> tag.
            var submenuWidth = false; // Not set from the <li> tag. 
            var helpText = aTag.getAttribute('title');
            if (!helpText) 
                helpText = aTag.title;
            
            this.menuItems[id].setMenuVars(id, itemText, itemIcon, url, parentId, helpText, jsFunction, type, submenuWidth);
        }
        var subUls = ulObj.getElementsByTagName('UL');
        for (var no = 0; no < subUls.length; no++) {
            var width = subUls[no].getAttribute('width');
            if (!width) 
                width = subUls[no].width;
            if (width) {
                var id = subUls[no].parentNode.id.replace(/[^0-9]/gi, '');
                this.setSubMenuWidth(id, width);
            }
        }
        ulObj.style.display = 'none';
        
    }    // }}}	
    ,
    // {{{ setSubMenuWidth()
    setSubMenuWidth: function(id, newWidth){
        this.menuItems[id].setSubMenuWidth(newWidth);
    },
    // {{{ setMainMenuGroupWidth()
    setMainMenuGroupWidth: function(newWidth){
        this.mainMenuGroupWidth = newWidth;
    },
    // {{{ addSeparator()

    addSeparator: function(parentId){
        id = this.__getUniqueId(); // Get unique id
        if (!parentId) 
            parentId = 0;
        this.menuItems[id] = new DHTMLSuite.menuModelItem();
        this.menuItems[id].setAsSeparator(id, parentId);
        this.menuItemsOrder[this.menuItemsOrder.length] = id;
        return this.menuItems[id];
    },
    // {{{ init()
    /**
     *	Initilizes the menu model. This method should be called when all items has been added to the model.
     *
     *
     * @public
     */
    init: function(){
        this.__getDepths();
        this.__setHasSubs();
        
    }    // }}}	
    ,

    setMenuItemVisibility: function(id, visible){
        this.menuItems[id].setVisibility(visible);
    }    // }}}
    ,
    // {{{ setSubMenuType()
    /**
     *	Set menu type for a specific menu depth.
     *
     *	@param int depth = 1 = Top menu, 2 = Sub level 1...
     *	@param String newType = New menu type(possible values: "top" or "sub")
     *
     * @private
     */
    setSubMenuType: function(depth, newType){
        this.submenuType[depth] = newType;
        
    }    // }}}		
    ,
    // {{{ __getDepths()
    /**
     *	Create variable for the depth of each menu item.
     *
     *
     * @private
     */
    getItems: function(parentId, returnArray){
        if (!parentId) 
            return this.menuItems;
        if (!returnArray) 
            returnArray = new Array();
        for (var no = 0; no < this.menuItemsOrder.length; no++) {
            var id = this.menuItemsOrder[no];
            if (!id) 
                continue;
            if (this.menuItems[id].parentId == parentId) {
                returnArray[returnArray.length] = this.menuItems[id];
                if (this.menuItems[id].hasSubs) 
                    return this.getItems(this.menuItems[id].id, returnArray);
            }
        }
        return returnArray;
        
    }    // }}}
    ,
    // {{{ __getUniqueId()
    /**
     *	Returns a unique id for a menu item. This method is used by the addSeparator function in case an id isn't sent to the method.
     *
     *
     * @private
     */
    __getUniqueId: function(){
        var num = Math.random() + '';
        num = num.replace('.', '');
        num = '99' + num;
        num = num / 1;
        while (this.menuItems[num]) {
            num = Math.random() + '';
            num = num.replace('.', '');
            num = num / 1;
        }
        return num;
    }    // }}}	
    ,
    // {{{ __getDepths()
    /**
     *	Create variable for the depth of each menu item.
     *
     *
     * @private
     */
    __getDepths: function(){
        for (var no = 0; no < this.menuItemsOrder.length; no++) {
            var id = this.menuItemsOrder[no];
            if (!id) 
                continue;
            this.menuItems[id].depth = 1;
            if (this.menuItems[id].parentId) {
                this.menuItems[id].depth = this.menuItems[this.menuItems[id].parentId].depth + 1;
                
            }
            this.menuItems[id].type = this.submenuType[this.menuItems[id].depth]; // Save menu direction for this menu item.  		
        }
    }    // }}}
    ,
    // {{{ __setHasSubs()
    /**
     *	Create variable for the depth of each menu item.
     *
     *
     * @private
     */
    __setHasSubs: function(){
        for (var no = 0; no < this.menuItemsOrder.length; no++) {
            var id = this.menuItemsOrder[no];
            if (!id) 
                continue;
            if (this.menuItems[id].parentId) {
                this.menuItems[this.menuItems[id].parentId].hasSubs = 1;
                
            }
        }
    }    // }}}
    ,
    // {{{ __hasSubs()
    /**
     *	Does a menu item have sub elements ?
     *
     *
     * @private
     */
    // }}}	
    __hasSubs: function(id){
        for (var no = 0; no < this.menuItemsOrder.length; no++) {
            var id = this.menuItemsOrder[no];
            if (!id) 
                continue;
            if (this.menuItems[id].parentId == id) 
                return true;
        }
        return false;
    }    // }}}
    ,
    // {{{ __deleteChildNodes()
    /**
     *	Deleting child nodes of a specific parent id
     *
     *	@param int parentId
     *
     * @private
     */
    // }}}		
    __deleteChildNodes: function(parentId, recursive){
        var itemsToDeleteFromOrderArray = new Array();
        for (var prop = 0; prop < this.menuItemsOrder.length; prop++) {
            var id = this.menuItemsOrder[prop];
            if (!id) 
                continue;
            
            if (this.menuItems[id].parentId == parentId && parentId) {
                this.menuItems[id] = false;
                itemsToDeleteFromOrderArray[itemsToDeleteFromOrderArray.length] = id;
                this.__deleteChildNodes(id, true); // Recursive call.
            }
        }
        
        if (!recursive) {
            for (var prop = 0; prop < itemsToDeleteFromOrderArray; prop++) {
                if (!itemsToDeleteFromOrderArray[prop]) 
                    continue;
                this.__deleteItemFromItemOrderArray(itemsToDeleteFromOrderArray[prop]);
            }
        }
        this.__setHasSubs();
    }    // }}}
    ,
    // {{{ __deleteANode()
    /**
     *	Deleting a specific node from the menu model
     *
     *	@param int id = Id of node to delete.
     *
     * @private
     */
    // }}}		
    __deleteANode: function(id){
        this.menuItems[id] = false;
        this.__deleteItemFromItemOrderArray(id);
    },
    // {{{ __deleteItemFromItemOrderArray()
    /**
     *	Deleting a specific node from the menuItemsOrder array(The array controlling the order of the menu items).
     *
     *	@param int id = Id of node to delete.
     *
     * @private
     */
    // }}}		
    __deleteItemFromItemOrderArray: function(id){
        for (var no = 0; no < this.menuItemsOrder.length; no++) {
            var tmpId = this.menuItemsOrder[no];
            if (!tmpId) 
                continue;
            if (this.menuItemsOrder[no] == id) {
                this.menuItemsOrder.splice(no, 1);
                return;
            }
        }
        
    }    // }}}
    ,
    // {{{ __appendMenuModel()
    /**
     *	Replace the sub items of a menu item with items from a new menuModel.
     *
     *	@param menuModel newModel = An object of class menuModel - the items of this menu model will be appended to the existing menu items.
     *	@param Int parentId = Id of parent element of the appended items.
     *
     * @private
     */
    // }}}		
    __appendMenuModel: function(newModel, parentId){
        if (!newModel) 
            return;
        var items = newModel.getItems();
        for (var no = 0; no < newModel.menuItemsOrder.length; no++) {
            var id = newModel.menuItemsOrder[no];
            if (!id) 
                continue;
            if (!items[id].parentId) 
                items[id].parentId = parentId;
            this.menuItems[id] = items[id];
            for (var no2 = 0; no2 < this.menuItemsOrder.length; no2++) { // Check to see if this item allready exists in the menuItemsOrder array, if it does, remove it. 
                if (!this.menuItemsOrder[no2]) 
                    continue;
                if (this.menuItemsOrder[no2] == items[id].id) {
                    this.menuItemsOrder.splice(no2, 1);
                }
            }
            this.menuItemsOrder[this.menuItemsOrder.length] = items[id].id;
        }
        this.__getDepths();
        this.__setHasSubs();
    }
    // }}}
}

/* Class for menu items - a view */

/************************************************************************************************************
 *	DHTML menu item class
 *
 *	Created:						October, 21st, 2006
 *	@class Purpose of class:		Creates the HTML for a single menu item.
 *
 *	Css files used by this script:	menu-item.css
 *
 *	Demos of this class:			demo-menu-strip.html
 *
 * 	Update log:
 *
 ************************************************************************************************************/
/**
 * @constructor
 * @class Purpose of class:	Creates the div(s) for a menu item. This class is used by the menuBar class. You can
 *	also create a menu item and add it where you want on your page. the createItem() method will return the div
 *	for the item. You can use the appendChild() method to add it to your page.
 *
 * @version 1.0
 * @author	Alf Magne Kalleland(www.dhtmlgoodies.com)
 */
DHTMLSuite.menuItem = function(){
    var layoutCSS;
    var divElement; // the <div> element created for this menu item
    var expandElement; // Reference to the arrow div (expand sub items)
    var cssPrefix; // Css prefix for the menu items.
    var modelItemRef; // Reference to menuModelItem
    this.layoutCSS = 'menu-item.css';
    this.cssPrefix = 'DHTMLSuite_';
    
    if (!standardObjectsCreated) 
        DHTMLSuite.createStandardObjects();
    
    
    var objectIndex;
    this.objectIndex = DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects.length;
    
    
}

DHTMLSuite.menuItem.prototype = {

    /*
     *	Create a menu item.
     *
     *	@param menuModelItem menuModelItemObj = An object of class menuModelItem
     */
    createItem: function(menuModelItemObj){
        DHTMLSuite.commonObj.loadCSS(this.layoutCSS); // Load css
        DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects[this.objectIndex] = this;
        
        this.modelItemRef = menuModelItemObj;
        this.divElement = document.createElement('DIV'); // Create main div
        this.divElement.id = 'DHTMLSuite_menuItem' + menuModelItemObj.id; // Giving this menu item it's unque id
        this.divElement.className = this.cssPrefix + 'menuItem_' + menuModelItemObj.type + '_regular';
        this.divElement.onselectstart = function(){
            return DHTMLSuite.commonObj.cancelEvent(false, this)
        };
        if (menuModelItemObj.helpText) { // Add "title" attribute to the div tag if helpText is defined
            this.divElement.title = menuModelItemObj.helpText;
        }
        
        // Menu item of type "top"
        if (menuModelItemObj.type == 'top') {
            this.__createMenuElementsOfTypeTop(this.divElement);
        }
        
        if (menuModelItemObj.type == 'sub') {
            this.__createMenuElementsOfTypeSub(this.divElement);
        }
        
        if (menuModelItemObj.separator) {
            this.divElement.className = this.cssPrefix + 'menuItem_separator_' + menuModelItemObj.type;
            this.divElement.innerHTML = '<span></span>';
        }
        else {
            /* Add events */
            var tmpVar = this.objectIndex / 1;
            this.divElement.onclick = function(e){
                DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects[tmpVar].__navigate(e);
            }
            this.divElement.onmousedown = this.__clickMenuItem; // on mouse down effect
            this.divElement.onmouseup = this.__rolloverMenuItem; // on mouse up effect
            this.divElement.onmouseover = this.__rolloverMenuItem; // mouse over effect
            this.divElement.onmouseout = this.__rolloutMenuItem; // mouse out effect.
            DHTMLSuite.commonObj.__addEventElement(this.divElement);
        }
        return this.divElement;
    }    // }}}
    ,
    // {{{ setLayoutCss()
    /**
     *	Creates the different parts of a menu item of type "top".
     *
     *  @param String newLayoutCss = Name of css file used for the menu items.
     *
     * @public
     */
    setLayoutCss: function(newLayoutCss){
        this.layoutCSS = newLayoutCss;
        
    }    // }}}
    ,
    // {{{ __createMenuElementsOfTypeTop()
    /**
     *	Creates the different parts of a menu item of type "top".
     *
     *  @param menuModelItem menuModelItemObj = Object of type menuModelItemObj
     *  @param Object parentEl = Reference to parent element
     *
     * @private
     */
    __createMenuElementsOfTypeTop: function(parentEl){
        if (this.modelItemRef.itemIcon) {
            var iconDiv = document.createElement('DIV');
            iconDiv.innerHTML = '<img src="' + this.modelItemRef.itemIcon + '">';
            iconDiv.id = 'menuItemIcon' + this.modelItemRef.id
            parentEl.appendChild(iconDiv);
        }
        if (this.modelItemRef.itemText) {
            var div = document.createElement('DIV');
            div.innerHTML = this.modelItemRef.itemText;
            div.className = this.cssPrefix + 'menuItem_textContent';
            div.id = 'menuItemText' + this.modelItemRef.id;
            parentEl.appendChild(div);
        }
        /* Create div for the arrow -> Show sub items */
        var div = document.createElement('DIV');
        div.className = this.cssPrefix + 'menuItem_top_arrowShowSub';
        div.id = 'DHTMLSuite_menuBar_arrow' + this.modelItemRef.id;
        parentEl.appendChild(div);
        this.expandElement = div;
        if (!this.modelItemRef.hasSubs) 
            div.style.display = 'none';
        
    }    // }}}
    ,
    
    // {{{ __createMenuElementsOfTypeSub()
    /**
     *	Creates the different parts of a menu item of type "sub".
     *
     *  @param menuModelItem menuModelItemObj = Object of type menuModelItemObj
     *  @param Object parentEl = Reference to parent element
     *
     * @private
     */
    __createMenuElementsOfTypeSub: function(parentEl){
        if (this.modelItemRef.itemIcon) {
            parentEl.style.backgroundImage = 'url(\'' + this.modelItemRef.itemIcon + '\')';
            parentEl.style.backgroundRepeat = 'no-repeat';
            parentEl.style.backgroundPosition = 'left center';
        }
        if (this.modelItemRef.itemText) {
            var div = document.createElement('DIV');
            div.className = 'DHTMLSuite_textContent';
            div.innerHTML = this.modelItemRef.itemText;
            div.className = this.cssPrefix + 'menuItem_textContent';
            div.id = 'menuItemText' + this.modelItemRef.id;
            parentEl.appendChild(div);
        }
        
        /* Create div for the arrow -> Show sub items */
        var div = document.createElement('DIV');
        div.className = this.cssPrefix + 'menuItem_sub_arrowShowSub';
        parentEl.appendChild(div);
        div.id = 'DHTMLSuite_menuBar_arrow' + this.modelItemRef.id;
        this.expandElement = div;
        
        if (!this.modelItemRef.hasSubs) {
            div.style.display = 'none';
        }
        else {
            div.previousSibling.style.paddingRight = '15px';
        }
    }    // }}}
    ,
    // {{{ setCssPrefix()
    /**
     *	Set css prefix for the menu item. default is 'DHTMLSuite_'. This is useful in case you want to have different menus on a page with different layout.
     *
     *  @param String cssPrefix = New css prefix.
     *
     * @public
     */
    setCssPrefix: function(cssPrefix){
        this.cssPrefix = cssPrefix;
    }    // }}}
    ,
    // {{{ setMenuIcon()
    /**
     *	Replace menu icon.
     *
     *	@param String newPath - Path to new icon (false if no icon);
     *
     * @public
     */
    setIcon: function(newPath){
        this.modelItemRef.setIcon(newPath);
        if (this.modelItemRef.type == 'top') { // Menu item is of type "top"
            var div = document.getElementById('menuItemIcon' + this.modelItemRef.id); // Get a reference to the div where the icon is located.
            var img = div.getElementsByTagName('IMG')[0]; // Find the image
            if (!img) { // Image doesn't exists ?
                img = document.createElement('IMG'); // Create new image
                div.appendChild(img);
            }
            img.src = newPath; // Set image path
            if (!newPath) 
                img.parentNode.removeChild(img); // No newPath defined, remove the image.			
        }
        if (this.modelItemRef.type == 'sub') { // Menu item is of type "sub"
            this.divElement.style.backgroundImage = 'url(\'' + newPath + '\')'; // Set backgroundImage for the main div(i.e. menu item div)	
        }
    }    // }}}
    ,
    // {{{ setText()
    /**
     *	Replace the text of a menu item
     *
     *	@param String newText - New text for the menu item.
     *
     * @public
     */
    setText: function(newText){
        this.modelItemRef.setText(newText);
        document.getElementById('menuItemText' + this.modelItemRef.id).innerHTML = newText;
        
        
    }    // }}}
    ,
    // {{{ __clickMenuItem()
    /**
     *	Effect - click on menu item
     *
     *
     * @private
     */
    __clickMenuItem: function(){
        this.className = this.className.replace('_regular', '_click');
        this.className = this.className.replace('_over', '_click');
    }    // }}}	
    ,
    // {{{ __rolloverMenuItem()
    /**
     *	Roll over effect
     *
     *
     * @private
     */
    __rolloverMenuItem: function(){
        this.className = this.className.replace('_regular', '_over');
        this.className = this.className.replace('_click', '_over');
    }    // }}}
    ,
    // {{{ __rolloutMenuItem()
    /**
     *	Roll out effect
     *
     *
     * @private
     */
    __rolloutMenuItem: function(){
        this.className = this.className.replace('_over', '_regular');
        
    }    // }}}
    ,
    // {{{ setState()
    /**
     *	Set state of a menu item.
     *
     *	@param String newState = New state for the menu item
     *
     * @public
     */
    setState: function(newState){
        this.divElement.className = this.cssPrefix + 'menuItem_' + this.modelItemRef.type + '_' + newState;
        this.modelItemRef.setState(newState);
    }    // }}}
    ,
    // {{{ getState()
    /**
     *	Return state of a menu item.
     *
     *
     * @public
     */
    getState: function(){
        var state = this.modelItemRef.getState();
        if (!state) {
            if (this.divElement.className.indexOf('_over') >= 0) 
                state = 'over';
            if (this.divElement.className.indexOf('_click') >= 0) 
                state = 'click';
            this.modelItemRef.setState(state);
        }
        return state;
    }    // }}}
    ,
    // {{{ __setHasSub()
    /**
     *	Update the item, i.e. show/hide the arrow if the element has subs or not.
     *
     *
     * @private
     */
    __setHasSub: function(hasSubs){
        this.modelItemRef.hasSubs = hasSubs;
        if (!hasSubs) {
            document.getElementById(this.cssPrefix + 'menuBar_arrow' + this.modelItemRef.id).style.display = 'none';
        }
        else {
            document.getElementById(this.cssPrefix + 'menuBar_arrow' + this.modelItemRef.id).style.display = 'block';
        }
    }    // }}}	
    ,
    // {{{ hide()
    /**
     *	Hide the menu item.
     *
     *
     * @public
     */
    hide: function(){
        this.modelItemRef.setVisibility(false);
        this.divElement.style.display = 'none';
    },
    // {{{ show()
    /**
     *	Show the menu item.
     *
     *
     * @public
     */
    show: function(){
        this.modelItemRef.setVisibility(true);
        this.divElement.style.display = 'block';
    }    // }}}
    ,
    // {{{ __hideGroup()
    /**
     *	Hide the group the menu item is a part of. Example: if we're dealing with menu item 2.1, hide the group for all sub items of 2
     *
     *
     * @private
     */
    __hideGroup: function(){
        if (this.modelItemRef.parentId) {
            this.divElement.parentNode.style.visibility = 'hidden';
            if (DHTMLSuite.clientInfoObj.isMSIE) {
                try {
                    var tmpId = this.divElement.parentNode.id.replace(/[^0-9]/gi, '');
                    document.getElementById('DHTMLSuite_menuBarIframe_' + tmpId).style.visibility = 'hidden';
                } 
                catch (e) {
                    // IFRAME hasn't been created.
                }
            }
        }
        
    }    // }}}	
    ,
    // {{{ __navigate()
    /**
     *	Navigate after click on a menu item.
     *
     *
     * @private
     */
    __navigate: function(e){
        /* Check to see if the expand sub arrow is clicked. if it is, we shouldn't navigate from this click */
        if (document.all) 
            e = event;
        if (e) {
            var srcEl = DHTMLSuite.commonObj.getSrcElement(e);
            if (srcEl.id.indexOf('arrow') >= 0) 
                return;
        }
        if (this.modelItemRef.state == 'disabled') 
            return;
        if (this.modelItemRef.url) {
            location.href = this.modelItemRef.url;
        }
        if (this.modelItemRef.jsFunction) {
            try {
                eval(this.modelItemRef.jsFunction);
            } 
            catch (e) {
                alert('Defined Javascript code for the menu item( ' + this.modelItemRef.jsFunction + ' ) cannot be executed');
            }
        }
    }
}


/************************************************************************************************************
 *	DHTML menu bar class
 *
 *	Created:						October, 21st, 2006
 *	@class Purpose of class:		Creates a top bar menu
 *
 *	Css files used by this script:	menu-bar.css
 *
 *	Demos of this class:			demo-menu-bar.html
 *
 * 	Update log:
 *
 ************************************************************************************************************/
/**
 * @constructor
 * @class Purpose of class:	Creates a top bar menu strip. Demos: <br>
 *	<ul>
 *	<li>(<a href="../../demos/demo-menu-bar-2.html" target="_blank">A menu with a detailed description on how it is created</a>)</li>
 *	<li>(<a href="../../demos/demo-menu-bar.html" target="_blank">Demo with lots of menus on the same page</a>)</li>
 *	<li>(<a href="../../demos/demo-menu-bar-custom-css.html" target="_blank">Two menus with different layout</a>)</li>
 *	<li>(<a href="../../demos/demo-menu-bar-custom-css-file.html" target="_blank">One menu with custom layout/css.</a>)</li>
 *	</ul>
 *
 *	<a href="../images/menu-bar-1.gif" target="_blank">Image describing the classes</a> <br><br>
 *
 * @version 1.0
 * @author	Alf Magne Kalleland(www.dhtmlgoodies.com)
 */
DHTMLSuite.menuBar = function(){
    var menuItemObj;
    var layoutCSS; // Name of css file
    var menuBarBackgroundImage; // Name of background image
    var menuItem_objects; // Array of menu items - html elements.
    var menuBarObj; // Reference to the main dib
    var menuBarHeight;
    var menuItems; // Reference to objects of class menuModelItem
    var highlightedItems; // Array of currently highlighted menu items.
    var menuBarState; // Menu bar state - true or false - 1 = expand items on mouse over
    var activeSubItemsOnMouseOver; // Activate sub items on mouse over	(instead of onclick)
    var submenuGroups; // Array of div elements for the sub menus
    var submenuIframes; // Array of sub menu iframes used to cover select boxes in old IE browsers.
    var createIframesForOldIeBrowsers; // true if we want the script to create iframes in order to cover select boxes in older ie browsers.
    var targetId; // Id of element where the menu will be inserted.
    var menuItemCssPrefix; // Css prefix of menu items.
    var cssPrefix; // Css prefix for the menu bar
    var menuItemLayoutCss; // Css path for the menu items of this menu bar
    var globalObjectIndex; // Global index of this object - used to refer to the object of this class outside
    this.cssPrefix = 'DHTMLSuite_';
    this.menuItemLayoutCss = false; // false = use default for the menuItem class.
    this.layoutCSS = 'menu-bar.css';
    this.menuBarBackgroundImage = 'menu_strip_bg.jpg';
    this.menuItem_objects = new Array();
    DHTMLSuite.variableStorage.menuBar_highlightedItems = new Array();
    
    this.menuBarState = false;
    
    this.menuBarObj = false;
    this.menuBarHeight = 26;
    this.submenuGroups = new Array();
    this.submenuIframes = new Array();
    this.targetId = false;
    this.activeSubItemsOnMouseOver = false;
    this.menuItemCssPrefix = false;
    this.createIframesForOldIeBrowsers = true;
    if (!standardObjectsCreated) 
        DHTMLSuite.createStandardObjects();
    
    
}





DHTMLSuite.menuBar.prototype = {

    // {{{ init()
    /**
     *	Initilizes the script
     *
     *
     * @public
     */
    init: function(){
    
        DHTMLSuite.commonObj.loadCSS(this.layoutCSS);
        this.__createDivs(); // Create general divs
        this.__createMenuItems(); // Create menu items
        this.__setBasicEvents(); // Set basic events.
        window.refToThismenuBar = this;
    }    // }}}
    ,
    // {{{ setTarget()
    /**
     *	Specify where this menu bar will be inserted. the element with this id will be parent of the menu bar.
     *
     *  @param String targetId = Id of element where the menu will be inserted.
     *
     * @public
     */
    setTarget: function(targetId){
        this.targetId = targetId;
        
    }    // }}}	
    ,
    // {{{ setLayoutCss()
    /**
     *	Specify the css file for this menu bar
     *
     *  @param String layoutCSS = Name of new css file.
     *
     * @public
     */
    setLayoutCss: function(layoutCSS){
        this.layoutCSS = layoutCSS;
        
    }    // }}}
    ,
    // {{{ setMenuItemLayoutCss()
    /**
     *	Specify the css file for the menu items
     *
     *  @param String layoutCSS = Name of new css file.
     *
     * @public
     */
    setMenuItemLayoutCss: function(layoutCSS){
        this.menuItemLayoutCss = layoutCSS;
        
    }    // }}}
    ,
    // {{{ setCreateIframesForOldIeBrowsers()
    /**
     *	This method specifies if you want to the script to create iframes behind sub menu groups in order to cover eventual select boxes. This
     *	can be needed if you have users with older IE browsers(prior to version 7) and when there's a chance that a sub menu could appear on top
     *	of a select box.
     *
     *  @param Boolean createIframesForOldIeBrowsers = true if you want the script to create iframes to cover select boxes in older ie browsers.
     *
     * @public
     */
    setCreateIframesForOldIeBrowsers: function(createIframesForOldIeBrowsers){
        this.createIframesForOldIeBrowsers = createIframesForOldIeBrowsers;
        
    }    // }}}
    ,
    // {{{ addMenuItems()
    /**
     *	Add menu items
     *
     *  @param DHTMLSuite.menuModel menuModel Object of class DHTMLSuite.menuModel which holds menu data
     *
     * @public
     */
    addMenuItems: function(menuItemObj){
        this.menuItemObj = menuItemObj;
        this.menuItems = menuItemObj.getItems();
    }    // }}}
    ,
    // {{{ setActiveSubItemsOnMouseOver()
    /**
     *	 Specify if sub menus should be activated on mouse over(i.e. no matter what the menuState property is).
     *
     *	@param Boolean activateSubOnMouseOver - Specify if sub menus should be activated on mouse over(i.e. no matter what the menuState property is).
     *
     * @public
     */
    setActiveSubItemsOnMouseOver: function(activateSubOnMouseOver){
        this.activeSubItemsOnMouseOver = activateSubOnMouseOver;
    }    // }}}
    ,
    // {{{ setMenuItemState()
    /**
     *	This method changes the state of the menu bar(expanded or collapsed). This method is called when someone clicks on the arrow at the right of menu items.
     *
     *	@param Number menuItemId - ID of the menu item we want to switch state for
     * 	@param String state - New state(example: "disabled")
     *
     * @public
     */
    setMenuItemState: function(menuItemId, state){
        this.menuItem_objects[menuItemId].setState(state);
    }    // }}}	
    ,
    // {{{ setMenuItemCssPrefix()
    /**
     *	Specify prefix of css classes used for the menu items. Default css prefix is "DHTMLSuite_". If you wish have some custom styling for some of your menus,
     *	create a separate css file and replace DHTMLSuite_ for the class names with your new prefix.  This is useful if you want to have two menus on the same page
     *	with different stylings.
     *
     *	@param String newCssPrefix - New css prefix for menu items.
     *
     * @public
     */
    setMenuItemCssPrefix: function(newCssPrefix){
        this.menuItemCssPrefix = newCssPrefix;
    }    // }}}
    ,
    // {{{ setCssPrefix()
    /**
     *	Specify prefix of css classes used for the menu bar. Default css prefix is "DHTMLSuite_" and that's the prefix of all css classes inside menu-bar.css(the default css file).
     *	If you want some custom menu bars, create and include your own css files, replace DHTMLSuite_ in the class names with your own prefix and set the new prefix by calling
     *	this method. This is useful if you want to have two menus on the same page with different stylings.
     *
     *	@param String newCssPrefix - New css prefix for the menu bar classes.
     *
     * @public
     */
    setCssPrefix: function(newCssPrefix){
        this.cssPrefix = newCssPrefix;
    }    // }}}
    ,
    // {{{ replaceSubMenus()
    /**
     *	This method replaces existing sub menu items with a new subset (To replace all menu items, pass 0 as parentId)
     *
     *
     *	@param Number parentId - ID of parent element ( 0 if top node) - if set, all sub elements will be deleted and replaced with the new menu model.
     *	@param menuModel newMenuModel - Reference to object of class menuModel
     *
     * @private
     */
    replaceMenuItems: function(parentId, newMenuModel){
        this.hideSubMenus(); // Hide all sub menus
        this.__deleteMenuItems(parentId); // Delete old menu items.
        this.menuItemObj.__appendMenuModel(newMenuModel, parentId); // Appending new menu items to the menu model.
        this.__clearAllMenuItems();
        this.__createMenuItems();
    }    // }}}	
    ,
    // {{{ deleteMenuItems()
    /**
     *	This method deletes menu items from the menu dynamically
     *
     *	@param Number parentId - Parent id - where to append the new items.
     *	@param Boolean includeParent - Should parent element also be deleted, or only sub elements?
     *
     * @public
     */
    deleteMenuItems: function(parentId, includeParent){
        this.hideSubMenus(); // Hide all sub menus
        this.__deleteMenuItems(parentId, includeParent);
        this.__clearAllMenuItems();
        this.__createMenuItems();
    }    // }}}	
    ,
    // {{{ appendMenuItems()
    /**
     *	This method appends menu items to the menu dynamically
     *
     *	@param Number parentId - Parent id - where to append the new items.
     *	@param menuModel newMenuModel - Object of type menuModel. This menuModel will be appended as sub elements of defined parentId
     *
     * @public
     */
    appendMenuItems: function(parentId, newMenuModel){
        this.hideSubMenus(); // Hide all sub menus
        this.menuItemObj.__appendMenuModel(newMenuModel, parentId); // Appending new menu items to the menu model.
        this.__clearAllMenuItems();
        this.__createMenuItems();
    }    // }}}	
    ,
    // {{{ hideMenuItem()
    /**
     *	This method doesn't delete menu items. it hides them only.
     *
     *	@param Number id - Id of the item you want to hide.
     *
     * @public
     */
    hideMenuItem: function(id){
        this.menuItem_objects[id].hide();
        
    }    // }}}	
    ,
    // {{{ showMenuItem()
    /**
     *	This method shows a menu item. If the item isn't hidden, nothing is done.
     *
     *	@param Number id - Id of the item you want to show
     *
     * @public
     */
    showMenuItem: function(id){
        this.menuItem_objects[id].show();
    }    // }}}
    ,
    // {{{ setText()
    /**
     *	Replace the text for a menu item
     *
     *	@param Integer id - Id of menu item.
     *	@param String newText - New text for the menu item.
     *
     * @public
     */
    setText: function(id, newText){
        this.menuItem_objects[id].setText(newText);
    }    // }}}
    ,
    // {{{ setIcon()
    /**
     *	Replace menu icon for a menu item.
     *
     *	@param Integer id - Id of menu item.
     *	@param String newPath - Path to new menu icon. Pass blank or false if you want to clear the menu item.
     *
     * @public
     */
    setIcon: function(id, newPath){
        this.menuItem_objects[id].setIcon(newPath);
    }    // }}}
    ,
    // {{{ __clearAllMenuItems()
    /**
     *	Delete HTML elements for all menu items.
     *
     * @private
     */
    __clearAllMenuItems: function(){
        for (var prop = 0; prop < this.menuItemObj.menuItemsOrder.length; prop++) {
            var id = this.menuItemObj.menuItemsOrder[prop];
            if (this.submenuGroups[id]) {
                this.submenuGroups[id].parentNode.removeChild(this.submenuGroups[id]);
                this.submenuGroups[id] = false;
            }
            if (this.submenuIframes[id]) {
                this.submenuIframes[id].parentNode.removeChild(this.submenuIframes[id]);
                this.submenuIframes[id] = false;
            }
        }
        this.menuBarObj.innerHTML = '';
    }    // }}}
    ,
    // {{{ __deleteMenuItems()
    /**
     *	This method deletes menu items from the menu, i.e. menu model and the div elements for these items.
     *
     *	@param Number parentId - Parent id - where to start the delete process.
     *
     * @private
     */
    __deleteMenuItems: function(parentId, includeParent){
        if (includeParent) 
            this.menuItemObj.__deleteANode(parentId);
        if (!this.submenuGroups[parentId]) 
            return; // No sub items exists.		
        this.menuItem_objects[parentId].__setHasSub(false); // Delete existing sub menu divs.
        this.menuItemObj.__deleteChildNodes(parentId); // Delete existing child nodes from menu model
        var groupBox = this.submenuGroups[parentId];
        groupBox.parentNode.removeChild(groupBox); // Delete sub menu group box. 
        if (this.submenuIframes[parentId]) {
            this.submenuIframes[parentId].parentNode.removeChild(this.submenuIframes[parentId]);
        }
        this.submenuGroups.splice(parentId, 1);
        this.submenuIframes.splice(parentId, 1);
    }    // }}}	
    ,
    // {{{ __changeMenuBarState()
    /**
     *	This method changes the state of the menu bar(expanded or collapsed). This method is called when someone clicks on the arrow at the right of menu items.
     *
     *	@param Object obj - Reference to element triggering the action
     *
     * @private
     */
    __changeMenuBarState: function(){
        var objectIndex = this.getAttribute('objectRef');
        var obj = DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects[objectIndex];
        var parentId = this.id.replace(/[^0-9]/gi, '');
        var state = obj.menuItem_objects[parentId].getState();
        if (state == 'disabled') 
            return;
        obj.menuBarState = !obj.menuBarState;
        if (!obj.menuBarState) 
            obj.hideSubMenus();
        else {
            obj.hideSubMenus();
            obj.__expandGroup(parentId);
        }
        
    }    // }}}		
    ,
    // {{{ __createDivs()
    /**
     *	Create the main HTML elements for this menu dynamically
     *
     *
     * @private
     */
    __createDivs: function(){
        window.refTomenuBar = this; // Reference to menu strip object
        this.menuBarObj = document.createElement('DIV');
        this.menuBarObj.className = this.cssPrefix + 'menuBar_' + this.menuItemObj.submenuType[1];
        
        if (!document.getElementById(this.targetId)) {
            alert('No target defined for the menu object');
            return;
        }
        // Appending menu bar object as a sub of defined target element.
        var target = document.getElementById(this.targetId);
        target.appendChild(this.menuBarObj);
    },
    // {{{ hideSubMenus()
    /**
     *	Deactivate all sub menus ( collapse and set state back to regular )
     *	In case you have a menu inside a scrollable container, call this method in an onscroll event for that element
     *	example document.getElementById('textContent').onscroll = menuBar.__hideSubMenus;
     *
     *	@param Event e - this variable is present if this method is called from an event.
     *
     * @public
     */
    hideSubMenus: function(e){
        if (this && this.tagName) { /* Method called from event */
            if (document.all) 
                e = event;
            var srcEl = DHTMLSuite.commonObj.getSrcElement(e);
            if (srcEl.tagName.toLowerCase() == 'img') 
                srcEl = srcEl.parentNode;
            if (srcEl.className && srcEl.className.indexOf('arrow') >= 0) {
                return;
            }
        }
        for (var no = 0; no < DHTMLSuite.variableStorage.menuBar_highlightedItems.length; no++) {
            DHTMLSuite.variableStorage.menuBar_highlightedItems[no].setState('regular'); // Set state back to regular
            DHTMLSuite.variableStorage.menuBar_highlightedItems[no].__hideGroup(); // Hide eventual sub menus
        }
        DHTMLSuite.variableStorage.menuBar_highlightedItems = new Array();
    },
    // {{{ __expandGroup()
    /**
     *	Expand a group of sub items.
     * 	@param parentId - Id of parent element
     *
     * @private
     */
    __expandGroup: function(parentId){
    
        var groupRef = this.submenuGroups[parentId];
        var subDiv = groupRef.getElementsByTagName('DIV')[0];
        
        var numericId = subDiv.id.replace(/[^0-9]/g, '');
        
        groupRef.style.visibility = 'visible'; // Show menu group.
        if (this.submenuIframes[parentId]) 
            this.submenuIframes[parentId].style.visibility = 'visible'; // Show iframe if it exists.
        DHTMLSuite.variableStorage.menuBar_highlightedItems[DHTMLSuite.variableStorage.menuBar_highlightedItems.length] = this.menuItem_objects[numericId];
        this.__positionSubMenu(parentId);
        
        if (DHTMLSuite.clientInfoObj.isOpera) { /* Opera fix in order to get correct height of sub menu group */
            var subDiv = groupRef.getElementsByTagName('DIV')[0]; /* Find first menu item */
            subDiv.className = subDiv.className.replace('_over', '_over'); /* By "touching" the class of the menu item, we are able to fix a layout problem in Opera */
        }
    },
    // {{{ __activateMenuElements()
    /**
     *	Traverse up the menu items and highlight them.
     *
     *
     * @private
     */
    __activateMenuElements: function(inputObj, objectRef, firstIteration){
        if (!this.menuBarState && !this.activeSubItemsOnMouseOver) 
            return; // Menu is not activated and it shouldn't be activated on mouse over.
        var numericId = inputObj.id.replace(/[^0-9]/g, ''); // Get a numeric reference to current menu item.
        var state = this.menuItem_objects[numericId].getState(); // Get state of this menu item.
        if (state == 'disabled') 
            return; // This menu item is disabled - return from function without doing anything.		
        if (firstIteration && DHTMLSuite.variableStorage.menuBar_highlightedItems.length > 0) {
            this.hideSubMenus(); // First iteration of this function=> Hide other sub menus. 
        }
        // What should be the state of this menu item -> If it's the one the mouse is over, state should be "over". If it's a parent element, state should be "active".
        var newState = 'over';
        if (!firstIteration) 
            newState = 'active'; // State should be set to 'over' for the menu item the mouse is currently over.
        this.menuItem_objects[numericId].setState(newState); // Switch state of menu item.
        if (this.submenuGroups[numericId]) { // Sub menu group exists. call the __expandGroup method. 
            this.__expandGroup(numericId); // Expand sub menu group
        }
        DHTMLSuite.variableStorage.menuBar_highlightedItems[DHTMLSuite.variableStorage.menuBar_highlightedItems.length] = this.menuItem_objects[numericId]; // Save this menu item in the array of highlighted elements.
        if (objectRef.menuItems[numericId].parentId) { // A parent element exists. Call this method over again with parent element as input argument.
            this.__activateMenuElements(objectRef.menuItem_objects[objectRef.menuItems[numericId].parentId].divElement, objectRef, false);
        }
    }    // }}}	
    ,
    // {{{ __createMenuItems()
    /**
     *	Creates the HTML elements for the menu items.
     *
     *
     * @private
     */
    __createMenuItems: function(){
        if (!this.globalObjectIndex) 
            this.globalObjectIndex = DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects.length;
        ;
        var index = this.globalObjectIndex;
        DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects[index] = this;
        
        // Find first child of the body element. trying to insert the element before first child instead of appending it to the <body> tag, ref: problems in ie
        var firstChild = false;
        var firstChilds = document.getElementsByTagName('DIV');
        if (firstChilds.length > 0) 
            firstChild = firstChilds[0]
        
        for (var no = 0; no < this.menuItemObj.menuItemsOrder.length; no++) { // Looping through menu items		
            var indexThis = this.menuItemObj.menuItemsOrder[no];
            if (!this.menuItems[indexThis].id) 
                continue;
            this.menuItem_objects[this.menuItems[indexThis].id] = new DHTMLSuite.menuItem();
            if (this.menuItemCssPrefix) 
                this.menuItem_objects[this.menuItems[indexThis].id].setCssPrefix(this.menuItemCssPrefix); // Custom css prefix set
            if (this.menuItemLayoutCss) 
                this.menuItem_objects[this.menuItems[indexThis].id].setLayoutCss(this.menuItemLayoutCss); // Custom css file name
            var ref = this.menuItem_objects[this.menuItems[indexThis].id].createItem(this.menuItems[indexThis]); // Create div for this menu item.
            // Actiave sub elements when someone moves the mouse over the menu item - exception: not on separators.
            if (!this.menuItems[indexThis].separator) 
                DHTMLSuite.commonObj.addEvent(ref, "mouseover", function(){
                    DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects[index].__activateMenuElements(this, DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects[index], true);
                });
            
            if (this.menuItem_objects[this.menuItems[indexThis].id].expandElement) { /* Small arrow at the right of the menu item exists - expand subs */
                var expandRef = this.menuItem_objects[this.menuItems[indexThis].id].expandElement; /* Creating reference to expand div/arrow div */
                var parentId = DHTMLSuite.variableStorage.arrayOfDhtmlSuiteObjects[index].menuItems[indexThis].parentId + ''; // Get parent id.
                var tmpId = expandRef.id.replace(/[^0-9]/gi, '');
                expandRef.setAttribute('objectRef', index); /* saving the index of this object in the DHTMLSuite.variableStorage array as a property of the tag - We need to do this in order to avoid circular references and thus memory leakage in IE */
                expandRef.objectRef = index;
                expandRef.onclick = this.__changeMenuBarState;
            }
            var target = this.menuBarObj; // Temporary variable - target of newly created menu item. target can be the main menu object or a sub menu group(see below where target is updated).
            if (this.menuItems[indexThis].depth == 1 && this.menuItemObj.submenuType[this.menuItems[indexThis].depth] != 'top' && this.menuItemObj.mainMenuGroupWidth) { /* Main menu item group width set */
                var tmpWidth = this.menuItemObj.mainMenuGroupWidth + '';
                if (tmpWidth.indexOf('%') == -1) 
                    tmpWidth = tmpWidth + 'px';
                target.style.width = tmpWidth;
            }
            
            if (this.menuItems[indexThis].depth == '1') { /* Top level item */
                if (this.menuItemObj.submenuType[this.menuItems[indexThis].depth] == 'top') { /* Type = "top" - menu items side by side */
                    ref.style.styleFloat = 'left';
                    ref.style.cssText = 'float:left';
                }
            }
            else {
                if (!this.menuItems[indexThis].depth) {
                    alert('Error in menu model(depth not defined for a menu item). Remember to call the init() method for the menuModel object.');
                    return;
                }
                if (!this.submenuGroups[this.menuItems[indexThis].parentId]) { // Sub menu div doesn't exist - > Create it.
                    this.submenuGroups[this.menuItems[indexThis].parentId] = document.createElement('DIV');
                    this.submenuGroups[this.menuItems[indexThis].parentId].style.zIndex = 10000;
                    this.submenuGroups[this.menuItems[indexThis].parentId].id = 'DHTMLSuite_menuBarSubGroup' + this.menuItems[indexThis].parentId;
                    this.submenuGroups[this.menuItems[indexThis].parentId].style.visibility = 'hidden'; // Initially hidden.
                    if (this.menuItemObj.submenuType[this.menuItems[indexThis].depth] == 'sub') 
                        this.submenuGroups[this.menuItems[indexThis].parentId].className = this.cssPrefix + 'menuBar_sub';
                    if (firstChild) {
                        firstChild.parentNode.insertBefore(this.submenuGroups[this.menuItems[indexThis].parentId], firstChild);
                    }
                    else {
                        document.body.appendChild(this.submenuGroups[this.menuItems[indexThis].parentId]);
                    }
                    
                    if (DHTMLSuite.clientInfoObj.isMSIE && this.createIframesForOldIeBrowsers) { // Create iframe object in order to conver select boxes in older IE browsers(windows).
                        this.submenuIframes[this.menuItems[indexThis].parentId] = document.createElement('<IFRAME src="about:blank" frameborder=0>');
                        this.submenuIframes[this.menuItems[indexThis].parentId].id = 'DHTMLSuite_menuBarIframe_' + this.menuItems[indexThis].parentId;
                        this.submenuIframes[this.menuItems[indexThis].parentId].style.position = 'absolute';
                        this.submenuIframes[this.menuItems[indexThis].parentId].style.zIndex = 9000;
                        this.submenuIframes[this.menuItems[indexThis].parentId].style.visibility = 'hidden';
                        if (firstChild) {
                            firstChild.parentNode.insertBefore(this.submenuIframes[this.menuItems[indexThis].parentId], firstChild);
                        }
                        else {
                            document.body.appendChild(this.submenuIframes[this.menuItems[indexThis].parentId]);
                        }
                    }
                }
                target = this.submenuGroups[this.menuItems[indexThis].parentId]; // Change target of newly created menu item. It should be appended to the sub menu div("A group box").				
            }
            target.appendChild(ref); // Append menu item to the document.		
            if (this.menuItems[indexThis].visible == false) 
                this.hideMenuItem(this.menuItems[indexThis].id); // Menu item hidden, call the hideMenuItem method.
            if (this.menuItems[indexThis].state != 'regular') 
                this.menuItem_objects[this.menuItems[indexThis].id].setState(this.menuItems[indexThis].state); // Menu item hidden, call the hideMenuItem method.
        }
        
        
        this.__setSizeOfAllSubMenus(); // Set size of all sub menu groups
        this.__positionAllSubMenus(); // Position all sub menu groups.
        if (DHTMLSuite.clientInfoObj.isOpera) 
            this.__fixLayoutOpera(); // Call a function which fixes some layout issues in Opera.		
    }    // }}}
    ,
    // {{{ __fixLayoutOpera()
    /**
     *	A method used to fix the menu layout in Opera.
     *
     *
     * @private
     */
    __fixLayoutOpera: function(){
        for (var no = 0; no < this.menuItemObj.menuItemsOrder.length; no++) {
            var id = this.menuItemObj.menuItemsOrder[no];
            if (!id) 
                continue;
            this.menuItem_objects[id].divElement.className = this.menuItem_objects[id].divElement.className.replace('_regular', '_regular'); // Nothing is done but by "touching" the class of the menu items in Opera, we make them appear correctly
        }
    }    // }}}	
    ,
    // {{{ __setSizeOfAllSubMenus()
    /**
     *	*	Walk through all sub menu groups and call the positioning method for each one of them.
     *
     *
     * @private
     */
    __setSizeOfAllSubMenus: function(){
        for (var prop in this.submenuGroups) {
            this.__setSizeOfSubMenus(prop);
        }
    }    // }}}	
    ,
    // {{{ __positionAllSubMenus()
    /**
     *	Walk through all sub menu groups and call the positioning method for each one of them.
     *
     *
     * @private
     */
    __positionAllSubMenus: function(){
        for (var prop in this.submenuGroups) {
            this.__positionSubMenu(prop);
        }
        
    }    // }}}	
    ,
    // {{{ __positionSubMenu(parentId)
    /**
     *	Position a sub menu group
     *
     *	@param parentId
     *
     * @private
     */
    __positionSubMenu: function(parentId){
        try {
            var shortRef = this.submenuGroups[parentId];
            
            var depth = this.menuItems[parentId].depth;
            var dir = this.menuItemObj.submenuType[depth];
            if (dir == 'top') {
                shortRef.style.left = DHTMLSuite.commonObj.getLeftPos(this.menuItem_objects[parentId].divElement) + 'px';
                shortRef.style.top = (DHTMLSuite.commonObj.getTopPos(this.menuItem_objects[parentId].divElement) + this.menuItem_objects[parentId].divElement.offsetHeight) + 'px';
            }
            else {
                shortRef.style.left = (DHTMLSuite.commonObj.getLeftPos(this.menuItem_objects[parentId].divElement) + this.menuItem_objects[parentId].divElement.offsetWidth) + 'px';
                shortRef.style.top = (DHTMLSuite.commonObj.getTopPos(this.menuItem_objects[parentId].divElement)) + 'px';
            }
            
            if (DHTMLSuite.clientInfoObj.isMSIE) {
                var iframeRef = this.submenuIframes[parentId]
                iframeRef.style.left = shortRef.style.left;
                iframeRef.style.top = shortRef.style.top;
                iframeRef.style.width = shortRef.clientWidth + 'px';
                iframeRef.style.height = shortRef.clientHeight + 'px';
            }
            
        } 
        catch (e) {
        
        }
    }    // }}}	
    ,
    // {{{ __setSizeOfSubMenus(parentId)
    /**
     *	Set size of a sub menu group
     *
     *	@param parentId
     *
     * @private
     */
    __setSizeOfSubMenus: function(parentId){
        try {
            var shortRef = this.submenuGroups[parentId];
            var subWidth = Math.max(shortRef.offsetWidth, this.menuItem_objects[parentId].divElement.offsetWidth);
            if (this.menuItems[parentId].submenuWidth) 
                subWidth = this.menuItems[parentId].submenuWidth;
            subWidth = subWidth + '';
            if (subWidth.indexOf('%') == -1) 
                subWidth = subWidth + 'px';
            shortRef.style.width = subWidth;
            
            if (DHTMLSuite.clientInfoObj.isMSIE) {
                this.submenuIframes[parentId].style.width = shortRef.style.width;
                this.submenuIFrames[parentId].style.height = shortRef.style.height;
            }
        } 
        catch (e) {
        
        }
        
    }    // }}}	
    ,
    // {{{ __repositionMenu()
    /**
     *	Position menu items.
     *
     *
     * @private
     */
    __repositionMenu: function(inputObj){
        // self.status = this;
        inputObj.menuBarObj.style.top = document.documentElement.scrollTop + 'px';
        
    }    // }}}	
    ,
    // {{{ __menuItemRollOver()
    /**
     *	Position menu items.
     *
     *
     * @private
     */
    __menuItemRollOver: function(inputObj){
        var numericId = inputObj.id.replace(/[^0-9]/g, '');
        inputObj.className = 'DHTMLSuite_menuBar_menuItem_over_' + this.menuItems[numericId]['depth'];
    }    // }}}	
    ,
    // {{{ __menuItemRollOut()
    /**
     *	Position menu items.
     *
     *
     * @private
     */
    __menuItemRollOut: function(inputObj){
        var numericId = inputObj.id.replace(/[^0-9]/g, '');
        inputObj.className = 'DHTMLSuite_menuBar_menuItem_' + this.menuItems[numericId]['depth'];
    }    // }}}	
    ,
    // {{{ __menuNavigate()
    /**
     *	Navigate by click on a menu item
     *
     *
     * @private
     */
    __menuNavigate: function(inputObj){
        var numericIndex = inputObj.id.replace(/[^0-9]/g, '');
        var url = this.menuItems[numericIndex]['url'];
        if (!url) 
            return;
        alert(this.menuItems[numericIndex]['url']);
        
    }    // }}}	
    ,
    // {{{ __setBasicEvents()
    /**
     *	Set basic events for the menu widget.
     *
     *
     * @private
     */
    __setBasicEvents: function(){
        DHTMLSuite.commonObj.addEvent(document.documentElement, "click", this.hideSubMenus);
    }
}


//Context Menu

var contextMenuObj;
var MSIE = navigator.userAgent.indexOf('MSIE') ? true : false;
var navigatorVersion = navigator.appVersion.replace(/.*?MSIE (\d\.\d).*/g, '$1') / 1;
var activeContextMenuItem = false;
function highlightContextMenuItem(){
    this.className = 'contextMenuHighlighted';
}

function deHighlightContextMenuItem(){
    this.className = '';
}

function showContextMenu(e){
    if (activeContextMenuItem) 
        activeContextMenuItem.className = '';
    if (document.all) 
        e = event;
    contextMenuObj.style.display = 'block';
    var xPos = e.clientX;
    if (xPos + contextMenuObj.offsetWidth > (document.documentElement.offsetWidth - 20)) {
        xPos = xPos + (document.documentElement.offsetWidth - (xPos + contextMenuObj.offsetWidth)) - 20;
    }
    
    var yPos = e.clientY;
    if (yPos + contextMenuObj.offsetHeight > (document.documentElement.clientHeight - 20)) {
        yPos = yPos + (document.documentElement.clientHeight - (yPos + contextMenuObj.offsetHeight)) - 20;
    }
    contextMenuObj.style.left = xPos + 'px';
    contextMenuObj.style.top = yPos + 'px';
    
    return false;
}

function hideContextMenu(e){
    if (document.all) 
        e = event;
    if (e.button == 0 && !MSIE) {
    
    }
    else {
        contextMenuObj.style.display = 'none';
    }
}

function initContextMenu(){
    contextMenuObj = document.getElementById('contextMenu');
    contextMenuObj.style.display = 'block';
    var menuItems = contextMenuObj.getElementsByTagName('LI');
    for (var no = 0; no < menuItems.length; no++) {
        menuItems[no].onmouseover = highlightContextMenuItem;
        menuItems[no].onmouseout = deHighlightContextMenuItem;
        
        var aTag = menuItems[no].getElementsByTagName('A')[0];
        
        var img = menuItems[no].getElementsByTagName('IMG')[0];
        if (img) {
            var div = document.createElement('DIV');
            div.className = 'imageBox';
            div.appendChild(img);
            
            if (MSIE && navigatorVersion < 6) {
                aTag.style.paddingLeft = '0px';
            }
            
            var divTxt = document.createElement('DIV');
            divTxt.className = 'itemTxt';
            divTxt.innerHTML = aTag.innerHTML;
            
            aTag.innerHTML = '';
            aTag.appendChild(div);
            aTag.appendChild(divTxt);
            if (MSIE && navigatorVersion < 6) {
                div.style.position = 'absolute';
                div.style.left = '2px';
                divTxt.style.paddingLeft = '15px';
            }
            
            if (!document.all) {
                var clearDiv = document.createElement('DIV');
                clearDiv.style.clear = 'both';
                aTag.appendChild(clearDiv);
            }
        }
        else {
            if (MSIE && navigatorVersion < 6) {
                aTag.style.paddingLeft = '15px';
                aTag.style.width = (aTag.offsetWidth - 30) + 'px';
            }
            else {
                aTag.style.paddingLeft = '30px';
                aTag.style.width = (aTag.offsetWidth - 60) + 'px';
            }
        }
    }
    contextMenuObj.style.display = 'none';
    document.documentElement.oncontextmenu = showContextMenu;
    document.documentElement.onclick = hideContextMenu;
}
