//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// SUPORTING FUNCTIONS
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
function getObj(n, d) { 
    var p,i,x;  
    if(!d) {
        d=document; 
    }
    if((p=n.indexOf("?")) > 0 && parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; 
        n=n.substring(0,p);
    }
    if(!(x=d[n]) && d.all) {
        x=d.all[n]; 
    }
    for (i=0; !x && i<d.forms.length; i++) {
        x=d.forms[i][n];
    }
    for(i=0; !x&&d.layers && i<d.layers.length; i++) {
        x=getObj(n,d.layers[i].document);
    }
    if(!x && d.getElementById) {
        x=d.getElementById(n); 
    }
    return x;
}

//-----------------------------------------------------------------------------
function Replace(argvalue, x, y)
{
	if (argvalue)
	{
		if ((x == y) || (parseInt(y.indexOf(x)) > -1))
		{
			errmessage = "replace function error: \n";
			errmessage += "Second argument and third argument could be the same ";
			errmessage += "or third argument contains second argument.\n";
			errmessage += "This will create an infinite loop as it's replaced globally.";
			alert(errmessage);
			return false;
		}

		while (argvalue.indexOf(x) != -1)
		{
			var leading = argvalue.substring(0, argvalue.indexOf(x));
			var trailing = argvalue.substring(argvalue.indexOf(x) + x.length, 
			argvalue.length);
			argvalue = leading + y + trailing;
		}
	}
	
    return argvalue;
}

//-----------------------------------------------------------------------------
function Trim(theValue)
{
    var objRegex = new RegExp('(^\\s+)|(\\s+$)');
    var strResult = theValue.replace(objRegex, '');

    return strResult;
}

//-----------------------------------------------------------------------------
function IsNumeric(thefield) 
{
    sText = getObj(thefield).value;
    var ValidChars = "0123456789.:";
    var IsNumber = true;
    var Char;
    
    for (i = 0; i < sText.length && IsNumber == true; i++) 
    {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) 
        {
            IsNumber = false;
        }
    }

    return IsNumber;
}

//-----------------------------------------------------------------------------
function GetBadChars(theValue)
{
    var badChars = '';
    var theChars = '/\+?!£$%^&*|_<>[]';
    for (var i = 1; i <= theChars. length - 1; i++)
    {
        var thisChar = (Mid(theChars, i, 1));
        var bFound = theValue.indexOf(thisChar);
        if (bFound != -1)
        {
            badChars += thisChar;
        }
    }
    
    return badChars;
}

//-----------------------------------------------------------------------------
function Mid(str, start, len)
{
    if (start < 0 || len < 0)
    {
        return '';
    }
    
    var iEnd, iLen = String(str).length;
    if (start + len > iLen)
    {
        iEnd = iLen;
    }
    else
    {
        iEnd = start + len;
    }
    return String(str).substring(start,iEnd);
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Ajax Search Keyword Suggestions
//-----------------------------------------------------------------------------
function SuggestSearchKeywords(obj, hiddenDivName, kwType)
{
	var typedSoFar = obj.value;
	var hiddenDivObj = getObj(hiddenDivName);
	if (hiddenDivObj != null)
	{
	    if (typedSoFar.length >= 3)
	    {
	        var url = 'search_suggestions.asp?o=' + obj.name + '&h=' + hiddenDivName + '&q=' + Replace(typedSoFar, "'", "");
	        
		    this.RunScript(url, hiddenDivName, '');
		    
		    if (hiddenDivObj.innerHTML != '')
		    {
			    hiddenDivObj.style.display = 'block';
		    }
	    }
	    else
	    {
		    hiddenDivObj.style.display = 'none';
	    }
	}
}

//-----------------------------------------------------------------------------
// User Clicks on suggestion.
function SearchClickSuggest(catName, entryObjName, hiddenDivName)
{
	getObj(entryObjName).value = catName;
	getObj(hiddenDivName).style.display = 'none';
}

//-----------------------------------------------------------------------------
// ... for a location
function SearchClickSuggestLoc(catName, entryObjName, hiddenDivName, locId)
{
	getObj(entryObjName).value = catName;
	if (getObj('loc_id') != null)
	{
	    getObj('loc_id').value = locId;
	}
	getObj(hiddenDivName).style.display = 'none';
}

//-----------------------------------------------------------------------------
// User Exits Search box
function HideSuggest(hiddenDivName)
{
    if (getObj(hiddenDivName) != null)
    {
        getObj(hiddenDivName).style.display = 'none';
	}
}

//-----------------------------------------------------------------------------
// User Clicks Search Box - Clear Dummy Stuff
function ClickSearchBox(obj)
{
	if (obj.value == 'e.g. Company Name, Postcode...')
	{
		obj.value = '';
		obj.style.color = '#000';
	}
}

//-----------------------------------------------------------------------------
function SearchGo(searchType)
{
    var strKeyword = Trim(getObj('SrchKeyword').value);
	if (strKeyword == 'e.g. Network, Database...')
	{
		strKeyword = '';
	}
	if (strKeyword == 'e.g. Sales Jobs...')
	{
		strKeyword = '';
	}
	if (strKeyword == 'Search the archive...')
	{
		strKeyword = '';
	}
		
    if (strKeyword.length >= 3)
    {
		//strKeyword = Replace(strKeyword, ' ', '');
		strKeyword = Replace(strKeyword, '&', ' and ');
		srchURL = 'customscripts/searchresults.asp?k=' + strKeyword.toLowerCase();
		
		var strLocation = getObj('SrchLocation');
		if (strLocation != null)
		{
			strLocation.value = Trim(strLocation.value);
			if (strLocation.value == 'e.g. London, Bristol...')
			{
				strLocation.value = '';
			}
			if (strLocation.value.length > 0)
			{
				srchURL += '&l=' + strLocation.value.toLowerCase();
			}
		}
		if (searchType == 'j')
		{
			srchURL += '&job=1';
		}
		if (searchType == 'bac')
		{
			srchURL += '&bac=1';
		}
		if (getObj('loc_id') != null)
		{
		    if (getObj('loc_id').value != '' && strLocation.value != '')
		    {
		        srchURL += '&locid=' + getObj('loc_id').value;
		    }
		}
		
		location.href = srchURL;
    }
    else
    {
        alert('Please enter a Search Keyword of at least 3 characters in length');
    }
}

//-----------------------------------------------------------------------------
function OnKeydownSearch(e, searchType, inputBoxName)
{
	if (!e)
    {
        e = window.event; // for ie
    }
	if (e.keyCode == 13) // CR
	{
		SearchGo(searchType);
	}
	else
	{
		// Trim input if too long
		var searchKeyword = getObj('SrchKeyword');
		if (searchKeyword != null)
		{
			searchKeyword.style.color = '#000';
			if (searchKeyword.value.length > 45)
			{
				searchKeyword.value = searchKeyword.value.substring(0, 45);
			}
		}
		
		var searchLocation = getObj('SrchLocation');
		if (searchLocation != null && searchLocation.value != 'e.g. London, Bristol...')
		{
			searchLocation.style.color = '#000';
			if (searchLocation.value.length > 45)
			{
				searchLocation.value = searchLocation.value.substring(0, 45);
			}
			
			if (inputBoxName == 'loc')
			{
			    // User is typing a location. 0 the location id
			    getObj('loc_id').value = '';
			}
		}
	}
}

//-----------------------------------------------------------------------------
function RefreshSearch(kw, loc, locationId)
{
	// Refresh the search results given the passed in parameters
	var run1 = 'customscripts/search' + 'results';
	var run2 = '.as' + 'p?';
	var run3 = 'k=' + kw + '&l=' + loc;
	if (locationId != '')
	{
	    run3 += '&locid=' + locationId;
	}
	location.href = run1 + run2 + run3;
}

//-----------------------------------------------------------------------------
function LocationSelect(locationId, postTown, divToFill, pcFieldName)
{
	var url = 'customscripts/signup_selectloc.asp?locationId=' + locationId + '&posttown=' + postTown + '&divtofill=' + divToFill;
	
	RunScript(url, divToFill, pcFieldName);
}


//-----------------------------------------------------------------------------
// Ajax functions
//-----------------------------------------------------------------------------
function RunScript(strScript, strDivName, strFieldName)
{
    // strDivName is the div to fill with what is response.written in the script
    // strFieldName is used to pass a parameter which can be accessed by Request("q")
    var xmlHttpReq = false;
    var self = this;
    if (window.XMLHttpRequest)
    {   // Mozilla / Safari / IE7
        self.xmlHttpReq = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {   // IE
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strScript, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function()
    {
        if (self.xmlHttpReq.readyState == 4)
        {
            UpdatePage(self.xmlHttpReq.responseText, strDivName);
        }
    }
    self.xmlHttpReq.send(this.GetQueryString(strFieldName));
}

//-----------------------------------------------------------------------------
function UpdatePage(strInnerHTML, strDivName)
{
    var result = getObj(strDivName);
    if (result != null)
    {
        result.innerHTML = strInnerHTML;
        if (strInnerHTML == '')
        {
            result.style.display = 'none';
        }
        else
        {
            result.style.display = 'block';
        }
    }
}

//-----------------------------------------------------------------------------
function GetQueryString(strFieldName)
{
    var strQuery = '';
    var field = getObj(strFieldName);
    if (field != null)
    {
        var strValue = field.value;
        strValue = Replace(strValue, '+', 'PLUS_SIGN');
        strQuery = 'q=' + escape(strValue) + '';  // NOTE: no '?' before query string
    }
    return strQuery;
}


//-----------------------------------------------------------------------------
function HideDiv(divName)
{
    var divObj = getObj(divName);
    if (divObj != null)
    {
        divObj.style.display = 'none';
    }
}

//-----------------------------------------------------------------------------
function ShowDiv(divName)
{
    var divObj = getObj(divName);
    if (divObj != null)
    {
        divObj.style.display = 'block';
    }
}

