var GPlotter = Class.create();

Object.extend(GPlotter.prototype, {
  initialize: function() {
    this.VERSION = '0.9.0';
    this.initialized = false;
    this.totalFoundItems = 0; 
    this.mapDocument = "";
    this.maxIconNumber = 25;
    this.baseIcon = new GIcon();
    this.markers = new Array();
    this.baseIcon.shadow = "images/shadow50.png";
    this.baseIcon.iconSize = new GSize(20, 34);
    this.baseIcon.shadowSize = new GSize(37, 34);
    this.baseIcon.iconAnchor = new GPoint(9, 34);
    this.baseIcon.infoWindowAnchor = new GPoint(9, 2);
    this.baseIcon.infoShadowAnchor = new GPoint(18, 25);
    this.iconUrl = "images/";
    this.RED = "r";
    this.GREEN = "g";
    this.BLUE = "b";
    this.color = this.GREEN;
    this.winnerColor = this.BLUE; 
    this.maps = new Array();
  },
  // Functions
  setColor: function(c) {
    if (c == this.RED) {
      this.color = this.RED;
    }
    else if (c == this.GREEN) {
      this.color = this.GREEN;
    }
    else if (c == this.BLUE) {
      this.color = this.BLUE;
    }
    else {
      alert("Color not supported: " + c);
    }
  },
  click: function(i) {
     GEvent.trigger(this.markers[i], "click");
  },
  setIconUrl: function(url) {
    this.iconUrl = url;
  }, 
  getMinMax: function(page, total, totalGroup, isMin){
        var j = 0; 
        for(var i = 0; i< page; i+totalGroup){ j++; if((j*totalGroup) >= page) break;}
        var largestValue = (j*totalGroup);  
        var ret = (isMin)?((totalGroup*j)-totalGroup)+1:((totalGroup*(j+1))-totalGroup);
        ret= (isMin)?(ret<1?1:ret):(ret>total?total:ret);
        return (isNaN(ret))?1:ret; 
  },
  getURL: function(allItems, page, keyword, city, zip, scratch, wS, region)
  {  
        var r = parseInt(allItems)%5; 
        var totalPages = (r!=0)?((allItems-r)/5)+1:allItems/5;
        
        var c = ""; 
        page = (isNaN(page))?1:parseInt(page); 
        page = (page<1)?1:(page>totalPages)?totalPages:page; 
         
        var maxindex = this.getMinMax(page, totalPages, 10, false); 
        var minindex = this.getMinMax(page, totalPages, 10, true); 

        var base = "Default.aspx?keyword="+keyword; 
        var citybase = "&city=" + city; 
        var zipbase = "&zip="+zip; 
        var pagebase = "&page="; 
        var regionbase = "&regionID="+region;
        var scratchBase = "&scratch="+scratch;
        var wsBase = "&winnerStores="+wS;  
        var isNotMore = (maxindex+1 >= totalPages); 
        var isNotLess = (minindex-1 <= 0); 
        
        if(!isNotLess)c+="<a href="+base+citybase+zipbase+scratchBase+wsBase+regionbase+pagebase+(minindex-1)+" class='results'><<</a>  "; 
        for(var i = minindex; i <= maxindex; i++){if(i==page){c+="<b style='font-size:0.85em;'>["+i+"]</b> "; }else{c+="<a href="+base+citybase+zipbase+scratchBase+wsBase+regionbase+pagebase+i+" class='results'>"+i+"</a> "; }}  
        if(!isNotMore) c+="<a href="+base+citybase+zipbase+scratchBase+wsBase+regionbase+pagebase+(maxindex+1)+" class='results'>>></a>  "; 
        return c; 
  }, 
  PageQuery: function(q) {
        if(q.length > 1) this.q = q.substring(1, q.length);
        else this.q = null;
        this.keyValuePairs = new Array();
        if(q) {for(var i=0; i < this.q.split("&").length; i++) {this.keyValuePairs[i] = this.q.split("&")[i];}}
        this.getKeyValuePairs = function() { return this.keyValuePairs; }
        this.getValue = function(s) {for(var j=0; j < this.keyValuePairs.length; j++) {
                if(this.keyValuePairs[j].split("=")[0] == s)return this.keyValuePairs[j].split("=")[1];}return false;}
                this.getParameters = function() {var a = new Array(this.getLength());for(var j=0; j < this.keyValuePairs.length; j++) {
                    a[j] = this.keyValuePairs[j].split("=")[0];}return a;}
        this.getLength = function() { return this.keyValuePairs.length; } 
  },
  queryString: function(key){
        var page = new PageQuery(window.location.search); 
        return unescape(page.getValue(key)); 
  }, 
  displayItem: function(key){
        return (queryString(key)!='false') ? queryString(key) : 0;
  },
  plot: function(mapId, labelsId, feedName, noValueID, pagingUpID, pagingDownID, city, keyword, zip, scratch, winningStores, region, currentPage, topPagingID, bottomPagingID) 
  {
    if (!this.initialized) {
      var plotter = this;
      this.labels = $(labelsId);
      this.noValueID = $(noValueID); 
      this.pagingUp = $(pagingUpID);
      this.pagingDown = $(pagingDownID);
	  this.topPaging = $(topPagingID); 
	  this.bottomPaging = $(bottomPagingID); 
      this.cityValue = city; 
      this.keywordValue = keyword; 
      this.zipValue = zip; 
      this.pageValue = currentPage; 
      this.scratchValue = scratch; 
      this.winningStoresValue = winningStores; 
      this.region = region; 
      var mapElem = $(mapId);
      if (mapElem) {
        var map;

        if (this.maps[mapId] && this.maps[mapId].setCenter) {
          map = this.maps[mapId];
        }
        else {
          map = new GMap2(mapElem);
          map.addControl(new GSmallMapControl());
          map.addControl(new GMapTypeControl());
          this.maps[mapId] = map;
        }

        var params = {
          map : map,
          mapID : mapId,
          labelsID : labelsId, 
          novalueID : noValueID, 
          pagingUpID : pagingUpID,
          pagingDownID : pagingDownID,
          zip : zip,
          keyword : keyword, 
          city : city, 
          scratch : scratch, 
          winningStores : winningStores, 
          region : region
        }

        this.successHandler = this.handleResponse.bind(this, params);

        var opt = {
          asynchronous:true,
          method: 'GET',
          onSuccess: this.successHandler,
          on500: function(t) {
              alert('Error 500: location "' + t.statusText + '" was not found.');
          },
          on404: function(t) {
              alert('Error 404: location "' + t.statusText + '" was not found.');
          },
          onFailure: function(t) {
              alert('Error ' + t.status + ' -- ' + t.statusText);
          }
        }

        new Ajax.Request(feedName, opt);

        this.initialized = true;
      }
    }
  },
  handleResponse: function(p, t) {
    this.runPlotter(p.map, t.responseXML);
  },
  runPlotter: function(map, xmlDoc)
  {
    
    this.mapDocument = xmlDoc;
    var root = xmlDoc.getElementsByTagName("locations")[0];
    var version = root.getAttribute("version");
    if (version == "0.9") {
      this.runPlotter09(map, xmlDoc);
    }
    else {
      alert("Locations version not supported");
    }
  },
  runPlotter09: function(map, xmlDoc)
  {

    var innerHTML = "";
    var cLat, cLong, zoomLevel;
    var root = xmlDoc.getElementsByTagName("locations")[0];
    cLat = root.getAttribute("latitude");
    cLong = root.getAttribute("longitude");
    zoomLevel = parseInt(root.getAttribute("zoomlevel"));
    this.totalFoundItems = parseInt(root.getAttribute("totalrecords")); 
    this.page = parseInt(root.getAttribute("pagenumber")); 
    var centerPoint = new GLatLng(cLat, cLong);
    map.setCenter(centerPoint, zoomLevel);
       
    var bounds = map.getBounds(); 
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat(); 
     

    var locations = xmlDoc.getElementsByTagName("location");
     var bounds = new GLatLngBounds();
    for (var i = 0;i<locations.length;i++) {
      var node = locations[i];
    
      var label = node.getAttribute("label");
      var latitude = node.getAttribute("latitude");
      var longitude = node.getAttribute("longitude");
      var retailer = this.getTagNodeValue(node, "retailer");
      var street = this.getTagNodeValue(node, "street");
      var suite = this.getTagNodeValue(node, "suite");
      var city = this.getTagNodeValue(node, "city");
      var state = this.getTagNodeValue(node, "state");
      var phone = this.getTagNodeValue(node, "phone");
      var zip = this.getTagNodeValue(node, "zip");
      var isWinner = this.getTagNodeValue(node, "winners"); 
      
      var totalWinners = parseInt(isWinner); 
      
      var latForPoint = parseFloat(latitude);
      var lngForPoint = parseFloat(longitude);
      var point = new GLatLng(latForPoint,lngForPoint);

      var number = i + 1
      innerHTML = innerHTML + "<div class='storeName'><a href='javascript:plotter.click("+this.markers.length+");'>"+number+") "+retailer + "</a></div>";
      var address = "";
      var listAddress = ""; 
      if (street != "") { address += street; listAddress+="<div class='storeInfo'>"+street+"</div>";}
      if (suite) { address += "<br />" + suite; }
      if (city) { address += "<br />" + city; listAddress+="<div class='storeInfo'>"+city+", WA " +zip.substr(0,5)+ "</div>";}
      address += ", WA";
      if (zip) { address += " " + zip; }
      if (phone) { address += "<br />Phone: " + phone + ""; listAddress+="<div class='storeInfo'>Phone: " + phone + "</div>"}
      innerHTML += listAddress+"<br />";;
      
      if(totalWinners > 0)
      {
        address += "<br /><br />This store has <b>" + totalWinners + "</b> jackpot winner"; 
        address +=  totalWinners > 1 ? "s!" : "!"; 
      }

      var icon = new GIcon(this.baseIcon);
      if (number <= this.maxIconNumber) 
      {
        if(totalWinners == 0){
            icon.image = this.iconUrl + "icon" + this.color + number + ".png";
        }else{
            icon.image = this.iconUrl + "icon" + this.winnerColor + number + ".png";
        }
      }
      else {
        icon.image = this.iconUrl + "icon" + this.color + ".png";
      }
      var marker = this.createMarker09(label, longitude, latitude, icon, address);

      map.addOverlay(marker);
      bounds.extend(point);
    }

    if(i == 0)
    {

        var centerPoint = new GLatLng(cLat, cLong);
        map.setCenter(centerPoint, 6);
    }else{

        map.setZoom(map.getBoundsZoomLevel(bounds));
        map.setCenter(bounds.getCenter());
    }

    if(i == 0)
    {
        if(this.noValueID){
    
            this.noValueID.style.visibility ="visible";
            this.noValueID.innerHTML="We're sorry, but we couldn't find any Washington's Lottery retail locations based on your search. Please revise your criteria and search again.";   
            
        }    
    }
    if (this.labels) 
        this.labels.innerHTML = innerHTML;
	
	if(this.pagingUp)
		this.pagingUp.innerHTML = this.getURL(this.totalFoundItems, this.pageValue, this.keywordValue, this.cityValue, this.zipValue, this.scratchValue, this.winningStoresValue, this.region);  
	
		if(this.pagingDown)
		this.pagingDown.innerHTML = this.getURL(this.totalFoundItems, this.pageValue, this.keywordValue, this.cityValue, this.zipValue, this.scratchValue, this.winningStoresValue, this.region);  
	
    var totalStores = (this.totalFoundItems) ? "Total Stores Found: <b>"+this.totalFoundItems + "</b>" : ""; 
	
    if(this.topPaging)
        this.topPaging.innerHTML = totalStores; 
		
	if(this.bottomPaging)
		this.bottomPaging.innerHTML = totalStores; 
      
    
    
  },
  createMarker09: function(label, longitude, latitude, icon, address)
  {
    var point = new GLatLng(latitude, longitude);
    var marker = new GMarker(point, icon);
    var text = "<b>" + label + "</b>";
    if (address != "") { text += "<br />" + address; }
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(text);
    });
    this.markers[this.markers.length] = marker;
    return marker;
  },
  getTagNodeValue: function(node, tagName)
  {
      var value = "";
      var tag = node.getElementsByTagName(tagName)[0];
      if (tag && tag.firstChild) {
        value = tag.firstChild.nodeValue;
      }
      return value;
  },
  enableDebug: function() { alert('Function not supported: enableDebug'); }
});



