// Generic Settings for JQuery
var ajax_load = "<img src='fx/progress.gif' alt='loading...' />";
$.ajaxSetup ({cache: false});

// Window Completely Loaded - JQuery Handlers 
//-----------------------------------------------------------------------------
$(window).load(function() {
    // Make fullwidth Template height of screen if less than a certain amount...
    if ($('#fullwidth_container').length > 0) {
        var divHeight = $('#fullwidth_container').height();
        var ScreenHeight = $(window).height();
        var footer_offset = 483;
        if (($('#selectedtab').val() == 'mfi') || ($('#selectedtab').val() == 'inbox')) {
            footer_offset = 240
        }
        
        if (divHeight+footer_offset < ScreenHeight) {
            $('#fullwidth_container').height(ScreenHeight - footer_offset);
        }
    }
});

// Dom Ready - JQuery Handlers 
//-----------------------------------------------------------------------------
$(document).ready(function() {
    
    // Tab Nav Drop Downs
    $('.tab,.tab_on').mouseenter(function() {
        $('#tabnav').stop(true, true).fadeOut('fast');
        $('.tab_rollover').removeClass('tab_rollover');

        $(this).addClass('tab_rollover');

        var offset = $(this).offset();
        $('#tabnav').html("<br /><br /><br /><br />" + ajax_load).load('/customscripts/ajax_tabnav.asp', 'tab=' + $(this).attr('id'));
        $('#tabnav').css('left', offset.left - 2);
        $('#tabnav').stop(true, true).fadeIn();
    });


    // Close TabNav if Mouse goes out of box
    $('#tabnav').mouseleave(function() {
        $('#tabnav').stop(true, true).fadeOut('fast');
        $('.tab_rollover').removeClass('tab_rollover');
    });

    // Close TabNav if Mouse goes above Menu Bar or below Tab Nav Height
    $(document).mousemove(function(e) {
        if ($('#tabnav').css('display') == 'block') {
            if ((e.pageY < 65) || (e.pageY > 430)) {
                $('.tab_rollover').removeClass('tab_rollover');
                $('#tabnav').stop(true, true).fadeOut('fast');
            }
        }
    });

    // Show Suggestions for what Search
    $('#SrchKeyword').keyup(function() {
        if (($('#ShowSuggestions').val() == "1") && ($('#SrchKeyword').val().length > 2)) {
            var kwType = $('#selectedtab').val();
            $('#keyword_suggestions').html(ajax_load).load('/customscripts/ajax_search_suggestions.asp', "o=SrchKeyword&h=keyword_suggestions&q=" + $('#SrchKeyword').val() + "&kwtype=" + kwType, function() {
                $("#keyword_suggestions").slideDown();
                //Hide Suggestion Box if no suggestions
                if ($('#num_kw_suggestions').text() == '0') {
                    $("#keyword_suggestions").hide();
                }
            });
        } else {
            $("#keyword_suggestions").hide();
        }
    });

    // Show Suggestions for Location Search
    $('#SrchLocation').keyup(function() {
        if ($('#SrchLocation').val().length > 2) {
            $('#keyword_locations').html(ajax_load).load('/customscripts/ajax_search_suggestions.asp', "o=SrchLocation&h=keyword_locations&q=" + $('#SrchLocation').val() + "&kwtype=location", function() {
                $("#keyword_locations").slideDown();
                //Hide Suggestion Box if no suggestions
                if ($('#num_loc_suggestions').text() == '0') {
                    $("#keyword_locations").hide();
                }
            });
        } else {
            $("#keyword_locations").hide();
        }
    });

    // Submit Search on Enter Press
    $('#SrchKeyword,#SrchLocation').bind('keypress', function(e) {
        if (e.keyCode == 13) {
            SearchGo();

        }
    });

    // Clear Contents of Search on click
    $('#SrchKeyword,#SrchLocation').click(function() {
        var Typed = $(this).val();
        var TipsField = (this.name + '_Tips');
        var Tips = $('#' + TipsField).val();
        if (Typed == Tips) {
            $(this).val('');
            $(this).css('color', '#000');
        }
    });

    // Put Search tips back in if empty text
    $('#SrchKeyword,#SrchLocation').focusout(function() {
        if ($(this).val() == '') {
            var TipsField = (this.name + '_Tips');
            $(this).val($('#' + TipsField).val());
            $(this).css('color', '#999');
        }
    });

    // Hide Search Suggestion on Blur
    $('#SrchKeyword,#SrchLocation').blur(function() {
        $("#keyword_suggestions").hide();
        $("#keyword_locations").hide();
    });


    // Submit Search
    $('#submitsearch').click(function(e) {
        e.preventDefault();
        SearchGo();
    });

    //---------------------------

    // Gallery thumbnail hover
    $('.thumb_box').hover(function() {
        $(this).fadeTo('fast', '1');
    });
    $('.thumb_box').mouseleave(function() {
        $(this).fadeTo('fast', '0.8');
    });

    $('.thumb').click(function() {
        var iid = Replace($(this).attr('id'), 't', '');
        var fullsize = "\\media\\" + $(this).attr('name');

        $('#mainImg').fadeOut('fast', function() {
            $('#mainImg').attr('src', fullsize).fadeTo('slow', '1');
        });
        $('#caption').text($(this).attr('alt'));
        $('#uploaded').text('Uploaded : ' + $(this).attr('title'));
    });

    // Gallery pager
    $('.imgpager').click(function() {
        var amount = $(this).attr('id')
        $('#inner').animate({ right: amount });
        $('.imgpager').css('background-color', '#666')
        $(this).css('background-color', '#fff');
    });

    // Gallery next / prev
    $('#pic_container').mouseenter(function() {
        $('#btn_prev').fadeTo('fast', 1);
        $('#btn_next').fadeTo('fast', 1);
    });
    $('#pic_container').mouseleave(function() {
        $('#btn_next').hide();
        $('#btn_prev').hide();
    });
    $('#pic_container').mouseover(function() {
        $('#btn_prev').css('top', ($('#mainImg').height() / 2) - 25);
        $('#btn_next').css('top', ($('#mainImg').height() / 2) - 25);
        $('#btn_next').css('left', $('#mainImg').width() - 48);
    });
    $('#btn_prev').mouseenter(function() {
        $('#btn_prev_img').css('opacity', 0.8);
    });
    $('#btn_prev').mouseleave(function() {
        $('#btn_prev_img').css('opacity', 0.5);
    });
    $('#btn_next').mouseenter(function() {
        $('#btn_next_img').css('opacity', 0.8);
    });
    $('#btn_next').mouseleave(function() {
        $('#btn_next_img').css('opacity', 0.5);
    });
    $('#btn_next').mousedown(function() {
        // Loop through thumbs to find current index
        var currentIndex;
        var nImages = 0;
        $('.thumb').each(function(index, obj) {
            if ('\\media\\' + obj.name == $('#mainImg').attr('src')) {
                currentIndex = index;
            }
            nImages++;
        });

        var newIndex = currentIndex + 1;
        if (currentIndex == (nImages - 1)) {
            newIndex = 0;
        }
        var imgSrc = '\\media\\' + $('#t' + newIndex).attr('name');
        var imgAlt = $('#t' + newIndex).attr('alt');
        var imgTitle = $('#t' + newIndex).attr('title');

        $('#mainImg').attr('src', imgSrc).fadeTo('slow', '1');
        $('#caption').text(imgAlt);
        $('#uploaded').text('Uploaded : ' + imgTitle);
    });
    $('#btn_prev').mousedown(function() {
        // Loop through thumbs to find current index
        var currentIndex;
        var nImages = 0;
        $('.thumb').each(function(index, obj) {
            if ('\\media\\' + obj.name == $('#mainImg').attr('src')) {
                currentIndex = index;
            }
            nImages++;
        });

        var newIndex = currentIndex - 1;
        if (newIndex < 0) {
            newIndex = nImages - 1;
        }
        
        var imgSrc = '\\media\\' + $('#t' + newIndex).attr('name');
        var imgAlt = $('#t' + newIndex).attr('alt');
        var imgTitle = $('#t' + newIndex).attr('title');

        $('#mainImg').attr('src', imgSrc).fadeTo('slow', '1');
        $('#caption').text(imgAlt);
        $('#uploaded').text('Uploaded : ' + imgTitle);
    });

    // Show account menu
    $("#AccountMenu").click(function() {
        $("#AccountMenu_options").slideToggle();
    });
    $("#AccountMenu_options").mouseleave(function() {
        $("#AccountMenu_options").fadeOut();
    });

    // Show Listings Toolbar ViewType Menu
    $("#viewtype_openarrow").click(function() {
        $("#viewtype_options").slideToggle();
    });
    $("#viewtype_options").mouseleave(function() {
        $("#viewtype_options").fadeOut();
    });

    // Show Listings Toolbar Range Menu
    $("#location_openarrow").click(function() {
        $("#location_options").slideToggle();
    });
    $("#location_options").mouseleave(function() {
        $("#location_options").fadeOut();
    });

    // Show Form Help Tips
    $('.formfield').focus(function() {
        if (('#FVal_' + $(this).attr('name')).length > 0) {
            $('#FVal_' + $(this).attr('name')).hide();
        }
        if (('#FTip_' + $(this).attr('name')).length > 0) {
            $('#FTip_' + $(this).attr('name')).fadeIn();
        }
    });

});

//-----------------------------------------------------------------------------
function toggleSubcats() {
    $("#listings_subcats").slideToggle(function() {
        if ($("#listings_subcats").css('display') == 'none') {
            $("#updownarrow").attr('src', '/fx/arrow-down.gif');
            $("#updowntext").html('Show Navigation');
            jQuery.ajax('/customscripts/ajax_subcats_showhide.asp?display=0');
        } else {
            $("#updownarrow").attr('src', '/fx/arrow-up.gif');
            $("#updowntext").html('Hide');
            jQuery.ajax('/customscripts/ajax_subcats_showhide.asp?display=1');
        }
    });	
}

//-----------------------------------------------------------------------------
function SearchClickSuggest(value, locationId, objSearchInputBox, kwSuggestionsDivName) {

    // Set the value of the search input box
    $('#' + objSearchInputBox).val(value);
    
    // Set a hidden location id field if an id has been set
    if (locationId != '0')
        $('#loc_id').val(locationId);

    // Hide the suggestion box
    $('#' + kwSuggestionsDivName).hide();
}

//-----------------------------------------------------------------------------
function SearchGo() {
	var kw = $('#SrchKeyword').val();
	
	if ((kw.length < 3) || (kw == $('#SrchKeyword_Tips').val())) {
		alert('Please enter a keyword of at least 3 characters in length');
	} else {
    	var loc = $('#SrchLocation').val();
		var locationId = $('#loc_id').val();
		
		if (loc == $('#SrchLocation_Tips').val()) {
    		loc = '';
		}
    	kw = Replace(kw, ' ', '_');
		kw = Replace(kw, '&', ' and ');
		
		searchType =  $('#selectedtab').val();
		
		$('#submitsearchtd').html(ajax_load);
		url = '/searchresults.htm?searchType=' + searchType + '&k=' + kw.toLowerCase() + '&l=' + loc.toLowerCase() + '&locid=' + locationId
		url = Replace(url,' ','_');
        window.location.href = url;
	}
}

//-----------------------------------------------------------------------------
// 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) {
    var sText = getObj(theField).value;
    sText = Trim(sText);
    var validChars = "0123456789.:";
    var bIsNumber = true;
    var aChar;
    for (var i = 0; i < sText.length && bIsNumber == true; i++) {
        aChar = sText.charAt(i);
        if (validChars.indexOf(aChar) == -1) {
            bIsNumber = false;
        }
    }
    return bIsNumber;
}

//-----------------------------------------------------------------------------
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 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);
    }
}

//-----------------------------------------------------------------------------
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;
}

//-----------------------------------------------------------------------------
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;
}

//-----------------------------------------------------------------------------
// 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 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;
}

//-----------------------------------------------------------------------------
// If on a subdomain page - generate the basehref to add to Ajax Calls...
//-----------------------------------------------------------------------------
function GetSubDomBaseHref() {
    var theURL = window.location.href;
    theURL = theURL.toLowerCase();
    theURL = Replace(theURL, 'http://www.', '');
    theURL = Replace(theURL, 'http://', '');
    if (theURL.indexOf('.freeindex') != -1) {
        return window.location.href;
    } else {
        return '';
    }
}

//-----------------------------------------------------------------------------
// 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">';
        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">';
            s += '<a target="_blank" style="line-height:25px;" 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 - Fills in All AFS AD Blocks
//-----------------------------------------------------------------------------
function GetAFSAds(afs_query, afs_channel, strAdType) {
    var bgColour = '';
    var titleColour = '#52662C';
    
    if (strAdType.indexOf('job') >= 0) {
        bgColour = '#F7EAE8';
        titleColour = '#833B2D';
    } else if (strAdType.indexOf('event') >= 0) {
        bgColour = '#E7F1F8';
        titleColour = '#2C6F9A';
    } else if (strAdType.indexOf('lead') >= 0) {
        bgColour = '#F9EFD8';
        titleColour = '#AA7C28';
    } else if (strAdType.indexOf('forum') >= 0) {
        bgColour = '#FAF5FA';
        titleColour = '#A55D9F';
    }
    
    var pageOptions = {
    'pubId' : 'pub-3230112801643320',
    'query' : afs_query,
    'channel' : afs_channel,
    'linkTarget' : '_blank',
    'hl' : 'en',
    'rolloverAdBackgroundColor' : '',
	'rolloverLinkBold' : true,
	'rolloverLinkUnderline' : true,
	'rolloverLinkBackgroundColor' : '',
	'rolloverLinkColor' : '#cc0000',
    'lines' : '3',
    'fontFamily' : 'arial',
    'fontSizeTitle' : '19px',
    'fontSizeDescription' : '13px',
    'fontSizeDomainLink' : '12px',
    'colorTitleLink' : titleColour,
    'colorText' : '#999',
    'colorAdBorder' : '#ccc', 
    'colorDomainLink' : '#000000',
    'titleBold' : true,
    'siteLinks' : false,
    'sellerRatings' : false
    };
    
    if ((typeof(afs_MID) != 'undefined')) {
        new google.ads.search.Ads(pageOptions, afs_TOP, afs_MID, afs_BTM);
    } else {
        new google.ads.search.Ads(pageOptions, afs_TOP, afs_BTM);
    }
}

//-----------------------------------------------------------------------------
// Google AdSense for Search TEST FORMAT - Fills in All AFS AD Blocks with new format for testing
//-----------------------------------------------------------------------------
function GetAFSAdsTestFormat(afs_query, afs_channel) {
    var pageOptions = {
    'pubId' : 'pub-3230112801643320',
    'query' : afs_query,
    'channel' : afs_channel,
    'linkTarget' : '_blank',
    'hl' : 'en',
	'rolloverLinkBold' : true,
	'rolloverLinkUnderline' : true,
	'rolloverLinkBackgroundColor' : '',
	'rolloverLinkColor' : '#cc0000',
    'lines' : '3',
    'fontFamily' : 'arial',
    'fontSizeTitle' : '19px',
    'fontSizeDescription' : '13px',
    'fontSizeDomainLink' : '12px',
    'colorTitleLink' : '#52662C',
    'colorText' : '#999',
    'colorAdBorder' : '#ccc', 
    'colorDomainLink' : '#000000',
    'titleBold' : true,
    'siteLinks' : false,
    'sellerRatings' : false
    };

    if ((typeof(afs_MID) != 'undefined')) {
        new google.ads.search.Ads(pageOptions, afs_TOP, afs_MID, afs_BTM);
    } else {
        new google.ads.search.Ads(pageOptions, afs_TOP, afs_BTM);
    }
}


//Decides Whether or not to display Google Ad Banner
//-----------------------------------------------------------------------------
function ShowGoogleBannerAd() {
   	bShowAd = true;
   	//If GoogleBannerAd Banner Div is not present, Hide ad
	if ($('#GoogleBannerAd').length == 0) {
    	bShowAd = false;
    }
   	//If Screen is not big enough, Hide ad
    if ($(window).width() < 1279) {
    	bShowAd = false;
    }
    // If the page content is not high enough - dont show ad
    var minHeight = 600;
    if ($('#fullwidth_container').length > 0) {
        ContainerHeight = $('#fullwidth_container').offset().top + 8;
        if ($('#fullwidth_container').height() < minHeight) {
            bShowAd = false;
        }
    } else if ($('#right_content_container').length > 0) {
        ContainerHeight = $('#right_content_container').offset().top + 0;
        if ($('#right_content_container').height() < minHeight) {
            bShowAd = false;
        }
    } else if ($('#listings_content').length > 0) {
        ContainerHeight = $('#listings_content').offset().top + 30;
        if ($('#listings_content').height() < minHeight) {
            bShowAd = false;
        }
    }
    if (bShowAd == true) {
	    google_ad_type = 'image_html_flash';
	    google_ad_client = "pub-3230112801643320";
	    google_ad_slot = "1752039791";
	    google_ad_channel = "7499621204";
	    google_ad_width = 120;
	    google_ad_height = 600;
	    
	    //Position Ad
	    $('#GoogleBannerAd').css('top', ContainerHeight);
	    $('#GoogleBannerAd').css('margin-left', 420);
	} else {
		$('#GoogleBannerAd').css('display', 'none');
    }
}



//-----------------------------------------------------------------------------
// Map functions
// Displays Google map with single location marker based at lat long.
// Used on profile style pages.
//-----------------------------------------------------------------------------
function LoadMap(g_lat, g_lon, zoom, bShowControls) {
    var centreLatLng = new google.maps.LatLng(g_lat, g_lon);

    // Decide which navigation control to display
    var navigationControlOptions = { style: google.maps.NavigationControlStyle.SMALL };
    if (bShowControls == false) {
        navigationControlOptions.style = '';
    }

    // Add control options
    var arrMapTypes = new Array();
    arrMapTypes.push(google.maps.MapTypeId.ROADMAP);
    arrMapTypes.push(google.maps.MapTypeId.SATELLITE);
    arrMapTypes.push(google.maps.MapTypeId.HYBRID);

    var mapTypeControlOptions = { mapTypeIds: arrMapTypes };

    // Set the main options for the map
    var myOptions = {
        zoom: zoom,
        center: centreLatLng,
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControlOptions: mapTypeControlOptions,
        navigationControlOptions: navigationControlOptions
    };
    if (bShowControls == false) {
        myOptions.disableDefaultUI = true;
        myOptions.draggable = false;
        myOptions.disableDoubleClickZoom = true;
    }

    var objGMap = new google.maps.Map(getObj("map"), myOptions);

    // Poistion a standard marker and add to the main map object
    var marker = new google.maps.Marker({
        position: centreLatLng,
        map: objGMap
    });
}

//-----------------------------------------------------------------------------
// Create, load and display Category Map
// Used on category style pages..
//-----------------------------------------------------------------------------
function LoadCatMap(bShowControls) {
    var navigationControlOptions = { style: google.maps.NavigationControlStyle.DEFAULT };
    if (bShowControls == false) {
        navigationControlOptions.style = '';
    }

    var myOptions = {
        zoom: 8,
        center: new google.maps.LatLng(51.45497, -2.59157), // Bristol
        scrollwheel: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        navigationControlOptions: navigationControlOptions
    }
    if (bShowControls == false) {
        myOptions.disableDefaultUI = true;
        myOptions.draggable = false;
        myOptions.disableDoubleClickZoom = true;
    }
    var objGMap = new google.maps.Map(getObj("catMap"), myOptions);
    var bounds = new google.maps.LatLngBounds();
    var infoWindow = new google.maps.InfoWindow();

    google.maps.event.addListener(objGMap, 'click', function() {
        infoWindow.close();
    });
    for (var i = 0; i < arrMapData.length; i++) {
        var thisLoc = arrMapData[i];
        if (thisLoc != null) {
            var myLatLng = new google.maps.LatLng(LatLongDecode(thisLoc[1]), LatLongDecode(thisLoc[2]));
            var marker = CreateMarker(objGMap, myLatLng, thisLoc[0], bounds, infoWindow, thisLoc[3]);
        }
    }
    objGMap.setCenter(bounds.getCenter());

    if (arrMapData.length == 1) {
        objGMap.setZoom(14);
    } else {
        objGMap.fitBounds(bounds);
    }
}

//-----------------------------------------------------------------------------
// Loads the points for the catmap above...
//-----------------------------------------------------------------------------
function CreateMarker(objGMap, myLatLng, myHTML, bounds, infoWindow, index) {
    var letter = String.fromCharCode('A'.charCodeAt(0) + index);
    var iconImg = new google.maps.MarkerImage('/fx/mapmarkers/blue_Marker' + letter + '.png',
    // This marker is 20 pixels wide by 34 pixels tall.
        new google.maps.Size(20, 34),
    // The origin for this image is 0,0.
        new google.maps.Point(0, 0),
    // The anchor for this image is the base of the baloon at (0, 34).
        new google.maps.Point(0, 34));

    var marker = new google.maps.Marker({
        position: myLatLng,
        map: objGMap,
        icon: iconImg,
        zIndex: Math.round(myLatLng.lat() * -100000) << 5
    });

    // Add a listener for when the markers gets clicked on
    google.maps.event.addListener(marker, 'click', function() {
        infoWindow.open(objGMap, marker);
        if (objGMap.getZoom() < 10) {
            objGMap.setZoom(10); // Zoom in if zoomed out
        }
        infoWindow.setContent(myHTML);
    });

    // Add a listener for all baloon icons that appear against the listings.
    if (getObj('markericon_' + index)) {
        google.maps.event.addDomListener(getObj('markericon_' + index), 'click', function() {
            infoWindow.open(objGMap, marker);
            infoWindow.setContent(myHTML);
            if (objGMap.getZoom() < 10) {
                objGMap.setZoom(10); // Zoom in if zoomed out
            }

            objGMap.setCenter(myLatLng);
        });
    }
    bounds.extend(myLatLng);
}

//-----------------------------------------------------------------------------
// 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;
}

//-----------------------------------------------------------------------------
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 = 'FreeIndex was trying to open a window to allow you to do something, but a pop-up blocker on your computer stopped us from doing so.\n';
        msg += 'Please allow pop-ups for this site, and then click on the button again.';

        alert(msg);
    }
}

//-----------------------------------------------------------------------------
// UPLOAD - Opens uploader Iframe in div
//-----------------------------------------------------------------------------
function InitialiseUpload(U_FieldName,U_Folder,U_Types,U_MaxFiles,U_DisplayType) {
	// Display Uploader Window and Center in window...
	$('#Uploader_' + U_FieldName).show();
	uploaderframeHeight = 450;
	uploaderframeWidth = 600;
    var w = $(window).width();
    var h = $(window).height();
    var ffHpos = (w / 2) - 300;
   	var ffVpos = $(window).scrollTop() + ((h / 2) - (uploaderframeHeight / 2) - 20);
    $('#Uploader_' + U_FieldName).offset({left:ffHpos, top:ffVpos});
    
    U_Files = $('#' + U_FieldName).val();
	Frameurl = '/customscripts/upload.asp?U_FieldName=' + U_FieldName + '&U_Folder=' + U_Folder + '&U_Types=' + U_Types + '&U_MaxFiles=' + U_MaxFiles + '&U_Files=' + U_Files + '&U_DisplayType=' + U_DisplayType
    $('#UploaderIframe_' + U_FieldName).attr('src',Frameurl);
}

//-----------------------------------------------------------------------------
// UPLOAD - Checks file types for standard uploader
//-----------------------------------------------------------------------------
function CheckStandardUploadTypes(U_Types) {
	var Filename = document.forms[0].elements[0].value;
	var FileExtension = "." + Filename.split('.').pop();
	FileExtension = FileExtension.toLowerCase();
	
	if (Filename == '') {
		alert('Please select a File.');
	} else {
		if (U_Types.indexOf(FileExtension) != -1) {
			document.StandardUploadForm.submit();
		} else {
			alert('Please only select one of our approved File Types.\n' + U_Types);
		}
	}
}

//-----------------------------------------------------------------------------
// UPLOAD - Display Uploads
//-----------------------------------------------------------------------------
function DisplayUploads(U_FieldName, U_Folder, U_Files, U_DisplayType) {
    var url = GetSubDomBaseHref() + '/customscripts/upload_display.asp';
    var params = 'U_FieldName=' + U_FieldName + '&U_Folder=' + U_Folder + '&U_Files=' + U_Files + '&U_DisplayType=' + U_DisplayType;
    $("#Uploads_" + U_FieldName).load(url, params);
}

//-----------------------------------------------------------------------------
// UPLOAD - Remove Upload
//-----------------------------------------------------------------------------
function removeUpload(U_FieldName, id, filename, U_Folder) {
	//Remove Row from Upload Table
	$('#upload_' + id).remove();
	
	//Remove name file from hidden Store
	U_Files = $('#' + U_FieldName).val();
	U_Files = Replace(U_Files,filename + '|','')
	$('#' + U_FieldName).val(U_Files);
	
	//Remove the file
    var url = '/customscripts/upload_removefile.asp?U_FieldName=' + U_FieldName + '&ufile=' + filename + '&ufolder=' + U_Folder;
	jQuery.ajax(url);
	
	//Make Sure Upload Button Is Displayed...
	$('#uploadbutton_' + U_FieldName).show();
}

//-----------------------------------------------------------------------------
// UPLOAD - Finish Upload
//-----------------------------------------------------------------------------
function finishUpload(U_FieldName, U_Folder, U_MaxFiles, U_DisplayType, U_Files, NewUploads, flashorstandard) {
	
	var ExistingFilesAndNewFiles = U_Files + NewUploads;
	numfilesuploaded = ExistingFilesAndNewFiles.replace(/[^|]/g, '').length; 
	
	if (flashorstandard == 'flash') {
		// FLASH - scope is window. parent
		//---------------------------------------------------------------------
		window.parent.DisplayUploads(U_FieldName,U_Folder, ExistingFilesAndNewFiles, U_DisplayType);
		
		// Hide Uploader Window
		$('#Uploader_' + U_FieldName, window.parent.document).hide();
		
		// Hide Upload button if max uploads reached.
		if (parseInt(numfilesuploaded) >= parseInt(U_MaxFiles)) {
			$('#uploadbutton_' + U_FieldName, window.parent.document).hide();
		}
		
		if (U_DisplayType == 'mfiphotos') {
			// Go to Captions Float Form
		    window.parent.DisplayFloatForm('mfiphotocaptions', U_FieldName + '££' + U_Folder + '$$' + NewUploads);
		} else {
			// Set Hidden Form Field with filenames.
			$('#' + U_FieldName, window.parent.document).val(ExistingFilesAndNewFiles);
		}
	} else {
		// STANDARD UPLOADER - scope is Normal
		//---------------------------------------------------------------------------
		if (NewUploads == 'REMOVEDTOBIG|') {
			alert('Sorry but the file you uploaded was to big. The maximum allowed size is 1MB.');
			// Hide Uploader Window
			$('#Uploader_' + U_FieldName).hide();
		} else {
			DisplayUploads(U_FieldName,U_Folder, ExistingFilesAndNewFiles, U_DisplayType);
			
			// Hide Uploader Window
			$('#Uploader_' + U_FieldName).hide();
			
			// Hide Upload button if max uploads reached.
			if (parseInt(numfilesuploaded) >= parseInt(U_MaxFiles)) {
				$('#uploadbutton_' + U_FieldName).hide();
			}
			
			if (U_DisplayType == 'mfiphotos') {
				// Go to Captions Float Form
			    DisplayFloatForm('mfiphotocaptions', U_FieldName + '££' + U_Folder + '$$' + NewUploads);
			} else {
				// Set Hidden Form Field with filenames.
				$('#' + U_FieldName).val(ExistingFilesAndNewFiles);
			}
		}
	}
}

//-----------------------------------------------------------------------------
// After an image has been uploaded, adds the image name to the combo box
//-----------------------------------------------------------------------------
function AddOptionToOpener(Listbox, fText, fValue) {
    if (getObj(Listbox) != null) {
        getObj(Listbox).options[getObj(Listbox).length] = new Option(fText, fValue, false, false);
        getObj(Listbox).options[getObj(Listbox).length - 1].selected = true;
    }
}

//-----------------------------------------------------------------------------
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;
        case 'E':
            defaultValue = 'Flower Show 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';
            getObj(fieldName).value = 0;
            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, '&', '');
                theValue = Replace(theValue, ' ', '_');
                var url = '/customscripts/ajax_SelectBusinessCategory.asp?keyword=' + theValue + '&fieldname=' + fieldName + '&DataType=' + dataType;
                
                $('#' + fieldName + '_catSelectOptions').load(url);
                
                catSelectField.focus();
            }
        }
        else {
            catSelectOptions.style.display = 'none';
        }
    }
}

//-----------------------------------------------------------------------------
function CatSelectOptionClick(id, dataType, catTxt, fieldName) {
    $('#' + fieldName + '_catTypeSelect').hide();
    $('#' + fieldName).val(id);
    $('#' + fieldName + '_Title').val(catTxt);
    $('#' + fieldName + '_DispSelectedCat').show();
    getObj(fieldName + '_DispSelectedCat').innerHTML = catTxt + ' (<a href="javascript:CatSelectReSelect(\'' + fieldName + '\',\'' + dataType + '\',\'\',\'\');">Change</a>)';
    $('#' + fieldName + '_catSelectOptions').hide();
    if (getObj(fieldName + '_PreviouslySuggestedCat')) {
        getObj(fieldName + '_PreviouslySuggestedCat').value = '0';
    }
    ValidateField(getObj(fieldName), '|NOT_EMPTY|', 'FTip_' + fieldName, '');

    if (dataType == 'Q') {
        $('#' + fieldName + '_DispSelectedCat').innerHTML = catTxt;
        var objRange = getObj('range_org');
        var objPostcode = getObj('postcode');
        if (objRange != null && objPostcode != null) {
            ReloadQuoteForm(id, objRange.value, objPostcode.value,'');
        }
    }
}

//-----------------------------------------------------------------------------
function CatSelectReSelect(fieldName, dataType, reloadTxt, reloadDesc) {
    var inputBox = $('#' + fieldName + '_catTypeSelect');
    inputBox.show();

    if (reloadTxt == '') {
        reloadTxt = inputBox.val();
    }

    var defaultValue = '';
    switch (dataType) {
        case 'J':
            defaultValue = 'Electrician, Florist etc';
            break;
        case 'Q':
            defaultValue = 'Builders, Accountants, Taxis etc';
            break;
        case 'E':
            defaultValue = 'Flower Show etc';
            break;
        default:
            defaultValue = 'Plumber, Florist, Gift Shop etc';
            break;
    }

    if (inputBox.val() != defaultValue) {
        $('#' + fieldName + '_catSelectOptions').show();
    }
    
    if (reloadTxt != '') {
        inputBox.val(reloadTxt);
        inputBox.css('color', '#000');
        
        var url = '/customscripts/ajax_SelectBusinessCategory.asp';
        var params = 'keyword=' + reloadTxt + '&desc=' + reloadDesc + '&fieldname=' + fieldName + '&DataType=' + dataType;
        
	    $('#' + fieldName + '_catSelectOptions').load(url, params);
    }

    var dispSelectedCat = $('#' + fieldName + '_DispSelectedCat');
    dispSelectedCat.innerText = '';
    dispSelectedCat.hide();

    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/ajax_SelectBusinessCategory.asp?suggest=1&fieldname=' + fieldName + '&DataType=' + dataType;
	$('#' + fieldName + '_catSelectOptions').load(url);
	$('#' + fieldName + '_catSelectOptions').height(270);
}

//-----------------------------------------------------------------------------
function CompleteSuggest(fieldName, dataType) {
    var bError = false;
    
    var theTitle = '';
    if (getObj(fieldName + '_Suggested_catTitle').value != '')  {
        theTitle = getObj(fieldName + '_Suggested_catTitle').value;
        theTitle = Replace(theTitle, '\'', '');
    }
    else {
        alert('Please enter the Title of your Suggested Category.');
        bError = true;
    }
    
    var theDesc = '';
    if (getObj(fieldName + '_Suggested_catDesc').value != '') {
        theDesc = getObj(fieldName + '_Suggested_catDesc').value;
        theDesc = Replace(theDesc, '\'', '');
        theDesc = Replace(theDesc, '"', '');
    }
    else {
        alert('Please enter a description of your Suggested Category.');
        bError = true;
    }

    if (bError == false) {
        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';
        ValidateField(getObj(fieldName),'|NOT_EMPTY|', 'FTip_' + fieldName,'');

    }
}

//-----------------------------------------------------------------------------
function CatSelectClose(fieldName, dataType) {
    var objField = getObj(fieldName + '_catSelectOptions');
    if (objField != null) {
        objField.style.display = 'none';

        // Hide the text input area.
        getObj(fieldName + '_catTypeSelect').value = '';
        getObj(fieldName + '_catTypeSelect').style.display = 'none';

        // Set the fields values to be displayed correctly.
        var catTitle = getObj(fieldName + '_Title').value;
        var catText = getObj(fieldName + '_catTypeSelect').value;
        
        getObj(fieldName + '_DispSelectedCat').style.display = 'block';
        getObj(fieldName + '_DispSelectedCat').innerHTML = catTitle + ' (<a href="javascript:CatSelectReSelect(\'' + fieldName + '\',\'' + dataType + '\',\'' + catText + '\',\'\');">Change</a>)';
        getObj(fieldName + '_catSelectOptions').style.display = 'none';
        if (getObj(fieldName + '_PreviouslySuggestedCat')) {
            getObj(fieldName + '_PreviouslySuggestedCat').value = '0';
        }

        if (dataType == 'Q') {
            getObj(fieldName + '_DispSelectedCat').innerHTML = catTitle;
        }
    }
}

//-----------------------------------------------------------------------------
// Opens Tradebody window
//-----------------------------------------------------------------------------
function OpenTBWindow() {
    var membersOf = getObj('MEMBERSHIPS').value;
    if (membersOf == null)
         membersOf = '';
         
    var args = 'toolbar=0,status=1,menubar=0,scrollbars=1,resizable=0';
    OpenCenteredWindow('/customscripts/mfi_selectTradeBodies.asp?membersof=' + membersOf, 375, 650, null, args)
}

//-----------------------------------------------------------------------------
// Displays Tradebody list
//-----------------------------------------------------------------------------
function ShowTradeBodies(membersOf) {
    var url = '/customscripts/ajax_showTradeBodies.asp?membersOf=' + membersOf;
	$("#MEMBERSHIPS_disp").load(url);
}

//-----------------------------------------------------------------------------
// Stats
//-----------------------------------------------------------------------------
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 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
    if (countField != null) {
        countField.value = reqLimit - textField.value.length;
        if (countField.value <= 0) {
            countField.value = 0;
            countField.style.color = '#000';
        }
        else {
            countField.style.color = '#c00';
        }
    }
}

//-----------------------------------------------------------------------------
function ShowProductService(id, imgURL) {
    // Turn off all products / services.
    var divs = document.getElementsByTagName('div');
    var div_id, justId, thisImg, thisSrc;
    for (var i = 0; i < divs.length; i++) {
        div_id = divs[i].id;
        
        if ((div_id.indexOf('psDesc_') != -1) && (div_id != 'psDesc_' + id)) {
            justId = Replace(div_id, 'psDesc_', '');
            getObj('psMore_' + justId).style.display = 'block';
            getObj('psDesc_' + justId).style.display = 'none';
            getObj('psSnip_' + justId).style.display = 'block';
            if (getObj('psImg_' + justId)) {
                thisImg = getObj('psImg_' + justId);
                thisSrc = thisImg.src;
                thisSrc = Replace(thisSrc, '&maxW=200&maxH=150', '&maxW=40&maxH=40&action=crop');
                getObj('psImg_' + justId).src = thisSrc;
            }
        }
    }

    // Turn on selected product / service
    if (getObj('psImg_' + id)) {
        getObj('psImg_' + id).src = imgURL + '&maxW=200&maxH=150';
    }
    getObj('psSnip_' + id).style.display = 'none';
    getObj('psMore_' + id).style.display = 'none';
    getObj('psDesc_' + id).style.display = 'block';
}

//-----------------------------------------------------------------------------
function ChangeEnquiryType(listingId) {
    if (listingId == '') {
        var enquiry_type = getObj('enquiry_type');
        if (enquiry_type != null) {
            var selItem = enquiry_type.options[enquiry_type.selectedIndex].value;
            if (selItem == 'DIC') {
                var enquiry = getObj('enquiry');
                if (enquiry != null) {
                    enquiry.value += '-- Please let us know the name and Id of the business whose details are incorrect --';
                }
            }
        }
    }
}

//-----------------------------------------------------------------------------
// Adds companyId to users address book.
//-----------------------------------------------------------------------------
function AddToAddressBook(companyId, fromWhere, bAdd) {
    var action = 'add';
    if (bAdd == false) {
        action = 'delete';
    }

    var url = '/customscripts/ajax_addtoaddressbook.asp?id=' + companyId + '&action=' + action;
    jQuery.ajax(url);

    switch (fromWhere) {
        case 'profile':
            getObj('bookmarklink').href = '/myfreeindex(map-bookmarks).htm';
            getObj('bookmarklink').innerText = 'Bookmarked';
            
            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;
    }
}

//-----------------------------------------------------------------------------
// Listing Controls Functions
//-----------------------------------------------------------------------------
function setOption(selView) {
	getObj('list_view_type').value = selView;
    document.ListingControls_form.submit();
}

//-----------------------------------------------------------------------------
function ApplyListRangeFilter(overrideRange) {
    // Get Range Radio Value
    var selectedRange = 0;
    var rangeOptions = null;
    
    for (var i = 0; i < 4; i++) {
        rangeOptions = getObj('list_range_options_' + i);
        if (rangeOptions.checked == true) {
            switch (i) {
                case 0: selectedRange = 0; break;
                case 1: selectedRange = 50; break;
                case 2: selectedRange = 25; break;
                case 3: selectedRange = 10; break;
            }
        }
    }

    if (overrideRange != '') {
        selectedRange = overrideRange;
    }

    $('#list_refresh').val('go');

    getObj('list_range').value = selectedRange + '|' + getObj('list_range_postcode').value;
    document.ListingControls_form.submit();
}

//-----------------------------------------------------------------------------
// Branch editor functions
//-----------------------------------------------------------------------------
function OpenBranchesWindow() {
    var args = 'toolbar=0,status=1,menubar=0,scrollbars=1,resizable=0';
    OpenCenteredWindow('/customscripts/mfi_SelectBranches.asp', 375, 650, null, args)
}

//-----------------------------------------------------------------------------
function CloseBranchWindow() {
    window.close();
}

//-----------------------------------------------------------------------------
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 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 == true) {
            pollAnswer = i;
        }
    }

    if (pollAnswer != '') {
        getObj('PollForm').submit();
    }
    else {
        alert('Please select one answer to vote...');
    }
}

//-----------------------------------------------------------------------------
// Forum compliments
//-----------------------------------------------------------------------------
function GiveCompliment(contentType, contentId, authorId) {
    $('#compliment_' + contentId).load('/customscripts/ajax_forum_compliment.asp?ctype=' + contentType + '&CID=' + contentId + '&AID=' + authorId);
}

//-----------------------------------------------------------------------------
function ShowTels(cid) {
    //RunScript(GetSubDomBaseHref() + '/customscripts/ajax_view_' + 't' + 'el_det' + 'ails.asp?id=' + cid, 'TelcomsInfo', '');
    var url = GetSubDomBaseHref() + "/customscripts/ajax_view_tel_details.asp?id=" + cid
    $("#TelcomsInfoBox").load(url);
    
}

//-----------------------------------------------------------------------------
function SetUserImage(imageIndex) {
    // Grey out all of the images then set the selected images border to Red
    var img_preview = getObj('user_photo_image');
    if (img_preview != null) {
        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.value = 'fi_avatar_' + imageIndex + '.gif';
    }
    else {
        img_preview.style.border = '2px solid #c00';

        if (imageIndex == '0') {
            var user_photo_uploaded = getObj('user_photo_uploaded');
            if (user_photo_uploaded != null) {
                user_photo.value = user_photo_uploaded.value;
            }
        }
    }
}

//-----------------------------------------------------------------------------
function InboxDelete() {
    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_row;
        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_row = getObj('inbox_row_msg_' + msgId);
                    if (inbox_row != null) {
                        inbox_row.style.display = 'none';
                    }
                }
            }
        }

        var url = '/customscripts/ajax_inbox_delete.asp?ids=' + toDelete;
		jQuery.ajax(url)
    }
}

//-----------------------------------------------------------------------------
// Shows Help Pop Up Windows and centers
//-----------------------------------------------------------------------------
function ShowHelpFloatBox(objname) {
    // Close other help windows...
    $('.FFHelp').hide();
    
    // Open this HelpWindow
    $('#' + objname).show();
    
    // Center it if not in a popup in a floatform;
    if ($("#FloatFormIframe", window.parent.document).length == 0) {
        var w = $(window).width();
        $('#' + objname).offset({ left: ((w / 2) - (700 / 2)), top: ($(window).scrollTop() + 200) });
    } else { 
        var w = $(window).width();
        $('#' + objname).offset({ left: ((w / 2) - (700 / 2))});
    }
}

//-----------------------------------------------------------------------------
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 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';
    }
}

//-----------------------------------------------------------------------------
function FlagForum(msgId) {
    var flag = getObj('flag_' + msgId);
    if (flag != null) {
        flag.innerHTML = '<font style="font-size:11px;">Thanks: We\'ll check it</font>';
		jQuery.ajax('/customscripts/ajax_forum_flag.asp?id=' + msgId);
    }
}

//-----------------------------------------------------------------------------
function DeleteUserComment(newsCommentId) {
    var url = '/customscripts/mediacentre.asp?newsCommentId=' + newsCommentId + '&action=del_comment';
	jQuery.ajax(url);
    
    var del_item = getObj('del_item_' + newsCommentId);
    if (del_item != null) {
        del_item.innerHTML = 'Deleted';
    }
}

//-----------------------------------------------------------------------------
function SetMapListingsHeight() {
    var objMap = getObj('catMap');
    var objListing = getObj('MapListings');
    var viewPortHeight = $(window).height();
    var mapTop = GetPosition(objMap)
    var mapHeight = (viewPortHeight - mapTop) - 3;
    
    objMap.style.height = mapHeight + 'px';
    objListing.style.height = mapHeight + 'px';
}

//-----------------------------------------------------------------------------
function GetPosition(obj, leftOrTop) {
    var topValue = 0;
    var leftValue = 0;
    while (obj) {
        leftValue += obj.offsetLeft;
        topValue += obj.offsetTop;
        obj = obj.offsetParent;
    }
    if (leftOrTop == 'L') {
        return leftValue;
    } else {
        return topValue;
    }
}

//-----------------------------------------------------------------------------
// Get ajax float over forms
//-----------------------------------------------------------------------------
function DisplayFloatForm(action, params) {
    var w = $(window).width();
    var h = $(window).height();
    var fadeoutHeight = $(document).height();
    if (fadeoutHeight < h) {
        fadeoutHeight = h;
    }
    var frameHeight = 400;
    switch (action) {
        case 'emaillogin': case 'upgrade': case 'tour': case 'mfiphotocaptions':
            frameHeight = 700;
            break;
        case 'gallery':
            frameHeight = 600;
            break;
        case 'print': case 'link': case 'send': case 'customise_reviews_gadget':
            frameHeight = 650;
            break;
        case 'eventpics':
            frameHeight = 600;
            break;
        case 'writereview':
            frameHeight = 570;
            break;
        case 'jobapply': case 'login': case 'signup': case 'forum': case 'compliment':
            frameHeight = 520;
            break;
        case 'upload': case 'video':
            frameHeight = 500;
            break;
        case 'profilewizard': case 'addeditproduct': case 'addeditservice': case 'suggesteventcat':
            frameHeight = 450;
            break;
        case 'enquiry':
            frameHeight = 430;
            break;
        case 'change-location':
            frameHeight = 270;
            break;
    }

    var leftOfScreen = (w / 2) - 450;
    
    if ($('#fade_out') != null) {
        $('#fade_out').height(fadeoutHeight);
        $('#fade_out').fadeTo('fast','0.8', function() {
		    if ($('#float_over_form') != null) {
		        $('#float_over_form').show();
	    	    
	        	var ffVpos = $(window).scrollTop() + ((h / 2) - (frameHeight / 2) - 20);
	        	if (ffVpos < 0) {
	            	ffVpos = 0
	        	}
	    	    $('#float_over_form').offset({left:leftOfScreen, top:ffVpos});
        	}
    	});
    }

    var url = GetSubDomBaseHref() + '/customscripts/floatforms.asp'
    
	$('#float_over_form').load(url, 'action=' + action + '&frameheight=' + frameHeight + '&params=' + params);
}

//-----------------------------------------------------------------------------
function CloseFloatOverForm() {
    $('#float_over_form').fadeOut('fast', function() {
        $('#fade_out').hide();
    });
}

//-----------------------------------------------------------------------------
function ValidateField(e, strValidation, tipDivName, strConditionalDisplay) {
    
    if (getObj(tipDivName)) {
        getObj(tipDivName).style.display = 'none';
    }
    var fieldValue = '';
    if (e.type == 'checkbox') {
        if (e.checked) {
            fieldValue = 1;
        } else {
            fieldValue = '';
        }
    } else {
        fieldValue = e.value;
        fieldValue = Replace(fieldValue, '&', '--and--');
    }
    
    // Conditionally Display / Hide Other fields
    // DollarPos = strConditionalDisplay.indexOf('$');
    if (strConditionalDisplay != '') {
        var conditions = strConditionalDisplay.substr(strConditionalDisplay.indexOf("$") + 1)
        var fieldToDisplay = Mid(strConditionalDisplay, 0, strConditionalDisplay.indexOf("$"))
        var selectedValue = e.value.toLowerCase();
        
        if ((fieldToDisplay !='') && (conditions != '')) {
            conditions = conditions.toLowerCase();
            if (conditions.indexOf('|' + selectedValue + '|') != -1) {
                getObj(fieldToDisplay + '_container').style.display = 'block';
            } else {
                getObj(fieldToDisplay + '_container').style.display = 'none';
            }
        }
    }
    
    if (strValidation.indexOf("NOT_SIMILAR_TO") > 0) {
	 	if (e.value != '') {
		 	var validationFirstPart = strValidation.substring(0,strValidation.indexOf("!!"))
		 	
		 	//Get FieldValues for Passed in FieldNames
		 	CompareFieldNames = strValidation.slice(strValidation.indexOf("!!") + 2, strValidation.length-1)
		 	if (CompareFieldNames.indexOf("~") > 0) {
			 	CompareFieldArray = CompareFieldNames.split("~");
			 	
			 	var OutputValString = validationFirstPart + "!!"
			 	
			    for (var i = 0; i < CompareFieldArray.length; i++) {
				    if (e.id != CompareFieldArray[i]) {
					    var thisCompareValue = $('#' + CompareFieldArray[i]).val();
					 	if (thisCompareValue != '') {
						 	OutputValString += thisCompareValue + "~"
						}
					}
			    }
				strValidation = OutputValString.slice(0,OutputValString.length-1) + "|";
			}
	 	}
    }

    $('#FVal_' + e.name).load('/customscripts/ajax_fieldvalidation.asp', 'ValidationStr=' + escape(strValidation) + '&fieldname=' + e.name + '&fieldvalue=' + escape(fieldValue));
    $('#FVal_' + e.name).show();
}

//-----------------------------------------------------------------------------
function OnFocusDateField(fieldName) {
    // Remove the 'DD/MM/YYYY' with nothing and sort out the colour
    var objField = getObj(fieldName);
    if (objField != null) {
        if (objField.value == 'DD/MM/YYYY') {
            objField.value = '';
            objField.style.color = '#999';
        } else {
            objField.style.color = '#000';
        }
    }
}

//-----------------------------------------------------------------------------
function LocationSelect(pcObj, locFieldName) {
    // Run Location Selector
    if (pcObj != null && getObj(locFieldName) != null) {
        var url = '/customscripts/ajax_selectlocation.asp';
        //RunScript(url, locFieldName + '_Display', '');
        $("#" + locFieldName + "_Display").load(url, "fieldname=" + locFieldName + "&PostCode=" + pcObj.value + "&selectedlocation=" + Replace(getObj(locFieldName).value,'$','^'));
    }
}

//-----------------------------------------------------------------------------
function UpdateLocationSelectorHiddenField(e,hiddenfieldname) {
    localityValue = e.options[e.selectedIndex].value;
    getObj(hiddenfieldname).value = localityValue;
}

//-----------------------------------------------------------------------------
function SubmitFloatForm() {
    var btnSubmit = getObj('SubmitBtn');
    if (btnSubmit != null) {
        getObj('SubmitBtn').style.display = 'none';
        getObj('Submit_progress').style.display = 'block';
        document.floatform.submit();
    }
}

//-----------------------------------------------------------------------------
function OnKeydownFloatForm(e, formName) {
    // If the key down is a Return, submit the form
    if (!e) {
        e = window.event; // for ie
    }
    if (e.keyCode == 13) { // CR
        if (getObj(formName) != null) {
            getObj(formName).submit();
        }
    }
}

//-----------------------------------------------------------------------------
function DisplayWideScreenQuoteAd() {
    screenWidth = $(window).width();
    
    if (screenWidth >= 1270) {
        if (getObj('BusinessOfferAd') != null) {
            getObj('BusinessOfferAd').style.display = 'block';
        }
    }
}

//-----------------------------------------------------------------------------
function ReloadQuoteForm(catId, range, postcode, processform) {
    var loadingHTML = '<div style="text-align:center;height:120px;">';
    loadingHTML += '<br /><br />Please wait - searching for local businesses.<br /><br />';
    loadingHTML += '<img src="fx/progress.gif" alt="loading..." />';
    loadingHTML += '</div>';

    var url = '/customscripts/ajax_qr_top.asp';
    var params = 'catid=' + catId + '&range=' + range + '&postcode=' + postcode + '&processform=' + processform;
    
    $("#quote_form_top").html(loadingHTML).load(url, params);
	
    QRSetTitle();
}

//-----------------------------------------------------------------------------
function QRSetTitle() {
    // Set quote_title
    var objQRTitle = getObj('NOTICKCROSS_quote_title');
    if (objQRTitle != null) {
        if (objQRTitle.value == '') {
            var suggested_title = getObj('suggested_title');
            if (suggested_title != null) {
                objQRTitle.value = suggested_title.value;
            }
        }
    }
}

//-----------------------------------------------------------------------------
function QREditPostcode(bEdit) {
    var pcDisplay = getObj('postcode_disp');
    var pcEdit = getObj('postcode_edit');

    if (bEdit == true) {
        // Hide display
        if (pcDisplay != null) {
            pcDisplay.style.display = 'none';
        }

        // Display edit
        if (pcEdit != null) {
            pcEdit.style.display = 'block';
        }
    } else {
        // Display display
        if (pcDisplay != null) {
            pcDisplay.style.display = 'block';
        }

        // Hide edit
        if (pcEdit != null) {
            pcEdit.style.display = 'none';
        }

        var found_msg = getObj('found_msg');
        if (found_msg != null) {
            // Display 'working on it' message
            found_msg.innerHTML = '<img src="/fx/progress.gif" />';
        }

        // We're closing, so recalc
        ReloadQuoteForm(getObj('catid').value, getObj('range').options[getObj('range').selectedIndex].value, getObj('postcode').value,'');
    }
}

//-----------------------------------------------------------------------------
function QREditRange(bEdit) {
    // Hide display
    var rgDisplay = getObj('range_disp');
    if (rgDisplay != null) {
        rgDisplay.style.display = 'none';
    }

    // Display edit
    var rgEdit = getObj('range');
    if (rgEdit != null) {
        rgEdit.style.display = 'block';
    }
}

//-----------------------------------------------------------------------------
function QRShowDescStrength() {
    var descLength = $('#NOTICKCROSS_quote_desc').val().length;

    if (descLength > 40) {
        // Before this, they'll get a red message saying they have to type more
        var html = '<font style="font-size:11px;">Detail level : ';
        
        if (descLength > 40 && descLength <= 130) {
            html += '<font style="color:#C00;">Low. Provide more detail to get a better response.</font>';
        } else if (descLength > 130 && descLength <= 200) {
            html += '<font style="color:#D59309;">Medium. Add more detail to get an even better response.</font>';
        } else {
            html += '<font style="color:#63931F;">High. You\'ve got the best chance of getting a good response.</font>';
        }
        html += '</font>';
        
        $('#desc_strength').html(html);
        $('#desc_strength').show();
	} else {
        $('#desc_strength').html('');
        $('#desc_strength').hide();
    }
}

//-----------------------------------------------------------------------------
// Called from category pages
//-----------------------------------------------------------------------------
function DisplayQRFormFromCats() {
	catid = $('#quad_catid').val();
	pc = $('#quad_postcode').val();
	window.location.href = '/getquotes.htm?catid=' + catid + '&postcode=' + pc
}

//-----------------------------------------------------------------------------
// Display or hide full title of links on MFI dashbord
//-----------------------------------------------------------------------------
function DisplayLinkTitle(divId, bDisplay) {
    var objInfo = getObj(divId);
    if (objInfo != null) {
        if (bDisplay == true) {
            objInfo.style.display = 'block';
        } else {
            objInfo.style.display = 'none';
        }
    }
}

//-----------------------------------------------------------------------------
// Display Review Warnings in Write Review
//-----------------------------------------------------------------------------
function DisplayNegativeReviewWarings() {
    var value_score = getObj('value_for_money').options[getObj('value_for_money').selectedIndex].value;
    var service_score = getObj('service').options[getObj('service').selectedIndex].value;
    var quality_score = getObj('quality').options[getObj('quality').selectedIndex].value;
    
    getObj('NegativeReviewWarnings').style.display = 'none';
    
    if ((value_score != '') && (service_score != '') && (quality_score != '')) {
        var total_score = value_score + service_score + quality_score;
        if (total_score < 9) {
            getObj('NegativeReviewWarnings').style.display = 'block';
        }
    }
}

//-----------------------------------------------------------------------------
// Display Review Validation info
//-----------------------------------------------------------------------------
function ShowReviewValidationInfo(e,sameIpBusiness,sameIpReviews) {
    divObj = getObj('ReviewValidationInfo');
    divObj.style.display = 'block';
    topPos = GetPosition(e, 'T') + 20;
    leftPos = GetPosition(e, 'L') - 220;
    
    divObj.style.top = topPos + 'px';
    divObj.style.left = leftPos + 'px';
    
    var warnings = '';
    if (sameIpBusiness == 'True') {
        warnings += 'This review has been written on a computer with the same IP Address as a computer used by the company.<br /><br />';
    }
    
    if (sameIpReviews == 'True') {
        warnings += 'This review has been written on a computer with the same IP Address as another review written about this company.';
    }
    divObj.innerHTML = '<b>Review Information</b><br />' + warnings;
}

//-----------------------------------------------------------------------------
// Show OAuth signup form / normal registration form
//-----------------------------------------------------------------------------
function ShowSignup(providerType) {
    switch (providerType) {
        case '':
            $('#signup_freeindex').show();
            $('#signup_oauth').hide();

            $('#signup_with_f').hide();
            $('#signup_with_g').hide();
            $('#signup_with_w').hide();
            $('#signup_with_y').hide();
            break;
        case 'f': case 'g': case 'w':case 'y':
            $('#signup_freeindex').hide();
            $('#signup_oauth').show();

            $('#signup_with_f').hide();
            $('#signup_with_g').hide();
            $('#signup_with_w').hide();
            $('#signup_with_y').hide();

            $('#signup_with_' + providerType).show();

            $('#NOTICKCROSS_OAuthSIGNUPWITH').val(providerType);
            break;
    }
}

//-----------------------------------------------------------------------------
function SubmitOauthSignup() {
    var bValidForm = true;

    if ($('#NOTICKCROSS_OAuthNAME').val() == '') {
        bValidForm = false;
    }
    if ($('#NOTICKCROSS_OAuthPOSTCODE').val() == '') {
        bValidForm = false;    
    }
    if ($('#NOTICKCROSS_OAuthSIGNUPWITH').val() == '') {
        bValidForm = false;    
    }
    if ($('#NOTICKCROSS_OAuthTERMS').is(':checked') == false) {
        bValidForm = false;    
    }

    if (bValidForm == true) {
        // Only fire up login window if all fields are complete
        var providerType = $('#NOTICKCROSS_OAuthSIGNUPWITH').val();
        OAuthLogin(providerType, 'SIGNUP');
    } else {
        document.oAuthSignupform.submit();
    }
}

//-----------------------------------------------------------------------------
// loginType = f (Facebook), g (Google) etc
// actionType = LOGIN, SIGNUP
//-----------------------------------------------------------------------------
function OAuthLogin(providerType, loginOrSignup) {
    var url = '/customscripts/oauth/';
    var windowHeight = '460';
    var windowWidth = '830';
    var name = '';
    if (getObj('NOTICKCROSS_OAuthNAME') != null) {
        name = getObj('NOTICKCROSS_OAuthNAME').value;
    }
    var postcode = '';
    if (getObj('NOTICKCROSS_OAuthPOSTCODE') != null) {
        postcode = getObj('NOTICKCROSS_OAuthPOSTCODE').value;
    }
    
    switch (providerType) {
        case 'f':
            url += 'facebook.asp'
            windowHeight = '570';
            windowWidth = '1000';
            break;
        case 'g':
            url += 'google.asp'
            break;
        case 't':
            url += 'twitter.asp'
            break;
        case 'w':
            url += 'mslive.asp'
            windowHeight = '460';
            windowWidth = '465';
            break;
        case 'y':
            url += 'yahoo.asp'
            windowHeight = '500';
            windowWidth = '500';
            break;
        default:
            url = '';
            break;
    }

    if (url != '') {
        url += '?LoginOrSignup=' + loginOrSignup + '&oauth_submit=go&fullname=' + name + '&postcode=' + postcode;
        
        OpenCenteredWindow(url, windowHeight, windowWidth, 'oauth', '');
    }
}

//-----------------------------------------------------------------------------
function AccountOAuthSettings(providerType, settingType) {
    var settingValue = '0';
    var objSetting = getObj('set_' + settingType + '_' + providerType);
    if (objSetting != null) {
        if (objSetting.checked == true) {
            settingValue = '1';
        }
    }
    if (settingType == 'LINK') {
        var page_link = getObj('page_link_' + providerType);
        if (page_link != null) {
            settingValue = page_link.value;
        }
    }
    
    var url = "/customscripts/ajax_oauth_settings.asp?provider_type=" + providerType + "&setting_type=" + settingType + "&setting_value=" + settingValue;

    if (settingType == 'POST' && settingValue == '0') {
        var agree = confirm("Are you sure you want to stop publishing to this account?");

        if (agree == true) {
            jQuery.ajax(url);
        }
    } else if (settingType == 'DELETE') {
        var agree = confirm("Are you sure you want to remove your link to this account?");

        if (agree == true) {
            jQuery.ajax(url);
            
            alert('Linked account deleted!');
            location.href = '/myfreeindex(account-link).htm';
        }
    }
    else if (settingType == 'LINK') {
        $('#link_error_' + providerType).load(url);
    } else {
        jQuery.ajax(url);
    }
}

//-----------------------------------------------------------------------------
function PostToNetworkLink(providerType, ajaxDiv, link, width, height) {
	$('#' + ajaxDiv).load('/customscripts/ajax_social_network.asp', 'providerType=' + providerType + '&link=' + link + '&width=' + width + '&height=' + height);
}

//-----------------------------------------------------------------------------
function Rating_HighlightStars(whichStar, fieldName) {
    switch (whichStar) {
        case '0':
            $('#' + fieldName + '_star_1').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_2').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_3').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_4').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_5').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_rating_description').html('< Click to rate');
            break;
        case '1':
            $('#' + fieldName + '_star_1').attr('src', '/fx/rating_star_red.gif');
            $('#' + fieldName + '_star_2').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_3').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_4').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_5').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_rating_description').html('Awful');
            break;
        case '2':
            $('#' + fieldName + '_star_1').attr('src', '/fx/rating_star_red.gif');
            $('#' + fieldName + '_star_2').attr('src', '/fx/rating_star_red.gif');
            $('#' + fieldName + '_star_3').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_4').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_5').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_rating_description').html('Below average');
            break;
        case '3':
            $('#' + fieldName + '_star_1').attr('src', '/fx/rating_star_orange.gif');
            $('#' + fieldName + '_star_2').attr('src', '/fx/rating_star_orange.gif');
            $('#' + fieldName + '_star_3').attr('src', '/fx/rating_star_orange.gif');
            $('#' + fieldName + '_star_4').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_star_5').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_rating_description').html('Satisfactory');
            break;
        case '4':
            $('#' + fieldName + '_star_1').attr('src', '/fx/rating_star_green.gif');
            $('#' + fieldName + '_star_2').attr('src', '/fx/rating_star_green.gif');
            $('#' + fieldName + '_star_3').attr('src', '/fx/rating_star_green.gif');
            $('#' + fieldName + '_star_4').attr('src', '/fx/rating_star_green.gif');
            $('#' + fieldName + '_star_5').attr('src', '/fx/rating_star_grey.gif');
            $('#' + fieldName + '_rating_description').html('Better than expected');
            break;
        case '5':
            $('#' + fieldName + '_star_1').attr('src', '/fx/rating_star_green.gif');
            $('#' + fieldName + '_star_2').attr('src', '/fx/rating_star_green.gif');
            $('#' + fieldName + '_star_3').attr('src', '/fx/rating_star_green.gif');
            $('#' + fieldName + '_star_4').attr('src', '/fx/rating_star_green.gif');
            $('#' + fieldName + '_star_5').attr('src', '/fx/rating_star_green.gif');
            $('#' + fieldName + '_rating_description').html('Exceptional');
            break;
    }
}

//-----------------------------------------------------------------------------
function Rating_ResetStars(fieldName) {
    var currentStarValue = $('#' + fieldName).val();
    if (currentStarValue == '') {
        currentStarValue = '0';
    }
    
    Rating_HighlightStars(currentStarValue, fieldName);
}

//-----------------------------------------------------------------------------
function Rating_SetStars(whichStar, fieldName) {
    $('#' + fieldName).val(whichStar);

    Rating_HighlightStars(whichStar, fieldName);

    // Work out average rating
    var averageRating = Ratings_GetAverage(fieldName);
    if (averageRating < 3 && averageRating != 0) {
        $('#NegativeReviewWarnings').show();
    } else {
        $('#NegativeReviewWarnings').hide();
    }
}

//-----------------------------------------------------------------------------
// Assumes that the fields have the same names.
//-----------------------------------------------------------------------------
function Ratings_GetAverage(fieldName) {
    // Work out average rating
    var valueForMoney = 0;
    var service = 0;
    var quality = 0;
    var nFind = 0;

    // Extract the field id from the fieldName if there is one.
    var fieldId = '';
    var nFind = fieldName.lastIndexOf('_');
    if (nFind > 0) {
        fieldId = fieldName.substring(nFind);
    }

    valueForMoney = parseInt($('#value_for_money' + fieldId).val());
    service = parseInt($('#service' + fieldId).val());
    quality = parseInt($('#quality' + fieldId).val());
    
    var totalScore = valueForMoney + service + quality;
    var averageRating = 0;
    if (totalScore > 0 && valueForMoney != 0 && service != 0 && quality != 0) {
        averageRating = totalScore / 3;
    }

    return averageRating;
}

//-----------------------------------------------------------------------------
function LoginShowAll() {
    getObj('all_login_methods').style.display = 'block';
    getObj('last_loggedin_with').style.display = 'none';
}

//-----------------------------------------------------------------------------
function GetMFIInbox() {
	$("#mfi_inbox").load('/customscripts/ajax_mfi_inbox.asp');
}

//-----------------------------------------------------------------------------
function validatecaptions() {
	var bad = false;
	$("input[name^=caption]").each(function(i,x) {
		if ((x.value).length < 5) {
			bad = true;
		}
	}); 
	if (bad) {
		alert('Please make sure you enter a proper caption for all your images.');		
	} else {
		document.addcaptionsform.submit();
	}
}

//-----------------------------------------------------------------------------
function SetReviewGraph(listingId, cType) {
    // Changes the review graph type
    $('#review_chart').attr('src', '/customscripts/ajax_chart_reviews.asp?id=' + listingId + '&ctype=' + cType);

    if (cType == 'trend') {
        $('#review_link_dist').html('<a href="javascript:SetReviewGraph(' + listingId + ',\'dist\');">Rating Summary</a>');
        $('#review_link_trend').html('Trend');
    } else {
        $('#review_link_dist').html('Rating Summary');
        $('#review_link_trend').html('<a href="javascript:SetReviewGraph(' + listingId + ',\'trend\');">Trend</a>');
        
    }
}
