var map;
var globalMarker;
var markersArray = new Array();   

var ap = String.fromCharCode(34);

var options = {
      onGenerateMarkerHtmlCallback : extendMarker, 
      onMarkersSetCallback : extendMarkerInner
      };
//var localSearch = new google.maps.LocalSearch(options);

/*
var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
//baseIcon.iconSize = new GSize(20, 20);
baseIcon.shadowSize = new GSize(20, 20);
baseIcon.iconAnchor = new GPoint(9, 20);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);              
*/

var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(19, 27);
baseIcon.shadowSize = new GSize(36, 27);
baseIcon.iconAnchor = new GPoint(9, 27);
baseIcon.infoWindowAnchor = new GPoint(9, 2);



function extendMarkerInner(markers){
	for( i = 0 ; i < markers.length; i++){
		markers[i].marker.hide();
	}
}

function extendMarker() {
  marker = globalMarker;
  GEvent.addListener(marker, "infowindowclose", function() {
    	sendForm("unlinkFile","unlinkFileResult");
	}); 
  lat = marker.getLatLng().lat();
  lng = marker.getLatLng().lng(); 
  changeData('newLocation','Map','showAddForm',lng,lat,null); 
}

function initialize(doubleClickZoom,showSearch,fullScrollBar) {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map_canvas"));
    if(latlng) map.setCenter(latlng, 15);
    else map.setCenter(new GLatLng(50.070362,22.002182), 11);
    if(fullScrollBar) map.addControl(new GLargeMapControl());
    else map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    //map.enableScrollWheelZoom();
    
    if(!doubleClickZoom) { 
        map.disableDoubleClickZoom(); 
        GEvent.addListener(map, "dblclick", function(overlay,  point) {
            if(user_id == -1) { alert("Musisz sie zalogowac by moc dodawac lokalizacje... "); return false; }
    	    overlay = new GMarker(point);
    	    map.addOverlay(overlay);
            overlay.hide();       
	        overlay.openInfoWindowHtml("<div id=\"newLocation\" style=\"height:350px;width:250px;\"></div>");
            globalMarker=overlay;
            setTimeout("extendMarker();",1000);	        
	    });
    }

    if(showSearch) {
        var localSearch = new google.maps.LocalSearch(options);
        map.addControl(localSearch, new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,20)));
    }
    
    loadMarkers();
  } else alert('Przegladarka nie kompatybilna z mapą Google');
}

function loadMarkers() {
    for(var i = 0;i<markersArray.length; i++) {
        addMarker2(markersArray[i][0],markersArray[i][1],markersArray[i][2],markersArray[i][3],markersArray[i][4],markersArray[i][5]);
    }
}

function infoForMarker(parent, lat, lng, ico, location_id, location_description, location_name, location_photo, city_name, location_category_ico, center, editable){
	divDispose = document.createElement("div");
		divDispose.style['display'] = "none";
		divDispose.className = "hiddenMarkerInfo";
		divDispose.innerHTML = lat+';'+ lng+';'+ ico+';'+ location_id+';'+ location_description+';'+ location_name+';'+ location_photo+';'+ city_name+';'+ location_category_ico+';'+ center+';'+ editable;
	parent.appendChild(divDispose);
}

function addMarker(lat, lng, ico, location_id, location_description, location_name, location_photo, city_name, location_category_ico, center, editable, area_id, event){
	var latlng = new GLatLng(parseFloat(lat), parseFloat(lng));
	if(center){
		map.setCenter(latlng, 12);
	}
	var locationIcon = new GIcon(baseIcon);
	locationIcon.image = "images/LocationCategory/"+location_category_ico;
	markerOptions = { icon:locationIcon };
	var marker = new GMarker(latlng, markerOptions);
	GEvent.addListener(marker, "click", function() {
		
        divId = "locationInfoWindow_";
		var info = '<div id='+divId+' class="locationInfoWindow">'+infoWindowBody(document.getElementById(divId), location_photo, location_name, location_description, city_name, editable, location_id, area_id, event)+'</div>';
		marker.openInfoWindowHtml(info);
	});
	map.addOverlay(marker);
}

function addMarker2(lat, lng, ico, location_id, innerHtml, center) {
   var latlng = new GLatLng(parseFloat(lat), parseFloat(lng));
    if(center == '1'){
        map.setCenter(latlng, 15);
    }
    
    var tempIco = ico.split("/");
    if(tempIco.length > 1) var locationIcon = new GIcon(G_DEFAULT_ICON);
    else var locationIcon = new GIcon(baseIcon);              
    
    //var locationIcon = new GIcon(G_DEFAULT_ICON);
    
    locationIcon.image = "images/LocationCategory/"+ico;
    markerOptions = { icon:locationIcon, draggable:true };
    var marker = new GMarker(latlng, markerOptions);
    
    var drag = location_id.split("/",2);
    if(drag.length > 1) { marker.enableDragging();
        location_id = drag[1]; 
    } 
    else marker.disableDragging();
    GEvent.addListener(marker, "click", function() {
        globalMarker = marker;
        var info = innerHtml;    
        if(info == 'clickLink') {
         
            window.location.href="index.php?location="+location_id; 
            exit;
            }
        else 
        marker.openInfoWindowHtml(info);
    });
    map.addOverlay(marker);
    if(markersArray.length == 1) {
        if(innerHtml != 'clickLink') {
        	globalMarker=marker;
            marker.openInfoWindowHtml(innerHtml);
        }
    }
}


function infoWindowBody(parent, photo, name, desc, city, editable, location_id, area_id, event){
	var table = document.createElement("table");
		var tbody = document.createElement("tbody");
		table.appendChild(tbody);
		var tr = document.createElement("tr");
		tbody.appendChild(tr);
		var tdLeft = document.createElement("td");
		var tdRight = document.createElement("td");
		tbody.appendChild(tdLeft);
		tbody.appendChild(tdRight);


	var mainDiv = document.createElement("div");
	var leftDiv = document.createElement("div");
		leftDiv.style['float'] = "left";
	if(photo.length > 0){
		var img = document.createElement("img");
			img.src = photo;
			leftDiv.appendChild(img);
	}
	var rightDiv = document.createElement("div");
		rightDiv.style['float'] = "left";
		rightDiv.id = "AAA";
	var divName = document.createElement("div");
		divName.innerHTML = name;
	var divDesc = document.createElement("div");
		divDesc.innerHTML = desc;
	var divCity = document.createElement("div");
		divCity.innerHTML = city;
		rightDiv.appendChild(divName);
		rightDiv.appendChild(divDesc);
		rightDiv.appendChild(divCity);
	if(editable){
		var divDelete = document.createElement("div");
			divDelete.id = "delete_location_container";
			divDelete.align = "right";
			
			if(navigator.userAgent.toLowerCase().indexOf("msie") != -1) { isIE = true; } else { isIE = false; }
			  if(isIE){
			  	var form = document.createElement('<FORM id=\'delete_location_form\'></FORM>');
			  }
			  else{
			  	var form = document.createElement('form');
			  	form.id = "delete_location_form";
			  }
				form.method = "POST";
				form.onsubmit = "false";
				divDelete.appendChild(form);
			
			  if(isIE){
			  	var inputClass = document.createElement('<input name=\'p_class\'></input>');
			  }
			  else{
			  	var inputClass = document.createElement("input");
				inputClass.name = "p_class";
			  }
				inputClass.type = "hidden";
				inputClass.value = "Map";
				form.appendChild(inputClass);
				
			  if(isIE){
			  	var inputFunc = document.createElement('<input name=\'p_function\'></input>');
			  }
			  else{
			  	var inputFunc = document.createElement("input");
				inputFunc.name = "p_function";
			  }
			  	inputFunc.type = "hidden";
				inputFunc.value = "DeleteLocation";
				form.appendChild(inputFunc);
			
			  if(isIE){
			  	var inputLocID = document.createElement('<input name=\'p_data\'></input>');
			  }
			  else{
			  	var inputLocID = document.createElement("input");
				inputLocID.name = "p_data";
			  }  
				inputLocID.type = "hidden";
				inputLocID.value = location_id;
				form.appendChild(inputLocID);
				
			if(isIE){
			  	var inputLocPhoto = document.createElement('<input name=\'p_photo\'></input>');
			  }
			  else{
			  	var inputLocPhoto = document.createElement("input");
				inputLocPhoto.name = "p_photo";
			  }  
				inputLocPhoto.type = "hidden";
				inputLocPhoto.value = photo;
				form.appendChild(inputLocPhoto);
				
			var aDelete = document.createElement("a");
				aDelete.setAttribute("onclick", "if(confirm('Usunąć wskazaną lokalizację?')){sendFormMap('delete_location_form','delete_location_container');}");
				//aDelete.onclick = "sendFormMap('delete_location_form','delete_location_container')";
				//aDelete.onclick = function(){
				//	sendFormMap('delete_location_form','delete_location_container');
				//};
				aDelete.innerHTML = "Usuń";
			divDelete.appendChild(aDelete);		
			rightDiv.appendChild(divDelete);
	}
	tdLeft.appendChild(leftDiv);
	tdRight.appendChild(rightDiv);
	mainDiv.appendChild(table);
	
	if(event == 1) {
      var tmp = document.createElement("DIV"); 
			tmp.innerHTML = '<a onclick="setEventLocation(\''+ location_id +'\', \''+ area_id+'\');">Wybierz lokalizacje</a>';
			mainDiv.appendChild(tmp);
	}
	
	return mainDiv.innerHTML;
}

document.getElementsByClassName = function(clsName){
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName)
                    retVal.push(elements[i]);
            }
        }
        else if(elements[i].className == clsName)
            retVal.push(elements[i]);
    }
    return retVal;
}

function addLocation(location_id, user_name, location_name, location_category_ico, city_name, lat, lng){
	locationList = document.getElementById("map_location_point_list");
	a = document.createElement("a");
	a.onclick = function(){
		map.setCenter(new GLatLng(parseFloat(lat), parseFloat(lng)), map.getZoom());
	};
	locationList.appendChild(a); 
	div = document.createElement("div");
	div.setAttribute("id", "location_id:"+location_id);
	div.setAttribute("class","map_location_point_list_element");
	div.setAttribute("className","map_location_point_list_element");
	a.appendChild(div); 
	document.getElementById("location_id:"+location_id).innerHTML = "<img src=\"images/LocationCategory/"+location_category_ico+"\"></img> "+user_name+" "+
																location_name+" "+
																city_name;
}

function validateLocation(form){
	return true;
}

function scrollDown(){
		document.getElementById('map_location_point_list').scrollTop += 500;
}

function scrollUp(){
		document.getElementById('map_location_point_list').scrollTop -= 500;                                    
}
                                             
function setEventLocation(user_id,loc_id, area_id) {
  //window.parent.document.getElementById('eventLocationId').style.display = 'inline';
  //window.parent.document.getElementById('eventLocationId').value = id;
  //alert(window.parent.document.getElementById('eventLocationId').id);
  if(!opener.closed) {
    if(area_id != 'null') {
        el = opener.document.getElementById('eventAreaId');
        el.value = area_id;
        setLocationSelect2(loc_id,area_id,user_id); 
    }
      
    }
   
}

function setLocationSelect2(loc_id,area_id,user_id) {   
   $.post("dispather.php",{
		   p_class: 'Event',
	       p_function: 'makeLocationSelect',
	       p_arg1: user_id,
	       p_arg2: area_id,
	       p_arg3: loc_id
		},function(txt) { opener.document.getElementById('locationSelectRow').innerHTML = txt;
            //validateNewSelect();                               
            opener.document.getElementById('eventLocationId').attributes['class'].nodeValue = "validOk";
            opener.document.getElementById('eventAreaId').attributes['class'].nodeValue = "validOk";
            self.close();             
         }        
	);
    
    
}                

function validateNewSelect() {
    var aaaa = opener.document.getElementById('eventLocationId');
    var val = aaaa.options[aaaa.selectedIndex].value;
    //alert(val + 'aa');
    $.post("dispather.php",{
           p_class: 'Validator',
           p_function: 'eventLocation',
           p_arg1: val,
           p_arg2: null,
           p_arg3: null
        },function(txt) { opener.document.getElementById('infoLocation').innerHTML = txt;
        self.close();
         }        
    );    

}                                      
function resizeCloud(loc_id) {   
//	globalMarker=marker;
//	alert(globalMarker);
    globalMarker.closeInfoWindow();
//    alert('asd');
    globalMarker.openInfoWindowHtml('<div id=\'newLocation\'></div>');
//    alert('asd');
    globalMarker.disableDragging();
//    alert('asd');
    html = document.getElementById("newLocation");
//    alert('asd');
    GEvent.addListener(globalMarker, "infowindowclose", function() {
        globalMarker.enableDragging();
        sendForm("unlinkFile","unlinkFileResult");
    });
//    alert('asd');
    html.style['height'] = "350px";
    html.style['width'] = "250px";
    lat = globalMarker.getLatLng().lat();
    lng = globalMarker.getLatLng().lng();
    changeData('newLocation','Map','showEditForm',loc_id,lat,lng);
}

function checkMapForm(formId,contener) {
    var el = document.getElementById('loc_name');
    if(el.value == '') {
        alert("Nazwa lokalizacji nie może być pusta");
    }
    else {
        sendForm(formId,contener);
    }
}

function centerGMap(lat,lng) {
    $(document).ready(function () {
        latlng = new GLatLng(parseFloat(lat), parseFloat(lng));
        if(map) map.setCenter(latlng, 15);    
    });
}

function showLoading(id) {
    document.getElementById(id).innerHTML = '<br /><img src="images/ajax-loader.gif"></img> Loading...';
}

var directions = new GDirections();
var polyline = null;
function drawPath(lat1,lng1,lat2,lng2,divId,divId2) {
    var latlng1 = new GLatLng(parseFloat(lat1), parseFloat(lng1));
    var latlng2 = new GLatLng(parseFloat(lat2), parseFloat(lng2));
   
    directions.clear();
    
    if(polyline) map.removeOverlay(polyline);

    directions = new GDirections(document.getElementById(divId));
    GEvent.addListener(directions, "error", function(){
                                //alert("could not calculate distance(error code : "+directions.getStatus().code+")");
                            });
    GEvent.addListener(directions, "load", function() {
        $("#"+divId2).html('<div class="duration">'+directions.getDuration().html+'</div><div class="distance">'+directions.getDistance().html+'</div>');
        var bndsView = directions.getBounds();
        polyline = directions.getPolyline();
        map.addOverlay(polyline);
        map.setZoom(map.getBoundsZoomLevel(bndsView));
        map.setCenter(bndsView.getCenter());
    });
    var pointsArray = [latlng1,latlng2];
    directions.loadFromWaypoints(pointsArray , {getPolyline:true});
}
