// <![CDATA[

( function( $ )
{
    window.TxAtraHashDetected = false;
    
    var selectors = {
        selects : {
            make  : '#marque',
            model : '#models',
            km    : {
                from : '#km-from',
                to   : '#km-to'
            },
            price : {
                from : '#price-from',
                to   : '#price-to'
            }
        },
        checks : {
            oldCars: '#cartype-old',
            newCars: '#cartype-new'
        },
        table : '#tx-atra-pi1-carlist-results',
        td    : {
            makeModel : 'TD.tx-atra-pi1-makeModel',
            mileage   : 'TD.tx-atra-pi1-mileage',
            price     : 'TD.tx-atra-pi1-price'
        },
        makeModel : {
            make  : 'SPAN.tx-atra-pi1-make',
            model : 'SPAN.tx-atra-pi1-model'
        }
    };
    
    function single()
    {
        var selectors = {
            smallImage : '#tx-atra-pi1-smallImages IMG',
            bigImage   : '#tx-atra-pi1-bigImage IMG',
            texts      : [
                '#tx-atra-pi1-equipment-standard P',
                '#tx-atra-pi1-equipment-optional P'
            ]
        };
        
        var $bigImage = $( selectors.bigImage );
        
        if( !$bigImage.length ) {
            
            return;
        }
        
        var $smallImages = $( selectors.smallImage );
        
        $smallImages.hover(
            function()
            {
                var $this = $( this );
                
                $bigImage.attr( 'src', $this.attr( 'src' ) );
                
                $smallImages.removeClass( 'hovered' );
                
                $this.addClass( 'hovered' );
            }
        );
        
        var options = {
            slicePoint:       180,
            expandText:       '[+]',
            userCollapseText: '[-]'
        };
        
        for( var i = 0; i < selectors.texts.length; i++ ) {
            
            $( selectors.texts[ i ] ).expander( options );
        }
        
        $( '#tx-atra-pi1-interested' ).fancybox( {
            hideOnContentClick : false,
            width               : 520,
            height              : 480,
            autoScale           : false,
            transitionIn        : 'none',
            transitionOut       : 'none',
            type                : 'iframe'
        } );
        
        $( '#tx-atra-pi1-actions-finance' ).fancybox( {
            hideOnContentClick : false,
            width               : 150,
            height              : 210,
            autoScale           : false,
            transitionIn        : 'none',
            transitionOut       : 'none',
            type                : 'iframe'
        } );
        
        var $priceNew = $( '#tx-atra-pi1-property-pricenew' ),
            $previous = $priceNew.prev();
        
        $priceNew.addClass( $previous.hasClass( 'odd' ) ? 'even' : 'odd' );
        
        // $( '#tx-atra-other-cars' ).remove().appendTo( '#footer' );
    }
    
    function list()
    {
        // $( "select, input:checkbox, input:radio, input:file" ).uniform();
        var $table           = $( selectors.table ),
            $makeSelect      = $( selectors.selects.make ),
            $modelSelect     = $( selectors.selects.model ),
            $priceFromSelect = $( selectors.selects.price.from ),
            $priceToSelect   = $( selectors.selects.price.to ),
            $oldCheck        = $( selectors.checks.oldCars ),
            $newCheck        = $( selectors.checks.newCars );
            
        var selectedMake      = '',
            selectedModel     = '',
            selectedFromPrice = 0.0,
            selectedToPrice   = 0.0;
        
        populateMakeSelect();
        populatePriceFromSelect();
        populatePriceToSelect();
        
        $( '#reset' ).click( displayAll );
        
        $priceToSelect.children( ':last-child' ).attr( 'selected', 'selected' );
        
        $makeSelect.change( function()
        {
            filterListByMake( selectedMake = $makeSelect.val() );
            populateModelSelect();
            populatePriceFromSelect();
            populatePriceToSelect();
            
            reOddEvenRows();
        } );
        
        $modelSelect.change( function()
        {
            filterListByMake( selectedMake );
            filterListByModel( selectedModel = $modelSelect.val() );
            populatePriceFromSelect();
            populatePriceToSelect();
            
            reOddEvenRows();
        } );
        
        $priceFromSelect.change( function()
        {
            var prevVal = $priceToSelect.val();
            
            filterListByMake( selectedMake );
            filterListByModel( selectedModel );
            filterListByPriceFrom( selectedFromPrice = $priceFromSelect.val() );
            populatePriceToSelect( prevVal );
            
            filterListByPriceTo( prevVal );
            
            reOddEvenRows();
        } );
        
        $priceToSelect.change( function()
        {
            filterListByMake( selectedMake );
            filterListByModel( selectedModel );
            filterListByPriceFrom( selectedFromPrice );
            filterListByPriceTo( selectedToPrice = $priceToSelect.val() );
            populatePriceFromSelect( selectedFromPrice );
            
            reOddEvenRows();
        } );
        
        $oldCheck.add( $newCheck ).click( function()
        {
            var $parent = $oldCheck.parent();
            
            displayAll();
            
            filterListByMake( selectedMake );
            filterListByModel( selectedModel );
            filterListByPriceFrom( selectedFromPrice );
            filterListByPriceTo( selectedToPrice );
            
            filterListByCarType( {
                oldCars: !!( $parent.children( '#' + $oldCheck.attr( 'id' ) + ':checked' ).length ),
                newCars: !!( $parent.children( '#' + $newCheck.attr( 'id' ) + ':checked' ).length )
            } );
            
            populatePriceFromSelect();
            populatePriceToSelect();
            
            reOddEvenRows();
        } );
        
        function displayAll()
        {
            $table.find( 'TR' ).removeClass( 'hidden' ).removeClass( 'visible' ).addClass( 'visible' );
            
            reOddEvenRows();
        }
        
        function filterListByCarType( types )
        {
            if( !types ) {
                
                return;
            }
            
            if( types.oldCars ) {
                
                $table.find( 'TR.occasion.visible' ).removeClass( 'hidden' ).addClass( 'visible' );
            
            } else {
            
                $table.find( 'TR.occasion.visible' ).removeClass( 'visible' ).addClass( 'hidden' );
            }
            
            if( types.newCars ) {
                
                $table.find( 'TR.neuf.visible' ).removeClass( 'hidden' ).addClass( 'visible' );
                
            } else {
            
                $table.find( 'TR.neuf.visible' ).removeClass( 'visible' ).addClass( 'hidden' );
            }
        }
        
        function populateMakeSelect()
        {
            var $select = $makeSelect;
            var $makes  = $table.find( selectors.makeModel.make );
            var texts   = array_unique( filter( $makes, 'text' ) );
            
            var html = '<option value="">Toutes les marques</option>';
            
            for( i in texts ) {
                
                html += '<option value="' + texts[ i ] + '">' + texts[ i ] + '</option>';
            }
            
            $select.html( html );
        }
        
        function populateModelSelect()
        {
            var $select = $modelSelect;
            var html    = '<option value="">Tous les modèles</option>';
            
            if( !selectedMake ) {
                
                $select.html( html );
                
                return;
            }
            
            var $models = $table.find( 'TR:visible ' + selectors.makeModel.model );
            var texts   = array_unique( filter( $models, 'text' ) );
            
            for( i in texts ) {
                
                html += '<option value="' + texts[ i ] + '">' + texts[ i ] + '</option>';
            }
            
            $select.html( html );
        }
        
        function populatePriceFromSelect()
        {
            var minMax = getMinMaxPrice( 5000 ),
                steps  = ( minMax.max - minMax.min ) / 5000,
                html   = '';
            
            if( minMax.min === minMax.max ) {
                
                html = '<option value="' + minMax.min + '">de ' + minMax.min.commafy() + '.-</option>';
                
            } else {
                
                for( var i = 0; i < steps; i++ ) {
                    
                    var value = minMax.min + i * 5000;
                    
                    html += '<option value="' + value + '">de ' + value.commafy() + '.-</option>';
                }
            }
            
            $priceFromSelect.html( html );
            
            window.SelectSkin.setText( 'text-price-from', $priceFromSelect[ 0 ] );
        }
        
        function populatePriceToSelect( selectedPrice )
        {
            var minMax = getMinMaxPrice( 5000 ),
                steps  = ( minMax.max - parseInt( $priceFromSelect.val(), 10 ) ) / 5000,
                html   = '';
            
            if( minMax.min === minMax.max ) {
                
                html = '<option value="' + minMax.min + '">à ' + minMax.min.commafy() + '.-</option>';
                
            } else {
            
                for( var i = 0; i < steps; i++ ) {
                    
                    var value = parseInt( $priceFromSelect.val(), 10 ) + ( ( 1 + i ) * 5000 );
                    
                    html += '<option value="' + value + '">à ' + value.commafy() + '.-</option>';
                }
            }
            
            $priceToSelect.html( html );
            
            if( !selectedPrice ) {
                
                $priceToSelect.children( ':last-child' ).attr( 'selected', 'selected' );
            
            } else {
            
                $priceToSelect.val( selectedPrice );
            }
            
            window.SelectSkin.setText( 'text-price-to', $priceToSelect[ 0 ] );
        }
        
        function filterListByMake( make )
        {
            // selectedMake = make;
            
            if( !make ) {
                
                $table.find( 'TR' ).removeClass( 'hidden' ).addClass( 'visible' );
                
                window.location.hash = '';
                
                return;
            }
            
            var $makes = $table.find( selectors.makeModel.make );
            
            for( var i = 0; i < $makes.length; i++ ) {
                
                var $el = $( $makes[ i ] );
                
                if( $el.text() !== make ) {
                    
                    $el.closest( 'TR' ).removeClass( 'visible' ).addClass( 'hidden' );
                
                } else {
                
                    $el.closest( 'TR' ).removeClass( 'hidden' ).addClass( 'visible' );
                }
            }
            
            window.location.hash = '#' + make.toLowerCase();
        }
        
        function filterListByModel( model )
        {
            if( !model ) {
                
                return filterListByMake( selectedMake );
            }
            
            var $models = $table.find( 'TR:visible ' + selectors.makeModel.model );
            
            for( var i = 0; i < $models.length; i++ ) {
                
                var $el = $( $models[ i ] );
                
                if( $el.text() !== model ) {
                    
                    $el.closest( 'TR' ).removeClass( 'visible' ).addClass( 'hidden' );
                
                } else {
                
                    $el.closest( 'TR' ).removeClass( 'hidden' ).addClass( 'visible' );
                }
            }
            
            return undefined;
        }
        
        function filterListByPriceFrom( priceFrom )
        {
            if( !priceFrom ) {
                
                return;
            }
            
            var $prices = $table.find( 'TR:visible ' + selectors.td.price );
            
            for( var i = 0; i < $prices.length; i++ ) {
                
                var $el = $( $prices[ i ] );
                
                if( parseFloat( $el.text().replace( '\'', '' ) ) < priceFrom ) {
                    
                    $el.closest( 'TR' ).removeClass( 'visible' ).addClass( 'hidden' );
                
                } else {
                
                    $el.closest( 'TR' ).removeClass( 'hidden' ).addClass( 'visible' );
                }
            }
        }
        
        function filterListByPriceTo( priceTo )
        {
            if( !priceTo ) {
                
                return;
            }
            
            var $prices = $table.find( 'TR:visible ' + selectors.td.price );
            
            for( var i = 0; i < $prices.length; i++ ) {
                
                var $el = $( $prices[ i ] );
                
                if( parseFloat( $el.text().replace( '\'', '' ) ) > priceTo ) {
                    
                    $el.closest( 'TR' ).removeClass( 'visible' ).addClass( 'hidden' );
                
                } else {
                
                    $el.closest( 'TR' ).removeClass( 'hidden' ).addClass( 'visible' );
                }
            }
        }
        
        function getMinMaxPrice( roundToClosest )
        {
            var $prices = $table.find( 'TR:visible ' + selectors.td.price ),
                prices  = [];
            
            for( var i = 0; i < $prices.length; i++ ) {
                
                var price = parseFloat( $( $prices[ i ] ).text().replace( '\'', '' ) ),
                    round = parseInt( price / roundToClosest, 10 ) * roundToClosest;
                
                round = ( price > round ) ? ( round + roundToClosest ) : round;
                
                prices.push( round );
            }
            
            return {
                max : Math.max.apply( Math, prices ),
                min : Math.min.apply( Math, prices )
            };
        }
        
        function reOddEvenRows()
        {
            $rows = $table.find( 'TR.visible' );
            
            for( var i = 0; i < $rows.length; i++ ) {
                
                var $el = $( $rows[ i ] ).removeClass( 'odd' ).addClass( 'even' );
                
                if( i % 2 ) {
                    
                    $el.addClass( 'even' );
                
                } else {
                
                    $el.addClass( 'odd' );
                }
            }
        }
        
    }
    
    function ready()
    {
        bindSellFormChecks();
        
        if( $( '.tx-atra-pi1-singleView' ).length )
        {
            single();
        }
        else
        {
            bindSellFormChecks();
            list();
            checkUrl();
        }
    }
    
    $( ready );
    
    function checkUrl()
    {
        var hash        = window.location.hash + '',
            $makeSelect = $( selectors.selects.make );
            
        hash     = hash.substr( 1 ).toUpperCase();
        
        if( hash && window.AlchemyTracking )
        {
            AlchemyTracking.registerLanding();
        }
        
        $makeSelect.val( hash );
        $makeSelect.change();
    }
    
    function bindSellFormChecks()
    {
        var $sellInputs = $( '#tx-atra-pi1-sell input[type="text"]' ),
            $sellForm   = $( '#tx-atra-pi1-sell form' );
        
        $sellInputs.placeHoldize( true, false );
        
        $sellForm.submit(
            function( event )
            {
                if( $sellForm.find( '.placeholder-visible' ).length )
                {
                    event.preventDefault();
                    
                    $sellForm.find( '.fields-notice' ).remove();
                    
                    $sellForm.find( 'fieldset' ).prepend(
                      '<span class="fields-notice" style="color: red; font-weight: bold"><br />'
                      + 'Veuillez remplir tous les champs.'
                      + '</span>'
                    );
                    
                    return false;
                }
            }
        );
        
        $( '#tx-atra-pi3-sell-firstname' ).keyup( function()
        {
            $( '#tx-atra-pi3-sell-firstname-ph' ).html( $( this ).val() );
        } );
        
        $( '#tx-atra-pi3-sell-lastname' ).keyup( function()
        {
            $( '#tx-atra-pi3-sell-lastname-ph' ).html( $( this ).val() );
        } );
    }
    
    String.prototype.commafy = function()
    {
        return this.replace(
            /(^|[^\w.])(\d{4,})/g,
            function( $0, $1, $2 )
            {
                return $1 + $2.replace( /\d(?=(?:\d\d\d)+(?!\d))/g, "$&'" );
            }
        );
    };
    
    Number.prototype.commafy = function () {
    	return String(this).commafy();
    };
    
    var array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if (haystack.hasOwnProperty) {
                if ((haystack[fkey] + '') === (needle + '')) {
                    return fkey;
                }
            }
        }
        return false;
    };
    
    function array_unique( inputArr )
    {
        // Removes duplicate values from array  
        // 
        // version: 1002.420
        // discuss at: http://phpjs.org/functions/array_unique
        // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
        // +      input by: duncan
        // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   bugfixed by: Nate
        // +      input by: Brett Zamir (http://brett-zamir.me)
        // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   improved by: Michael Grier
        // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
        // %          note 1: The second argument, sort_flags is not implemented;
        // %          note 1: also should be sorted (asort?) first according to docs
        // *     example 1: array_unique(['Kevin','Kevin','van','Zonneveld','Kevin']);
        // *     returns 1: {0: 'Kevin', 2: 'van', 3: 'Zonneveld'}
        // *     example 2: array_unique({'a': 'green', 0: 'red', 'b': 'green', 1: 'blue', 2: 'red'});
        // *     returns 2: {a: 'green', 0: 'red', 1: 'blue'}
        var key = '', tmp_arr2 = {}, val = '';
        
        for (key in inputArr) {
            if (inputArr.hasOwnProperty) {
                val = inputArr[key];
                if (false === array_search(val, tmp_arr2)) {
                    tmp_arr2[key] = val;
                }
            }
        }
        
        return tmp_arr2;
    }
    
    function filter( $elements, property )
    {
        var results = [];
        
        for( var i = 0; i < $elements.length; i++ ) {
            
            var $el = $( $elements[ i ] );
            
            if( $.isFunction( $el[ property ] ) ) {
                
                results.push( $el[ property ]() );
                
            } else {
            
                results.push( $el[ property ] );
            }
        }
        
        return results;
    }
    
} )( jQuery );

// ]]>
