google.load("feeds", "1");
google.load("gdata", "1");

function handleGDError(e) {
}    

function padNumber(num) {
      if (num <= 9) {
        return "0" + num;
      }
      return num;
}


function loadCalendar(calendarAddress) {
      google.gdata.client.init(handleGDError);
      var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                        calendarAddress + 
                        '/public/full';
      var service = new 
          google.gdata.calendar.CalendarService('ieuro2008');
      var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
      query.setOrderBy('starttime');
      query.setSortOrder('ascending');
      //query.setFutureEvents(true);
      query.setSingleEvents(true);
      query.setMaxResults(35);
      var startMin = google.gdata.DateTime.fromIso8601('2008-06-01T00:00:00.000-08:00');
      var startMax = google.gdata.DateTime.fromIso8601('2008-07-01T00:00:00.000-08:00');
      query.setMinimumStartTime(startMin);
      query.setMaximumStartTime(startMax);

      service.getEventsFeed(query, addCalendarEvents, handleGDError);
}
    
function loadNewsFeed(newsAddress, count) {
      var feed = new google.feeds.Feed(newsAddress);
      feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT);
      feed.setNumEntries(count);
      feed.load(addNewsEvents);      
}

function loadMap(currentCityName) {
      var city = new Array(
        {city : "null", lat : 47.19, lng : 11.36}, 
        {city : "Vienna", lat : 48.2070, lng : 16.4208, stadium: "Ernst Happel", photo: "901285"}, 
        {city : "Klagenfurt", lat : 46.609, lng : 14.2782, stadium: "Wörthersee", photo: "6461569"}, 
        {city : "Salzburg", lat : 47.8161, lng : 12.9981, stadium: "EM Stadion Wals-Siezenheim", photo: "5837239"}, 
        {city : "Innsbruck", lat : 47.2559, lng : 11.4113, stadium: "Tivoli Neu", photo: "366451"}, 
        {city : "Basel", lat : 47.5414, lng : 7.62017, stadium: "St. Jakob-Park", photo: "906272"}, 
        {city : "Berne", lat : 46.9630, lng : 7.4649, stadium: "Stade de Suisse", photo: "1588802"}, 
        {city : "Geneva", lat : 46.1778, lng : 6.1273, stadium: "Stade de Genève", photo: "337879"}, 
        {city : "Zurich", lat : 47.3828, lng : 8.5043, stadium: "Letzigrund", photo: "5225307"}
      );
     
      if (GBrowserIsCompatible()) {
        var divMap = "container_map";
        var container = document.getElementById(divMap);
        container.style.width = "490px";
        container.style.height = "275px";
        var map = new GMap2(document.getElementById(divMap));
        var currentCity = city[0];
        for (var c = 1; c <= 8; c++) {
          if (city[c].city == currentCityName) {
             currentCity = city[c];
             break;
          }
        }
        map.setCenter(new GLatLng(currentCity.lat, currentCity.lng), (currentCity.city =="null" ? 6 : 12));
        map.setMapType(G_HYBRID_MAP);
        var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
        map.addControl(new GMapTypeControl(), topRight);
        map.addControl(new GSmallMapControl());

        var blueIcon = new GIcon(G_DEFAULT_ICON);
        blueIcon.image = "http://maps.google.com/mapfiles/kml/shapes/play.png"; 
        blueIcon.shadow = "";
        blueIcon.iconSize = new GSize(32,32);
        blueIcon.iconAnchor = new GPoint(16,16);
        markerOptions = { icon : blueIcon };
        function createMarker(latlng, number) {
          var marker = new GMarker(latlng, markerOptions);
          marker.value = number;
          GEvent.addListener(marker,"click", function() {
            var myHtml = '<div>';
            var cityLink = '<a href="' + (city[number].city.toLowerCase()) + '.html">';
            
            myHtml += '<div style="font-weight: bold; font-size: 130%; text-align:left;">' + city[number].city + '</div>';
            myHtml += '<div style="font-weight: bold; text-align:center;">'+((currentCity.city == city[number].city) ? '' : cityLink) + '<img src="http://mw2.google.com/mw-panoramio/photos/thumbnail/' + city[number].photo + '.jpg" width="100px" height="75px" border="0">' + ((currentCity.city == city[number].city) ? '' : '</a>')+'</div>';
            myHtml +='<div style="font-weight: bold; text-align:center;">'+ ((currentCity.city == city[number].city) ? '' : cityLink) + city[number].stadium + ((currentCity.city == city[number].city) ? '' : '</a>')+ '</div>';
            myHtml +='<div class="match_location">Image &copy; <a href="http://www.panoramio.com/map/#lt='+city[number].lat+'&ln='+city[number].lng+'&z=0&k=2&a=1&tab=1" target="_blank">Panoramio</a></div>';
            myHtml +='</div>';
            map.openInfoWindowHtml(latlng, myHtml);
          });
          return marker;
    	  }

        for (var i = 1; i <= 8; i++) {
           var point = new GLatLng(city[i].lat, city[i].lng);
           map.addOverlay(createMarker(point, i));
        }
      }
}

   
function parseCalendarTitle(title) {
      var teamList = new Array(
        {name: "Austria", shortcut: "aut"},
        {name: "Croatia", shortcut: "cro"},
        {name: "Czech", shortcut: "cze"},
        {name: "France", shortcut: "fra"},
        {name: "Germany", shortcut: "ger"},
        {name: "Greece", shortcut: "gre"},
        {name: "Italy", shortcut: "ita"},
        {name: "Netherlands", shortcut: "ned"},
        {name: "Poland", shortcut: "pol"},
        {name: "Portugal", shortcut: "por"},
        {name: "Romania", shortcut: "rou"},
        {name: "Russia", shortcut: "rus"},
        {name: "Spain", shortcut: "esp"},
        {name: "Switzerland", shortcut: "sui"},
        {name: "Sweden", shortcut: "swe"},
        {name: "Turkey", shortcut: "tur"}
      );
      title = title.substring(title.indexOf(": ") + 2);
      for (var i = 0; i < 16; i++) {
        teamStringLeft = '<a href="' + teamList[i].name.toLowerCase() + '.html" style="background: url(img/flag_' + teamList[i].shortcut + '.gif) no-repeat 0px 50%;" class="teamlinkleft">' + teamList[i].name + '</a>';
        teamStringRight = '<a href="' + teamList[i].name.toLowerCase() + '.html" style="background: url(img/flag_' + teamList[i].shortcut + '.gif) no-repeat 100% 50%;" class="teamlinkright">' + teamList[i].name + '</a>';
        if (title.indexOf(teamList[i].name) <= 1) {
          title = title.replace(teamList[i].name, teamStringLeft);
        } else {
          // Right one seems ugly
          title = title.replace(teamList[i].name, teamStringLeft);
        }
      }
      title = '<div>' + title + '</div>';
      return title;
}
    
function parseCalendarInfo(location, date, linkUrl) {
      var dateString;
      dateString = (date.getMonth() + 1) + "-" + date.getDate();
      dateString += " " + date.getHours() + ":" + padNumber(date.getMinutes());
      location = location.substring(0, location.indexOf(" - "));
      location = '<div class="match_location"><a href="' + linkUrl + '" title="Add to calendar">' + dateString + '</a> @ <a href="' + location.toLowerCase() + '.html">' + location + '</a></div>';
      return location;
}
    
function addCalendarEvents(feedRoot) {
      var entries = feedRoot.feed.getEntries();
      var eventDiv = document.getElementById("container_calendar");
      if (eventDiv.childNodes.length > 0) {
        eventDiv.removeChild(eventDiv.childNodes[0]);
      }	  
      var out = "<ul>";
      /* loop through each event in the feed */
      for (var i = 0; i < entries.length; i++) {
        var entry = entries[i];
        var title = parseCalendarTitle(entry.getTitle().getText());
        var info = parseCalendarInfo(entry.getLocations()[0].getValueString(), entry.getTimes()[0].getStartTime().getDate(), entry.getHtmlLink().getHref());
        out += '<li class="panel_box'+(i%2==1 ? ' match_b' : "")+'">';
        out += title + info + "</li>";
      }
      out +="</ul>";
      eventDiv.innerHTML = out;
}

function addNewsEvents(result) {
        var divNews = "container_news";
        var divHeadline = "container_headline";
        if (!result.error) {
          var newsContainer = document.getElementById(divNews);
          var headlineContainer = document.getElementById(divHeadline);
          var filledHeadline = 0;
          if (headlineContainer == null) {
            filledHeadline = 1;
          }
          var out = "<ul class='list_news'>";
          for (var i = 0; i < result.feed.entries.length; i++) {
            var entry = result.feed.entries[i];
            var t = entry.xmlNode.getElementsByTagName("enclosure");
            var image;
            if (t.length <= 0) {
              image = "";
            } else {
              image = t[0].getAttribute("url");
            }
            
            if ((image != "")&&(filledHeadline == 0)) {
              filledHeadline = 1;
              image = image.replace("_s5", "_w3");              
              hout = "";
              hout += '<div class="panel_imagebox">';
              hout += '<a href="' + entry.link + '" target="_blank"><img src="' + image + '"></a>';
              hout += '<div class="headline_shadow">' + entry.title + '</div>';
              hout += '<div class="headline_text">' + entry.title + '</div>';
              hout += '</div>';
              hout += '<a href="' + entry.link + '" target="_blank">' + entry.contentSnippet + '</a>';
              headlineContainer.innerHTML = hout;
            } else {
              var date = new Date(entry.publishedDate);
              out += '<li>';
              out += '<a href="' + entry.link + '" target="_blank">' + entry.title + '</a><span style="color:#999999"> (' + (date.getMonth() + 1) + "-" + date.getDate() + ')</span>'; 
              out += '</li>';
            }
          }
          out += "</ul>";
          newsContainer.innerHTML = out;
        }
}
    
function jsonFlickrApi(obj) {
      var divPhoto = "container_photo";
      var containerPhoto = document.getElementById(divPhoto);
      var photoList = obj.photos.photo;
      var out = '<div class="list_photo">';
      for (var i = 0; i < photoList.length; i++) {
        var p = photoList[i];
        thumbnailUrl = "http://farm" + p.farm + ".static.flickr.com/" + p.server + "/" + p.id + "_" + p.secret + "_s.jpg";        
        linkUrl = "http://www.flickr.com/photos/" + p.owner + "/" + p.id + "";
        if (i  == 5) {
          out += '</div>';
          out += '<div class="list_photo">';
        }
        out += '<a class="link_photo" target="_blank" href="'+linkUrl + '"><img width="75" height="75" src="' + thumbnailUrl + '"/></a>';
      }
      out += '</div>';
      containerPhoto.innerHTML = out;
}


