//=====================================================================
// Home Helper Functions
//=====================================================================
var CONST_RESULTS_DISPLAYED_NUM = 50;
var CONST_SEARCH_OFFSET = 15;
var topZIndex = 11;
var searchResultsIds = new Array();
var searchResultsIntros = new Array();
var searchResultsIntrosColors = new Array();
var searchResultsScrollIndex = new Array();
var sliders = Array();
var noMoreResults = new Array(); //Keep track of which search boxes have scrolled to the point of no more results
var canScroll = true; // ensure that more than one request for more results doesn't happen at a time.  prevents misordering
var numberOfSearches = 0;
var searchPositions = "";
var preloadDistance = 500;
var binHidden = true;
var pseudoSearchId = 0;

var map = null;
var geocoder = null;
var longitude = null;
var latitude = null;

// Search Types
// 0 => tag
// 1 => User
// 2 => Recent Posts
// 3 => Recent Threads
// 4 => Geotag
var searchTypeImages = new Array('tag_blue','user','tag_blue','tag_blue','world');
Event.observe(window,'load',init);

function init() {
	// Observe changes of a form element
	geoTagsArray = new Array();
	Event.observe($('query'), 'focus', function(event) { Effect.Appear('searchHelp'); });	

	if(isFirstTimeUser) {
		displayWelcomeWindow();
	}
	
	if(!isLoggedIn) {
		displayWelcomeWindow();
	}
}

function changeToUserSearch() {
	 //changeSearchTabBodyColor('#D1FFD1');
	 $('userSearchTabBody').style.display = "block";
	 $('searchTabBody').style.display = "none";
	 creatingPost = 1;
	 $('centerwrap').style.zIndex = topZIndex + 10;
	 $('rolloverZone').style.zIndex = 0;	 
	 $('navCreate').className = "active";
	 $('navSearch').className = "inactive";

}

function changeToTagSearch() {
	 //changeSearchTabBodyColor('#BAD6F5');
	 $('userSearchTabBody').style.display = "none";
	 $('searchTabBody').style.display = "block";
	 creatingPost = 0;
	 $('centerwrap').style.zIndex = 0;	
	 $('navCreate').className = "inactive";
	 $('navSearch').className = "active";

}

function changeSearchTabBodyColor(color) {
	$('searchTabBody').style.backgroundColor = color;
}

function attachTooltip() {
// Start the Tooltips in motion
	Tooltip.setup();
}

function showBackgroundGrid() {
	$('backgroundDrop').style.backgroundImage = 'url(\'/images/grid.gif\')';
}

function hideBackgroundGrid() {
	$('backgroundDrop').style.backgroundImage = '';
}

function createHTMLPostList(list, searchTerms, searchBoxId,type) {
	var searchResults = '<ul><li><a id="scrollUpLink_'+searchBoxId+'" href="javascript:void(0);"  class="scrollUpArrow" onMouseUp="scrollUp(\''+searchTerms+'\', '+searchBoxId+');"><img src="/images/upArrow.gif" /></a></li></ul>';
	searchResults += '<div style="height: 100%; display: none;z-index:1000; width: 3px; float:right;" id="scrollerTrack_'+searchBoxId+'">&nbsp;<div style="height: 10px; width: 3px;cursor:move; background: black;" id="scrollerMark_'+searchBoxId+'">&nbsp;</div></div><div id="scroller_'+searchBoxId+'" style="position:relative; height: 100%; overflow:hidden;"><ul class="listOfSearchResults" id="listOfSearchResults_'+searchBoxId+'">';
	numResults = list.length;
	if(searchTerms == '') {
		searchTermsURLString = '';
	} else {
		searchTermsURLString = '/search/' + searchTerms;
	
		// Only do this if we have search terms because we don't care about the type if there are no search terms
		searchTermsURLString += '/t/' + type;
		
	}


	//If there are no results then output message
	if(numResults == 0) {
		searchResults += '<li style="color: #333333; text-align: center; font-weight: normal;">There are no results yet for <br />' + searchTerms + '.  <br /><br /><a href="/post/create/tags/'+searchTerms+'" style="line-height: 1.5;text-decoration: underline">Start a discussion about <span style="font-weight:bold;">' + searchTerms 	+ '</span> and get people talking now!</a></li>';
		noMoreResults[searchBoxId] = true;
	} else {

		for(i = 0; i < numResults; i++) {
			if((list[i].original_post_id == list[i].id) || (type == 3)){
				var isOP = true;
			} else {
				var isOP = false;
			}
			searchResultsIntrosColors[list[i].id] = rgb2hex(Math.round(list[i].red), Math.round(list[i].green), Math.round(list[i].blue));
			
			if(isOP) { 
				searchResults += '<li style="position: relative;" id="searchResult_'+list[i].id+'"><a href="/post/view/id/'+list[i].id+searchTermsURLString+'/title/'+list[i].title.replace(/[ .%]/g,"_")+'" id="searchResult_'+list[i].id+'" class="searchResult_'+list[i].read+'" style="background:#'+searchResultsIntrosColors[list[i].id]+'"><span class="title">'+list[i].title+' ('+list[i].postsInThread+')</span>';
			} else {
				searchResults += '<li style="position: relative;" id="searchResult_'+list[i].id+'"><a href="/post/view/id/'+list[i].id+searchTermsURLString+'/title/'+list[i].title.replace(/[ .%]/g,"_")+'#SPP_'+list[i].id+'" id="searchResult_'+list[i].id+'" class="searchResult_'+list[i].read+'" style="background:#'+searchResultsIntrosColors[list[i].id]+'"><span class="title">'+list[i].title+' ('+list[i].postsInThread+')</span>';
			}

			searchResultsIds[i] = list[i].id;
			searchTermsBold = "<span style=\"font-size: 12px; font-style: italic; font-weight: bold;\">"+searchTerms+"</span>";
			searchResultsIntros[i] = "<span id='searchResult_"+list[i].id+"_intro'><span style='font-weight: bold; font-size: 12px;'>" + list[i].username + ": </span>" + list[i].intro.replace(searchTerms,searchTermsBold) + "</span>";

			var postDate = convertTimestampToDate(list[i].datePosted);			
			var dateString = createSmartDate(postDate);
			searchResults += "&nbsp;<span class='date' style='position: absolute;right:10px;background:#"+searchResultsIntrosColors[list[i].id]+"'>"+ dateString + " </span><br />";
			searchResults += "<span class='username' style='font-style:italic; font-weight: 600;'>"+list[i].username + " said: </span><span class='intro'> " + list[i].intro.replace(searchTerms,searchTermsBold) + "...</span>";
			searchResults += "</a></li>";
		}
		
	}

	searchResults += '</ul></div>';
	return searchResults;
}

function appendToHTMLPostList(list, searchTerms, searchBox, type, searchBoxId) {
	
	var searchResults = "";
	numResults = list.length;

	if(searchTerms == '') {
		searchTermsURLString = '';
	} else {
		searchTermsURLString = '/search/' + searchTerms;

		// Only do this if we have search terms because we don't care about the type if there are no search terms
			searchTermsURLString += '/t/' + type;
		
	}
	//If there are no results then output message
	if(numResults == 0) {

		if(noMoreResults[searchBoxId]) { // Don't repeat the message if we already know there are no more results
			return;
		}
		searchResults += '<li style="color: #333333; text-align: center; font-weight: normal;">There are no more results for ' + searchTerms + '.  <br /><br /><a href="/post/create/tags/'+searchTerms+'" style="line-height: 1.5;text-decoration: underline">Start a discussion about <span style="font-weight:bold;">' + searchTerms 	+ '</span> and get people talking now!</a></li>';
		noMoreResults[searchBoxId] = true;		
		
	} else {
		
		for(i = 0; i < numResults; i++) {
			if(list[i].original_post_id == list[i].id) {
				var isOP = true;
			} else {
				var isOP = false;
			}

			searchResultsIntrosColors[list[i].id] = rgb2hex(Math.round(list[i].red), Math.round(list[i].green), Math.round(list[i].blue));
			
			if(isOP) { 
				searchResults += '<li style="position: relative;" id="searchResult_'+list[i].id+'"><a href="/post/view/id/'+list[i].id+searchTermsURLString+'/title/'+list[i].title.replace(/[ .%]/g,"_")+'" id="searchResult_'+list[i].id+'" class="searchResult_'+list[i].read+'" style="background:#'+searchResultsIntrosColors[list[i].id]+'"><span class="title">'+list[i].title+' ('+list[i].postsInThread+')</span>';
			} else {
				searchResults += '<li style="position: relative;" id="searchResult_'+list[i].id+'"><a href="/post/view/id/'+list[i].id+searchTermsURLString+'/title/'+list[i].title.replace(/[ .%]/g,"_")+'#SPP_'+list[i].id+'" id="searchResult_'+list[i].id+'" class="searchResult_'+list[i].read+'" style="background:#'+searchResultsIntrosColors[list[i].id]+'"><span class="title">'+list[i].title+' ('+list[i].postsInThread+')</span>';
			}

			searchResultsIds[i] = list[i].id;
			searchTermsBold = "<span style=\"font-size: 12px; font-style: italic; font-weight: bold;\">"+searchTerms+"</span>";
			searchResultsIntros[i] = "<span id='searchResult_"+list[i].id+"_intro'><span style='font-weight: bold; font-size: 12px;'>" + list[i].username + ": </span>" + list[i].intro.replace(searchTerms,searchTermsBold) + "</span>";

			var postDate = convertTimestampToDate(list[i].datePosted);			
			var dateString = createSmartDate(postDate);
			searchResults += "&nbsp;<span class='date' style='position: absolute;right:10px;background:#"+searchResultsIntrosColors[list[i].id]+"'>"+ dateString + " </span><br />";
			searchResults += "<span class='username' style='font-style:italic; font-weight: 600;'>"+list[i].username + " said: </span><span class='intro'> " + list[i].intro.replace(searchTerms,searchTermsBold) + "...</span>";
			searchResults += "</a></li>";
		}
		
	}

	searchBox.innerHTML += searchResults;	
	
}

// scroll the element vertically based on its width and the slider maximum value
function scrollVertical(value, element, slider, searchTerms, id, type, start) {
	obj = element;
	objadd = $('listOfSearchResults_'+id);	
	element.scrollTop = Math.round(value/slider.maximum*(element.scrollHeight-element.offsetHeight));
	
	if(getSearchHeight(obj) - getScrollHeight(obj) < preloadDistance) {
		if(canScroll) {
			canScroll = false;
			appendToSearch(searchTerms,objadd,type,searchResultsScrollIndex[id],id);
			searchResultsScrollIndex[id] = searchResultsScrollIndex[id] + CONST_SEARCH_OFFSET;
		}
	}	
}

function scrollDown(searchTerms,id,type,start,sort) {

		objadd = $('listOfSearchResults_'+id);
		obj = $('scroller_'+id);
		obj.scrollTop += 10; //scroll by 10px at a time

	    $('scrollerMark_'+id).style.top = ((obj.scrollTop/getSearchHeight(obj))*_getWindowHeight(obj))+obj.scrollTop+"px";
		//		$('scrollerMark_'+id).innerHTML = (getScrollHeight(obj)/_getWindowHeight(obj));
		//$('scrollerMark_'+id).innerHTML = (obj.scrollTop/getSearchHeight(obj));


		//offset = ((sliders[id].maximum-sliders[id].minimum)/10);
		if(getSearchHeight(obj) - getScrollHeight(obj) < preloadDistance) {
			if(canScroll) {
				canScroll = false;
				appendToSearch(searchTerms,objadd,type,searchResultsScrollIndex[id],id,sort);
				searchResultsScrollIndex[id] = searchResultsScrollIndex[id] + CONST_SEARCH_OFFSET;
				//sliders[id].setValueBy(-offset);
			}
		} else {
				//sliders[id].setValueBy(offset);
		}
}


function scrollUp(searchTerms, id) {

		obj = $('scroller_'+id);
		if(obj.scrollTop >= 0) {
			obj.scrollTop -= 10;
		}
		// offset = ((sliders[id].maximum-sliders[id].minimum)/10);		
		// sliders[id].setValueBy(-offset);
}

function getSearchHeight(searchBox){
  var y;
  var test1 = searchBox.scrollHeight;
  var test2 = searchBox.offsetHeight
  if (test1 > test2) {
    y = searchBox.scrollHeight;
  } else {
	  y = searchBox.offsetHeight;
  }
  return parseInt(y);
}

function _getWindowHeight(searchBox){
  if (searchBox.innerWidth) {
		frameWidth = searchBox.innerWidth;
		frameHeight = searchBox.innerHeight;
  } else {
    frameWidth = searchBox.clientWidth;
    frameHeight = searchBox.clientHeight; 
  } 
  return parseInt(frameHeight);
}

function getScrollHeight(searchBox){
  var y;
  y = searchBox.scrollTop;
  
  return parseInt(y)+_getWindowHeight(searchBox);
}

function setResultsList(resultsHTML, searchResultsBoxId) {
		$(searchResultsBoxId+'_results').innerHTML = resultsHTML;
		
}

function setAlertBox(message){
	$("alertbox").innerHTML = message;
}

function createNewSearch(searchTerms, type) {
			new Ajax.Request('/search/create/query/'+searchTerms+'/searchType/'+type+'/sort/1', {asynchronous:true, evalScripts:true, onComplete:function(request){createSearch(request)}});
}

function createSearch(request) {
	//var searchResults = eval('('+request.responseText+')');

	var searchResults = request.responseText.evalJSON(true);
    var type = 0;
	//listOfSimplePosts = json.ListOfQualitySimplePosts;
	if(searchResults.answer.answerSearch.status == "search successfully inserted") {
		var searchId = searchResults.answer.answerSearch.id;

		searchTitle = searchResults.title;
		type = searchResults.type;
		xPos = 150;
		yPos = 200;
		positionOffset = getPositionOffset(xPos,yPos,CONST_SEARCH_OFFSET,CONST_SEARCH_OFFSET);
		xPos += positionOffset;
		yPos += positionOffset;
		searchPositions += xPos+','+yPos+';';
		displaySearch(searchResults.result.ListOfQualitySimplePosts,searchTitle,searchTitle,searchId,xPos,yPos,300,300,type,1,1,1);
	} else {
		return "there was an error";
	}
	pageTracker._trackPageview("/search/"+searchTitle+"/type/"+type);

}

function renderSearch(request,title,searchTerms,id,xPos,yPos,height,width,type) {
	//var listOfPosts = eval('('+request.responseText+')');
	var listOfPosts = request.responseText.evalJSON(true);
	
	var result = listOfPosts.ListOfQualitySimplePosts;	
	displaySearch(result,title,searchTerms,id,xPos,yPos,height,width,type,0);
}

function renderSearchJson(request,title,searchTerms,id,xPos,yPos,height,width,type,sort) {

	//var listOfPosts = eval('('+request.responseText+')');
	var listOfPosts = request.evalJSON(true);
	
	var result = listOfPosts.ListOfQualitySimplePosts;	
	displaySearch(result,title,searchTerms,id,xPos,yPos,height,width,type,0,sort);
}

function getPositionOffset(xPos,yPos,origOffset,offset) {
	coordinateString = xPos+','+yPos+';';

	if(searchPositions.indexOf(coordinateString,0) != -1) {
		return getPositionOffset(xPos+offset,yPos+offset,origOffset,offset+origOffset);
	} else {
		return offset-origOffset;
	}
}

var scrollButtonInterval = null;

// result = json from ajax call
// title = title of the search
// searchTerms = search terms
// id
// xPos, yPos, heigh, width = specs for search box
// type = tag, user, geotag, recent, new
// new = is this search created prior to a refresh?
// sort = the sort type... by date or relevancy
function displaySearch(result,title,searchTerms,id,xPos,yPos,height,width,type,isNew,sort)
{	
	var newWindowId;

	if((id == 0) || (!id)){
		newWindowId = pseudoSearchId++;
	} else {
		newWindowId = id;
	}
//	title = "<select style='background: url(\"/images/icons/"+searchTypeImages[type]+".gif\") no-repeat; width: 14px; padding: 0px 10px; border: 0px solid black;'><option style='background: url(\"/images/icons/"+searchTypeImages[0]+".gif\");'>&nbsp;</option><option style='background: url(\"/images/icons/"+searchTypeImages[1]+".gif\");'>&nbsp;</option><option style='background: url(\"/images/icons/"+searchTypeImages[4]+".gif\");'>&nbsp;</option></select>&nbsp;"+title;
	title = "<img src='/images/icons/"+searchTypeImages[type]+".gif' style='vertical-align:middle' />&nbsp;"+title;
	var win = new Window({id: "window_"+newWindowId, className: "dialog", width:width, height:height, zIndex: topZIndex, resizable: true, maximizable: false, sortType: sort, searchType: type, title: title, tags: searchTerms, showEffect:Effect.Appear, hideEffect: Effect.Fade, draggable:true, wiredDrag: false, onEndMove: savePosition, onEndResize: updateDimensions, onSelectSort: updateSort, destroyOnClose: true, gridX: 5, gridY: 5, minWidth: 200});
	topZIndex += 10;
	
	noMoreResults[newWindowId] = false; //Set initial value of false when new search is created, since we havent check for more results yet


	win.setLocation(yPos,xPos);
	var listOfPosts = result;
	var newSearch;
	var didYouMeanText = "";
	if(listOfPosts.status != "error") {
		
		if(isNew == 1) {
			if(type == 0) {
				didYouMeanText = "<span id='didYouMean_" + newWindowId + "' style='background: #FFFFAA; color: black; margin: 30px 10px 0px 10px; padding: 5px;  position: relative; display: block;'><span style='position: absolute; top: 2px; right: 2px;'><a href='#' onClick='Effect.Fade(\"didYouMean_"+newWindowId+"\")'>X</a></span>Did you mean:" +
							 " <Br /><img src='/images/icons/world.gif' style='vertical-align:middle'/>&nbsp;location <a href='#' onClick='Windows.close(\"window_"+newWindowId+"\", event); createNewSearch(\""+searchTerms+"\", "+4+")'>" + searchTerms + "?</a>" +			
							 " <Br /><img src='/images/icons/user.gif' style='vertical-align:middle'/>&nbsp;user <a href='#' onClick='Windows.close(\"window_"+newWindowId+"\", event); createNewSearch(\""+searchTerms+"\", "+1+")'>" + searchTerms + "?</a></span>";			
			} else if(type == 1) {
				didYouMeanText = "<span id='didYouMean_" + newWindowId + "' style='background: #FFFFAA; color: black; margin: 30px 10px 0px 10px; padding: 5px;  position: relative; display: block;'><span style='position: absolute; top: 2px; right: 2px;'><a href='#' onClick='Effect.Fade(\"didYouMean_"+newWindowId+"\")'>X</a></span>Did you mean:" +
							 " <Br /><img src='/images/icons/world.gif' style='vertical-align:middle'/>&nbsp;location <a href='#' onClick='Windows.close(\"window_"+newWindowId+"\", event); createNewSearch(\""+searchTerms+"\", "+4+")'>" + searchTerms + "?</a>" +			
							 " <Br /><img src='/images/icons/tag_blue.gif' style='vertical-align:middle'/>&nbsp;tag <a href='#' onClick='Windows.close(\"window_"+newWindowId+"\", event); createNewSearch(\""+searchTerms+"\", "+0+")'>" + searchTerms + "?</a></span>";			
			} else if(type == 4) {
				didYouMeanText = "<span id='didYouMean_" + newWindowId + "' style='background: #FFFFAA; color: black; margin: 30px 10px 0px 10px; padding: 5px;  position: relative; display: block;'><span style='position: absolute; top: 2px; right: 2px;'><a href='#' onClick='Effect.Fade(\"didYouMean_"+newWindowId+"\")'>X</a></span>Did you mean:" +
							 " <Br /><img src='/images/icons/tag_blue.gif' style='vertical-align:middle'/>&nbsp;tag <a href='#' onClick='Windows.close(\"window_"+newWindowId+"\", event); createNewSearch(\""+searchTerms+"\", "+0+")'>" + searchTerms + "?</a>" +			
							 " <Br /><img src='/images/icons/user.gif' style='vertical-align:middle'/>&nbsp;user <a href='#' onClick='Windows.close(\"window_"+newWindowId+"\", event); createNewSearch(\""+searchTerms+"\", "+1+")'>" + searchTerms + "?</a></span>";							
			}
		}
		if(searchTerms == null) {
			searchTerms = document.ipiqitagsearchform.query.value;
		
		}

		win.setSearchId(newWindowId);
		win.setSortType(sort);
		win.setTags(searchTerms);

		win.setSearchType(type);
		
		win.setCloseCallback(deleteSearch)
		searchResultsScrollIndex[newWindowId] = listOfPosts.length;

		win.getContent().update(didYouMeanText + createHTMLPostList(listOfPosts, searchTerms, newWindowId,type));		
		win.setStatusBar('<a href="javascript:void(0);" id="scrollDownLink_'+newWindowId+'" onMouseDown="scrollDown(\''+searchTerms+'\', '+newWindowId+','+type+', '+searchResultsScrollIndex[newWindowId]+', '+sort+');"  class="scrollDownArrow"><img src="/images/downArrow.gif" /></a>');
		win.setDestroyOnClose();
		win.setConstraint(true, {left:245, right:0, top: 130, bottom: -100000})
		win.show();
		savePosition(win);
		
		// Event listener for IE/Opera etc
		Event.observe($('window_'+newWindowId), "mousewheel", function(event) {  handleSearchBoxScroll(event,searchTerms,newWindowId,type,sort); }, false);
	
		//Adding event listener for Mozilla
		Event.observe($('window_'+newWindowId), "DOMMouseScroll", function(event) {  handleSearchBoxScroll(event,searchTerms,newWindowId,type,sort); }, false); // Firefox

		// Event listeners for up and down arrow.  Create interval to allow for scrolling when held down
		Event.observe($('scrollDownLink_'+newWindowId), "mousedown", function(event) { scrollButtonInterval = setInterval('handleSearchBoxScrollButton(\''+searchTerms+'\', '+newWindowId+', '+type+', 0,'+sort+')',100) },false);
		Event.observe($('scrollDownLink_'+newWindowId), "mouseout", function(event) { if(scrollButtonInterval > 0){ clearInterval(scrollButtonInterval) }});
		Event.observe($('scrollDownLink_'+newWindowId), "mouseup", function(event) { if(scrollButtonInterval > 0){ clearInterval(scrollButtonInterval) }});
		Event.observe($('scrollUpLink_'+newWindowId), "mousedown", function(event) { scrollButtonInterval = setInterval('handleSearchBoxScrollButton(\''+searchTerms+'\', '+newWindowId+', '+type+', 1,'+sort+')',100) },false);
		Event.observe($('scrollUpLink_'+newWindowId), "mouseout", function(event) { if(scrollButtonInterval > 0){ clearInterval(scrollButtonInterval) }});
		Event.observe($('scrollUpLink_'+newWindowId), "mouseup", function(event) { if(scrollButtonInterval > 0){ clearInterval(scrollButtonInterval) }});		
				
		win.getId();

	}
	hideAutocomplete();
	
}


function replaceSearch(result,win) {

	var sort = win.sortType;
	var searchTerms = win.tags;
	var id = win.searchId;
	var type = 0;

	var searchResults = result.responseText.evalJSON(true);
	searchResultsScrollIndex[id] = 0;

	win.getContent().update(createHTMLPostList(searchResults.ListOfQualitySimplePosts, searchTerms,id,type));		
	win.setStatusBar('<a href="javascript:void(0);" id="scrollDownLink_'+id+'" onMouseDown="scrollDown(\''+searchTerms+'\', '+id+','+type+', '+searchResultsScrollIndex[id]+', '+sort+');"  class="scrollDownArrow"><img src="/images/downArrow.gif" /></a>');


	Event.stopObserving($('window_'+id));
	Event.stopObserving($('scrollDownLink_'+id));
	Event.stopObserving($('scrollUpLink_'+id));
	// Event listener for IE/Opera etc
	Event.observe($('window_'+id), "mousewheel", function(event) {  handleSearchBoxScroll(event,searchTerms,id,type,sort); }, false);

	//Adding event listener for Mozilla
	Event.observe($('window_'+id), "DOMMouseScroll", function(event) {  handleSearchBoxScroll(event,searchTerms,id,type,sort); }, false); // Firefox

	// Event listeners for up and down arrow.  Create interval to allow for scrolling when held down
	Event.observe($('scrollDownLink_'+id), "mousedown", function(event) { scrollButtonInterval = setInterval('handleSearchBoxScrollButton(\''+searchTerms+'\', '+id+', '+type+', 0,'+sort+')',100) },false);
	Event.observe($('scrollDownLink_'+id), "mouseout", function(event) { if(scrollButtonInterval > 0){ clearInterval(scrollButtonInterval) }});
	Event.observe($('scrollDownLink_'+id), "mouseup", function(event) { if(scrollButtonInterval > 0){ clearInterval(scrollButtonInterval) }});
	Event.observe($('scrollUpLink_'+id), "mousedown", function(event) { scrollButtonInterval = setInterval('handleSearchBoxScrollButton(\''+searchTerms+'\', '+id+', '+type+', 1,'+sort+')',100) },false);
	Event.observe($('scrollUpLink_'+id), "mouseout", function(event) { if(scrollButtonInterval > 0){ clearInterval(scrollButtonInterval) }});
	Event.observe($('scrollUpLink_'+id), "mouseup", function(event) { if(scrollButtonInterval > 0){ clearInterval(scrollButtonInterval) }});		
	
	
}

function tooltipColor(obj, i) {
	if(obj.style.backgroundColor == "rgb(243, 243, 255)") {
		obj.style.backgroundColor = "#"+searchResultsIntrosColors[i];
	} else {
		obj.style.backgroundColor = "#F3F3FF";
	}
}


/*
direction:  0=down, 1=up
*/

function handleSearchBoxScrollButton(searchTerms, id, type, direction, sort) {

	if(direction == 0) {
		scrollDown(searchTerms,id,type,searchResultsScrollIndex[id],sort);
	} else {
		scrollUp(searchTerms,id,type,searchResultsScrollIndex[id]);
	}
}

function handleSearchBoxScroll(e, searchTerms, id, type, sort) {
	if(Event.wheel(e) < 0) {
		scrollDown(searchTerms,id,type,searchResultsScrollIndex[id],sort);
	} else {
		scrollUp(searchTerms,id,type,searchResultsScrollIndex[id]);
	}
	
	if( !e ) e = window.event;

	if( e.preventDefault )
	e.preventDefault();
	else
	e.returnValue = false;
}

function appendToSearch(searchTerms,searchListObject,type,start,searchBoxId,sort) {

		// Prevent another ajax call from happening if we already know there are no more results!
		if(noMoreResults[searchBoxId]) {
			canScroll = true;
			return;			
		}

		if(type == 1) {			
			//<![CDATA[
			new Ajax.Request('/search/userShow/tags/'+searchTerms+'/start/'+start, {asynchronous:true, evalScripts:true, onComplete:function(request, json){appendToSearchWindow(request,searchTerms,searchListObject,type,searchBoxId)}});
			//]]>
		} else if(type == 2) {			
			//<![CDATA[
			new Ajax.Request('post/getRecentPosts/start/'+start, {asynchronous:true, evalScripts:true, onComplete:function(request, json){appendToSearchWindow(request,searchTerms,searchListObject,type,searchBoxId)}});
			//]]>
		} else if (type == 3) {
			//<![CDATA[
			new Ajax.Request('post/getRecentThreads/start/'+start, {asynchronous:true, evalScripts:true, onComplete:function(request, json){appendToSearchWindow(request,searchTerms,searchListObject,type,searchBoxId)}});
			//]]>			
		} else if (type == 4) {
			//<![CDATA[
			new Ajax.Request('/search/geotagShow/tags/'+searchTerms+'/start/'+start, {asynchronous:true, evalScripts:true, onComplete:function(request, json){appendToSearchWindow(request,searchTerms,searchListObject,type,searchBoxId)}});
			//]]>		
		} else {
			//<![CDATA[
			new Ajax.Request('/search/show/tags/'+searchTerms+'/start/'+start+'/sort/'+sort, {asynchronous:true, evalScripts:true, onComplete:function(request, json){appendToSearchWindow(request,searchTerms,searchListObject,type,searchBoxId)}});
			//]]>
		}
	
}

function appendToSearchWindow(request,searchTerms,searchListObject,type,searchBoxId) {
	var listOfPosts = request.responseText.evalJSON(true);
	var result = listOfPosts.ListOfQualitySimplePosts;
	appendToHTMLPostList(result, searchTerms, searchListObject,type,searchBoxId);	
	canScroll = true;
}

function savePosition(win){
	if(isLoggedIn) {
		element = win.element;
		new Ajax.Updater('', '/search/saveState', {asynchronous:true, evalScripts:false, parameters: 'id='+win.searchId+'&xpos='+parseInt(win.getLocation().left)+'&ypos='+parseInt(win.getLocation().top)})
	}
}

function updateDimensions(win) {
	if(isLoggedIn) {
		element = win.element;
		new Ajax.Updater('','/search/updateDimensions', {asynchronous: true, evalScripts:false, parameters: 'id='+win.searchId+'&height='+parseInt(win.getSize().height)+'&width='+parseInt(win.getSize().width)})
	}
}

function updateSort(win) {
	element = win.element;

	//<![CDATA[	
	new Ajax.Request('/search/updateSort', {asynchronous: true, evalScripts:false, parameters: 'id='+win.searchId+'&sort='+win.sortType+'&tags='+win.tags+'&type='+win.searchType, onComplete: function(request,json){replaceSearch(request,win)}});		
	//]]>
}

function removeFromMyThreads(element) {
	new Ajax.Updater('','/post/removeFromMyThreads',{asynchronous:true, evalScripts:false, parameters:'id='+element.getAttribute("threadId")});
	Effect.BlindUp('myThreadsList_'+element.getAttribute("threadId"));
	
}

function createRecentThreadsSearch() {
	new Ajax.Request('/search/recentThreadsCreate', {asynchronous:true, evalScripts:true, onComplete:function(request, json){
		var newSearch = request.responseText.evalJSON(true);
		var newSearchId = newSearch.answer.answerSearch.id;
		retrieveSearch('New Threads','New Threads',newSearchId,3); //Type 3 for recent Threads search
	}});		

	//$(elementName).style.display = "none";
}

function createRecentPostsSearch() {
	new Ajax.Request('/search/recentPostsCreate', {asynchronous:true, evalScripts:true, onComplete:function(request, json){
		var newSearch = request.responseText.evalJSON(true);
		var newSearchId = newSearch.answer.answerSearch.id;
		retrieveSearch('Latest Posts','Latest_Posts',newSearchId,2); //Type 2 for recent posts search
	}});
}


function deleteSearch(win) {
	new Ajax.Updater('', '/search/delete', {asynchronous:true, evalScripts:false, parameters: 'id='+win.searchId});
	Effect.Fade(win.element);
}

function maximizeSearch(title, tags, id, type) {
	retrieveSearch(title, tags, id, type);
	changeSearchState(id, 1,title,tags,type);
}

function changeSearchState(id,state,title,tags,type) {
	if(isLoggedIn) {
		new Ajax.Updater('', '/search/updateState', {asynchronous:true, evalScripts:false, parameters: 'id='+id+'&state='+state, onComplete:function(request, json){

					var searches = request.responseText.evalJSON(true);
					if(searches.searchesWithNewStuff == 0) {
						changeMinimizedBin('#EFEFEF');
					}
					refreshTheBin();
				}});
	} else {
		if(state == 2) {
			if($('minimized_error').style.display != 'none') {
				Effect.Fade('minimized_error');
			}
			var minimizedItem = new Element('li', { 'id': 'minimizedSearch_'+id, 'style': 'position:relative;display:none'});
			var minimizedItemLink = new Element('a',{'href': '#', 'id':'minimizedItemLink_'+id});
			minimizedItemLink.insert('<img src="/images/icons/'+searchTypeImages[0]+'.gif" />');
			minimizedItemLink.insert(tags);
			minimizedItem.insert(minimizedItemLink);
			minimizedItemLink.observe('click',function() {maximizeSearch(tags,tags,id,0);});
			Effect.Appear(minimizedItem);
			$('myMinimizedSearchesList').insert(minimizedItem);
		} else if(state == 1) {
			Effect.BlindUp('minimizedSearch_'+id);
		}
	}
}

function checkForMinimizedUpdates() {
			new Ajax.Request('home/myBin', {asynchronous:true, evalScripts:true, parameters: "call=0", onComplete:function(request){
				var searches = request.responseText.evalJSON(true);
				updateMinimizedBin(searches.minimized.ListOfSearches);
			}});	
}


	function showListOfSimplePosts(request,elementId, error) {
		var json = request.responseText.evalJSON(true);
		listOfSimplePosts = json.ListOfQualitySimplePosts;
		numResults = listOfSimplePosts.length;

		var searchResults = '<span id="closeBin"><a href="#" onClick="Effect.BlindUp(\''+elementId+'\')">X</a></span><ul>';

		//If there are no results then output message
		if(numResults == 0) {
			searchResults += '<li>' + error + '</li>';
		} else {

			for(i = 0; i < numResults; i++) {
				if(listOfSimplePosts[i].original_post_id == listOfSimplePosts[i].id) {
					var isOP = true;
				} else {
					var isOP = false;
				}

				if(isOP) {
					searchResults += '<li style="position: relative;" class="row'+(i%2)+'"><a href="/post/view/id/'+listOfSimplePosts[i].id+'/title/'+listOfSimplePosts[i].title.replace(/[ .%]/g,"_")+'" id="searchResult_'+listOfSimplePosts[i].newPost+'">'+listOfSimplePosts[i].title+'</a></li>';
					
				} else {
					searchResults += '<li style="position: relative;" class="row'+(i%2)+'"><a href=\"/post/view/id/'+listOfSimplePosts[i].original_post_id+'/title/'+listOfSimplePosts[i].title.replace(/[ .%]/g,"_")+'#SPP_'+listOfSimplePosts[i].id+'\" id=\"searchResult_'+listOfSimplePosts[i].newPost+'\">'+listOfSimplePosts[i].title+' (c)</a></li>';
					
				}

				searchResults += '';				
			}
			
		}
		$(elementId).innerHTML = searchResults;		
		
		
	}	

	function showListOfThreads(request,elementId, error) {		
		var json = request.responseText.evalJSON(true);
		listOfThreads = json.ListOfQualitySimplePosts;
		numResults = listOfThreads.length;
		//If there are no results then output message
		var threadResults = '<span id="closeBin"><a href="#" onClick="Effect.BlindUp(\''+elementId+'\')">X</a></span><ul id="myThreadsList">';


		if(numResults == 0) {
			threadResults += '<li> ' + error + '</li>';
		} else {
			//Limit the number of displayed results to CONST_RESULTS_DISPLAYED_NUM

			for(i = 0; i < numResults; i++) {

				threadResults += '<li id="myThreadsList_'+listOfThreads[i].id+'" class="row'+(i%2)+'" style="display:block;"><a href="javascript:void(0)" onClick="removeFromMyThreads(this)" threadId="'+listOfThreads[i].id+'"><img src="/images/icons/cross.gif" /></a><a href="/post/view/id/'+listOfThreads[i].id+'/title/'+listOfThreads[i].title.replace(/[ .%]/g,"_")+'" id="search'+listOfThreads[i].id+'">'+listOfThreads[i].title+'</a></li>';
			}
		}

		threadResults += '</ul>';
		$(elementId).innerHTML = threadResults;	
	}

function saveMyThreads(container) {
	//alert(container);
		//new Ajax.Updater('myThreadsList', '/post/updateMyThreads', {asynchronous:true, evalScripts:true})	
}
function changeMinimizedBin(color) {
//	$('minimizedBin').style.background = color;
}

function isNewPosts(listOfSearches) {

		for(i = 0; i < listOfSearches.length; i++) {
			if(listOfSearches[i].something_new > 0) {
				return true;
			}
		}
}

function updateMinimizedBin(listOfSearches) {

	if(isNewPosts(listOfSearches)) {
		changeMinimizedBin('#DFA745');
	} else {
		changeMinimizedBin('#EEEEEE');
	}
}

function hideTheBin() {
	if(!binHidden) {
		Effect.BlindUp('theBin'); 
		binHidden = true;
	}
}

	function showTheBin(request, elementId, error) {
		
		binHidden = false;
		
		var json = request.responseText.evalJSON(true);
		tags = json.tags;
		
		var searchResults = '<ul>';
		searchResults += '<li class="header">Minimized Searches</li><li><ul id="myMinimizedSearchesList">';
		if(json.minimized != undefined) {
		
			listOfSearches = json.minimized.ListOfSearches;
			numResults = listOfSearches.length;
			//If there are no results then output message

			var isSomethingNew = 0;


			if(numResults == 0) {
				searchResults += '<li id="minimized_error"> ' + error + '</li>';
			} else {
				//Limit the number of displayed results to CONST_RESULTS_DISPLAYED_NUM

				for(i = 0; i < numResults; i++) {

					if(listOfSearches[i].something_new > 0) {
						isSomethingNew = 1;
					} else {
						isSomethingNew = 0;
					}

					searchResults += '<li style="position: relative;" id="minimizedSearch_'+listOfSearches[i].id+'" class="row'+isSomethingNew+'"><a href="#" onClick="maximizeSearch(\''+listOfSearches[i].title+'\',\''+listOfSearches[i].modified_tags+'\', '+listOfSearches[i].id+','+listOfSearches[i].type+');" id="search'+listOfSearches[i].id+'"><img src="/images/icons/'+searchTypeImages[listOfSearches[i].type]+'.gif" />&nbsp;'+listOfSearches[i].title+'</a></li>';
					searchResults += '';
				}
			}
		} else {
			searchResults += '<li id="minimized_error"> ' + error + '</li>';
		}
		searchResults += '</ul></li>';
		
		if(json.watches != undefined) {
			searchResults += '<li class="header">Watched Threads<li><li><ul id="myThreadsList">';
			//Create List Of Favorite Threads
		
			listOfThreads = json.watches.ListOfQualitySimplePosts;
			numThreads = listOfThreads.length;
		
			if(numThreads == 0) {
				searchResults += '<li>You are not currently watching any threads. You can start watching a thread by clicking on the <img src="/images/icons/star.gif" /> on any thread.<li>';
			} else {
	
				for(i = 0; i < numThreads; i++) {
					searchResults += '<li id="myThreadsList_'+listOfThreads[i].id+'" class="row'+(i%2)+'" style="display:block;"><a href="javascript:void(0)" onClick="removeFromMyThreads(this)" threadId="'+listOfThreads[i].id+'"><img src="/images/icons/cross.gif" style="padding-right: 3px" /></a><a href="/post/view/id/'+listOfThreads[i].id+'/title/'+listOfThreads[i].title.replace(/[ .%]/g,"_")+'" id="search'+listOfThreads[i].id+'">'+listOfThreads[i].title+'</a></li>';
				}
			}

			searchResults += '</ul></li>';
		}
		
		searchResults += '<li class="header">Extras</li>';
		searchResults += '<li><a href="javascript:void(0)" onClick="createRecentPostsSearch()">Latest Posts</a></li>';
		searchResults += '<li><a href="javascript:void(0)" onClick="createRecentThreadsSearch()">New Threads</a></li>';
		searchResults += '<li class="header">Popular Topics</li>';
		searchResults += '<li>';
		searchResults += createTagCloud(tags,10);
		searchResults += '</li>';
		searchResults += '</ul>';		

		$(elementId).innerHTML = searchResults;	

		for(k = 0; k < tags.length; k++){
			var tagType = tags[k].type;

			$('tagCloud_'+tags[k].keyword.replace("'","_")).observe('mousedown',createNewSearchFromTagCloud.bindAsEventListener(tags[k]));
		}
		
		if(listOfSearches)
			updateMinimizedBin(listOfSearches);
					
	}
	
	function createNewSearchFromTagCloud(event) {
		createNewSearch(escape(this.keyword), this.type);
	}
	
	function refreshTheBin() {
		new Ajax.Request('/home/myBin', {asynchronous:true, evalScripts:true, onComplete:function(request, json){showTheBin(request, 'theBin', 'There are no minimized searches!');}}); 
	}

function createTagCloud(tags,sizes) {
	var max = 0;
	var min = 65535;
	var numSizes = sizes;
	var zones = Array();
	var tagCloud = "";
	
	tags.sort(sortTags); //use sortTags function as sorter because the array is of objects

	//Determine the min and max tag counts
	for(j = 0; j < tags.length; j++) {
		if(tags[j].count > max) max = tags[j].count;
		if(tags[j].count < min) min = tags[j].count;
	}

	//Find the number for count increments between min and max count to separate tags
	delta = (max - min)/numSizes;

	//Determine the exact count numbers for splitting up the tags into size zones
    for(x = 1; x <= numSizes; x++) {
            zones[x-1] = min + (x * delta);
    }

	//make sure the top zone isnt higher than the max count
    if (zones[numSizes - 1] > max)
		zones[numSizes - 1] = max;

	// for each tag, determine which zone it is in and set that equal to the size
	for(j = 0; j < tags.length; j++) {		

		size = 0;
		for(y = 0; y <= zones.length; y++) {
			if(tags[j].count >= zones[y])
				size = y;
		}
		if(j > 0) {
			tagCloud += ", "
		}
		tagCloud += "<a href='#' id='tagCloud_"+tags[j].keyword.replace("'","_")+"' style='text-decoration: underline; display:inline; font-size: "+(size+12)+"px;'>"+tags[j].keyword+"</a>";
	}
	
	return tagCloud;
	
}

function sortTags(a,b) {

	var result = a.keyword.toLowerCase() > b.keyword.toLowerCase();
	
	if(result) {
		return 1;
	} else {
		return -1;
	}
}

	function showListOfSearches(request,elementId, error) {
		var json = request.responseText.evalJSON(true);
		listOfSearches = json.ListOfSearches;
		numResults = listOfSearches.length;
		//If there are no results then output message
		var searchResults = '<span id="closeBin"><a href="#" onClick="Effect.BlindUp(\''+elementId+'\')">X</a></span><ul>';
		var isSomethingNew = 0;


		if(numResults == 0) {
			searchResults += '<li> ' + error + '</li>';
		} else {
			//Limit the number of displayed results to CONST_RESULTS_DISPLAYED_NUM

			for(i = 0; i < numResults; i++) {

				if(listOfSearches[i].something_new > 0) {
					isSomethingNew = 1;
				} else {
					isSomethingNew = 0;
				}

				searchResults += '<li style="position: relative;" id="minimizedSearch_'+listOfSearches[i].id+'" class="row'+isSomethingNew+'"><a href="#" onClick="maximizeSearch(\''+listOfSearches[i].title+'\',\''+listOfSearches[i].modified_tags+'\', '+listOfSearches[i].id+','+listOfSearches[i].type+')" id="search'+listOfSearches[i].id+'"><img src="/images/icons/page_white_stack.gif" />'+listOfSearches[i].title+'</a></li>';
				searchResults += '';
			}
		}

		searchResults += '</ul>';
		$(elementId).innerHTML = searchResults;		
		updateMinimizedBin(listOfSearches);
		
	}

	function retrieveSearch(title, searchTerms, id, type, start) {
		xPos = 150;
		yPos = 200;
		if(!start) {
			start = 0;
		}
		positionOffset = getPositionOffset(xPos,yPos,CONST_SEARCH_OFFSET,CONST_SEARCH_OFFSET);
		xPos += positionOffset;
		yPos += positionOffset;
		searchPositions += xPos+','+yPos+';';		

		if(type == 1) {			
			//<![CDATA[
			new Ajax.Request('/search/userShow/tags/'+searchTerms, {asynchronous:true, evalScripts:true, onComplete:function(request, json){renderSearch(request,title,searchTerms,id,xPos,yPos,300,300,type)}});
			//]]>
		} else if(type == 2) {			
			//<![CDATA[
			new Ajax.Request('post/getRecentPosts', {asynchronous:true, evalScripts:true, onComplete:function(request, json){renderSearch(request,title,searchTerms,id,xPos,yPos,300,300,type)}});
			//]]>
		} else if (type == 3) {
			//<![CDATA[
			new Ajax.Request('post/getRecentThreads', {asynchronous:true, evalScripts:true, onComplete:function(request, json){renderSearch(request,title,searchTerms,id,xPos,yPos,300,300,type)}});
			//]]>			
		} else if (type == 4) {
			//<![CDATA[
			new Ajax.Request('/search/geotagShow/tags/'+searchTerms, {asynchronous:true, evalScripts:true, onComplete:function(request, json){renderSearch(request,title,searchTerms,id,xPos,yPos,300,300,type)}});
			//]]>				
		} else {
			
			//<![CDATA[
			new Ajax.Request('/search/show/tags/'+searchTerms+'/start/'+start, {asynchronous:true, evalScripts:true, onComplete:function(request, json){renderSearch(request,title,searchTerms,id,xPos,yPos,300,300,type)}});
			//]]>
		}
	}


function iterrateSearches(json) {
	var listOfSearches = eval('(' + json + ')');
	numSearches = listOfSearches["ListOfSearches"].length;
	var parentObject = this;
	var searchIndex;
	var i;
	for(i = 0; i < numSearches; i++) {
		searchIndex = i;
		//<![CDATA[
		new Ajax.Request('/search/show/id/'+listOfSearches["ListOfSearches"][i].id, {asynchronous:true, evalScripts:true, onComplete:function(request,i){displaySearch(request,listOfSearches["ListOfSearches"][i].title)}})
		//]]>

	}

	
}

function displayWelcomeWindow()
{	
	var win = new Window({className: "dialog", width:"500", height:"500", zIndex: topZIndex, resizable: false, maximizable: false, minimizable: false, searchType: 3, title: "Welcome to Ipiqi", showEffect:Effect.Appear, hideEffect: Effect.Fade, draggable:true, wiredDrag: false, destroyOnClose: true, onClose: updateFirstTime, gridX: 5, gridY: 5, minWidth: 200});
		win.setConstraint(true, {left:245, right:0, top: 130, bottom: -100000})

	
	topZIndex += 100;
	
	win.setLocation(130,560);
	win.setSearchType(3);
	
	
	win.getContent().update("<div style='color: black; text-align:center; pading: 3px;'><br /><span style='font-size: 12px; padding: 5px;'>ipiqi is a new type of forum where nothing is off topic.<br /><br />Are you new to ipiqi? It's free and easy to use. <a href='/signup' style='text-decoration:underline'>Create an account now</a> and:<br /><ul style='list-style:disc outside none;text-align:left; margin: auto; width: 300px; padding: 10px;'><li>Keep a personalized dashboard of your favorite topics.</li><li>Start new discussions and interact with others.</li><li>Get recognition and reputation for being an expert on what you know.</li><li>Find out when someone replies to your post.</li><li>Piq what you like!</li></ul>To get started, watch the video and check out our <a href='/help' style='font-weight:bold; text-decoration: underline'>Help Section</a>.</span><br /><br /><object width='400' height='300'><param name='allowfullscreen' value='true' /><param name='allowscriptaccess' value='always' /><param name='movie' value='http://vimeo.com/moogaloop.swf?clip_id=3062959&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=&amp;fullscreen=1' /><embed src='http://vimeo.com/moogaloop.swf?clip_id=3062959&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=&amp;fullscreen=1' type='application/x-shockwave-flash' allowfullscreen='true' allowscriptaccess='always' width='400' height='300'></embed></object></div>");

	win.show();
	
}

function updateFirstTime() {
		new Ajax.Updater('', '/user/updateFirstTimeUser', {asynchronous:true, evalScripts:false})
}


function rgb2hex(red, green, blue)
{
    var decColor = blue + 256 * green + 65536 * red;
    return decColor.toString(16);
}

function hideAutocomplete() {
	$('query_auto_complete').hide();
}


// This extends the object model so we can use prototype to catch the mouse scroll wheel events

	Object.extend(Event, {
		wheel:function (event){
			var delta = 0;
			if (!event) event = window.event;
			if (event.wheelDelta) {
				delta = event.wheelDelta / Math.abs(event.wheelDelta)
				if (window.opera) delta = -delta;
			} else if (event.detail) { delta = -event.detail/3;	}
			return Math.round(delta); //Safari Round
		}
	});




function whichElement(e)
{
var targ;
if (!e)
  {
  var e=window.event;
  }
if (e.target)
  {
  targ=e.target;
  }
else if (e.srcElement)
  {
  targ=e.srcElement;
  }
if (targ.nodeType==3) // defeat Safari bug
  {
  targ = targ.parentNode;
  }
  return targ;
}
