if (typeof console == "undefined") {
 var F = function(){};
 var console={log:F, info:F, dir:F};
}



var addListener = (function() {
    if ( window.addEventListener ) {
        return function(el, type, fn) {
            el.addEventListener(type, fn, false);
        };
    } else if ( window.attachEvent ) {
        return function(el, type, fn) {
            var f = function() {
                fn.call(el, window.event);
            };
            el.attachEvent('on'+type, f);
        };
    } else {
        return function(el, type, fn) {
            element['on'+type] = fn;
        }
    }
})();


var RND = function (tmpl, ns)
{
  var fn = function(w, g) {
    g = g.split("|");
    var cnt = ns[g[0]];
    for(var i=1; i < g.length; i++)
      cnt = eval(g[i])(cnt);
    return cnt || w;
  };
  return tmpl.replace(/%([A-Za-z0-9_|.]*)/g, fn);
}

//window.localStorage = window.localStorage || window.globalStorage[location.hostname];

function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}


Deferred.define();

var viewAndInsertComment = function (story_id, paragraph_limit) {
    //var anchor =$("h2 a", $("#centerblocks div.storytext:has(ul.feedback li > a[href])"));
    
    var template = '<div style="margin:0pt;padding:0pt;text-align:left">'+
  '<ul style="list-style-position: outside;list-style-type: none; margin: 0; padding: 0;">'+
    '<li style="display:block; margin: 1em 0 0.5em 0; padding: 4px;  border: 1px solid #E7E7E7;  background: #F7F7F7;">%title</li>'+





    '<li style="display:block; margin: 0 0 1em 0;  padding: 0;">%author</li>    '+
  '</ul>'+
  '<div style="margin: 0 0 1em 0;  padding: 0;"><p> %comment </p></div>'+
'</div>';       
   // for (var i =0, l=anchor.length; i < l; ++i) {
      //var href = anchor.get(i).href;
      //var slash_point = href.lastIndexOf("/");
      //var base = href.substr(0, slash_point);
      var base = "http://www.shibaura-hac.net/mycms/article.php";
      //var target = href.substr(slash_point + 1);
      var target = story_id.split("_")[1];
      console.log("target",  target);
      
      $.post(
          base, 
          {
            order:"ASC", mode:"flat", story:target, type:"article"
          }, 
          function(response, status){
            //console.log(response, status)
            var sid = $("#commentbar-selector input:hidden[name=story]", $(response)).val();
            console.log("storyId..", sid);
            var insert_point = $("#centerblocks .feedback :has(a[href*='" + sid + "'])");
            var content ="";
            var html = $("#comments .block-comment-content", $(response));
            //console.log("storyId..", sid, "InsertPoint..", insert_point);
            for (var i = 0, l = html.length; i < l; ++i) {
             content += RND(template, {
                title: $(".title" ,html.get(i)).text(), 
                author: $(".author" ,html.get(i)).text(),
                comment: $(".comment" ,html.get(i)).text()
             });
            }
            console.log("content  ", content)
            console.log("storyId..", sid, "InsertPoint..", insert_point);
            $("<div style='border-style:solid; border-width:thin;'>" + content +"<\/div>").insertAfter(insert_point);

      });
      //debugger;
  //  }
    

}

var setPdfClicker = function () {
    if (!!$("#research_list")) {
        var pdf_anchors = $("#research_list a");
        for (var i = 0,l = pdf_anchors.length; i<l; ++i) {
            var regexp_result = pdf_anchors.get(i).href.match(/(20\d{2})\/(.*\.pdf)/);
            var year =regexp_result[1];
            var file_name = regexp_result[2];
            var track_address = "/research/" + year + "/" + file_name;
            addListener(pdf_anchors.get(i), "click", function()
            {
                pageTracker._trackPageview(track_address);
            }, false);

        }

    }
}

var insertCommentLink = function ()
{

    //var anchor = $("#centerblocks div.storytext ul.feedback li > a[href]");
    var anchor = $("#centerblocks div[class*=storytext] ul.feedback li > a[href]");
    for (var i =0, l=anchor.length; i < l; ++i) {
      var href = anchor.get(i).href;
      var slash_point = href.lastIndexOf("/");
      var base = href.substr(0, slash_point);
      var target = href.substr(slash_point + 1);
      if (target.indexOf("#") != -1) {
          target = target.split("#")[0];
      }
      var tag = RND ("<button id='%id'>書き込みを読み込む<\/button>", {id: "sid_"+target});
      $(tag).insertAfter($(anchor.get(i)));
      $("#sid_"+ target).click(function () {
        
        viewAndInsertComment($(this).attr("id"));
/*
        return (function (id) { 
          var hoge = id;
          return (function () {
              console.log(hoge);
            })();
          })(target);
*/
      })
    }
    
    
}

var insertFeaturedStoryTextComment = function ()
{
    var anchor = $("#centerblocks div.featuredstorytext ul.feedback li > a[href]");
    for (var i =0, l=anchor.length; i < l; ++i) {
      var href = anchor.get(i).href;
      var slash_point = href.lastIndexOf("/");
      var base = href.substr(0, slash_point);
      var target = href.substr(slash_point + 1);
      if (target.indexOf("#") != -1) {
          target = target.split("#")[0];
      }

      viewAndInsertComment("sid_" + target);

    }

}

var setupMigrationMode = function()
{
  $("#leftblocks").empty().css("margin", "0");
  $("#centerblocks").css({"width":"100%", "margin":"0"});

}

//insertFeaturedStoryTextComment();
$(function () {

    if (location.href.indexOf("diary") != -1 || location.href.indexOf("bbs") != -1) {
      setupMigrationMode();
    }

    insertCommentLink();

    //if (!!getCookie("gl_session") && location.href.indexOf("admin") < 0 ) {
    if (!!getCookie("gl_session")) {
         console.info("login");
    } else {
         console.info("not login"); 
    }
    if (!localStorage.username) {
      console.log("getJSON start");
      $.getJSON("http://www.shibaura-hac.net/mycms/get_username.php").next(function(status){
          console.log("save to localStorage");
          localStorage.username = username = status.username;
          console.log("username is %s", username);
      });
    } else {
          console.log("username:(%s) is saved" ,localStorage.username);
          username = localStorage.username;
    }
   /*
    $("a[@href*='%auth']").each( function(){
               $(this).attr("href",
                  $(this).attr('href').replace("%auth",  username + ":"+ getCookie('login_time'))   
               )
     }) ; 

    for (var i = 0, l = menu_list.length; i < l; ++i) {
       for (var key in menu_list[i]) {
             console.log("key:%s, value:%s", key, menu_list[i][key])
       }
    }
   */
    $("body").append('<div id="gl_menu" style="position:absolute;top:10px;left:10px;width:30px; height:30px;background-color:transparent;"></div>');

    $("#gtalk_control").one('click' , function()
    {
       
      console.log("gtalk toggle.");
      for (var i = 0, l = GoogleTalk.list.length; i < l; ++i) {
        $("#gtalk").append(RND('<img height="9" width="9" style="padding:0 2px 0 0;margin:0;border:none" src="%img_address&w=9&h=9" alt="">'
    + '<a href="%chat_address" target="_blank" title="Click here to chat with %name">%section</a><br />', 
            {chat_address: GoogleTalk.base + "Start" + GoogleTalk.list[i].address, 
              img_address:  GoogleTalk.base + "Show" + GoogleTalk.list[i].address, 
              name: GoogleTalk.list[i].name, 
              section:GoogleTalk.list[i].section}));
      }
      /*
      $("#gtalk").append('<script charset="utf-8" src="http://www.lingr.com/room/8ND0uJ7tEAD/badge/render" type="text/javascript"/>');
     */
     //$('#gtalk').append('http://www.lingr.com/room/8ND0uJ7tEAD/badge/render');

      return false;
    });
    setPdfClicker();

})




