var _refresh_rate = 10000;
var map_counter = 0;
var map_maxShowPerMap = 3;
var map = null;
var map_array = Array();
var my_array = Array();
var data_timeout = 15000;
var latest_marker;
var geocoder;
var myCounter = 0;

function bigmap_call(){
  _refresh_rate  = 1000 * refresh_rate;
  $.ajaxSetup({url:data_url,global:false,timeout:data_timeout});  // type:"POST",dataType:"json",
  $.ajax({
    data:"initial=true",
    success:function(b){myParseXML(b); getCoordinates(1); map_start_big_Map(map_array)},
    error:function(b){}
  })
}

function newItem(ordnum, Suburb, PostCode, Latitude, Longitude, title, titleUrl, coverUrl, timeDiff) {

  var tmp = Object();

  tmp['ordnum']    = ordnum;
  tmp['Suburb']    = Suburb;
  tmp['PostCode']  = PostCode;
  tmp['Latitude']  = Latitude;
  tmp['Longitude'] = Longitude;
  tmp['title']     = title;
  tmp['titleUrl']  = titleUrl;
  tmp['coverUrl']  = coverUrl;
  tmp['timeDiff']  = timeDiff;
  tmp['cntShow']   = 1;
  tmp['isShow']    = 0;

  return tmp;
}

function myParseXML(xmlDoc) {

  geocoder = new GClientGeocoder();
  geocoder.setBaseCountryCode('.au')

  try
  {     
    $(xmlDoc).find("Order").each(
      function() {

        var Latitude  = 0;
        var Longitude = 0;

        var timeDiff = 0;

        var tmp = $(this);

        var ordnum   = $(tmp).attr("ordnum");

        var dateStr = $(tmp).find("OrderDate").text()  

        var Suburb   = $(tmp).find("Suburb").text()  
        var PostCode = $(tmp).find("PostCode").text();

        var datePat = /^([0-9]{4})([0-9]{2})([0-9]{2})$/; // 20090603

        var matchArray = dateStr.match(datePat); // is the format ok?

        if (matchArray == null) {
        }
        else {
          month = matchArray[2]; // parse date into variables
          day  = matchArray[3];
          year = matchArray[1];

          var oldDate = new Date(year, month - 1, day) //Month is 0-11 in JavaScript
          var today   = new Date()

          var diff = new Date();

          diff.setTime(today.getTime() - oldDate.getTime());

          var timediff = diff.getTime(); 

          var weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
          timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

          if (weeks == 0) {

            days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
            timediff -= days * (1000 * 60 * 60 * 24);

            if (days == 0) {

              timeDiff = 'Today';
            }
            else {

              if (days == 1) {

                timeDiff = 'One day ago';
              }
              else {

                timeDiff = days + ' days ago';
              }
            }
          }
          else {

            if (weeks == 1) {

              timeDiff = 'One week ago';
            }
            else {

              timeDiff = weeks + ' weeks ago';
            }
          }


          var tmp2;

          var tmp3 = $(tmp).find("Product");

          if (tmp3.size() - 1 > 0) {

            var r = Math.ceil(Math.random() * tmp3.size());

            tmp2 = tmp3[r];
          }
          else {

            tmp2 = tmp3;
          }

          var title    = $(tmp2).find("BookTitle").text();

          var titleUrl = $(tmp2).find("TitleURL").text();

          var coverUrl = $(tmp2).find("ImageURL").text();

          my_array[my_array.length] = newItem(ordnum, Suburb, PostCode, Latitude, Longitude, title, titleUrl, coverUrl, timeDiff);

        }
      }
    );
  
  } catch(e) {}

  return my_array;
}


function getCoordinates(isRepeat) {

  for(var b2 = 0; b2 - my_array.length < 0; b2++){

    var myrnd = Math.floor ( Math.random() * my_array.length ); 

    var tmp2 = my_array[myrnd];

    if (tmp2["Latitude"] == 0 || tmp2["Longitude"] == 0) {

      var Suburb   = tmp2["Suburb"]
      var PostCode = tmp2["PostCode"];

      if (geocoder && PostCode) {

        var address = Suburb + ', ' + PostCode;

        var address2 = 'Australia ' + Suburb + ', Postcode ' + PostCode;

        geocoder.getLocations(
         address2,
          function(response) {
            if (!response || response.Status.code != 200) {
              if (response && response.Status) {

                showMessage(':: ' + myrnd + '. ' + address + ' -- <b>' + response.Status.code + '</b>');
              }
              else {

                showMessage(':!: No response');
              }
            } else {

              showMessage(':: ' + myrnd + '. ' + address);

              // Retrieve the object
              place = response.Placemark[0];

              var Latitude  = place.Point.coordinates[1];
              var Longitude = place.Point.coordinates[0];

              my_array[myrnd]["Latitude"] = Latitude
              my_array[myrnd]["Longitude"] = Longitude

              setTimeout("getCoordinates(0)", 3000);
            }
          }
        );
      }

      break;
    }
  }

  if (isRepeat) {

    setTimeout("getCoordinates(1)", 10000);	
  }
}



function refreshArray() {

  var b = getMostFarIndex();

  if (b < 0) { }
  else {
    if (my_array[b]) {

      var tmp = my_array[b];

      if (map_array.length - map_maxShowPerMap >= 0) {

        for(var b2 = 0; b2 - my_array.length < 0; b2++){

          if (my_array[b2]["ordnum"] == map_array[0]["ordnum"]) {

            my_array[b2]["isShow"] = 0;
            break;
          }
        }

        map_array[0]["marker"].closeLittleInfoWidow();
        map_array[0]["marker"].remove();
        map_array.splice(0,1)
      }

      tmp["marker"] = '';

      map_array[map_array.length] = tmp;

      my_array[b]["isShow"] = 1;
      my_array[b]["cntShow"]++;
    }
  }
}


function getMostFarIndex() {

  var myIndex = -1;
  var cntShow = 10000;

  for(var b2 = 0; b2 - my_array.length < 0; b2++){

    var tmp2 = my_array[b2];

    if (tmp2["Latitude"] == 0 || tmp2["Longitude"] == 0) {

    }
    else {

      if (tmp2["isShow"] == 0) {

        var tmpPostCode = tmp2["PostCode"];
        var tmpP0 = tmpPostCode.substring(0,1)

        var notFound = 1;

        for(var b = 0; b - map_array.length < 0; b++){

          var tmp = map_array[b];

          var tmpPostCode = tmp["PostCode"];
          var tmpP1 = tmpPostCode.substring(0,1)

          var tmpP12 = tmpP1;

          if (tmpP12 == 3) {

            tmpP12 = 2;
          }
          else {
            if (tmpP12 == 2) {

              tmpP12 = 4;
            }
          }

          if (tmpP1 == tmpP0 || tmpP12 == tmpP0) {
            notFound = 0;
            break;
          }
        }

        if (notFound && ((myIndex == -1) || (cntShow - tmp2["cntShow"] > 0))) {

          cntShow = tmp2["cntShow"];
          myIndex = b2;
        }
      }
    }
  }

  showTestResults();

  return myIndex;
}


function map_refresh_big_Map(){

  refreshArray();

  for(var b = 0; b < map_array.length; b++){

    var tmp = map_array[b];

    if (!tmp["marker"]) {

      big_map_varSuburb   =tmp["Suburb"];
      big_map_varPostcode =tmp["PostCode"];
      big_map_varLatitude =tmp["Latitude"];
      big_map_varLongitude=tmp["Longitude"];
      big_map_vartitle    =tmp["title"];
      big_map_vartitleUrl =tmp["titleUrl"];
      big_map_varBookimage=tmp["coverUrl"];
      big_map_vartimeDiff =tmp["timeDiff"];

      htmlinfo='<span id="GoogleMap" onclick="big_map_openBook(\''+big_map_vartitleUrl+'\');"><img src="'+
      big_map_varBookimage+'" alt="'+big_map_vartitle+
      '" width="75" height="80" class="bookImage">';
      
      htmlinfo+='<span class="orderContent">'+
      '<span class="location">'+
      'Someone in<br/> ' + big_map_varSuburb + ', ' + big_map_varPostcode +
      '</span>';

      htmlinfo+='<span class="bookTitle"><em>Bought </em>' + '<b>' + big_map_vartitle + '</b>' + '</span>'
      
      htmlinfo+='<span class="map_minutes">' + big_map_vartimeDiff + '</span>'
      
      htmlinfo+='</span>';

      htmlinfo+='</span>';

      point = new GLatLng(big_map_varLatitude,big_map_varLongitude);
      var a = createMarker(point,htmlinfo);

      map_array[b]["marker"] = a

    }
  }

  $(document).stopTime();

  if (map_array.length - map_maxShowPerMap < 0) {

    $(document).everyTime(Math.ceil(_refresh_rate/2)+1000,function(b){map_refresh_big_Map()},10,true)
  }
  else {

    $(document).everyTime(_refresh_rate,function(b){map_refresh_big_Map()},10,true)
  }
}

function map_start_big_Map(c){
  map=new GMap2(document.getElementById("map"));
  map.addControl(new GSmallMapControl());
  map.setCenter(new GLatLng(-25.0,133.0),zoomLevel);

  $(document).stopTime();
  $(document).everyTime(_refresh_rate/10,function(d){map_refresh_big_Map()},10,true)
}

function createMarker(a,c){
  var d = new GIcon();
  d.image = map_varimageDir+"mm_20_red.png";
  d.shadow = map_varimageDir+"mm_20_shadow.png";
  d.iconSize   = new GSize(12,20);
  d.shadowSize = new GSize(22,20);
  d.iconAnchor = new GPoint(6,20);

  d.infoWindowAnchor = new GPoint(4,1);
  markerOptions={icon:d};
  var b = new GMarker(a,markerOptions);
  map.addOverlay(b);
  b.openLittleInfoWindow(c);
  return b
}

window.onunload = GUnload;

function big_map_openBook(a){
  document.location = a
}


function showTestResults() {

  return;

  myCounter++;

  var t = document.getElementById('testResults');

  var s = 'My Counter = ' + myCounter + '. <br/>' + "\n";

  for(myIdx = 0; myIdx - my_array.length < 0; myIdx++){

    var tmp2 = my_array[myIdx];

    var Suburb   = tmp2["Suburb"]
    var PostCode = tmp2["PostCode"];

    s += myIdx + '. ' + Suburb + ', ' + PostCode

    if (tmp2["Latitude"] == 0 || tmp2["Longitude"] == 0) {


    }
    else {

      s += ' :: ' + tmp2["Latitude"] + ' :: ' + tmp2["Longitude"];
    }

    s += '<br/>' + "\n";
  }

  t.innerHTML = s;
}

function showMessage(s) {

  return;

  var t = document.getElementById('message');

  t.innerHTML += s;
}
