/// MarkerClass ///

function MarkerClass(lng,lat,id) {
	this.lng=lng;
	this.lat=lat;
	this.id =id;
	this.icontype='';
	if(arguments.length>3){ this.icontype=arguments[3]; }
	this.label;
	this.toolkit;
	if(arguments.length>4){
		this.label=arguments[4];
		this.tooltip = '<div class="tooltip">'+this.label+'</div>';
	}
	this.infowin;
	if(arguments.length>5){this.infowin=arguments[5];}
	this.markerInstance;
	this.labelObj;
	this.labelOpacity = 80;
}

MarkerClass.prototype.showLabel=function(marker) {
//alert('show');
                    if ($('#map_message').is(':hidden')) {//Allow toggling of markers
                        $('#map_message').fadeIn();
                    }
                    else{//Remove all .active classes and hide markers
                        $('#map_message').hide();
                        $(".active").removeClass();
                    }
                    //$("#map_message").hide();//Default behaviour, doesn't allow toggling

                    var markerOffset = myMapClass.map.fromLatLngToDivPixel(new GLatLng(marker.lat, marker.lng));
                        //marker.getLatLng());
                        //new GLatLng(marker.lat, marker.lng));
                        //new GLatLng(marker.lat, marker.lng));
                        $("#map_message")
                            .html(marker.infowin) //markers[index][2])//Use information from array
                            .fadeIn()
                            .css({ top:markerOffset.y, left:markerOffset.x });

                    if (0) {
                    var moveEnd = GEvent.addListener(myMapClass.map, "moveend", function(){
                        //var abc=this.getLatLng();
                        //alert(this);
                        var markerOffset = myMapClass.map.fromLatLngToDivPixel(new GLatLng(marker.lat, marker.lng));
                        //marker.getLatLng());
                        //new GLatLng(marker.lat, marker.lng));
                        $("#map_message")
                            .html(marker.infowin) //markers[index][2])//Use information from array
                            .fadeIn()
                            .css({ top:markerOffset.y, left:markerOffset.x });
                        GEvent.removeListener(moveEnd);
                    });
                    myMapClass.map.panTo(this.markerInstance.getLatLng());
                    }

}

MarkerClass.prototype.hideLabel=function() {
//alert('hide');
	//if (typeof this.labelObj != "undefined" ) {
	//	this.labelObj.style.display = "none";
	//}
	//this.tooltip.style.visibility="hidden";
}

MarkerClass.prototype.doclick=function() {
	GEvent.trigger(this.markerInstance,'click');
}

/// MapClass ///

var mapInstance;
var place=$("#place_for_some_inserts");

function MapClass(trackback, extparam, divid) {
	mapInstance = this;
	this.trackbackurl=trackback;
	this.extparam=extparam;
	this.map = new GMap2(document.getElementById(divid));
	this.map.addControl(new GLargeMapControl());
	this.map.addControl(new GMapTypeControl());
	this.allMarkers = new Array();
	this.gicons = new Array();
    this.gicons[""] = new GIcon(G_DEFAULT_ICON, "/themes/lofty/img/map/iconb.png");
	this.gicons["blue"] = new GIcon(G_DEFAULT_ICON, "/themes/lofty/img/map/iconb.png");
    this.gicons["green"] = new GIcon(G_DEFAULT_ICON, "/themes/lofty/img/map/icong.png");

	//for google center zoom
	this.bounds = new GLatLngBounds();
	GEvent.addListener(this.map, "moveend", function() { mapInstance.moveend(); });
	GEvent.addListener(this.map, "zoomend", function(oldLevel, newLevel) { mapInstance.zoomend(oldLevel, newLevel); });
	GEvent.addListener(this.map, "click", function(marker, point) { mapInstance.click(marker, point); });
}

MapClass.prototype.addMarker=function(marker) {
	if (typeof this.allMarkers[marker.id]!="undefined") return false;
	var latlng = new GLatLng(marker.lat, marker.lng)
	//for google center zoom
	this.bounds.extend(latlng);

    var iconOptions = {};
    iconOptions.width = 32;
    iconOptions.height = 32;
    if (marker.icontype.substring(0,2) == 'r-') {
        iconOptions.primaryColor = "#FF0000";
    } else if (marker.icontype.substring(0,2) == 'b-') {
        iconOptions.primaryColor = "#0000FF";
    }
    iconOptions.label = marker.icontype.substring(2);
    iconOptions.labelSize = 0;
    iconOptions.labelColor = "#000000";
    iconOptions.shape = "roundrect";
    var newIcon = MapIconMaker.createFlatIcon(iconOptions);

	var markee =  new GMarker(latlng, {icon: newIcon});// this.gicons[marker.icontype] //, icon);
	marker.markerInstance= markee;
	GEvent.addListener(markee, 'click', function() {
		marker.hideLabel();
		markee.openInfoWindowHtml(marker.infowin,{maxWidth:100});
		//alert("E:aaaa");
		//itemclick(marker.id, marker.lat, marker.lng);
		});
	GEvent.addListener(markee, 'mouseover', function(){ marker.showLabel(marker) });
	GEvent.addListener(markee, 'mouseout', function(){ marker.hideLabel() });
	this.map.addOverlay(markee);
	this.allMarkers[marker.id]=markee;
}

MapClass.prototype.itemclick=function(id, y, x) {
	//var xmlfile = this.trackbackurl+'?action=clicked'+'&id=' + id + '&xclicked=' + x + '&yclicked=' + y + '&' + geturlproperties()+this.extparam;
	//this.processrequest(xmlfile, true);
}

MapClass.prototype.removeclick=function(marker) {
	if (!marker.point) {
		market.point = market.getPoint();
	}
	var xmlfile = this.trackbackurl+'?action=removeclicked'+ '&id='+ 'new' + '&xclicked=' + marker.point.x + '&yclicked=' + marker.point.y + '&' + this.geturlproperties()+this.extparam;
	this.processrequest(xmlfile, true);
}

MapClass.prototype.processXMLnode=function(marker) {
	if (marker.getAttribute("type") == "alert") {
		alert(marker.getAttribute("alert"));
	}
	if (marker.getAttribute("type") == "point") {
		markey = new MarkerClass(parseFloat(marker.getAttribute("x")),parseFloat(marker.getAttribute("y")),marker.getAttribute("id"),marker.getAttribute("icon"),marker.getAttribute("prc"),marker.getAttribute("info"));
		//mapMarkers.push(markey);
		this.addMarker(markey);
	};
	if (marker.getAttribute("type") == "trace") {
		var pointspolyline = [];
		var markers = marker.getElementsByTagName("point");
		for (var i = 0; i < markers.length; i++) {
			pointspolyline.push(loadPoint(markers[i]));
		}
		var trace = new GPolyline(pointspolyline,
			marker.getAttribute("color"),
			parseFloat(marker.getAttribute("weight")),
			parseFloat(marker.getAttribute("opacity"))
		);
		this.map.addOverlay(trace);
		lasttrace = trace;
	}
	if (marker.getAttribute("type") == "clear") {
		//clean markers
		this.allMarkers.length=0;
		//clean google center zoom
		this.bounds = new GLatLngBounds();
		this.map.clearOverlays();
	}
	if (marker.getAttribute("type") == "center") {
		//for google center zoom
		var clat = (this.bounds.getNorthEast().lat() + this.bounds.getSouthWest().lat()) /2;
		var clng = (this.bounds.getNorthEast().lng() + this.bounds.getSouthWest().lng()) /2;
		var zoom = this.map.getBoundsZoomLevel(this.bounds)
		this.map.setCenter(new GLatLng(clat,clng), zoom);
	}
	if (marker.getAttribute("type") == "clearlasttrace") {
		this.map.removeOverlay(lasttrace);
	}
	if (marker.getAttribute("type") == "setcenter") {
		this.map.setCenter(new GLatLng(parseFloat(marker.getAttribute("y")), parseFloat(marker.getAttribute("x"))), parseFloat(marker.getAttribute("zl")));
	}
	if (marker.getAttribute("type") == "info") {
		document.getElementById(marker.getAttribute("id")).innerHTML = marker.getAttribute("text");
	}
}

MapClass.prototype.processxmlDoc=function(xmlDoc) {
	var markers = xmlDoc.documentElement.getElementsByTagName("data");
	markerstoadd = [];

	for (var i = 0; i < markers.length; i++) { // er"<"erg<>
		this.processXMLnode(markers[i]);
	}
}

MapClass.prototype.processrequest=function(url, async) {
	request = GXmlHttp.create();

	if (async) {
		request.onreadystatechange = function() {
				//alert("C:"+":"+request.responseText+":"+request.readyState);
				if (request.readyState == 4) {
					//alert("A:"+":"+request.responseText);        	////////
					mapInstance.processxmlDoc(request.responseXML);
				}
			}
		request.open("GET", url, async);
		request.send(null);
	} else {
		request.open("GET", url, async);
		request.send(null);
		this.processxmlDoc(request.responseXML);
	}
}

MapClass.prototype.modified=function(actionmade, async) {
	var xmlfile = this.trackbackurl+'?action='+actionmade+'&'+this.geturlproperties()+this.extparam;
	this.processrequest(xmlfile, async);
}

MapClass.prototype.moveend=function() {
	//alert("1:moveend");
	//this.modified('moveend', true);
	//alert("2:moveend");
}

MapClass.prototype.click=function(marker, point) {
	//if (marker)
		//document.getElementById('info').innerHTML = marker;
	if (point)
		document.getElementById('info').innerHTML = point;
	//alert("1:click"+marker+';'+point);
	this.modified('click', true);
	//alert("2:click");
}

MapClass.prototype.zoomend=function(oldLevel, newLevel) {
	//alert("1:zoomend");
	//this.modified('zoomend', true);
	//alert("2:zoomend");
}

MapClass.prototype.geturlproperties=function() {
	 var res = '';
	 //alert("1:getproperties");
	 if (this.map.isLoaded()) {
	 	//alert("2:getproperties");
	 	var bounds = this.map.getBounds();
	 	//alert("3:getproperties");
	 	res = 'sw=' + bounds.getSouthWest().toUrlValue() + '&ne=' + bounds.getNorthEast().toUrlValue();
	 	res = res + '&c=' + this.map.getCenter().toUrlValue();
	 	//alert("7:getproperties");
	 	res = res + '&z=' + this.map.getZoom();
	 	//alert("8:getproperties");
	 }
	 //alert("9:getproperties");
	 return res;
}

MapClass.prototype.initmap=function() {
	//modified('initsync', false);
	this.modified('initasync', true);
}

function search_item() {
	//alert('start');
	var f = document.forms["SEARCH_FORM"];
	document.getElementById('info').innerHTML = "Searching...";
	var showmap = document.getElementById("maplist").checked;
	if (showmap) {
		//alert("make request");
		makerequest();
		return false;
	} else {
		f.action = "list.php?action=search"+myMapClass.extparam+'&'+searchparam();
		//alert("make submit: "+f.action);
		f.submit();
		return true;
	}
	//alert('end');
}

function searchparam() {
    $('#map_message').hide();
	var pricemin = document.getElementById("pricemin").value;
	var pricemax = document.getElementById("pricemax").value;
	var bedrm = document.getElementById("bedrm").selectedIndex;
	var parking = document.getElementById("parking").selectedIndex;
	var pets = document.getElementById("pets").selectedIndex;
	var lnew = document.getElementById("lnew").value;
	SetCookie('pricemin_cookie',pricemin);
	SetCookie('pricemax_cookie',pricemax);
    var extra = '';
    if(document.getElementById("neighbourhood") !== null) {
        extra += '&neighbourhood=' + document.getElementById("neighbourhood").value;
    }
    if(document.getElementById("bathrm") !== null) {
        extra += '&bathrm=' + document.getElementById("bathrm").selectedIndex;
    }
	return 'pricemin='+pricemin+'&pricemax='+pricemax+'&bedrm='+bedrm+extra+'&parking='+parking+'&pets='+pets+'&lnew='+lnew;
}

function makerequest() {
	var urltext = searchparam();

	var actionmade='search';
	var async=true;
	var xmlfile = myMapClass.trackbackurl+'?action='+actionmade+'&'+urltext+this.extparam;
	//alert(xmlfile);
	myMapClass.processrequest(xmlfile, async);
}

function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)+";expires="+expire.toGMTString();
}

/***** popup ****/
var close_layer = function() {
	$("#nl_frame, #nl_shadow").remove();
}
//-------
var cursor_pointer = function() {
	$(this).css('cursor','pointer');
}

function qwe(id) {
    $("#place_for_some_inserts").html('<div id="nl_shadow" style="opacity:0.6; background-color:black; width:100%; height:1200px; position:absolute; top:0px; left:0px;"></div>'+
            '<div id="nl_frame" style="z-order:9;height:65.4em; width:60em; margin-left:0px; border:1px solid #396D93; background-color:white; position:relative; top:-36em; left:0em; background-color:#F8F8F8;">'+
                '<div id="nl_frame_top_line" style="background-color: lightBlue; border:1px solid #396D93; color:white; padding:3px 1px 3px 7px;">'+
                    '<b>Details</b></div>'+
                '<div id="nl_frame_x" style="position:relative; left:57.8em; top:-23px; color:white; border:1px solid white; width:23px; padding:0px 0px 0px 2px;">'+
                    '<CENTER><b>X</b></CENTER>'+
                '</div>'+
                '<CENTER style="margin-top: -3em;"><div id="place_for_detail"></div></CENTER>'+
            '</div>');
    $("#place_for_detail").load(id);
    $("#nl_shadow, #nl_frame_x").click(close_layer);
    $("#nl_shadow, #nl_frame_x").mouseover(cursor_pointer);
    //return false;
}

function wer(id) {
    var place=$("#place_for_some_inserts");
    place.load(id);
}