/*
  Author: Alexander Schwarzman (http://thor.dev.ru)
  Date:   June 2010
*/

  var map, map_zoom, map_bounds, geocoder, curLocation, latlngbounds, ctime, countries_data, total_users;
  var markers_array = new Array()
  var infowindow = null, infowindowNew = null;
  var defualt_center = new google.maps.LatLng(41.87194, 12.56738);
  var default_zoom = 2;
  var loading_box = "<div style='float:left'><img src='images/ajax-loader-white.gif' width='28' height='28' align='left'></div><div style='float:left;padding-top:14px;'>Loading. Please, wait...</div><div style='clear:both'></div>"

  function init() {
    $.jGrowl.defaults.position = 'center';
    $.jGrowl.defaults.closer = false;

    var myOptions = {
      center: defualt_center,
      zoom: default_zoom,
      navigationControl: true,
      navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    geocoder = new google.maps.Geocoder();

    getInitialData();

    $("button#vote_button").button();
    $("div#submit_vote").dialog(
      {autoOpen:false,bgiframe:true,width:330,height:490,modal:true,resizable:false,title:"My World Cup BBQ",
        open: function(event, ui){
          clear_form_elements("form#submit_vote_form");
        },
        buttons: {
          'SUBMIT': function() {
            doSubmitVote();
          },
          'Close': function() {
            $("div#submit_vote").dialog("close");
          }
        }
      }
    );
  }

  function getUsersUpdates(){
    $.ajax({
      type: "GET",
      url: "data.php?operation=get_updates&dt="+ctime,
      dataType: "json",
      success: getUsersUpdatesOutput
    });
  }

  function getUsersUpdatesOutput(jd){
    ctime = jd.server_time;
    if(!infowindow){
      if(jd.user.length>0){
        var u = jd.user[0];
        var marker = new google.maps.Marker({
            map: map, 
            position: new google.maps.LatLng(parseFloat(u.lat), parseFloat(u.lng))
        });
        if(infowindowNew){
          infowindowNew.close();
        }
        infowindowNew = new google.maps.InfoWindow({
          maxWidth: 400,
          content: "<div style='background-color:#EF5100'><div style='padding:10px'>"+
                   "  <p><b>"+u.name+"</b> is having a World Cup BBQ in...</p>"+
                   "  <p><b>"+u.address+"</b> for the</p>"+
                   "  <p><b>"+u.match+"</b> match</p>"+
                   "  <p>Supporting <b>"+u.team+"</b></p>"+
                   "  <p><b>"+u.grill+"</b> is on the grill</p>"+
                   "</div></div>"
        });
        google.maps.event.addListener(marker, 'click', function() {
          infowindowNew.open(map,marker);
        });
        google.maps.event.addListener(marker, 'mouseover', function() {
          marker.zindex = marker.getZIndex();
          marker.setZIndex(1000);
        });
        google.maps.event.addListener(marker, 'mouseout', function() {
          marker.setZIndex(marker.zindex);
        });
        infowindowNew.open(map,marker);
      }
    }
    $(jd.countries).each(function(){
      var country = null;
      var id = this.id;
      $(countries_data.countries).each(function(){
        if(id==this.id) country = this;
      });
      if(country){
        if(country.count != this.count){
          for(var i=0;i<markers_array.length;i++){
            if(markers_array[i].id==country.id){
              markers_array[i].setIcon("marker.php?country="+this.title.replace(" ","").toLowerCase()+"&c="+this.count);
            }
          }
        }
      } else {
        addMarker(this);
      }
    });
    if(jd.total_users!=total_users){
      $("div#stats h2").html("There are "+jd.total_users+" World Cup BBQ's Worldwide");
    }
    countries_data = jd;
  }

  function getInitialData(){
    $.ajax({
      type: "GET",
      url: "data.php",
      dataType: "json",
      success: getInitialDataOutput
    });
  }

  function addMarker(l){
    var cid = l.id;
    var marker = new google.maps.Marker({
        map: map, 
        id: cid,
        icon: "marker.php?country="+l.title.replace(" ","").toLowerCase()+"&c="+l.count,
        position: new google.maps.LatLng(parseFloat(l.lat), parseFloat(l.lng))
    });
    var ld = "<div style='width:400px;height:100px;background-color:#EF5100'><div style='padding:10px;'><div style='float:left'><img src='images/ajax-loader-white.gif' width='28' height='28' align='left' style='padding:9px'></div><div style='float:left;padding-top:14px;'>Loading. Please, wait...</div><div style='clear:both'></div></div></div>";
    google.maps.event.addListener(marker, 'mouseover', function() {
      marker.zindex = marker.getZIndex();
      marker.setZIndex(1000);
    });
    google.maps.event.addListener(marker, 'mouseout', function() {
      marker.setZIndex(marker.zindex);
    });
    google.maps.event.addListener(marker, 'click', function() {
      if(infowindowNew){
        infowindowNew.close();
      }
      if(infowindow){
        infowindow.close();
        infowindow.setContent(ld);
      }
      infowindow = new google.maps.InfoWindow({
        maxWidth: 400,
        content: ld
      });
      google.maps.event.addListener(infowindow, 'closeclick', function() {
        infowindow = null;
      });    
      infowindow.open(map,marker);
      curLocation = marker;
      setTimeout(function() { getCountry(cid); }, 1000)
    });
    markers_array.push(marker);
  }

  function getInitialDataOutput(jd){
    $("select#sv_match").find("option").remove();
    $(jd.matches).each(function(){
      $("select#sv_match").append("<option value='"+this.id+"'>"+this.date+" "+this.title+"</option>");
    });
    $("select#sv_grill").find("option").remove();
    $("select#sv_grill").append("<option value=''>---</option>");
    $(jd.grill_options).each(function(){
      $("select#sv_grill").append("<option value='"+this.id+"'>"+this.title+"</option>");
    });
    ctime = jd.server_time;

    $("div#stats h2").html("There are "+jd.total_users+" World Cup BBQ's Worldwide");
    total_users = jd.total_users;

    $("select#match_stats").find("option").remove();
    $("select#match_stats").append("<option value=''>- BBQ's Match Stats -</option>");
    $(jd.matches).each(function(){
      $("select#match_stats").append("<option value='"+this.id+"'>"+this.date+" "+this.title+"</option>");
    });
    $("div#stats").show();
    countries_data = jd;
    $(jd.countries).each(function(){
      addMarker(this);
    });
    setInterval("getUsersUpdates()",5000);
    getTeams();
  }

  function getCountry(id){
    $.ajax({
      type: "GET",
      url: "data.php?operation=get_country&id="+id,
      dataType: "json",
      success: getCountryOutput
    });
  }

  function getCountryOutput(jd){
    var content = "<h3 style='background: #EF5100 url(\"images/flags/"+jd.country.title.replace(" ","").toLowerCase()+"flagsmall.gif\") no-repeat top left;padding:0px 0px 2px 39px;margin-left:4px;'><b>"+jd.country.count+" World Cup Match BBQ's in "+jd.country.title+"</b></h3>";
    $(jd.grills).each(function(){
      content += "<p style='background: #EF5100 url(\"images/grills/"+this.title.toLowerCase()+".png\") no-repeat top left;padding:10px 0px 9px 42px;'>"+this.cm+" having "+this.title+" on their BBQ</p>";
    });
    infowindow.close();
    infowindow.setContent("<div style='width:400px;background-color:#EF5100'><div style='padding:10px;'>"+content+"</div></div>");
    infowindow.open(map,curLocation);
  }

  function getMatchStats(){
    var content = "";
    if($("select#match_stats").val()!=""){
      content = loading_box;
      $.ajax({
        type: "GET",
        url: "data.php?operation=get_match_stats&mid="+$("select#match_stats").val(),
        dataType: "json",
        success: getMatchStatsOutput
      });
    }
    $("div#stats p").html(content);
  }

  function getMatchStatsOutput(jd){
    var content = "<p style='background: #EF5100 url(\"images/grills/grill.png\") no-repeat top left;padding:10px 0px 9px 42px;'>"+jd.users+" World Cup Match BBQ's</p>";
    $(jd.teams).each(function(){
      content += "<p style='background: #EF5100 url(\"images/flags/"+this.title.replace(" ","").toLowerCase()+"flagsmall.gif\") no-repeat top left;padding:0px 0px 9px 38px;margin:5px 0px 5px 4px;'>"+this.cm+" fans support "+this.title+"</p>";
    });
    $(jd.grills).each(function(){
      content += "<p style='background: #EF5100 url(\"images/grills/"+this.title.toLowerCase()+".png\") no-repeat top left;padding:10px 0px 9px 42px;'>"+this.cm+" having "+this.title+" on their BBQ</p>";
    });
    $("div#stats p").html(content);
  }

  function getTeams(){
    $("select#sv_team").find("option").remove();
    $("select#sv_team").append("<option value=''>Loading...</option>");
    $.ajax({
      type: "GET",
      url: "data.php?operation=get_teams&mid="+$("select#sv_match").val(),
      dataType: "json",
      success: getTeamsOutput
    });
  }

  function getTeamsOutput(jd){
    $("select#sv_team").find("option").remove();
    $("select#sv_team").append("<option value=''>---</option>");
    $(jd.teams).each(function(){
      //$("select#sv_team").append("<option value='"+this.id+":"+this.match_id+"'>"+this.title+"</option>");
      $("select#sv_team").append("<option value='"+this.id+"'>"+this.title+"</option>");
    });
  }

  function doSubmitVote(){
    var error = false;
    $("form#submit_vote_form :input").each(function(){
      if($(this).attr("class").indexOf("required")>-1 && $(this).val()==""){
        error = true;
        $(this).addClass("req_field");
      } else {
        $(this).removeClass("req_field");
      }
    });
    if(error){
      $.jGrowl("Please, fill all required fields!");
      return;
    }
    if(!isValidEmailAddress($("input#sv_email").val())){
      $("input#sv_email").addClass("req_field");
      $.jGrowl("Email field is not valid!");
      $("input#sv_email").focus();
      return;
    } else {
      $("input#sv_email").removeClass("req_field");
    }
    codeAddress($("input#sv_address").val());
  }

  function doSubmitVoteForm(){
    $("div#submit_vote").dialog("close");
    $.jGrowl("Sending...");
    var data = $("form#submit_vote_form").serialize();
    $.ajax({
      type: "POST",
      url: "data.php?operation=submit_vote",
      data: data,
      dataType: "json",
      success: doSubmitVoteFormOutput
    });
  }

  function doSubmitVoteFormOutput(jd){
    switch(jd.response){
      case "ok":
        $.jGrowl("Thank you!");
      break;
      default:
        $.jGrowl("Unknown error!");
      break;
    }    
  }

  function clear_form_elements(trg){
    $(trg+' :input').each(function() {
      switch(this.type) {
        case 'password':
        case 'select-multiple':
        case 'select-one':
        case 'text':
        case 'hidden':
        case 'file':
        case 'textarea':
          $(this).val('');
        break;
        case 'checkbox':
        case 'radio':
          this.checked = false;
      }
    });
  }

  function codeAddress(address) {
    if (geocoder) {
      geocoder.geocode( { 'address': address,language: "en" }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          $("input#sv_address").removeClass("req_field");
          $("input#sv_lat").val(results[0].geometry.location.lat());
          $("input#sv_lng").val(results[0].geometry.location.lng());
          var country;
          $(results[0].address_components).each(function() {
            if(this.types[0]=="country") country = this.long_name;
          });
          if(!country){
            $.jGrowl("Address error: cannot find such location!");
            return;
          }
          $("input#sv_country").val(country);
          doSubmitVoteForm();
        } else {
          $("input#sv_address").addClass("req_field");
          $.jGrowl("Address error: cannot find such location!");
        }
      });
    }
  }

  function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
      $.jGrowl("Geolocation service failed.");
    } else {
      $.jGrowl("Your browser doesn't support geolocation.");
    }
  }

  function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
  }
