// JavaScript Document
var t = null;
var flagForm = false;
var punctualExecute = false;

var inner
var id = new Array()
var idContent = new Array()
var tagis = new Array()
var updated = new Array()
var showTimer
var now = new Date()

var holdTag	
var holdID
var holdIDContent
var holdTime
var holdcurrentSize = 0
var counterNewTweet = 0

function terminateTimeout(timeouts){
	for ( var i in timeouts )
	{
		clearTimeout(timeouts[i]);
	}
}

function loadXMLDoc(string, hldStr, size, id, slideshow){
	terminateTimeout([timedGrab,t]);
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLDOM");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
	var results = xmlhttp.responseText
	var isEmpty = results.split("<ids>")[0].split("</ids>")[0].split("<tagis>")[1].split("</tagis>")[0]
	if ((isEmpty == "isempty")){
		if(($("#searching").length == 0) && ($(".resultsol").children("li").length > 0)){
			if(tagis.length == 0){
				if(counterNewTweet == 0){
					counterNewTweet++
					$('#twitterverse').slideUp('fast', function(){
					$('#twitterverse').html("<strong>No New Tweets To Display<strong>")
					$('#twitterverse').slideDown("slow", function(){$t = setTimeout(function(){$('#twitterverse').slideUp("slow", function(){
							$('#results').fadeTo('slow', 1); 
							timedGrab=setTimeout(function(){loadXMLDoc(string,hldStr,size,id,true)},10000)
						})},2000)})
					})
				}
				else{
					counterNewTweet++; 
					if(counterNewTweet == 3){
						newTWEETSlookup();
					}
					timedGrab=setTimeout(function(){loadXMLDoc(string,hldStr,size,id,true)},10000)
				}
			}
		}
		else if(($("#searching").length == 0) && ($(".resultsol").children("li").length == 0) && (tagis.length < 1)){
			if( $(".resultsol").children("li").length == 0){
				$(".resultsol").append('<li class="lifield" style="display:none; text-align:center;"></li>')
				$(".resultsol").children("li:eq(0)").html('<div class="msgdiv" id="-999"><strong>Your Search Did Not Return Any Results.  I\'m sorry :(<strong></div>')
				$(".resultsol li:first").fadeIn("slow", function(){
					$('#twitterverse').slideUp('fast', function(){$('#results').fadeTo('slow', 1)})
				});
			}
		}
	}
	else if(($(".resultsol").children("li").length == 0) && ($("#searching").length == 0) && (isEmpty == "isempty") && (holdTag.length <= 0)){
		$(".resultsol").append('<li class="results lifield" id="-999" style="display:none; text-align:center;"></li>')
		$(".resultsol").children("li").html('<div class="msgdiv"><strong>Your Search Did Not Return Any Results.  I\'m sorry :(<strong></div>')
		$("li:eq(0)").fadeIn("slow")
	}
	else{
		punctualExecute = false;
		buildResults(results, slideshow)
	}
    }
  }
  var buildURL
  if((hldStr != "") || (hldStr != undefined)){
	  buildURL = "&id="+hldStr
  }
  if((size != "") || (size != undefined)){
	  buildURL += "&rpp="+size
  }
  if((id != "") || (id != undefined)){
	  buildURL += "&since_id="+id
  }
	xmlhttp.open("GET","/search.asp?q="+encodeURL(string)+buildURL+"&result_type=recent",true);
	xmlhttp.send();
}

var timedGrab
function punctualRetrieval(retrievalTime, id){
	var hldStr = new Array();
	var setSZ = 20;
	$(".resultsol").find("li").each(function(i) {
		if(i < setSZ){
			hldStr[hldStr.length] = $(".msgdiv:eq("+i+")").attr("id");
		}
   	})
	timedGrab=setTimeout(function(){loadXMLDoc(document.getElementById("status").value,hldStr,setSZ,lastID, true); clearTimeout(timedGrab)},retrievalTime)
}

function newTWEETSlookup(){
	counterNewTweet = 0
	terminateTimeout([showTimer])
	$('#twitterverse').slideUp('fast', function(){
		$('#twitterverse').html("<strong>searching for tweets, please hold...</strong>")
		$('#twitterverse').slideDown("slow", function(){$t = setTimeout(function(){$('#twitterverse').slideUp("slow", function(){
				$('#results').fadeTo('slow', 1); 
				terminateTimeout([t])})},2000);
				showTimer=setTimeout(function(){showResults()},3000)									  
			});
		})
}

function showTheHours(theHour) {
	if (hours>12){
	theHour=theHour+12
	}
	if ((theHour+12) >= 24){
		theHour = 0
	}
	return (theHour);
/**	var d=new Date()
var gmtHours = -d.getTimezoneOffset()/60;

var convertTime
var timePeriod = "AM"

var UTC = new Array();
UTC[0] = "22:01";
UTC[1] = "20:00";
UTC[2] = "23:59";
UTC[3] = "12:00";
UTC[4] = "8:59";
UTC[5] = "4:59";
UTC[6] = "2:59";
UTC[7] = "0:59";
UTC[8] = "13:01";
UTC[9] = "1:00";
UTC[10] = "1:11";
UTC[11] = "16:01";
UTC[12] = "0:00";

for (var i=0; i <= UTC.length; i++){
	timePeriod = "AM"
	convertTime = parseInt(UTC[i].split(":")[0])+gmtHours
	if(convertTime > 12){
		if((convertTime-12) > 0){
			convertTime -= 12
			timePeriod = "PM"
		}
		else{
			timePeriod = "AM"
		}
		document.write("The local time of UTC " +UTC[i]+ ": " + convertTime + ":" + UTC[i].split(":")[1] + timePeriod + "</br>");
		}
	else{
		if(convertTime <= 0){
			convertTime += 12
			timePeriod = "PM"
		}
		document.write("The local time of UTC " +UTC[i]+ ": " + convertTime + ":" + UTC[i].split(":")[1] + timePeriod + "</br>");
	}
}**/
}

function buildResults(string, slideshow){
	if((holdTag == undefined) && (holdTag == "isempty")){
	terminateTimeout([showTimer,timedGrab])
	return false
	}
	terminateTimeout([showTimer,timedGrab])
	var innerArrary = string.split("<entrys>")
	innerArrary.reverse()
	for(i=0; i < innerArrary.length-1; i++){
		inner = innerArrary[i].split("</entrys>")[0]
		if($("#"+inner.split("<id>")[1].split("</id>")[0]).attr("id") == undefined){
			tagis[tagis.length] = inner.split("<ids>")[0].split("</ids>")[0].split("<tagis>")[1].split("</tagis>")[0]
			id[id.length] = inner.split("<id>")[1].split("</id>")[0]
			idContent[idContent.length] = inner.split("<ids>")[1].split("</ids>")[0]
			updated[updated.length] = inner.split("<time>")[1].split("</time>")[0]
		}
	}
	lastID = id[id.length-1]
	if(slideshow || ($(".resultsol").children("li").length != 0)){
		showTimer=setTimeout(function(){showResults()},4000)
	}
	else{
		showTimer=setTimeout(function(){intShowResults()},4000)
	}
}

function intShowResults(){
	terminateTimeout([showTimer])
	for(var j=0; j < 15; j++){
		if(tagis[j] == undefined){
			showTimer=setTimeout(function(){showResults()},2000)
			break;
		}
		holdTag = tagis.shift();
		holdIDContent = idContent.shift();
		holdTime = updated.shift();
		holdID = id.shift();
		if($("#"+holdID).attr("id") == undefined){
			if( $(".resultsol").children("li").length == 0){
				$(".resultsol").append('<li class="results lifield" style="display:block">'+holdIDContent+"</li>")
			}
			else{
				$(".lifield:eq(0)").before('<li class="results lifield" style="display:block">'+holdIDContent+"</li>")
			}
		}
		if($(".lifield").length > 20){
			$(".lifield:last").remove();
		}
	}
	showTimer=setTimeout(function(){showResults()},2000)
}

function showResults(){
	holdTag = tagis.shift();
	holdIDContent = idContent.shift();
	holdTime = updated.shift();
	holdID = id.shift();
	if((holdTag != undefined) && (holdTag != "isempty")){
		if($("#"+holdID).attr("id") == undefined){
			if( $(".resultsol").children("li").length == 0){
				$(".resultsol").append('<li class="results lifield" style="display:none">'+holdIDContent+"</li>")
			}
			else{
				$(".lifield:eq(0)").before('<li class="results lifield" style="display:none">'+holdIDContent+"</li>")
			}
			$(".lifield:eq(0)").slideDown("slow", function(){
				$('#twitterverse').slideUp('slow', function(){$('#results').fadeTo('slow', 1)})
				$(".resultsol").find("#-999").each(function(i) {
				$(this).slideUp("fast", function(){$(this).remove();});
				})
				terminateTimeout([showTimer])
				showTimer=setTimeout(function(){showResults()},3000)
			})
		}
		else if($('#twitterverse').is(":hidden") && (tagis.length > 0)){
				newTWEETSlookup();
		}
		if($(".lifield").length > 20){
			$(".lifield:last").remove();
		}
		else{
			terminateTimeout([showTimer])
		}
	}
	else{
		terminateTimeout([showTimer])
		return false
	}
	if ((tagis.length <= 2) && (punctualExecute == false)){
		punctualExecute = true;
		punctualRetrieval(1000, lastID);
	}
	else{
		punctualExecute = false;
	}
}

function hldPattern(string){
	clearTimeout(t);
    $('#results').fadeTo('slow', 0.5)
	$('#twitterverse').slideDown('slow');
	t=setTimeout(function(){searchSTR(string)},1500)
}
function switchLink(links, doing, txt){
	terminateTimeout([showTimer,timedGrab, t])
	$('#twitterverse').slideUp('slow', function(){$('#results').fadeTo('slow', 1)})
	if($(links).html() != "Turn Off Twitterverse"){
		$(links).html("Turn Off Twitterverse")
		$(doing).html("What are you looking for?")
		$("#tweeting_button").html("Search")
		$("#tweeting_button").removeAttr("disabled")
		$("#tweeting_button").removeAttr("href")
		$("#tweeting_button").removeAttr("class")
		$("#tweeting_button").removeAttr("name")
		$("#tweeting_button").attr("name", "search")
		$("#tweeting_button").attr("class", "a-btn a-btn-m btn-enabled")
		$("#tweeting_button").attr("href", "#")
		$("#status-field-char-counter").html("")
		$("#tweeting_button").click(function() {
		  flagForm = true;
		  $('#udpate_tweet').submit();
		});		
		$("#status").addClass("searchFLD")
		 document.getElementById("status").value = "start your search here"
		 $("#status").unbind();
		$(txt).focus(function() {
		  $(txt).unbind('focus');
		  $("#status").removeClass("searchFLD")
		  document.getElementById("status").value = ""
		});
		$(txt).keyup(function() {
		  id = new Array()
		  idContent = new Array()
          tagis = new Array()
          updated = new Array()
		  counterNewTweet = 0
		  terminateTimeout([showTimer,timedGrab, t])
		  $('#twitterverse').html("<strong>Getting your results from the tweet universe...</strong>")
		  hldPattern(document.getElementById("status"))
		});
	}
	else{
		terminateTimeout([timedGrab])
		$(links).html("Try It Now")
		$(doing).html("Whats Happening?")
		$("#status-field-char-counter").html("140")
		$("#tweeting_button").html("Tweet")
		$("#tweeting_button").attr("disabled", "disabled")
		$("#tweeting_button").removeAttr("class")
		$("#tweeting_button").attr("class", "a-btn a-btn-m btn-disabled")
		$("#tweeting_button").removeAttr("name")
		$("#tweeting_button").attr("name", "status")
		$("#tweeting_button").attr("href", "#")
		$("#status").removeClass("searchFLD")
		document.getElementById("status").value = ""
		//$(txt).bind("onkeyup", function(event){hldPattern(document.getElementById("status"))})
		$(txt).unbind();
		$(txt).keyup(function() {
		  getLength()
		});
		$("#udpate_tweet").submit( function () {
		  flagForm = false;
		  $('#udpate_tweet').submit();
		} );
	}
}
function replaceHTML(str){
	var str2
	str2 = str.replace("#", "&#35;")
	str = str2.replace("<", "&#60;")
	str2 = str.replace(">", "&#62;")
	return str2;
}
function encodeURL(str){
	var str2
	str2 = str.replace("#", "%23")
	str = str2.replace("<", "%3C")
	str2 = str.replace(">", "%3E")
	return str2;
}
function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}
function searchSTR(string){
	var str = new RegExp(replaceHTML('\\b'+string.value+'\\b'),'i')
	var hldStr = new Array();
	var i = 0
	
	idContent = new Array()
	tagis = new Array()
	updated = new Array()

	$(".resultsol").find("li").each(function(i) {
        var ahref = $(this).find(".msg").find("a:eq(0)").html();
		var htmlSTR = $(this).find(".msgtxt").html();
		htmlSTR = strip(ahref + " " + htmlSTR)
		if(htmlSTR.match(str) != null){
			hldStr[hldStr.length] = $(this).find(".msgdiv").attr("id");
		}
		else{
			$(this).remove();
		}
    })
	$("#search_query").html("Results for <b>"+replaceHTML(string.value)+"</b>")
	if($(".resultsol").children("li").length == 0){
		loadXMLDoc(string.value,"",20,"", false)
	}
	else{
		loadXMLDoc(string.value,"",20,$(".resultsol li:first .msgdiv:eq(0)").attr("id"), false)
	}
}
var holdSize = 0
function getLength(){
	if($("#status").val().length != 0){
		$("#tweeting_button").attr("class", "a-btn a-btn-m btn-enabled")
		if (holdSize < $("#status").val().length){
			$("#status-field-char-counter").html(parseInt($("#status-field-char-counter").html())+(holdSize-$("#status").val().length))
		}
		else{
			$("#status-field-char-counter").html(parseInt($("#status-field-char-counter").html())-($("#status").val().length-holdSize))
		}
		if(parseInt($("#status-field-char-counter").html()) < 0){
			$("#tweeting_button").attr("class", "a-btn a-btn-m btn-disabled")
			$("#status-field-char-counter").css({'color': 'rgb(204, 0, 0)'})
		}
		else{
			$("#status-field-char-counter").css({'color': 'rgb(204, 204, 204)'})
		}
		holdSize = $("#status").val().length
	}
	else{
		$("#tweeting_button").attr("class", "a-btn a-btn-m btn-disabled")
		$("#status-field-char-counter").css({'color': 'rgb(204, 204, 204)'})
		$("#status-field-char-counter").html("140")
		holdSize = 0
	}
}
$(document).ready(function() {
	$("#status").keyup(function() {
		getLength()
	});
	$("#udpate_tweet").submit( function () {
	  return this.flagForm;
	} );
});
// JavaScript Document
