var SiteIndex = function()
{
  this.map = null;
  this.mapLoaded = false;
  
  var me = this;
    
  $(document).ready(function()
  {
    me.init();
    me.initUI();
  });
}

SiteIndex.prototype.init = function()
{
}

SiteIndex.prototype.initUI = function()
{
  var me = this;
  
  this.pathInfos = eval('(' + $("#path-infos").text() + ')');
  this.userInfos = eval('(' + $("#user-infos").text() + ')');
  this.searchInfos = eval('(' + $("#search-infos").text() + ')');
  this.storesInfos = eval('(' + $("#stores-infos").text() + ')');

  $("#store-search-location-text").click(function()
  {
    me.onClickStoreSearchLocationText(this);
  });
    
  $("#store-search-form").submit(function()
  {
    return me.onSubmitStoreSearchForm();
  });
  
  this.loadMap()
  
  this.updateNearStoresScroll();

  $("#near-stores-scroll-up-btn").click(function()
  {
      me.onClickNearStoresScrollUp();
  });
  
  $("#near-stores-scroll-down-btn").click(function()
  {
      me.onClickNearStoresScrollDown();
  });
  
  $(".country-zone-label").click(function()
  {
    me.onClickCountryZoneLabel(this);
  });
  
  var event = {name:"view_display", type:"display", object:"site", data:{pageType:"site_index", search:this.searchInfos}};
  Tool.sendStats(application, event);
}

SiteIndex.prototype.updateNearStoresScroll = function()
{
  var marginTop = $("#near-stores-list").css("marginTop");
  
  if (!marginTop)
    marginTop = 0;
  else  
    marginTop = parseInt(marginTop.replace("px", ""), 10);
  
  if(marginTop + $("#near-stores-list").height() > $("#near-stores-list-container").height() + 8)
  {
    $("#near-stores-scroll-down-btn").show();
  }
  else
  {
    $("#near-stores-scroll-down-btn").hide();
  }
  
  if(marginTop < 0)
  {
    $("#near-stores-scroll-up-btn").show();
  }
  else
  {
    $("#near-stores-scroll-up-btn").hide();
  }
}

SiteIndex.prototype.onClickNearStoresScrollUp = function()
{
  var marginTop = $("#near-stores-list").css("marginTop");
  marginTop = parseInt(marginTop.replace("px", ""), 10);
  
  var containerHeight = $("#near-stores-list-container").height();
  marginTop += containerHeight;
  
  if (marginTop > 0)
    marginTop = 0;
    
  marginTop += "px";
  
  var me = this;
  $("#near-stores-list").animate({marginTop: marginTop}, 500, "swing", function(){me.updateNearStoresScroll();}); 
}

SiteIndex.prototype.onClickNearStoresScrollDown = function()
{
  var marginTop = $("#near-stores-list").css("marginTop");
  marginTop = parseInt(marginTop.replace("px", ""), 10);
  
  var containerHeight = $("#near-stores-list-container").height();
  marginTop -= containerHeight;
  
  if (marginTop + $("#near-stores-list").height() < $("#near-stores-list-container").height())
    marginTop = $("#near-stores-list-container").height() - $("#near-stores-list").height();
    
  marginTop += "px";
  
  var me = this;
  $("#near-stores-list").animate({marginTop: marginTop}, 500, "swing", function(){me.updateNearStoresScroll();}); 
}

SiteIndex.prototype.onSubmitStoreSearchForm = function()
{
  var locationTextElement = $("#store-search-location-text")[0];
  
  if (locationTextElement.value == locationTextElement.defaultValue && (this.searchInfos.store.locationText == null || this.searchInfos.store.locationText.length == 0))
  {
    locationTextElement.value = "";
  }
  else
  {
    if (Tool.isIntNumeric(locationTextElement.value))
    {
      if (locationTextElement.value.length != 5)
      {
        $("#store-search-location-text-error-zip-length").show();
        return false; 
      }
    }
  }
  
  var fieldsArray = $("#store-search-form").serializeArray();
  var searchForm = new Object();
  
  jQuery.each(fieldsArray, function(i, field)
  {
    var fieldShortName = field.name;
    var left = fieldShortName.indexOf("[");
    var right = fieldShortName.indexOf("]");
    
    if (left != -1 && right != -1)
    {
      fieldShortName = field.name.substr(left+1, right - left - 1);
      
      searchForm[fieldShortName] = field.value;
    }
  });
  
  var event = {name:"site_search_store_input", type:"visitor_action", object:"site", data:{search:searchForm}};
  Tool.sendStats(application, event, function()
  {
    $("#store-search-form").unbind("submit");
    $("#store-search-form").submit();
  });
  
  return false;
}

SiteIndex.prototype.onClickStoreSearchLocationText = function(element)
{
  if (element.value == element.defaultValue)
  {
    element.value = "";
  }
}

SiteIndex.prototype.onClickCountryZoneLabel = function(element)
{
  if (element.shown)
  {
    $(element).parent().find(".country-zone-stores-list").slideUp();
    element.shown = false;
  }
  else
  {
    $(element).parent().find(".country-zone-stores-list").slideDown();
    element.shown = true;
  }
}

SiteIndex.prototype.loadMap = function()
{
  var me = this;
  
  if (GBrowserIsCompatible())
  {
    if ($("#near-stores-gmap").height() == 0)
    {
      setTimeout(function(){me.loadMap()}, 100);
      return; 
    }
        
    var storesCoveringRadius = 0;

    if (this.storesInfos)
    {    
      for (var index = 0; index < this.storesInfos.length; index++)
      {	
        var storeInfo = this.storesInfos[index];
        if (parseFloat(storeInfo["geo_distance"]) > storesCoveringRadius)
          storesCoveringRadius = parseFloat(storeInfo["geo_distance"]);
      }
      
    	//zoom level = 10 -> 12.5km de radius
  	  var zoomLevel = 10;
      
  	  if (storesCoveringRadius)
  	    zoomLevel = (10 - Math.log(storesCoveringRadius / 12.5) / Math.log(2)) | 0;
  	  else
  	    zoomLevel = (10 - Math.log(this.searchInfos["store"]["radius"] / 12.5) / Math.log(2)) | 0;
  
      if (zoomLevel < 0)
        zoomLevel = 0;
      else if (zoomLevel > 19)
        zoomLevel = 19;
      
      var nearStoresGMap = $("#near-stores-gmap")[0];
      
      this.map = new GMap2(nearStoresGMap);
  
  	  this.map.addControl(new google.maps.SmallMapControl());
  	  
  	  var centerLat = this.searchInfos["store"]["lat"];
  	  var centerLng = this.searchInfos["store"]["lng"];
  	  
  	  var centerLatLng = new GLatLng(centerLat, centerLng);
  	  
  	  this.map.setCenter(centerLatLng, zoomLevel);
      
      for (var index = 0; index < this.storesInfos.length; index++)
      {	
        var storeInfo = this.storesInfos[index];
        
        var point = new GLatLng(storeInfo["lat"], storeInfo["lng"]);
        
        var icon = new GIcon();
        icon.image = this.pathInfos["assetsProxiwebAffiliateImageFolder"] + "map/marker.png";
        icon.shadow = this.pathInfos["assetsProxiwebAffiliateImageFolder"] + "map/marker_shadow.png";      
        icon.iconSize = new GSize(48, 48);
        icon.shadowSize = new GSize(48, 48);
        icon.iconAnchor = new GPoint(24, 48);
        icon.infoWindowAnchor = new GPoint(25, 7);
        
        opts = { 
          "icon": icon,
          "clickable": true,
          "labelText": this.storesInfos.length <= 26 ? String.fromCharCode(65+index) : (index+1),
          "labelOffset": new GSize(-7, -41),
          "labelClass": "map-marker"
        };
        
        var marker = new LabeledMarker(point, opts);
        marker.value = index;
        
  //      var marker = new GMarker(point);
      	
      	GEvent.addListener(marker, "click", function() {
          window.location.href = me.storesInfos[this.value]["sheet_url"];
        });
        
        this.map.addOverlay(marker);
      }
      
      this.drawDisc(this.map, centerLatLng, this.searchInfos["store"]["radius"], 100, "#7F7FFF", 4, 0.5, "#AFAFFF", 0.2);
    }
    
	  this.mapLoaded = true;
  }
}

SiteIndex.prototype.drawDisc = function(map, center, radius, numPoints, strokeColor, strokeWeight, strokeOpacity, fillColor, fillOpacity)
{
  var poly = [] ;
  var lat = center.lat() ;
  var lng = center.lng() ;
  var d2r = Math.PI/180 ; // degrees to radians
  var r2d = 180/Math.PI ; // radians to degrees
  var Clat = (radius/6371) * r2d ; // using 3963 as earth's radius
  var Clng = Clat/Math.cos(lat*d2r);
  
  //Add each point in the circle
  for (var i = 0 ; i < numPoints ; i++)
  {
    var theta = Math.PI * (i / (numPoints / 2)) ;
    Cx = lng + (Clng * Math.cos(theta)) ;
    Cy = lat + (Clat * Math.sin(theta)) ;
    poly.push(new GLatLng(Cy,Cx)) ;
  }
  
  poly.push(poly[0]) ;
  
  var polygon = new GPolygon(poly, strokeColor, strokeWeight, strokeOpacity, fillColor, fillOpacity);

  $(window).load(function()
  {
    map.addOverlay(polygon);
  });
}

var siteIndex = new SiteIndex();
