﻿// copyright 2006, Peter Tyrrell, Andornot Consulting

/* EVENTS */
// attach rewind to page load
addEvent(window, "load", RewindSearch);

// event listener
function addEvent(o,e,f)
{
	if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}

/* HELPERS */

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
String.prototype.trimSeparator = function(separator) 
{
	var output = this;
	if (output.indexOf(separator + separator) != -1)
	{
		output = output.replace(separator + separator, separator);	
	}
	if (output.indexOf(separator) == 0)
	{
		output = output.substring(separator.length, output.length);
	}
	else if (output.lastIndexOf(separator) == (output.length - separator.length))
	{
		output = output.substring(0, (output.length - separator.length));
	} 
	return output;
}

/*
GetQueryParamByKey() returns the first value found for key in a query string like key1=value1&key2=value2
*/
function GetQueryParamByKey(key, strQuery) // returns string
{
	var output = "";
	if (!strQuery)
	{
		strQuery = window.location.search.substring(1);
	}
	var arrPairs = strQuery.split("&");
	var i = 0, pos = 0;
	
	for (i=0;i<arrPairs.length;i++)
	{
		pos = arrPairs[i].indexOf('=');
		if (pos >= 0)
		{
			if (key.toLowerCase() == arrPairs[i].substring(0,pos).toLowerCase())
			{
				output = arrPairs[i].substring(pos+1);
				break;
			}
		}
	}
	return output;
}

/*
ResetAll() clears hidden inputs that contain QIx values
*/

function ResetAll(oForm)
{
	if (!oForm)
	{
		oForm = document.getElementById("qbe_form");
		if (!oForm)
		{
			oForm = document.getElementsByName("qbe_form")[0];
		}
		if (!oForm)
		{
			oForm = document.forms[0];	
		}
	}
	
    for (var i = 0; i < oForm.elements.length; i++)
    {
        if (oForm.elements[i].type == "hidden" && oForm.elements[i].name.toUpperCase().substring(0,2) == "QI")
        {
            oForm.elements[i].value = "";
        }    
    }    
}

/*
ValidateForm(oForm) ensures some search text has been entered in QIx or QY inputs
*/

function ValidateForm(oForm)
{
    var isValid = false;
    var i;
	
    for (i = 0; i < oForm.elements.length; i++)
    {
        if (oForm.elements[i].name.toUpperCase().substring(0,2) == "QI" || oForm.elements[i].name.toUpperCase().substring(0,2) == "QY")
        {
            if (oForm.elements[i].value != "")
            {
                isValid = true;
                return true;
            }
        }
    }
		
	alert("Please enter search criteria.");
	return false;
}

/*
GetTextbaseName() fetches the TN input value on the page, returns null if not found
*/

function GetTextbaseName()
{
	var output = "";
	var target = document.getElementById('TN');
	if (target == null)
	{
		target = document.getElementsByName('TN')[0];
	}
	if (target == null)
	{
		return null;	
	}
	output = target.value;
	return output;
}



/*******************************************************************************
REWIND
Functions to return to search page without hard-coding urls into results pages,
for both 'new search' and 'revise search'
*******************************************************************************/

/*
RewindSearch() loads form values if conditions are met.
Is attached to search page load event by addEvent()
*/

function RewindSearch()
{
	var remember = GetQueryParamByKey("remember");
	
	if (remember == "true")
	{
		var strFormState;
		var cookieName = null;
		
		var elCookieName = document.getElementById('RewindCookieName');
		if (elCookieName)
		{
			cookieName = elCookieName.value;	
		}
		else
		{
			var tn = GetTextbaseName();
			if (tn)
			{
				cookieName = GetTextbaseName() + "AndornotRewind";
			}	
		}
		
		if (!cookieName)
		{
			return;	
		}

		strFormState = GetRewindCookie(cookieName);
		if (strFormState)
		{
			var oForm;
			oForm = document.getElementById("qbe_form");
			if (!oForm)
			{
				oForm = document.getElementsByName("qbe_form")[0];
			}
			if (!oForm)
			{
			    oForm = document.forms[0];
			}
			if (oForm)
			{
				SetFormState(oForm, strFormState);
			}
		}
	}
}


/*
SetRewind() fires on search form submit, writes user-affected form settings to cookie
*/

function SetRewind(cookieName)
{
	if (!navigator.cookieEnabled)
	{
		return;
	}
	
	var oForm;
	var arrFormState = [];
	var strFormState = "";
	
	oForm = document.getElementById("qbe_form");
	if (!oForm)
	{
		oForm = document.getElementsByName("qbe_form")[0];
	}
	if (!oForm)
	{
	    oForm = document.forms[0];
	}
	if (oForm)
	{
		arrFormState = GetFormState(oForm);
		if (arrFormState.length > 0)
		{
			strFormState = arrFormState.join("&");
			if (!cookieName)
			{
				SetRewindCookie(GetTextbaseName() + "AndornotRewind", strFormState, null, "/");	
			}
			else
			{
				SetRewindCookie(cookieName, strFormState, null, "/");	
			}
			
		}
	}
}

/*
GetFormState() polls the supplied form, returns array of name/value strings ("name=value")
*/

function GetFormState(oForm)
{
	var output = [];
	var intFormLength = oForm.elements.length;
	var strValue = "";
	var strKey = "";
	var i = 0;
	
	for (i=0;i<intFormLength;i++)
	{
		if (oForm.elements[i].type)
		{
			strValue = "";
			
			if (oForm.elements[i].type.substring(0,6) == "select")
			{
				strValue = oForm.elements[i].selectedIndex;
			}	
			else if (oForm.elements[i].type == "checkbox" || oForm.elements[i].type == "radio")
			{
				strValue = oForm.elements[i].checked.toString();
			}
			else if (oForm.elements[i].type == "text")
			{
				strValue = oForm.elements[i].value;	
			}
			else if (oForm.elements[i].type == "hidden" && oForm.elements[i].name.toUpperCase().substring(0,2) == "QI")
			{
				strValue = oForm.elements[i].value;	
			}
			
			if (strValue != "")
			{
				// preferentially use id as key
				if (oForm.elements[i].id != "")
				{
					strKey = oForm.elements[i].id;
				}
				else
				{
					strKey = oForm.elements[i].name.toUpperCase();
				}
				output[output.length] = strKey + "=" + encodeURIComponent(strValue);
			}
		}	
	}
	return output;
}

/*
SetFormState() populates the supplied form with supplied name/value settings 
*/

function SetFormState(oForm, strFormState)
{
	var intFormLength = oForm.elements.length;
	var strValue = "";
	var strKey = "";
	var i = 0;
	
	for (i=0;i<intFormLength;i++)
	{
		if (oForm.elements[i].type)
		{
			strKey = "";
			if (oForm.elements[i].id != "")
			{
				strKey = oForm.elements[i].id;
			}
			else
			{
				strKey = oForm.elements[i].name;
			}
			
			strValue = "";
			strValue = GetQueryParamByKey(strKey, strFormState);
			
			if (strValue != "")
			{
				strValue = decodeURIComponent(strValue);
				
				switch (oForm.elements[i].type)
				{
					case "select-one":
						oForm.elements[i].selectedIndex = parseInt(strValue);
						break;
					case "select-multiple":
						oForm.elements[i].selectedIndex = parseInt(strValue);
						break;
					case "checkbox":
						if (strValue == "true")
						{
							oForm.elements[i].checked = true;
						}
						else
						{
							oForm.elements[i].checked = false;
						}
						break;
					case "radio":
						if (strValue == "true")
						{
							oForm.elements[i].checked = true;
						}
						else
						{
							oForm.elements[i].checked = false;
						}
						break;
					case "text":
						oForm.elements[i].value = strValue;
						break;
					case "textarea":
						oForm.elements[i].innerHTML = strValue;
						break;
					case "hidden":
						if (oForm.elements[i].name.toUpperCase().substring(0,2) == "QI")
						{
							oForm.elements[i].value = strValue;
						}
						break;
				}
			}
		}	
	}
}

function GetRewindCookie( name ) 
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) 
	{
		return null;
	}
	if ( start == -1 )
	{
		return null;
	}
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 )
	{
		end = document.cookie.length;
	}
	return decodeURIComponent( document.cookie.substring( len, end ) );
}

function SetRewindCookie( name, value, expires, path, domain, secure ) 
{
    var output = "";
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) 
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	output = name + '=' + encodeURIComponent( value ) +
		( ( expires ) ? '; expires='+expires_date.toGMTString() : '' ) +
		( ( path ) ? '; path=' + path : '' ) +
		( ( domain ) ? '; domain=' + domain : '' ) +
		( ( secure ) ? '; secure' : '' );
		
	document.cookie = output;
}




/*************************************************
ADDREMOVEME
Functions for extending WebPublisher search/edit forms
*************************************************/

/*
AddRemoveMe() adds calling element's value to a target element if not already there,
or removes calling element's value from a target element if found.
Multiple additions are separated by a supplied separator string (e.g. " / " typical for a search form).
Used to update hidden or text inputs with checkboxes and radio buttons.
Caller and target assumed to have a value property.
*/
function AddRemoveMe(me, targetID, strSeparator)
{
  var target;
  target = document.getElementById(targetID);
  if (!target)
  {
  	target = document.getElementsByName(targetID)[0];
  }
  if (!strSeparator)
  {
  	strSeparator = " / ";	
  }
  me.value = me.value.toString().trim();
  var index = target.value.indexOf(me.value);
    
  // if me.value not found, add me.value 
  if (index == -1)
  {
    target.value += strSeparator + me.value;
  }
  // if me.value is found, remove me.value
  else if (index != -1)
  {
    var pre = target.value.substring(0, index);
    var post = target.value.substring(index + me.value.length, target.value.length);
    target.value = pre+post;
  }

  //Remove extraneous separators
  target.value = target.value.trimSeparator(strSeparator)
}


/*
AddRemoveValue is like AddRemoveMe except passes a string instead of the originating object.
*/
function AddRemoveValue(value, targetID, strSeparator)
{
  var target;
  target = document.getElementById(targetID);
  if (!target)
  {
  	target = document.getElementsByName(targetID)[0];
  }
  value = value.trim();
  var index = target.value.indexOf(value);
    
  // if me.value not found, add me.value 
  if (index == -1)
  {
    target.value += strSeparator + value;
  }
  // if me.value is found, remove me.value
  else if (index != -1)
  {
    var pre = target.value.substring(0, index);
    var post = target.value.substring(index + value.length, target.value.length);
    target.value = pre+post;
  }

  //Remove extraneous separators
  target.value = target.value.trimSeparator(strSeparator)
}


/*********************************************************************
AutoBoolean "google-izes" Inmagic text inputs:
forces words/terms to be separated by a given boolean operator
in the named search boxes.
**********************************************************************/
function AutoBoolean(BooleanChar, targetList, stemOn)
{
	var sep = "|";
	var targetArray = new Array();
	targetArray = targetList.split(sep);
	var i = 0;
	var CurrentTarget;
	var InitialTargetValue;
	var oForm;
	
	oForm = document.forms.qbe_form;
	if (oForm == null)
	{
		oForm = document.forms[0];		
	}
	
	for (i=0;i<targetArray.length;i++)
	{
		CurrentTarget = oForm.elements[targetArray[i]];
		InitialTargetValue = CurrentTarget.value.trim();
		CurrentTarget.value = makeAutobooleanQuery(BooleanChar, splitStr(InitialTargetValue, /("[^"]*")|([^"\s]+(\s|$))/g), stemOn);
	}
}


function splitStr(strAddr, splitWith)
{
        var tmpStr  = new String(strAddr);
        return tmpStr.match(splitWith);
}

function makeAutobooleanQuery(BooleanChar, myArray, stemOn)
{
	if (!myArray)
	{ 
		return '';
	}

	var tempArray = new Array();
	var i = 0;
	var j = 0;
	var str = '';
	var AddBooleanNext = true;

	for (i = 0; i < myArray.length; i++)
	{
		str = myArray[i].trim().toLowerCase();
		
		if (str != '')
		{	
				switch (str)
				{
					case '!':
						tempArray[j++] = str;
						if (j > 0)
						{
							AddBooleanNext = false;
						}
						break;
					case '/':
						tempArray[j++] = str;
						if (j > 0)
						{
							AddBooleanNext = false;
						}
						break;
					case '&':
						tempArray[j++] = str;
						if (j > 0)
						{
							AddBooleanNext = false;
						}
						break;
					case ':':
						tempArray[j++] = str;
						if (j > 0)
						{
							AddBooleanNext = false;
						}
						break;
					case 'a':
						break;
					case 'an':
						break;
					case 'and':
						break;
					case 'by':
						break;
					case 'for':
						break;
					case 'from':
						break;
					case 'of':
						break;
					case 'the':
						break;
					case 'to':
						break;
					default:
						if (str.match(/^(w|p){1}\d+$/g) != null)
						{
							tempArray[j++] = str;
							AddBooleanNext = false;
							break;
						}
						else
						{
							if (AddBooleanNext == true && j > 0)
							{
								tempArray[j++] = BooleanChar;
							}
							if (stemOn && (stemOn == true) && (str.indexOf("\"") != 0) && (str.lastIndexOf("*") == -1))
							{
							    tempArray[j++] = str + "*";   
							}
							else
							{
							    tempArray[j++] = str;
							}
							AddBooleanNext = true;
						}
				}
			//}
			
		}
	}

	return tempArray.join(' ');

}
