<!DOCTYPE html>
<html>
<head>
  <title><%= @channel.name  %></title>
  <style type="text/css">
    html, body { font-family: Helvetica, Arial, sans-serif; color: #333333; font-size: 16px; background-color: #bcd1e4; }
    a { color: #55a; }
    h2 {
      margin: 10px 0 0 0;
      font: 45px Tahoma, Helvetica, Arial, Sans-Serif;
      text-align: left;
      color: #535353;
      text-shadow: 0px 2px 3px #62a09d;
    }
    h3 {
      margin: 0 0 0 0;
      font: 14px Tahoma, Helvetica, Arial, Sans-Serif;
      text-align: center;
      color: #656fad;
      text-shadow: 0px 1px 2px #62a09d;
    }
    input[type='text'] { width: 180px; }
    textarea { width: 178px; height: 40px; overflow: auto; }
    input, #submit {
      font: 14px Tahoma, Helvetica, Arial, Sans-Serif;
      text-align: left;
      color: #656fad;
      border: 1px solid #535353;

    }
    #content {
      margin: 0 auto;
      text-align: left;
      width: 980px;
    }
    #social {
      float:left;
    }
    #developers { float: right; color: #555; font-size: 13px; }
    #developers a { font-size: 11px; text-decoration: none; font-weight: bold; }
    #footer { font-size: 80%; margin-left: 5px; }
    .CB { clear: both; }
    .default_text {
      margin: 0 0 0 3px;
      font: 15px Tahoma, Helvetica, Arial, Sans-Serif;
      color: #353f7d;
    }
  </style>
  <script type="text/javascript">

    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-22749436-1']);
    _gaq.push(['_trackPageview']);

    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

  </script>
</head>
<body>

  <div id="content">

    <div id="social">
      <script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>
      <a href="http://twitter.com/share?via=socialsensors" class="twitter-share-button">Tweet</a>
      <iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.socialsensornetwork.com%2F<%= @channel.slug.gsub('-', '%2D') %>&amp;layout=button_count&amp;show_faces=true&amp;width=450&amp;action=like&amp;font=tahoma&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:21px;" allowTransparency="true"></iframe>
    </div>

    <div id="developers">
      Developers?
      <%= link_to 'JSON', "#{@api_domain}channels/#{@channel.id}/feed.json?results=100&location=true&offset=0&round=2&status=true" %>
      <%= link_to 'XML', "#{@api_domain}channels/#{@channel.id}/feed.xml?results=100&location=true&offset=0&round=2&status=true" %>
      <%= link_to 'CSV', "#{@api_domain}channels/#{@channel.id}/feed.csv?results=100&location=true&offset=0&round=2&status=true" %>
    </div>

    <div style="clear:both;"></div>

    <div style="float:left; padding-right: 40px;">
      <a href="http://www.socialsensornetwork.com">
        <img src='<%= "#{@api_domain}images/social_sensor_network_logo.png "%>' width='120' height='120' border='0' />
      </a>
    </div>

    <div style="display: block; padding-top: 25px;">
      <h2><%= @channel.name %></h2>
    </div>

    <br class="CB" />

    <% if !@channel.description.blank? %>
      <div class="default_text"><%= t(:channel_directions) %>: <%= @channel.description %></div>
      <br>
    <% end %>

    <%= form_tag "#{@post_url}" do %>
      <table>
        <% @fields.each do |f| %>
          <tr>
            <td><%= @channel[f] %></td>
            <td><%= text_field_tag "#{f}" %></td>
          </tr>
        <% end %>
        <% if !@channel.status.blank? %>
          <tr>
            <td style="vertical-align: top;"><div style="padding-top: 5px;"><%= @channel.status %></div></td>
            <td><%= text_area_tag :status %></td>
          </tr>
        <% end %>

        <tr>
          <td></td>
          <td>
            <%= submit_tag t(:submit), :id => 'submit' %>
            <span id="msg" />
          </td>
        </tr>

      </table>
    <% end %>

    <br><br>

    <div style="float: left; width: 600px;">

      <iframe width="600" height="300" frameborder="0" scrolling="no" style="border: 1px solid #cccccc;" src="<%= @api_domain %>channels/<%= @channel.id %>/maps/default?width=600&height=300&results=100&round=2&status=true&dynamic=true"></iframe>

      <% @fields.each do |f| %>
        <br><br>
        <iframe width="600" height="300" frameborder="0" style="border: 1px solid #cccccc;" src="<%= @api_domain %>channels/<%= @channel.id %>/charts/<%= f[-1] %>?width=600&height=300&results=100&round=2&color=C46353&location=true&dynamic=true&push=false&max=20000&min=-20000"></iframe>
      <% end %>

      <div id="footer">
        <br><br>
        &copy;2011 Social Sensor Network - Powered by <a href="https://www.thingspeak.com/">ThingSpeak</a>
      </div>

    </div>

    <div style="float: right; width: 300px;">

      <iframe width="300" height="1100" frameborder="0" scrolling="no" allowTransparency="true" style="border: 0;" src="<%= @api_domain %>channels/<%= @channel.id %>/social_feed"></iframe>

    </div>

  </div>

  <script type="text/javascript" src="<%= @api_domain %>javascripts/rest.js"></script>
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
  <script type="text/javascript">

    // keep track of whether user entered something in the form
    var thingspeak_user_input = 0;

    // keep track of whether user has submitted form
    var thingspeak_submitted = 0;

    // get location from latitude and longitude
    function reverseGeocode(latitude, longitude) {
      var geocoder = new google.maps.Geocoder();
      var latlng = new google.maps.LatLng(latitude,longitude);
      var location = '';

      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results) {
            $.each(results, function() {
              // if city
              if (this.types == "locality,political") {
                location = this.address_components[0].long_name;
              }
              if (this.types == "administrative_area_level_1,political") {
                if (location.length > 0) { location += ', '; }
                location += this.address_components[0].short_name;
              }
              // if country
              if (this.types == "country,political") {
                if (location.length > 0) { location += ', '; }
                location += this.address_components[0].long_name;
              }
            });
          }
        }

        // submit the post
        submitPost(latitude, longitude, location);
      });
    }

    // set the user's location
    function setLocation() {
      // Try W3C Geolocation method (Preferred)
      if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          reverseGeocode(position.coords.latitude, position.coords.longitude);
        }, function() {
          handleNoGeolocation();
        });
      // Try Google Gears Geolocation
      } else if (google.gears) {
        var geo = google.gears.factory.create('beta.geolocation');
        reverseGeocode(position.latitude, position.longitude);
      } else {
        // Browser doesn't support Geolocation
        handleNoGeolocation();
      }
    }

    // use maxmind's geoip service
    function handleNoGeolocation() {
      var latitude = geoip_latitude();
      var longitude = geoip_longitude();
      var location = geoip_city();
      if (location.length > 0 && geoip_region()) { location += ', '; }
      location += geoip_region();
      if (location.length > 0 && geoip_country_name()) { location += ', '; }
      location += geoip_country_name();
      submitPost(latitude, longitude, location);
    }

    // do the form post
    function submitPost(latitude, longitude, location) {
      if (thingspeak_submitted === 0) {
        $.create(
          // url to post to
          '<%= @post_url %>',

          // data to send
          {
            <% @fields.each do |f| %>
              <%= f %>: Number($('#<%= f %>').val().replace(/[^0-9\.\-]+/g, "")),
            <% end %>
            latitude: latitude,
            longitude: longitude,
            location: location<%= ',' if !@channel.status.blank? %>
            <% if !@channel.status.blank? %>status: $('#status').val()<% end %>
          },

          // if post was successful
          function (response) {
            var msg = (response == '0') ? '<%= t(:saved_error) %>' : '<%= t(:social_saved) %>';
            $('#msg').html(msg);
            clearMsg();
          },

          // if post failed
          function (response) {
            $('#msg').html('<%= t(:saved_error) %>');
            clearMsg();
          }
        );
      }

      // mark the form as submitted
      thingspeak_submitted = 1;
    }

    // clears message
    function clearMsg() {
      setTimeout(function() {
        $('#msg').html('');
      }, 3000);
    }

    // when document is ready
    $(document).on('page:load ready', function() {

      // event to make sure user types something into form
      <% @fields.each do |f| %>
        $('#<%= f %>').keyup(function() {
          thingspeak_user_input = 1;
        });
        $('#<%= f %>').bind('paste', function() {
          thingspeak_user_input = 1;
        });
      <% end %>
      <% if !@channel.status.blank? %>
        $('#status').keyup(function() {
          thingspeak_user_input = 1;
        });
        $('#status').bind('paste', function() {
          thingspeak_user_input = 1;
        });
      <% end %>

      // event to capture update button click
      $('#submit').click(function() {

        // if nothing entered into form
        if (thingspeak_user_input === 0) {
          $('#msg').html('<%= t(:social_channel_no_value) %>');
          clearMsg();
        } else {
          // set geolocation data (and submit the post)
          setLocation();
        }
        return false;
      });

    });
  </script>
  <script type="text/javascript" src="http://j.maxmind.com/app/geoip.js"></script>

</body>
</html>

