//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// 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);
}

//-----------------------------------------------------------------------------
function ContainsWebAddress(str) {
	var badchars = '.com,.co.uk,.net,.org,.biz, com ,www.'
	badcharArray = badchars.split(',');
	
	for(var i=0;i<badcharArray.length;i++) {
		if(str.indexOf(badcharArray[i])!=-1) {
			return true;
		}
	}
    return false;
}
//-----------------------------------------------------------------------------
function EmailCheck(emailStr)
{
    emailStr = Trim(emailStr);
    var emailPat = /^([.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    var matchArray = emailStr.match(emailPat);
    if (matchArray == null)
    {
        return false;
    }

    var IPArray = matchArray[2].match(/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/);
    if (IPArray != null)
    {
        for (var i = 1; i <= 4; i++)
        {
            if (IPArray[i] > 255)
            {
                return false;
            }
        }
    }
    return true;
}

//-----------------------------------------------------------------------------
function OpenCenteredWindow(url, height, width, name, parms)
{
    var left = Math.floor( (screen.width - width) / 2);
    var top =
	 Math.floor( (screen.height - height) / 2);
    var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
    if (parms)
    {
        winParms += "," + parms;
    }
    var win = window.open(url, name, winParms);
    if (parseInt(navigator.appVersion) >= 4 && win != null)
    {
        win.window.focus();
    }
}

//-----------------------------------------------------------------------------
function OpenWindow(windowType, params)
{
    switch (windowType)
    {
		case 'testimonials':
            OpenCenteredWindow('/staticFiles/signup_testimonials.htm', '500', '600', 'testimonials', '');
            break;
        case 'casestudy':
			OpenCenteredWindow('/staticFiles/signup_casestudy.htm', '540', '700', '', '');
			break;
        case 'rating_example':
            OpenCenteredWindow('/customscripts/profile_example.asp?level=ratings', '450', '550', 'example', 'scrollbars=yes');
            break;
        case 'edit_product':
            OpenCenteredWindow('/customscripts/pm_products.asp?' + params, '450', '600', 'AddProduct', 'resizable=yes');
            break;
        case 'add_product':
            OpenCenteredWindow('/customscripts/pm_products.asp?action=add', '450', '600', 'AddProduct', 'resizable=yes');
            break;
        case 'edit_service':
            OpenCenteredWindow('/customscripts/pm_services.asp?' + params, '450', '600', 'AddService', 'resizable=yes');
            break;
        case 'add_service':
            OpenCenteredWindow('/customscripts/pm_services.asp?action=add', '450', '600', 'AddService', 'resizable=yes');
            break;
        case 'third_person':
            OpenCenteredWindow('/staticFiles/pm_3rdperson.htm', '500', '500', '3rdperson', '');
            break;
        case 'link_help':
            OpenCenteredWindow('/customscripts/pm_links_help.asp', '400', '600', 'Enquiry', 'toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0');
            break;
        case 'logo_example':
            OpenCenteredWindow('customscripts/pm_logo.asp', '300', '400');
            break;
        case 'review_email':
            OpenCenteredWindow('/customscripts/review_email_example.asp', '430', '680', null, 'status=no, resizable=no, scrollbars=no');
            break;
        case 'review_precautions':
			OpenCenteredWindow('/staticFiles/pm_reviews_precautions.htm', '450', '500', 'review_precautions', '');
        case 'job_examples':
            switch (params)
            {
                case '1':
                    OpenCenteredWindow('/staticFiles/job_examples1.htm', '500', '550', null, 'status=no, resizable=no, scrollbars=no');
                    break;
                case '2':
                    OpenCenteredWindow('/staticFiles/job_examples2.htm', '500', '550', null, 'status=no, resizable=no, scrollbars=no');
                    break;
                case '3':
                    OpenCenteredWindow('/staticFiles/job_examples3.htm', '500', '550', null, 'status=no, resizable=no, scrollbars=no');
                    break;
            }
            break;
        case 'job_faqs':
            OpenCenteredWindow('/staticFiles/job_faqs.htm', '500', '550', null, 'status=no, resizable=no, scrollbars=no');
            break;
        case 'job_covering_tips':
            OpenCenteredWindow('/staticFiles/job_covering_tips.htm', '350', '550', null, 'status=no, resizable=no, scrollbars=no');
            break;
    }
}


//Ajax Search Keyword Suggestions
//-----------------------------------------------------------------------------
function SuggestSearchKeywords(obj,hiddenDiv) {
	typedsofar = obj.value;
	hiddenDivObj = getObj(hiddenDiv);
	if (typedsofar.length >= 3) {
		//hiddenDivObj.style.display = 'block';
		RunScript('/customscripts/search_suggestions.asp?o=' + obj.name + '&h=' + hiddenDiv + '&q=' + typedsofar, hiddenDiv, '');
		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';
}
//User Exits Search box
function HideSuggest(HiddenDivName) {
	getObj(HiddenDivName).style.display = 'none';
}
//User Clicks Search Box - Clear Dummy Stuff
function ClickSearchBox(obj) {
	if (obj.value == 'e.g. Plumber, Courier...' || obj.value == 'e.g. London, Bristol...' || obj.value == 'e.g. Sales Jobs...') {
		obj.value = '';
		obj.style.color = '#000';
	}
}
//-----------------------------------------------------------------------------
function SearchGo(searchType)
{
    var strKeyword = Trim(getObj('SrchKeyword').value);
	if (strKeyword == 'e.g. Plumber, Courier...')
	{
		strKeyword = '';
	}
	if (strKeyword == 'e.g. Sales Jobs...')
	{
		strKeyword = '';
	}
		
    if (strKeyword.length >= 3)
    {
		strKeyword = Replace(strKeyword, ' ', '-');
		strKeyword = Replace(strKeyword, '&', ' and ');
		srchURL = '/searchresults.asp?k=' + strKeyword;
		
		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 = srchURL + '&l=' + strLocation.value;
			}
		}
		if (searchType == 'j')
		{
			srchURL = srchURL + '&job=1';
		}
		location.href = srchURL;
    }
    else
    {
        alert('Please enter a Search Keyword of at least 3 characters in length');
    }
}

//-----------------------------------------------------------------------------
function OnKeydownSearch(e, searchType)
{
	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);
			}
		}
	}
}

//-----------------------------------------------------------------------------
function RefreshSearch(kw,loc)
{
	// Refresh the search results given the passed in parameters
	var run1 = '/search' + 'results';
	var run2 = '.as' + 'p?';
	var run3 = 'k=' + kw + '&l=' + loc;
	location.href = run1 + run2 + run3;
}

//-----------------------------------------------------------------------------
function LocationSelect(locationId, postTown, divToFill, pcFieldName)
{
	var url = '/customscripts/signup_selectloc.asp?locationId=' + locationId + '&posttown=' + postTown;
	
	RunScript(url, divToFill, pcFieldName);
}

//-----------------------------------------------------------------------------
function UploadImage(thePath, previewImageName, hiddenFieldName, bNoResize)
{
	var left = Math.floor((screen.width - 400) / 2);
	var top = Math.floor((screen.height - 200) / 2);
	mywindow = window.open('upload.asp', 'upload', 'top=' + top + ', left=' + left + ', status=yes, resizable=no, width=400, height=200');
	if (bNoResize == true)
	{   // This is our way which sets combo box item etc.
	    mywindow.location.href = '/customscripts/upload_noresize.asp?thepath=' + thePath + '&previewImageName=' + previewImageName + '&HiddenFieldName=' + hiddenFieldName;
	}
	else
	{   // Do the normal way the users have to
	    mywindow.location.href = '/customscripts/upload.asp?thepath=' + thePath + '&previewImageName=' + previewImageName + '&HiddenFieldName=' + hiddenFieldName;
	}
	
	if (mywindow.opener == null)
	{
	    mywindow.opener = self;
	}
}

//-----------------------------------------------------------------------------
function PreviewImage(fieldName, previewName, formName)
{
    // Set the preview object to be the fieldName
    var fieldNameValue = getObj(fieldName).value;
    var previewObj = getObj(previewName);
    if (fieldNameValue != '')
    {
        previewObj.src = '/customscripts/systemfunctions/showimage.asp?img=' + fieldNameValue + '&folder=listinglogos&maxw=100&maxh=60';
    }
    else
    {
        previewObj.src = '/media/images/noimage.gif';
    }
}

//-----------------------------------------------------------------------------
function AddOptionToOpener(Listbox, fText, fValue)
{
    getObj(Listbox).options[getObj(Listbox).length] = new Option(fText, fValue, false, false);
    getObj(Listbox).options[getObj(Listbox).length - 1].selected = true;
}
    
//-----------------------------------------------------------------------------
//Used by pager on Profile Products Page
//-----------------------------------------------------------------------------
function ChangePager(newPage, formName, theType)
{
    var thePage = getObj('pager');
    thePage.value = newPage;
    
    var theForm = eval('document.' + formName);
    
    if (getObj('page_search_type') != null)
    {
        getObj('page_search_type').value = theType;
    }
    
    theForm.submit();
    
    return;
}

//-----------------------------------------------------------------------------
// Listing Builder specific code
//-----------------------------------------------------------------------------
function SaveProfile()
{
    var bad = '';
    if (getObj('remLen') != null)
    {
        var remLen = getObj('remLen');
        if (remLen.value != 0)
        {
            bad += 'You must enter another ' + remLen.value + ' characters before continuing\n';
        }
    }
    
    if (bSpellChecked == false)
    {
        bad += 'You must Spell Check your profile before saving\n';
    }
    
    if (bad != '')
    {
        msg = 'Required Information is missing or is incorrect.\n'
        msg += '-------------------------------------------------------\n'
        alert(msg + bad);
    }
    else
    {
        document.saveprofile.submit();
    }
}

//-----------------------------------------------------------------------------
function SaveEnhanced()
{
	var bad='';
    // Make sure the opening times are valid
    if (AreHoursValid() == false)
    {
        bad += 'Your Opening Times must must contain valid times.\n If you are closed on a certain day, enter \'closed\'.\n';
    }
	
	
    if (bad != '')
    {
        msg = 'A problem was detected.\n'
        msg += '-------------------------------------------------------\n'
        alert(msg + bad);
    }
    else
    {
        document.enhanced.submit();
    }
}

//-----------------------------------------------------------------------------
function InsertHours()
{
    var sunOpen = getObj('sun_open');
    if (sunOpen != null)
    {
        sunOpen.value = 'closed';
    }
    var sunClose = getObj('sun_close');
    if (sunClose != null)
    {
        sunClose.value = 'closed';
    }
    
    var monOpen = getObj('mon_open');
    if (monOpen != null)
    {
        monOpen.value = '9:00';
    }
    var monClose = getObj('mon_close');
    if (monClose != null)
    {
        monClose.value = '5:30';
    }
    
    var tueOpen = getObj('tue_open');
    if (tueOpen != null)
    {
        tueOpen.value = '9:00';
    }
    var tueClose = getObj('tue_close');
    if (tueClose != null)
    {
        tueClose.value = '5:30';
    }
    
    var wedOpen = getObj('wed_open');
    if (wedOpen != null)
    {
        wedOpen.value = '9:00';
    }
    var wedClose = getObj('wed_close');
    if (wedClose != null)
    {
        wedClose.value = '5:30';
    }
    
    var thuOpen = getObj('thu_open');
    if (thuOpen != null)
    {
        thuOpen.value = '9:00';
    }
    var thuClose = getObj('thu_close');
    if (thuClose != null)
    {
        thuClose.value = '5:30';
    }
    
    var friOpen = getObj('fri_open');
    if (friOpen != null)
    {
        friOpen.value = '9:00';
    }
    var friClose = getObj('fri_close');
    if (friClose != null)
    {
        friClose.value = '5:30';
    }
    
    var satOpen = getObj('sat_open');
    if (satOpen != null)
    {
        satOpen.value = 'closed';
    }
    var satClose = getObj('sat_close');
    if (satClose != null)
    {
        satClose.value = 'closed';
    }
}

//-----------------------------------------------------------------------------
function AreHoursValid()
{
    var bValid = true;
    if (!IsNumeric('mon_open') && getObj('mon_open').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('mon_close') && getObj('mon_close').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('tue_open') && getObj('tue_open').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('tue_close') && getObj('tue_close').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('wed_open') && getObj('wed_open').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('wed_close') && getObj('wed_close').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('thu_open') && getObj('thu_open').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('thu_close') && getObj('thu_close').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('fri_open') && getObj('fri_open').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('fri_close') && getObj('fri_close').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('sat_open') && getObj('sat_open').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('sat_close') && getObj('sat_close').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('sun_open') && getObj('sun_open').value != 'closed')
    {
        bValid = false;
    }
    if (!IsNumeric('sun_close') && getObj('sun_close').value != 'closed')
    {
        bValid = false;
    }
    
    return bValid;
}

// Listing Builder - Products
//-----------------------------------------------------------------------------
function lb_product_check()
{
    var bad = '';
    var strTitle = getObj('p_title').value;
    if (strTitle == '')
    {
        bad += 'You must enter a product title.\n';
    }    
    
    var strBadChars = GetBadChars(strTitle);
    if (strBadChars != '')
    {
        bad += 'The product title contains these disallowed characters : ' + strBadChars + '\n';
    }

    if (getObj('p_description').value == '')
    {
        bad += 'You must enter a product description.\n';
    }
    
    if (getObj('cost').value >= 32768)
    {
        bad += 'The price you have entered is too high.\n';
    }
    if (!IsNumeric('cost'))
    {
        bad += 'The price contains invalid characters.\n';
    }
    
    if (bad != '')
    {
        msg = 'Required Information is missing or is incorrect.\n'
        msg += '-------------------------------------------------------\n'
        alert(msg + bad);
    }
    else
    {
        document.addeditproduct.submit();
    }
}

//-----------------------------------------------------------------------------
function del_product_check(id,thename)
{
    var agree = confirm("Are you sure you want to delete the product : " + thename + "?");
    if (agree)
    {
		RunScript('/customscripts/pm_products_services_list.asp?delprodid=' + id,'pm_product_service_list','');
    }
}

//-----------------------------------------------------------------------------
function DeleteProdServPic() {
	getObj('image1').value='';
	getObj('prevImg1').src='/media/files/fileicons/noimage.gif';
}

// Listing Builder - Services
//-----------------------------------------------------------------------------
function lb_service_check()
{
    var bad = '';
    var strTitle = getObj('p_title').value;
    if (strTitle == '')
    {
        bad += 'You must enter a service title.\n';
    }    
    var strBadChars = GetBadChars(strTitle);
    if (strBadChars != '')
    {
        bad += 'The service title contains these disallowed characters : ' + strBadChars + '\n';
    }
    
    if (getObj('p_description').value == '')
    {
        bad += 'You must enter a description of your service.\n';
    }
    
    if (bad != '')
    {
        msg = 'Required Information is missing or is incorrect.\n'
        msg += '-------------------------------------------------------\n'
        alert(msg + bad);
    }
    else
    {
        document.addeditservice.submit();
    }
}

//-----------------------------------------------------------------------------
function del_service_check(id,thename)
{
    var agree = confirm("Are you sure you want to delete the service : " + thename + "?");
    if (agree)
    {
		RunScript('/customscripts/pm_products_services_list.asp?delservid=' + id,'pm_product_service_list','');
    }
}

//-----------------------------------------------------------------------------
function CatSelectChange(fieldname, e,DataType)
{
	catSelectField = getObj(fieldname + '_catTypeSelect');
	catSelectOptions = getObj(fieldname + '_catSelectOptions');
	
	thevalue = catSelectField.value;
	if (e.type == 'focus')
	{
		if (thevalue == 'Plumber, Florist, Gift Shop etc')
		{
			catSelectField.value = '';
			catSelectField.style.color = '#999';
		}
	}
	if (e.type == 'blur')
	{
		if (thevalue == '')
		{
			catSelectField.value = 'Plumber, Florist, Gift Shop etc';
			catSelectField.style.color = '#999';
			if (getObj('catSelectOptions') != null)
			{
				getObj('catSelectOptions').style.display = 'none';
			}
		}
	}
	if ((e.type == 'keyup'))
	{
		if (thevalue.length > 2)
		{
			if (catSelectField.style.display = 'block')
			{
				catSelectOptions.style.display = 'block';
				thevalue = Replace(thevalue, '&', '');
				var url = '/customscripts/SelectBusinessCategory.asp?keyword=' + thevalue + '&fieldname=' + fieldname + '&DataType=' + DataType;
				RunScript(url, fieldname + '_catSelectOptions','');
			}
		}
		else
		{
			catSelectOptions.style.display = 'none';
		}
	}
}

//-----------------------------------------------------------------------------
function CatSelectOptionClick(id, dataType, catTxt, fieldName)
{
	getObj(fieldName + '_catTypeSelect').style.display = 'none';
	getObj(fieldName).value = id;
	getObj(fieldName + '_Title').value = catTxt;
	getObj(fieldName + '_DispSelectedCat').style.display = 'block';
	getObj(fieldName + '_DispSelectedCat').innerHTML = catTxt + ' (<a href="javascript:CatSelectReSelect(\'' + fieldName + '\',\'' + dataType + '\',\'\',\'\');" class="lightblue">Change</a>)';
	getObj(fieldName + '_catSelectOptions').style.display = 'none';
	if (getObj(fieldName + '_PreviouslySuggestedCat'))
	{
		getObj(fieldName + '_PreviouslySuggestedCat').value = '0';
	}
}

//-----------------------------------------------------------------------------
function CatSelectReSelect(fieldName, dataType, reloadTxt, reloadDesc)
{
	var inputBox = getObj(fieldName + '_catTypeSelect');
	inputBox.style.display = 'block';
	
	if (reloadTxt == '')
	{
		reloadTxt = inputBox.value;
	}
		
	if (inputBox.value != 'Plumber, Florist, Gift Shop etc')
	{
		getObj(fieldName + '_catSelectOptions').style.display = 'block';
		reloadTxt = '';
	}
	
	if (reloadTxt != '')
	{
		getObj(fieldName + '_catTypeSelect').value = reloadTxt;
		getObj(fieldName + '_catTypeSelect').style.color = '#000';
		RunScript('/customscripts/SelectBusinessCategory.asp?keyword=' + reloadTxt + '&desc=' + reloadDesc + '&fieldname=' + fieldName + '&DataType=' + dataType, fieldName + '_catSelectOptions','');
	}
	
	getObj(fieldName + '_DispSelectedCat').innerText = '';
	getObj(fieldName + '_DispSelectedCat').style.display = 'none';
}

//-----------------------------------------------------------------------------
function CatSelectSuggest(fieldName, dataType)
{
	var url = '/customscripts/SelectBusinessCategory.asp?suggest=1&fieldname=' + fieldName + '&DataType=' + dataType;
	RunScript(url, fieldName + '_catSelectOptions','');
}

//-----------------------------------------------------------------------------
function CompleteSuggest(fieldName, dataType)
{
	var bError = false;
	var theTitle = '';
	if (getObj(fieldName + '_Suggested_catTitle') != null)
	{
		theTitle = getObj(fieldName + '_Suggested_catTitle').value;
	}
	else
	{
		bError = true;
	}
	var theDesc = '';
	if (getObj(fieldName + '_Suggested_catDesc') != null)
	{
		theDesc = getObj(fieldName + '_Suggested_catDesc').value;
	}
	else
	{
		bError = true;
	}
	
	if (bError == false)
	{
		if (theTitle == '' || theDesc == '')
		{
			alert('Please enter both a Title and Description for your Suggested Category.');
		}
		else
		{
			getObj(fieldName).value = '0';
			getObj(fieldName + '_Title').value = theTitle;
			getObj(fieldName + '_Description').value = theDesc;
			getObj(fieldName + '_catTypeSelect').style.display = 'none';
			getObj(fieldName + '_DispSelectedCat').style.display = 'block';
			getObj(fieldName + '_DispSelectedCat').innerHTML = 'Suggested Category - ' + theTitle + ' (<a href="javascript:CatSelectReSelect(\'' + fieldName + '\',\'' + dataType + '\',\'' + theTitle + '\',\'' + theDesc + '\');">Change</a>)';
			getObj(fieldName + '_catSelectOptions').style.display = 'none';
		}
	}
	else
	{
		alert('An error has occured.\n- Please select an existing category\n- You can suggest a category once you have completed this form.');
	}
}

//-----------------------------------------------------------------------------
function OpenTBWindow()
{
	var membersOf = getObj('tradebodies').value;
	var args = 'toolbar=0,status=1,menubar=0,scrollbars=1,resizable=0';
	OpenCenteredWindow('/customscripts/SelectTradeBodies.asp?membersof=' + membersOf, 375, 650, null, args)
}

//-----------------------------------------------------------------------------
function trackclick(clickType, id)
{
    // Affillate Click Tracker
    if (document.images)
    { 
        (new Image()).src = "/customscripts/systemfunctions/trackclick.asp?ctype=" + clickType + "&id=" + id;
    }
    return true;
}

//Pager Drop Down in all Listings
//-----------------------------------------------------------------------------
function SelectPage(theURL, topbottom)
{
	// Changes the page of a list of pages
	thepageselect = getObj('pg');
	thenewpg = thepageselect.options[thepageselect.selectedIndex].value;
	location.href = thenewpg;
}

//-----------------------------------------------------------------------------
function TextCounter(fieldName, countFieldName, maxLimit, reqLimit)
{
	var textField = getObj(fieldName);
	var countField = getObj(countFieldName);
	
    if (textField.value.length > maxLimit) 
    {   // If too long, trim it
        textField.value = textField.value.substring(0, maxLimit);
    }
    else 
    {   // Otherwise, update 'characters left' counter
        countField.value = reqLimit - textField.value.length;
        if (countField.value < 0)
        {
            countField.value = 0
        }
    }
}

//-----------------------------------------------------------------------------
function DisplayDivForTime(thediv, showlen)
{
    getObj(thediv).style.display = 'block';
    setTimeout('getObj(\'' + thediv + '\').style.display = \'none\';', showlen);
}

//-----------------------------------------------------------------------------
function DoReject()
{
    var bad = '';
    
    // Loop through check boxes to make sure at least one has been selected
    
    var arrInputs = document.getElementsByTagName('input');
    var bOneChecked = false;
    for (i = 0; i < arrInputs.length; i++)
    {
        if (arrInputs[i].className == 'rejection')
        {
            if (arrInputs[i].checked == true)
            {
                //alert(getObj('desc_' + arrInputs[i].name).value);
                bOneChecked = true;
            }
        }
    }
    if (bOneChecked == false)
    {
        bad = 'Please select at least one reject reason.';
    }
    
    if (bad != '')
    {
        alert(bad);
    }
    else
    {
        document.reject.submit();
    }
}

//-----------------------------------------------------------------------------
// 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 RevertProfile(theId, adpass)
{
    // Convert the profile wizard type profile to the cleaned normal text area
    var agree = confirm('Are you sure?');
    if (agree == true)
    {
        // Refresh the page with the revert flag set
        location.href = '/admin/admin_listings.asp?action=edit&adpass=' + adpass + '&theid=' + theId + '&revert=1';
    }
}

//-----------------------------------------------------------------------------
function ConfirmWebLink()
{
	var webaddress = getObj('website').value;
	var allowWebsite = getObj('allow_website').value;
	
	if (webaddress != '' && allowWebsite != 'true')
	{
		var chk_webaddress = Trim(webaddress.toLowerCase());
		chk_webaddress = Replace(chk_webaddress,'http://','');
		chk_webaddress = Replace(chk_webaddress,'https://','');
		chk_webaddress = Replace(chk_webaddress,'index.html','');
		chk_webaddress = Replace(chk_webaddress,'index.htm','');
		chk_webaddress = Replace(chk_webaddress,'index.php','');
		chk_webaddress = Replace(chk_webaddress,'home.html','');
		chk_webaddress = Replace(chk_webaddress,'home.htm','');
		chk_webaddress = Replace(chk_webaddress,'default.htm','');
		chk_webaddress = Replace(chk_webaddress,'default.html','');
		chk_webaddress = Replace(chk_webaddress,'/default.aspx','');
		chk_webaddress = Replace(chk_webaddress,'default.asp','');
		chk_webaddress = Replace(chk_webaddress,'home.php','');
		
		strLen = chk_webaddress.length;
		if ((chk_webaddress.substr(strLen-1,1)) == '/')
		{
			chk_webaddress = chk_webaddress.substr(0,strLen-1)
		}
		if (chk_webaddress.indexOf("/") > 0)
		{
			alert('That doesn\'t appear to be your homepage.\n\n- Only links on your homepage are accepted.\n- Link pages or other pages on your site won\'t be accepted.\n- Homepages that re-direct to other URLs may also cause problems.\n\nPlease contact us if the link on your homepage is not being found.')
			getObj('upgrade_disabled').style.display = 'block';
		}
		else
		{
			getObj('iframe-line').style.display = 'block';
			getObj('pagescan').style.display = 'block';
			getObj('scanning').style.display = 'block';
			getObj('pagescan').src = '/customscripts/pm_pagescan.asp?url=' + webaddress;
		}
	}
	else if (webaddress != '' && allowWebsite == 'true')
	{
		getObj('iframe-line').style.display = 'block';
		getObj('pagescan').style.display = 'block';
		getObj('scanning').style.display = 'block';
		getObj('pagescan').src = '/customscripts/pm_pagescan.asp?url=' + webaddress;
	}
	else if (webaddress == '')
	{
		alert("A web address (URL) has not been entered.");
	}
}

//-----------------------------------------------------------------------------
function showFAQ(id, maxfaqs)
{
	// Turn off all other faqs.
	var faq_title;
	for (var i = 1; i <= maxfaqs; i++)
	{
		getObj('faq_' + i).style.display = 'none';
		faq_title = getObj('faq_title_' + i);
		if (faq_title != null)
		{
			faq_title.style.backgroundColor = 'transparent';
			faq_title.style.paddingTop = '5px';
			faq_title.style.marginTop = '0px';
		}
	}
	getObj('faq_' + id).style.display = 'block';
	faq_title = getObj('faq_title_' + id);
	if (faq_title != null)
	{
		faq_title.style.backgroundColor = '#F2F4F6';
		faq_title.style.paddingTop = '10px';
		faq_title.style.marginTop = '10px';
	}
}

//-----------------------------------------------------------------------------
function showProductService(id,maxps) {
	//Turn off all other faqs.
	for (i = 1; i <= maxps; i++) {
		getObj('ps_' + i).style.display = 'none';
		getObj('prodlink_' + i).innerHTML = 'View Details';
		getObj('prodtitle_' + i).style.backgroundColor = '';
		getObj('prodlink_' + i).href = 'javascript:showProductService(' + i + ',' + maxps + ');';
		getObj('prodtitle_' + i).style.fontWeight = 'normal';
	}
	getObj('ps_' + id).style.display = 'block';
	getObj('prodlink_' + id).innerHTML = 'Hide Details';
	getObj('prodlink_' + id).href = 'javascript:hideProductService(' + id + ',' + maxps + ');';
	getObj('prodtitle_' + id).style.backgroundColor = '#eeeeee';
	getObj('prodtitle_' + id).style.fontWeight = 'bold';
}

//-----------------------------------------------------------------------------
function hideProductService(id,maxps) {
	getObj('ps_' + id).style.display = 'none';
	getObj('prodlink_' + id).innerHTML = 'View Details';
	getObj('prodlink_' + id).href = 'javascript:showProductService(' + id + ',' + maxps + ');';
	getObj('prodtitle_' + id).style.backgroundColor = '';
	getObj('prodtitle_' + id).style.fontWeight = 'normal';
}

//-----------------------------------------------------------------------------
function showComparisonInfo(id,maxitems) {
	for (i = 1; i <= maxitems; i++) {
		getObj('info_' + i).style.display = 'none';
	}
	getObj('info_' + id).style.display = 'block';
}

function hideComparisonInfo(maxitems) {
	for (i = 1; i <= maxitems; i++) {
		getObj('info_' + i).style.display = 'none';
	}
}

//-----------------------------------------------------------------------------
function IsUpperCase(strValue)
{
    if (strValue.toUpperCase() == strValue)
    {
        return true;
    }
    
    return false;
}

//-----------------------------------------------------------------------------
function IsTitleCase(strValue)
{
    // Convert string to title case and compare
    // First character should be upper, followed by all characters after a space
    var strTitled = TitleCase(strValue, true);
    if (strTitled == strValue)
    {
        return true;
    }
    
    return false;
}

//-----------------------------------------------------------------------------
// Converts 'a fine old day' into 'A Fine Old Day' when bWholeWord == true,
// Converts 'a fine old day' into 'A fine old day' when bWholeWord == false
//-----------------------------------------------------------------------------
function TitleCase(strValue, bWholeWord)
{
    var strTitled = '';
    var thisChar = '';
    var lastChar = '';
    for (var i = 0; i < strValue.length; i++)
    {
        thisChar = strValue.charAt(i);
        if (i == 0)
        {
            strTitled += thisChar.toUpperCase();
        }
        else
        {
            if (bWholeWord == true)
            {
                if (lastChar == ' ')
                {
                    strTitled += thisChar.toUpperCase();
                }
                else
                {
                    strTitled += thisChar.toLowerCase();
                }
            }
            else
            {
                strTitled += thisChar.toLowerCase();
            }
            lastChar = thisChar;
        }
    }

    return strTitled;
}


//-----------------------------------------------------------------------------
//Profile Wizard
//-----------------------------------------------------------------------------
function openProfileWiz(paraID, ParaType, ListingID, AddEdit, group, userType)
{
	var action='';
	
	if (AddEdit == 'A')
	{
		action='&action=add';
	}
	else
	{
		//Hide Edit Del Div.
		action='&action=edittext&directedit=1';
		var editDelDiv = getObj('EditDelDiv_'+ paraID);
		if (editDelDiv != null)
		{
		getObj('EditDelDiv_'+ paraID).style.display='none';
	}
	}
    OpenCenteredWindow('/customscripts/pm_profilewizard.asp?para=' + paraID + '&paratype=' + ParaType + '&groups=' + group + '&userType=' + userType + '&Lid=' + ListingID + action, '490', '750', null, 'status=no, resizable=no, scrollbars=no');
}

//-----------------------------------------------------------------------------
function showEditDelDiv(paraID,e)
{
	var EDDiv = getObj('EditDelDiv_para' + paraID);
	if (EDDiv != null)
	{
	    var ParaText = getObj('para' + paraID);
    	
	    //Highlight Para
	    for (var i = 1; i < 6; i++)
	    {
		    getObj('para' + i).style.color = '#000';
	    }
	    ParaText.style.color = '#CC0000';
    	
	    //Show Edit / Delete Links
	    var divs=document.getElementsByTagName('div');
	    var len=divs.length;
    	
	    for (i = 0; i < len; i++)
	    {
		    d_id=divs[i].id;
    		
		    if (d_id.indexOf('EditDelDiv_para') != -1)
		    {
			    divs[i].style.display='none';
		    }
	    }
	    // Get mouse click position
        var scrollX, scrollY;
        if (document.all)
        {
            if (!document.documentElement.scrollLeft)
                scrollX = document.body.scrollLeft;
            else
                scrollX = document.documentElement.scrollLeft;

            if (!document.documentElement.scrollTop)
                scrollY = document.body.scrollTop;
            else
                scrollY = document.documentElement.scrollTop;
        }   
        else
        {
            scrollX = window.pageXOffset;
            scrollY = window.pageYOffset;
        }

        pos_x = e.clientX + scrollX;
        pos_y = e.clientY + scrollY;
    	
	    EDDiv.style.display = 'block';
	    EDDiv.style.left = (pos_x) + 'px';
	    EDDiv.style.top = (pos_y) + 'px';
	}
	
	return false;
}
//-----------------------------------------------------------------------------
function clickoffEditDelOption(e) {
    var scrollX, scrollY;
    if (document.all)
    {
        if (!document.documentElement.scrollLeft)
            scrollX = document.body.scrollLeft;
        else
            scrollX = document.documentElement.scrollLeft;

        if (!document.documentElement.scrollTop)
            scrollY = document.body.scrollTop;
        else
            scrollY = document.documentElement.scrollTop;
    }   
    else
    {
        scrollX = window.pageXOffset;
        scrollY = window.pageYOffset;
    }
        
    pos_x = e.clientX + scrollX;
    pos_y = e.clientY + scrollY;
	
	//thediv.style.display='block';
	var divs = document.getElementsByTagName('div');
	var len = divs.length;
	for(var i = 0; i < len; i++)
	{
		d_id = divs[i].id;
		if (d_id.indexOf('EditDelDiv_para') != -1)
		{
			if (getObj(d_id).style.display == 'block')
			{
				var x_lowerlimit = parseInt(Replace((getObj(d_id).style.left),'px',''));
				var x_upperlimit = x_lowerlimit + 140;
				var y_lowerlimit = parseInt(Replace((getObj(d_id).style.top),'px',''));
				var y_upperlimit = y_lowerlimit - 30;
				
				if ((pos_x < x_lowerlimit) || (pos_x > x_upperlimit))
				{
					getObj(d_id).style.display = 'none';
				}
			}
		}
	}
}

//-----------------------------------------------------------------------------
function clearProilePara(paraID, listingId, userType)
{
    var msg = 'Are you sure you want to delete the text in this paragraph?\n';
    msg += 'Make sure you save any changes before doing this.';
    var agree = confirm(msg);
    if (agree)
    {
        switch (userType)
        {
            case '':
                location.href = '/myfreeindex(clear-para)_' + paraID + '.htm';
                break;
            case 'admin_listing':
                location.href = '/admin/admin_listings.asp?action=clearpara&theid=' + listingId + '&paraID=' + paraID + '&adpass=%D6%F4%8BW0%7D%B2%C4%9B%0F%A3%B8%FC'
                break;
            case 'admin_quick':
                location.href = '/admin/admin_quick.asp?action=clearpara&theid=' + listingId + '&paraID=' + paraID + '&adpass=%D6%F4%8BW0%7D%B2%C4%9B%0F%A3%B8%FC'
                break;
        }
    }
}

//-----------------------------------------------------------------------------
function showtag_Options(tagid,e)
{
	var thediv = getObj('DIV_OPTIONS_' + tagid);
	
	// Get mouse click position
    pos_x = e.clientX?(e.clientX):e.clientX;
    pos_y = e.clientY?(e.clientY):e.clientY;
	thediv.style.display='block';
	thetoptd = getObj('wordchoice_options_top_' + tagid);
	
	if (pos_x > 400)
	{
		// Show selected box and change to the right.
		thediv.style.left = (pos_x - 150) + 'px';
		thediv.style.top = (pos_y) + 'px';
		thetoptd.style.backgroundImage = 'url(/fx/wordchoice_option_top_right.gif)';
	}
	else
	{
		// Show selected box to the left
		thediv.style.left = (pos_x - 35) + 'px';
		thediv.style.top = (pos_y) + 'px';
		thetoptd.style.background = 'url(/fx/wordchoice_option_top.gif)';
	}
	
	// Unhilight all links
	var links = document.getElementsByTagName('a');
	var len = links.length;
	for (var i = 0; i < len; i++)
	{
		l_id = links[i].id;
		
		if (l_id.indexOf('LSPAN_') != -1)
		{
			links[i].style.backgroundColor = 'transparent';
		}
	}

	// Highlight Link Word
	var targetSpan = getObj('LSPAN_' + tagid);
	if (targetSpan != null)
	{
	    targetSpan.style.backgroundColor = '#FFE066';
	}
	
	// Set focus into UserEntry_ field if there is one and if its displayed
	var textInput = getObj('UserEntry_' + tagid);
	if (textInput != null)
	{
	    if (textInput.style.display != 'none')
	    {
	        textInput.focus();
	    }
	}
	
	// Set global values that can be accessed when user clicks off
	userclicked = tagid;
	lastbox = tagid;
	
	previousboxOriginalText = lastboxOriginalText;
	previousboxOriginalTextColour = lastboxOriginalColour;
	
	if (document.all)
	{
		lastboxOriginalText = getObj('LSPAN_' + tagid).innerText;
	}
	else
	{
		lastboxOriginalText = getObj('LSPAN_' + tagid).textContent;
	}
	lastboxOriginalColour = getObj('LSPAN_' + tagid).style.color;
}

//-----------------------------------------------------------------------------
function setTagText(tagid, thetext, clickortype)
{
	var trimmedText = thetext;
	var thediv = getObj('DIV_OPTIONS_' + tagid);
	var targetSpan = getObj('LSPAN_' + tagid);
	var bad = '';
    
    if (clickortype == 'click')
    {
		if (getObj('UserEntry_' + tagid)) {
			getObj('UserEntry_' + tagid).value = thetext;
		}
		thediv.style.display = 'none';
		targetSpan.style.backgroundColor = 'transparent';
	}
		
    // Set the target content
	if (document.all)
	{
	     targetSpan.innerText = trimmedText;
	}
	else
	{
	    targetSpan.textContent = trimmedText;
	    targetSpan.innerText = trimmedText; // needs also to be set for Mac Safari
	}
	targetSpan.style.color = '#0000ff';
	
	// Get the height of the main div
	var mainDiv = getObj('paragraph_editor');
	if (mainDiv != null)
	{
	    if (mainDiv.clientHeight > 120)
	    {
	        mainDiv.style.overflowY = 'scroll';
	    }
	    else
	    {
	        mainDiv.style.overflowY = 'auto';
	    }
	}
	
	// Process key downs to hide div if Esc or Enter pressed
	if (lastKeyPressed == 27 || lastKeyPressed == 13) // Escape = 27, Enter = 13
	{   // hide the div
	    ProcessTagText(tagid);
		lastKeyPressed = 0;
	    return false;
	}
}

//-----------------------------------------------------------------------------
function WizardKeyPress(e)
{
    if (!e)
    {
        e = window.event; // for ie
    }
    lastKeyPressed = e.keyCode;
}

//-----------------------------------------------------------------------------
function TrimText(strText)
{
    // Trim twice - it seems to need this to trim leading and trailing spaces
    var trimmedText = Trim(strText);
    trimmedText = Trim(trimmedText);
    
    // Also, remove any full stops at the end
    var lastChar = trimmedText.charAt(trimmedText.length - 1);
    if (lastChar == '.')
    {
        trimmedText = trimmedText.substr(0, trimmedText.length - 1);
    }
    
    return trimmedText;
}

//-----------------------------------------------------------------------------
function saveParagraphContent(allowedWords)
{
	var targetDiv = getObj('hiddencontainer');
	var sourcedivContent = getObj('paragraph_editor').innerHTML;
	
	// For ie, the color is expressed as #cc0000.
	// In ns, the color is expressed as rgb(...)
	if (sourcedivContent.indexOf("#cc0000") > 0 || sourcedivContent.indexOf("rgb(204, 0, 0)") > 0)
	{
		alert("Please make sure that all of the Red Words have been filled in.");
	}
	else
	{
        // Continue to the save
	    targetDiv.value = sourcedivContent;
	    document.paragraph_editor_form.submit();
	}
}

//-----------------------------------------------------------------------------
function clickoffcloseboxes(e) {
    pos_x = e.clientX?(e.clientX):e.clientX;
    pos_y = e.clientY?(e.clientY):e.clientY;
	var theboxtoprocess = '';
	
	var divs=document.getElementsByTagName('div');
	var len=divs.length;
	for(var i=0;i<len;i++) {
		d_id=divs[i].id;
		
		if(d_id.indexOf('DIV_OPTIONS_')!=-1) {
			if (getObj(d_id).style.display == 'block') {
				
				boxleft = parseInt(Replace((getObj(d_id).style.left),'px',''));
				boxtop = parseInt(Replace((getObj(d_id).style.top),'px',''));
		
				//var textlinkObj = getObj('LSPAN_' + Replace(d_id,'DIV_OPTIONS_',''));
		
				//box below
				var x_lowerlimit = parseInt(Replace((getObj(d_id).style.left),'px',''));
				var x_upperlimit = x_lowerlimit + 188;
				
				if (userclicked == '') {
					//User did not click on another link
					//check to see if click is outside a currently open box range.
					if ((pos_x < x_lowerlimit) || (pos_x > x_upperlimit)) {
						theboxtoprocess = Replace(d_id,'DIV_OPTIONS_','');
					}
				} else {
					//look for open divs that are not the one the user has last clicked on.
					if (Replace(d_id,'DIV_OPTIONS_','') != lastbox) {
						theboxtoprocess = Replace(d_id,'DIV_OPTIONS_','');
					}
				}
			}
		}
		
	}
	
	// Process Tag Text
	if (theboxtoprocess != '')
	{
	    ProcessTagText(theboxtoprocess);
	}
	
	userclicked = '';
}

//-----------------------------------------------------------------------------
function ProcessTagText(theboxtoprocess)
{
    var bad = '';
	var targetSpan = getObj('LSPAN_' + theboxtoprocess);
	var textbox = getObj('UserEntry_' + theboxtoprocess);
	var innerText = '';
	if (document.all)
	{
	    innerText = targetSpan.innerText; // ie
	}
	else
	{
	    innerText = targetSpan.textContent; // ns
	}
	
	var trimmedText = TrimText(innerText);
	
    var strBadChars = GetBadChars(trimmedText);
    if (strBadChars != '')
    {
        bad += 'Please do not use the following dis-allowed characters : ' + strBadChars + '\n';
    }
	if (ContainsWebAddress(trimmedText))
	{
        bad += 'Please do not enter web addresses\n';
	}
    if (bad != '')
    {
		//if user has clicked on another box - Close it and refocus on problem box.
		if (theboxtoprocess != lastbox)
		{
			getObj('DIV_OPTIONS_' + lastbox).style.display = 'none';
			getObj('LSPAN_' + lastbox).style.backgroundColor = 'transparent';
			getObj('LSPAN_' + theboxtoprocess).style.backgroundColor = '#FFE066';
		}
		
        msg = 'A problem was detected.\n'
        msg += '-------------------------------------------------------\n'
        alert(msg + bad);
	}
	else
	{
	    // Set the case of the content
	    if (getObj('text_case_' + theboxtoprocess))
	    {
		    var textCase = getObj('text_case_' + theboxtoprocess).value;
			switch (textCase)
		    {
		        case 'normal':
	                // If it's all upper case, lower case it
	                if (IsUpperCase(trimmedText))
	                {
	                    trimmedText = trimmedText.toLowerCase();
	                }
	                else if (IsTitleCase(trimmedText))
	                {   // If it's PCase, lower case it
	                    trimmedText = trimmedText.toLowerCase();
	                }
	                break;
	            case 'start':
	                // If it's the start of a sentence, always PCase it
	                trimmedText = TitleCase(trimmedText, false);
	                break;
	            case 'leave':
	                break; // do nothing
		    }
	    }
	    // Set the target content and close the box
		if (trimmedText == '')
		{
			if (previousboxOriginalText !='')
			{
				trimmedText = previousboxOriginalText;
				targetSpan.style.color = previousboxOriginalTextColour;
			}
			else
			{
				trimmedText = lastboxOriginalText;
				targetSpan.style.color = lastboxOriginalColour;
			}
		}
		
		if (document.all)
		{
		    targetSpan.innerText = trimmedText;
		}
		else
		{
		    targetSpan.textContent = trimmedText;
		    targetSpan.innerText = trimmedText; // needs also to be set for Mac Safari
		}
		getObj('DIV_OPTIONS_' + theboxtoprocess).style.display = 'none';
		targetSpan.style.backgroundColor = 'transparent';
	}
}

//-----------------------------------------------------------------------------
function SaveCategory(bApprove, catid, cat, theid, bJobCat, adminPassword)
{
    var jobCatAction = '';
    if (bJobCat == true)
    {
        jobCatAction = '1';
    }
    if (bApprove == true)
    {
        document.forms.cat.action = '/admin/admin_cats.asp?action=savecatapprove&theid=' + theid + '&catid=' + catid + '&cat=' + cat + '&jobcat=' + jobCatAction + '&adpass=' + adminPassword;
    }
    else
    {
        document.forms.cat.action = '/admin/admin_cats.asp?action=savecat&theid=' + theid + '&catid=' + catid + '&cat=' + cat + '&jobcat=' + jobCatAction + '&adpass=' + adminPassword;
    }
    document.forms.cat.submit();
}

//-----------------------------------------------------------------------------
function displayProfileProducts(id,col)
{
	run1 = 'customscripts'
	run2 = 'profile_products.asp'
	run3 = '?id=' + id + '&col=' + col
	RunScript(run1 + '/' + run2 + run3,'products','');
}

//-----------------------------------------------------------------------------
function UpdateReviews(customerReviewId, bCompanyReview)
{
	if (bCompanyReview == true)
	{
		getObj('review_to_save_id').value = customerReviewId;
		document.reviews.submit();
	}
	else
	{
		getObj('written_to_save_id').value = customerReviewId;
		document.written.action = '/myfreeindex(reviews)_' + customerReviewId + '.htm';
		document.written.submit();
	}
}

//-----------------------------------------------------------------------------
function ViewReviewItem(customerReviewId, bShow)
{
	// Close all open items
	var arrDivs = document.getElementsByTagName('div');
    var len = arrDivs.length;
    var review_details_div = null;
    var review_details_td = null;
    
	for (var i = 0; i < len; i++)
	{
	    var divname = arrDivs[i].id;
        if (divname.lastIndexOf("review_details_div_") > -1)
        {
			var divID = divname.substr(divname.lastIndexOf("_") + 1);
			review_details_div = arrDivs[i];
			review_details_td = getObj('review_details_td_' + divID);
			
			review_details_div.style.display = 'none';
			review_details_td.innerHTML = '<a href=\'javascript:ViewReviewItem(' + divID + ',true);\'><img src=\'/fx/plus.gif\' border=\'0\' alt=\'View details\' /></a>&nbsp;<br />';	
		}	
	}
		
	if (bShow == true)
	{
		// Open the selected item
		review_details_div = getObj('review_details_div_' + customerReviewId);
		review_details_td = getObj('review_details_td_' + customerReviewId);
		review_details_div.style.display = '';
		review_details_td.innerHTML = '<a href=\'javascript:ViewReviewItem(' + customerReviewId + ',false);\'><img src=\'/fx/minus.gif\' border=\'0\' alt=\'Hide details\' /></a>&nbsp;<br />';
	}
}

//-----------------------------------------------------------------------------
function ValidateReview()
{
    document.write_review.submit();
}


//-----------------------------------------------------------------------------
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';
    }
}


//-----------------------------------------------------------------------------
function RefreshCatInfo(catId, bJobCat)
{
    var cat3 = getObj('cat3').value;
    if (bJobCat == false)
    {
        var sing = getObj('meta_single').value;
        var plur = getObj('meta_plural').value;
        var notDefault = getObj('Meta_NotDefault').checked;
        var notDefaultValue = 'off';
        if (notDefault == true)
        {
            notDefaultValue = 'on';
        }
        RunScript('/admin/admin_catinfo.asp?catId=' + catId + '&cat3=' + cat3 + '&sing=' + sing + '&plur=' + plur + '&notDefault=' + notDefaultValue, 'cat_info', '');
    }
    else
    {
        RunScript('/admin/admin_catinfo.asp?catId=' + catId + '&cat3=' + cat3 + '&sing=' + sing + '&plur=' + plur + '&jobcat=1', 'cat_info', '');
    }
}

//-----------------------------------------------------------------------------
// Displays trade body list
//-----------------------------------------------------------------------------
function ShowTradeBodies(selectedBodies)
{
	var url = '/customscripts/ShowTradeBodies.asp?selected=' + selectedBodies;
	RunScript(url, 'tradebodies_disp', '');
	
	var tradebodies_disp = getObj('tradebodies_disp');
	if (tradebodies_disp != null)
	{
		tradebodies_disp.style.display = 'block';
	}
}

//-----------------------------------------------------------------------------
// Jobs
//-----------------------------------------------------------------------------
function ShowJobDuration()
{
	if (getObj('jobType').selectedIndex > 2)
	{
		getObj('duration').style.display = 'block';
		getObj('hoursperweek').style.display = 'none';
	}
	else
	{
		getObj('duration').style.display = 'none';
		
		if (getObj('jobType').selectedIndex == 2)
		{
			getObj('hoursperweek').style.display = 'block';
		}
		else
		{
			getObj('hoursperweek').style.display = 'none';
		}
	}
}

//---------------------------------------------------------------------------------
function ShowProfileLength()
{
	var descLen = 0;
	if (document.all)
	{   // ie
	    descLen += getObj("joboverview").innerText.length;
	    descLen += getObj("jobduties").innerText.length;
	    descLen += getObj("jobskills").innerText.length;
	}
	else
	{   // ns
	    descLen += getObj("joboverview").value.length;
	    descLen += getObj("jobduties").value.length;
	    descLen += getObj("jobskills").value.length;
	}
	
	if (descLen >= 400)
	{
		getObj('profilelength').innerHTML = '<font style="color:#090;">Current characters = ' + descLen + '</font>';
	}
	else
	{
		getObj('profilelength').innerHTML = '<font style="color:#900;">Current characters = ' + descLen + '</font>';
	}
}

//---------------------------------------------------------------------------------
function ShowHideJob(jobid)
{
	// Close all divs first
	var arrDivs = document.getElementsByTagName('div');
    for (i = 0; i < arrDivs.length; i++)
    {
		var divname = arrDivs[i].id;
        if (divname.indexOf("job_") > -1)
        {
			var divID = divname.substr(divname.indexOf("_") + 1);
			if (divID != jobid)
			{
				arrDivs[i].style.display = 'none';
				getObj('plusminus_' + divID).src = '/fx/plus.gif';
			}
		}
	}
	
	var jobDiv = getObj('job_' + jobid);
	var plusMinus = getObj('plusminus_' + jobid);
	
	if (jobDiv.style.display == 'none')
	{
		// Show div & change plus to minus
		jobDiv.style.display = 'block';
		plusMinus.src = '/fx/minus.gif';
	}
	else
	{
		// Hide div & change minus to plus
		jobDiv.style.display = 'none';
		plusMinus.src = '/fx/plus.gif';
	}
}


//---------------------------------------------------------------------------------
function ViewCoveringLetter(applicantId)
{
    OpenCenteredWindow('customscripts/pm_applicant_letter.asp?applicantId=' + applicantId, '500', '500', null, 'status=yes, resizable=no, scrollbars=no');
}

//---------------------------------------------------------------------------------
function ChangeUKBased()
{
    var uk_based = getObj('uk_based');
    var uk_based_yes = getObj('uk_based_yes');
    var uk_based_no = getObj('uk_based_no');
    
    if (uk_based[0].checked == true)
    {
        uk_based_yes.style.display = 'block';
        uk_based_no.style.display = 'none';
    }
    else
    {
        uk_based_yes.style.display = 'none';
        uk_based_no.style.display = 'block';
    }
}

//-----------------------------------------------------------------------------
function UploadCV()
{
    OpenCenteredWindow('customscripts/cv_upload.asp', '250', '380', null, 'status=yes, resizable=no, scrollbars=no');
}

//-----------------------------------------------------------------------------
function SaveJob(bNewJob)
{
    var bad = '';
    
    if (bSpellChecked == false && bChangesMade == true && bNewJob == true)
    {
        bad += 'You must Spell Check your job text before saving\n';
    }
    
    if (bad != '')
    {
        msg = 'Required Information is missing or is incorrect.\n'
        msg += '-------------------------------------------------------\n'
        alert(msg + bad);
    }
    else
    {
        document.addjob.submit();
    }
}

//-----------------------------------------------------------------------------
function CheckNameChange()
{
    var bad = '';
    if (getObj('name').value == '')
    {
        bad += '- Please enter your full name.\n';
    }
    	
    if (bad != '')
    {
        alert(bad);
    }
    else
    {
        document.changename.submit();
    }
}

//-----------------------------------------------------------------------------
function CheckEmailChange()
{
    var bad = '';
    if (getObj('email1').value=="" || getObj('email2').value=="")
    {
        bad += '- Please complete both email boxes with your new email address.\n';
    }
    else
    {
	    if (EmailCheck(getObj('email1').value) == false)
	    {
    	    bad += '- Your New Email Address appears to be an invalid !.\n';
		}
		else
		{
		    if (getObj('email1').value != getObj('email2').value)
		    {
    		    bad += '- The email addresses you have specified are different !.\n';
    		}
		}
	}
	
    if (bad != '')
    {
        alert(bad);
    }
    else
    {
        document.changeusername.submit();
    }
}

//-----------------------------------------------------------------------------
function CheckPasswordChange()
{
    var bad = '';
    var currentPass = getObj('currentpass');
    var newPass1 = getObj('newpass1');
    var newPass2 = getObj('newpass2');
    
    if (currentPass != null)
    {
        if (currentPass.value == '' || newPass1.value == '' || newPass2.value == '')
        {
            bad += 'Please complete all the fields.\n';
        }
    }
    else
    {
        if (newPass1.value == '' || newPass2.value == '')
        {
            bad += 'Please complete all the fields.\n';
        }
    }
    if (bad == '')
    {
	    if (newPass1.value != newPass2.value)
	    {
   		    bad += 'The passwords you have specified are different!\n';
		}
		else
		{
		    if (newPass1.value.length < 7)
		    {
        		bad += 'Your New Password must be at least 7 characters in length.\n';
			}
		}
	}
	
    if (bad != '')
    {
        alert(bad);
    }
    else
    {
        document.changepassword.submit();
    }
}

//-----------------------------------------------------------------------------
function ChangeAccountSettingState(fieldName, currentState)
{
	getObj('FieldtoChange').value = fieldName;
	if (currentState == 0)
	{
		getObj('SetState').value = 1;
	}
	else
	{
		getObj('SetState').value = 0;
	}
	
	document.accountsettings.submit();
}

//-----------------------------------------------------------------------------
// Standard Google Ad Script
//-----------------------------------------------------------------------------
function google_ad_request_done(google_ads)
{
	if (google_ads.length == 0)
	{
		return;
	}
	
	var s = '';
	
	// Display ads in normal way by doing a document.write
	if (google_ads.length == 1)
	{
		s += '<a href=\"' + google_info.feedback_url + '\" class="g_adsby">Ads by Google</a><br>';
		s += '<div class="googleaddiv" onmouseover="this.style.background=\'#F7F7F2\';" onmouseout="this.style.background=\'#fff\';">';
		s += '<a target="_blank" style="text-decoration:none;" href="' + google_ads[0].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[0].visible_url + '\'"><font class="g_link" style="font-size:18px;">' + google_ads[0].line1 + '</font></a>';
		s += '<font class="g_text" style="font-size:13px;">' + google_ads[0].line2 + ' ' + google_ads[0].line3 + '</font><br />';
		s += '<a target="_blank" style="text-decoration:none;" href="' + google_ads[0].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[0].visible_url + '\'"><font class="g_url">' + google_ads[0].visible_url + '</font></a>';
		s += '</div>';
	}
	else if (google_ads.length > 1)
	{
		s += '<a href=\"' + google_info.feedback_url + '\" class="g_adsby">Ads by Google</a>';

		for(var i = 0; i < google_ads.length; i++)
		{
			s += '<div class="googleaddiv" onmouseover="this.style.background=\'#F7F7F2\';" onmouseout="this.style.background=\'#fff\';">';
			s += '<a target="_blank" style="text-decoration:none;" href="' + google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[i].visible_url + '\'"><font class="g_link">' + google_ads[i].line1 + '</font></a><br />';
			s += '<font class="g_text">' + google_ads[i].line2 + ' ' + google_ads[i].line3 + '</font><br />';
			s += '<a target="_blank" style="text-decoration:none;" href="' + google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[i].visible_url + '\'"><font class="g_url">' + google_ads[i].visible_url + '</font></a>';
			s += '</div>';
		}
	}
    document.write(s);
	
    return;
}

//-----------------------------------------------------------------------------
// Google AdSense for Search script
//
// This function is required. It processes the google_ads JavaScript object,
// which contains AFS ads relevant to the user's search query. The name of
// this function <i>must</i> be <b>google_afs_request_done</b>. If this
// function is not named correctly, your page will not display AFS ads.
//-----------------------------------------------------------------------------
function google_afs_request_done(google_ads)
{
	// Verify that there are actually ads to display.
	var google_num_ads = google_ads.length;
	if (google_num_ads <= 0)
	{
		return;
	}

	var s = '';
	// Get the divs to fill
	// Search divs with class name google_afs_ad
	// The id of the div will be of the format google_ad_17_2
	// (where 2 is the number of ads to display in this block and 17 a unique id)
	var divs = document.getElementsByTagName('div');
    
	var divToFill = null;
	var strAdsInDiv = '';
	var nAdsInDiv = 0;
	var nAdsDisplayed = 0;
    for(var j = 0; j < divs.length; j++)
    {
	    if (divs[j].className == 'google_afs_ad')
	    {
			if (divs[j].innerHTML.length <= 6) // Div is empty - needs filling
			{
				divToFill = divs[j]; // next empty ad div
				// Number of ads to display is in div id as _x - get last _
				strAdsInDiv = divToFill.id.substr(divToFill.id.lastIndexOf('_') + 1);
				nAdsInDiv = new Number(strAdsInDiv);
				
				// Fill the div with that many ads
				if (nAdsDisplayed < google_num_ads)
				{
					if (google_ads.length == 1)
					{
						s = '<div class="afs_adsby"><a href="http://services.google.com/feedback/online_hws_feedback" class="afs_g_adsby">Ads by Google</a></div>';
						s += '<div class="afs_googleaddiv" onmouseover="this.style.background=\'#E7EBF1\';" onmouseout="this.style.background=\'#F3F5F8\';">';
						s += '<a target="_blank" style="text-decoration:none;" href="' + google_ads[0].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[0].visible_url + '\'"><font class="afs_g_link" style="font-size:18px;">' + google_ads[0].line1 + '</font></a><br />';
						s += '<font class="afs_g_text" style="font-size:13px;">' + google_ads[0].line2 + '</font><br />';
						s += '<a target="_blank" style="text-decoration:none;" href="' + google_ads[0].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[0].visible_url + '\'"><font class="g_url">' + google_ads[0].visible_url + '</font></a>';
						s += '</div>';
						
						nAdsDisplayed++;
					}
					else
					{
						s = '<div class="afs_adsby"><a href="http://services.google.com/feedback/online_hws_feedback" class="afs_g_adsby">Ads by Google</a></div>' 
					
						var nTotalAds = nAdsDisplayed + nAdsInDiv;
						if (nTotalAds > google_num_ads)
						{
							nTotalAds = google_num_ads;
						}
						
						for (var i = nAdsDisplayed; i < nTotalAds; i++)
						{
							s += '<div class="afs_googleaddiv" onmouseover="this.style.background=\'#E7EBF1\';" onmouseout="this.style.background=\'#F3F5F8\';">'
							s += '<a target="_blank" style="text-decoration:none;line-height:20px;" href="' + google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[i].visible_url + '\'"><font class="afs_g_link">' + google_ads[i].line1 + '</font></a><br />';
							s += '<font class="afs_g_text">' + google_ads[i].line2 + '</font><br />';
							s += '<a target="_blank" style="text-decoration:none;" href="' + google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[i].visible_url + '\'"><font class="g_url">' + google_ads[i].visible_url + '</font></a>';
							s += '</div>';
							
							nAdsDisplayed++;
						}
					}
					
					divToFill.innerHTML = s;
				}
			}
	    }
    }

    return;
}

//-----------------------------------------------------------------------------
function inbox_Delete(id, msgType, bSpam)
{
	// Mark the message as deleted
        RunScript('/customscripts/inbox_delete.asp?id=' + id + '&mt=' + msgType + '&spam=' + bSpam, '', '');
    
    // Return to the inbox
    location.href = 'inbox.htm';
}

//-----------------------------------------------------------------------------
// In-place Login
//-----------------------------------------------------------------------------
function DisplayLogin(whereFrom)
{
	getObj('fadeout').style.height = document.body.clientHeight;
	getObj('fadeout').style.display = 'block';
	changeOpac(60,'fadeout');
	getObj('inplacelogin').style.display = 'block';
	
	// Vertical position
	if (window.pageYOffset)
	{
		pos = window.pageYOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		pos = document.documentElement.scrollTop
	}
	else if (document.body)
	{
		  pos = document.body.scrollTop
	}
	getObj('inplacelogin').style.top = (200 + pos) + 'px';
	
	// Center Horizontally..
	var myWidth = 0;
	if (typeof(window.innerWidth) == 'number')
	{
		myWidth = window.innerWidth;
	}
	else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
	{
		myWidth = document.documentElement.clientWidth;
	}
	else if(document.body && (document.body.clientWidth || document.body.clientHeight))
	{
		myWidth = document.body.clientWidth;
	}
	getObj('inplacelogin').style.left = (myWidth / 2);
	RunScript('/customscripts/inPlaceLogin.asp?wherefrom=' + whereFrom, 'inplacelogin', '');
}

//-----------------------------------------------------------------------------
function changeOpac(opacity, id)
{ 
    var object = getObj(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")"; 
} 

//-----------------------------------------------------------------------------
function cancelInPlaceLogin()
{
	parent.getObj('fadeout').style.display = 'none';
	parent.getObj('inplacelogin').style.display = 'none';
}

//-----------------------------------------------------------------------------
function ShowReviewComments(bShow)
{
    if (bShow == true)
    {
        ShowDiv('signupValidationMsgs');
        HideDiv('signupValidationMsgs_closed');
    }
    else
    {
        HideDiv('signupValidationMsgs');
        ShowDiv('signupValidationMsgs_closed');
    }
}

//-----------------------------------------------------------------------------
// Adds companyId to users address book.
//-----------------------------------------------------------------------------
function AddToAddressBook(companyId, fromWhere, bAdd)
{
	var action = 'add';
	if (bAdd == false)
	{
		action = 'delete';
	}
	RunScript('/customscripts/addtoaddressbook.asp?id=' + companyId + '&action=' + action, '', '');
	
	switch (fromWhere)
	{
		case 'profile':
			getObj('addressBookIcon').src = '/fx/icon_inaddressbook.gif';
			getObj('addressBooktd').innerHTML = 'Company is <a class="lightblue" href="/myfreeindex(mapbook)_bookmarked.htm">Bookmarked</a>';
			break;
		case 'map':
			var abookLink = getObj('ABookLink' + companyId);
			if (abookLink != null)
			{
				abookLink.innerText = 'Bookmark';
				abookLink.href = 'javascript:AddToAddressBook(\'' + companyId + '\',\'map\', true);';
				if (bAdd == true)
				{
					abookLink.innerText = 'Bookmarked';
					abookLink.href = 'javascript:MapShowMe(\'bookmarked\',\'1\');';
				}
			}
			break;
		default:
			var abookLink = getObj('ABookLink' + companyId);
			if (abookLink != null)
			{
				abookLink.innerText = 'Bookmarked';
				abookLink.href = '/myfreeindex(mapbook)_bookmarked.htm';
				if (bAdd == false)
				{
					abookLink.innerText = 'Bookmark this company';
					abookLink.href = 'javascript:AddToAddressBook(\'' + companyId + '\',\'map\', true);';
				}
			}
			break;
	}
}

//-----------------------------------------------------------------------------
function DisplaySendToMobile(CompanyID)
{
	getObj('Sendtomobileform').style.display = 'block';
	RunScript('/customscripts/sendtoMobile.asp?id=' + CompanyID,'Sendtomobileform','');
}

//-----------------------------------------------------------------------------
function SubmitSendMobileForm()
{
	var mobilenumber = getObj('mobilenumber').value;
	var CompanyID = getObj('CompanyID').value;
	RunScript('/customscripts/sendtoMobile.asp?id=' + CompanyID + '&mobilenumber=' + mobilenumber,'Sendtomobileform','');
}

//-----------------------------------------------------------------------------
function CloseMobileWindow()
{
	getObj('Sendtomobileform').style.display = 'none';
}


//-----------------------------------------------------------------------------
// Reviews
//-----------------------------------------------------------------------------
function changeReviewBusinessOrUser() {
	if (getObj('BusinessOrUser')[0].checked)
		getObj('companydetails').style.display = 'block';
	else
		getObj('companydetails').style.display = 'none';
}

//-----------------------------------------------------------------------------
function ShowReviewLoginForm()
{
	getObj('review_LoginForm').style.display = 'block';
	getObj('review_SignupForm').style.display = 'none';
	getObj('review_login').value = '1';
}

//-----------------------------------------------------------------------------
function ShowReviewSignUpForm()
{
	getObj('review_LoginForm').style.display = 'none';
	getObj('review_SignupForm').style.display = 'block';
	getObj('review_login').value = '';
}

//-----------------------------------------------------------------------------
// Displays Google map with business location and baloon on.
// The variables objGMap and objGDirections should have already been defined.
//-----------------------------------------------------------------------------
function loadmap(isLogo, logoCompanyName, g_lon, g_lat, zoom)
{
    if (GBrowserIsCompatible())
    {
		var mapDiv = getObj('map');
		var inplaceDirectionsDiv = getObj('inplacedirections');
		if (mapDiv != null)
		{
			objGMap = new GMap2(mapDiv);
			if (inplaceDirectionsDiv != null)
			{
				objGDirections = new GDirections(objGMap, inplaceDirectionsDiv);
			}
			
			objGMap.addControl(new GSmallMapControl());
			objGMap.setCenter(new GLatLng(g_lon, g_lat), zoom);
			if (logoCompanyName != '')
			{
				var ballooncontent = '<div class="balloon">'
				ballooncontent += '<table border="0" cellpadding="0" cellspacing="0">'
				ballooncontent += '<tr><td height="36" width="81" align="center">'
            
				if (isLogo == 1)
				{
					ballooncontent += '<img src="/customscripts/systemfunctions/showimage.asp?img=' + logoCompanyName + '&folder=listinglogos&maxw=75&maxh=33" border="0" alt="" />'
				}
				else
				{
					ballooncontent += logoCompanyName;
				}
				ballooncontent += '</td></tr></table></div>';
            
				var label = new TLabel();
				label.id = '1';
				label.anchorLatLng = new GLatLng (g_lon,g_lat);
				label.anchorPoint = 'bottomLeft';
				label.content = ballooncontent;
				label.percentOpacity = 80;
		        
				objGMap.addTLabel(label);            
			}
		}
	}
	else
    {
        alert("Sorry, our Interactive Map is not compatible with your browser");
    }
}

//-----------------------------------------------------------------------------
// Create, load and display Google map showing businesses.
// Gets points and data from already loaded arrMapData.
// The variable objGMap should have already been defined.
//-----------------------------------------------------------------------------
function loadCatMap(catsorjobs)
{
	if (GBrowserIsCompatible())
	{
		// Limit Zoom Level on Jobs..
		if (catsorjobs == 'jobs')
		{
			G_NORMAL_MAP.getMaximumResolution = function() {return 11;} 
		}
		
		var catMap = getObj('catMap');
		if (catMap != null && arrMapData != null)
		{
			objGMap = new GMap2(catMap);
			objGMap.addControl(new GLargeMapControl());
			objGMap.setCenter(new GLatLng(52,-2), 8);
			var bounds = new GLatLngBounds();
		
			// Create a base icon for all of our markers that specifies the
			// shadow, icon dimensions, etc.
			var baseIcon = new GIcon();
			baseIcon.iconSize = new GSize(20, 34);
			baseIcon.shadowSize = new GSize(37, 34);
			baseIcon.iconAnchor = new GPoint(9, 34);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			baseIcon.infoShadowAnchor = new GPoint(18, 25);
	
			// Creates a marker whose info window displays the letter corresponding
			// to the given index.
			function createMarker(point, index, infowindow)
			{
				// Create a lettered icon for this point using our icon class
				var letter = String.fromCharCode('A'.charCodeAt(0) + index);
				var letteredIcon = new GIcon(baseIcon);
				letteredIcon.image = '/fx/mapmarkers/blue_Marker' + letter + '.png';
			
				// Set up our GMarkerOptions object
				markerOptions = { icon : letteredIcon };
				var marker = new GMarker(point, markerOptions);
				GMarkers[index] = marker; 
				
				GEvent.addListener(marker, 'click', function()
				{
					marker.openInfoWindowHtml(infowindow);
					objGMap.savePosition();
				});
				return marker;
			}
			
			for (i = 0; i < arrMapData.length; i++)
			{
				poundsPos = arrMapData[i].indexOf('££');
				dollarPos = arrMapData[i].indexOf('$$');
				
				var lat = arrMapData[i].substr(0, poundsPos);
				var lon = arrMapData[i].substr(poundsPos + 2, ((dollarPos - poundsPos) - 2));
				var info = arrMapData[i].substr(dollarPos + 2);
				
				var decodedLat = LatLongDecode(lat);
				var decodedLon = LatLongDecode(lon);
				var point = new GLatLng(decodedLat, decodedLon);
				objGMap.addOverlay(createMarker(point, i, info));
				bounds.extend(point);
				objGMap.setCenter(bounds.getCenter());
				objGMap.setZoom(objGMap.getBoundsZoomLevel(bounds));
			}
			
			// Extend bounds to search location
			if (loc_lat != null && loc_lon != null && loc_lat != 0 && loc_lon != 0)
			{
				var point = new GLatLng(loc_lat, loc_lon);
				bounds.extend(point);
				objGMap.setCenter(bounds.getCenter());
				objGMap.setZoom(objGMap.getBoundsZoomLevel(bounds));
			}
			if (arrMapData.length <= 1)
			{
				objGMap.setZoom(12);
			}
		}
		else if (arrMapData == null && catMap != null)
		{
			// There is no map data - show default centred map
			objGMap = new GMap2(catMap);
			objGMap.addControl(new GLargeMapControl());
			objGMap.setCenter(new GLatLng(54,-2), 5);
		}
	}
}

//-----------------------------------------------------------------------------
function zoomCatMap(thispoint)
{
	thispoint = thispoint - 65;
	
	poundsPos = arrMapData[thispoint].indexOf('££')
	dollarPos = arrMapData[thispoint].indexOf('$$')
		
	var lat = arrMapData[thispoint].substr(0, poundsPos)
	var lon = arrMapData[thispoint].substr(poundsPos + 2, ((dollarPos - poundsPos) - 2))
	var info = arrMapData[thispoint].substr(dollarPos + 2)
		
	var decodedLat = LatLongDecode(lat);
	var decodedLon = LatLongDecode(lon);
	
	GMarkers[thispoint].openInfoWindowHtml(info);
	objGMap.panTo(new GLatLng(decodedLat, decodedLon));
	objGMap.setZoom(10);
}

//-----------------------------------------------------------------------------
// Only decodes numbers.
// ie, 0 to 9, . and -
//-----------------------------------------------------------------------------
function LatLongDecode(fLatOrLon)
{
	var strLatOrLon = fLatOrLon.toString();
	var fDecoded = 0;
	if (strLatOrLon.length != 0)
	{
		var strDecoded = '';
		var strLen = 0;
		strLen = strLatOrLon.length;
		
		var thisChar = '';
		for (var x = 0; x < strLen; x++)
		{
			thisChar = strLatOrLon.charAt(x);
			switch (thisChar)
			{
				case '0':
					thisChar = '6';
					break;
				case '1':
					thisChar = '4';
					break;
				case '2':
					thisChar = '5';
					break;
				case '3':
					thisChar = '9';
					break;
				case '4':
					thisChar = '7';
					break;
				case '5':
					thisChar = '8';
					break;
				case '6':
					thisChar = '0';
					break;
				case '7':
					thisChar = '2';
					break;
				case '8':
					thisChar = '3';
					break;
				case '9':
					thisChar = '1';
					break;
				default:
					thisChar = thisChar;
					break;
			}
			
			strDecoded += thisChar;
		}
		fDecoded = new Number(strDecoded);
	}
	
	return fDecoded;
}

//-----------------------------------------------------------------------------
// Sets the focus to the username field when logging in
// Called in onload
//-----------------------------------------------------------------------------
function SetFocusLogin()
{
	var username = getObj('username');
	if (username != null)
	{
		username.focus();
	}
}

//-----------------------------------------------------------------------------
// Sets the focus to the username field when logging in
// Called in onload
//-----------------------------------------------------------------------------
function SetFocusSignup()
{
	var fullname = getObj('fullname');
	if (fullname != null)
	{
		fullname.focus();
	}
}

//-----------------------------------------------------------------------------
// Gets lat long from given postcode
// Sets the value of two fields, user_lat and user_lon
// Submits the given form
// Must be used with the GetMapJS script included
//-----------------------------------------------------------------------------
function GetLatLong(strPostcode, formToSubmit)
{
	if (GBrowserIsCompatible())
	{
		var localSearch = new GlocalSearch();
		
		if (strPostcode != '')
		{
			localSearch.execute(strPostcode);
			
			// Create a callback function. This only gets in the result
			// bit once a result has been returned from the google API
			localSearch.setSearchCompleteCallback(null,
				function()
				{
					if (localSearch.results[0])
					{
						// It won't get here until a lat long has been found
						// fill in the hidden form vars
						var user_lat = getObj('user_lat');
						if (user_lat != null)
						{
							user_lat.value = localSearch.results[0].lat;
						}
						
						var user_lon = getObj('user_lon');
						if (user_lon != null)
						{
							user_lon.value = localSearch.results[0].lng;
						}
						
						// And submit the form to do the sort
						if (formToSubmit != null)
						{
							formToSubmit.submit();
						}
					}
				} 
			);
		}
    }
}

//-----------------------------------------------------------------------------
// Gets lat long from given postcode.
// Runs a script to update the DefaultLocation field in the Accounts table.
// Must be used with the GetAjaxMapJS script included.
//-----------------------------------------------------------------------------
function UpdateLatLong(strPostcode, accountId)
{
	if (GBrowserIsCompatible())
	{
		var localSearch = new GlocalSearch();
		
		if (strPostcode != '')
		{
			localSearch.execute(strPostcode);
			
			// Create a callback function. This only gets in the result
			// bit once a result has been returned from the google API
			localSearch.setSearchCompleteCallback(null,
				function()
				{
					if (localSearch.results[0])
					{
						// It won't get here until a lat long has been found
						// fill in the hidden form vars
						var user_lat = localSearch.results[0].lat;
						var user_lon = localSearch.results[0].lng;
												
						RunScript('/customscripts/signup_setlatlon.asp?aid=' + accountId + '&lat=' + user_lat + '&lon=' + user_lon, '', '');
					}
				} 
			);
		}
    }
}


//-----------------------------------------------------------------------------
// Sets Profile page height 
//-----------------------------------------------------------------------------
function setProfileHeight()
{
	var x,y;
	var test1 = document.body.scrollHeight;
	var test2 = document.body.offsetHeight
	if (test1 > test2) // all but Explorer Mac
	{
		y = document.body.scrollHeight;
	}
	else // Explorer Mac;
	{
		y = document.body.offsetHeight;
	}
	
	getObj('profile_content_table').style.height = (y - 350) + 'px';
}

//-----------------------------------------------------------------------------
// Displays Image Upload within MFI
//-----------------------------------------------------------------------------
function OpenProfileImageUpload(paracount)
{
	var left = Math.floor((screen.width - 400) / 2);
	var top = Math.floor((screen.height - 200) / 2);
	if (paracount >= 3)
	{
		var mywindow = window.open('/customscripts/uploadprofileImage.asp', 'upload', 'top=' + top + ', left=' + left + ', status=yes, resizable=no, width=550, height=420');
		if (mywindow.opener == null)
		{
		    mywindow.opener = self;
		}
	}
	else
	{
		alert('Please complete at least 3 sections of text before uploading pictures.')
	}
}

//-----------------------------------------------------------------------------
function deleteImage()
{
    var agree = confirm("Are you sure you want to delete this Image ?");
    if (agree)
    {
		getObj('DeleteImage').value = 1;
		document.imageinfo.submit();
    }
}

//-----------------------------------------------------------------------------
// Displays Image Gallery within Profile Page.
//-----------------------------------------------------------------------------
function showGallery(listingid)
{
	getObj('fadeout').style.height = document.body.clientHeight;
	getObj('fadeout').style.display = 'block';
	changeOpac(60,'fadeout');
	getObj('ImageGallery').style.display = 'block';
	
	if (window.pageYOffset)
	{
		  pos = window.pageYOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		pos = document.documentElement.scrollTop
	}
	else if (document.body)
	{
		  pos = document.body.scrollTop
	}
	getObj('ImageGallery').style.top = (100 + pos) + 'px';
	RunScript('/custom' + 'scrip' + 'ts/displ' + 'aygall' + 'ery.as' + 'p?id=' + listingid,'ImageGallery','');
}

//-----------------------------------------------------------------------------
function blendimage(divid, imageid, imagefile, millisec, imgCount, totalpics)
{ 
    var speed = Math.round(millisec / 100); 
    var timer = 0; 
    document.getElementById(divid).style.backgroundImage = "url(" + document.getElementById(imageid).src + ")"; 
    changeOpac(0, imageid); 
    document.getElementById(imageid).src = imagefile; 
    for(i = 0; i <= 100; i++)
    { 
        setTimeout("changeOpac(" + i + ",'" + imageid + "')",(timer * speed)); 
        timer++; 
    } 
	document.getElementById(divid).style.backgroundImage = "url('')";
	getObj('caption').innerHTML = getObj('caption_' + imgCount).value;
	getObj('filename').innerHTML = 'Uploaded on ' + getObj('dateadded_' + imgCount).value;
	getObj('CurrentImageID').value = imgCount;
	
    for (i = 0; i < totalpics; i++)
    {
		getObj('PreviewIMG_' + i).style.borderColor = '#ccc';
	}
	getObj('PreviewIMG_' + imgCount).style.borderColor = '#cc0000';
} 

//-----------------------------------------------------------------------------
function changeOpac(opacity, id)
{ 
    var object = document.getElementById(id).style; 
    object.opacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.KhtmlOpacity = (opacity / 100); 
    object.filter = "alpha(opacity=" + opacity + ")";
}

//-----------------------------------------------------------------------------
function closeGallery()
{
	getObj('ImageGallery').style.display='none';
	getObj('fadeout').style.display='none';
}

//-----------------------------------------------------------------------------
function showNextPic(totalpics,listingid)
{
	nextImage = (+getObj('CurrentImageID').value + 1);
	if (nextImage > totalpics - 1)
	{
		nextImage = 0;
	}
	blendimage('blenddiv','blendimage', 'media/profilepics/' + listingid + '/' + getObj('filename_' + nextImage).value,500, nextImage, totalpics);
}

//-----------------------------------------------------------------------------
function showPrevPic(totalpics,listingid)
{
	prevImage = (+getObj('CurrentImageID').value - 1);
	if (prevImage == -1)
	{
		prevImage = totalpics - 1;
	}
	blendimage('blenddiv','blendimage', 'media/profilepics/' + listingid + '/' + getObj('filename_' + prevImage).value,500, prevImage, totalpics);
}

//-----------------------------------------------------------------------------
function LoadInboxMessages(pg,fil)
{
	var url = '/customscripts/inbox_data.asp?pg=' + pg + '&fil=' + fil;
	RunScript(url,'inbox_messages','');

	setTimeout('InboxDisplayLoadFailed(\'' + pg + '\',\'' + fil + '\')', 10000);
}

//-----------------------------------------------------------------------------
function InboxDisplayLoadFailed(pg, fil)
{
	// Called after waiting to load inbox after 10 seconds
	var inbox_messages = getObj('inbox_messages');
	
	if (inbox_messages != null)
	{
		var nFind = inbox_messages.innerHTML.indexOf('data_searching');
		if (nFind > 0)
		{
			// Page hasn't loaded inbox, still searching
			// Use a different format URL to load the non ajax way
			var url = '/inbox.htm?pg=' + pg + '&fil=' + fil + '&na=1'; // No Ajax (na)
			
			inbox_messages.innerHTML = '<br /><br /><br />If you still can\'t access your inbox, please click on the following link - <a href="' + url + '">click here</a>.'
		}
	}
}

//-----------------------------------------------------------------------------
function AdminSetStockText()
{
	var stock_sel = getObj('stock_sel');
	var id = stock_sel.options[stock_sel.selectedIndex].value;

	var hiddenText = getObj('stock_response_' + id);
	var stocktext = getObj('stocktext');
	
	if (hiddenText != null)
	{
		stocktext.value = hiddenText.value;
	}
	else
	{
		stocktext.value = '';
	}
}

//-----------------------------------------------------------------------------
function ChangeSelectedCase(theType)
{
	var sel = document.selection;
	if (sel != null)
	{
		var rng = sel.createRange();
		if (rng != null)
		{
			var selectedText = rng.text;
			var newText = '';
			switch (theType)
			{
				case 'lower':
					newText = selectedText.toLowerCase();
					break;
				case 'title':
					newText = TitleCase(selectedText);
					break;
				case 'upper':
					newText = selectedText.toUpperCase();
					break;
			}
			rng.text = newText;
		}
	}
}

//View Type in listings / Search
//-----------------------------------------------------------------------------
function ls_DisplayViewOptions() {
	//Shut sort Options..
	getObj('ls_st_options').style.display = 'none';
	
	
	var opDiv = getObj('ls_vw_options');
	if (opDiv.style.display == 'block') {
		opDiv.style.display = 'none';
	} else {
		opDiv.style.display = 'block';
	}
}

function ls_DisplaySortOptions() {
	//Shut sort Options..
	getObj('ls_vw_options').style.display = 'none';
	
	var opDiv = getObj('ls_st_options');
	if (opDiv.style.display == 'block') {
		opDiv.style.display = 'none';
	} else {
		opDiv.style.display = 'block';
	}
}

function Change_ls_ViewType(SelView) {
	getObj('ls_vtype').value=SelView;
	document.LsCtrlsForm.submit();
}
function Change_ls_SortType(SelSort) {
	getObj('ls_sort').value=SelSort;
	document.LsCtrlsForm.submit();
}

function DisplayFullPhotoView(pid,e) {
	//Get Mouse Position
	var posx = 0;
	var posy = 0;
	posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
	posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	
	//Get Window Size
	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 || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	
	//Calculate Width Offset and adjust posx
	var WinXOffset = (myWidth-981) / 2;
	var winPosX = (posx-WinXOffset);
	if (winPosX > 600) {
		posx = posx-400;
	}
	//Calculate Height Offset and adjust posy
	if ((myHeight - e.clientY) < 300) {
		posy = posy-320;
	}
	
	//Display Photo Window
	var DivName = 'PhotoFullView_' + pid
	getObj(DivName).style.display='block';
	getObj(DivName).style.left = (posx) + 'px';
	getObj(DivName).style.top = (posy) + 'px';
}


function HideFullPhotoView() {
    var arrDivs = document.getElementsByTagName('div');
    for (i = 0; i < arrDivs.length; i++) {
		d_id=arrDivs[i].id;
	    if (d_id.indexOf('PhotoFullView_') != -1) {
		    arrDivs[i].style.display='none';
		}
	}
}

//-----------------------------------------------------------------------------
function ChangeCompanyType()
{
	// Get selected companyType
	var companyType = getObj('companyType');
	if (companyType != null)
	{
		var ctValue = companyType.options[companyType.selectedIndex].value;
		
		var branchselector = getObj('branchselector');
		if (branchselector != null)
		{
			if (ctValue == '' || ctValue == "SOLE")
			{
				branchselector.style.display = 'none';
			}
			else
			{
				branchselector.style.display = 'block';
			}
		}
	}
}

//-----------------------------------------------------------------------------
// Branch editor functions
//-----------------------------------------------------------------------------
function OpenBranchesWindow()
{
	var companyType = getObj('companyType');
	var ctValue = '';
	if (companyType != null)
	{
		ctValue = companyType.options[companyType.selectedIndex].value;
	}
	var args = 'toolbar=0,status=1,menubar=0,scrollbars=1,resizable=0';
	OpenCenteredWindow('/customscripts/SelectBranches.asp?ctype=' + ctValue, 375, 650, null, args)
}

//-----------------------------------------------------------------------------
function CloseBranchWindow()
{
	window.close();
}

//-----------------------------------------------------------------------------
function AddBranch()
{
	var action = getObj('action');
	action.value = 'add';
	
	var theForm = getObj('branches');
	theForm.submit();
}

//-----------------------------------------------------------------------------
function EditBranch(branchId)
{
	var action = getObj('action');
	action.value = 'edit';
	
	var theid = getObj('theid');
	theid.value = branchId;
	
	var theForm = getObj('branches');
	theForm.submit();
}

//-----------------------------------------------------------------------------
function SaveBranch()
{
	var action = getObj('action');
	action.value = 'save';
	
	var theForm = getObj('branches');
	theForm.submit();
}

//-----------------------------------------------------------------------------
function RemoveBranch(branchId, bRemove)
{
	var action = getObj('action');
	if (bRemove == 1)
	{
		action.value = 'remove';
	}
	else
	{
		action.value = 'display';
	}
	var theid = getObj('theid');
	theid.value = branchId;
	
	var theForm = getObj('branches');
	theForm.submit();

}

//-----------------------------------------------------------------------------
function CancelBranch()
{
	var action = getObj('action');
	action.value = '';
	
	var theForm = getObj('branches');
	theForm.submit();
}