/*** SETUP ***/
var data="";
var monthstr = ['January', 'February', 'March', 'April','May','June', 'July', 'August', 'September', 'October', 'November', 'December'];

var now;
var privacy;
var yesterday;
var pageDate;

window.addEvent('domready', function() {
	now = new Date();
	pageDate=now;
	setPageDate(now.getDate(), now.getMonth(), now.getFullYear());
	
	if(page_username){
	}else{
	var page_username="everyone";
	}
	
	getPrivacy();
	
	getBlurb();
	refreshData();
	//eventLoad();
	//onResize();
	
	//setTitleSize();

	if(location.pathname=="/input.php"){
		editables();
	}
	
	if($('checkbox')!=null) setPrivacy();
});


function setTitleSize(){
	//var titleSize=$('logo_text').getStyle('height').toInt();
	//var fontSize=$('logo_text').getStyle('font-size').toInt();

	/*
while (titleSize>50){
	titleSize=$('logo_text').getStyle('height').toInt();

//alert(fontSize);	
	fontSize--;
	$('logo_text').setStyle('font-size',fontSize);

	}
*/
	//$('logo_text').setStyle('font-size','18px');
	//$('logo_text').setStyle('letter-spacing','1px');
	//$('logo_text').setStyle('letter-spacing','1px');
	
}

function getPrivacy(){

			var request = new Request({
				url: "./php/getPrivacy.php",
				link: 'chain',
				method:'get',
				onSuccess: function(html) {
				if($('checkbox')!=null) setPrivacy();
				}
			});
			
			request.send();
		
}

function setPrivacy(){
	//alert(privacy);
	if(privacy==0){
	
	}
	else{
		$('checkbox').checked = true;
	}
	
	FancyForm.start( 0, {
	onSelect: function(chk){
	var el = chk.inputElement;
	if(el==$('checkbox')){
		privacy=1;
		var request = new Request({
				url: "./php/updatePrivacy.php?privacy="+privacy,
				link: 'chain',
				method:'get',
				onRequest: function() {

				},
				onSuccess: function(html) {

				}
			});
			
			request.send();
			}
		},
	onDeselect: function(chk){
		var el = chk.inputElement;

		if(el==$('checkbox')){

				privacy=0;
				var request = new Request({
				url: "./php/updatePrivacy.php?privacy="+privacy,
				link: 'chain',
				method:'get',
				onRequest: function() {

				},
				onSuccess: function(html) {

				}
			});
			
			request.send();
			}
		}	
	});


}




function editables(){
    new Editor({
                container: $('container'),
                editableElement: $('excerpt')
                });
}
          

function getBlurb(){

			var request = new Request({
				url: "./php/getBlurb.php?page_username="+page_username,
				link: 'chain',
				method:'get',
				onRequest: function() {

				},
				onSuccess: function(html) {
					var blurbData = eval('(' + html + ')');	
					var blurb=blurbData[0].blurb;
					$('blurb').set('html',blurb);
				}
			});
			
			request.send();
}

function refreshData(){	
		var alerter=softalert("loading noodles");;
		var request = new Request({
			url: "./php/getAllData.php?page_username="+page_username,
			link: 'chain',
			method:'get',
			onRequest: function() {

			},
			onSuccess: function(html) {
				softalertKill(alerter);
				setDateStyles(html);
			}
		});
		
		request.send();

}

function setDateStyles(response){
  	data = eval('(' + response + ')');	
	loadDate();	
}

var onResize = function(){

//$('year_container').setStyle('width',window.width);

var leftInc = ((window.innerWidth-20)/12).toInt();
var months = $$('.month_floater');
var inc = 5;
var max = 90 * 12;
var spacing12 = (window.innerWidth-91.0*12.0).toInt()/12.0;
var spacing6 = (window.innerWidth-91.0*7.0).toInt()/6.0;

var monthwidth=window.innerWidth/13.0;
/* $('year_container').setStyle('width', window.innerWidth); */

months.each(function(item){
	if (window.innerWidth <= max)
	{
		//$('year_container').setStyle('height', '165px');

	}else{
		//$('year_container').setStyle('height', '85px');
	}
	
	
	if (window.innerWidth <= max)
	{
		//months.setStyle('margin-right',spacing6);
		//months.setStyle('margin-left',spacing6);

	}else
	{
		//months.setStyle('margin-right',spacing12);

	}
		item.setStyle('width',monthwidth);

		//inc+=leftInc;
});
}

var map = function (value, istart, istop, ostart, ostop) {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}

/*** EVENTS ***/

var eventLoad = function()
{
	window.addEvent('resize',onResize);
}

var setPageDate = function(_dayInt, _monthInt, _yearInt)
{
	$('page_date').set('text', 'today is '+monthstr[_monthInt]+' '+_dayInt+' '+_yearInt );
}


function keypressed(text){
	var count=text.length;
	$('textcounter').set('text',140-count);
	
	if(count>140)
	{
	$('textcounter').set('style','text-decoration:blink');
		$('textcounter').set('style','color:rgb(255,0,0)');

	
}
	else
{	
		$('textcounter').set('style','color:#333333');

		//$('textcounter').set('style','text-decoration:none');
}
}



function submitInputs(value){
	var softAl;
	//alert(value.length);
	if(value.length>0){
	
	
		var mysqlDate=new Date();
		
			if($('checkbox_yest').checked == true){
				mysqlDate.setDate (mysqlDate.getDate() -1);

			}

		mysqlDate=formatDate(mysqlDate);
			
				var request = new Request({
					url: "./php/enterData.php?note="+escape(value)+"&datetime="+mysqlDate+"&privacy="+privacy,
					link: 'chain',
					method:'get',
					onRequest: function() {
						softAl=softalert("noted");
					},
					onSuccess: function(html) {
					
					if(html=="session-expired"){
					    window.location="./php/login.php?msg=<warn>Session expired. Please login again.</warn>";
					 }
						$('textcounter').set('text',140);
						$('input_note').set('value','');
						refreshData();
						softalertKill(softAl);
					
					}
				});
				
				request.send();
				
				if(privacy==0){
				var request2 = new Request({
					url: "./twitter/tweet.php?note="+escape(value),
					link: 'chain',
					method:'get'
				});
				request2.send();
				}
	}else{
 		$('input_note').set('value','');
	}				
	
}

function formatDate(date1) {
  return date1.getFullYear() + '-' +
    (date1.getMonth() < 9 ? '0' : '') + (date1.getMonth()+1) + '-' +
    (date1.getDate() < 10 ? '0' : '') + date1.getDate()+' '+
    (date1.getHours() < 10 ? '0' : '') + date1.getHours()+':'+
        (date1.getMinutes() < 10 ? '0' : '') + date1.getMinutes()+':'+
        (date1.getSeconds() < 10 ? '0' : '') + date1.getSeconds();
}



function insertData(m,d){
	
	if (data.length==0)
	{
		var pageEntry  = new Element('div');
		pageEntry.set('class', 'entry_item');
		pageEntry.inject($('entry_container'),'bottom');	
		
		var note='';
		//var delText=false;
	}


	
	for (var i=0; i<data.length;i++)
	{
	
		
		
		var datetime=data[i].TIME;
		datetime=datetime.split(' ');
		var date=datetime[0];
		var year=date.split('-')[0];
		var time=datetime[1];
		
		time=time.split(':');
		time=time[0]+":"+time[1];

		note=data[i].note;
		
		var ymd=datetime[0].split('-');
		var mm=ymd[1];
		var dd=ymd[2];
		
		var dataId=data[i].ID;		
		var userId=data[i].user_id;

		
		if(m==mm && d==dd){
		
			var pageEntry  = new Element('div');
			pageEntry.set('class', 'entry_item');
			pageEntry.set('id', dataId);
			pageEntry.inject($('entry_container'),'top');
		
		
			//meta container
			var meta  = new Element('div');
			meta.set('class', 'meta');
			meta.inject(pageEntry,'top');	
			
			//time
			var t  = new Element('div');
			t.set('class', 'entry_time');
			t.inject(meta,'top');	
			t.set('text',time);
			
			//year
			var y  = new Element('div');
			y.set('class', 'entry_year');
			y.inject(meta,'top');	
			y.set('text',year);
			
			//usernames on everyone page
			

			
			//the note
			var n  = new Element('div');
			n.set('class', 'entry_note');
			n.inject(pageEntry,'top');	
			note=linkify(note);
			if(data[i].privacy==1)n.set('html',note+"<small>*</small>");
			else n.set('html',note);
			
			
			if(page_username=="everyone"){
				var user  = new Element('a');
				user.set('class', 'entry_user');
				user.inject(n,'top');	
				user.set('href',"/beta/"+data[i].username);
				user.set('text', data[i].username );

			}
			
			
			
					
					
			if(page_username==username)	$('input_note').focus();

			//delete button on today and yesterday
			if(mm==now.getMonth()+1 && dd==now.getDate() && page_username==username ||
			mm==now.getMonth()+1 && dd==now.getDate()-1 && page_username==username
			){

			var x  = new Element('img');
			x.set('class', 'entry_ex');
			x.set('id', 'entry_ex_'+dataId);
			x.inject(meta,'top');	
			x.set('src','http://onnoodles.com/beta/images/ex_solid.png');
			
			
				x.addEvents({
				'mouseover':function(){
			        this.getParent().setStyle('text-decoration','line-through');
			        //this.getParent().getElement('.entry_note').setStyle('color','rgb(255,0,0)');
			        //this.getParent().setStyle('background','rgb(255,0,0)');
				},
				
				'mouseleave':function(){
			        this.getParent().setStyle('text-decoration','none');	
			        //this.getParent().getElement('.entry_note').setStyle('color','#000');
			        //this.getParent().setStyle('background','none');
				},
				'click':function(){
						var note_id=this.getParent().getParent().id;				
						var alert;
						var request = new Request({
							url: "./php/delete_note.php?note_id="+note_id,
							link: 'chain',
							method:'get',
							onRequest: function() {
								alert=softalert("deleting note");
							},
							onSuccess: function(html) {
										$('input_note').set('value',"");
										refreshData();
								softalertKill(alert);
							}
						});
						request.send();	
					}
				
				});
			}
			
			
			
			
			
			
		}
	
	}
}
  	

  	
function loadDate(monthdateyear){
	
	var m;
	var d;
	var mdy;
	
	//reset daybox styling
	var daybox=$$('.day-box');		
	daybox.each(function(item,index){
		//set border style so box size doesn't shift when it highlights later
		//item.setStyle('border','1px solid white');
		//popup is done in css, hover span
		item.setStyle('background','none');

	});
	
	
	if(!data)return;
	
	for (var i=0; i<data.length;i++)
	{
		var datetime=data[i].TIME;
		datetime=datetime.split(' ');
		var date=new Date(datetime[0]);
		
		var ymd=datetime[0].split('-');
		var m=ymd[1];
		var d=ymd[2]*1;
		
		//highlight all months with data
		var day=monthstr[m-1]+"-"+d+"-1000";
		$(day).setStyle('color','#000');
		

	}
	
	
	if(monthdateyear==null){
		mdy= new Date();
	}
	else{
		mdy= new Date(Date.parse(monthdateyear));
		pageDate=mdy;	

	}
	
	m=mdy.getMonth()+1;
	d=mdy.getDate();
	
	$('entry_container').set('html','');			
	
	//highlight current month
	var todayid=monthstr[m-1]+"-"+d+"-1000"; 
	//$(todayid).getParent().setStyle('border','1px solid black');
	$(todayid).getParent().setStyle('background','yellow');

	//line-through visited dates
	$(todayid).setStyle('text-decoration','line-through');

	//set ON JANUARY 1 text
	$('entries_date').set('text', 'on '+monthstr[m-1]+' '+d);


	//previous next

	//var prevMDY = new date( mdy-1 ); 
	//var nextMDY=new date( date.getTime() + 86400000 ); 
	/*
	var pm=prevMDY.getMonth()+1;
	var pd=prevMDY.getDate();
	var nm=prevMDY.getMonth()+1;
	var nd=prevMDY.getDate();
*/
	
  			//$('previous-day').addEvent('click', function(){loadDate(monthstr[m-1]+"-"+(d-1)+"-1000");} );
  			//$('next-day').addEvent('click', function(){loadDate(monthstr[m-1]+"-"+(d+1)+"-1000");} );


	insertData(m,d);
  	

  	
  }	
  
  
  function loadPrevDate(){
	pageDate=new Date(pageDate.getTime() - 86400000); 
	var m=pageDate.getMonth();
	var d=pageDate.getDate();
	loadDate(monthstr[m]+"-"+(d)+"-1000");
  }
  
    function loadNextDate(){
  
		pageDate=new Date(pageDate.getTime() + 86400000); 
		var m=pageDate.getMonth();
		var d=pageDate.getDate(); 
		loadDate(monthstr[m]+"-"+(d)+"-1000");
		
	}
  
  
  
function monthIn(id,z){
	$(id).setStyle('z-index',z);
}

function monthOut(id,z){
	$(id).setStyle('z-index',z);
}



function isValidURL(url){
    var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

    if(RegExp.test(url)){
        return true;
    }else{
        return false;
    }
}








