/* $Id: map_search.js,v 1.6 2011/03/19 05:13:48 hetal Exp $ */

function sendMapRequest(ulLat,ulLng,brLat,brLng,zoomLevel)
{
	isCatch=true;
	var urlStr='';

	//  get request from database and show loading text
	pendingRequestCount--;
	isRunning = true;
	showLoadingText();

	urlStr=getUrl(ulLat,ulLng,brLat,brLng,zoomLevel);

	/** To check if First time map load then no need add hash */
	if(isFirstTime) {
		isFirstTime = false;
	}
	else {
		document.location.hash=urlStr;
	}
	for(var i=0;i<arrCatchUrl.length;i++)
	{
		/** Check if request is already in catch then get data from array */

		if(arrCatchUrl[i] == urlStr)
		{
			isCatch=false;
			getDataCallback(arrCatchUrlValue[i]); // pass the data from catch
			return false;
		}
	}

	/** To check if isCatch is true then send request to server */
	if(isCatch)
	{
		arrCatchUrl[arrCatchUrl.length+0]=urlStr;
		xmlHttp=GXmlHttp.create();
		xmlHttp.open("POST",location.protocol+'//'+location.hostname+'/getCoordinate.php', true);
		xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xmlHttp.send(urlStr);
		xmlHttp.onreadystatechange = function() {
				if (xmlHttp.readyState == 4)
				{
					var response = xmlHttp.responseXML.documentElement;

					/** Cache the respone into array */
					arrCatchUrlValue[arrCatchUrl.length-1]=response;

					if(xmlHttp.responseText == "not")
						return;
					else
						getDataCallback(response);

					delete response;
				}
		}
	}
}

function getDataCallback(response)
{
	if(lastOpenWindow[0] == '')
		map.clearOverlays();

	lastOpenWindow[0]='';

	rows = response.getElementsByTagName("Marker");
	for(var i=0;i<rows.length;i++)
	{
		markerOptions='';

		adId = rows[i].getElementsByTagName("adId")[0].childNodes[0].nodeValue;

		if(rows[i].getElementsByTagName("adType")[0])
		{
			adType = rows[i].getElementsByTagName("adType")[0].childNodes[0].nodeValue;
			markerOptions = { icon:icons[adType] };
		}

		currLatitude = rows[i].getElementsByTagName("lat")[0].childNodes[0].nodeValue;
		currLongitude = rows[i].getElementsByTagName("lng")[0].childNodes[0].nodeValue;
		showDetail=rows[i].getElementsByTagName("showDetail")[0].childNodes[0].nodeValue;

		// replace #euro# to euro sign
		showDetail = showDetail.replace(/#euro#/g,'€');
		point=new GLatLng(currLatitude,currLongitude);
		markerData = createMapMarker(point,adId,showDetail,markerOptions);
		map.addOverlay(markerData);
	}

	if(pendingRequestCount == 0) {
		hideLoadingText();
	}
	isRunning = false;
}

var lastOpenWindow = [];

function createMapMarker(point,adId,showDetail,option)
{
	var marker = new GMarker(point,option);
	var markerHtmlData="<div id=\"map_marker\"><ul>" + showDetail + "</ul></div>";
	marker.tooltip = "<div id=\"map_tooltip\">"+markerHtmlData+"</div>";

	GEvent.addListener(marker, "mouseover", function() {
		showTooltip(marker);
		//marker.openInfoWindowHtml(markerHtmlData);
	});
	GEvent.addListener(marker, "mouseout", function() {
		//marker.closeInfoWindow();
		if(document.getElementById('hideShowTooltip'))
		    document.getElementById('hideShowTooltip').style.visibility="hidden";
	});
	GEvent.addListener(marker, "click", function() {
		if(document.getElementById('hideShowTooltip'))
		    document.getElementById('hideShowTooltip').style.visibility="hidden";
		marker.openInfoWindowHtml(markerHtmlData,getOpenInfoWindow(adId));
	});
	return marker;
}

// ====== This function displays the tooltip ======
function showTooltip(marker)
{
	tooltip=document.getElementById('hideShowTooltip');
	tooltip.innerHTML = marker.tooltip;

	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y));
	pos.apply(tooltip);

	tooltip.style.visibility="visible";
}

function getOpenInfoWindow(adId)
{
	lastOpenWindow[0] = adId;
}

/** To check request is running or not */
var isRunning=false;

function chkUpdater()
{

	/** To check if First time map loaded then no need to send request */
	if(isFirstTime) {
		return false;
	}

	/** To check if request is running */
	if(pendingRequestCount > 0){
		// already request is running
	} else {
		pendingRequestCount++;
		chkRequest();
	}
}

function chkRequest()
{
	// To check if request is running then wait and again check after specified time
	if(isRunning) {
		window.setTimeout("chkRequest()", 100);
	} else {
		sendMapRequest();
	}
}

function showLoadingText()
{
    document.getElementById('loadingText').style.display = "block";
}

function hideLoadingText()
{
    document.getElementById('loadingText').style.display = "none";
}

mapFull=true;
function mapResize(imgUrl)
{
	if(mapFull)
	{
		mapFull=false;
		document.getElementById('right_nav').style.display='none';
		document.getElementById('largeMap').style.position='absolute';
		document.getElementById('content_size').style.width='97%';
		document.getElementById('mapbluebox').style.height='660px';
	    document.getElementById('largeMap').style.width=jQuery('#content_size').width() - 205 + 'px';
        document.getElementById('map_canvas').style.width=jQuery('#content_size').width() - 230 + 'px';
        document.getElementById('loadingText').style.left=jQuery('#content_size').width() - 430 + 'px';

		document.getElementById('map_canvas').style.height='600px';

		document.getElementById('loadingText').style.top= -570 + 'px';
		document.getElementById('zoomImg').src=imgUrl+'/zoom_out.gif';
	}
	else
	{
		mapFull=true;
		document.getElementById('right_nav').style.display='';
		document.getElementById('largeMap').style.position='';
		document.getElementById('content_size').style.width='76em';
		document.getElementById('mapbluebox').style.height='560px';
		document.getElementById('largeMap').style.width='auto';
		document.getElementById('map_canvas').style.width='540px';
		document.getElementById('map_canvas').style.height='500px';
		document.getElementById('loadingText').style.left='340px';
		document.getElementById('loadingText').style.top= -470 + 'px';
		document.getElementById('zoomImg').src=imgUrl+'/zoom_in.gif';
	}

	var bounds = map.getBounds();
	ul=bounds.getSouthWest();
	br=bounds.getNorthEast();
	map_load(ul.lat(),ul.lng(),br.lat(),br.lng(),map.getZoom());
}
var map;
var xmlHttp;
var pendingRequestCount = 0;
var defaultLatitude=60.171574;
var defaultLongitude=24.937592;
var minZoomLevel=8;
var maxZoomLevel=16;
var defaultZoomLevel=12;
arrCatchUrl = [];
arrCatchUrlValue = [];
var isFirstTime=true;
var latTownId;
var map_category='S';
var ulLat,ulLng,brLat,brLng,zoomLevel,sel_map_town;

hash=location.hash;
hash=hash.substr(1); // remove # sign
if (location.hostname.match(/nettiasunto/i))
{
    /** For check selected value in selction box */
    var sel_map_town='',sel_map_domicile='',sel_map_area_from='',sel_map_area_to='',sel_map_price_from='',sel_map_price_to='';

    jQuery(document).ready(function(){
        if(hash.length > 0)
        {
            hashValue=hash.split("&");
            for(var i=0;i<hashValue.length;i++)
            {
                getValue=hashValue[i].split("=");
                switch(getValue[0])
                {
                    case "ulLat":
                        ulLat=getValue[1];
                    case "ulLng":
                        ulLng=getValue[1];
                    case "brLat":
                        brLat=getValue[1];
                    case "brLng":
                        brLng=getValue[1];
                    case "zoomLevel":
                        zoomLevel=getValue[1];

                    case "map_category":
                        map_category=getValue[1];
                        if(getValue[1] == "S")
                            document.frmMap.map_category[0].checked=true;
                        else
                            document.frmMap.map_category[1].checked=true;
                        break;
                    case "map_domicile":
                        sel_map_domicile=getValue[1];
                        break;
                    case "map_town":
                        sel_map_town=getValue[1]
                        break;
                    case "map_sub_type":
                        chkOptValue("map_sub_type",getValue[1]);
                        break;
                    case "map_building_year_from":
                        chkOptValue("map_building_year_from",getValue[1]);
                        break;
                    case "map_building_year_to":
                        chkOptValue("map_building_year_to",getValue[1]);
                        break;
                    case "map_area_from":
                        chkOptValue("map_area_from",getValue[1]);
                        sel_map_area_from=getValue[1];
                        break;
                    case "map_area_to":
                        sel_map_area_to=getValue[1];
                        break;
                    case "map_price_from":
                        chkOptValue("map_price_from",getValue[1]);
                        sel_map_price_from=getValue[1];
                        break;
                    case "map_price_to":
                        sel_map_price_to=getValue[1];
                        break;
                    case "map_no_room":
                        roomVal=getValue[1].split(",");
                        for(var j=0;j<roomVal.length;j++)
                        {
                            chkOptValue("map_no_room",roomVal[j]);
                        }
                        break;
                }
            }
        }
        if(sel_map_area_from)
        {
            areaFromChange(3,'S',C_AREA_TO,sel_map_area_from,document.getElementById('map_area_to'));
            if(sel_map_area_to)
                chkOptValue("map_area_to",sel_map_area_to);
        }
    });
}
else // mokki
{
    var sel_price_opt='',sel_price_from='',sel_price_to='',sel_map_town='',sel_map_domicile='',sel_map_area_from='',sel_map_area_to='',sel_map_price_from='',sel_map_price_to='';
    jQuery(document).ready(function(){
    if(hash.length > 0)
    {
        hashValue=hash.split("&");
        for(var i=0;i<hashValue.length;i++)
        {
            getValue=hashValue[i].split("=");
            switch(getValue[0])
            {
                case "ulLat":
                    ulLat=getValue[1];
                case "ulLng":
                    ulLng=getValue[1];
                case "brLat":
                    brLat=getValue[1];
                case "brLng":
                    brLng=getValue[1];
                case "zoomLevel":
                    zoomLevel=getValue[1];
                case "map_price_opt":
                    sel_price_opt=getValue[1];
                case "map_price_from":
                    sel_price_from=getValue[1];
                case "map_price_to":
                    sel_price_to=getValue[1];
                case "map_domicile":
                    sel_map_domicile=getValue[1];
                    break;
                case "map_town":
                    sel_map_town=getValue[1]
                    break;
                case "map_price_from":
                    chkOptValue("map_price_from",getValue[1]);
                    sel_map_price_from=getValue[1];
                    break;
                case "map_price_to":
                    sel_map_price_to=getValue[1];
                    break;
                case "map_no_room":
                    roomVal=getValue[1].split(",");
                    for(var j=0;j<roomVal.length;j++)
                    {
                        chkOptValue("map_no_room",roomVal[j]);
                    }
                    break;
            }
        }
    }

        dateChange(document.frmMap.map_dateFrom,document.frmMap.map_dateTo,'');
        newPriceCombo(document.frmMap.map_price_opt,document.frmMap.map_price_from,document.frmMap.map_price_to,V_P_FROM,V_P_TO,C_PRICE_FROM,C_PRICE_TO);
        berthsCmbVal(document.frmMap.map_berthsFrom,document.frmMap.map_berthsTo,V_B_FROM,V_B_TO);
    });

}
function map_load(ulLat,ulLng,brLat,brLng,zoomLevel) {
    if (GBrowserIsCompatible()) {

        mapTypes = [
            new GMapType(G_NORMAL_MAP.getTileLayers(), G_NORMAL_MAP.getProjection(), 'Normaali', {minResolution: minZoomLevel, maxResolution: maxZoomLevel}),
            new GMapType(G_SATELLITE_MAP.getTileLayers(), G_SATELLITE_MAP.getProjection(), 'Satelliitti', {minResolution: minZoomLevel, maxResolution: maxZoomLevel}),
            new GMapType(G_HYBRID_MAP.getTileLayers(), G_HYBRID_MAP.getProjection(), 'Hybrid', {minResolution: minZoomLevel, maxResolution: maxZoomLevel})
        ];

        map = new GMap2(document.getElementById('map_canvas'),{mapTypes: mapTypes});

        if(V_LATITUDE != 0 && V_LONGITUDE != 0)
        {
            defaultLatitude=V_LATITUDE;
            defaultLongitude=V_LONGITUDE;
        }

        map.setCenter(new GLatLng(defaultLatitude, defaultLongitude),defaultZoomLevel);
        geocoder = new GClientGeocoder();

        map.addControl(new GMapTypeControl());
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl());
        map.addControl(new GOverviewMapControl(new GSize(170, 150)));
        GEvent.bind(map, 'moveend', this, chkUpdater);

        var hideShowTooltip = document.createElement("div");
        hideShowTooltip.id="hideShowTooltip";
        document.getElementById("map_canvas").appendChild(hideShowTooltip);
        hideShowTooltip.style.visibility="hidden";

        pendingRequestCount++;
        sendMapRequest(ulLat,ulLng,brLat,brLng,zoomLevel);
    }
    else { alert("Sorry, the Google Maps API is not compatible with this browser"); }
}
window.onbeforeunload = function() {
    GUnload;
}

function getUrl(ulLat,ulLng,brLat,brLng,zoomLevel)
{
    if(ulLat > 0 && ulLng > 0 && brLat > 0 && brLng > 0)
    {
        var bounds = new GLatLngBounds(new GLatLng(ulLat, ulLng), new GLatLng(brLat, brLng));
        map.setCenter(bounds.getCenter(),parseInt(zoomLevel));
    }
    else
        var bounds = map.getBounds();

    /** To check if town is already set then no need to set map center */
    tonwId=document.frmMap.map_town.selectedIndex;
    if(tonwId != '' && latTownId != tonwId)
    {
        latTownId=tonwId;
        if(geocoder)
        {
            address=document.frmMap.map_town[tonwId].text + ',Finland';

            geocoder.getLatLng(address,function(point) {
                            if (point)
                                map.setCenter(point);
                            }
            );
        }
    }

    ul=bounds.getSouthWest();
    br=bounds.getNorthEast();

    urlStr="ulLat="+ul.lat()+"&ulLng="+ul.lng()+"&brLat="+br.lat()+"&brLng="+br.lng()+"&zoomLevel="+map.getZoom();

    if(jQuery('#map_domicile').val())
        urlStr = urlStr + "&map_domicile=" + jQuery('#map_domicile').val();

    if(jQuery('#map_town').val())
        urlStr = urlStr + "&map_town=" + jQuery('#map_town').val();

    if(jQuery('#map_price_from').val())
        urlStr = urlStr + "&map_price_from=" + jQuery('#map_price_from').val();

    if(jQuery('#map_price_to').val())
        urlStr = urlStr + "&map_price_to=" + jQuery('#map_price_to').val();

    if(location.hostname.match(/nettimokki/i))
    {
        if(jQuery('#map_price_opt').val())
            urlStr = urlStr + "&map_price_opt=" + jQuery('#map_price_opt').val();

        if(jQuery('#map_berthsFrom').val())
            urlStr = urlStr + "&map_berthsFrom=" + jQuery('#map_berthsFrom').val();

        if(jQuery('#map_berthsTo').val())
            urlStr = urlStr + "&map_berthsTo=" + jQuery('#map_berthsTo').val();

        if(jQuery('#map_dateFrom').val())
            urlStr = urlStr + "&map_dateFrom=" + jQuery('#map_dateFrom').val();

        if(jQuery('#map_dateTo').val())
            urlStr = urlStr + "&map_dateTo=" + jQuery('map_dateTo').val();
    }
    if(location.hostname.match(/nettiasunto/i))
    {
        if(document.frmMap.map_category[0].checked)
            urlStr = urlStr + "&map_category=" + document.frmMap.map_category[0].value;
        else if(document.frmMap.map_category[1].checked)
            urlStr = urlStr + "&map_category=" + document.frmMap.map_category[1].value;

        if(jQuery('#map_sub_type').val())
            urlStr = urlStr + "&map_sub_type=" + jQuery('#map_sub_type').val();

        if(jQuery('#map_building_year_from').val())
            urlStr = urlStr + "&map_building_year_from=" + jQuery('#map_building_year_from').val();

        if(jQuery('#map_building_year_to').val())
            urlStr = urlStr + "&map_building_year_to=" + jQuery('#map_building_year_to').val();

        if(jQuery('#map_area_from').val())
            urlStr = urlStr + "&map_area_from=" + jQuery('#map_area_from').val();

        if(jQuery('#map_area_to').val())
            urlStr = urlStr + "&map_area_to=" + jQuery('#map_area_to').val();
    }
    var strNoOfRooms='';
    for(var i=0;i<document.frmMap.map_no_room.length;i++)
    {
        if(document.frmMap.map_no_room[i].checked)
        {
            if(strNoOfRooms == '')
                strNoOfRooms= strNoOfRooms + document.frmMap.map_no_room[i].value;
            else
                strNoOfRooms= strNoOfRooms + ',' + document.frmMap.map_no_room[i].value;
        }
    }

    if(strNoOfRooms != '')
        urlStr = urlStr + "&map_no_room=" + strNoOfRooms;

    return urlStr;
}
/** For check selected value in selction box */
function chkOptValue(objName,val)
{
    optName=eval("document.frmMap."+objName);

    if(objName == "map_no_room")
    {
        for(var i=0;i<optName.length;i++)
        {
            if(optName[i].value == val)
            {
                optName[i].checked = true;
            }
        }
    }
    else
    {
        for(var i=0;i<optName.length;i++)
        {
            if(optName.options[i].value == val)
            {
                optName.options[i].selected = true;
                return;
            }
        }
    }
}
function mapOnLoad()
{
    map_load(ulLat,ulLng,brLat,brLng,zoomLevel);
}
jQuery(document).ready(function(){
    if(sel_map_price_from)
    {
        priceFromChange(3,'S',C_PRICE_TO,sel_map_price_from,document.getElementById('map_price_to'));
        if(sel_map_price_to)
            chkOptValue("map_price_to",sel_map_price_to);
    }
    getDomTown(document.frmMap.map_domicile.value,document.frmMap.map_town.value,'SIMP','map');
});

window.onload=mapOnLoad;
