$(function(){
  var api_key, base_url
  if(window.location.hostname == "localhost")
  {
    api_key = "ABQIAAAAsk_dG8x_48uO_V5lPeHY0BTH6qritnsMpL-uf7QelD1TpxlX3RT6u3lWZ5clB1VulMUE6Vmh4qWm1g";
    base_url = "/~martin/php/Ringspun/trunk";
  }
  else
  {
    api_key = "ABQIAAAAsk_dG8x_48uO_V5lPeHY0BTH6qritnsMpL-uf7QelD1TpxlX3RT6u3lWZ5clB1VulMUE6Vmh4qWm1g";
    base_url = "";
  }

  // TODO BEN: change MEDIA_PATH to /wp-content/themes/custom/ - done
  var MEDIA_PATH = base_url + "/wp-content/themes/custom/";
  if($(".arrow").length)
  {
    var $arrow = $("a.arrow");
    $arrow.click(function(e){
      e.preventDefault();
    });

    $arrow.mouseup(function(){
      $(this).blur();
    });
  }

  $(function() {

		$("#navigation ul li a").click(function(){
		 $(this).addClass("selected");
		 $("#navigation a").not(this).removeClass("selected");
		 $("#navigation div ul li a").not(this).removeClass("selected");

		});

		$("#navigation a").not(document.getElementById('navigation')).click(function(){
		 $("#navigation").removeClass("selected");
		});
	});


  // Only load google maps if we're on the right page!
  if($("#store_finder_overlay").length)
  {
    var latlng = new google.maps.LatLng(53.9, -2);
    var myOptions = {
      zoom: 8,
      center: latlng,
      disableDefaultUI: false,
  		scrollwheel: false,
      mapTypeId: google.maps.MapTypeId.TERRAIN
    };
    var map = new google.maps.Map(document.getElementById("map"), myOptions);
    var markers = [];

    function closeAllPopouts(){
    	var allpops=document.getElementsByClassName('popout');
    	 $.each(allpops, function(i,thispop){
    		thispop.style.display = 'none';
    	 });
    }

    // Custom overlay bubble
    var MyOverlay = function(marker, html) {

    	this.popoutWidth=140;
    	this.popoutHeight=119;
    	this.pointerWidth=0;
    	this.pointerHeight=119;

      this.marker = marker;
      this.html = html;
      this.inited = false;
      this.visible = false;
      this.overlaydiv = document.createElement("div");
      this.contentdiv = document.createElement("div");
      this.contentdiv.style.padding = "5px";
      this.topdiv=null;
      this.middiv=null;
    };

    //--------- the overlay class thingy ---------

    MyOverlay.prototype = new google.maps.OverlayView();

    MyOverlay.prototype.draw = function(){
    	if (this.inited===false){
    		this.reallyInit();
    		this.inited=true;
    	}
    	var offsetX = 14;
    	this.conheight=this.contentdiv.offsetHeight;
    	var offsetY = this.popoutHeight;//-this.popoutHeight-this.pointerHeight;

    	var latlngPos=this.marker.position;
    	var reallatlng=new google.maps.LatLng(parseFloat(latlngPos.lat()),parseFloat(latlngPos.lng()));
    	this.projection=this.getProjection();
    	var thisPosition=this.projection.fromLatLngToDivPixel(reallatlng);

    	this.overlaydiv.style.top = (thisPosition.y - offsetY) + 'px';
    	this.overlaydiv.style.left = (thisPosition.x - offsetX) + 'px';
    };

    MyOverlay.prototype.remove = function(){

    };


    MyOverlay.prototype.reallyInit = function(){
    	this.overlaydiv.className='popout';
    	this.overlaydiv.style.display = 'none';
    	this.overlaydiv.style.position = 'absolute';
      this.overlaydiv.style.backgroundImage='url('+MEDIA_PATH+'layout/map/infoWindow/pin-pop-out-box.png)';
    	this.overlaydiv.style.width = this.popoutWidth+'px';
    	this.overlaydiv.style.height = this.popoutHeight+'px';

    	this.pointdiv=document.createElement("div");
    	this.pointdiv.style.position = 'absolute';
    	this.pointdiv.style.width= this.pointerWidth+"px";
    	this.pointdiv.style.height= this.pointerHeight+"px";
    	this.pointdiv.style.top=-this.pointerHeight+"px";
    	this.pointdiv.style.left=(this.popoutWidth/2)-(this.pointerWidth/2)+"px";

    //	this.pointdiv.className='po-pointer';
    	this.overlaydiv.appendChild(this.pointdiv);

    	this.contentdiv.className='content';
    	this.overlaydiv.appendChild(this.contentdiv);

    // nasty closebox thing
    	var closeboxdiv=document.createElement("div");

    	var closebox=document.createElement("img");
    	closebox.src= MEDIA_PATH + "layout/map/infoWindow/close-button.gif";
    	closebox.style.cursor="pointer";

    	closebox.className="closebox";
    	closebox.onclick=function(){closeAllPopouts();};

    	closeboxdiv.style.position = 'absolute';
    	closeboxdiv.style.top="5px";
    	closeboxdiv.style.right="5px";
    	closeboxdiv.style.marginLeft='20px';

    	closeboxdiv.appendChild(closebox);

    	this.overlaydiv.appendChild(closeboxdiv);
    	this.getPanes().floatPane.appendChild(this.overlaydiv);
    };

    MyOverlay.prototype.setContentHTML = function(theHTML){
      this.html=theHTML;
    	this.contentdiv.innerHTML=this.html;
    };

    MyOverlay.prototype.open = function(){
    	closeAllPopouts();
    	//this.conheight=this.contentdiv.offsetHeight;

    	this.draw();
    	this.overlaydiv.style.display = 'block';
    	this.centreOverlay();

    };

    MyOverlay.prototype.centreOverlay = function(){
    	if (this.projection===undefined){
    		//this.draw();
    		//this.projection=this.getProjection();
    	} else {
    		// Centre the overlay....
    		var pointPos = this.projection.fromLatLngToDivPixel(this.marker.position);
        // pointPos.y+=(this.popoutHeight+this.pointerHeight)/2;
    		var midPos = this.projection.fromDivPixelToLatLng(pointPos);
    		map.panTo(midPos);//was panTo....
    	}
    };

    MyOverlay.prototype.close = function(){
    	this.overlaydiv.style.display = 'none';
    };

    function reset_form()
    {
      $("form")[0].reset();
  	  $("#loader").css({"display": "none"});
  	  $("input#address").attr({"value": "Enter Location..."});
  	  $(".checkbox_replace, .checkbox_replace_checked").removeClass("checkbox_replace_checked").addClass("checkbox_replace");
  	  $("#loader").css({"display": "none"});
    }

    function add_panel(store)
    {
      var li = $("<li/>").attr({"id": store.id});
    }

    function reset_map(lat, lng)
    {
      if(lat === undefined) {lat = 53.9};
      if(lng === undefined) {lng = -2};
      // Re-position map
      latlng = new google.maps.LatLng(lat, lng);
      map.panTo(latlng);
      //
      if(markers.length)
      {
        $.each(markers, function(k, v)
        {
          v.setMap(null);
        });
      }
    }

    function error(error)
    {
      alert(error);
    }

    $("#store_locator").submit(function(e)
    {
      $(this).find("#loader").show();
      // Don't reload page
      e.preventDefault();

      // Initialize variables, slight performance booster
      var coordinates;
      var latitude;
      var longitude;

      // Get search term - Postcode / Address / City etc.
      var query = $(this).find("input[type='text']").attr("value");

      $.getJSON("http://maps.google.com/maps/geo?q="+query+"&key="+api_key+"&sensor=false&gl=uk&output=json&callback=?",
      function(data, textStatus)
      {
        if(data.Status.code == 200) // Location was found
        {
          coordinates = data.Placemark[0].Point.coordinates;
          longitude = data.Placemark[0].Point.coordinates[0];
          latitude = data.Placemark[0].Point.coordinates[1];

          // Get points near location
          $.ajax({
            type: "GET",
            url: base_url + "/stockists.php",
          	data: {lat: latitude, lng: longitude, men: "true", women: "true"},
          	dataType: "json",
          	success: function(json)
          	{
          	  if(json.length > 0)
          	  {
          	    $("ul.store_info_panels li").hide();

                reset_map(latitude, longitude)
                $("ul.store_info_panels li").hide();
                $("#store_finder_overlay").fadeOut("slow", function(){
                  reset_form();
                  $("#search_again_button").show();
                });

                 var image;
                $.each(json, function(k, store)
                {
                  if(store.lat && store.lng) $("ul.store_info_panels li#store_"+store.id).css({"display": "inline-block"});
                  image = "layout/map/generic-pin.gif";
                  // TODO: Put gender pins back in
                  // image = "/layout/map/unisexpin.png";
                  // if(store.menswear == "1" && store.womenswear == "0") {
                  //   image = "/layout/map/manpin.png";
                  // }
                  // if(store.menswear == "0" && store.womenswear == "1") {
                  //   image = "/layout/map/womanpin.png";
                  // }
                  var latlng = new google.maps.LatLng(store.lat, store.lng);
                  var marker = new google.maps.Marker({
                    position: latlng,
                    map: map,
                    title: store.name,
                    icon: MEDIA_PATH+image
                  });
                  marker.store = store;
                  markers.push(marker);

            			var html="";
            			var overlay = new MyOverlay(marker, html);
            			overlay.setMap(map);

            			// Popup Contents
                  var html="<h3 style='width: 120px; text-transform: uppercase; font-weight: bold; margin: 5px;'>"+marker.store.name+"</h3><p style='line-height: 1.2; font-size: 11px; width: 120px; text-transform: capitalize; margin: 5px;'>"+marker.store.address+"</p><div style='position:absolute; bottom: 20px; right: 5px;'>";

                  // TODO: Put gender icons back in
                  // if(marker.store.womenswear == 1){
                  //   html += "<img src='" + MEDIA_PATH + "layout/map/infoWindow/woman-logo-black.gif' style='float: right;'>";
                  // }
                  //
                  // if(marker.store.menswear == 1){
                  //   html += "<img src='" + MEDIA_PATH + "layout/map/infoWindow/man-logo-black.gif' style='float: right;'>";
                  // }
                  this.html += "</div>";

                  overlay.setContentHTML(html);
            			google.maps.event.addListener(marker, 'click', function() {
            			  overlay.open();
            			});
                });
              }
              else
              {
                // No pins error
                error("There were no results for your search. Try a Town / Postcode.");
                reset_form();
              }
          	}
          });
        }
        else
      	{
      	  error("location wasn't found.");
          reset_form();
      	}
      });
    });

    reset_form();

    $("#search_again_button").click(function(e){
      e.preventDefault();
      $("#store_finder_overlay").fadeIn("slow", function(){
        $("#search_again_button").hide();
        reset_map();
      });
    });

    $("input#address").focus(function(){
      var v = $(this).attr("value");
      if (v == "Enter Location...") {
        $(this).attr("value", "");
      }
    });

    $("input#address").blur(function(){
      var v = $(this).attr("value");
      if (v == "") {
        $(this).attr("value", "Enter Location...");
      }
    });
  }
});


