/**
 * masher.js
 * Author: Younes Bouab
 * eMail: YBinSF@yahoo.com
 * Version: Beta 0.7
 * Date:  02/06/2011 06:37 PM
 * 
 */
var loadingImg = "<br><img src=\"resources/images/loading.gif\" width=\"32\" height=\"32\">";
var numServiceProviders = 4;
var services = new Array ("web", "news", "images", "video");
var numServices = services.length;
var menuServices = new Array ("web", "news", "images", "video", "all", "custom");
var numMenuServices = menuServices.length;
var customMenuIndex = 5;
var allServicesIndex=4;
var prevQuery = "";
var maxSuggestionsOptions=5;
var ajaxCallInterval = 1100;
var timer = null;
var SCREEN_WIDTH=0;
var SCREEN_HEIGTH=0;
var SCREEN_FACTOR=1.5;
var isIphone = false;
var queryLabelValue = "";
if(typeof String.prototype.trim !== 'function') {
	String.prototype.trim = function() {
	    return this.replace(/^\s+|\s+$/g, ''); 
	}
}
function init(isIphone, queryLabelValue)
{
	this.isIphone=isIphone;
	this.queryLabelValue = queryLabelValue.toLowerCase();
	var queryObj = document.searchForm.query;
	document.searchForm.searchProvider.value="all";
	document.searchForm.service.value="web";
	setService(0);
	//queryObj.focus();
	document.onmousedown = dragPopupLayer;
	document.onmouseup = checkClick;
	document.onkeypress = checkKeys;
	var queryObj = document.searchForm.query;
	queryObj.focused=false;
	queryObj.hasFocus = function() {
	return this.focused;
	};
	queryObj.onfocus=function() {
	this.focused=true;
	};
	queryObj.onblur=function() {
	this.focused=false;
	};
	setScreenSize();
}
function cleanQuery() {
   var queryObj = document.searchForm.query;
   var queryValue = queryObj.value.toLowerCase(); 
   if(queryValue==queryLabelValue)
   {
     queryObj.value="";
     queryObj.style.color="#000000";
   }
}
function runQuery() {
	var currQuery = specialTrim(document.searchForm.query.value);
	if (currQuery.length > 0) {
		if (currQuery != this.prevQuery) {
			runIt();
		}
	} else {
		document.getElementById("searchResultDiv").innerHTML = "";
	}
	this.prevQuery = currQuery;
}
function setService(menuIndex)
{
	selectServiceMenu(menuIndex);
	if(menuIndex!=5)
	{
		hide("customMenuDiv");
		show("customServicesMenuDiv");
		setCustomSearchProvidersMenu(true);
		setCustomServicesMenu(false);
		checkCustomService(menuIndex);
		//if(menuIndex==4)
		document.searchForm.searchProvider.value="all";
		document.searchForm.service.value=menuServices[menuIndex];
		runIt();
	}
	else
	{
		if(isHidden("customMenuDiv"))
		show("customMenuDiv");
		else
		hide("customMenuDiv");
	}
}
function selectServiceMenu(menuIndex) {
	for(var i=0;i<numMenuServices;i++)
	{
		eval("document.getElementById('menu_"+i+"').style.border=\"1px solid #eeeeee\"");
	}
	eval("document.getElementById('menu_"+menuIndex+"').style.border=\"1px solid #0000ff\"");
}
function oMOverServiceMenu(menuIndex) {
	if(eval("document.getElementById('menu_"+menuIndex+"').style.border")!="1px solid rgb(0, 0, 255)")
	eval("document.getElementById('menu_"+menuIndex+"').style.border=\"1px solid #cccccc\"");
}
function oMOutServiceMenu(menuIndex) {
	if(eval("document.getElementById('menu_"+menuIndex+"').style.border")!="1px solid rgb(0, 0, 255)")
	eval("document.getElementById('menu_"+menuIndex+"').style.border=\"1px solid #eeeeee\"");
}
function setCurrentService(menu) {
	if(isEmpty(menu) || menu=="null")
	{
	   document.searchForm.advanced_service_0.checked=true;
	}
	else if(menu=="all")
	{
		for(var i=0;i<services.length;i++)
		{
	      eval("document.searchForm.advanced_service_"+i+".checked=true;");
		}
	}
	else
	{
		for(var i=0;i<services.length;i++)
		{
			if(menu.indexOf(services[i])!=-1)
			eval("document.searchForm.advanced_service_"+i+".checked=true;");
		}
	}
}

function setCustomSearchProviders(a){
	if(!atLeastCustomSearchProvidersChecked())
	{
	  a.checked=true;
	  return true;
	}
	if(onlyCustomServiceIndexChecked(3))
	hide("customServicesMenuDiv");
	else
	show("customServicesMenuDiv");	
	var searchProviders = "";
	for(var i=0;i<this.numServiceProviders;i++)
	{
		var obj = eval("document.searchForm.advanced_sp_"+i);
		if(obj.checked)
		{
		  if(searchProviders.length>0)
		  searchProviders+=",";
		  searchProviders+=obj.value;
		}
	}
	document.searchForm.searchProvider.value=searchProviders;
}
function getCustomServiceIndex(){
	var index=-1;
	for(var i=0;i<this.numServices;i++)
	{
		var obj = eval("document.searchForm.advanced_service_"+i);
		if(obj.checked)
		{
			if(index==-1)
			index=i;
			else
			{
				index=-1;
				break;
			}
		}
	}
	return index;
}
function setCustomServices(a){
	if(!atLeastCustomServicesChecked())
	{
	  a.checked=true;
	  return true;
	}
	var services = "";
	var menuIndex = 0;
	for(var i=0;i<this.numServices;i++)
	{
		obj = eval("document.searchForm.advanced_service_"+i);
		if(obj.checked)
		{
		  if(services.length>0)
		  services+=",";
		  services+=obj.value;
		  menuIndex=i;
		}
	}
	document.searchForm.service.value=services;
}
function setCustomSearchProvidersMenu(flag)
{
	for(var i=0;i<this.numServiceProviders;i++)
	{
		var obj = eval("document.searchForm.advanced_sp_"+i);
		obj.checked = flag;
	}	
}
function atLeastCustomSearchProvidersChecked()
{
	for(var i=0;i<this.numServiceProviders;i++)
	{
		var obj = eval("document.searchForm.advanced_sp_"+i);
		if(obj.checked)
		return true;
	}	
	return false;
}
function atLeastCustomSearchProvidersChecked()
{
	for(var i=0;i<this.numServiceProviders;i++)
	{
		var obj = eval("document.searchForm.advanced_sp_"+i);
		if(obj.checked)
		return true;
	}	
	return false;
}
function setCustomServicesMenu(flag)
{
	for(var i=0;i<this.numServices;i++)
	{
		var obj = eval("document.searchForm.advanced_service_"+i);
		obj.checked = flag;
	}	
}
function atLeastCustomServicesChecked()
{
	for(var i=0;i<this.numServices;i++)
	{
		obj = eval("document.searchForm.advanced_service_"+i);
		if(obj.checked)
		return true;		
	}
	return false;
}
function onlyCustomServiceIndexChecked(index)
{
	var obj = eval("document.searchForm.advanced_sp_"+index);
	if(!obj.checked)
	return false;
	for(var i=0;i<this.numServices;i++)
	{
		if(i!=index)
		{
			obj = eval("document.searchForm.advanced_sp_"+i);
			if(obj.checked)
			return false;
		}
	}
	return true;
}
function checkCustomService(serviceId)
{
	if(serviceId!=this.allServicesIndex)
	{
		obj = eval("document.searchForm.advanced_service_"+serviceId);
		obj.checked = true;
	}
	else
	{
		setCustomSearchProvidersMenu(true);
		setCustomServicesMenu(true);
	}
}
function applyCustomSettings()
{
	runIt();
	if(document.searchForm.service.value.indexOf(",")==-1)
	{
		var menuIndex = getCustomServiceIndex();
		if(menuIndex!=-1)
		selectServiceMenu(menuIndex);
	}
	else
	selectServiceMenu(this.customMenuIndex);
	hide("customMenuDiv");
}
function cancelCustomSettings() {
  runIt();
  hide('customMenuDiv');
}
function hide(id) {
	var obj = document.getElementById(id);
	obj.style.display="none";
}
function show(id) {
	var obj = document.getElementById(id);
	obj.style.display="inline";
}
function isHidden(id) {
	return eval("document.getElementById('"+id+"').style.display!='inline'");
}
function runIt() {
	var currQuery = specialTrim(document.searchForm.query.value).toLowerCase();//Store all queries as lower case
	if(!isEmpty(currQuery) && currQuery!=queryLabelValue)
	{
		var currSearchProvider = document.searchForm.searchProvider.value;
		var currService = document.searchForm.service.value;
		var currSize = document.searchForm.size.value;
		var currStart = document.searchForm.start.value;
		document.getElementById("searchResultDiv").innerHTML = loadingImg;
		ajax("search.action?searchProvider="+escape(currSearchProvider)+"&service="+escape(currService)+"&query="+escape(currQuery)+"&start="+currStart+"&size="+currSize,
			"searchResultDiv");
		if(isIphone)	
		document.searchForm.searchButton.focus();
		else
		document.searchForm.query.focus();
	}
}
function nextPrevious(url, div) {
	document.getElementById("searchResultDiv").innerHTML = loadingImg;
	ajax(url, div);
}
function ajax(url, div) {
	if (timer != null)
		clearTimeout(timer);
	timer = setTimeout("callAjaxGet('" + url + "', '" + div + "')",
			ajaxCallInterval);
}
function checkKeys(e) {
	var keyCode;
	if (window.event) {
		keyCode = window.event.keyCode;
	} else if (e) {
		keyCode = e.which;
	} else {
		return true;
	}
	if (keyCode == 13 || keyCode == 10) {
		runIt();
	} else {
		return true;
	}
}
function checkClick(e)
{
	dragPopupLayerMoveFlag=false;
	var clickCode;
	if (window.event) {
		clickCode = window.event.keyCode;
	} else if (e) {
		clickCode = e.which;
	} else {
		return true;
	}
	if (!isHidden("suggestionsDiv") && (clickCode == 0 || clickCode == 1)) {
		hide("suggestionsDiv");
	}
}
function isEmpty(a) {
	if (a == null || a == "")
		return true;
	else
		return false;
}
function showImg(i,url,t,d)
{
	var obj = document.getElementById("resultImageVideoDiv_"+i);
	obj.innerHTML = "<img src="+url+"><br>"+t+"<br>"+d;
}
function displaySuggestions()
{
   var queryObj=document.searchForm.query;
   var queryValue = queryObj.value.toLowerCase();
   var query = specialTrim(queryValue);
   if(isEmpty(query))
   hide("suggestionsDiv");
   else
   {
     callAjaxGetReturnFunction("autoComplete.action?query="+query,"setSuggestionsSelectContent");
   }
}
function setSuggestionsSelectContent(result)
{
	hide("suggestionsDiv");
	var list = document.searchForm.suggestionsSelect;
	ClearOptions(list);
	list.size=maxSuggestionsOptions;
	var countries = eval("(" + result + ")");
	if(countries.Options.length)
	{
		var counter=0;
		for(i=0;i<countries.Options.length;i++)
		{
			if(counter==maxSuggestionsOptions)
			break;
			else if (countries.Options[i].value.toLowerCase()!=specialTrim(document.searchForm.query.value.toLowerCase()))
			{
				AddToOptionList(list, countries.Options[i].value, countries.Options[i].text);
				counter++;
			}
		}
		if(list.length>0)
		show("suggestionsDiv");
	}
}
function ClearOptions(list)
{
	for (x = list.length; x >= 0; x = x - 1) {
	list[x] = null;
	}
}
function AddToOptionList(list, value, text)
{
	list[list.length] = new Option(text, value);
}
function setQueryValue()
{
	document.searchForm.query.value=document.searchForm.suggestionsSelect.options[document.searchForm.suggestionsSelect.selectedIndex].text;
	runQuery();
	hide('suggestionsDiv');
}
function changeSuggestionBackColor(f,e)
{
	var index=0;
	var value=(!e.target?event.srcElement.value:e.target.value);
	for(var i=0;i<document.searchForm.suggestionsSelect.length;i++)
	{
		if(value==document.searchForm.suggestionsSelect.options[i].value)
		index=i;
	}
	if(f)
	document.searchForm.suggestionsSelect.options[index].style.background="#ccc";
	else
	document.searchForm.suggestionsSelect.options[index].style.background="#ffffff";
}
function specialTrim(stringValue)
{
	var lString = stringValue.trim();
	var newString="";
	var previousChar="";
	var currentChar="";
	for(var i=0;i<lString.length;i++)
	{
		currentChar=lString.charAt(i);
		if(currentChar!=" " || currentChar!=previousChar)
		newString+=currentChar;
		previousChar=currentChar;
	}
	return newString;
}
var dragPopupLayerMoveOffsetx = 0;
var dragPopupLayerMoveOffsety = 0;
var dragPopupLayerMoveNowx = 0;
var dragPopupLayerMoveNowy =0;
function dragPopupLayer(e){
  	var layer = null;
	if (window.event) {
		var element = event.srcElement;
		layer = element.parentElement;
		dragPopupLayerMoveOffsetx = event.clientX;
		dragPopupLayerMoveOffsety = event.clientY;

	} else if (e) {
		var element =  e.target;
		layer = element.parentNode;
		dragPopupLayerMoveOffsetx = e.clientX; 
		dragPopupLayerMoveOffsety = e.clientY;
	} else {
		return true;
	}
	if (layer!=null && layer.id=="dragPopupDiv"){
		dragPopupLayerMoveNowx = parseInt(layer.style.left);
		dragPopupLayerMoveNowy = parseInt(layer.style.top);
		dragPopupLayerMoveFlag=true;
		document.onmousemove=dragPopupLayerMove;
	}
}
function dragPopupLayerMove(e){
	if (!dragPopupLayerMoveFlag)
	return true;

	var obj = document.getElementById("dragPopupDiv");
	if (window.event) {
		obj.style.left=(dragPopupLayerMoveNowx+event.clientX-dragPopupLayerMoveOffsetx)+"px";
		obj.style.top=(dragPopupLayerMoveNowy+event.clientY-dragPopupLayerMoveOffsety)+"px";
	} else if (e) {
		obj.style.left=(dragPopupLayerMoveNowx+e.clientX-dragPopupLayerMoveOffsetx)+"px";
		obj.style.top=(dragPopupLayerMoveNowy+e.clientY-dragPopupLayerMoveOffsety)+"px";
	}
	return false;
}
function setScreenSize() {
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  } else if( document.documentElement && document.documentElement.clientWidth) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } else if( document.body && document.body.clientWidth) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
	  SCREEN_WIDTH=myWidth;
	  SCREEN_HEIGHT=myHeight;
}
function setDragPopupLayerContent(i,ty,u,cu,w,h,ti,d)
{
	var title=ti;
	if(title=="null")
	title="";
	var desc=d;
	if(desc=="null")
	desc="";
	else
	desc="<br>"+desc;
	var wh=getThumbWidth(w,h);
	var array = wh.split(",");
	var imgWidth=array[0];
	var imgHeight=array[1];
	var obj;
	if(ty=='image')
	{
		obj=document.getElementById("dragPopupDiv");
		var img = new Image();img.src=u;
		document.getElementById("dragPopupDivTitleBar").innerHTML="<a href=\""+u+"\" target=\"imageResult_"+i+"\"><img src=\"resources/images/max.png\" border=\"0\"></a>&nbsp;<a href=\"#\" onClick=\"closeDragPopupLayerContent();\"><img src=\"resources/images/close.png\" border=\"0\"></a>&nbsp;";
		document.getElementById("dragPopupDivContent").innerHTML="<a href=\""+u+"\" target=\"imageResult_"+i+"\"><img src=\""+u+"\" width=\""+imgWidth+"\" height=\""+imgHeight+"\" class=\"dragPopupDivContentImg\" title=\"Click to open in a new window!\"></a>";
		document.getElementById("dragPopupDivDescription").innerHTML=title+desc;
	}
	obj.style.width=imgWidth+"px";
	obj.style.left=((SCREEN_WIDTH/2)-imgWidth/2)+"px";
	obj.style.top=((SCREEN_HEIGHT/2)-imgHeight/2)+"px";
	show("dragPopupDiv");
}
function closeDragPopupLayerContent()
{
	hide("dragPopupDiv");
	document.getElementById("dragPopupDivContent").innerHTML="";
	document.getElementById("dragPopupDivDescription").innerHTML="";
}
function getThumbWidth(imgWidth, imgHeight) {
	var thisImgWidth = imgWidth;
	var thisImgHeight = imgHeight;
	if(thisImgWidth>SCREEN_WIDTH/SCREEN_FACTOR)
	{
		var factor = (SCREEN_WIDTH/SCREEN_FACTOR)/thisImgWidth;
		thisImgWidth=SCREEN_WIDTH/SCREEN_FACTOR;
		thisImgHeight=thisImgHeight*factor;
	}
	if(thisImgHeight>SCREEN_HEIGHT/SCREEN_FACTOR)
	{
		var factor = (SCREEN_HEIGHT/SCREEN_FACTOR)/thisImgHeight;
		thisImgHeight=SCREEN_HEIGHT/SCREEN_FACTOR;
		thisImgWidth=thisImgWidth*factor;
	}
	return thisImgWidth+","+thisImgHeight;
}
function getYear()
{
	var now = new Date;
	var year=parseInt(now.getYear());
	if(year < 1900)
	year=year+1900;
	return year;
}
function getPage(url)
{
	if(url=="about")
	callAjaxGet("about.jsp", "contentDiv");
}
function oMOverResultBorder(obj)
{
	if(obj.id.indexOf('_R0')!=-1)
	obj.style.border='1px solid #999999';
	else
	obj.style.border='1px solid #999999';
}
function oMOutResultBorder(obj)
{
	if(obj.id.indexOf('_R0')!=-1)
	obj.style.border='1px solid #eeeeee';
	else
	obj.style.border='1px solid #ffffff';
}
function hideURLbar(){
window.scrollTo(0,1);
}

