$(function() {
    //On Page Load

    //Rotating banners, this element has a noJs class so if javascript is disabled
    //only the first banner in the list is displayed else noJs class is removed
    $('ul#rotateAds li').removeClass('noJs');

    //The following event handlers are loaded
    searchBoxEventHandlers();
    homepageRotateEventHandlers();
    loadImagesEventHandlers();

    //Weak JS for WEAK Navigation
    P7_initPM(1, 9, 1, -4, 0)

    //Adding stripes to catalogue list
    $("div.auction:odd").addClass("odd");
});

//Search Box
function searchBoxEventHandlers() {
    var searchTextVal = ' Gold coins', //Set the default text here to appear in search box
	    searchInputBox = $('#txtLotFindCriteria');

    searchInputBox.val(searchTextVal);

    //Clears the search box text field if the text is equal to the default one set above
    searchInputBox.focus(function() {
        if (searchInputBox.val() == searchTextVal) {
            searchInputBox.val('');
        }
    });

    //When the user clicks away and the textbox is empty it adds in the default search
    searchInputBox.blur(function() {
        if (searchInputBox.val() == '') {
            searchInputBox.val(searchTextVal);
        }
    });
}

//Rotating banners
function homepageRotateEventHandlers() {
    var numLow = 1, //lowest number in list
		numHigh = 4, //the total number of items in the list
		adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1,
		numRand = Math.floor(Math.random() * adjustedHigh) + parseFloat(numLow);

    //Finds element that matches and adds class
    $('ul#rotateAds li#ad-' + numRand).addClass('show');
}

//Load Images
function loadImagesEventHandlers() {
    //As were applying margins to the images once there loaded the user would see them move on the page which doesn’t look great
    //To get around this were only going to display images once they have fully downloaded and the margins have been added
    $('div.auctionmainpic a img').each(function() {
        if (!this.complete) {
            $(this).load(function() {
                //image has been downloaded
                $(this).cAlign().show();
            });
        } else {
            //image has been cached
            $(this).cAlign().show();
        }
    });
}

//Centre Align Function
//This finds the width and height of the parent element and adds the right amount of margin to
//the image so it looks centred both vertically and horizontally
(function($) {
    $.fn.cAlign = function() {
        return this.each(function() {
            //Horizontal
            var aw = $(this).width(),
			    pw = $(this).parent().width(),
			    nw = (pw - aw) / 2,
            //Vertical
			    ah = $(this).height(),
			    ph = $(this).parent().height(),
			    nh = (ph - ah) / 2;
            $(this).css('margin-top', nh);
            $(this).css('margin-left', nw);
        });
    };
})(jQuery);