// Configuration
var CSE_ID = "007498188896825459573:uo9cpacir0e";

// Switch from normal to advanced search and back
function advancedSearchVisibility() {
	if (document.getElementById('advanced_search').style.visibility == "hidden") {
		document.getElementById('advanced_search').style.visibility = "visible";
	} else {
		document.getElementById('advanced_search').style.visibility = "hidden";
	}
	return false;
}

// Return the url without the query string
function uri (url) {
   var split_url = url.split('?');
   return split_url[0];
 }

 function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

 // Does actual search
function doSearch(labelid2label)
{
	var q = document.getElementById('searchbox_'+CSE_ID).q.value;
	var origq = q;
	var siteid = document.getElementById('searchbox_'+CSE_ID).site.value;
	var site = "";
	var url = "";
	var label = "";
	
	// Alert and stop search if query string is empty
	if (trim(q)=="") {
		alert("Please enter search term")
		return false
	}
/*
	// If mylist was selected, create list of "site:"
	if (siteid == "1") {
		// Read mylist cookie
		 var val = getCookieValue("mylist");
		 // If cookie exist, concatenate list of domains
		 if (val) {
			 arr = val.split(",");
			 first = true;
			 for (x in arr) {
				 if (!first) site += " OR ";
				 site += "site:" + siteid2domain[arr[x]];
				 first = false;
			 }
		 }
		 // If cookie doesn't exist alert
		 else {
			 alert("Favorite recipe sites not defined");
			 return false;
		 }
	}
*/	
	// If label was selected (but not 0 - all sites, 1 - favorite sites, or 2 - separation line)
	if (siteid != "0" && siteid != "1" && siteid != "2") {
		label = "more:" + labelid2label[siteid];
	}


/*	
	// If single site was selected (but not 0 - all sites or 2 - separation line)
	if (siteid != "0" && siteid != "1" && siteid != "2") {
		site = "site:" + siteNameToDomain(siteSelectIdToName(siteid));
	}
	
	// Add forums (y/n)
	var forum = "true";
	if (!document.getElementById('searchbox_007498188896825459573:zpbwn3abjie').forum.checked) {
//		q = q + " more:no_forum";
		forum = "false";
	}
*/
	// Add sites to query string
/*	if (site != "") {
		q = q + " " + site;
	}
*/
	// Add label to query string
	if (label != "") {
		q = q + " " + label;
	}

	var cx = encodeURIComponent(CSE_ID);
	var cof = encodeURIComponent("FORID:10");
	
	// Use compound search string
	q = encodeURIComponent(q);
	origq = encodeURIComponent(origq);
	url = "search?cx=" + cx + "&q=" + q + "&sa=Search&cof=" + cof + "&origq=" + origq + "&siteid=" + siteid;
//	url = "search?cx=" + cx + "&q=" + q + "&sa=Search&cof=" + cof + "&origq=" + origq + "&siteid=0";
	location.href = url;
	return false;
}

// Google toolbar search button
function gtbSearch() {
	q = decodeURIComponent(urlParam(location.href, 'q'));
	url = "";
	cx = encodeURIComponent("007498188896825459573:blz2qe14fgi");
	cof = encodeURIComponent("FORID:10");
	respage = "results_n_f.html";
	forum = "false";
	url = respage + "?hl=iw&cx=" + cx + "&q=" + q + "&sa=Search&cof=" + cof + "&origq=" + q + "&siteid=" + "0" + "&f=" + forum;
	location.href = url;
	return false;
}

function urlParam (url, param) {
   var split_url = url.split('?');
   var cgi_args = split_url[1];
   if (!cgi_args) return "";
   var param_array = cgi_args.split('&');
   for (var i = 0; i < param_array.length; i++) {
      var attr_val = param_array[i].split('=');
      if (attr_val[0] == param) return attr_val[1];
   }
   return "";
 }

 // Set values for input forms
function setQ()
{
	// Set original query string
	var origq = decodeURIComponent(urlParam(location.href, 'origq'));
	if (origq != "") {
		document.getElementById('searchbox_'+CSE_ID).q.value = origq;
	}

	// Set 'search in' site
	if (urlParam(location.href, 'siteid') != "") {
		// Handling strange # sign that appeared after siteid in cookoo.us
		var split_siteid = urlParam(location.href, 'siteid').split('#');
		document.getElementById('searchbox_'+CSE_ID).site.value = split_siteid[0];
	}

/*	else {
		if (urlParam(location.href, 'from') == "mylist") {
			document.getElementById('searchbox_'+CSE_ID).site.value = 1;
		}
	}
	
	// Set forum value. The withforum variable holds the value for cookie setting.
	var withforum = "false";
	if (urlParam(location.href, 'f').match("true") == "true" && urlParam(location.href, 'q').match("no_forum") != "true") {
		document.getElementById('searchbox_'+CSE_ID).forum.checked = true;
		withforum = "true";
	}
	// If direct access to search page (no 'f' parameter on URL), check if there's cookie from last visit.	
	else if (urlParam(location.href, 'f') == "") {
		 var wfc = getCookieValue("withforum");
		 if (wfc) {
			 if (wfc == "true") {
				 document.getElementById('searchbox_'+CSE_ID).forum.checked = true;
				 withforum = "true";
			 }
		 }
	}
	
	// If cookies are enabled, store  cookie selection in persistent cookie
	 if (testPersistentCookie()) {
		 writePersistentCookie("withforum", withforum, "years", 5);
	 }
*/
	// Place cursor in search box
//	if (origq != "") {
		document.getElementById('searchbox_'+CSE_ID).q.focus();
//	}
}

/*==============================================================================

    Routines written by John Gardner - 2003 - 2005

    See www.braemoor.co.uk/software for information about more freeware
    available.

/*==============================================================================

Routine to write a session cookie

    Parameters:
        cookieName        Cookie name
        cookieValue       Cookie Value
    
    Return value:
        true              Session cookie written successfullly
        false             Failed - persistent cookies are not enabled

   e.g. if (writeSessionCookie("pans","drizzle") then
           alert ("Session cookie written");
        else
           alert ("Sorry - Session cookies not enabled");
*/

function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

/*==============================================================================

Routine to get the current value of a cookie

    Parameters:
        cookieName        Cookie name
    
    Return value:
        false             Failed - no such cookie
        value             Value of the retrieved cookie

   e.g. if (!getCookieValue("pans") then  {
           cookieValue = getCoookieValue ("pans2);
        }
*/

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

/*==============================================================================

Routine to see if session cookies are enabled

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testSessionCookie())
           alert ("Session coookies are enabled");
        else
           alert ("Session coookies are not enabled");
*/

function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;
}

/*==============================================================================

Routine to see of persistent cookies are allowed:

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testPersistentCookie()) then
           alert ("Persistent coookies are enabled");
        else
           alert ("Persistent coookies are not enabled");
*/

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  if (getCookieValue ("testPersistentCookie")=="Enabled")
    return true  
  else 
    return false;
}

/*==============================================================================

Routine to write a persistent cookie

    Parameters:
        CookieName        Cookie name
        CookieValue       Cookie Value
        periodType        "years","months","days","hours", "minutes"
        offset            Number of units specified in periodType
    
    Return value:
        true              Persistent cookie written successfullly
        false             Failed - persistent cookies are not enabled
    
    e.g. writePersistentCookie ("Session", id, "years", 1);
*/       

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;
  
  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years":
      expireDate.setYear(expireDate.getFullYear()+offset);
      break;
    case "months":
      expireDate.setMonth(expireDate.getMonth()+offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate()+offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours()+offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes()+offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  } 
  
  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}  

/*==============================================================================

Routine to delete a persistent cookie

    Parameters:
        CookieName        Cookie name
    
    Return value:
        true              Persistent cookie marked for deletion
    
    e.g. deleteCookie ("Session");
*/    

function deleteCookie (cookieName) {

  if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);  
  return true;     
}

// Set value of the 'mylist' cookie according to value of checkboxes in mylist.html. Called on submit
// Note that changes location to index.html (doesn't care about form original 'action'.
function setMylistCookie(arr) {
	// Alert in case persistent cookies are not enabled
	 if (!testPersistentCookie()) {
		 alert("Cookies must be enabled in your Web browser in order to define favorite sites");
		 return false;
	 }

	// Create cookie value
	var mylist="";
	var count = 0;
//	var arr = getSitesArray();
	var first = true;
	for (x in arr) {
		if (document.getElementById(arr[x]).checked) {
			if (!first) {
				mylist+=",";
			}
			mylist+=arr[x]; 
			first = false;
			count+=1;
		}
	 }

	 // Check if no site was selected
	if (count==0) {
		alert("You did not define any favorite sites.");
		return false;
	}
	
	// Check if more than 20 sites were selected
	if (count>20) {
		alert("It is possible to define up to 20 favorite sites.");
		return false;
	}
	
	// Write the list into the cookie
	writePersistentCookie("mylist", mylist, "years", 5);
	
	// Return to index.html with original search parameters
	// In cookoo.us for now I'm ignoring search paramers
//	url = "home?origq=" + urlParam(location.href, "origq") + "&siteid=" + urlParam(location.href, "siteid") + "&f=" + urlParam(location.href, "f");
	url = location.href.replace("/mylist", "");
	location.href = url;
	return false;
}

// Load function of mylist page - alerts if cookies are not enabled, loads current favorites to checkboxes
function loadMylist () {
	// Alert in case persistent cookies are not enabled
	 if (!testPersistentCookie()) {
		 alert("In order to use favorite sites Cookies must be enabled in your Web browser.");
	 }
	 
	 // If cookie is set, read its value into checkboxes
	 var val = getCookieValue("mylist");
	 if (val) {
		 arr = val.split(",");
		 for (x in arr) {
			 document.getElementById(arr[x]).checked = true;
		 }
	 }
}
// Get URL to mylist.html with current search form values as query string
function getMylistUrl() {
	/*
	var origq = document.getElementById('searchbox_005533144069438960690:y9zwfd7cfem').q.value;
	var siteid = document.getElementById('searchbox_005533144069438960690:y9zwfd7cfem').site.value;
	*/
	/*
	if (document.getElementById('searchbox_005533144069438960690:y9zwfd7cfem').forum.checked) {
		forum = "true";
	}
	else {
		forum = "false";
	}
	*/
/*
	// Set URL
	origq = encodeURIComponent(origq);
//	url = "mylist?origq=" + origq + "&siteid=" + siteid + "&f=" + forum;
	url = "mylist?origq=" + origq + "&siteid=" + siteid;
	*/
	url = "mylist";
	// In cookoo.us for now I ignore original search parameters
	return url;
}

// If 'my list' is selected in drop down select and my list not defined - redirect to my list page.
function onMylistSelect() {
	if (document.getElementById('searchbox_'+CSE_ID).site.value == "1") {
		 var val = getCookieValue("mylist");
		 if (!val) {
			 alert("You are being redirected to the Favorite sites page.");
			location.href = getMylistUrl();
		 }
	}
	return false;
}

/*
// On submit of cancel in mylist, returns to index.html with original search params
function onMylistCancel() {
	// Return to index.html with original search parameters
	url = "home?origq=" +  urlParam(location.href, "origq") + "&siteid=" + urlParam(location.href, "siteid") + "&f=" + urlParam(location.href, "f");
	location.href = url;
	return false;
}
*/

// When link to mylist is clicked add current form values to URL
function goToMylist() {
	location.href = getMylistUrl();
	return false;
}
