// BERPA namespace
var BERPA = {
    topMenuHover: {
    
        menuOptions: {
            noMenu: {
                id: 0,
                html: ''
            },
            historyMenu: {
                id: 1,
                html: ''
            },
            auctionMenu: {
                id: 2,
                html: ''
            }
        },
        
        defaultMenu: 0,
        
        currentMenu: 0,
        
        initialize: function() {
            // Detect which is the current menu.
            if( $('#submenu li').length === 5 )
            {
                BERPA.topMenuHover.currentMenu = 1;
                BERPA.topMenuHover.defaultMenu = 1;
            }            
            else if( $('#submenu li').length === 4 )
            {
                BERPA.topMenuHover.currentMenu = 2;
                BERPA.topMenuHover.defaultMenu = 2;
            }
            
            // Bind the top menu elements to the mouseover.
            $('#topmenu li a').mouseenter(function() {
                var newMenuIndex = $('#topmenu li a').index(this);
 
                switch( newMenuIndex )
                {
                    case 1:
                        BERPA.topMenuHover.changeMenu( 1 );
                        break;                        
                    case 2:
                        BERPA.topMenuHover.changeMenu( 2 );
                        break;
                    default:
                        BERPA.topMenuHover.changeMenu( BERPA.topMenuHover.defaultMenu );
                }
            });
        },
        
        changeMenu: function( newMenuId ) {
            // Change the menu displayed if the id is different.
            var newMenuHTML;
            
            if( newMenuId != BERPA.topMenuHover.currentMenu )
            {         
                switch( newMenuId )
                {
                    case 0:
                        newMenuHTML = BERPA.topMenuHover.menuOptions.noMenu.html;
                        BERPA.topMenuHover.currentMenu = 0;
                        break;
                    case 1:
                        newMenuHTML = BERPA.topMenuHover.menuOptions.historyMenu.html;
                        BERPA.topMenuHover.currentMenu = 1;
                        break;
                    case 2:
                        newMenuHTML = BERPA.topMenuHover.menuOptions.auctionMenu.html;  
                        BERPA.topMenuHover.currentMenu = 2;  
                        break;
                    default:
                        // If the defaultMenu doesn't exist, this will create an infinite loop.
                        BERPA.topMenuHover.changeMenu( BERPA.topMenuHover.defaultMenu );
                }
                
                $('#submenu').html( newMenuHTML );
            }
        }
    },
    
    connectionOverlay: {
        handle: null,
        
        html: '',
        
        initialize: function() {
            // Create the overlay with the login box.
            BERPA.connectionOverlay.handle =   $('<div></div>')
                                        .html( BERPA.connectionOverlay.html )
                                        .dialog({
                                            autoOpen: false,
                                            closeText: BERPA.languageStrings['ConnectionOverlay_CloseButton'],
                                            dialogClass: 'dialog',
                                            draggable: false,
                                            modal: true,
                                            resizable: false,
                                            title: BERPA.languageStrings['ConnectionOverlay_Title'],
                                            width: 500
                                        });
                                        
            // Need to add the buttons separately because of the localized text.
            BERPA.connectionOverlay.handle.dialog( "option", "buttons", [
                {
                    text: BERPA.languageStrings['ConnectionOverlay_ConnectButton'],
                    click: function() { BERPA.connectionOverlay.validateForm(); }
                }, 
                {
                    text: BERPA.languageStrings['ConnectionOverlay_CancelButton'],
                    click: function() { $(this).dialog('close'); }
                }
            ] );
            
            // Add the enter event to the form.
            $('form', BERPA.connectionOverlay.handle).jkey('enter',function(){
                BERPA.connectionOverlay.validateForm();
            });
            
            // Automatically switch to the password field after 6 characters have been entered.
            $('#username', BERPA.connectionOverlay.handle).keyup( function() {
                var username = $('#username', BERPA.connectionOverlay.handle).val();
                
                if( ( username.length === 5 ) && ( !isNaN( parseInt( username, 10 ) ) ) )
                {
                    $('#password', BERPA.connectionOverlay.handle).focus();
                }
            });
                                        
            // Add the click event on the connection button.
            if( $('#userbar li').length === 1 )
            {
                $('#userbar li a').click(function(event) {               
                    BERPA.connectionOverlay.handle.dialog('open');
                    event.preventDefault();
                });
            }
        },
        
        validateForm: function() {
            // Validate the form data.
            var username = $('#username', BERPA.connectionOverlay.handle).val();
            var password = $('#password', BERPA.connectionOverlay.handle).val();
            var error = '';
            
            function displayError(error) {
                $('.error', BERPA.connectionOverlay.handle).html(error);
            }
            
            if( username == '' )
            {
                displayError(BERPA.languageStrings['ConnectionOverlay_EmptyUsername']);
                $('#username', BERPA.connectionOverlay.handle).focus();
            }
            else if( password == '' )
            {
                displayError(BERPA.languageStrings['ConnectionOverlay_EmptyPassword']);
                $('#password', BERPA.connectionOverlay.handle).focus();
            }
            else
            {               
                // Send the login request to the server.
                
                // Disable the login button for the request, re-enable it at the end.
                $('button:eq(0)', BERPA.connectionOverlay.handle.dialog.buttons).button('disable');
                
                $.ajax( 'js/ajax-login.js', {
                    cache: false,
                    complete: function() {
                        // Re-enable the login button.
                        $('button:eq(0)', BERPA.connectionOverlay.handle.dialog.buttons).button('enable');
                    },
                    data: ({
                        username: username,
                        password: password
                    }),
                    dataType: 'json',
                    error: function(){
                        // There was an error processing the request.
                        displayError(BERPA.languageStrings['ConnectionOverlay_UnknownError']);
                    },
                    success: function(data){
                        // Successfully received the response, what does the data say?
                        switch( data.response )
                        {
                            case 'internal':
                            case 'granted':
                                // The credentials provided seem ok, submit the form and change the buttons accordingly.
                                $('button:eq(0)', BERPA.connectionOverlay.handle.dialog.buttons).hide();
                                $('button:eq(1)', BERPA.connectionOverlay.handle.dialog.buttons).button('option', 'label',BERPA.languageStrings['ConnectionOverlay_LoggingIn'] + '...');
                                $('button:eq(1)', BERPA.connectionOverlay.handle.dialog.buttons).button('disable');
                                $('form', BERPA.connectionOverlay.handle).submit();
                                break;
                            default:
                                // Wrong login information was provided.
                                displayError(BERPA.languageStrings['ConnectionOverlay_WrongInformation']);
                                $('#username', BERPA.connectionOverlay.handle).select();
                        }
                    },
                    timeout: 5000,
                    type: 'POST'
                    }                    
                )
            }
        }
    },
    
    photoCarousel: {
        initialize: function() {
            // Grab the information we need of the current thumbnails.
            var DOMPhotoList = $('.vehicledetails_photo');
            var photoCount = DOMPhotoList.length;
            var photoContainer = DOMPhotoList.parents('.content-box-body');
            var finalPhotoList = new Array( photoCount );
            
			// Apply the carousel only if the user chose so.
			if( $.cookie('nophotocarousel') != '1' )
			{
				// Populate the carousel with the correct data.
				DOMPhotoList.each( function(index) {
					var imageSource = $('img', $(this)).attr('src');

					finalPhotoList[index] = new Object();
					finalPhotoList[index].image = imageSource.slice(0, imageSource.length - 12);
					finalPhotoList[index].link = $(this).attr('href');                                   
				});
				
				// Do some housekeeping on the page.
				photoContainer.html('');
				
				// Instantiate the carousel.
				photoContainer.PikaChoose({
					carousel: true,
					data: finalPhotoList,
					showCaption: false,
					text: {
						previous: BERPA.languageStrings['PhotoOverlay_Previous'],
						next: BERPA.languageStrings['PhotoOverlay_Next']
					},
					transition: [0]
				});
				
				photoContainer.addClass('pikachoose');
				
				// Prevent default behaviour on picture click.
				photoContainer.click(function(event) {
					if( $(event.target).is('img') && ( $(event.target).width() == 640 ) )
					{
						event.preventDefault();
						event.stopPropagation();
					}                       
				});
			}
			
			// Option to disable the photo carousel.
			photoContainer.append('<p class="center"><label for="carouselon">' + BERPA.languageStrings['PhotoOverlay_EnableCarousel'] + ':</label> <input id="carouselon" type="checkbox" />');
			
			if( $.cookie('nophotocarousel') != '1' )
			{
				$('#carouselon').attr('checked', 'checked');
			}
			
			$('#carouselon').click( function(event) {
				if( $(this).is(':checked') )
				{
					$.cookie('nophotocarousel', null, { path: '/' });
				}
				else
				{
					$.cookie('nophotocarousel', '1', { path: '/' });
				}
				location.reload();
			});
        }
    },
    
    preOffer: {
        handle: null,
        
        amountHandle: null,
        
        errorInserted: false,
        
        html: '',
        
        initialize: function() {
            // Reset the properties.
            BERPA.preOffer.handle = null;
            BERPA.preOffer.amountHandle = null;
            BERPA.preOffer.errorInserted = false;
            
            // Is the form for a preoffer on the page?
            if( $('#preofferlink').length === 1 )
            {
                // What happends when we click on it?
                $('#preofferlink').click( function(event) {
                    event.preventDefault();
                    
                    // Is the user logged in?
                    if( BERPA.isLoggedIn )
                    {
                        // Yes, dynamically load the form to submit a preoffer.
                        var formAction = $('#preofferlink a').attr('href');

                        $('#preofferlink').replaceWith(BERPA.preOffer.html);
                        BERPA.preOffer.handle = $('form .right');
                        BERPA.preOffer.handle.parent('form').attr('action', formAction);
                        BERPA.preOffer.amountHandle = $('input:eq(0)', BERPA.preOffer.handle);
                        BERPA.preOffer.amountHandle.focus();

                        // Make sure that when a user inputs a comma it gets converted to a period.
                        BERPA.preOffer.amountHandle.jkey('<',function(key){
                            var selectionStart = BERPA.preOffer.amountHandle.getSelection().start;
                            BERPA.preOffer.amountHandle.insertText('.', selectionStart, 1);
                        });
                        
                        // Validation logic for when the user submits the form.
                        BERPA.preOffer.handle.parent('form').submit( function(event) {
                            var amount = parseFloat(BERPA.preOffer.amountHandle.val());
                            
                            if( isNaN(amount) )
                            {
                                // Nothing was inputed in the text field.
                                event.preventDefault();
                                BERPA.preOffer.displayError(BERPA.languageStrings['PreOfferDynamic_PreOfferEmpty']);
                                BERPA.preOffer.amountHandle.val('');
                                BERPA.preOffer.amountHandle.focus();
                            }
                            else if( amount < 200.00 )
                            {
                                // The amount provided is too low.
                                event.preventDefault();
                                var moneyValue = money_format( '%n', 200.00 );
                                
                                BERPA.preOffer.displayError(BERPA.languageValues('PreOfferDynamic_PreOfferTooSmall', '<span class="bold">' + moneyValue + '</span>'));
                                BERPA.preOffer.amountHandle.val('');
                                BERPA.preOffer.amountHandle.focus();
                            }
                            else
                            {
                                // Everything is fine, proceed with the form submission.
                                $('input:eq(1)', BERPA.preOffer.handle).after('<br /><span class="bold">' + BERPA.languageStrings['PreOfferDynamic_Submitting'] +  '...</span>');
                                
                                if( BERPA.preOffer.errorInserted )
                                {
                                    $('.error', BERPA.preOffer.handle).html('');
                                }
                                
                                BERPA.preOffer.handle.parent('form').unbind('submit');
                                BERPA.preOffer.handle.parent('form').submit( function(event) {
                                    event.preventDefault();
                                });
                            }
                        });
                    }
                    else
                    {
                        // No, create an overlay to inform the user.
                        BERPA.preOffer.handle =   $('<div></div>')
                                                    .html( BERPA.languageStrings['PreOfferDynamic_OverlayMustLogin'] )
                                                    .dialog({
                                                        autoOpen: true,
                                                        closeText: BERPA.languageStrings['PreOfferDynamic_CloseButton'],
                                                        dialogClass: 'dialog',
                                                        draggable: false,
                                                        modal: true,
                                                        resizable: false,
                                                        title: BERPA.languageStrings['PreOfferDynamic_OverlayTitle'],
                                                        width: 500
                                                    });
                                                    
                        // Need to add the buttons separately because of the localized text.
                        BERPA.preOffer.handle.dialog( "option", "buttons", [
                            {
                                text: BERPA.languageStrings['PreOfferDynamic_OverlayConnectButton'],
                                click: function() { $(this).dialog('close');$('#userbar li a').click(); }
                            }, 
                            {
                                text: BERPA.languageStrings['PreOfferDynamic_OverlayCancelButton'],
                                click: function() { $(this).dialog('close'); }
                            }
                        ] );
                        
                        $('#preofferlink').unbind('click');
                        
                        $('#preofferlink').click( function(event) {
                            event.preventDefault();
                            BERPA.preOffer.handle.dialog('open');
                        });
                    }
                });
            }
        },
        
        displayError: function(errorMessage) {
            // Create the error element if it hasn't been created yet.
            if( !BERPA.preOffer.errorInserted )
            {
                $('input:eq(1)', BERPA.preOffer.handle).after('<br /><span class="error"></span>');
                
                BERPA.preOffer.errorInserted = true;
            }
            
            // Place the error message in it.
            $('.error', BERPA.preOffer.handle).html(errorMessage);
        }
    },
    
    /*
    dynamicVehicleDetails: {
        initialize: function() {
            $('.nextlink').click( function(event) {
                
                event.preventDefault();
                
                $.ajax( 'js/ajax-loadvehicle.js', {
                    cache: false,
                    complete: function() {
                        
                    },
                    data: ({
                        direction: 'up',
                        currentrank: '130',
                        auctionid: '1234567'
                    }),
                    dataType: 'json',
                    error: function(){
                        
                    },
                    success: function(data){
                        // Successfully received the response, what does the data say?
                        switch( data.response )
                        {
                            case 'success':
                                
                                break;
                            default:
                                // Error.
                        }
                    },
                    timeout: 5000,
                    type: 'POST'
                    }                    
                )
                
            });
        }
    },
    */
    
    auctionExpress: {
        overlayHandle: null,
        
        overlayHTML: null,
        
        auctionId: null,
        
        initialize: function() {
            if( $('#encancontainer').length !== 0 )
            {
                // Temporary, integrate the old Auction-Express skeleton.
                BERPA.auctionExpress.auctionId = parseInt( $('#encancontainer').attr('auctionId') );
                
                if( BERPA.rcaaqId != false )
                {
                    
                    
                    // Did the user previously accept the agreement for this auction?
                    if( parseInt( $.cookie('berpa_ae_agree') ) == BERPA.auctionExpress.auctionId )
                    {
                        // Yes he did, load the auction.
                        BERPA.auctionExpress.loadInterface();
                    }
                    else
                    {
                        // No he did not, display the agreement.
                        $('#encancontainer').prev('p').html(BERPA.languageStrings['AE_Agreement_Loading'] + '...');
                        
                        BERPA.auctionExpress.overlayHandle =   $('<div></div>')
                            .html( BERPA.auctionExpress.overlayHTML )
                            .dialog({
                                autoOpen: true,
                                close: function() {
                                    if( parseInt( $.cookie('berpa_ae_agree') ) == BERPA.auctionExpress.auctionId ) 
                                    {
                                        BERPA.auctionExpress.loadInterface();
                                    }
                                    else
                                    {
                                        $('#encancontainer').prev('p').html(BERPA.languageStrings['AE_Agreement_RefuseMessage']);
                                    }
                                },
                                closeText: BERPA.languageStrings['AE_Agreement_CloseButton'],
                                dialogClass: 'dialog',
                                draggable: false,
                                modal: true,
                                resizable: false,
                                title: BERPA.languageStrings['AE_Agreement_OverlayTitle'],
                                width: 680
                            });
                                                    
                        // Need to add the buttons separately because of the localized text.
                        BERPA.auctionExpress.overlayHandle.dialog( "option", "buttons", [
                            {
                                text: BERPA.languageStrings['AE_Agreement_AcceptButton'],
                                click: function() { 
                                    $.cookie('berpa_ae_agree', BERPA.auctionExpress.auctionId, { expires: 2, path: '/' });
                                    $(this).dialog('close'); 
                                }
                            }, 
                            {
                                text: BERPA.languageStrings['AE_Agreement_RefuseButton'],
                                click: function() { $(this).dialog('close'); }
                            }
                        ] );
                    }
                }
                else
                {
                    // Directly load Auction-Express for Berpa members.
                    BERPA.auctionExpress.loadInterface();
                }
            }
        },
        
        loadInterface: function() {
            // Temporarily, integrate the old Auction-Express skeleton.
            if( BERPA.rcaaqId != false )
            {
                load_encan(BERPA.auctionExpress.auctionId, BERPA.rcaaqId, 1, {	lang: BERPA.language,
																				langStrings: BERPA.languageStrings,
																				languageValues: BERPA.languageValues });
            }
            else
            {
                load_encan(BERPA.auctionExpress.auctionId, -1, 1, {	lang: BERPA.language,
																				langStrings: BERPA.languageStrings,
																				languageValues: BERPA.languageValues });
            }
        }
    },
    
        
    insurerInventoryDropdown: {
        initialize: function() {        
            $("#selectedinsuranceco").next("input").hide();
            
            $("#selectedinsuranceco").change(function(event) {
                $(this).parents("form").submit();
            });
            
        }
    },
    
    insurerInventorySearchHint: {
        textToShow: '# dossier, # berpa ou VIN',
        
        initialize: function() {                               
            var textReference = BERPA.insurerInventorySearchHint.textToShow;
            
            $("#searchtext").width( 200  );
            
            if( $("#searchtext").val() == '' )
            {
                $("#searchtext").val(textReference);
            }
            
            $("#searchtext").parents("form").submit(function(event) 
            {
                BERPA.insurerInventorySearchHint.clearBeforeSending();
            });
            
            $("#searchtext").focus(function(event) 
            {
                BERPA.insurerInventorySearchHint.clearBeforeSending();
            });
            
            $("#searchtext").blur(function(event) {
                if( $("#searchtext").val() == '' )
                {
                    $("#searchtext").val(textReference);
                }
            });
        },
        
        clearBeforeSending: function() {
            if( $("#searchtext").val() == BERPA.insurerInventorySearchHint.textToShow )
            {
                $("#searchtext").val('');
            }
        },
    },
    
    insurerPriceHistoryAutoComplete: {      
        modelListHandle: null,
        
        makeLastSearched: '',
        
        initialize: function() {            
            $.ajax( 'js/ajax-insurer_autocomplete.js', {
                cache: true,
                dataType: 'json',
                success: function(data){
                    // Successfully received the response, what does the data say?
                    $('#make').autocomplete({
                        // Taken from http://stackoverflow.com/questions/2382497/jquery-autocomplete-plug-in-search-configuration.
                        delay: 0,
                        minLength: 0,
                        select: function(event, ui) { setTimeout(function(){$('#model').focus()}, 100) },
                        source: function(req, responseFn) {
                            var re = $.ui.autocomplete.escapeRegex(req.term);
                            var matcher = new RegExp( "^" + re, "i" );
                            var a = $.grep( data.matches, function(item,index){
                                return matcher.test(item);
                            });
                            responseFn( a );
                        }
                    });
                },
                type: 'POST'
                }                    
            );
            
            // Setup events for autocompletion on the forms.
            BERPA.insurerPriceHistoryAutoComplete.modelListHandle = $('#model').autocomplete(
            {
                delay: 0,
                minLength: 0, 
                select: function(event, ui) { $('#syear').focus() }, 
                source: [""]}
            );
            
            //$('#syear').selectmenu();
            
            /*
            $('#syear').autocomplete({
                autoFocus: true,
                disabled: true,
                select: function(event, ui) { setTimeout(function(){$('#eyear').focus()}, 100) },
            });
            */
            
            $('#make').focus(function(event) 
            {
                if( $(this).val() == '*' )
                {
                    $(this).val('');
                }
                
                $(this).autocomplete( 'search' );
            });
            
            $('#make').blur(function(event) 
            {
                if( $(this).val() == '' )
                {
                    $(this).val('*');
                }
            });
            
            $('#model').focus(function(event) 
            {
                if( $(this).val() == '*' )
                {
                    $(this).val('');
                }
                
                if( BERPA.insurerPriceHistoryAutoComplete.makeLastSearched != $('#make').val() && $('#make').val() != '' )
                {
                    BERPA.insurerPriceHistoryAutoComplete.makeLastSearched = $('#make').val();
                    
                    $.ajax( 'js/ajax-insurer_autocomplete.js', {
                        cache: true,
                        data: ({
                            make: $('#make').val()
                        }),
                        dataType: 'json',
                        success: function(data){
                            // Successfully received the response, what does the data say?
                            BERPA.insurerPriceHistoryAutoComplete.modelListHandle.autocomplete( 'option' , 'source' , function(req, responseFn) {
                                    var re = $.ui.autocomplete.escapeRegex(req.term);
                                    var matcher = new RegExp( "^" + re, "i" );
                                    var a = $.grep( data.matches, function(item,index){
                                        return matcher.test(item);
                                    });
                                    responseFn( a );
                                } );
                                
                            $('#model').autocomplete( 'search' );    
                        },
                        type: 'POST'
                        }                    
                    );
                }
                else
                {
                    $(this).autocomplete( 'search' );
                }
            });
            
            $('#model').blur(function(event) 
            {
                if( $(this).val() == '' )
                {
                    $(this).val('*');
                }
            });
        }
    },
    
    myAccountTableSort: {
        initialize: function() {
            $("table").tablesorter({
                sortList: [[3,1],[4,1]],
                sortMultiSortKey: null,
                textExtraction: function(node) { 
                    // Extract/alter data from the markup and return it for proper sorting. 
                    switch( $('td', $(node).parents('tr')).index(node) )
                    {
                        case 2:
                            // Money column.
                            if( BERPA.language == 'en' )
                            {
                                return $(node).html().replace(',', '').replace('$', '');
                            }
                            
                            if( BERPA.language == 'fr' )
                            {
                                return $(node).html().replace(' ', '').replace(',', '.').replace('$', '');
                            }
                        case 3:
                        case 4:
                            // Date columns.
                            return $(node).attr('timestamp');
                    }
                    
                    // Return the standard content of the cell if there is no need for specific sorting.
                    return $(node).html(); 
                }
            });

            // Give the table headers their style.
            $('table').addClass('tablesorter');     
        }
    },
    
    nextAuctionTableSort: {
        initialize: function() {
            var sortingSaved = $.cookie('nextauctionsorting');
            var defaultSorting = [[4,0]];
            
            if( sortingSaved != null )
            {
                defaultSorting = Array( Array(sortingSaved[0], sortingSaved[2]) );
            }

            $("table").tablesorter({
                headers: {
                    2: { sorter: false },
                    3: { sorter: false },
                    5: { sorter: false },
                    6: { sorter: false }
                },
                //selectorHeaders: 'thead th, tfoot th',
                //sortList: [[defaultSortcolumn,defaultSortDirection]],
                sortList: defaultSorting,
                sortMultiSortKey: null
            });
            
            
            // Resort given to cookies.
            $("table th").click(function(event) {
                event.preventDefault();
                var saveSortColumn = $('th', $(this).parents('tr')).index($(this));
                var saveSortDirection = 0;
                
                //TODO: Get more accurate data regarding column sorting direction.
                if( $(this).hasClass( 'headerSortUp' ) )
                {
                    //TODO.
                }
                else if( $(this).hasClass( 'headerSortDown' ) )
                {
                    saveSortDirection = 1;
                }
                else
                {
                    //TODO.
                }
                
                $.cookie('nextauctionsorting', saveSortColumn + ',' + saveSortDirection);
            });
            

            // Give the table headers their style.
            $('table thead img').hide();
            $('table tfoot').remove();
            $('table').addClass('tablesorter');  
        }
    },
    
    rcaaqId: false,
    
    isLoggedIn: false,
    
    isModerator: false,
    
    isSuperModerator: false,
    
    isAdministrator: false,
    
    language: null,
    
    languageStrings: null,
    
    languageValues: function() {
        var languageName = arguments[0];
        var functionArguments = Array.prototype.slice.call(arguments);
        
        functionArguments.shift();
        
        return vsprintf(BERPA.languageStrings[languageName], functionArguments);
    },
    
    initializePage: function(moduleName) {
        // Are we on a page that needs extra initialization?
        switch( moduleName )
        {
            case 'nextauction':
                BERPA.nextAuctionTableSort.initialize();
                
                break;
                
            case 'vehicledetails':
                BERPA.preOffer.initialize();
                BERPA.photoCarousel.initialize();
                //BERPA.dynamicVehicleDetails.initialize();
                
                break;
            
            case 'specialvehicledetails':
                BERPA.photoCarousel.initialize();
                
                break;
                
            case 'auctionexpress':
                BERPA.auctionExpress.initialize();
            
                break;
                
            case 'myaccount':
                BERPA.myAccountTableSort.initialize();
                
                break;   
                
            case 'insurer_inventory':
                BERPA.insurerInventoryDropdown.initialize();
                BERPA.insurerInventorySearchHint.initialize();
                
                break; 

            case 'insurer_pricehistory':
                BERPA.insurerPriceHistoryAutoComplete.initialize();
                
                break;                 
        }
    },
    
    initializeSite: function() {        
        // Load external resources such as html parts, language strings, etc.
        $.ajax('js/berpa.resources.js', {
            cache: true,
            dataType: 'json',
            error: function() {
                BERPA.initializeSite();
            },
            success: function(json, textStatus) {
                // Set the locale.
                BERPA.language = json.siteLanguage;
                setlocale('LC_ALL', BERPA.language + '_CA');
                
                // Language strings.
                BERPA.languageStrings = json.languageStrings;
                
                // Sessions.
                BERPA.rcaaqId = json.permissions.rcaaq;
                BERPA.isLoggedIn = json.permissions.loggedIn;
                BERPA.isModerator = json.permissions.moderator;
                BERPA.isSuperModerator = json.permissions.superModerator;
                BERPA.isAdministrator = json.permissions.administrator;
                
                // HTML for the top submenus.
                BERPA.topMenuHover.menuOptions.historyMenu.html = json.topMenuHTML[0];
                BERPA.topMenuHover.menuOptions.auctionMenu.html = json.topMenuHTML[1];
                
                // HTML for the connection overlay.
                BERPA.connectionOverlay.html = json.connectionOverlayHTML;
                
                // HTML for the pre-offer module.
                BERPA.preOffer.html = json.preOfferHTML;
                
                // HTML for the Auction-Express agreement overlay.
                BERPA.auctionExpress.overlayHTML = json.auctionExpressHTML;
                
                // 
            
                // Then call various methods to initialize the client-end of the website.
                BERPA.topMenuHover.initialize();
                BERPA.connectionOverlay.initialize();
                
                // Then call page-specific initializers, if need be.
                $.each( $('#content').attr('class').split(/\s+/), function(index, item){
                    if( item.slice(0, 5) == 'page_' )
                    {
                        BERPA.initializePage( item.slice(5, item.length) );
                    }
                });
                
                // When everything is done, load Google Analytics.
                BERPA.loadGoogleAnalytics();
            },
        });
    },
    
    // Dynamically load Google Analytics, see http://lyncd.com/2009/03/better-google-analytics-javascript/.
    loadGoogleAnalytics: function() {
        var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."),
        pageTracker,
        s;
        
        s = document.createElement('script');
        s.src = gaJsHost + 'google-analytics.com/ga.js';
        s.type = 'text/javascript';
        s.onloadDone = false;
        
        function init () {
            pageTracker = _gat._getTracker('UA-23674738-1');
            pageTracker._trackPageview();
        }
        
        s.onload = function () {
            s.onloadDone = true;
            init();
        };
        
        s.onreadystatechange = function() {
            if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) {
              s.onloadDone = true;
              init();
            }
        };
        
        document.getElementsByTagName('head')[0].appendChild(s);
    }
    
};

// Fires up when the DOM is ready to be manipulated.
$(function() {
    BERPA.initializeSite();
});

