$(function(){

var closed_message = $("<div class='widget-closed-message'>警告文中のリンクをクリックすると表示されます</div>");

var closed = $(".widget-closed");
closed.before(closed_message);
closed.css("z-index", -1);

var openlink = $("#open-closed-widget");
openlink.click(function () {
  closed.css("z-index", "auto");
  $(".widget-closed-message").remove();
  openlink.remove();

  var url="http://pipes.yahoo.com/pipes/pipe.run";

  $.ajax( {
    "url": url,
    "data": {
      "_id" : "1b9e56951e90caec33d35d5e8a6ca247",
      "_render" : "json"
    },
    "dataType": "jsonp",
    "jsonp": "_callback",
    "success": function(e,code,xhr) {
      var items = $.map(e.value.items, function(e,i){
        var title = e.title.replace(/^turugina:\s*http:\/\/twitpic\.com\/\w+/, '');
        var url = e.link;

        var anchor = $("<a />");
        anchor.attr("href", url);
        anchor.attr("target", "_blank");
        
        return $("<div />")
          .append(
            $("<div />")
              .addClass("slide-title")
              .append(anchor.clone().append(title))
          )
          .append(
            anchor.clone().append(
              $("<img />")
              .attr("src", e.thumburl || e.imageurl)
              .attr("title", title)
            )
          );
        });

      var widget = $(".widget-drawings > .widget-content");

      if ( items.length == 0 ) {
        widget.text("データ取得に失敗しました");
        return;
      }
           
      var idx = 0;
      window.setInterval(function() {
        widget.fadeOut(500, function() {
          var content2 = $("<div>");
          content2.append(items[idx]);
          widget.empty().append(content2).fadeIn(1000);
          if ( ++idx == items.length ) idx = 0;
        });
        },
        6000
      );
      widget.text("スライドショーを開始します。しばらくお待ちください");
    },
    "error": function(code,xhr) {
      window.alert("ERROR: failed to load drawings data");
    }
  });

});

});