var map_max_left=600;
var map_max_top=600;
var map_marker_ids=new Array();
var map_cur_popup='';
var map_timer_popup=0;
var map_delay_popup=500;
var map_width_popup=200;
var map_height_popup=100;
var map_marker_line_height=40;
var map_marker_line_height_admin=20;
var map_marker_line_height_offset_admin=-6;
var map_marker_line_width=33;
var map_marker_default_image='';
var map_zoom_level_max=3;
var map_zoom_levels=new Array;
var map_zoom_level_current=1;
var map_lock=false;
var map_animate_duration=500;
var map_animate_type='swing';

jQuery(function(){

	///////////
	///ADMIN///	
	///////////
	if(jQuery("#admin_map").length)
	{
		//remember our element order
		var all_markers=jQuery("A.map_marker");
		var index=0;
		for(var i=0;i<all_markers.length;i++)
			map_marker_ids[i]=all_markers[i].id;
	
		//Do not //find max height,width
		//get fed from outside.... if imqage not yert cached this will be wrong.
		//MapSetBounds(jQuery('#rendering_image').width(),jQuery('#rendering_image').height());
	
		MapInitDraggableMarkers();			
	}
	else
	{
		////////////
		///PUBLIC///	
		////////////
		jQuery("div.map_marker_popup").bind("mouseleave",function(){
			MapStartPopupTimeout(map_cur_popup);
		});
		jQuery("div.map_marker_popup").bind("mouseenter",function(){
			MapKillPopupTimeout(map_cur_popup);
		});
	
		jQuery("#map_elements").easydrag();
		jQuery("#map_elements").ondrop(function(e, element){ 
			MapDrop();
		});
		jQuery("#map_elements").ondrag(function(e, element){ 
			MapDrag();
		});
		
		jQuery("div.map_marker").mousedown(function(e){return false;});
		jQuery("div.map_marker_popup").mousedown(function(e){return false;});
	}
});

function MapInitDraggableMarkers()
{
	jQuery("#admin_map A.map_marker").unbind();
	jQuery("#admin_map A.map_marker").css({cursor:'default'});

	// add drag and drop functionality
	jQuery("#admin_map A.map_marker_draggable").easydrag();
 
	// set a function to be called on a drop event
	jQuery("A.map_marker_draggable").ondrop(function(e, element){ 
		MapMarkerDrop(element);
	});

	jQuery("A.map_marker_draggable").ondrag(function(e, element){ 	
		MapStatus('Moving...');
	});  
}

function MapSetZoom(level,lwidth,lheight)
{
  	var lvl=new Array;
	lvl['width']=lwidth;
	lvl['height']=lheight;
	map_zoom_levels[level]=lvl;
}

function MapSetZoomMax(mx)
{
	map_zoom_level_max=mx;  
}

function MapSetDefaultImage(img)
{
	map_marker_default_image=img;
}

function MapSetBounds(w,h)
{
	map_max_left=w;
	map_max_top=h;  
}

function MapMarkerDrop(element,parent_id)
{
 	var left=parseInt(element.style.left); 
 	var top=parseInt(element.style.top); 
 	var marker_id=element.id; 


  	if(left<0 || left>map_max_left || top<0 || top>map_max_top)
	{	
		top=-1;
		left=-1;
		
		var index=0;
		for(var i=0;i<map_marker_ids.length;i++)
		{
		  if(map_marker_ids[i]==marker_id)
		  	  index=i;
		}
		
		element.style.left=map_max_left+'px';
		element.style.top=((index*map_marker_line_height_admin)+map_marker_line_height_offset_admin)+'px';
	}
	else
	{
//		left+=map_marker_line_width;
//		top+=map_marker_line_height; 
	}
  
	MapStatus('Saving Location...');
	AjaxRequest.post(
	{
		'url':'ajax/marker.php',
		'parameters':{'marker_id':marker_id,'top':top,'left':left,'parent_id':parent_id?parent_id:0},
		'onComplete':function(request){MapStatus('Location Saved.');}
	}
	);
}

function MapGroupMarker(element_id,parent_id)
{
  	var element=jQuery('#'+element_id);
  	if(element.length)
  	{
  	  	if(parent_id)
  	  	{
			MapStatus('Ungrouping Item...');
			jQuery(element).css({top:"-1px",left:"-1px",background:"#ccddcc"});			
			jQuery(element).addClass('map_marker_grouped');
			jQuery(element).removeClass('map_marker_draggable');
		}
		else
		{
		  	MapStatus('Grouping Item...');
			jQuery(element).addClass('map_marker_draggable');
			jQuery(element).removeClass('map_marker_grouped');
			jQuery(element).css({top:"-1px",left:"-1px",background:"url('"+map_marker_default_image+"')"});
		}
		MapMarkerDrop(element.get(0),parent_id);
		MapInitDraggableMarkers();
	}
}

function MapStatus(text)
{
  	if(document.getElementById('map_status'))
		document.getElementById('map_status').innerHTML=text;
}


function MapStartPopupTimeout(id)
{
	map_timer_popup=setTimeout(function(){MapShowPopup(map_cur_popup,false)},map_delay_popup);
}

function MapKillPopupTimeout(id)
{
	if(id==map_cur_popup)  
		clearTimeout(map_timer_popup);
}

function MapShowPopup(id,vis)
{
	if(vis)
	{
	  	if(map_cur_popup==id)
	  	{
	  		MapKillPopupTimeout(id);	
	  		return;
	  	}
	  	//close existing before open new
	  	if(map_cur_popup)
	  		MapShowPopup(map_cur_popup,false);

	  	//open new	
		map_cur_popup=id;
		
			  	
		//move and make sure it is in the window
		var idstr=map_cur_popup;		
		var popup_obj=document.getElementById(map_cur_popup);		
		var marker_obj=document.getElementById(idstr.replace('_popup',''));
		var pad=10;
		var curwidth=jQuery('#map_image IMG').width();
		var curheight=jQuery('#map_image IMG').height();
		if(marker_obj)
		{	
			popup_obj.style.top=(parseInt(marker_obj.style.top)-map_height_popup-pad)+'px';
			popup_obj.style.left=(parseInt(marker_obj.style.left)+pad)+'px';
		}
		var bnd_top=pad;
		var bnd_left=pad;
		var bnd_bottom=((curheight-map_height_popup)-pad);;
		var bnd_right=((curwidth-map_width_popup)-pad);
		if(popup_obj)
		{
			if(parseInt(popup_obj.style.top)>bnd_bottom)
				popup_obj.style.top=bnd_bottom+'px';
			if(parseInt(popup_obj.style.left)>bnd_right)
				popup_obj.style.left=bnd_right+'px';
			if(parseInt(popup_obj.style.top)<bnd_top)
				popup_obj.style.top=bnd_top+'px';
			if(parseInt(popup_obj.style.left)<bnd_left)
				popup_obj.style.left=bnd_left+'px';
		}
		jQuery('#'+id).fadeIn(800,function(){});		
	}
	else
	{
	  	if(map_cur_popup!=id)
	  		return;

	  	//close existng
  		MapKillPopupTimeout(map_cur_popup);	
		jQuery('#'+map_cur_popup).fadeOut(400,function(){});
		//no existing
		map_cur_popup='';
	}
}

function MapZoomIn()
{
	MapZoomTo(map_zoom_level_current+1)  ;
}

function MapZoomOut()
{
	MapZoomTo(map_zoom_level_current-1);
}

function MapLock()
{
  	map_lock=true;
  	jQuery("#map").css({cursor:'wait'});
  	jQuery("#map A").css({cursor:'wait'});
}

function MapLocked()
{
  	return map_lock;
}

function MapUnlock()
{
  	map_lock=false;
  	jQuery("#map").css({cursor:'move'});
  	jQuery("#map A").css({cursor:'pointer'});
}

function MapZoomTo(level)
{
	//locked?
	if(MapLocked())
		return;

	//locals+error trap to see if we should bother
	if(level==0)
		return;
	if(level>map_zoom_level_max)
		return;
	if(level==map_zoom_level_current)
		return;

	var lvl=map_zoom_levels[level];
	var towidth=lvl['width'];
	var toheight=lvl['height'];
	var curwidth=jQuery('#map_image IMG').width();
	var curheight=jQuery('#map_image IMG').height();
	var curleft=parseInt(jQuery('#map_elements').get(0).style.left);
	var curtop=parseInt(jQuery('#map_elements').get(0).style.top);

	if(!towidth || !toheight)
		return;

	//lock
	MapLock();
	
	//scale
	var ratiox=towidth/curwidth;
	var ratioy=toheight/curheight;


	//calculate recentering
	var curcx=(curleft+curwidth/2);
	var curcy=(curtop+curheight/2);
	var x=(curcx-(towidth/2));
	var y=(curcy-(toheight/2));
	var targ=MapCheckPan(x,y,towidth,toheight);

	//enlarge containers and image, move map due to enlargement
	jQuery("#map_image").css({width:towidth+"px",height:toheight+"px"});

	jQuery("#map_elements").css({width:towidth+"px",height:toheight+"px",top:(targ['y'])+"px",left:(targ['x'])+"px"});
	
	//hide markers
	jQuery("A.map_marker").css({display:"none"});
	jQuery("A.map_marker_popup").css({display:"none"});
	MapShowPopup(map_cur_popup,false);
	
	//save..
	MapSetCurrentZoom(level);

	//animated zoom...
	//jQuery("#map_image IMG").animate({width:towidth+"px",height:toheight+"px"}, map_animate_duration,map_animate_type,function(){MoveMarkers(ratiox,ratioy);MapUnlock();});

	//non animated
	jQuery("#map_image IMG").css({width:towidth+"px",height:toheight+"px"});
	MapMoveMarkers(ratiox,ratioy);
	MapUnlock();
}

function MapMoveMarkers(ratiox,ratioy)
{

	//spread or contract markers so they can be moved on map_elements plane w/pan
	jQuery("A.map_marker").each(function (i) 
	{
	  	var newpos=MapTranslateMarkerPosition(this,ratiox,ratioy);
	  	jQuery("#"+this.id).css({top:newpos['top']+"px",left:newpos['left']+"px"}, map_animate_duration,map_animate_type);
	});
	jQuery("DIV.map_marker_popup").each(function (i) 
	{
	  	var newpos=MapTranslateMarkerPosition(this,ratiox,ratioy);
	  	jQuery("#"+this.id).css({top:newpos['top']+"px",left:newpos['left']+"px"}, map_animate_duration,map_animate_type);
	});

	//show markers again
	jQuery("A.map_marker").css({display:"block"});
	
	//show a popup if there was one
	//if(map_cur_popup)	MapShowPopup(map_cur_popup,true);
}

function MapTranslateMarkerPosition(item,ratiox,ratioy)
{
	var newpos=new Array()

  	newpos['left']=(parseInt(item.style.left)*ratiox)+((ratiox-1)*((map_marker_line_width)/2));
  	newpos['top']=(parseInt(item.style.top)*ratioy)+((ratioy-1)*(map_marker_line_height));  
  	
  	return newpos;
}

function MapSetCurrentZoom(level)
{
	if(jQuery('#map_controls_large').length)
	{
		jQuery('#map_controls_zoom_level A').get(map_zoom_level_max-map_zoom_level_current).className='';
		map_zoom_level_current=level;
		jQuery('#map_controls_zoom_level A').get(map_zoom_level_max-map_zoom_level_current).className='current';	
	}
	else
	{
	  	map_zoom_level_current=level;
		jQuery('#map_controls_zoom_level A').removeClass('disabled');
		if(map_zoom_level_current==1)	  
			jQuery('#map_controls_zoom_level #map_zoom_out A').addClass('disabled');
		else if(map_zoom_level_current==map_zoom_level_max)	  
			jQuery('#map_controls_zoom_level #map_zoom_in A').addClass('disabled');
	}
}

function MapPanBy(panx,pany)
{
	var curleft=parseInt(jQuery('#map_elements').get(0).style.left);
	var curtop=parseInt(jQuery('#map_elements').get(0).style.top);
  
	MapPanTo(curleft+panx,curtop+pany);
}

function MapPanTo(targx,targy)
{
	if(MapLocked())
		return;
	MapLock();  
	
	var curwidth=jQuery('#map_image IMG').width();
	var curheight=jQuery('#map_image IMG').height();
	var targ=MapCheckPan(targx,targy,curwidth,curheight);


	jQuery("#map_elements").animate({top:targ['y']+"px",left:targ['x']+"px"}, map_animate_duration,map_animate_type,function(){MapUnlock();});

}

function MapCheckPan(targx,targy,chkwidth,chkheight)
{
  	var targs=new Array;
	var contwidth=jQuery('#map').width();
	var contheight=jQuery('#map').height();
	var max_left=contwidth-chkwidth;
	var max_top=contheight-chkheight;  

	if(targy>0)			targy=0;
	if(targx>0)			targx=0;
	if(targy<max_top)	targy=max_top;
	if(targx<max_left)	targx=max_left;

	targs['x']=targx;
	targs['y']=targy;
	
	return targs;
}

function MapCenter()
{
	var curwidth=jQuery('#map_image IMG').width();
	var curheight=jQuery('#map_image IMG').height();
	var contwidth=jQuery('#map').width();
	var contheight=jQuery('#map').height();

	var cx=(contwidth-curwidth)/2;
	var cy=(contheight-curheight)/2;
  
	MapPanTo(cx,cy);
}

function MapDrag()
{
	var curleft=parseInt(jQuery('#map_elements').get(0).style.left);
	var curtop=parseInt(jQuery('#map_elements').get(0).style.top);
	var curwidth=jQuery('#map_image IMG').width();
	var curheight=jQuery('#map_image IMG').height();
	var targ=MapCheckPan(curleft,curtop,curwidth,curheight);
	MapShowPopup(map_cur_popup,false);
	jQuery("#map_elements").css({top:targ['y']+"px",left:targ['x']+"px"});			  
}

function MapDrop()
{
	MapDrag();
}
