// Return the url without the query string
function uri (url) {
   var split_url = url.split('?');
   return split_url[0];
 }

// 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_007498188896825459573:zpbwn3abjie').q.value = origq;
		document.getElementById('searchbox_007498188896825459573:zpbwn3abjie').q.value = origq;
	}
	// Set 'search in' site
	if (urlParam(location.href, 'siteid') != "") {
		document.getElementById('searchbox_007498188896825459573:zpbwn3abjie').site.value = urlParam(location.href, 'siteid');
	}
	else {
		if (urlParam(location.href, 'from') == "mylist") {
			document.getElementById('searchbox_007498188896825459573:zpbwn3abjie').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_007498188896825459573:zpbwn3abjie').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_007498188896825459573:zpbwn3abjie').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_007498188896825459573:zpbwn3abjie').q.focus();
//	}
	// Setting focus on search button, so it won't be set to text box, to avoid predictad auto-open on search page (setQ is now used only from search page)
	document.getElementById('searchbox_007498188896825459573:zpbwn3abjie').sa.focus();

	// If 'my favorites' or specific site used, show advanced search
	if (urlParam(location.href, 'siteid') != "0" && urlParam(location.href, 'siteid') != "") {
		document.getElementById('advanced_search').style.visibility = "visible";
	}
	
}

/*==============================================================================

    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("על מנת להגדיר אתרים מועדפים יש לאפשר בדפדפן תמיכה ב\"קוקי\" (כרגע לא מאופשר). תודה");
		 return false;
	 }

	// Create cookie value
	var mylist="";
	var count = 0;
//	var arr = getSitesArray();
	var first = true;
	for (x=0; x<arr.length; x++) {
		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("לא נבחרו אתרים");
		return false;
	}
	
	// Check if more than 20 sites were selected
	if (count>20) {
		alert("לא ניתן לבחור יותר מעשרים אתרים למועדפים");
		return false;
	}
	
	// Write the list into the cookie
	writePersistentCookie("mylist", mylist, "years", 5);
	
	// Return to index.html with original search parameters
//	url = "index.html?origq=" + urlParam(location.href, "origq") + "&siteid=" + urlParam(location.href, "siteid") + "&f=" + urlParam(location.href, "f");
//	url = ".";
//	location.href = url;
	return true;
}

// 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("על מנת להגדיר אתרים מועדפים יש לאפשר בדפדפן תמיכה ב\"קוקי\" (כרגע לא מאופשר). תודה");
	 }
	 
	 // If cookie is set, read its value into checkboxes
	 var val = getCookieValue("mylist");
	 if (val) {
		 arr = val.split(",");
		 for (x=0; x<arr.length; x++) {
			 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_007498188896825459573:zpbwn3abjie').q.value;
	var siteid = document.getElementById('searchbox_007498188896825459573:zpbwn3abjie').site.value;
	if (document.getElementById('searchbox_007498188896825459573:zpbwn3abjie').forum.checked) {
		forum = "true";
	}
	else {
		forum = "false";
	}

	// Set URL
	origq = encodeURIComponent(origq);
	url = "mylist.html?origq=" + origq + "&siteid=" + siteid + "&f=" + forum; */
	url = "mylist";
	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_007498188896825459573:zpbwn3abjie').site.value == "1") {
		 var val = getCookieValue("mylist");
		 if (!val) {
			 alert("הנך מופנה כעת לעמוד הגדרת אתרים מועדפים");
			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 = "index.html?origq=" +  urlParam(location.href, "origq") + "&siteid=" + urlParam(location.href, "siteid") + "&f=" + urlParam(location.href, "f");
//	location.href = url;
	return true;
}

// When link to mylist is clicked add current form values to URL
function goToMylist() {
	location.href = getMylistUrl();
	return false;
}

// Copyright © 2001 by Apple Computer, Inc., All Rights Reserved.
//
// You may incorporate this Apple sample code into your own code
// without restriction. This Apple sample code has been provided "AS IS"
// and the responsibility for its operation is yours. You may redistribute
// this code, but you are not permitted to redistribute it as
// "Apple sample code" after having made changes.

// whole form

function checkContactForm(theForm) {
	var why = "";
	why += checkName(theForm.name.value);
//	why += checkPassword(theForm.pass.value, theForm.pass2.value);
	why += checkEmail(theForm.email.value);
	why += checkSubject(theForm.subject.value);
	why += checkMessage(theForm.message.value);
	/*   why += checkPhone(theForm.phone.value);
	    why += isEmpty(theForm.notempty.value);
	why += isDifferent(theForm.different.value);
	for (i=0, n=theForm.radios.length; i<n; i++) {
		if (theForm.radios[i].checked) {
			var checkvalue = theForm.radios[i].value;
			break;
		} 
	}
	why += checkRadio(checkvalue);
	why += checkDropdown(theForm.choose.selectedIndex);*/
	if (why != "") {
		alert(why);
		return false;
	}
	return true;
}

// email

function checkEmail (strng) {
	var error="";
	if (strng == "") {
		error = "אימייל ריק.\n";
	}
	
	var emailFilter=/^.+@.+\..{2,4}$/;
	if (!(emailFilter.test(strng))) { 
		error = "מבנה כתובת דואר אלקטרוני לא תקין\n";
	}
	else {
		//test email for illegal characters
		var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
		if (strng.match(illegalChars)) {
			error = "כתובת דואר אלקטרוני מכילה תווים לא חוקיים";
		}
	}
	return error;    
}

function checkName (strng) {
	var error = "";
	if (strng == "") {
		error = "שם ריק.\n";
	}
	
	return error;
}

function checkSubject (strng) {
	var error = "";
	if (strng == "") {
		error = "נושא ריק.\n";
	}
	
	return error;
}

function checkMessage (strng) {
	var error = "";
	if (strng == "") {
		error = "הודעה ריקה.\n";
	}
	
	return error;
}

// phone number - strip out delimiters and check for 10 digits

function checkPhone (strng) {
	var error = "";
	if (strng == "") {
		error = "You didn't enter a phone number.\n";
	}
	
	var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
	if (isNaN(parseInt(stripped))) {
		error = "The phone number contains illegal characters.";
		
	}
	if (!(stripped.length == 10)) {
		error = "The phone number is the wrong length. Make sure you included an area code.\n";
	} 
	return error;
}


// password 
function checkPassword (strng, strng2) {
	var error = "";

	var illegalChars = /[\W_]/; // allow only letters and numbers
	
	// checking length
	if ((strng.length < 4) || (strng.length > 10)) {
		error = "אורך סיסמא צריך להיות בין 4-8 תווים\n";
	}
	// checking legal characters
	else if (illegalChars.test(strng)) {
		error = "סיסמא יכולה להכיל אותיות באנגלית ומספרים בלבד\n";
	} 
	// checking that the two  passwords match
	else if (strng != strng2) {
		error = "אישור סיסמא שגוי\n";
	}
	return error;    
}    

// username - 4-10 chars, uc, lc, and underscore only.

function checkUsername (strng) {
	var error = "";

	var illegal1 = /[^a-zA-Z_\-\s0-9א-ת]/;
	if ((strng.length < 1) || (strng.length > 20)) {
		error = "אורך שם משתמש צריך להיות בין 1-20 תווים\n";
	}
	else if (illegal1.test(strng)) {
		error = "שם משתמש יכול להכיל אותיות בעברית או אנגלית, מספרים, רווח, קו תחתי וסימן מינוס בלבד\n";
	} 
	return error;
}       


// non-empty textbox

function isEmpty(strng) {
	var error = "";
	if (strng.length == 0) {
		error = "The mandatory text area has not been filled in.\n"
	}
	return error;	  
}

// was textbox altered

function isDifferent(strng) {
	var error = ""; 
	if (strng != "Can\'t touch this!") {
		error = "You altered the inviolate text area.\n";
	}
	return error;
}

// exactly one radio button is chosen

function checkRadio(checkvalue) {
	var error = "";
	if (!(checkvalue)) {
		error = "Please check a radio button.\n";
	}
	return error;
}

// valid selector from dropdown list

function checkDropdown(choice) {
	var error = "";
	if (choice == 0) {
		error = "You didn't choose an option from the drop-down list.\n";
	}    
	return error;
}    


