//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// 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;
    sText = Trim(sText);
    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 (win != null)
    {
        if (parseInt(navigator.appVersion) >= 4 && win != null)
        {
            win.window.focus();
        }
    }
    else
    {
        // Pop-up blocker could be on - in any case, warn user to turn them off
        var msg = 'We\'ve detected that you have Pop-up\'s Blocked.\n';
        msg += 'To open this window you\'ll need to allow pop-ups for the site.';
        
        alert(msg);
    }
}

//-----------------------------------------------------------------------------
function OpenWindow(windowType, params)
{
    switch (windowType)
    {
        case 'rating_example':
            OpenCenteredWindow('/customscripts/profile_example.asp?level=ratings', '450', '550', 'example', 'scrollbars=yes');
            break;
        case 'third_person':
            OpenCenteredWindow('/staticFiles/pm_3rdperson.htm', '500', '500', '3rdperson', '');
            break;
        case 'logo_example':
            OpenCenteredWindow('customscripts/pm_logo.asp', '300', '400');
            break;
        case 'review_email':
            OpenCenteredWindow('/customscripts/review_email_example.asp', '450', '690', null, 'status=no, resizable=no, scrollbars=no');
            break;
        case 'recomend_email':
            OpenCenteredWindow('/customscripts/recomend_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;
        case 'ReviewWidgetClass':
            OpenCenteredWindow('/staticFiles/Review_Widget_Class.htm', '350', '550', null, 'status=no, resizable=no, scrollbars=no');
            break;
        case 'signup_privacy':
            OpenCenteredWindow('/staticFiles/signup_privacy.htm', '300', '550', null, 'status=no, resizable=no, scrollbars=no');
            break;
    }
}

//-----------------------------------------------------------------------------
// Ajax Search Keyword Suggestions
//-----------------------------------------------------------------------------
function SuggestSearchKeywords(obj, hiddenDivName, kwType)
{
    var typedSoFar = obj.value;
    var hiddenDivObj = getObj(hiddenDivName);
    if (hiddenDivObj != null)
    {
        if (typedSoFar.length >= 3)
        {
            var url = '/customscripts/search_suggestions.asp?o=' + obj.name + '&h=' + hiddenDivName + '&q=' + typedSoFar;
            if (kwType == 'location')
            {
                url = '/customscripts/search_locations.asp?o=' + obj.name + '&h=' + hiddenDivName + '&q=' + typedSoFar;
            }

            this.RunScript(url, hiddenDivName, '');
            
            if (hiddenDivObj.innerHTML != '')
            {
                hiddenDivObj.style.display = 'block';
            }
        }
        else
        {
            hiddenDivObj.style.display = 'none';
        }
    }
}

//-----------------------------------------------------------------------------
// User Clicks on suggestion.
function SearchClickSuggest(catName, entryObjName, hiddenDivName)
{
    getObj(entryObjName).value = catName;
    getObj(hiddenDivName).style.display = 'none';
}

//-----------------------------------------------------------------------------
// ... for a location
function SearchClickSuggestLoc(catName, entryObjName, hiddenDivName, locId)
{
    getObj(entryObjName).value = catName;
    if (getObj('loc_id') != null)
    {
        getObj('loc_id').value = locId;
    }
    getObj(hiddenDivName).style.display = 'none';
}

//-----------------------------------------------------------------------------
// User Exits Search box
function HideSuggest(hiddenDivName)
{
    if (getObj(hiddenDivName) != null)
    {
        getObj(hiddenDivName).style.display = 'none';
    }
}

var searchDummyValues = ['e.g. Plumber, Courier...','e.g. London, Bristol...','e.g. Sales Jobs...','Search the archive...','Builders, Accountants, Taxis etc','Full Postcode','DD/MM/YYYY'];

//-----------------------------------------------------------------------------
// User Clicks Search Box - Clear Dummy Stuff
function ClickSearchBox(obj)
{
    if (obj.value != '')
    {   // See if the content should be cleared
        for (var i = 0; i < searchDummyValues.length; i++)
        {
            if (obj.value == searchDummyValues[i])
            {
                obj.value = '';
                obj.style.color = '#000';
            }
        }
    }
}

//-----------------------------------------------------------------------------
function ClickOffSearchBox(obj, inputType)
{
    // See if the content should go back to the suggestion
    if (obj.value == '')
    {
        switch (inputType)
        {
            case 'C': // Category
                obj.value = searchDummyValues[0];
                break;
            case 'L': // Location
                obj.value = searchDummyValues[1];
                break;
            case 'J': // Jobs
                obj.value = searchDummyValues[2];
                break;
            case 'A': // Business Advice
                obj.value = searchDummyValues[3];
                break;
            case 'Q': // Quote category
                obj.value = searchDummyValues[4];
                break;
            case 'P': // Postcode
                obj.value = searchDummyValues[5];
                break;
            case 'D': // Date
                obj.value = searchDummyValues[6];
                break;
        }
        obj.style.color = '#999';
    }
}

//-----------------------------------------------------------------------------
function SearchGo(searchType)
{
    // Get data for the search
    var strKeyword = '';
    var strLocation = '';
    var locationId = 0;
    var forumId = 0;
    var filters = '';
    
    switch (searchType)
    {
        case '':
            strKeyword = Trim(getObj('SrchKeyword').value);
            if (strKeyword == 'e.g. Plumber, Courier...')
            {
                strKeyword = '';
            }
            strLocation = Trim(getObj('SrchLocation').value);
            if (strLocation == 'e.g. London, Bristol...')
            {
                strLocation = '';
            }
            locationId = getObj('loc_id').value;
            if (getObj('filter_profile').checked == true)
            {
                filters += 'd';
            }
            if (getObj('filter_photos').checked == true)
            {
                filters += 'p';
            }
            if (getObj('filter_reviews').checked == true)
            {
                filters += 'r';
            }
            if (getObj('filter_offers').checked == true)
            {
                filters += 'o';
            }
            break;
        case 'jobs':
            strKeyword = Trim(getObj('SrchKeyword').value);
            if (strKeyword == 'e.g. Sales Jobs...')
            {
                strKeyword = '';
            }
            var job_filter = getObj('job_filter');
            filters = job_filter[job_filter.selectedIndex].value;
            break;
        case 'forums':
            strKeyword = Trim(getObj('SrchKeyword').value);
            if (strKeyword == 'Search the archive...')
            {
                strKeyword = '';
            }
            forumId = getObj('forumid').value;
            break;
    }
    
    // Do some validation
    strKeyword = Replace(strKeyword, ' ', '-');
    strKeyword = Replace(strKeyword, '&', ' and ');
    
    if (strKeyword.length >= 3)
    {
        // Format the URL
        srchURL = '/searchresults.asp?k=' + strKeyword.toLowerCase();
        switch (searchType)
        {
            case '':
                if (strLocation.length > 0)
                {
                    srchURL += '&l=' + strLocation.toLowerCase();
                }
                if (locationId != 0)
                {
                    srchURL += '&locid=' + locationId;
                }
                if (filters != '')
                {
                    srchURL += '&f=' + filters;
                }
                break;
            case 'jobs':
                srchURL += '&jobs=1';
                if (filters != '')
                {
                    srchURL += '&f=' + filters;
                }
                break;
            case 'forums':
                srchURL += '&forums=1';
                srchURL += '&forumid=' + forumId;
                break;
        }
        
        location.href = srchURL;
    }
    else
    {
        alert('Please enter a Search Keyword of at least 3 characters in length');
    }
}

//-----------------------------------------------------------------------------
function OnKeydownSearch(e, searchType, inputBoxName)
{
    if (!e)
    {
        e = window.event; // for ie
    }
    if (e.keyCode == 13) // CR
    {
        SearchGo(searchType);
    }
    else
    {
        // Trim input if too long
        var searchKeyword = getObj('SrchKeyword');
        if (searchKeyword != null)
        {
            searchKeyword.style.color = '#000';
            if (searchKeyword.value.length > 45)
            {
                searchKeyword.value = searchKeyword.value.substring(0, 45);
            }
        }
        
        var searchLocation = getObj('SrchLocation');
        if (searchLocation != null && searchLocation.value != 'e.g. London, Bristol...')
        {
            searchLocation.style.color = '#000';
            if (searchLocation.value.length > 45)
            {
                searchLocation.value = searchLocation.value.substring(0, 45);
            }
            
            if (inputBoxName == 'loc')
            {
                // User is typing a location. 0 the location id
                getObj('loc_id').value = '';
            }
        }
    }
}

//-----------------------------------------------------------------------------
function RefreshSearch(kw, loc, locationId)
{
    // Refresh the search results given the passed in parameters
    var run1 = '/search' + 'results';
    var run2 = '.as' + 'p?';
    var run3 = 'k=' + kw + '&l=' + loc;
    if (locationId != '')
    {
        run3 += '&locid=' + locationId;
    }
    location.href = run1 + run2 + run3;
}

//-----------------------------------------------------------------------------
function LocationSelect(locationId, postTown, divToFill, pcFieldName, locFieldName)
{
    var url = '/customscripts/signup_selectloc.asp?locationId=' + locationId + '&posttown=' + postTown + '&divtofill=' + divToFill + '&fieldname=' + locFieldName;
    
    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);
    var mywindow = window.open('upload.asp', 'upload', 'top=' + top + ', left=' + left + ', status=yes, resizable=no, width=400, height=220');
    
    if (mywindow != null)
    {
        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;
        }
    }
    else
    {
        // Pop-up blocker could be on - in any case, warn user to turn them off
        var msg = 'We\'ve detected that you have Pop-up\'s Blocked.\n';
        msg += 'To open this window you\'ll need to allow pop-ups for the site.';
        
        alert(msg);
    }
}

//-----------------------------------------------------------------------------
function PreviewImage(fieldName, previewName, formName, folderName)
{
    // 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=' + folderName + '&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 (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 ClearHours()
{
    var arrInputs = document.getElementsByTagName('input');
    
    for (i = 0; i < arrInputs.length; i++)
    {
        if (arrInputs[i].className == 'hours')
        {
            arrInputs[i].value = '';
        }
    }
}

//-----------------------------------------------------------------------------
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;
}

//-----------------------------------------------------------------------------
function DeleteLogo()
{
    var delete_btn = getObj('delete_btn');
    if (delete_btn != null)
    {
        delete_btn.style.display = 'none';
    }
    var prevImg = getObj('prevImg');
    if (prevImg != null)
    {
        prevImg.src = '/customscripts/systemfunctions/showimage.asp?img=lb_no_image_available.gif&folder=listinglogos&maxW=150&maxH=60';
    }
    
    var companylogo = getObj('companylogo');
    if (companylogo != null)
    {
        companylogo.value = '';
    }
}

//-----------------------------------------------------------------------------
// Products
//-----------------------------------------------------------------------------
function LoadProducts()
{
    // Empty the products list
    var pm_product_list = getObj('pm_product_list');
    if (pm_product_list != null)
    {
        pm_product_list.innerHTML = '';
    }
    
    // Re-load the products
    RunScript('/customscripts/pm_products_services_list.asp?action=products', 'pm_product_list', '');
}

//-----------------------------------------------------------------------------
function AddProduct()
{
    OpenCenteredWindow('/customscripts/pm_products.asp?action=add', '450', '600', 'AddProduct', 'resizable=yes');
}

//-----------------------------------------------------------------------------
function EditProduct(productId)
{
    OpenCenteredWindow('/customscripts/pm_products.asp?action=edit&id=' + productId, '480', '600', 'AddProduct', 'resizable=yes');
}

//-----------------------------------------------------------------------------
function DeleteProduct(productId, theName)
{
    var agree = confirm("Are you sure you want to delete the product : " + theName + "?");
    if (agree)
    {
        RunScript('/customscripts/pm_products_services_list.asp?action=products&delid=' + productId, 'pm_product_list', '');
    }
}

//-----------------------------------------------------------------------------
function ValidateProduct()
{
    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 (!IsNumeric('cost'))
    {
        bad += 'The price contains invalid characters. Please remove , £ etc.\n';
    }
    
    if (bad != '')
    {
        msg = 'Required Information is missing or is incorrect.\n'
        msg += '-------------------------------------------------------\n'
        alert(msg + bad);
    }
    else
    {
        document.addeditproduct.submit();
    }
}

//-----------------------------------------------------------------------------
function DeleteProdServPic()
{
    getObj('image1').value = '';
    getObj('prevImg1').src = '/media/files/fileicons/noimage.gif';
}

//-----------------------------------------------------------------------------
// Services
//-----------------------------------------------------------------------------
function LoadServices()
{
    // Empty the services list
    var pm_service_list = getObj('pm_service_list');
    if (pm_service_list != null)
    {
        pm_service_list.innerHTML = '';
    }
    
    // Re-load the services
    RunScript('/customscripts/pm_products_services_list.asp?action=services', 'pm_service_list', '');
}

//-----------------------------------------------------------------------------
function AddService()
{
    OpenCenteredWindow('/customscripts/pm_services.asp?action=add', '450', '600', 'AddService', 'resizable=yes');
}

//-----------------------------------------------------------------------------
function EditService(serviceId)
{
    OpenCenteredWindow('/customscripts/pm_services.asp?action=edit&id=' + serviceId, '450', '600', 'AddService', 'resizable=yes');
}

//-----------------------------------------------------------------------------
function DeleteService(serviceId, theName)
{
    var agree = confirm("Are you sure you want to delete the service : " + theName + "?");
    if (agree)
    {
        RunScript('/customscripts/pm_products_services_list.asp?action=services&delid=' + serviceId, 'pm_service_list', '');
    }
}
      
//-----------------------------------------------------------------------------
function ValidateService()
{
    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 CatSelectChange(fieldname, e, dataType)
{
    var catSelectField = getObj(fieldname + '_catTypeSelect');
    var catSelectOptions = getObj(fieldname + '_catSelectOptions');
    
    var theValue = catSelectField.value;
    
    var defaultValue = '';
    switch (dataType)
    {
        case 'J':
            defaultValue = 'Electrician, Florist etc';
            break;
        case 'Q':
            defaultValue = 'Builders, Accountants, Taxis etc';
            break;
        default:
            defaultValue = 'Plumber, Florist, Gift Shop etc';
            break;
    }
    
    if (e.type == 'focus')
    {
        if (theValue == defaultValue)
        {
            catSelectField.value = '';
            catSelectField.style.color = '#999';
        }
    }
    if (e.type == 'blur')
    {
        if (theValue == '')
        {
            catSelectField.value = defaultValue;
            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','');
                
                catSelectField.focus();
            }
        }
        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;
    }
    
    var defaultValue = '';
    switch (dataType)
    {
        case 'J':
            defaultValue = 'Electrician, Florist etc';
            break;
        case 'Q':
            defaultValue = 'Builders, Accountants, Taxis etc';
            break;
        default:
            defaultValue = 'Plumber, Florist, Gift Shop etc';
            break;
    }
        
    if (inputBox.value != defaultValue)
    {
        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';
    
    if (dataType == 'Q')
    {
        if (getObj('listing_ids'))
        {
            // Resets quote form listings Ids when category is changed...
            getObj('listing_ids').value = '';
        }
    }
}

//-----------------------------------------------------------------------------
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;
        theTitle = Replace(theTitle, '\'', '');
    }
    else
    {
        bError = true;
    }
    var theDesc = '';
    if (getObj(fieldName + '_Suggested_catDesc') != null)
    {
        theDesc = getObj(fieldName + '_Suggested_catDesc').value;
        theDesc = Replace(theDesc, '\'', '');
    }
    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 CatSelectClose(fieldName, dataType)
{
    var objField = getObj(fieldName + '_catSelectOptions');
    if (objField != null)
    {
        objField.style.display = 'none';
        
        var catTxt = getObj(fieldName + '_catTypeSelect').value;
        getObj(fieldName + '_catTypeSelect').style.display = 'none';
        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 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)
    {
        var url = '/customscripts/systemfunctions/trackclick.asp?ctype=' + clickType + '&id=' + id;
        if (getObj('record_id') != null)
        {
            url += '&recordid=' + getObj('record_id').value;
        }
        
        (new Image()).src = url;
    }
    return true;
}

//-----------------------------------------------------------------------------
function recordclick(clickType, listingId)
{
    // Profile click tracker used where a redirect is not needed
    if (document.images)
    {
        var url = '/record_click.asp?ctype=' + clickType + '&id=' + listingId + '&just_stats=true';
        
        (new Image()).src = url;
    }
    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);
    }
    
    // Update 'characters required' counter
    countField.value = reqLimit - textField.value.length;
    if (countField.value <= 0)
    {
        countField.value = 0;
        countField.style.color = '#000';
    }
    else
    {
        countField.style.color = '#c00';
    }
}

//-----------------------------------------------------------------------------
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)
{
    // 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&theid=' + theId + '&revert=1';
    }
}

//-----------------------------------------------------------------------------
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 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;
                break;
            case 'admin_quick':
                location.href = '/admin/admin_quick.asp?action=clearpara&theid=' + listingId + '&paraID=' + paraID;
                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, catType)
{
    if (bApprove == true)
    {
        document.forms.cat.action = '/admin/admin_cats.asp?action=savecatapprove&theid=' + theid + '&catid=' + catid + '&cat=' + cat + '&catType=' + catType;
    }
    else
    {
        document.forms.cat.action = '/admin/admin_cats.asp?action=savecat&theid=' + theid + '&catid=' + catid + '&cat=' + cat + '&catType=' + catType;
    }
    document.forms.cat.submit();
}

//-----------------------------------------------------------------------------
function displayProfileProducts(id)
{
    var run1 = 'customscripts';
    var run2 = 'profile_products.asp';
    var run3 = '?id=' + id;
    RunScript(run1 + '/' + run2 + run3, 'products', 'products');
}

//-----------------------------------------------------------------------------
function UpdateReviews(customerReviewId, bCompanyReview, action)
{
    if (bCompanyReview == true)
    {
        getObj('review_to_save_id').value = customerReviewId;
        getObj('review_save_action').value = '';
        
        switch (action)
        {
            case 'RESEND':
                var msg = 'You are about to send an email to the author of the review.\n\n';
                msg += 'The email allows them to validate the review they have written.\n\n';
                msg += 'Are you sure?';
                if (confirm(msg) == true)
                {
                    getObj('review_save_action').value = action;
                }
                break;
            case 'DELETE':
                var msg = 'You are about to delete the incomplete review.\n\n';
                msg += 'Are you sure?';
                if (confirm(msg) == true)
                {
                    getObj('review_save_action').value = action;
                }
                break;
            default:
                getObj('review_save_action').value = action;
                break;
        }
        document.reviews.submit();
    }
    else
    {
        getObj('written_to_save_id').value = customerReviewId;
        document.written.action = '/myfreeindex(map-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 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';
        
        // If the div once displayed is going to go outside of the window,
        // position it so that the top right appears at the mouse position
        // rather than the top left
        var docWidth = document.body.clientWidth;
        var divLeftPos = divObj.offsetLeft;
        if (divLeftPos + divObj.clientWidth    > docWidth)
        {
            divObj.style.posLeft = divLeftPos - divObj.clientWidth - 80;
        }
    }
}

//-----------------------------------------------------------------------------
function RefreshCatInfo(catId, catType)
{
    var cat3value = '';
    if (getObj('cat3') != null)
    {
        cat3value = getObj('cat3').value;
    }
    
    var sing = '';
    var plur = '';
    var notDefault = '';
    var notDefaultValue = '';
    if (getObj('meta_single') != null)
    {
        sing = getObj('meta_single').value;
    }
    if (getObj('meta_plural') != null)
    {
        plur = getObj('meta_plural').value;
    }
    
    RunScript('/admin/admin_catinfo.asp?catId=' + catId + '&cat3=' + cat3value + '&sing=' + sing + '&plur=' + plur + '&catType=' + catType, '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 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 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 ConfirmCloseAccount() {
    var bad = '';
    optionselected = '';
    for (i = 0; i < document.closeaccount.closeaccountoptions.length; i++) {
        if (document.closeaccount.closeaccountoptions[i].checked) {
            optionselected=document.closeaccount.closeaccountoptions[i].value;
        }
    }
    
    if (optionselected =='') {
        bad +='Please select a reason why you are closing your account..\n';
    }
    
    if ((optionselected == 'B_AnotherReason') || (optionselected == 'U_AnotherReason')) {
        if (getObj('otherreason').value == '') {
            bad +='Please enter the reason you are leaving. Thanks.\n';
        }
    }
    if (getObj('e_catch').value != getObj('E_catchCheck').value) {
        bad +='Please make sure you enter the verification code correctly\n';
    }

    if (bad != '')
    {
        alert(bad);
    }
    else
    {
        document.closeaccount.submit();
    }


}




//-----------------------------------------------------------------------------
function ChangeAccountSettingState(fieldName, currentState)
{
    getObj('FieldtoChange').value = fieldName;
    var userResponse = true;
    var bSubmitForm = true;
    var msg;
    
    if (currentState == 0)
    {
        // User is about to disable a feature
        switch (fieldName)
        {
            case 'UserHidden':
                msg = 'You are about to hide all of your details on FreeIndex.\n\n';
                msg += 'Are you sure this is what you want to do?';
                userResponse = confirm(msg);
                break;
        }
        
        getObj('SetState').value = 1;
        if (userResponse == false)
        {
            bSubmitForm = false;
        }
    }
    else
    {
        // User is about to disable a feature
        switch (fieldName)
        {
            case 'EnquiryEmailMe':
                msg = 'You are about to disable a user\'s ability to send you an email from your Profile Page.\n\n';
                msg += 'Are you sure this is what you want to do?';
                userResponse = confirm(msg);
                break;
            case 'LeadEmailMe':
                msg = 'You will not receive any emails when a lead is posted in your category and location, potentially leading to work for your business.\n\n';
                msg += 'Are you sure this is what you want to do?';
                userResponse = confirm(msg);
                break;
            case 'LeadTxtMe':
                msg = 'You will not receive texts when a lead is posted in your category and location, potentially leading to work for your business.\n\n';
                msg += 'Are you sure this is what you want to do?';
                userResponse = confirm(msg);
                break;
        }
        
        getObj('SetState').value = 0;
        if (userResponse == false)
        {
            bSubmitForm = false;
        }
    }
    
    if (bSubmitForm == true)
    {
        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>';
        s += '<div class="afc_googleaddiv" onmouseover="this.style.background=\'#F3F5F8\';" onmouseout="this.style.background=\'#ffffff\';">'
        s += '<a target="_blank" style="text-decoration:none;line-height:20px;" href="' + google_ads[0].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'go to ' + google_ads[0].visible_url + '\'"><font class="g_link">' + google_ads[0].line1 + '</font></a><br />';
        s += '<font class="g_text">' + 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="afc_googleaddiv" onmouseover="this.style.background=\'#F3F5F8\';" onmouseout="this.style.background=\'#ffffff\';">'
            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="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;
}

//-----------------------------------------------------------------------------
// 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';
    }
    
    var url = '/customscripts/addtoaddressbook.asp?id=' + companyId + '&action=' + action;
    RunScript(url, '', '');
    
    switch (fromWhere)
    {
        case 'profile':
            getObj('addressBooktd').innerHTML = '<a class="lightblue" href="/myfreeindex(map-bookmarks).htm">Bookmarked</a></div>';
            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(map-bookmarks).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 ChangeBusinessOrUser()
{
    if (getObj('AccountType')[0].checked)
    {
        getObj('companydetails').style.display = 'block';
        getObj('userdetails').style.display = 'none';
        
        LocationSelect('', '', 'locationcat', 'postcode','locality');
    }
    else
    {
        getObj('companydetails').style.display = 'none';
        getObj('userdetails').style.display = 'block';
        
        LocationSelect('', '', 'user_locationcat', 'user_postcode', 'user_locality');
    }
}

//-----------------------------------------------------------------------------
function ShowLoginForm()
{
    getObj('login_form').style.display = 'block';
    getObj('signup_form').style.display = 'none';
    getObj('new_account').value = '';
    
    if (getObj('login_signup') != null)
    {
        getObj('login_signup').item(0).checked = true;
        getObj('login_signup').item(1).checked = false;
    }
    
    LocationSelect('', '', 'locationcat', 'postcode','locality');
}

//-----------------------------------------------------------------------------
function ShowSignUpForm()
{
    getObj('login_form').style.display = 'none';
    getObj('signup_form').style.display = 'block';
    getObj('new_account').value = '1';
    
    if (getObj('login_signup') != null)
    {
        getObj('login_signup').item(1).checked = true;
        getObj('login_signup').item(0).checked = false;
    }
    
    LocationSelect('', '', 'user_locationcat', 'user_postcode', 'user_locality');
}

//-----------------------------------------------------------------------------
// 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');
        if (mapDiv != null)
        {
            objGMap = new GMap2(mapDiv);
            
            // Add Controls
            objGMap.addControl(new GMapTypeControl());
            
            // If its on a job page, don't show the zoom and disable dragging
            if (getObj('job_map') != null)
            {
                objGMap.disableDragging();
            }
            else
            {
                objGMap.addControl(new GLargeMapControl3D());
            }
            
            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 mapCentreLat = 52;
        var mapCentreLon = -2;
        
        var catMap = getObj('catMap');
        if (catMap != null && arrMapData != null)
        {
            objGMap = new GMap2(catMap);
            objGMap.addControl(new GLargeMapControl3D());
            objGMap.addControl(new GMapTypeControl());
            
            objGMap.setCenter(new GLatLng(mapCentreLat, mapCentreLon), 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 SetZIndex(marker, b)
            {
                return -i; // negate the index so A appears on top, Z last
            }
            
            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, title : 'more info...', zIndexProcess : SetZIndex };
                var marker = new GMarker(point, markerOptions);
                GMarkers[index] = marker; 
                
                GEvent.addListener(marker, 'click', function()
                {
                    marker.openInfoWindowHtml(infowindow);
                    objGMap.savePosition();
                });
                return marker;
            }
            
            // Loop from the end point to A
            for (var i = arrMapData.length - 1; i >= 0; 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());
            if (loc_lat != '' && loc_lon != '')
            {
                objGMap.setCenter(new GLatLng(loc_lat, loc_lon), 9);
            }
            else
            {
                objGMap.setCenter(new GLatLng(mapCentreLat, mapCentreLon), 4);
            }
        }
    }
}

//-----------------------------------------------------------------------------
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();
    }
}


//-----------------------------------------------------------------------------
// Displays Image Upload within MFI
//-----------------------------------------------------------------------------
function OpenProfileImageUpload()
{
    var left = Math.floor((screen.width - 400) / 2);
    var top = Math.floor((screen.height - 200) / 2);
    
    var mywindow = window.open('/customscripts/uploadprofileImage.asp', 'upload', 'top=' + top + ', left=' + left + ', status=yes, resizable=no, width=550, height=420');
    if (mywindow != null)
    {
        if (mywindow.opener == null)
        {
            mywindow.opener = self;
        }
    }
    else
    {
        // Pop-up blocker could be on - in any case, warn user to turn them off
        var msg = 'We\'ve detected that you have Pop-up\'s Blocked.\n';
        msg += 'To open this window you\'ll need to allow pop-ups for the site.';
        
        alert(msg);
    }
}

//-----------------------------------------------------------------------------
function DeleteProfileImage()
{
    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, showProfileLink, imageID)
{
    getObj('fadeout').style.height = document.body.clientHeight;
    var Screenwidth = document.body.clientWidth;
    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)
    {
        //ie
        pos = document.documentElement.scrollTop
    }
    else if (document.body)
    {
        //ns
        pos = document.body.scrollTop
    }
    getObj('ImageGallery').style.left = (Screenwidth / 2) - 125 + 'px';
    getObj('ImageGallery').style.top = (100 + pos) + 'px';
    RunScript('/custom' + 'scrip' + 'ts/displ' + 'aygall' + 'ery.as' + 'p?id=' + listingId + '&spl=' + showProfileLink + '&imgID=' + imageID, '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 ShowNextQuoteRequestImage(totalPics, quoteRequestId)
{
    var nextImage = (+ getObj('CurrentImageID').value + 1);
    if (nextImage > totalPics - 1)
    {
        nextImage = 0;
    }
    var imageFile = 'Media/QuoteRequests/' + quoteRequestId + '/' + getObj('filename_' + nextImage).value;
    blendimage('blenddiv', 'blendimage', imageFile, 500, nextImage, totalPics);
}

//-----------------------------------------------------------------------------
function ShowPrevQuoteRequestImage(totalPics, quoteRequestId)
{
    prevImage = (+ getObj('CurrentImageID').value - 1);
    if (prevImage == -1)
    {
        prevImage = totalPics - 1;
    }
    var imageFile = 'Media/QuoteRequests/' + quoteRequestId + '/' + getObj('filename_' + prevImage).value;
    blendimage('blenddiv', 'blendimage', imageFile, 500, prevImage, totalPics);
}

//-----------------------------------------------------------------------------
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)
    {   // IE
        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, true);
                    break;
                case 'upper':
                    newText = selectedText.toUpperCase();
                    break;
            }
            rng.text = newText;
        }
    }
    else
    {   // NS
        var myField = getObj('newparagraph');
        var myValue = getObj('newparagraph').value;
        
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        
        var beforeSelection = myField.value.substring(0, startPos);
        var afterSelection = myField.value.substring(endPos, myField.value.length);
        
        var selectedText = myField.value.substring(startPos, endPos);
        var newText = '';
        switch (theType)
        {
            case 'lower':
                newText = selectedText.toLowerCase();
                break;
            case 'title':
                newText = TitleCase(selectedText, true);
                break;
            case 'upper':
                newText = selectedText.toUpperCase();
                break;
        }
        
        myField.value = beforeSelection + newText + afterSelection;
    }
}

//-----------------------------------------------------------------------------
// View type in listings / search
//-----------------------------------------------------------------------------
function DisplayMapOptions()
{
    // Shut view options / Sort Options
    if (getObj('ls_vw_options') != null)
        getObj('ls_vw_options').style.display = 'none';
    if (getObj('ls_st_options') != null)
        getObj('ls_st_options').style.display = 'none';
    
    var opDiv = getObj('ls_mp_options');
    if (opDiv.style.display == 'block') {
        opDiv.style.display = 'none';
    } else {
        opDiv.style.display = 'block';
    }
}
//-----------------------------------------------------------------------------
function ls_DisplayViewOptions()
{
    // Shut sort options...
    if (getObj('ls_st_options') != null)
        getObj('ls_st_options').style.display = 'none';
    if (getObj('ls_mp_options') != null)
        getObj('ls_mp_options').style.display = 'none';
    
    var opDiv = getObj('ls_vw_options');
    if (opDiv != null)
    {
        if (opDiv.style.display == 'block')
        {
            opDiv.style.display = 'none';
        }
        else
        {
            opDiv.style.display = 'block';
        }
    }
}

//-----------------------------------------------------------------------------
function ls_DisplaySortOptions()
{
    // Shut view options..
    if (getObj('ls_vw_options') != null)
        getObj('ls_vw_options').style.display = 'none';
    if (getObj('ls_mp_options') != null)
        getObj('ls_mp_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_MapType(SelMap)
{
    getObj('ls_map').value = SelMap;
    document.LsCtrlsForm.submit();
}

//-----------------------------------------------------------------------------
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();
}

//-----------------------------------------------------------------------------
function ValidatePoll(pollCount)
{
    var pollId = getObj('PollID').value;
    var pollVote = null;
    var pollAnswer = '';
    
    for (var i = 1; i <= pollCount; i++)
    {
        pollVote = getObj('PollVote_' + i);
        
        if (pollVote.checked)
        {
            pollAnswer = i;
        }
    }
    
    if (pollAnswer != '')
    {
        var url = '/customscripts/displaypoll.asp?vote=' + pollAnswer + '&PollID=' + pollId;
        RunScript(url, 'poll', '');
    }
    else
    {
        alert('Please select one answer to vote...');
    }
}

//-----------------------------------------------------------------------------
function GetIPInfo(ipAddress, fieldName)
{
    var url = '/customscripts/get_ipinfo.asp?ip=' + ipAddress;
    
    this.RunScript(url, 'ip_info_' + fieldName, '');
}

//-----------------------------------------------------------------------------
// BAC Vote Cast
function GiveCompliment(contentId, AuthorID)
{
    RunScript('/customscripts/F_GiveCompliment.asp?CID=' + contentId + '&AID=' + AuthorID, 'msg_' + contentId,'');
}

//-----------------------------------------------------------------------------
function EditExpert()
{
    var expert = getObj('expert');
    var expertAction = getObj('expert_action');
    if (expertAction != null)
    {
        expertAction.value = 'edit';
    }
    expert.submit();
}


//-----------------------------------------------------------------------------
function SaveExpert()
{
    var expert = getObj('expert');
    var expertAction = getObj('expert_action');
    if (expertAction != null)
    {
        expertAction.value = 'save';
    }
    expert.submit();
}


//-----------------------------------------------------------------------------
function PrintLinkSend(lid, action)
{
    var url = '/customscripts/profile_printlinksend.asp?id=' + lid + '&A=' + action;
    OpenCenteredWindow(url, '600', '680', 'testimonials', '');
}

//-----------------------------------------------------------------------------
function showTels(cid)
{
    RunScript('/customscripts/View' + 'T' + 'elDet' + 'ails.asp?id=' + cid, 'TelcomsInfo', '');
}

//-----------------------------------------------------------------------------
function showUserDetail(aid, e)
{
    RunScript('/customscripts/View' + 'U' + 'serDet' + 'ails.asp?id=' + aid,'ReviewUserInfo', '');

    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;

    getObj('ReviewUserInfo').style.display = 'block';
    getObj('ReviewUserInfo').style.left = (pos_x)-25 + 'px';
    getObj('ReviewUserInfo').style.top = (pos_y-151) + 'px';
}

//-----------------------------------------------------------------------------
function hideUserDetail() {
    getObj('ReviewUserInfo').style.display = 'none';
}

//-----------------------------------------------------------------------------
function SetUserImage(imageIndex)
{
    // Grey out all of the images then set the selected images border to Red
    var img_preview = getObj('img_preview');
    img_preview.style.border = '1px solid #ccc';
    
    // Then set the hidden field name to the appropriate file name
    var img_stock = null;
    for (var i = 1; i <= 6; i++)
    {
        img_stock = getObj('img_stock_' + i);
        img_stock.style.border = '1px solid #ccc';
    }
    
    var img_selected = null;
    var user_photo = getObj('user_photo');;
    if (imageIndex != '0')
    {
        img_selected = getObj('img_stock_' + imageIndex);
        img_selected.style.border = '2px solid #c00';
        
        user_photo = getObj('user_photo');
        user_photo.value = 'fi_avatar_' + imageIndex + '.gif';
    }
    else
    {
        img_preview.style.border = '2px solid #c00';
        
        user_photo.value = getObj('user_photo_perm').value;
    }
}

//-----------------------------------------------------------------------------
function DeleteUserImage()
{
    // Set the user image to the upload one and change the border style
    var img_preview = getObj('img_preview');
    img_preview.style.border = '1px solid #ccc';
    
    img_preview.src = '/customscripts/systemfunctions/showimage.asp?folder=UserPics&img=fi_avatar_upload.gif&maxW=45&maxH=70';
    
    // Set default selected image
    var img_selected = getObj('img_stock_1');
    img_selected.style.border = '2px solid #c00';
    
    // Hide the image delete div
    var image_delete = getObj('image_delete');
    image_delete.style.display = 'none';
    
    var image_to_delete = getObj('image_to_delete');
    image_to_delete.value = getObj('user_photo').value;
}

//-----------------------------------------------------------------------------
function DeleteLogo()
{
    // Set the logo to the upload one and change the border style
    var img_preview = getObj('img_preview');
    img_preview.style.border = '1px solid #ccc';
    
    img_preview.src = '/media/listinglogos/default_logo.gif';
    
    // Show the image upload link again.
    var image_upload = getObj('image_upload');
    image_upload.style.display = '';
    
    
    // Hide the image delete link
    var image_delete = getObj('image_delete');
    image_delete.style.display = 'none';
    
    // Set the hidden logo to nothing
    var logo_hid = getObj('logo_hid');
    logo_hid.value = '';
}

//-----------------------------------------------------------------------------
function ShowAdminAnalysis()
{
    getObj('analysis').style.display = 'block';
}

//-----------------------------------------------------------------------------
function InboxDelete(strPage)
{
    var yes_no = confirm('Are you sure you want to delete\nthe selected items from your Inbox?');
    if (yes_no == true)
    {
        var checkboxes = document.getElementsByTagName('input');
        
        var toDelete = '';
        var msgId = '';
        var inbox_td;
        for(var j = 0; j < checkboxes.length; j++)
        {
            if (checkboxes[j].className == 'inbox_delete')
            {
                if (checkboxes[j].checked == true)
                {
                    msgId = Replace(checkboxes[j].id, 'msg_', '');
                    toDelete += msgId + '|';
                    
                    inbox_td = getObj('inbox_td_msg_' + msgId);
                    if (inbox_td != null)
                    {
                        inbox_td.style.display = 'none';
                    }
                }
            }
        }
        
        var url = '/customscripts/inbox_delete.asp?ids=' + toDelete;
        RunScript(url, '', '');
    }
}

//-----------------------------------------------------------------------------
// Formats a postcode. Converts 'BS79BL to BS7 9BL', 'bs482hj to BS48 2HJ'
// Called when the postcode field loses focus on an onblur event.
// Also sets other postcode fields with the new value.
//-----------------------------------------------------------------------------
function FormatPostcode(fieldName)
{
    var objPostcode = getObj(fieldName);
    if (objPostcode != null)
    {
        var strPostcode = objPostcode.value;
    
        // Reformat postcode
        if (strPostcode != 'Full Postcode' && strPostcode != '')
        {
            var thisPC = Replace(strPostcode, ' ', '');
            var lastThreeDigits = Right(strPostcode, 3);
            var strPostcode = Replace(thisPC, lastThreeDigits, '') + ' ' + lastThreeDigits;
            strPostcode = strPostcode.toUpperCase();
            objPostcode.value = strPostcode;
        
            // If empty, set the other postcodes to be the same as the top one.
            if (getObj('postcode'))
            {
                if (getObj('postcode').value == '')
                {
                    getObj('postcode').value = strPostcode;
                }
            }
            if (getObj('user_postcode'))
            {
                if (getObj('user_postcode').value == '')
                {
                    getObj('user_postcode').value = strPostcode;
                }
            }
            
            return strPostcode;
        }
    }
}

//-----------------------------------------------------------------------------
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

//-----------------------------------------------------------------------------
// Submit the 'get a quote' form
//-----------------------------------------------------------------------------
function GetAQuote()
{
    // Submit the form
    document.quote_form.submit();
}

//-----------------------------------------------------------------------------
function UploadQuoteFile(file123)
{
    var left = Math.floor((screen.width - 400) / 2);
    var top = Math.floor((screen.height - 200) / 2);
    
    var mywindow = window.open('/customscripts/quote_upload.asp?file123=' + file123, 'upload', 'top=' + top + ', left=' + left + ', status=yes, resizable=no, width=400, height=320');
    if (mywindow != null)
    {
        if (mywindow.opener == null)
        {
            mywindow.opener = self;
        }
    }
    else
    {
        // Pop-up blocker could be on - in any case, warn user to turn them off
        var msg = 'We\'ve detected that you have Pop-up\'s Blocked.\n';
        msg += 'To open this window you\'ll need to allow pop-ups for the site.';
        
        alert(msg);
    }
}

//-----------------------------------------------------------------------------
function searchleads(sortBy, thePage, selCatId)
{
    var lead_option = getObj('lead_option');
    var leadL2 = getObj('LeadL2s');
        
    if (selCatId == '')
    {   // Get the selected category id from the search combos
        if (lead_option != null)
        {
            selCatId = lead_option[lead_option.selectedIndex].value
            
            if (selCatId == '0')
            {
                if (leadL2[leadL2.selectedIndex].value != '')
                {
                    selCatId = leadL2[leadL2.selectedIndex].value;
                }
            }
        }
        else if (leadL2 != null && leadL2.selectedIndex != null)
        {
            selCatId = leadL2[leadL2.selectedIndex].value;
        }
    }
    
    // Set the lead_cats to be this value.
    getObj('lead_cats').value = selCatId;
    
    var sort_by = getObj('sort_by');
    sort_by.value = sortBy;
    
    var leads_postcode = getObj('leads_postcode');
    if (leads_postcode != null)
    {
        if (leads_postcode.value == 'FULLPOSTC ODE' || leads_postcode.value == 'FULL POSTC ODE')
        {
            leads_postcode.value = 'Full Postcode'
        }
        
        if (leads_postcode.value == '' || leads_postcode.value == 'Full Postcode')
        {
            leads_postcode.style.border = '2px solid #c00';
            leads_postcode.style.color = '#999';
            leads_postcode.value = 'Full Postcode';
        }
        else
        {
            leads_postcode.style.border = 'none';
            leads_postcode = FormatPostcode('leads_postcode');
        }
    }
    
    document.search.action = '/searchresults.asp?leads=1&p=' + thePage;
    document.search.submit();
}

//-----------------------------------------------------------------------------
function SetLeadCatOptions(selCat2, selCatId)
{
    // Run when a page is loaded and you want the combos to be set to the
    // passed in cats
    
    // selCat2 selects the L2 combo item
    // selCatId selects the sub cat combo
    if (getObj('LeadL2s') != null)
    {
        // Select the right L2 cat
        var theL2Selector = getObj('LeadL2s');
        for (var i = 0; i < theL2Selector.length; i++)
        {
            theL2Selector[i].selected = false;
            if (theL2Selector[i].value == selCat2)
            {
                theL2Selector[i].selected = true;
            }
        }
        
        // Load the sub cats
        var url = '/customscripts/displayQRL3Options.asp?cat2=' + selCat2 + '&catid=' + selCatId;
        RunScript(url, 'L3Options', '');
    }
}

//-----------------------------------------------------------------------------
function LoadLeadCatOptions()
{
    // Run when LeadL2s.onchange to reload the subcats
    
    // Loads the Type of Lead combo boxes with values in cat_id and the combo
    if (getObj('LeadL2s') != null)
    {
        var theL2Selector = getObj('LeadL2s');
        var cat2 = theL2Selector.options[theL2Selector.selectedIndex].value;
        
        var catId = '';
        if (getObj('cat_id') != null)
        {
            catId = getObj('cat_id').value;
        }
        
        var url = '/customscripts/displayQRL3Options.asp?cat2=' + cat2 + '&catid=' + catId;
        RunScript(url, 'L3Options', '');
    }
}

//-----------------------------------------------------------------------------
function ChangeLeadsLocation()
{
    getObj('leads_postcode_disp').style.display = 'none';
    
    getObj('leads_postcode_input').style.display = 'block';
}

//-----------------------------------------------------------------------------
function ShowLeadImages(quoteRequestId)
{
    var fadeout = getObj('fadeout');
    var gallery = getObj('ImageGallery');
    
    if (fadeout != null && gallery != null)
    {
        fadeout.style.height = document.body.clientHeight;
        var screenWidth = document.body.clientWidth;
        fadeout.style.display = 'block';
        changeOpac(60, 'fadeout');
        
        gallery.style.display = 'block';
    
        if (window.pageYOffset)
        {
              pos = window.pageYOffset
        }
        else if (document.documentElement && document.documentElement.scrollTop)
        {
            //ie
            pos = document.documentElement.scrollTop
        }
        else if (document.body)
        {
            //ns
            pos = document.body.scrollTop
        }
        
        gallery.style.left = (screenWidth / 2) - 125 + 'px';
        gallery.style.top = (100 + pos) + 'px';
        
        var url = '/customscripts/displayleadimages.asp?id=' + quoteRequestId;
        RunScript(url, 'ImageGallery', '');
    }
}

//-----------------------------------------------------------------------------
function DeleteLeadFile(fileNumber, bUpload)
{
    var quoteFile = getObj('quote_file' + fileNumber);
    if (quoteFile != null)
    {
        quoteFile.value = '';
        
        var quoteFileDiv = getObj('file' + fileNumber);
        if (quoteFileDiv != null)
        {
            quoteFileDiv.style.float = 'left';
            quoteFileDiv.style.marginRight = '10px';
            quoteFileDiv.style.border = '1px solid #999';
            quoteFileDiv.style.padding = '5px';
            
            if (bUpload == 'True')
            {
                quoteFileDiv.innerHTML = '<img src="/fx/mfi_lead.gif">&nbsp;<a href="javascript:UploadQuoteFile(' + fileNumber + ');" class="lightblue">Upload File ' + fileNumber + '</a>';
            }
            else
            {
                quoteFileDiv.innerHTML = '-';
            }
        }
    }
}

//-----------------------------------------------------------------------------
function confirmcloseQR() {
    var bad = '';
    
	if ((!getObj('hirecompany')[0].checked) && (!getObj('hirecompany')[1].checked)) {
		bad += 'Did our service help you hire a company ?\n'
	}
	if ((!getObj('useagain')[0].checked) && (!getObj('useagain')[1].checked)) {
		bad += 'Would you use the service again ?\n'
	}
	
    if (bad != '')
    {
        msg = 'Please help us improve .\n'
        msg += '-------------------------------------------------------\n'
        alert(msg + bad);
    }
    else
    {
        document.feedback.submit();
    }
	
	
}

//-----------------------------------------------------------------------------
function ShowMoreFeedback(id)
{
    // Hide all feedback full divs
    var arrDivs = document.getElementsByTagName('div');
    var feedbackFull;
    var feedbackSnip;
    var feedbackMore;
    var feedbackId;
    
    for (var i = 0; i < arrDivs.length; i++)
    {
        feedbackFull = arrDivs[i].id;
        if (feedbackFull.lastIndexOf('feedback_text_full_') > -1)
        {
            // Hide the full text
            arrDivs[i].style.display = 'none';
            
            feedbackId = Replace(feedbackFull, 'feedback_text_full_', '');
            
            // Display the snippet
            feedbackSnip = getObj('feedback_text_snippet_' + feedbackId);
            if (feedbackSnip != null)
            {
                feedbackSnip.style.display = 'block';
            }
            
            // Display the more icon
            feedbackMore = getObj('feedback_more_' + feedbackId);
            if (feedbackMore != null)
            {
                feedbackMore.style.display = 'block';
            }
        }
    }
    
    // Expand the selected one
    feedbackFull = getObj('feedback_text_full_' + id);
    if (feedbackFull != null)
    {
        // Display the full text
        feedbackFull.style.display = 'block';
        
        // Hide the snippet
        feedbackSnip = getObj('feedback_text_snippet_' + id);
        if (feedbackSnip != null)
        {
            feedbackSnip.style.display = 'none';
        }
        
        // Hide the more icon
        feedbackMore = getObj('feedback_more_' + id);
        if (feedbackMore != null)
        {
            feedbackMore.style.display = 'none';
        }
    }
}

//-----------------------------------------------------------------------------
function AddLeadCat()
{
    document.forms.lead_add_cat.submit();
}

//-----------------------------------------------------------------------------
function PreviewOfferText(text) {
    if (text == '') {
        getObj('offer_title').innerHTML = 'A special offer will not be displayed on your page if you do enter any text.'
    } else {
        getObj('offer_title').innerHTML = text;
    }
}


// Ajax Home Page Content
//-----------------------------------------------------------------------------
function showHomePageContent(seltab) {
    var url = '/customscripts/displayHomeWhatsNew.asp?type=' + seltab;
    RunScript(url, 'whatsnew', '');
}

// Refreshes Quote category when not enough companies found and user clicks on suggestion
//--------------------------------------------------------------------------------------
function RefreshQuoteCat(newcatid)
{
    getObj('quote_cat_id').value = newcatid;
    document.quote_form.submit();
}

//-----------------------------------------------------------------------------
function SetLeadSetting(listingId, theType, value)
{
    // Change the way the radio buttons get displayed
    var lead_email_me_on = getObj('lead_email_me_on');
    var lead_email_me_off = getObj('lead_email_me_off');
    var lead_text_me_on = getObj('lead_text_me_on');
    var lead_text_me_off = getObj('lead_text_me_off');
    var bRunScript = true;
    
    if (theType == 'lead_email_me')
    {
        var no_alerts = getObj('no_alerts');
        if (value == 'on')
        {
            lead_text_me_on.disabled = false;
            lead_text_me_off.disabled = false;
            no_alerts.style.display = 'none';
        }
        else
        {
            var bYesNo = confirm('Are you sure you don\'t want to be notified\nwhen new Leads arrive in your area?')
            if (bYesNo == true)
            {
                lead_text_me_on.disabled = true;
                lead_text_me_off.disabled = true;
                no_alerts.style.display = 'block';
            }
            else
            {
                lead_email_me_on.checked = true;
                lead_email_me_off.checked = false;
                
                lead_text_me_on.disabled = false;
                lead_text_me_off.disabled = false;
                no_alerts.style.display = 'none';
                
                bRunScript = false;
            }
        }
    }
    
    // Run some ajax to change the dB
    if (bRunScript == true)
    {
        var url = '/customscripts/SetLeadSettings.asp?id=' + listingId + '&t=' + theType + '&v=' + value;
        RunScript(url, '', '');
    }
}

//-----------------------------------------------------------------------------
function AddLeadCategory()
{
    var form_action = getObj('form_action');
    form_action.value = 'add';
    
    var newCategory = getObj('NewCategory').value;
    if (newCategory == '')
    {
        alert('Please select a category.');
    }
    else
    {
        document.forms.cat_form.submit();
    }
}

//-----------------------------------------------------------------------------
function DeleteLeadCategory(tbId)
{
    if (confirm('Are you sure?'))
    {
        var form_action = getObj('form_action');
        form_action.value = 'delete';
        
        var delete_id = getObj('delete_id');
        delete_id.value = tbId;
        
        document.forms.cat_form.submit();
    }
}

// Makes sure hovered tab stays selected when user moves off tab...
//-----------------------------------------------------------------------------
function tabhover(e, hovertab, seltab, onoff) {
	//onmouseout=""tabhover(event,'directory','<direct>',0);
	if (onoff == 0) {
        // Cancel Hover - Choose class depending on whether this tab is active..
		getObj('items_' + hovertab).style.display='none';
        if (seltab == '_on') {
            getObj(hovertab).className = 'qmparent_on';
        } else {
            getObj(hovertab).className = 'qmparent';
        }
    } else {
        // Show hover tab
		getObj('items_' + hovertab).style.display='block';
        getObj(hovertab).className = 'qmparenthover'; 
    }
    return true;
}

//-----------------------------------------------------------------------------
function ControlLeadsResponseForm(what)
{
    switch (what)
    {
        case 'price':
			var theSelectOption = getObj('pricetype').options[getObj('pricetype').selectedIndex].value;
			if ((theSelectOption == 1) || (theSelectOption == 2))
				getObj('pricediv').style.display = 'block';
			else
				getObj('pricediv').style.display = 'none';
				
        case 'availability':
			var theSelectOption = getObj('availabilitytype').options[getObj('availabilitytype').selectedIndex].value;
			if (theSelectOption != 2)
				getObj('availabilitydiv').style.display = 'none';
			else
				getObj('availabilitydiv').style.display = 'block';
		
		case 'delivery':
			var theSelectOption = getObj('deliverytype').options[getObj('deliverytype').selectedIndex].value;
			if ((theSelectOption == 1) || (theSelectOption == 2))
				getObj('deliverdiv').style.display = 'block';
			else
				getObj('deliverdiv').style.display = 'none';
				
    }
}




//********************************************************************
//OLD
//OLD
//OLD
//********************************************************************

/*

function CheckNameChange()
{
    var bad = '';
    if (getObj('name').value == '')
    {
        bad += '- Please enter your full name.\n';
    }
        
    if (bad != '')
    {
        alert(bad);
    }
    else
    {
        document.changename.submit();
    }
}

//-----------------------------------------------------------------------------
// 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';
}


function SaveAnswer(bInsert)
{
    getObj('SaveSomething').value = 'true';
}

//-----------------------------------------------------------------------------
function OpenExpertCatsWindow()
{
    var expertId = getObj('expertid').value;
    var args = 'toolbar=0,status=1,menubar=0,scrollbars=1,resizable=0';
    OpenCenteredWindow('/customscripts/SelectExpertCats.asp?expertid=' + expertId, 375, 650, null, args);
}


//-----------------------------------------------------------------------------
function ConfirmWebLink()
{
    var webaddress = getObj('website_to_check').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 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 ShowExpertTerms()
{
    getObj('show_terms').value = 'show';
    document.forms.expert.submit();
}

//-----------------------------------------------------------------------------
function ExpertDeletePhoto()
{
    var prevImg = getObj('prevImg');
    if (prevImg != null)
    {
        prevImg.src = '/fx/bac_userpic.gif';
    }
    var photo = getObj('photo');
    if (photo != null)
    {
        photo.value = '';
    }
}

//-----------------------------------------------------------------------------
function HideShowComment(action, id)
{
    if (action == 'H')
    {
        getObj('ShowHideCom').value = 'HideComment';
        getObj('ShowHideCommentID').value = id;
    }
    else
    {
        getObj('ShowHideCom').value = 'ShowComment';
        getObj('ShowHideCommentID').value = id;
    }
    getObj('HidecomForm').submit();
}


//-----------------------------------------------------------------------------
function QuoteSearching()
{
    var quote_results = getObj('quote_results');
    if (quote_results != null)
    {
        quote_results.innerHTML = '<img src="/fx/fi_loading.gif" />';
    }
}


//-----------------------------------------------------------------------------
function SelectQuoteItem(listingId)
{
    var itemRow = getObj('quote_row_' + listingId);
    var itemCheckbox = getObj('cid_' + listingId);
    
    if (itemRow != null && itemCheckbox != null)
    {
        if (itemCheckbox.checked == true)
        {
            itemRow.style.backgroundColor = '#DFF4DF';
        }
        else
        {
            itemRow.style.backgroundColor = 'transparent';
        }
    }
    
    // Check we havent got more than 5 selected...
    var arrBoxes = document.getElementsByTagName("input");
    var nChecked = 0;
    
    for (var i = 0; i < arrBoxes.length; i++)
    {
        var divName = arrBoxes[i].id;
        if (divName.lastIndexOf("cid_") > -1)
        {
            if (arrBoxes[i].checked == true)
            {
                nChecked += 1;
            }
        }
    }
    if (nChecked > 5)
    {
        itemRow.style.backgroundColor = 'transparent';
        itemCheckbox.checked = false;
        alert("Please only select up to 5 companies. Please de-select some first, before adding more..");
    }
}


//-----------------------------------------------------------------------------
function QuoteDisplayQuickInfo(listingId)
{
    // Close all company detail divs
    var arrDivs = document.getElementsByTagName('div');
    var len = arrDivs.length;
    company_details_div = null;
    
    for (var i = 0; i < len; i++)
    {
        var divname = arrDivs[i].id;
        if (divname.lastIndexOf('company_details_') > -1)
        {
            var divID = divname.substr(divname.lastIndexOf('_') + 1);
            company_details_div = arrDivs[i];
            company_details_div.style.display = 'none';
        }    
    }
        
    // Open the selected item
    company_details_div = getObj('company_details_' + listingId);
    company_details_div.style.display = 'block';
}

//-----------------------------------------------------------------------------
function QuoteHideQuickInfo(listingId)
{
    var company_details_div = getObj('company_details_' + listingId);
    company_details_div.style.display = '';
}


//-----------------------------------------------------------------------------
function QuoteSelectTimescale(combo)
{
    if (combo.selectedIndex == 1)
    {
        getObj("quote_dateentry").style.display = 'block';
    }
    else
    {
        getObj("quote_dateentry").style.display = 'none';
    }
}

//-----------------------------------------------------------------------------
function LeadSelectPage()
{
    // Changes the page of a list of pages
    if (getObj('pg') != null)
    {
        var thePager = getObj('pg');
        var newPage = thePager.options[thePager.selectedIndex].value;
        
        searchleads(newPage);
    }
}


//-----------------------------------------------------------------------------
function SelectLeadsCats()
{
    var args = 'toolbar=0,status=1,menubar=0,scrollbars=1,resizable=0';
    OpenCenteredWindow('/customscripts/SelectLeadsCats.asp', 375, 650, null, args);
}

//-----------------------------------------------------------------------------
function ShowLeadsCats(newCatIds)
{
    var url = '/customscripts/mfi_leads_search.asp?action=show_sel_cats&catIds=' + newCatIds;
    
    RunScript(url, 'catIds_disp', '');
}

//-----------------------------------------------------------------------------
function OpenTagWindow() {
    var TagIDs = getObj('tagids').value;
    var CatID = getObj('CategoryID1').value;
    var args = 'toolbar=0,status=1,menubar=0,scrollbars=1,resizable=0';
    OpenCenteredWindow('/customscripts/SelectTags.asp?catid=' + CatID + '&tagids=' + TagIDs, 375, 650, null, args)
}

*/
