//
// string helpers
//
String.prototype.startsWith = function(str) {
	return (this.match("^" + str) == str);
}

String.prototype.stripTags = function() {
  return this.replace(/<\/?[^>]+>/gi, '');
}

String.prototype.truncate = function(n) {
	if (this.length > n)
		return this.substr(0, n - 3) + '...';
	return String(this);
}

// +   original by: Philip Peterson
// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
String.prototype.urlDecode = function() {
  ret = this.replace(/\+/g, '%20');
  ret = decodeURIComponent(ret);
  ret = ret.toString();
  return ret;
}

String.prototype.hostFromURL = function() {
	var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
	return this.match(re)[1].toString();
}

//
// ant search engine code
//

// helpers

ant.se.helper = {};

ant.se.helper.displayResults = function(results)
{
	var resultsObj = $('#results');

	$('#se_loader').remove();
  resultsObj.empty();
  for (var i = 0; i < results.length; ++i) {
		ant.se.helper.displayResultOneResult(resultsObj, results[i]);
  }
}

ant.se.helper.displayResultOneResult = function(resultsObj, result)
{
	resultsObj.append($('<li />')
		.hover(
			function() { $(this).addClass('hover');	},
			function() { $(this).removeClass('hover'); })
		.append($('<a />')
			.addClass('img')
			.attr('href', result.url)
  		.append($('<img />')
  			.attr('alt', result.titleNoFormatting)
  			.attr('src', 'http://open.thumbshots.org/image.pxf?url=' + result.url)))
		.append($('<p />')
			.addClass('title')
    	.append($('<a />')
  			.attr('href', result.url)
    		.addClass('title')
    		.html(result.title)))
   	.append($('<p />')
  		.addClass('desc')
  		.html(result.content.stripTags().truncate(170)))
		.append($('<p />')
	  	.append($('<span />')
 	 			.addClass('url')
				.html(result.unescapedUrl.substr(7).truncate(50)))
			.append($('<span />')
				.addClass('action')
				.append(' - ')
				.append($('<strong />')
					.append($('<small />')
  					.append($('<a />')
						.attr('href', '/site/' + result.url.hostFromURL())
  					.text('traffic details'))))
			)
		)
	);
}

ant.se.helper.searchInfo = function(curPageIndex, maxPageIndex, nResults) {
	var textInfo = 'No result for';
    
	if (curPageIndex != null) {
		textInfo = 'Results ' + (curPageIndex * 8 + 1)
	    + ' - ' + (curPageIndex * 8 + nResults)
	    + ' / ' + ((maxPageIndex + 1) * 8)
	    + ' for';
  }
  $('#searchInfo').text(textInfo);
}

ant.se.helper.displayPageButton = function(pageObj, pageIndex,
																		 	     text, title, className) {
	var	liObj = $('<li />');
	var aObj = $('<a />');

	aObj.attr('title', title);
	aObj.attr('href', '#');
	aObj.click(function() {
		ant.se.controller.self.gotoPage(pageIndex);
	});

	aObj.text(text);
	if (className != null) {
		aObj.addClass(className);
	}
	liObj.append(aObj);
	pageObj.append(liObj);
}

ant.se.helper.pagination = function(curPageIndex) {
	var pageListBegin = 0;
	var pageObj = $('#pages');
	var maxPageIndex = ant.se.controller.self.getMaxPageIndex();

	pageObj.empty();
	if (curPageIndex > 2
		&& curPageIndex < (maxPageIndex - 2)) {
		pageListBegin = curPageIndex - 2;
	} else if (curPageIndex >= (maxPageIndex - 2)) {
		pageListBegin = maxPageIndex - 4;
	}
	if (pageListBegin < 0) {
		pageListBegin = 0;
	}
 	if (pageListBegin > 0) {
		ant.se.helper.displayPageButton(pageObj, 0, '1 <<',
			'first page', 'first');
	}
	if (curPageIndex > 0) {
		ant.se.helper.displayPageButton(pageObj, (curPageIndex - 1),
			'<', 'previous page', 'prev');
	}
	for (var i = pageListBegin; i < pageListBegin + 5 && i <= maxPageIndex; ++i) {
		ant.se.helper.displayPageButton(pageObj, i, (i + 1),
			'page ' + (i + 1), (i == curPageIndex ? 'active' : null));
	}
	if (curPageIndex < maxPageIndex) {
		ant.se.helper.displayPageButton(pageObj, (curPageIndex + 1),
			'>', 'next page', 'next');
	}
	if (pageListBegin < (maxPageIndex - 4)) {
		ant.se.helper.displayPageButton(pageObj, maxPageIndex,
			(maxPageIndex + 1) + ' >>', 'last page', 'last');
	}
}

// controller

ant.se.controller = function() {
	ant.se.controller.TYPE_WEB		= 0;
	ant.se.controller.TYPE_INTRA	= 1;
	ant.se.controller.TYPE_ADS		= 2;

	this.maxPageIndex = null;
	this.getRequest();
	ant.social.sideads(this.query, this.page);
	$('#se_container').css('visibility', 'visible');

	if (this.type == ant.se.controller.TYPE_ADS) {
		if (this.page == null) {
			this.adsGotoPage(this.page);
		} else {
			this.adsGotoPage(this.page - 1);
		}
	} else {
	  this.searcher = new google.search.WebSearch();

	  if (this.type == ant.se.controller.TYPE_INTRA) {
			this.searcher.setSiteRestriction('ant.com');
  	}
  	this.searcher.setNoHtmlGeneration();
  	this.searcher.setResultSetSize(google.search.Search.LARGE_RESULTSET);
  	this.searcher.setSearchCompleteCallback(this,
																					ant.se.controller.prototype.gSearchComplete);
		this.searcher.execute(this.query);
	}
}

// controller loader
ant.se.controller.load = function() {
	ant.se.controller.self = new ant.se.controller();
}

ant.se.controller.prototype.getMaxPageIndex = function() {
	if (this.type == ant.se.controller.TYPE_ADS) {
		return 3;
	}
	if (this.searcher.cursor == null) {
		return null;
	}
	if (this.maxPageIndex == null) {
		var maxPageIndex = Math.floor(this.searcher.cursor.estimatedResultCount / 8) - 1;

		// google provides only 8 pages of results max;
		if (maxPageIndex > 7) {
			maxPageIndex = 7;
		}
		this.maxPageIndex = maxPageIndex;
		return maxPageIndex;
	}
	return this.maxPageIndex;
}

ant.se.controller.prototype.getRequest = function() {
	this.type = ant.se.controller.TYPE_WEB;
  this.page = null;

	// 7 for http:// length, 1 for /
	var path = document.location.href.substr(document.location.host.length + 8);
	splittedPath = path.split(/\/+/, 3);
	if (splittedPath[0] == 'intra') {
		this.type = ant.se.controller.TYPE_INTRA;
	} else if (splittedPath[0] == 'ads') {
		this.type = ant.se.controller.TYPE_ADS;
	}
	if (typeof splittedPath[2] == 'string') {
		this.page = parseInt(splittedPath[2]);
		if (isNaN(this.page) || this.page < 2) {
			this.page = null; // means page 1
		}
	}
	this.query = splittedPath[1].urlDecode();
}

ant.se.controller.prototype.gotoPage = function(pageIndex)
{
	ant.social.sideads(this.query, pageIndex + 1)
	if (this.type == ant.se.controller.TYPE_ADS) {
		this.adsGotoPage(pageIndex);
	} else {
		this.searcher.gotoPage(pageIndex);
	}
}

ant.se.controller.prototype.adsGotoPage = function(pageIndex) {
	var	maxPageIndex = this.getMaxPageIndex();

	if (pageIndex == null) {
		pageIndex = 0;
	} else if (pageIndex > maxPageIndex) {
		pageIndex = maxPageIndex
	}
	$.get("/ads/full/" + escape(this.query) + "/8/" + (pageIndex + 1),
		function(data, textStatus) {
			$('#se_loader').remove();
			ant.se.helper.searchInfo(pageIndex, maxPageIndex, 8);
			$('#results').html(data);
			ant.se.helper.pagination(pageIndex);
		}
	);
}

ant.se.controller.prototype.gSearchComplete = function() {
	var maxPageIndex = this.getMaxPageIndex();

	if (this.page != null) {
		// google page starts at 0;
		var pageIndex = this.page - 1;
		console.debug('pageIndex: ' + pageIndex);

		if (pageIndex > maxPageIndex) {
			pageIndex = maxPageIndex;
		}
		this.searcher.gotoPage(pageIndex);
		this.page = null;
		return ;
	}
	this.page = null;
	if (this.searcher.cursor == null) {
	  ant.se.helper.searchInfo(null, null, null);
	} else {
	  ant.se.helper.searchInfo(this.searcher.cursor.currentPageIndex,
				maxPageIndex, this.searcher.results.length);
	}
  if (this.searcher.results && this.searcher.results.length > 0) {
		ant.se.helper.displayResults(this.searcher.results);
		ant.se.helper.pagination(this.searcher.cursor.currentPageIndex);
  } else {
		$('#results').empty();
	}
}

if (typeof google.search.Search != 'undefined') {
  google.search.Search.setOnLoadCallback(ant.se.controller.load);
}
