/* ------------------------------------------------------------------------------------
 * LOGGING FUNCTION FOR UTILITY USE
 * -----------------------------------------------------------------------------------*/
jQuery.log = function(message) {
    if (window.console) {
        console.log(message);
    } else {
        alert(message);
    };
};

// Need this for DEMBB, outside of DOM ready function
var GB_ANIMATION = true;

/*
// Dwayne's Extremely Modified Modal Box (DEMMB, yo)
function displayModal(imgSrc) {
  var theImage = new Image();
  theImage.src = imgSrc;
  var imgWidth  = theImage.width;  // Gets the actual image width, not DOM width
  var imgHeight = theImage.height; // Gets the actual image height, not DOM height
  
  GB_show(theImage.alt, imgSrc, imgHeight, imgWidth);
  return false;
}*/

function getReferrerCookie(){
    referrer = ($.cookie('REFERRER'));
        if (referrer != null) {
        r=referrer.replace(/"/g, '').split("@");
        domain=r[0];
        path=r[1];
        txt=r[2];

        $("#referrerlink").attr('href', domain);
        $("#referrerlogo").attr('src', path);
        $("#referrerlogo").attr('alt', txt);
        $("#newspaperSource").css('display', 'block');
    };
};

//THE DOM READY CHECK
$(document).ready(function () {

    getReferrerCookie();
    
    // Dwayne's image modal box
    $("a.getItUp").click(function() {
      GB_show(this.title, this.href);
      return false;
    });

    /* ------------------------------------------------------------------------------------
     * FROST HOMEPAGE FUNCTION
     * -----------------------------------------------------------------------------------*/
    $('.fullList').bind('click', function(event) {
        event.preventDefault();
        if (!$(this).hasClass('hideMe') && !($("ul.bottom:animated").size() > 0)) {
            $(this).html('Hide').addClass('hideMe').prev('.bottom').slideDown('slow');    
        } else {
            if (!($("ul.bottom:animated").size() > 0)) {
                $(this).html('Full List').removeClass('hideMe').prev('.bottom').slideUp('slow');
            };
        };
    });
    
    /* ------------------------------------------------------------------------------------
     * KEV SPECIAL OFFERS - TERMS AND CONDITIONS DROPDOWN FUNCTION
     * -----------------------------------------------------------------------------------*/
    $('.termsLink').bind('click', function(event) {
        event.preventDefault();
        if (!$(this).hasClass('hideMe') && !($("ul.bottom:animated").size() > 0)) {
            $(this).html('Hide Terms &amp; Conditions').addClass('hideMe').parent().next('.bottom').slideDown('slow');    
        } else {
            if (!($("ul.bottom:animated").size() > 0)) {
                $(this).html('Terms &amp; Conditions').removeClass('hideMe').parent().next('.bottom').slideUp('slow');
            };
        };
    });
    
    /* ------------------------------------------------------------------------------------
     * CUSTOM SELECT BOXES
     * -----------------------------------------------------------------------------------*/
    $(".customSelectbox").selectbox();
    $(".customSelectbox").removeAttr('disabled');
    
    if (isIE && (isIE_Six || isIE_Seven)) {
        //Make them go on top of everything properly
        $(function() {
            var zIndexNumber = 1000;
            $('div#bd div').each(function() {
                $(this).css('zIndex', zIndexNumber);
                zIndexNumber -= 10;
            });
        });
    };
    
    /* ------------------------------------------------------------------------------------
     * LOCATION SELECT BOX onchange() EVENT HANDLER
     * -----------------------------------------------------------------------------------*/
    $("#locationArea").change(function(){
        $("#topSearch input, #topSearch button").attr('disabled', 'disabled').css('cursor', 'default');
        $("#category_input").css('background', 'none').css('background-color', '#eee').css('cursor', 'default');
        window.location = $("#locationArea").val();
    });
    
    /* ------------------------------------------------------------------------------------
     * SEARCH FORM onsubmit() EVENT HANDLER
     * -----------------------------------------------------------------------------------*/
    $('#topSearch form').submit(function(){
        $("#locationArea_input").attr('disabled', 'disabled').css('background', 'none').css('background-color', '#eee').css('cursor', 'default');
        if ($('#keywords').val() == 'Keyword Search') {
            $('#keywords').val('');
        }
    });
    

    /*Dwaynefield - coming to a cinema near you*/
    $("#q").dwaynefield();
//    $('#mc').lcCheckbox();
    $('#pageHeader a').frostModal();
    
    
    ///////////////////////////////////////////
    ////// Marketing Promo Carousel Widget
    //////////////////////////////////////////
    var initMarketingPromos = $('.promo-carousel ul').children().length;
    if ($('.promo-carousel').is('div') && initMarketingPromos > 1) {
        $('#promoController').show();
        $(".promo-carousel").jCarouselLite({
            auto: 7000,
            speed: 500,
            btnNext: "#nextPromo",
            btnPrev: "#previousPromo",
            visible: 1,
            scroll: 1,
            afterEnd: function(a) {
                a.each(function() {
                    $("#promoType").html($(this).find("input").attr("value"));
                });
            }
        });
    }
    
    
    /* ------------------------------------------------------------------------------------
     * BK-ClassMenu - KICK EVERYTHING OFF AND SET BINDINGS
     * -----------------------------------------------------------------------------------*/
    //Set up the height of the wrapping element for the menu so ie6 can have it's precious position: absolute
    if (isIE_Six) { //IE6
        wrapHeight();
    }
    //Toggle the flyout on first button
    $("#bkMenu div.listingBlock a.fullList").css("cursor","pointer").live("mousedown",flyOutToggle); 
    //Close with the flyouts button
    $("#bkMenu div.listingBlock div.fullListContainer a.fullListClose").css("cursor","pointer").live("click",flyOutToggle); 
    //Set up the actions for accordian
    $("#bkMenu div.bkMenuHeader h3").css("cursor","pointer").bind("click",runAccordian);
    
    /* ------------------------------------------------------------------------------------
     * Colorbox MODAL active elements (used for image ads)
     * -----------------------------------------------------------------------------------*/
    $("a.colorbox").colorbox({
		initialWidth: "60",
		initialHeight: "60",
		//maxWidth: ($(window).width() - 40) + "px",
		//scalePhotos: "true",
		close: ""
	});
	
	$("#cboxWrapper").click(function() {
	    $.fn.colorbox.close();
	});
	
    $().bind('cbox_closed', function(){
	    $('.resultBoxThumbnail').scrollTop(0);
    });
    
	/*
    $("#pageHeader a").colorbox({
        width:"50%",
		initialWidth: "50%",
		initialHeight: "10",
        inline:true,
        href:"#helpModal"
    });
    */
     
}); /*End the document ready function*/

/* ------------------------------------------------------------------------------------
 * BK-ClassMenu - class based animated accordion menu for Local Classifieds
 * -----------------------------------------------------------------------------------*/
    /*----------------- GLOBAL FLAGS ----------------*/

    var flyOutOpen = false; /*For running flyout code or not - just a bit of efficiency*/
    var debug = false; /*get statements for debugging*/
    
    /*------------ Browser sniffing :'-( -----------*/
    var isIE = $.browser.msie;
    var isIE_Six = false;
    var isIE_Seven = false;
    if(isIE && $.browser.version=="6.0") { isIE_Six = true; } else { isIE_Six = false; };
    if(isIE && $.browser.version=="7.0") { isIE_Seven = true; } else { isIE_Seven = false; };
    //if (debug) {$.log("isIE "+isIE);}
    
/*=== UTILITY FUNCTION FOR IE6 MENU WRAPPER HEIGHT BECAUSE IT'S 'POSITION:ABSOLUTE' ===*/
    var wrapHeight = function(){
        $('#bkMenuWrapper').height($('#bkMenu').outerHeight(true));
        //if (debug) {$.log("WrapHeight Called");}
    };

/*====== SORT OUT ANY OF THE FLYOUT ACTIONS ========================================== */
    var flyOutToggle = function(closeSwitch){
        //if (debug) {$.log("flyOutToggle function running");}
        if (!(closeSwitch == "close") && debug) { $.log("Clicked on "+this.className); }
        
        if (closeSwitch == "close") { //Special switch for closing it from other functions, not events.
            $("#bkMenu .listingBlock").animate({ width: "170px" }, 150, "linear", function(){
                //if (debug) {$.log("flyOutOpen special close - animated closed");}
            });
            $("#bkMenu .listingBlock a.fullList").html("Full List");
            //if (debug) {$.log("flyOutOpen function from special close");}
            flyOutOpen = false;
            //if (debug) {$.log("flyOutToggle ends with flyOutOpen: "+flyOutOpen);}
            return false;
        }
        if ($(this).hasClass("fullListClose")) {
            $(this).css('outline','none');
            $(this).parent().parent().stop().animate({ width: "170px" }, 500 );
            $('#bkMenu .listingBlock a.fullList').html("Full List");
            //if (debug) {$.log("flyOutClose function from fulllistclose");}
            flyOutOpen = false;
            //if (debug) {$.log("flyOutToggle ends with flyOutOpen: "+flyOutOpen);}
            return false;
        }
        if ($(this).hasClass("fullList") && ($(this).html()=="Full List")) {
            $(this).css('outline','none');

            $getListChildren = $(this).siblings('.fullListContainer').children('ul');
            
        getWidthFlyOutUderbugen = function(){
            var total = 0;            
                $getListChildren.each(function() {
                    total += $(this).outerWidth(true);
                });
                
            return Number(total);
        };

            $(this).siblings(".fullListContainer").height($(this).parent().outerHeight() - 2).width(getWidthFlyOutUderbugen() + 20);
                        
            $(this).parent().stop().animate({ width: getWidthFlyOutUderbugen() + 212 +'px' }, 500 );
            $(this).html("Hide");
            //if (debug) {$.log("flyOutOpen function from fulllist");}
            flyOutOpen = true;
            //if (debug) {$.log("flyOutToggle ends with flyOutOpen: "+flyOutOpen);}
            return false;
        }
        if ($(this).hasClass("fullList") && ($(this).html()=="Hide")) {
            $(this).css('outline','none');
            $(this).parent().stop().animate({ width: "170px" }, 500 );
            $(this).html("Full List");
            //if (debug) {$.log("flyOutClose function from fulllist");}
            flyOutOpen = false;
            //if (debug) {$.log("flyOutToggle ends with flyOutOpen: "+flyOutOpen);}
            return false;
        }
        //if (debug) {$.log("flyOutToggle function ends");}
        return false;
    };


/*====== THE MAIN EVENT ========================================================= */
    var runAccordian = function(){
        /*If it's an <a> tag get rid of the outline jibba jabba and get one more parent up!*/
        $(this).css('outline','none');
        
        /*FIRST CASE - The menu is open and you click on the open heading - just close it and don't close others*/
        if($(this).parent().parent().hasClass("listingBlock")) {
            /*Only if it's not animating currently*/
            //if (debug) {$.log("Animation state: "+$("div:animated").size());}
            if (!($("div:animated").size() > 0)) { 
                //if (debug) {$.log("Case 1");}
                // 1. Close flyout
                if (flyOutOpen) { flyOutToggle("close"); } //shut it with the special close mode
                if (!(isIE)) { //NOT IE
                    //if (debug) {$.log( "NORMAL BROWSER METHOD" );}
                    // 2. Retract the accordian
                    $(this).parent().parent().switchClass("listingBlock","closedListingBlock",350,"easeInOutQuint",
                    function(){
                        if (!flyOutOpen) { $(this).css({ width: "170px" }); } //cleanup for flyout function
                        //if (debug) {$.log("Retracted Accordian in first case");}
                    });
                } else {
                    //if (debug) {$.log("IE METHOD");}
                    // 2. Retract the accordian
                    $(this).parent().parent().animate(
                        {height:"34px",paddingBottom:"1px"},
                        { 
                        step: function(now){ if (isIE_Six) {wrapHeight(); 
                            /*if (debug) {$.log("RUNNING STEP");}*/}}, /* This is for ie6 */
                        duration:350,
                        easing:"easeInOutQuint",
                        complete: function(){
                                if (isIE_Six) { wrapHeight(); }
                                $(this).removeClass("listingBlock");
                                $(this).addClass("closedListingBlock");
                                //if (!flyOutOpen) { $(this).css({ width: "170px" }); } //cleanup for flyout function
                                 //if (debug) {$.log("Retracted Accordian in first case");}
                            }
                        }
                    );
                    
                    
                }
            }
        /*SECOND CASE - The menu is open and you click on another heading - close others and open the new one*/
        } else {
            /*Only if it's not animating currently*/
             //if (debug) {$.log("Animation state: "+$("div:animated").size());}
             if (!($("div:animated").size() > 0)) {
                //if (debug) {$.log("Case 2");}
                
                // 1. Close flyout
                if (flyOutOpen) { flyOutToggle("close"); } //shut it with the special close mode
                
                if (!(isIE)) { //NOT IE
                    //if (debug) {$.log("NORMAL BROWSER METHOD");}
                    // 2a. Retract the other accordian while opening the other below
                    $("#bkMenu .listingBlock").switchClass("listingBlock", "closedListingBlock", 350, "easeInOutQuint", function(){
                        if (!flyOutOpen) { $(this).css({ width: "170px" }); } //cleanup for flyout function
                        //if (debug) {$.log("Retracted All in second case");}
                    });
                    // 2b. Animate this to open at the same time
                    $(this).parent().parent().switchClass("closedListingBlock", "listingBlock", 550, "easeInOutQuint",
                    function(){ /*if (debug) {$.log("Opened Accordian in second case");}*/ });
                    
                } else {
                    //if (debug) {$.log("IE METHOD");}
                    // 2a. FOR IE 6 & 7: Retract the other accordian while opening the other below
                    $("#bkMenu .listingBlock").animate({ height: "34px", paddingBottom: "1px" }, 350, "easeInOutQuint", function(){
                        $(this).removeClass("listingBlock");
                        $(this).addClass("closedListingBlock");
                        if (!flyOutOpen) { $(this).css({ width: "170px" }); } //cleanup for flyout function
                        //if (debug) {$.log("Retracted Accordian in first case");}
                    });
                    // 2b. FOR IE: Animate this to open at the same time
                    //Cache where we are
                    var accordianBlock = $(this).parent().parent();
                    // Seems jquery cannot animate width/height with target auto (F***!)
                    var smallHeight = accordianBlock.css('height'); // So first remember thecurrent (collapsed) height
                    accordianBlock.css('height', 'auto'); // then temporarily set to auto
                    var newHeight = accordianBlock.height(); // to calculate the desired height
                    //if (debug) {$.log("We just figured out the px height of this div if it was auto");}
                    accordianBlock.css('height', smallHeight); // then set the collapsed height again
                    // and animate to the fixed expanded height
                    accordianBlock.animate(
                        {height:newHeight+"px",paddingBottom:"23px"},
                        { 
                        step: function(now){ if (isIE_Six) { wrapHeight(); /*if (debug) {$.log("RUNNING STEP");}*/}}, /* This is for ie6 */
                        duration:350,
                        easing:"easeInOutQuint",
                        complete: function(){
                                accordianBlock.css('height','auto'); // but set to auto again when animation is complete
                                //if (debug) {$.log("Animated to the right height, then flipped to auto on height");}
                                if (isIE_Six) { wrapHeight(); }
                                $(this).removeClass("closedListingBlock");
                                $(this).addClass("listingBlock");
                                if (!flyOutOpen) { $(this).css({ width: "170px" }); } //cleanup for flyout function
                                //if (debug) {$.log("Opened Accordian in second case");}
                            }
                        }
                    );
                }
            }
        }
        return false;
    };

// FROST WRITING CUSTOM CHECK BOX FUNCTION
(function($){    
    $.fn.lcCheckbox = function() {

        var cookieName = '_lcsl';

        this.each(function() {
            $parentWrapper = $(this);

            $allCheckBoxes = $parentWrapper.find('input:checkbox');
            
            $allCheckBoxes.wrap('<span class="checkBoxWrapper"></span>').after('<span class="boxUnChecked"></span>').css('opacity', 0);

            initialiseShortlistCheckboxes(cookieName);

            $allCheckBoxes.filter(':checked').each(function(index) {
                $(this).next('span').removeClass().addClass('boxChecked');
            });

            var titleVal = $parentWrapper.find('.boxUnChecked').siblings('input[type=checkbox]').attr('title');
            $parentWrapper.find('.boxUnChecked').attr('title', titleVal);
            
            var remTitleVal = "Remove from Short List";
            $parentWrapper.find('.boxChecked').attr('title', remTitleVal);
            
            //Trying to use classes for the bind...lets see how we go!
            $allCheckBoxesByClass = $parentWrapper.find('.boxUnChecked, .boxChecked');

            $allCheckBoxesByClass.bind('click', function(event) {

                $checkBox = $(this).prev('input:checkbox');

                var checked = $checkBox.attr('checked');
                var adID = $checkBox.attr('id');

                if (!checked) {
                    $(this).removeClass().addClass('boxChecked');
                    $checkBox.attr('checked', true);
                    $(this).attr('title', remTitleVal);
                    addAdIDToCookie(adID, cookieName);
                }
                else {
                    $(this).removeClass().addClass('boxUnChecked');
                    $checkBox.attr('checked', false);
                    $(this).attr('title', titleVal);
                    removeAdIDFromCookie(adID, cookieName);
                };

                updateShortlistLink(cookieName);
            });
        });
        
        // Shortlist page specific item fading effects
        $('li.shortListPageItem span.checkBoxWrapper span').bind("click", function(){
            if ($(this).hasClass("boxUnChecked")) {
                $(this).parent().parent().addClass("faded");
            }
            else {
                $(this).parent().parent().removeClass("faded");
            }
        });
    };
    
})(jQuery);

function readReferrerCookie(){
    alert ($.cookie('REFERRER'));
};

function cleanShortlistCookie(oldCookieValue) {

    var cookieName = '_lcsl';
    var cookieValue = $.cookie(cookieName);
    oldCookieValue = $.base64Decode(oldCookieValue);

    if (oldCookieValue == cookieValue) {
        $('#shortlistPersonalised').css('display', 'inline');

        var ids = '';
    
        $('#mc input[type=checkbox]').each(function() {
            ids += $(this).attr('id') + '.';
        });
    
        ids = ids.substring(0, ids.length - 1);
        
        $.cookie(cookieName, ids, { expires: 7, path: '/'});
    }
    else {
        $('#shortlistPersonalised').css('display', 'none');
    }
}

function initialiseShortlistCheckboxes(cookieName) {

    var cookieValue = $.cookie(cookieName);

    if (cookieValue != null && cookieValue != '') {
                                                   
        var ids = cookieValue.split('.');
        var selectorString = '';
        
        for (i = 0; i < ids.length; ++i) {
            selectorString += '#' + ids[i] + ',';
        }

        selectorString = selectorString.substring(0, selectorString.length - 1); //get rid of the trailing comma

        $(selectorString).each(function() {
            $(this).attr('checked', true);
        });
    }
}

function addAdIDToCookie(adID, cookieName) {

    var cookieValue = $.cookie(cookieName);

    cookieValue = cookieValue != null && cookieValue != '' ? cookieValue + '.' + adID : adID;

    $.cookie(cookieName, cookieValue, { expires: 7, path: '/'});
}

function removeAdIDFromCookie(adID, cookieName) {

    var cookieValue = $.cookie(cookieName);

    if (cookieValue != null && cookieValue != '') {

        var oldIDs = cookieValue.split('.');
        var newIDs = '';
        
        for (i = 0; i < oldIDs.length; ++i) {
        
            var currentID = oldIDs[i];
        
            if (currentID != adID) {
                newIDs += currentID + '.';
            }
        }
        
        cookieValue = newIDs.substring(0, newIDs.length - 1); //get rid of the trailing dot
    }
    
    $.cookie(cookieName, cookieValue, { expires: 7, path: '/'});
}

function updateShortlistLink(cookieName) {

    var cookieValue = $.cookie(cookieName);
    var numAdItems = 0;
    
    //example html (current as of time of writing this):
    //<div class="shortList"><span class="shortListLink">My Short List</span> <strong class="count">0</strong> Items</div>

    var $link = $('.shortList .shortListLink a');

    if (cookieValue == null || cookieValue == '') {

        if ($link.length) {
            $link.parent().html($link.html());
        }
    }
    else {
        numAdItems = cookieValue.split('.').length;
        // use the value from the location variable in the base template
        var newURL = '/shortlist/' + $.base64Encode(cookieValue) + '/';

        if ($link.length) {
            $link.attr('href', newURL);
        }
        else {
            var newLink = '<a href="' + newURL + '">' + $('.shortList .shortListLink').html() + '</a>';
            $('.shortList .shortListLink').html(newLink);
        }
    }

    $('.shortList .count').html(numAdItems);
}

// FROST WRITING CUSTOM MODAL PLUGIN

(function($){
    $.fn.frostModal = function() {
        
        var $mask = $('#mask');
        var $modal = $('.windowModal');
        var $body = $('body');
        var $html = $('html');
        var $close = $('.close');
        
        var $windowHeight = $(window).height();
        var $windowWidth = $(window).width();

        var $modalHeight = $modal.outerHeight();
        var $modalWidth = $modal.outerWidth();
        
        var top = ($windowHeight - $modalHeight) / 2;
        var left = ($windowWidth - $modalWidth) / 2;
        
        $modal.css({top: top, left: left});        
                
        _showModal = function() {
            $body.css({overflow: 'hidden', height: '100%', margin: 0, width: '100%'});
            $html.css({overflow: 'hidden', height: '100%', margin: 0, width: '100%'});                       
            $mask.css({display: 'block', opacity: 0 })
                .animate({opacity: 0.8}, 500);
                
            $modal.css({display: 'block', opacity: 0})
                .animate({opacity: 1.0}, 500);
            
            var $modalOffset = $modal.offset();
            var $modalWidth = $modal.outerWidth();
            var $closePosition = $modalOffset.left + $modalWidth;
            
            $close.css({display: 'block', top: $modalOffset.top - 8, left: $closePosition -12 });    
        };
        
        _closeModal = function() {
            $body.css({overflow: 'visible', height: 'auto', margin: 0, width: 'auto'});
            $html.css({overflow: 'auto', height: 'auto', margin: 0, width: 'auto'});
            $mask.hide();
            $modal.hide();
            $close.hide();
        };
        
        _moveModal = function() {
             $modal.css('top', topScroll+top);
        };
        
        $mask.bind('click', function() {
            _closeModal();
        });
        
        $('.close', $body).bind('click', function() {
            _closeModal();
        });
        
        return this.each(function() {
            $(this).bind('click', function(e) {
                _showModal();
            });
            
        });
        
    };
})(jQuery);


///////////////////////////////////////////
////// AD CHECK MAGIC: Checks the adzones for specific attributts and tag names: JQUERY Utility function
////// base.html uses a fucntion to call this script called $.pageAdCout... I think ;)
//////////////////////////////////////////
//++++ THIS FUNCTION NEEDS REFACTORING
 (function($) {
    $.pageAdCount = function(count) {

        //  GET ALL ADS THAT MAY DISPLAY NONE ON RIGHT SIDE
        var adSpace0 = $('#adSpace0') != null && $('#adSpace0').html();
        var adSpace1 = $('#adSpace1') != null && $('#adSpace1').html();
        var adSpace2 = $('#adSpace2') != null && $('#adSpace2').html();
        var adSpace3 = $('#adSpace3') != null && $('#adSpace3').html();
        var adSpace4 = $('#adSpace4') != null && $('#adSpace4').html();
        var adSpace5 = $('#adSpace5') != null && $('#adSpace5').html();
        var adSpace6 = $('#adSpace6') != null && $('#adSpace6').html();
        var adSpace7 = $('#adSpace7') != null && $('#adSpace7').html();
        var adSpace8 = $('#adSpace8') != null && $('#adSpace8').html();
        var adSpace9 = $('#adSpace9') != null && $('#adSpace9').html();
        var adSpace10 = $('#adSpace10') != null && $('#adSpace10').html();
        var adSpace11 = $('#adSpace11') != null && $('#adSpace11').html();
        var adSpace12 = $('#adSpace12') != null && $('#adSpace12').html();
        var adSpace13 = $('#adSpace13') != null && $('#adSpace13').html();
        var adSpace14 = $('#adSpace14') != null && $('#adSpace14').html();


        // REG EX WHICH FINDS AN IMAGE NAME IF NO AD IS SHOWING
        var reg = '/(AE[0-2]{1}|noimage)\.gif/mig';
        var result = eval(reg);
        var adZones = count;

        for (var i = 0; i < adZones; i++) {
            if ($('#adSpace' + i).is('div')) {
                var check = $('#adSpace' + i).html();

                if (check.search(result) > 0) {
                    $('#adSpace' + i).hide();
                };
            }
        }


        // SPECIFIC ADS ON THE RIGHT AD ADVERTISE TEXT ABOVE
        if (adSpace1 && adSpace1.search(result) < 0) {
            $('#adSpace1').before('<div class="advertiseText"><span>Advertisement</span></div>');
        };
        
        if (adSpace2 && adSpace2.search(result) < 0) {
            $('#adSpace2').before('<div class="advertiseText"><span>Advertisement</span></div>');
        };

        if (adSpace3 && adSpace3.search(result) < 0) {
            $('#adSpace3').before('<div class="advertiseText"><span>Advertisement</span></div>');
        };

        if (adSpace4 && adSpace4.search(result) < 0) {
            $('#adSpace4').before('<div class="advertiseText"><span>Advertisement</span></div>');
        };

        if ((adSpace9 && adSpace9.search(result) < 0) || (adSpace10 && adSpace10.search(result) < 0) || (adSpace11 && adSpace11.search(result) < 0)) {
            $('#sponsoredLinks').before('<div class="advertiseText sponsoredTop"><span>Sponsored links</span></div>');
        };

        if ((adSpace5 && adSpace5.search(result) < 0) || (adSpace6 && adSpace6.search(result) < 0) || (adSpace7 && adSpace7.search(result) < 0) || (adSpace8 && adSpace8.search(result) < 0)) {
            $('.partnerCenter1').before('<div id="partnerCenter" class="advertiseText"><span>Partner Center</span></div>');
        } else {
            $('.partnerCenter1').hide();
            $('.partnerCenter2').hide();
        };

    };
})(jQuery);
