/**
 * @author scott
 */
// set the root path for ajaxy stuff
var ajaxurl = '/weather/ajax2.php';

$(function(){
  $(".external").live("click" , function(){
    window.open($(this).attr('href'), '', 'resizable=yes, location=yes, menubar=yes, scrollbars=yes, status=yes, toolbar=yes, fullscreen=no, dependent=no, width=920, height=650');
    return false;
  });
  
  $('#wplaceloc').live("keyup", function(){
    $('#wplace2').text($(this).val());
  });

  $('#provider').change(function(){
    var thisprovider = this.value;
    getProvData(thisprovider);
    if(($(this).val().length > 0) && $('#locations2').val().length > 0) {
      $('#gobuild').attr('disabled','');
    } else {
      $('#gobuild').attr('disabled','disabled');
    }
  });

  $('#locations2').change(function(){
    $('#wplace p').remove();
    var thislocation = $('#locations2 option:selected').text();
    var thiscountry = $('#countries2 option:selected').text();
    if($(this).val().length > 0){
      $('#wplace').empty().append('<input type="text" id="wplaceloc" value="' + thislocation + ', ' + thiscountry + '" />');
      $('#wplace2').text(thislocation + ', ' + thiscountry);
      $('.mapapikey .external').attr('href', 'http://www.google.com/maps?q=' + thislocation + ', ' + thiscountry);
    } else {
      $('#wplaceloc').remove();
      $('#wplace2').empty();
      $('.mapapikey .external').attr('href', 'http://www.google.com/maps/');
    }
    
    // test if a provider is set. If it is, make the submit button active
    if($('#provider').length>0 && (($(this).val().length > 0) && $('#provider').val().length > 0)) {
      $('#gobuild').attr('disabled','');
    } else {
      $('#gobuild').attr('disabled','disabled');
    }
    
    // see if there is chart data available for this location. If not, link to climate page
    if ($('#provider').length>0 && $('#provider').val()!="1" && !isNaN($(this).val())){
      $('#wplaceloc').after('<span id="loading"><img src="/weather/images/loading.gif" />&nbsp; Checking data...</span>');
      $.get(ajaxurl, { type: "chart-test", id: $(this).val() },
      function(data){
        $('#loading').remove();
        if (data=="0"){
          $('#wplace').append('<p class="info"><a href="'+base_url+'climate-admin.php" class="external">Add climate data</a> before proceeding</p>');
        }
      });
    }

  });
  
  $('#wplaceloc').live("change", function(){
    $('#wplace2').text($(this).val());
  });
  

  function getProvData(thisid){
    if(thisid=="" || isNaN(thisid)){
      // reset the final fields
      $('#wname, #wurl').text("");
    } else {
      // fill in the final fields
      $.get(ajaxurl, { type: "provdata", id: thisid },
        function(data){
          var warr = data.split('|');
          $('#wname').text(warr[0]);
          $('#wurl').text(warr[1]);
        }
      );
    }
  }

  $('.provider :submit').click(function(){
    var provname = $('#providername').val();
    var provurl = $('#providerurl').val();
    var tid = "";
    $.get(ajaxurl, { type: "provider", name: provname, url: provurl },
      function(data){
        // clear the provider select and fill with data
        var warr = data.split('|');
        $('#provider option:gt(0)').remove();
        $('#provider').append(warr[0]);
        tid = warr[1];
        getProvData(tid);
      });
    $('.newprovider').hide();
    // test if a provider is set. If it is, make the submit button active
    if($('#locations2').val().length > 0) {
      $('#gobuild').attr('disabled','');
    } else {
      $('#gobuild').attr('disabled','disabled');
    }
    return false;
  });

  $('.provider :radio').click(function(){
    var addprovider = this.value;
    if (addprovider=='yes'){
      $('.newprovider').show();
    } else {
      $('.newprovider').hide();
    }
  });
  $('.mapset :radio').click(function(){
    var showmap = this.value;
    if (showmap=='yes'){
      $('.mapapikey').show();
      $('.mapapikey .info a').attr('style', 'position: static');
      $('#wmap').text('Yes');
    } else {
      $('.mapapikey').hide();
      $('#wmap').text('No');
    }
  });
  $('#continent2').change(function(){
    $('#countries2').after('<span id="loading"><img src="/weather/images/loading.gif" />&nbsp; Loading data...</span>');
    var thisid = $(this).val();
    $.get(ajaxurl, { type: "country", id: thisid },
      function(data){
        // clear the country select and fill with data
        $('#locations2 option:gt(0)').remove();
        $('#output').html("");
        $('#countries2 option:gt(0)').remove();
        $('#countries2').append(data);
        $('#loading').remove();
        $('#wplace, #wplace2').empty();
        // empty out the climate data and hide the climate form
        $('#climate-loc').text("");
        $('#locid').val("");
        $('#climatedata input[id^="ht"], #climatedata input[id^="lt"], #climatedata input[id^="r"]').val("");
        $('#climatedata').hide();
        $('#climatedata img[alt="Climate Chart"]').remove();
      });
  });
  $('#countries2').change(function(){
    $('#locations2').after('<span id="loading"><img src="/weather/images/loading.gif" />&nbsp; Loading data...</span>');
    var thisid = $(this).val();
    $.get(ajaxurl, { type: "location", id: thisid },
      function(data){
        // clear the location select and fill with data
        $('#locations2 option:gt(0)').remove();
        $('#locations2').append(data);
        $('#loading').remove();
        $('#wplace, #wplace2').empty();
        // empty out the climate data and hide the climate form
        $('#climate-loc').text("");
        $('#locid').val("");
        $('#climatedata input[id^="ht"], #climatedata input[id^="lt"], #climatedata input[id^="r"]').val("");
        $('#climatedata').hide();
        $('#climatedata img[alt="Climate Chart"]').remove();
      });
  });
  
  $('#climate1 #locations2').change(function(){
    // empty out the climate data and hide the climate form
    $('#climate-loc').text("");
    $('#locid').val("");
    $('#climatedata input[id^="ht"], #climatedata input[id^="lt"], #climatedata input[id^="r"]').val("");
    $('#climatedata').hide();
    $('#climatedata img[alt="Climate Chart"]').remove();
  });
  $('#builder2').submit(function(){
    $('#output').show().html("").append('<div id="loading"><img src="/weather/images/loader.gif" /><br/>Building the widget . . .</p>');
    var pid = $('#provider').val();
    var id = $('#locations2').val();
    var showmap = $("input[name=showmap]:checked").val();
    var mapurl = $('#mapurl').val();
    var loctext = $('#wplace input').val();
    var orientation = $("input[name=orientation]:checked").val()=='h' ? '&amp;o=h' : '';
    $.get(ajaxurl, { type: "widget", pid: pid, id: id, showmap: showmap, mapurl: mapurl, placename: loctext },
      function(data){
        // clear the location select and fill with data
        $('#output').replaceWith("<div id=\"output\"><h2>Here's your weather widget</h2><p>Copy and paste the following Javascript tag into your site to display the weather widget</p><textarea class=\"highlight\" cols=98 rows=3>&lt;center&gt;&lt;br&gt;&lt;script type='text/javascript' src='"+base_url+"widget?c="+data+orientation+"'&gt;&lt;/script&gt;&lt;br&gt;&lt;/center&gt;</textarea><h3>Optional - Positioning of Widget</h3><p>The position of the weather widget on your site can be controlled using CSS styles. The following styles will center the widget in an element and give it a top and bottom margin.</p><pre>#ag_weather_widget { margin: 20px auto; }</pre></div>");
        $('#output').append("<iframe src='"+base_url+"widget?c="+data+orientation+"&amp;a=1' frameborder='0' style='width:835px;height:500px;border:0;'></iframe>");
      });
    return false;
  });
  $('#climate1').submit(function(){
    $('#loading').show();
    var id = $('#locations2').val();
    $.get(ajaxurl, { type: "climatedata", id: id },
      function(data){
        var name = $('name', data).text();
        $('#climate-loc').text(name);
        $('#locid').val(id);
        if ($('status', data).text() == 'success') {
          // fill up the fields
          var temphigh = $('temphigh', data).text();
          if (temphigh.length > 0){
            temphigharr = temphigh.split(',');
            i = 0;
            while(i < 12){
              $('#ht' + (i+1)).val(temphigharr[i]);
              i+= 1;
            }
          }
          var templow = $('templow', data).text();
          if (templow.length > 0){
            templowarr = templow.split(',');
            i = 0;
            while(i < 12){
              $('#lt' + (i+1)).val(templowarr[i]);
              i+= 1;
            }
          }
          var rainfall = $('rainfall', data).text();
          if (rainfall.length > 0){
            rainfallarr = rainfall.split(',');
            i = 0;
            while(i < 12){
              $('#r' + (i+1)).val(rainfallarr[i]);
              i+= 1;
            }
          }
        }
        $('#climatedata').show();
        $('#loading').hide();
        
      });
    return false;
  });
  $('#climatedata').submit(function(){
    // get the form data
    var ht = lt = r = "";
    $('#climatedata input[id^="ht"]').each(function(){
      ht += $(this).val() + ',';
    });
    $('#climatedata input[id^="lt"]').each(function(){
      lt += $(this).val() + ',';
    });
    $('#climatedata input[id^="r"]').each(function(){
      r += $(this).val() + ',';
    });
    var id = $('#climatedata #locid').val();
    if (ht.length>0 || lt.length>0 || r.length>0){
      //save it to db
      $.get(ajaxurl, { type: "climate-save", id: id, ht: ht, lt: lt, r: r },
      function(data){
        $('#climatedata').append(data);
        alert('Data saved\n\nPress OK to view the climate image.');
      });
    }
    return false;
  });
  $('.highlight').live('click', function(){
    $(this).select();
  });
});
