/*!
 * - TwitBatch
 * Core Javascript Methods
 * Copyright 2014, Andrew Cobley
 */



var AGG = {
	results: [],
	searches: [
		// { site: "twitter", term: "bristol front end" },
		// { site: "twitter", term: "bristol frontend" },
		// { site: "twitter", term: "bristol junior web" },
		// { site: "twitter", term: "cardiff front end" },
		// { site: "twitter", term: "cardiff junior web" },
		// { site: "indeed", term: "bristol front end" },
		// { site: "indeed", term: "bristol junior web" },
		// { site: "indeed", term: "cardiff front end" },
		// { site: "indeed", term: "cardiff junior web" }
	],
	colors: [
		{ text: "", background: "rgb(123, 69, 105)" },
		{ text: "", background: "rgb(216, 92, 38)" },
		{ text: "", background: "rgb(145, 155, 143)" },
		{ text: "", background: "rgb(80, 195, 188)" },
		{ text: "", background: "rgb(145, 108, 41)" },
		{ text: "", background: "rgb(208, 106, 113)" },
		{ text: "", background: "rgb(182, 150, 84)" },
		{ text: "", background: "rgb(182, 186, 119)" },
		{ text: "", background: "rgb(56, 101, 145)" },
		{ text: "", background: "rgb(99, 116, 113)" }
	]
};


window.onload = function(){

	checkLocalStorage();
	setupSearches();
	displaySearches();
	initialSearch();
  
};

function checkLocalStorage()
{
	var saved_searches = JSON.parse(localStorage.getItem("AGG_SEARCHES"));
	AGG.searches = (saved_searches !== null) ? saved_searches : [];
}

function toggleSubOptions()
{
	console.dir(document.getElementById("sub-options"));

	var state = document.getElementById("sub-options").className;

	if (state === "sub-options-hidden" || state === "")
	{
		document.getElementById("sub-options").className = "sub-options-show";
	}
	else
	{
		document.getElementById("sub-options").className = "sub-options-hidden";
	}
}

// ################################################################################
// SEARCH FUNCTIONS
// ################################################################################

function newSearch()
{
	var select = document.getElementById("search_site");
	var option = select.options[select.selectedIndex].value;
	console.log(option);

	var term = document.getElementById("search_term").value;
	console.log(term);

	addNewSearch(option,term);
}

function addNewSearch(site,term)
{
	var search = {};
	search.site = site;
	search.term = term;
	search.initial = getInitials(search.term, 3);
	search.color = AGG.colors[AGG.searches.length % AGG.colors.length].background;
	search.uid = getNextSearchUID();

	AGG.searches.push(search);

	saveSearchesLocally();

	// Add To Sidebar
	displaySearch(search);

	// Start Search Proper
	startSearch(search);
}

function saveSearchesLocally()
{
	localStorage.setItem("AGG_SEARCHES",JSON.stringify(AGG.searches));
}

function setupSearches()
{
	for (var i = 0; i < AGG.searches.length; i++)
	{
		var search = AGG.searches[i];
		search.initial = getInitials(search.term, 3);
		search.color = AGG.colors[i % AGG.colors.length].background;
	}
}

function getInitials(content,num)
{
	var arr = content.split( ' ' );

	var results = '';
	for( x=0; x<arr.length; x++)
	{
	    results += arr[x].charAt(0);
	}

	return results.substring(0,num);
}

function initialSearch()
{
	for (var i = 0; i < AGG.searches.length; i++)
	{
		var search = AGG.searches[i];
		startSearch(search);
	}
}

function startSearch(search)
{
	console.dir(search);
	switch(search.site)
	{
		case "twitter" :
			searchTwitterForTerm(search);
			break;
		case "indeed" :
			searchIndeedForTerm(search);
			break;
		default:
			console.log("SEARCH SITE NOT RECOGNISED.");
	}	
}

function displaySearches()
{
	for (var i = 0; i < AGG.searches.length; i++)
	{
		var search = AGG.searches[i];
		displaySearch(search);
	}
}

function displaySearch(search)
{
	var li = document.createElement('li');

	var url = getUrlForSearch(search);
	// var color = AGG.colors[i % AGG.colors.length].background;
	// console.log(color);

	var html = "";
	html += "<a href='" + url + "'><span class='site'>" + search.site + "</span><span class='term' style='background:" + search.color + ";'>" + search.term + "</span></a>";
	html += "<a href='#' class='delete-search' data-uid='" + search.uid + "' onclick='deleteSearch(this)''>X</a>";

	li.innerHTML = html;
	document.getElementById("searches").appendChild(li);
}

function deleteSearch(e)
{
	var uid = parseInt(e.getAttribute("data-uid"));
	var index = getIndexForUID(uid);

	if (index > -1)
	{
		e.parentNode.parentNode.removeChild(e.parentNode);
		AGG.searches.splice(index,1);
		saveSearchesLocally();
	}
}

function getIndexForUID(uid)
{
	for (var i = 0; i < AGG.searches.length; i++)
	{
		if (AGG.searches[i].uid === uid)
		{
			return i;
		}
	}
}

function getUrlForSearch(search)
{
	if (search.site === "twitter")
	{
		return "https://twitter.com/search?q=" + encodeURIComponent(search.term);
	}
}

function getNextSearchUID()
{
	var nextUID = 0;
	for (var i = 0; i < AGG.searches.length; i++)
	{
		nextUID = (AGG.searches[i].uid >= nextUID) ? AGG.searches[i].uid + 1 : nextUID;
	}
	return nextUID;
}



// ################################################################################
// INDEED API FUNCTIONS
// ################################################################################

function searchIndeedForTerm(search)
{
	var query = "?q=" + encodeURIComponent(search.term);
	console.log(query);

	var xmlhttp;

	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp = new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.withCredentials = true;

	xmlhttp.open("GET","php/indeed.php" + query,true);
	xmlhttp.send();

	console.log(xmlhttp);

	xmlhttp.onreadystatechange = function()
  	{
  		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    	{
    		var response = JSON.parse(xmlhttp.response);
    		console.dir(response);
    		createIndeeds(response.results, search);
    	}
  	};
}

function createIndeeds(indeeds, search)
{
	for (var i = 0; i < indeeds.length; i++)
	{
		var result = indeeds[i];
		if ( !checkForDuplicateIndeed(result.jobkey) )
		{
			result.uid = result.jobkey;
			result.search = search;
			result.element = createIndeedFromTemplate(result);
			result.sortDate = new Date(Date.parse( result.date ));
			addToResults(result);
		}
		else
		{
			console.log("DUPLICATE ENTRY - INGNORE");
		}
	}
	if(AGG.results.length > 0)
	{
		displayResults();
	}
}

function createIndeedFromTemplate(indeed)
{

	var li = document.createElement('li');
	//var indeed_text = parseTwitterText(indeed.text);
	var indeed_date = parseTwitterDate(indeed.date);

	var html = "";

	html += "<header><a href='" + indeed.url + "'>" + indeed.source + "</a></header>";
	html += "<span class='site-initial'>In</span><span class='term-initial' title='Search Term = " + indeed.search.term + "' style='background-color:" + indeed.search.color + ";'>" + indeed.search.initial + "</span>";
	html += "<p>" + indeed.jobtitle + " " + indeed.snippet + "</p>";
	html += "<footer>" + indeed_date + "</footer>";

	li.innerHTML = html;

	return li;
}

function checkForDuplicateIndeed(uid)
{
	for (var i = 0; i < AGG.results.length; i++)
	{
		var result = AGG.results[i];
		if ( result.uid && result.uid === uid )
		{
			return true;
		}
	}
}


// ################################################################################
// TWITTER API FUNCTIONS
// ################################################################################

function searchTwitterForTerm(search)
{
	var query = "?q=" + encodeURIComponent(search.term);
	//console.log(query);

	var xmlhttp;

	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp = new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
	  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	xmlhttp.open("GET","php/twitter.php" + query,true);
	xmlhttp.send();

	console.log(xmlhttp);

	xmlhttp.onreadystatechange = function()
  	{
  		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    	{
    		var response = JSON.parse(xmlhttp.response);
    		console.dir(response);
    		createTweets(response.statuses, search);
    	}
  	};

}

function createTweets(tweets,search)
{
	for (var i = 0; i < tweets.length; i++)
	{
		var result = tweets[i];
		if ( !checkForDuplicateIndeed(result.uid) )
		{
			result.uid = result.id_str;
			result.search = search;
			result.element = createTweetFromTemplate(result);
			result.sortDate = new Date(Date.parse( result.created_at ));
			addToResults(result);
		}
		else
		{
			console.log("DUPLICATE ENTRY - INGNORE");
		}
	}
	if(AGG.results.length > 0)
	{
		displayResults();
	}
}

function createTweetFromTemplate(tweet)
{

	var li = document.createElement('li');
	var tweet_text = parseTwitterText(tweet.text);
	var tweet_date = parseTwitterDate(tweet.created_at);

	var html = "";

	html += "<header>" + tweet.user.name + " @" + tweet.user.screen_name + "</header>";
	html += "<span class='site-initial'>Tw</span><span class='term-initial' title='Search Term = " + tweet.search.term + "' style='background-color:" + tweet.search.color + ";'>" + tweet.search.initial + "</span>";
	html += "<p>" + tweet_text + "</p>";
	html += "<footer>" + tweet_date + "</footer>";

	li.innerHTML = html;

	return li;
}

function parseTwitterText(text)
{
	text = text.replace(/(\b(www\.|http\:\/\/)\S+\b)/g, "<a target='_blank' href='$1'>$1</a>");
	text = text.replace(/#(\w+)/g, "<a target='_blank' href='http://search.twitter.com/search?q=$1'>#$1</a>");
	text = text.replace(/@(\w+)/g, "<a target='_blank' href='http://twitter.com/$1'>@$1</a>");

	console.log(text);
	return text;
}

function parseTwitterDate(date)
{		
	return new Date(Date.parse(date.replace(/( +)/, ' UTC$1')));
}

// ################################################################################
// RESULT FUNCTIONS
// ################################################################################

function addToResults(result)
{
	AGG.results.push(result);
}

function displayResults()
{
	// Sort Results
	var sorted = sortResultsByDate(AGG.results);
	AGG.results = (sorted.length > 0) ? sorted : AGG.results;

	// Create Time Checks
	var now = new Date();
	var timestep = "";

	// Clear Old Results
	document.getElementById("results").innerHTML = "";

	for (var i = 0; i < AGG.results.length; i++)
	{
		//console.dir(AGG.results[i]);
		var result = AGG.results[i];
		var new_timestep = getTimestepForResultDate(now, result.sortDate);

		if (timestep !== "Older than a week" && new_timestep !== timestep)
		{
			addTimeIndicator(new_timestep);
			timestep = new_timestep;
		}

		document.getElementById("results").appendChild(result.element);
	}
}

function getTimestepForResultDate(now, result_date)
{
	var diff = (now - result_date) / 60000; // minutes
	console.log(diff + " minutes ago");

	if (diff <= 60)
	{
		return "Now";
	}
	else if (diff > 60 && diff <= 180)
	{
		return "Last 3 hours";
	}
	else if (diff > 180 && diff <= 360)
	{
		return "Last 6 hours";
	}
	else if (diff > 360 && diff <= 1440)
	{
		return "Last 24 hours";
	}
	else if (diff > 1440 && diff <= 10080)
	{
		return "This week";
	}
	else
	{
		return "Older than a week";
	}

	return "";
}

function addTimeIndicator(indicator)
{
	var div = document.createElement('div');
	div.className = "time-indicator";

	var html = "<span>" + indicator + "</span>";
	div.innerHTML = html;

	document.getElementById("results").appendChild(div);
}


function sortResultsByDate(results)
{
	var sorted_results = [];
	sorted_results.push(results[0]);

	for (var i = 1; i < results.length; i++)
	{
		var index = getIndexByDate(sorted_results, results[i]);
		sorted_results.splice(index,0,results[i]);
	}

	return sorted_results;
}

function getIndexByDate(sorted, entry)
{	
	for (var i = 0; i < sorted.length; i++)
	{
		//console.log(entry.sortDate + " ? " + sorted[i].sortDate);
		if (entry.sortDate > sorted[i].sortDate)
		{
			return i;
		}
	}
	return sorted.length;
}



