// identica badge --  updated 7Aug2008
// 7Aug: fixed broken $.a.server links and minor styling issues; added brute-force !important to all style rules
// as always, use at your own risk
// copyright Kent Brewster 2008
// see http://kentbrewster.com/identica-badge for info
( function() { 
   var trueName = '';
   for (var i = 0; i < 16; i++) { 
      trueName += String.fromCharCode(Math.floor(Math.random() * 26) + 97); 
   }
   trueNameBadge = trueName;
   window[trueName] = {};
   var $ = window[trueName];
   
   $.f = function() {
      return { 
         runFunction : [],
         init : function(target) {
            var theScripts = document.getElementsByTagName('script');
            for (var i = 0; i < theScripts.length; i++) {
               if (theScripts[i].src.match(target)) {
                  $.a = {};
                  if (theScripts[i].innerHTML) {
                     $.a = $.f.parseJson(theScripts[i].innerHTML);
                  }
                  if ($.a.err) {
                     alert('bad json!');
                  }
                  $.f.loadDefaults();
                  $.f.buildStructure();
                  $.f.buildPresentation();
                  theScripts[i].parentNode.insertBefore($.w, theScripts[i]);
                  theScripts[i].parentNode.removeChild(theScripts[i]);
                  break;
               }
            }         
         },
         parseJson : function(json) {
            this.parseJson.data = json;
            if ( typeof json !== 'string') {
               return {"err":"trying to parse a non-string JSON object"};
            }
            try {
               var f = Function(['var document,top,self,window,parent,Number,Date,Object,Function,',
                  'Array,String,Math,RegExp,Image,ActiveXObject;',
                  'return (' , json.replace(/<\!--.+-->/gim,'').replace(/\bfunction\b/g,'function&shy;') , ');'].join(''));
               return f();
            } catch (e) {
               return {"err":"trouble parsing JSON object"};
            }
         },
         loadDefaults : function() {
            $.d = { 
               "user":"",
               "items": 10,
               "headerText" : "",
               "height" : 450,
               "width" : 300,
               "background" : "#cf682f",
               "border" : "1px solid #d2d1cd",
               "userFontSize" : "inherit",
               "textColor" : "#111111",
               "linkColor" : "#098df2",
               "headerBackground" : "transparent", 
               "headerColor" : "white",
               "evenBackground" : "#fff",
               "oddBackground" : "#cae7fd",
               "thumbnailBorder" : "1px solid black",
               "thumbnailSize" : 24,
               "padding" : 3,
               "server" : "www.saigonica.com"
            };
            for (var k in $.d) { if ($.a[k] === undefined) { $.a[k] = $.d[k]; } }
         },
          buildPresentation : function () {
            var ns = document.createElement('style');
            document.getElementsByTagName('head')[0].appendChild(ns);
            if (!window.createPopup) {
               ns.appendChild(document.createTextNode(''));
               ns.setAttribute("type", "text/css");
            }
            var s = document.styleSheets[document.styleSheets.length - 1];                     
            var rules = {
               "" : "{zoom:1!important;margin:0!important;padding:0!important;width:" + ($.a.width) + "px!important;background:" + $.a.background + "!important; color: "+ $.a.textColor +"!important; border:" + $.a.border + "!important;font:13px/1.2em tahoma, veranda, arial, helvetica, clean, sans-serif!important;}",
               "a:link" : "{cursor:pointer!important; color: #ffffff!important;}",   
               "a:visited" : "{cursor:pointer!important; color: #ffffff!important;}",            
               "a:hover" : "{cursor:pointer!important; color: #ffffff!important;}",
               "cite, date":"{margin:0 0 0 4px!important;padding:0!important;display:block!important;font-style:normal!important;line-height:" + ($.a.thumbnailSize/2) + "px!important;}",
               "date":"{font-size:87%!important;}",
               "date:after" : "{clear:both!important; content:\".\"!important; display:block!important; height:0!important; visibility:hidden!important; }",
               "h3 a:link, h3 a:visited, h4 a:link, h4 a:visited" : "{font-size:92%!important; color:" + $.a.headerColor + "!important; text-decoration: none!important; }",
               "h3 a:hover, h4 a:hover" : "{font-size:92%!important; color:" + $.a.headerColor + "!important; text-decoration: none!important; }",
               "h3" : "{margin:0!important;padding:" + $.a.padding + "px!important;font-weight:bold!important;background:" + $.a.headerBackground + " url('http://" + $.a.server + "/favicon.ico') " + $.a.padding + "px 50% no-repeat!important;text-indent:" + ($.a.padding + 16) + "px!important;}",
               "h3.loading" : "{background-image:url('http://l.yimg.com/us.yimg.com/i/us/my/mw/anim_loading_sm.gif')!important;}",
               "h4" : "{font-weight:normal!important; background:" + $.a.headerBackground + "!important;text-align:right!important;margin:0!important;padding:" + $.a.padding + "px!important;}",
               "img":"{float:left!important; height:" + $.a.thumbnailSize + "px!important;width:" + $.a.thumbnailSize + "px!important;border:" + $.a.thumbnailBorder + "!important;margin-right:" + $.a.padding + "px!important;}",
               "p" : "{margin:0!important; padding:0!important;width:" + ($.a.width - 22) + "px;overflow:hidden!important;font-size:87%!important; color: "+ $.a.textColor +"!important;}",
               "ul li":"{background:" + $.a.evenBackground + "!important;margin:0!important;padding:" + $.a.padding + "px!important;list-style:none!important;width:" + ($.a.width - 22) + "px;overflow:hidden!important; color: "+ $.a.textColor +"!important;}",
               "ul li.odd" : "{background:" + $.a.oddBackground + "!important;}",
               "ul li a:link" : "{ color: "+ $.a.linkColor +"!important; text-decoration: none!important; }",
               "ul li a:visited" : "{ color: "+ $.a.linkColor +"!important; text-decoration: none!important; }",
               "ul li a:hover" : "{ color: "+ $.a.linkColor +"!important; text-decoration: none!important; }",
               "ul":"{margin:0!important!important; padding:0!important; height:" + $.a.height + "px;width:" + $.a.width + "px;overflow:auto!important;}"
            };
            /*
            var ieRules = "";
            // brute-force each and every style rule here to !important
            // sometimes you have to take off and nuke the site from orbit; it's the only way to be sure
            for (s in rules) {
               var selector = '.' + trueName + ' ' + s;               
               var rule = rules[s];
               if (typeof rule === 'string') {
                  var important = rule.replace(/;/gi, ';');
                  if (!window.createPopup) {                   
                  	var theRule = document.createTextNode(selector + important);
                     ns.appendChild(theRule);
                  } else {
                     ieRules += selector + important;
                  }
               }
            }
            if (window.createPopup) { s.cssText = ieRules; }
            */
            var ieRules = "";
            for (r in rules) {
               var selector = '.' + trueName + ' ' + r;
               if (!window.createPopup) {
                  var theRule = document.createTextNode(selector + rules[r]);
                  ns.appendChild(theRule);
               } else {
                  ieRules += selector + rules[r];
               }
            } 
            if (window.createPopup) { s.cssText = ieRules; }
         },
         buildStructure : function() {
            $.w = document.createElement('div');
            $.w.className = trueName;         
            $.w.h = document.createElement('h3');
            $.w.h.a = document.createElement('a');
            $.w.h.a.innerHTML = $.a.user + $.a.headerText;
            $.w.h.a.href = 'http://' + $.a.server + "/" + $.a.user;
            $.w.h.a.target = '_user';
            $.w.h.appendChild($.w.h.a);
            $.w.appendChild($.w.h);
            $.w.r = document.createElement('ul');
            $.w.appendChild($.w.r);
            
            $.w.frm = document.createElement("form");
			$.w.frm.name="badgeform";
			$.w.frm.setAttribute("id", "badgeform");
			
			$.w.frm.action= 'http://' + $.a.server + "/index.php?action=t8mlet";			
			$.w.frm.method="post";
			$.w.frm.target="_blank";
			
			$.w.i = document.createElement("input");
			$.w.i.type="text";
			$.w.i.name="title";
			$.w.i.value="";
			$.w.i.onkeypress = $.f.preventSubmit;
			$.w.i.style.cssText = 'width:'+($.a.width-70)+'px!important;margin:5px 5px 0 2px!important;'
			$.w.frm.appendChild($.w.i);
			
			$.w.s = document.createElement("input");			
			$.w.s.type="button";			
			$.w.s.value="Gửi";
			$.w.s.style.cssText	= '';		
			$.w.s.onclick = function(){ $.f.beforeSubmitBadge(); }
			$.w.frm.appendChild($.w.s);
			
            $.w.appendChild($.w.frm);            
            
            $.w.f = document.createElement('h4');
            var a = document.createElement('a');
            a.innerHTML = 'Saigonica';
            a.target = '_blank';
            a.href = 'http://'+$.a.server;
            $.w.f.appendChild(a);
            $.w.appendChild($.w.f);
            $.f.runSearch();
         },         
         runSearch : function() { 
         	setTimeout(function(){$.f.runSearch();}, 5*60*1000); 
         	
         	$.w.h.className = 'loading';
            $.w.r.innerHTML = '';
            if (!$.f.runFunction) { $.f.runFunction = []; }
            var n = $.f.runFunction.length;
            var id = trueName + '.f.runFunction[' + n + ']';
            $.f.runFunction[n] = function(r) {
               delete($.f.runFunction[n]);
               $.f.removeScript(id);
               $.f.renderResult(r.value.items); 
            };
            //var url = 'http://pipes.yahoo.com/kentbrew/laconica_friends?&_render=json';
			//var url = 'http://pipes.yahoo.com/pipes/pipe.run?_id=3e28a3cde788d9733e4860d56e83615c&_render=json&n=10';
			//var url = 'http://pipes.yahoo.com/pipes/pipe.run?_id=8d4c99c52ed0b51c769fd44a70f70669&_render=json&n='+$.a.items;		
			if ($.a.user){
				var url = 'http://pipes.yahoo.com/liennguyen/saigonica?&_render=json&n='+$.a.items;
	            url += '&_callback=' + id;
	            url += '&u=' + $.a.user;
			}
			else{
				var url = 'http://pipes.yahoo.com/liennguyen/saigonicapublic?&_render=json&n='+$.a.items;
	            url += '&_callback=' + id;	            
			}
			
			 url += '&b=' + $.a.server;
            			
            $.f.runScript(url, id);
         },
         changeUserTo : function(el) {			
            $.a.user = el.rel;
            if (!el.rev) {
               el.rev = $.a.user;
            }
            $.w.h.a.innerHTML = el.rev + $.a.headerText;
            $.w.h.a.href = 'http://' + $.a.server + '/' + el.rel;
            $.f.runSearch(); 
         },
         renderResult: function(r) { 		 	
            $.w.h.className = '';			
            for (var i = 0; i < r.length; i++) {
               var li = document.createElement('li');
               if (i % 2) { li.className = 'odd'; }
               var icon = document.createElement('a');
               if (r[i].u) {
                  icon.href = r[i].u;
                  icon.target = '_blank'; 
               }
               var img = document.createElement('img');			   
			   
               img.src = r[i].n;
               img.title = r[i].t + $.a.headerText;
               icon.appendChild(img);
               li.appendChild(icon); 
               
               var user = document.createElement('cite');
               var a = document.createElement('a');
               a.rel = r[i].k;
               //a.rev = r[i].t;
               a.innerHTML = r[i].a; 
               a.href = 'http://' + $.a.server + '/' + r[i].k;			   
               a.onclick = function() {
                  $.f.changeUserTo(this);
                  return false;
               };
               user.appendChild(a);
               li.appendChild(user);
               var updated = document.createElement('date');
               if (r[i].d) {
                  updated.innerHTML = r[i].d.split(/\+/)[0].replace("T", ' ');
               } else {
                  updated.innerHTML = 'has not updated yet';
               }
               li.appendChild(updated);
               var p = document.createElement('p');
               if (r[i].t) {
                  var raw = r[i].t;
                  var cooked = raw;				  
//                  cooked = raw.replace(/\/\/u([^ ]+)/gi, "&#$1;");
                  cooked = cooked.replace(/http:\/\/([^ ]+)/g, "<a href=\"http://$1\" target=\"_blank\">http://$1</a>");
                  var woo = "@<a class=\"changeUserTo\">$1</a>";
                  cooked = cooked.replace(/@([\w*]+)/g, woo);
                  //cooked = cooked.replace(/#([\w*]+)/g, "#<a target=\"_summize\" href=\"http://summize.com/search?tag=$1\">$1</a>");
				  cooked = cooked.replace(/#([\w*]+)/g, "#<a target=\"_summize\" href=\"http://"+$.a.server+"/tag/$1\">$1</a>");
                  p.innerHTML = cooked;
               }
               li.appendChild(p);
               var a = p.getElementsByTagName('a');
               for (var j = 0; j < a.length; j++) {
                  if (a[j].className == 'changeUserTo') {
                     a[j].className = '';
                     a[j].href = 'http://' + $.a.server + '/' + a[j].innerHTML;
                     a[j].rel = a[j].innerHTML;
                     a[j].onclick = function() { 
                        $.f.changeUserTo(this); 
                        return false;
                     } 
                  }
               }
               $.w.r.appendChild(li);
            }         
         },
//LN_Begin         
         //now create the event handler function to process the event
		preventSubmit : function(e) {
		  if( !e ) {
		    //if the browser did not pass the event information to the
		    //function, we will have to obtain it from the event register
		    if( window.event ) {
		      //Internet Explorer
		      e = window.event;
		    } else {
		      //total failure, we have no way of referencing the event
		      return;
		    }
		  }
		  
		  if (e.keyCode==13){
		  	e.preventDefault();
		  	e.stopPropagation();
		  	$.f.beforeSubmitBadge();
		  }
		},
         
		beforeSubmitBadge : function(){ 
			var tit = $.w.i.value;
			$.w.i.value = '';
			var url = $.w.frm.action + '&title=' + tit;
			$.f.open(url);
			
			$.f.runSearch();
		},
		
		open: function(url){
			var windowFeatures = "scrollbars=1,toolbar=0,location=0,resizable=0,status=0,width=575,height=475";
			window.open(url, "t8mlet", windowFeatures);
		},
//LN_End
         runScript : function(url, id) {
            var s = document.createElement('script');
            s.id = id;
            s.type ='text/javascript';
            s.src = url;
            document.getElementsByTagName('body')[0].appendChild(s);
         },
         removeScript : function(id) {
            if (document.getElementById(id)) {
               var s = document.getElementById(id);
               s.parentNode.removeChild(s);
            }
         }         
      };
   }();
//   var thisScript = /^https?:\/\/[^\/]*r8ar.com\/identica-badge.js$/;
   var thisScript = /saigonicabadge.js$/;
   if(typeof window.addEventListener !== 'undefined') {
      window.addEventListener('load', function() { $.f.init(thisScript); }, false);
   } else if(typeof window.attachEvent !== 'undefined') {
      window.attachEvent('onload', function() { 
      	$.f.init(thisScript); 
      });
   }
   
   
} )();
var saigonica_badge = true;