var _templ = {
	login: "<div style=\"margin-top:170px;\"><form action=\"javascript:_daily.login($('#userinput').val());\"><input type=\"password\" id=\"userinput\" size=\"25\"><input type=\"submit\" value=\"Open the door\"></form></div>",
	navigation: "<br/><br/><a href=\"#hello\"><img src='assets/image/hello.png' width='20' height='20' /></a>&nbsp;<a href=\"#shout\"><img src='assets/image/shout.png' width='20' height='20' /></a>&nbsp;<a href=\"#feed\"><img src='assets/image/feeds.png' width='20' height='20' /></a>&nbsp;<a href=\"#thought\"><img src='assets/image/thoughts.png' width='20' height='20' /></a></small>",
	shoutpanel: "<form action=\"javascript:_daily.shout.send();\">" + 
					  "<textarea rows=\"2\" id=\"newshout\"></textarea><br/>" + 
					  "<input type=\"submit\" value=\"shout!\"><div id=\"characters\"></div>" + 
					  "</form>" + 
 	              "<p align=\"right\">Auto reload new shouts ? <a href=\"javascript:_daily.shout.toggleMonitoring();\" id=\"shoutMonitor\">yes</a></p>" + 
					  "<div id=\"shoutlist\"></div>",
   feedpanel:  "<form action=\"javascript:_daily.feed.add();\">"+
            	"		<input id=\"feedurl\" style=\"width:100%\" type=\"text\" /><br/>"+
            	"		<input type=\"submit\" value=\"add new feed\">&nbsp; <a href='javascript:_daily.feed.update();'><img src='assets/image/reloadfeeds.png' width='20' height='20' /></a>"+
            	"</form>"+
            	"<div id=\"rsslist\"></div>",
   hotairpanel:  "<div class=\"box\"><a href=\"javascript:$('#hotadder').slideDown();\">NEW THOUGHT</a></div>"+
               "<div id=\"hotadder\" style=\"display: none;\">"+
            	"	<form action=\"javascript:_daily.air.add();\">"+
            	"		<textarea rows=\"3\" id=\"newair\"></textarea><br/>"+
            	"		<a href=\"javascript:_daily.air.cancel();\">Cancel</a> or	<input type=\"submit\" value=\"add!\">"+
            	"	</form>"+
            	"</div>"+
            	"<div id=\"airlist\"></div>",
	hellopanel: "<div id=\"hellolist\">so sagt man das <span id=\"hello-item\"></span></div>"
};

var _localDebug = false;

//###############################
//##### Hello ######
function Hello ()
{
//### variables
	var	self    = this;
	this.handle = false;
	
//### stop monitoring
   this.stopMonitoring = function ()
   { 
	  if (this.handle !== false) {
		clearInterval (this.handle);
		this.handle = false;
	  }
   }
	
//### quotes	
	this.quote = function ()
	{
		var list = ["Welcome", "Habari", "Willkommen", "Hej", "Merhaba", "Bonjour","bok","Sveiki","ahoj"];
		var id = Math.floor(Math.random()*(list.length));
   		$("#hello-item").html (list[id]);
	}
		
//### start monitoring
   this.startMonitoring = function ()
   {
		$("#list").html (_templ.hellopanel);
		
		this.quote ();
		
		this.handle = setInterval(function () {
			self.quote ();
			
        },8000);
   }	
}

//###############################
//##### class daily (main) ######
function DailyBox ()
{
//### variables
	var	self = this;
	
	this.shout = new Shout();
	this.feed = new Feed ();
	this.input = new InputHandler ();
	this.air   = new HotAir ();
	this.hello = new Hello ();
	
	$(window).bind('hashchange', function (evt) {
		self.hashHandler (evt);
    });
	
    //# startup animation
	if (_localDebug == true) {
		$("#list").html (_templ.login);
		$("#list").fadeIn ();
	}
	else {
		$("#nav,#list,#info").hide ();
		$("#nav").children().hide ();
		$("#nav").show().coreFX({duration:1000, from:0, to:200, property:"width", ease:"bouncePast", unit:"px"});
		setTimeout (function (){
			$("#nav").children().fadeIn(1000);
			$("#list").html (_templ.login);
			$("#list").fadeIn ();
			
			$("#userinput").focus();
		}, 2000);
	}

	//### hashHandler
	this.hashHandler = function (evt) 
	{
   	$.sticky ("starting " + location.hash.substring (1));
	   self.shout.stopMonitoring ();
	   self.feed.stopMonitoring ();
	   self.air.stopMonitoring ();
	   self.hello.stopMonitoring ();

      $("#info").html ("");
		   
	   if (location.hash === "#shout") {
         document.title = "dailybox: shout";
		   self.shout.startMonitoring ();
	   }
	   else if (location.hash === "#feed") {
         document.title = "dailybox: feed";
	      self.feed.startMonitoring ();
	   }
	   else if (location.hash === "#thought") {
         document.title = "dailybox: thoughts";
	      self.air.startMonitoring ();
	   }
	   else if (location.hash === "#hello") {
		  document.title = "dailybox: hello";
		  self.hello.startMonitoring ();
	   }
	}
	
	//### valid
	this.valid = function ()
	{
		$("#nav").append (_templ.navigation);
		$("#list").html ("");
		$.sticky ("welcome to dailybox!");
		
		location.hash = "#hello";
		$(window).trigger();
   }
	
	//### login
    this.login = function(val)
    {
        $.sticky("try to open the door. hope you have the right key");
        $("#userinput").val ("");
        $.ajax({    url: "login.php", data: "login="+val,async:true,success: function(data){
        	eval(data);
        	}
        });
    }
}

//###############################
//##### class inputhandler ######
function InputHandler ()
{
//### variables
   var self = this;
    this._panic = false;
    this.posmap = new Array();
 	 this.idmap  = new Array();
  
//### collect all items	
	this.collect = function ()
	{
	  this.posmap.splice (0,this.posmap.length);
	  this.idmap.splice (0,this.idmap.length);
	  
	  $("#rsslist").children().each(function(index) {
	  
		if ($(this).hasClass ('item')) {
		  self.idmap.push($(this).attr("id"));
		  self.posmap.push(parseInt ($(this).offset().top));
		}
	  });
	}

//### scroll to top
	this.setScrollTop = function(val)
	{
		$('html,body').animate({scrollTop: val}, 500);
	}

//### get top scroll offset	
	this.getScrollTop = function () 
	{
	  return parseInt ($(document).scrollTop());
	}

//### is read ?	
	this.isRead = function(idx)
	{
		_daily.feed.markAsRead ("#"+this.idmap[idx]);
	}

//### show previous item	
	this.showPrevious = function()
	{
	  var cur = this.getScrollTop();
	  for (i = this.posmap.length-1; i >= 0; i--) {
		if (this.posmap[i] < cur) {
			this.isRead (i);
			
		  this.setScrollTop (this.posmap[i]);
		  
		  $.sticky.show ("previous");
		  break;
		}
	  }            
	}

//### show next item	
	this.showNext = function()
	{
	  var cur = this.getScrollTop();
	  for (i = 0; i < this.posmap.length; i++) {
		if (this.posmap[i] > cur) {
			this.isRead (i);
		  
		  this.setScrollTop(this.posmap[i]);
		  $.sticky ("next");
		  
		  //# if this is the last or the second last one we force a reload
/*        if (i >= this.posmap.length-1) {
   			_daily.feed.reloadItems ();

        }*/
		  break;
		}
	  }            
	}
	
//### effect
	this.blowout = function ()
	{
		var cur = this.getScrollTop();
	  for (i = 0; i < this.posmap.length; i++) {
		if (this.posmap[i] > cur) {
			var idx = ((i-1) <= 0) ? 0 : (i-1);
			_daily.feed.magicEffect (this.idmap[idx]);
			this.isRead (idx);
 		   $.sticky ("slurp!");
			break;
		}
	  }  
	}
	
//### handle key event
	this.handle = function (e)
	{
		if (! e) {
			var e = window.event;
		}
		var code = e.charCode ? e.charCode : e.keyCode;
		//# ctrl+'A'
		if (! e.shiftKey && e.ctrlKey && ! e.altKey && ! e.metaKey && code == 65) {
			e.preventDefault();
			if (this.panic==false) {
				$("#panic").height ("100%");
				$("object").each(function(index) {$(this).hide ();});
			}
			else{
				$("#panic").height ("1px");
				$("object").each(function(index) {$(this).show ();});
			}
			this.panic=!this.panic;
		}
		
		if (! e.shiftKey && ! e.ctrlKey && ! e.altKey && ! e.metaKey) {
		
			//# only if feed is active tab
			if (_daily.feed.isActive ()==false) {
				return;
			}
		
			switch (code) {
				case 74:  //# next "J"
   				this.handleNext ();
					break;
			   case 75:  // prev "K"
					this.handlePrev ();
					break;
			   case 82:// 'r' reload
					_daily.feed.reloadItems ();
   				break;
			   case 84: //# 't'
					this.setScrollTop(0);
					break;  
				case 69: //# 'e'
					this.collect ();
					this.blowout ();
			}				
		}
	}

//### handle next
   this.handleNext = function () 
   {
		this.collect ();
		this.showNext ();
   }

//### handle previous
   this.handlePrev = function () 
   {
		this.collect ();
		this.showPrevious ();
   }
	  
//### setup
	this.setup = function ()
	{
		$("#newshout").keyup(function(){
			var text = $("#newshout").val();
			var len  = 140 - text.length;
			$("#characters").html (len);
		});
		$("#characters").html ("140");
	}
}

//########################
//##### class feed ######
function Feed ()
{
//### variables
    var  self = this;
	this.active = false;

//### update
   this.update = function () {
      $.ajax ({url:"feed.php",data:"cronjob=1",async:true});
   }
   
//### start moniroting
   this.startMonitoring = function ()
   {
		this.active = true;
		$("#list").html (_templ.feedpanel);
		
		$("#nav").append ("<div id='mobile'><a href='javascript:_daily.input.handlePrev();'><img src='assets/image/prev.png' /></a><br/><a href='javascript:_daily.input.handleNext();'><img src='assets/image/next.png' /></a></div>");
		
		this.unreadItems(true);
   }
   
//### stop monitoring
   this.stopMonitoring = function ()
   {
      $("#mobile").remove ();
      this.active = false;
   }
   
//### return activity state
   this.isActive = function ()
   {
	return this.active;
   }
	
//### magic effect
	this.magicEffect = function (itemid)
	{
		$.sticky ("out of my mind!");

		$(itemid).animate ({marginLeft:"300px"},700);
		$(itemid).hide (500);
	}
	
//### add new feed
	this.add = function ()
	{
		var url = $("#feedurl").val();
		$.ajax ({url:"feed.php",data:"rss_add_newfeed="+url,async:true,success:function(data){self.usercancel();eval(data);}});
	}
	
//### userbegin 
	this.userbegin = function ()
	{
		$("#feedadder").fadeIn (300);
	}

//### usercancel
	this.usercancel = function ()
	{
		$("#feedadder").fadeOut (300);
	}

//### mark as read	
	this.markAsRead = function (itemid)
	{
		var id = itemid.substring(6);

		//# mark via ajax
		$.ajax ({url:"feed.php",
		data:"rss_read="+id,
		context:document.body,
		async:true});
  
		//# change class
		setTimeout(function () {$(itemid).addClass("read");},1000);
  
		//# remove the eventhandler
		$(itemid).unbind ("mouseenter");	
	}
	
//### reload items	
	this.reloadItems = function ()
	{
		//# remove reloaditems element
		$("#reloaditems").remove();
		self.unreadItems (false);
	}
	
//### delete a feed
	this.deleteFeed = function (oid)
	{
		$.sticky ("delete feed");
		$.ajax ({   url: "feed.php", 
					data: "rss_deleteFeed="+oid,
					async:true,
					success: function(){}});

		//# just remove feed-<id>
		$("#feed-"+oid).fadeOut (500, function(){$("#feed-"+oid).remove();});
	}
	
//### get all unread
	this.unreadItems =function (resetContent)
	{
		$.sticky ("check for new feeds");
	
		if (resetContent) {
			$("#rsslist").html("");
		}
	
		self.updateCounter();
	
		$.ajax({    url: "feed.php", 
            data: "rss_get_all_unread",
			async:true,
            success: function(data)
			{
				if (data.length==0) {
					$("#rsslist").html("No more items...");
				}
				else {
				  var  o =$('[href^="http://feeds.feedburner.com/"]');
				  if (o.length !== 0) {
				     o.remove ();
				  }
				
					$("#rsslist").append(data);
				}
			}});
	}
	
//### update counter
	this.updateCounter = function ()
	{
		$.ajax ({url:"feed.php",data:"rss_total",async:true,success:function(data){
		    if (parseInt (data,10) === 0) {
		       document.title = "dailybox";
		    }
		    else {
		       document.title = "dailybox: "+data+" unread items";
		       }
   		 }
      });
	}
}

//###############################
//##### class hotair ######
function HotAir ()
{
//### variables
   var self = this;
   
//### start moniroting
   this.startMonitoring = function ()
   {
      //# get information from file via async request
  		$("#list").html (_templ.hotairpanel);

   	$.sticky ("loading your thoughts");

		$.ajax ({url:"hotair.php",async:true,data:"stream",success:function(data){
			//# put content in frame
			$("#airlist").html (data);
		}});

   }

//### stop monitoring
   this.stopMonitoring = function () {/*nothing to do*/}

//### tweet this
   this.tweet = function (date) 
   {
      $.ajax({    url: "hotair.php", 
                    type:"POST",
                    data: "tweet="+date,
                    async:true,
                    success: function(data){
                        $.sticky ("thought is now public on twitter");
                        if (data.length > 0) {
                           alert (data);
                        }
                     }
                    }); 
   }
   
//### remove user input 
    this.cancel = function ()
    {
		$("#hotadder").slideUp();
    }
   
//### add
    this.add = function ()
    {
        $.sticky ("sending thought");
        var val = $("#newair").val();
        $.ajax({    url: "hotair.php", 
                    type:"POST",
                    data: "hotair="+val,
                    async:true,
                    success: function(data){
                        $("#airlist").html (data);
                     }
                    }); 
                    
        $("#newair").val("");
        this.cancel ();
        
        this.startMonitoring (); //# simple reload
    }
}

//########################
//##### class shout ######
function Shout ()
{
//### variables
    var  self = this;
    this.handle = false;
    this.response = 0;

//### toggle monitoring 
	this.toggleMonitoring = function ()
	{
		var t = "";
		if (this.handle === false) {
			self.stream(true);
			$("#shoutMonitor").text ("yes");
			t = "on";
		}
		else {
			self.stopMonitoring ();
			$("#shoutMonitor").text ("no");
			t = "off";
		}
		$.sticky ("auto reload of shouts turned " + t);
	}
	
//### start monitoring
   this.startMonitoring = function ()
   {
        setTimeout (function (){
			
         self.reset (); 
         self.stream(true); 
			self.follower ();
			
			$("#list").html (_templ.shoutpanel);
			
			_daily.input.setup ();
			
        },100);
   }
   
//### stop monitoring
   this.stopMonitoring = function ()
   {
		if (this.handle !== false) {
            clearInterval (this.handle);
			this.handle = false;
		}
   }
   
//### resolve link
	this.resolve = function (url, el)
	{
		$.ajax ({url:"shout.php",async:true,data:"resolveLink="+url,success:function(data){
			$("#"+el).html (data);
			$("#"+el).removeClass("resolving");
		}});
	}
    
//### stream
    this.stream = function (force)
    {
        var counter = 0;
		
        if (this.handle !== false) {
            clearInterval (this.handle);
            counter = 90;   //# force direct update
        }
        
        if (typeof force != "undefined") {
            counter = 90;
        }
        
        this.handle = setInterval(function ()
            {
                if (counter++ >= 90) {
                    counter=0;
					
					if (_localDebug==true) {
						$("#shoutlist").html ("<div id=\"tweet-row\">"+
												"<div id=\"tweet-content\">"+
												"<h2>iPadBlog<div id=\"tweet-nav\"><a href=\"#\" onclick=\"_daily.shout.responseTo(118987073263910913,'iPadBlog');return false;\">reply</a> </div></h2>"+
												"Noch einen Tag! Letztes Sommergewinnspiel im September. Schicken Euch per App nach St. Tropez. <a href=\"http://t.co/VzHDKJbc\">http://t.co/VzHDKJbc</a>"+
												"<small>11:55:03</small>"+
												"</div>"+
												"</div><div id=\"tweet-row\">"+
												"<div id=\"tweet-content\">"+
												"<h2>MyHeritage<div id=\"tweet-nav\"><a href=\"#\" onclick=\"_daily.shout.responseTo(118985814452600833,'MyHeritage');return false;\">reply</a> </div></h2>"+
												"Amazing work! How a man's <span class=\"hashtag\">#familyhistory</span> <span class=\"hashtag\">#research</span> is giving insights into life on the frontline to others <a href=\"http://t.co/5cDH0ZC5\">http://t.co/5cDH0ZC5</a>"+
												"<small>11:50:03</small>"+
												"</div>"+
												"</div>");
					}
					else {
						$.ajax ({url:"shout.php",async:true,data:"stream",success:function(data){
							
							if (data.length>0) {
								$.sticky ("new shouts available!");
							}
							
							//# put content in frame
							var value = $("#shoutlist").html(); 
							$("#shoutlist").html (data + value);
							
							counter = 0; //# restore counter
						}});
					}
                }
            },1000);
        
    }
    
//### show input shout
    this.create = function()
    {
        $('#shouter').fadeIn(200);
        $('#newshout').focus();
    }
    
//### remove user input 
    this.cancel = function ()
    {
		$("#shouter").slideUp();
        this.responseTo(0,'');
    }

//### friendship creation
    this.makeFriend = function (user)
    {
        $.ajax ({url:"shout.php",async:true,data:"follow="+user,success:function(data){
                                                
			//# put content in frame
			var value = $("#shoutlist").html(); 
			$("#shoutlist").html (data + value);

		}});

    }

//### reset 
    this.reset = function ()
    {
        $.ajax({    url: "shout.php", 
                        data: "reset",
                        async:false
                        });

        $("#shoutlist").html("");
    }
    
//### send a response   
    this.responseTo = function (id, user)
    {
        this.response = id;
        
		if (id === 0) {
			$("#newshout").val("");
		}
		else {
			$("#newshout").val ("@"+user+" ");
			$("#newshout").focus();
			$("#shouter").show();
		}
    }
	
//### get followers
	this.follower = function ()
	{
		/*$.ajax({    url: "shout.php", 
                    type:"POST",
                    data: "followerList=1",
                    async:true,
                    success: function(data){
                        $("#info").html (data);
                       $("#info").show();
                    }
                    }); 
					*/
	}
    
//### sending new shout
    this.send = function ()
    {
        var reply = "";
        
        if (this.reponse!=0) {
            reply = "&reply="+this.response;
            this.response = 0;
        }
        $.sticky ("sending new shout");
        var val = $("#newshout").val();
        $.ajax({    url: "shout.php", 
                    type:"POST",
                    data: "shout="+val+reply,
                    async:true,
                    success: function(data){
                        self.stream ();
                    }
                    }); 
                    
        $("#newshout").val("");
        $("#characters").html("140");
        $("#shouter").hide ();
        
        //# reload
        self.stream(true);
    }
}
    

//###########################
//##### DOCUMENT LOADED #####
var     _daily;

$(document).ready(function() {
	
	_daily = new DailyBox ();
	
});

document.onkeydown = function(e) { 
  _daily.input.handle (e);
};


function imageResize(el)
{
    var im = document.getElementById(el);
  
    //# get father until nodename is DIV
    var father = im.parentNode;
    while (father != null && father.nodeName != "DIV") {
      father = father.parentNode;
    }
    
    if (father==null) {
      return;
    }
    var w=im.clientWidth;
    var h=im.clientHeight;
        
    var fw = father.clientWidth - 50;  /* an assumption for padding */

    if (fw == 0) {
        //# do nothing
        return;
    }
        
    if (w > fw) {
        //# resize
        if (w > h) {
            fct = (h/w) * fw;
        }
        else {
            fct = (w/h) * fw;
        }
         im.style.width = fw+"px";
         im.style.height= fct+"px";
    }
}

