/*-------------------------------------------------------------------------------------------------
setCookie
-------------------------------------------------------------------------------------------------*/
function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}




/*-------------------------------------------------------------------------------------------------
login
-------------------------------------------------------------------------------------------------*/
function login(user,redirectTo) {
	document.cookie  = 'user=' + user + '; path=/';
	window.location = redirectTo; 
}




/*-------------------------------------------------------------------------------------------------
checkEmail
-------------------------------------------------------------------------------------------------*/
function checkEmail(email) {

	var filter=/^.+@.+\..{2,4}$/
	
	// Fail
	if (!filter.test(email)) {
		return false;
	}
	else {
		return true;
	}
}




/* --------------------------------------------------
ajaxMagic
---------------------------------------------------
processUrl = the name of the php page which is doing processing
params     = an array of query strings to to be sent to the php page
	ex. params array may look like this:
	params[0] = "action=add";
	params[1] = "note=butterscotch";
	params[2] = "tags=dogs,cats,birds";
resultsTargetId = where the results should be put...div
*/
function ajaxMagic(processUrl,params,resultsTargetId,loaderDiv,doFade, postFunction){	

	// display loading graphic
	try {
		document.getElementById(loaderDiv).style.display  = "block";
		document.getElementById(loaderDiv).innerHTML = "<img src='/images/loader.gif' align='top'> " + loaderDiv;
	}
	catch(err) {
		document.getElementById(resultsTargetId).innerHTML = "<img src='/images/loader.gif' align='top'><span class='logoGreen'> Loading...</span>";
	}
	
	// START AJAX MAGIC
	// try to initiate xmlhttprequest
	var xmlHttp;
	try {
	  xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
	}
	catch (e){
	  // Internet Explorer
		try { 
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
	 	catch (e){
			try{ 
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){
		  		alert("Your browser does not support AJAX!");
		  		return false;
			}
		}
	 }
	  
	  

	
	
	// SEND INTO AJAX
	// grab info we're going to send to be processed
	var queryStrings = "";
	
	for(var i = 0; i < params.length; i++) {
		queryStrings += params[i] + "&";
	}	
	// remove the & off the end
	var queryString = queryStrings.substring(0,queryStrings.length-1);
	
	processUrl = processUrl + "?" + queryStrings;
	
	
	xmlHttp.open("POST",processUrl,true);
	xmlHttp.send(null);
	
	
	
	
	// GET OUT FROM AJAX
	 xmlHttp.onreadystatechange = function(){
		if(xmlHttp.readyState==4)
		  {
		  // this is what we get bak from the process
		  response = xmlHttp.responseText; 
	  	  
	  	  // throw graph into div
	  	  document.getElementById(resultsTargetId).innerHTML = response;
	  	  
	  	  // turn off loading graphic
	  	  try{
	  	  document.getElementById(loaderDiv).innerHTML = "";
	  	  document.getElementById(loaderDiv).style.display  = "none";
	  	  } catch(err) {}
	  	  
	  	  if(doFade == "doFade") {
	  	  	fade(resultsTargetId);
	  	  }
	  	  
	  	  
	  	  
	  	  // If this is Twitter, then do the twitter scroll
	  	  // Special case, should find a way to call this dynamically through a paramter, not by running a test here
	  	  isThisTwitter = processUrl.search("ajaxTwitter.php"); // it's twitter if the ajax page is called this
		  if (isThisTwitter != -1) { 
			twitterScroll(resultsTargetId); // if it is twitter, start the twitterScroll function
		  } 
		  
		  
		  // Do a post function if one was passed
		  if(postFunction) {
		  	postFunction();
		  }
	  	 
	  	  // Finally return the stuff that was echoed in the ajax page
	  	  return response;
	  	  
	  	  
		  }
	 }
	
	
	
	    
} // end ajaxMagic();

 
// JAVASCRIPT VERSION OF MY PHP stringBetweenTwoStrings function
function stringBetweenTwoStrings(string1,string2,haystack,cursor) {
	var pos1start = haystack.indexOf(string1,cursor);
	if(pos1start != -1) {
		str1length = string1.length; 								//  Find the length of string one so we can move to the end
		pos1end    = pos1start + str1length; 						//  Find the end position of the first string
		pos2start  = haystack.indexOf(string2,pos1end); 			// Find the start position of the second string
		howFarToGo = pos2start - pos1end; 							// How many characters between the end of string1 and the beginning of string2	
		return haystack.substring(pos1end,howFarToGo + pos1end);
	}
	else {
		return "An error has occured.";
	}	
}



/* --------------------------------------------------
TWITTER SCROLL MESS
---------------------------------------------------*/
var twitterHaystack = "";

// This function gets things ready and rolling
function twitterScroll(resultsTargetId) {

	twitterHaystack = document.getElementById(resultsTargetId).innerHTML; // Grab all the data that was spit into the resultsTargetId. It'll contain first the tweet count, then all the tweets
	
	// Begin parsin out the tweet count which is in between these two strings
	string1 = '[tweetCount]';
	string2 = '[endTweetCount]';
	
	
	// The first occurance of our search strings is actually here in this function which also prints out in the results div. 
	// Need to ignore this by making a cursor which starts after this 
	pos2start  = twitterHaystack.indexOf(string2); 	
	pos2length = string2.length; 	
	cursor     = pos2start + pos2length;
	
	// Finally, parse out the tweet count
	if(browser != "IE") { // IE Isn't including the functions, so we don't need to parse them out.
		twitterHaystack = stringBetweenTwoStrings(string1,'[DONE]',twitterHaystack,cursor); // get rid of all the functions at start	
	}
	twitterHaystack = "tweetCount" + twitterHaystack; // using brackets here messed something up? had to switch to no brackets
	
	
	// Again, the parsin of IE is different....have to search for this.
	// Remember that we're actually parsing this function right here too, so for instance if I added stringOne equals bracket end bracket, etc again, it screws things up
	if (browser != "IE") {
		string1         = "tweetCount"; 
	}
	

	tweetCount      = stringBetweenTwoStrings(string1,string2,twitterHaystack,0); // no longer need the cursor here since we just got rid of the functions
	
	// Got the junk now parse out the stuff at the front
	twitterHaystack = twitterHaystack.replace("tweetCount","");
	twitterHaystack = twitterHaystack.replace('[endTweetCount]',"");
	twitterHaystack = twitterHaystack.replace(tweetCount,"");
	document.getElementById(resultsTargetId).innerHTML = twitterHaystack; // put just the clean data back in
	document.getElementById(resultsTargetId).style.top = "0px";
	
	
	
	var error = ""
		
	// If twitter overloaded it also prints the word 
	if (tweetCount.search("overload") != -1) { 
		error = "overload";
	} 
	
	// If overload was injected into the count, we need to get rid of that
	
	tweetCount = parseInt(tweetCount);
	
	if(tweetCount == 0) {
		error = "notweets";
	}

	
	// No error, ok to go on
	if(error == "" && tweetCount > 3) { 
	// Now initiate our scroll (don't merge scroll function into here, because we don't want to continuously loop the above
		var heightOfTweets = tweetCount * 64;
		killMove = false;
		
		// Create the second div by loading it with the twitter data
		document.getElementById("thisTwitter2").innerHTML = twitterHaystack;

		// Get the first div rolling
		move(resultsTargetId,0,'pause',heightOfTweets,1500); // don't move at all the first time
		
		// Position the second div
		document.getElementById("thisTwitter2").style.top = heightOfTweets;
		
		// Then get the second div rolling
		move2("thisTwitter2",0,'pause',heightOfTweets,1500); // don't move at all the first time
	}
}

var killMove = false;

// This function controls div 1
function move(whichDiv,howMuch,pauseOrMove,heightOfTweets,speed) {
	
	if(killMove != true){
		posOfFirstDiv  = parseInt(document.getElementById(whichDiv).style.top);
		var stopThisLoop = false;
		
		// If this div is all the way off the "top of the screen"...ie, its top left corner is negative the height of the div, time to shift it down
		if(posOfFirstDiv == -heightOfTweets) {
			stopThisLoop = true;
		}
		
		// Fancy mootools stuff to do the scroll
		var growDiv = new Fx.Style($(whichDiv),
		'top', {duration: speed})
		.addEvent('onComplete', function() {
			
			// Pause (then move next time)
			if(pauseOrMove == "pause" && stopThisLoop != true) {
				move(whichDiv,howMuch,'move',heightOfTweets,1500); // recursive next time
			}
			// Move (then pause next time)
			else if(stopThisLoop != true){
				move(whichDiv,howMuch - 64,'pause',heightOfTweets,1500); // recursive next time
			}
			// stopThisLoop did equal true, means its time to flip
			else {
				document.getElementById(whichDiv).style.top =  heightOfTweets + "px"; // Put div1 at the "bottom of the screen"
				howMuch = 0; // ?
				move(whichDiv,heightOfTweets,'move',heightOfTweets,0); // Put div1 
				stopThisLoop = false
			}
			});	
		growDiv.start(howMuch);	
	}
	// Killed move (clicked a diff mood)...Reset twitter divs
	else { 
		document.getElementById(whichDiv).innerHTML = "";
		document.getElementById(whichDiv).style.top = "0px";
	
	}
}

// This function controls div2
function move2(whichDiv,howMuch,pauseOrMove, heightOfTweets,speed) {
	if(killMove != true){
	
	
		posOfSecondDiv = parseInt(document.getElementById(whichDiv).style.top);
		var stopThisLoop = false;
			
		if(posOfSecondDiv == -(heightOfTweets*2)) {
			stopThisLoop = true;
		}
	
		var growDiv = new Fx.Style($(whichDiv),
		'top', {duration: speed})
		.addEvent('onComplete', function() {
			if(pauseOrMove == "pause"  && stopThisLoop != true) {
				move2(whichDiv,howMuch,'move',heightOfTweets,1500); // pause then move next time
				
			}
			else if(stopThisLoop != true){
				move2(whichDiv,howMuch - 64,'pause',heightOfTweets,1500); // move then pause next time
			}
			else {
				document.getElementById(whichDiv).style.top =  heightOfTweets + "px";
				howMuch = 0;
				move2(whichDiv,0,'move',heightOfTweets,0); // move then pause next time..says move, but it'll actually be a pause
				stopThisLoop = false
			}
			});
			
		growDiv.start(howMuch);
	}
	// Killed move (clicked a diff mood)...Reset twitter divs
	else { 
		document.getElementById("thisTwitter2").innerHTML = "";
		document.getElementById("thisTwitter2").style.top = "192px";
	}
}



	
		





// The following functions have to be external. When called from ajaxGraph.php they don't work ?!
var selectedDot = "";


// clickDot - used in ajaxGraph.php
function clickDot(source,timestamp,level,note,id,thisDate,happyTags,sadTags,format,searchByDate,nsid,twitterUsername){

	killMove = true;
	
	document.getElementById("snapshot").style.display = "inline";
	
	
	

	try{														   // If we already had an arrow -- ie, selectedDot isn't blank
		document.getElementById(selectedDot + "arrow").style.display = "none";     //  Then clear that arrow 
		document.getElementById(selectedDot + "increment").style.color = "#acd47a"; // Turn it green again
	}
	catch(err) {
	
	}
	
	document.getElementById(id + "arrow").style.display = "inline";  			   // Then make this mood arrow
	
	document.getElementById(id + "increment").style.color = "#000000";
	
	
	
	selectedDot = id;															   // Then asign this id to the selectedDot variable!
	
	
	
	// Tags
		if(happyTags == ""){			
			happyTags = "<span class='noResults'>No happy tags :(</span>";
		}
		
		if(sadTags == ""){			
			sadTags = "<span class='noResults'>No sad tags :)</span>";
		}
		
			
			document.getElementById("thisHappyTags").innerHTML  = happyTags; 				// Inject the tags into the tag div where mood data is displayed (index.php)
			document.getElementById("thisHappyTags").className = theLevels[level];	// Change color of text, by calling appropriate class style from the stylesheet.
		
			
			document.getElementById("thisSadTags").innerHTML = sadTags; 				// Inject the tags into the tag div where mood data is displayed (index.php)
			document.getElementById("thisSadTags").className = theLevels[level];	// Change color of text, by calling appropriate class style from the stylesheet.
		
																			// This uses the array of levels found in common.php. Numeric => String. ex. theLevels[-4] = "neg4";
		
	// Note
		if(format == "dmy") {
			document.getElementById("noteContainer").style.display = "inline";
			if(note == ""){
				note = "No note";
			}
			
			note = note.replace("'","&#39;");
			document.getElementById("thisNote").innerHTML = note;				// Inject the note into the note div where mood data is displayed (index.php)
			document.getElementById("thisNote").className = theLevels[level];	// Change color of text, by calling appropriate class style from the stylesheet.
		}																	// This uses the array of levels found in common.php. Numeric => String. ex. theLevels[-4] = "neg4"
		else {
			document.getElementById("noteContainer").style.display = "none";
		}
		
		
		
	// Level
	var positive = "";
	if(level > 0) {
		positive = "+";
	}
	
	if(format == "my" || format == "y") {
		document.getElementById("thisLevel").innerHTML = "You averaged a level <span style='font-weight:800'>" + positive + level + "</span>";				
	}
	else {
		document.getElementById("thisLevel").innerHTML = "You checked in at a level <span style='font-weight:800'>" + positive + level + "</span>";	
	}
		
	// source
	if(source != "") {
		document.getElementById("thisSource").innerHTML = source;
	}
	
		
	// Date	
	document.getElementById("thisDate").innerHTML = thisDate;													     // Inject the date into the date div where mood data is displayed (index.php)
		
	

	// Flickr photos
		
		if(nsid != "") { // nsid is now passed in as a variable
			document.getElementById('thisFlickr').innerHTML = "";
			var params = new Array();
			params[0] = "timestamp=" + timestamp;								 // Need to send the flickr ajax page the timestamp so it knows which photos to grab
			ajaxMagic(mainUrl+'/archive/ajaxFlickr.php',params,'thisFlickr','Asking Flickr for your photos...'); // Flickr is processed at ajaxFlickr.php, and the results are loaded in the div id='thisFlickr' on index.php
		}
		
			
	// Twitter
		
		if(twitterUsername != "") { // twitter username is now passed in as a variable
			var params = new Array();
			params[0] = "timestamp=" + timestamp;								   // Need to send the twitter ajax page the timestamp so it knows which photos to grab
			params[1] = "format=" + format;		
			ajaxMagic(mainUrl+'/archive/ajaxTwitter.php',params,'thisTwitter','Fetching Tweets...','noFade'); // Twitter is processed at ajaxTwitter.php, and the results are loaded in the div id='thisTwitter' on index.php
		}
		
		
	// Retrospective Garden			
		document.getElementById('retrospectiveGarden').innerHTML = ""; // Clear previous results
		var params = new Array();
		params[0] = "date=" + searchByDate;								   // Need to send the twitter ajax page the timestamp so it knows which photos to grab
		params[1] = "format=" + format;						 		   
		ajaxMagic(mainUrl+'/archive/ajaxRetrospective.php',params,'retrospectiveGarden','Looking back...'); // Twitter is processed at ajaxTwitter.php, and the results are loaded in the div id='thisTwitter' on index.php
	
}


// clearDetails() - used in the chooseDate function on index.php .. so that whenever the graph changes, it clears the details
function clearDetails() {
	document.getElementById("snapshot").style.display = "none";  // Clear the tag
	document.getElementById("thisHappyTags").innerHTML = "";  // Clear the tag		
	document.getElementById("thisSadTags").innerHTML   = "";  // Clear the tag		
	document.getElementById("thisNote").innerHTML      = "";	// Clear the note	
	document.getElementById("thisDate").innerHTML      = "";	// Clear the date							  
	document.getElementById("thisFlickr").innerHTML    = "";	// Clear the flickr
	document.getElementById("thisTwitter").innerHTML   = "";	// Clear the twitter
	document.getElementById("thisSource").innerHTML    = "";  // Clear the source	
	selectedDot = "";
}









// Change the dates of the graph.
// This page calls the drawGraph ajax page. It gives that page the date and format to work with.
// This function is called by the function chooseDate everytime one of the date selectors is called.
function changeDate(format,chosenDate) {	

	// Have to do this in a try block because if it tries to do it on initial page load it'll throw an error because details aren't loaded yet.
	try {
		clearDetails();
	}
		catch(err){}
	var params = new Array();
	params[0]  = "action=changeTime";
	params[1]  = "chosenDate=" + chosenDate;				 
	params[2]  = "format=" + format;
	ajaxMagic(mainUrl+'/archive/ajaxGraph.php',params,"graph","Digging up your moodjar_moods...");
}



function change(increment) {
	if(document.getElementById("allThe" + increment).style.display == "block") {
		document.getElementById("allThe" + increment).style.display = "none";
	}
	else {
		document.getElementById("allThe" + increment).style.display = "block";
	}
}


function hide(increment) {
	document.getElementById("allThe" + increment).style.display = "none";
}


function pick(whichOne,increment) {
	//document.getElementById("selected" + increment).innerHTML = whichOne;
	document.getElementById("allThe" + increment).style.display = "none";
}







// Called everytime one of the date selector is clicked. 
// 1. It calls our ajaxDates page to refresh the dates...Passes the specific year, month, day
// 2. It calls the function changeDate which will make the graph represh
function chooseDate(increment, value) {

	// What the values were:
	// Used to tell whether what they're clickin on was already selected.. ie - they're turning it off
		lastYear  = year;
		lastMonth = month;
		lastDay   = day;

	// 1. CALLS AJAXDATES PAGE TO REFRESH THE DATES	
	// Clicked a YEAR
	if(increment == "year") {				// They clicked a year
			year       = value;				// Passed in to the functionvar params = new Array();
			var params = new Array();
			params[0]  = "year=" + value;
			params[1]  = "month=" + months[month];
			params[2]  = "day=" + lastDay;
			ajaxMagic(mainUrl+'/archive/ajaxDates.php',params,"dateSelectors","Loading dates...");	
		}
	
	// Clicked a MONTH
	if(increment == "month") {
		month = value;						    // Passed in to the function		
		var params = new Array();
		params[0] = "year=" + year;
		params[1] = "month=" + months[month];
		params[2] = "day=" + lastDay;
		ajaxMagic(mainUrl+'/archive/ajaxDates.php',params,"dateSelectors","Loading dates...");	
	}
	
	// Clicked a DAY
	if(increment == "day") {
		day 	  = value;						// Passed in to the function
		// Turning off the day
		if(day == lastDay) {
			day   = "";
		}
		var params = new Array();
		params[0] = "year=" + year;
		params[1] = "month=" + months[month];
		params[2] = "day=" + day;
		ajaxMagic(mainUrl+'/archive/ajaxDates.php',params,"dateSelectors","Loading dates...");
	}
	
	
	// 1. CALLS FUNCTION CHANGEDATE WHICH WILL INTURN REFRESH THE GRAPH 
	if(day != "" && month != "" && year != "") {				// If no day is selected...
		format = "dmy";		// Then we're looking at just the year
		chosenDate = months[month] + " " + day + " " + year ;
		
	}	
	else if(month != "" && year != "" && day == "") {		// If no month is selected...
		format = "my";		// Then we're looking at just the year
		chosenDate = months[month] + " " + year;
	}	
	else {					// But if there is a month, then the format is month year
		format = "y";
		chosenDate = year; // months[month] is using the array to get the human month...ex result for this is January 2008
	}
	
	changeDate(format,chosenDate);	// Finally - call changeDate function giving it what format we're looking at, and the exact date	
}





/* --------------------------------------------------
FADE
---------------------------------------------------*/
var FADE_RED = 255;
var FADE_GREEN = 253;
var FADE_BLUE = 55;

// THE THREE VARIABLES BELOW DEFINE THE MOVEMENT OF THE FADE:
//
// 		FADE_HOLD 	= Time (in milliseconds) that your base color lasts
//					  before the fade begins.
//		FADE_SPEED 	= Time (in milliseconds) that each color of the fade lasts
//		FADE_STEP	= Increase in the RGB value per color change

var FADE_HOLD = 500;
var FADE_SPEED = 100;
var FADE_STEP = 25;

// FOR BASIC FUNCTIONALITY, LEAVE EVERYTHING BELOW THIS POINT AS IS.
var fade_r = FADE_RED
var fade_g = FADE_GREEN
var fade_b = FADE_BLUE

function fade(container)
{
	if (fade_r == 0) fade_r == FADE_RED;
	if (fade_g == 0) fade_g == FADE_GREEN;
	if (fade_b == 0) fade_b == FADE_BLUE;
	
	if (fade_r + fade_g + fade_b != (255 * 3))
	{	
		document.getElementById(container).style.background = "rgb(" + fade_r + "," + fade_g + "," + fade_b + ")";
		
		if ((fade_r == FADE_RED) && (fade_g == FADE_GREEN) && (fade_b == FADE_BLUE))
		{
			setTimeout('fade("' + container + '")', FADE_HOLD)
		}
		else
		{	
			setTimeout('fade("' + container + '")', FADE_SPEED)
		}
		
		if ((fade_r >= 255) || (fade_r + FADE_STEP > 255)) fade_r = 255; else fade_r = fade_r + FADE_STEP;
		if ((fade_g >= 255) || (fade_g + FADE_STEP > 255)) fade_g = 255; else fade_g = fade_g + FADE_STEP;
		if ((fade_b >= 255) || (fade_b + FADE_STEP > 255)) fade_b  = 255; else fade_b = fade_b + FADE_STEP;
	}
	else
	{	
		document.getElementById(container).style.background = "rgb(" + fade_r + "," + fade_g + "," + fade_b + ")";
		fade_r = FADE_RED;
		fade_g = FADE_GREEN;
		fade_b = FADE_BLUE;
	}
}

var col=255;




// Submit form on enter
// Put this in the last field of a form like this : <input type="text" onKeyPress="checkEnter(event,hey)"> 
function checkEnter(e,submitFunction){ //e is event object passed from function invocation
	try{ // If i don't use this try statement, it'll throw an error when tab is pushed
		var characterCode;
		if(e && e.which){ //if which property of event object is supported (NN4)
			e = e
			characterCode = e.which //character code is contained in NN4's which property
		}
		else{
			e = event
			characterCode = e.keyCode //character code is contained in IE's keyCode property
		}
		
		if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
			submitFunction();
			return false 
		}
		else{
			return true 
		}
	}
	catch(err) {
	
	}

}