/* ==========================================================

 * MobilyMap

 * date: 29.11.2010

 * author: Marcin Dziewulski

 * last update: 20.1.2011

 * web: http://www.mobily.pl or http://playground.mobily.pl

 * email: hello@mobily.pl

 * Free to use under the MIT license.

 * ========================================================== */
(function ($) {
	$.fn.mobilymap = function (options) {

		var defaults = {
			position: "center",
			popupClass: "bubble",
			markerClass: "point",
			popup: true,
			cookies: true,
			caption: true,
			setCenter: true,
			navigation: true,
			navSpeed: 1000,
			navBtnClass: "navBtn",
			outsideButtons: false,
			onMarkerClick: function () {},
			onPopupClose: function () {},
			onMapLoad: function () {}
		};
		var sets = $.extend({}, defaults, options);
		
		return this.each(function () {
			var $this = $(this);
			
			
			
			$this.css({
				position: "relative",
				overflow: "hidden",
				cursor: "move"
			});
			
			$this.wrapInner($("<div />").addClass("imgContent").css({
				zIndex: "1",
				position: "absolute"
			}));
			
			var content = $this.find(".imgContent"),
				image = $this.find("img"),
				title = image.attr("alt"),
				point = $this.find("." + sets.markerClass),
				mouseDown = false,
				mx, my, ex, ey, imgw = image.width(),
				imgh = image.height(),
				divw = $this.width(),
				divh = $this.height();
			
			var cookies = {
				create: function (name, value, days) {
					if (days) {
						var date = new Date();
						date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
						var expires = "; expires=" + date.toGMTString()
					} else {
						var expires = ""
					}
					document.cookie = name + "=" + value + expires + "; path=/"
				},
				erase: function (name) {
					cookies.create(name, "", -1)
				},
				read: function (name) {
					var nameEQ = name + "=";
					var ca = document.cookie.split(";");
					for (var i = 0; i < ca.length; i++) {
						var c = ca[i];
						while (c.charAt(0) == " ") {
							c = c.substring(1, c.length)
						}
						if (c.indexOf(nameEQ) == 0) {
							return c.substring(nameEQ.length, c.length)
						}
					}
					return null
				}
			};
			
			var map = {
				check: function (x, y) {
					if (y < (divh - imgh)) {
						y = divh - imgh
					} else {
						if (y > 0) {
							y = 0
						}
					}
					if (x < (divw - imgw)) {
						x = divw - imgw
					} else {
						if (x > 0) {
							x = 0
						}
					}
					return {
						x: x,
						y: y
					}
				},
				init: function (position) {
					map.preloader();
					switch (position) {
					case "center":
						var x = (divw - imgw) / 2,
							y = (divh - imgh) / 2;
						break;
					case "top left":
						var x = 0,
							y = 0;
						break;
					case "top right":
						var x = divw - imgw,
							y = 0;
						break;
					case "bottom left":
						var x = 0,
							y = divh - imgh;
						break;
					case "bottom right":
						var x = divw - imgw,
							y = divh - imgh;
						break;
					default:
						var new_position = position.split(" "),
							x = -(new_position[0]),
							y = -(new_position[1]);
						if (y < (divh - imgh)) {
							y = divh - imgh
						} else {
							if (y > 0) {
								y = 0
							}
						}
						if (x < (divw - imgw)) {
							x = divw - imgw
						} else {
							if (x > 0) {
								x = 0
							}
						}
					}
					if (sets.cookies) {
						if (cookies.read("position") != null) {
							var pos = cookies.read("position").split(","),
								x = pos[0],
								y = pos[1]
						} else {
							var x = (divw - imgw) / 2,
								y = (divh - imgh) / 2
						}
					}
					content.css({
						top: y + "px",
						left: x + "px"
					})
				},
				preloader: function () {
					var loadimg = new Image(),
						src = image.attr("src");
					image.css({
						visibility: "hidden"
					});
					$this.append($("<div />").addClass("loader").css({
						position: "absolute",
						zIndex: "10",
						top: "0",
						left: "0",
						width: "100%",
						height: "100%"
					}));
					$(loadimg).load(function () {
						image.css({
							visibility: "visible"
						});
						$this.find(".loader").fadeOut(1000, function () {
							$(this).remove();
							if (sets.caption) {
								$this.append($("<div />").addClass("imgCaption").html(title).hide());
								captiond = $this.find(".imgCaption");
								captionh = captiond.innerHeight();
								captiond.css({
									bottom: -captionh + "px",
									position: "absolute",
									zIndex: "7"
								}).show().animate({
									bottom: 0
								})
							}
							sets.onMapLoad.call(this)
						})
					}).attr("src", src);
					image.removeAttr("alt")
				},
				mouse: function (e) {
					var x = e.pageX,
						y = e.pageY;
					return {
						x: x,
						y: y
					}
				},
				update: function (e) {
					var mouse = map.mouse(e),
						x = mouse.x,
						y = mouse.y,
						movex = x - mx,
						movey = y - my,
						top = ey + movey,
						left = ex + movex,
						check = map.check(left, top);
					content.css({
						top: check.y + "px",
						left: check.x + "px"
					});
					if (sets.cookies) {
						cookies.create("position", check.x + "," + check.y, 7)
					}
				},
				navigation: {
					buttons: function () {
						$this.prepend($("<div />").addClass("mapNav").css({
							position: "absolute",
							zIndex: "7",
							left: "20px",
							top: "20px"
						}));
						nav = $this.find(".mapNav");
						for (i = 0; i < 4; i++) {
							nav.append('<a href="#" class="' + sets.navBtnClass + " " + sets.navBtnClass + i + '" rel="' + i + '">btn' + i + "</a>")
						}
						nav.bind({
							mouseenter: function () {
								if (sets.caption) {
									captiond.stop()
								}
							}
						})
					},
					move: function () {
						$("." + sets.navBtnClass).bind({
							mousedown: function () {
								var navbtn = $(this).attr("rel");
								if (navbtn == 0) {
									content.animate({
										top: 0
									}, sets.navSpeed)
								}
								if (navbtn == 1) {
									content.animate({
										left: divw - imgw + "px"
									}, sets.navSpeed)
								}
								if (navbtn == 2) {
									content.animate({
										top: divh - imgh + "px"
									}, sets.navSpeed)
								}
								if (navbtn == 3) {
									content.animate({
										left: 0
									}, sets.navSpeed)
								}
							},
							mouseup: function () {
								content.stop();
								var pos = content.position(),
									x = pos.left,
									y = pos.top;
								if (sets.cookies) {
									cookies.create("position", x + "," + y, 7)
								}
							},
							mouseout: function () {
								content.stop()
							},
							click: function () {
								return false
							}
						})
					}
				}
			};
			if (sets.navigation) {
				map.navigation.buttons();
				map.navigation.move()
			}
			content.bind({
				mousedown: function (e) {
					e.preventDefault();
					mouseDown = true;
					var mouse = map.mouse(e);
					mx = mouse.x, my = mouse.y;
					var element = content.position();
					ex = element.left, ey = element.top;
					map.update(e)
				},
				mousemove: function (e) {
					if (mouseDown) {
						map.update(e)
					}
					return false
				},
				mouseup: function () {
					if (mouseDown) {
						mouseDown = false
					}
					return false
				},
				mouseout: function () {
					if (mouseDown) {
						mouseDown = false
					}
					return false
				},
				mouseenter: function () {
					if (sets.caption) {
						captiond.animate({
							bottom: -captionh + "px"
						})
					}
					return false
				},
				mouseleave: function () {
					if (sets.caption) {
						captiond.animate({
							bottom: 0
						})
					}
					return false
				}
			});
			map.init(sets.position);
			point.each(function () {
				var $this = $(this),
					pos = $this.attr("id").split("-");
				x = pos[1], y = pos[2];
				$this.css({
					position: "absolute",
					zIndex: "2",
					top: y + "px",
					left: x + "px"
				})
			}).children().next().wrapInner($("<div />").addClass("markerContent").css({
				display: "none"
			}));
			
			point.click(function () {
				var $this = $(this),
					pointw = $this.width(),
					pointh = $this.height(),
					pos = $this.position(),
					py = pos.top,
					px = pos.left,
					wrap = $this.find(".markerContent").html();
				if (sets.setCenter) {
					//PAGUIAR: modifico el centro
					//var center_y = -py + divh / 2 - pointh / 2,
					//center_x = -px + divw / 2 - pointw / 2,
					var center_y = -py + divh / 2 - pointh / 2 + sets.modificarCentroY;
					var center_x = -px + divw / 2 - pointw / 2 + sets.modificarCentroX;					
					
					var	center = map.check(center_x, center_y);
					content.animate({
						top: center.y + "px",
						left: center.x + "px"
					})
				}
				if (sets.popup) {
					
					$("." + sets.popupClass).remove();
					
					//PAGUIAR:MODIFICO EL POPUP PARA QUE CARGUE CONTENIDOS REMOTOS
					//$this.after($("<div />").addClass(sets.popupClass).css({
					//	position: "absolute",
					//	zIndex: "3"
					//}).html(wrap).append($("<a />").addClass("close")));
					
					$this.after($("<div />").addClass(sets.popupClass).css({
						position: "absolute",
						zIndex: "3"
					}).html('<div><div class="loader3">&nbsp;</div></div>').append($("<a />").addClass("close")));
					
					var popup = $this.next("." + sets.popupClass),
						popupw = popup.innerWidth(),
						popuph = popup.innerHeight(),
						y = py,
						x = px;
					//PAGUIAR: carga el contenido de la empresa
					id=$this.attr("id");
				    popup.children("div:first-child").load(sets.base_url+"empresa/punto/"+id);
					
					///////////////////////////////////
					//paguiar
					//DEjA FIJO EL MAPA MIENTRAS SE MUESTRA EL POPUP
					content.unbind("mousedown");
					content.bind({mousedown: function (e) {
						e.preventDefault();
					}});
					///////////////////////
					//correccion en X de la posicion del popup si pasa el borde derecho de la imagen con el mapa.
					//40 es un margen que agrega cuando corrige el pupup
					if(px+popupw > imgw){
						//corrige
						correccionX=-((px+popupw+40) - (imgw));
					}else{
						//no corrige
						correccionX=0;
					}
					popup.css({
						top: y + pointh + "px",
						left: x + "px",
						//marginLeft: -(popupw / 2 - pointw / 2) + "px"
						//pone el popup en la esquina superior izquierda
						marginLeft: correccionX+"px"
					})
				} else {
					sets.onMarkerClick.call(this)
				}
				return false
			});
			
			$this.find(".close").live("click", function () {
				////////////////////////////////////////////
				//PAGUIAR
				//BINDEA NUEVAMENTE EL MAPA Y EL MOUSE
				//alert("Cierra el popup");
				content.unbind("mousedown");
				content.bind({
					mousedown: function (e) {
						e.preventDefault();
						mouseDown = true;
						var mouse = map.mouse(e);
						mx = mouse.x, my = mouse.y;
						var element = content.position();
						ex = element.left, ey = element.top;
						map.update(e)
					}});
				///////////////////////////////////////////
				
				var $this = $(this);
				$this.parents("." + sets.popupClass).remove();
				setTimeout(function () {
					sets.onPopupClose.call(this)
				}, 100);
				return false
			});
			
			//PAGUIAR
			//PRENDE LA CATEGORIA, se ejecuta con iniciarZona
			//alert(sets.categoria_id);
			$("." + sets.markerClass).hide();					//apaga TODOS los puntos
			$("div.categoria_id_" + sets.categoria_id).show();		//prende los puntos de la categoria actual
			//AGREGA EL CLASS ACTIVO AL ITEM DE MENU DE CATEGORIAS DEL PANEL
			$("#panel ul.categorias").removeClass("activo");
			$("#panel ul.categorias a.categoria_id_" + sets.categoria_id).addClass("activo");
			
			
			//PAGUIAR, se ejecuta con iniciarZona
			//se fija si viene un punto en el set
			//si lo trae, hace click en el punto
			
			if(sets.punto_id){
				//alert("Carga punto: "+sets.punto_id);
				div = content.find("." + sets.markerClass).filter(function () {
					return $(this).attr("id") == sets.punto_id;
				});
				div.click();
			}
			
			//BOTONES DEL LISTADO
			if (sets.outsideButtons) {
				//define los sets y el conten como objetos globales para que los eva activarLinks
				global_sets=sets;		
				global_content=content;
				activarLinks(sets,content);
			}
		});
	}
}(jQuery));
