/*
 * homeSearch.js
 *
 * HomeSearch functionality exists here... This function builds processes the jSon from homeSearch.php
 *
 * @author Chris Warner
 * @date
 */

(function($){
 
    $.extend($.expr[':'],{
 
        data: function(a,i,m) {
 
            var e = $(a).get(0), keyVal;
            if(!m[3]) {
                for (var x in e) { if((/jQuery\d+/).test(x)) { return true; } }
 
            } else {
                keyVal = m[3].split('=');
                if (keyVal[1]) {
 
                    if((/^\/.+\/([mig]+)?$/).test(keyVal[1])) {
                        return
                         (new RegExp(
                             keyVal[1].substr(1,keyVal[1].lastIndexOf('/')-1),
                             keyVal[1].substr(keyVal[1].lastIndexOf('/')+1))
                          ).test($(a).data(keyVal[0]));
                    } else {
                        return $(a).data(keyVal[0]) == keyVal[1];
                    }
 
                } else {
 
                    if($(a).data(keyVal[0])) {
                        return true;
                    } else {
                        $(a).removeData(keyVal[0]);
                        return false;
                    }
                }
            }
 
            return false;
 
        }
 
    });
})(jQuery);

function HomeSearchJson(aDealerId, aTypeId){
    var theDealerID = 0;
    // if we get aTypeId use it else default to new.
    var theTypeId = (aTypeId != null) ? aTypeId : 1;
    var theJSONUrl = "common/ajax/homeSearch/homeSearch.php";
    var doAutoSelect = true;
    theDealerID = aDealerId;

    //We set the data that will condition data, and dealerID on the condition class.
    $('#condition').data('dealerId', theDealerID);
    $('#condition').data('typeId', theTypeId);

    // We are defining this.FetchData so it can only be defined on time.
    if(typeof(_Home_Search_Json_prototype_called)== 'undefined'){
        _Home_Search_Json_prototype_called = true;
        HomeSearchJson.prototype.FetchData = $.FetchData;
    }


    // Configuring the ajax values we will use.
    // url: what the URL is
    // type: POST
    // Success: callback that loads data into the boxes.
    // Complete: callback that handles display related issues.
    // dataType: json
    jQuery.ajaxSetup({
        url: theJSONUrl,
        type: 'POST',
        success: function (theResultsData) {
            
            $.DataLoad(theResultsData);

        },
        complete: function () {
            $.constructURL();
            $('.results .title').each(function(){
                if( $(this).data('value') || $(this).data('valueLow') || $(this).data('valueHigh') ){
                    $(this).find('.check').show();
                }
                else{
                    $(this).find('.check').hide();
                }
            });

            $('#makes p:odd, #models p:odd').addClass('oddRow');
            if(doAutoSelect == true){
            	$.singleMakeCheck();
            }
        },
        dataType:"json"
    });
    
    //per ticket #7600, if there's only 1 make retured for new vehicles, default to clicking it
    $.singleMakeCheck=function(){
    	if($('#condition').data('desc') == 'new'){
    		if($('#makes.output p').length == 1){
    	        $('#make').data('value', $('#makes.output p:first a').attr('value'));
    	        $('#make').data('desc', $('#makes.output p:first a').attr('desc'));
    	        $('#model, #year, #miles').removeData('value');

    	        $('#model, #year').data('allowed', 'true');
    	        $('#makes a').removeClass('selected');
    	        $('#makes.output p:first a').addClass('selected');
    	        $('#model, #year, #miles').css('opacity', 1.0);
    	        $('#year').show();
    	        $('#make div.check').show();
    	        $('#model div.check, #year div.check, #miles div.check').hide();
    	        $('#models').show();
    	        
    	        $('#model').click();

    		}
    	}
    	doAutoSelect = false;
    }
    
    // This is the success callback for ajax.  It's job is to populate hte control with the
    // JSON values form the server side script.
    $.DataLoad = function (aJson) {

        // we move the parameter to a local variable.
        var theData = aJson;
        
        // The Data is in contained in an array that we iterate over.
        // Years and mileage needs additional work.
        $.each(theData.data, function(key, value) {
            // we construct the Output of the elements into this array.
            var theOutput = [];
            var theKey = key;
            var theValue = value;
            // Construct an output array.
            $.each(theValue, function(key, value){
                var i = 0;
                switch(theKey) {
                    case 'years':
                        theOutput.push('<option value="' + key + '">' + value.description + '</option>');
                        break;
                    case 'mileage':
                        break;
                    default:
                        theOutput.push('<p><a href="#" value="' + key + '" desc="'+ value.description +'">'+
                            value.description + "</a></p>");
                }
                i++;
            });

            if($('#' + theKey).prev().data('value') == null) {

                // Load the contents into the controls.
                switch(theKey){
                    case 'years':
                        $('#years [name=$Year]').empty();

                        theOutput.sort();
                        theOutput.splice(0,0,'<option value="">Low Year</option>');

                        $('#years [name=minYear]').html(theOutput.join(''));

                        theOutput.reverse();
                        theOutput.pop();
                        theOutput.splice(0,0,'<option value="">High Year</option>');

                        $('#years [name=maxYear]').html(theOutput.join(''));
                        
                        break;
                    case 'mileage':
                        break;
                    default:
                        $("#" + theKey).empty();
                        $('#' + theKey).html(theOutput.join(''));
                        break;
                }
            } 
        });

    }

 
    // This sets the listing URL that is built from the
    // Selected values the user has submitted.
    $.constructURL=function() {
        // get the values we need to assemble the listing URL.
        var theCondition = $('#condition').data('desc');
        var theMake = $('#make').data('desc');
        var theModel = $('#model').data('desc');
        var theTrim = $('#time').data('desc');
        var theBody = $('#body').data('value');
        var theMinYear = ($('#year').data('minYear') != null)?$('#year').data('minYear'):null;
        var theMaxYear = ($('#year').data('maxYear') != null)?$('#year').data('maxYear'):null;
        var theMaxMileage = $('#miles').data('maxMileage');
        var theMaxPrice = null;
        var theMinPrice = null;
        if($('#condition .output').has('#prices').size() > 0){
            theMinPrice = ('#prices select [name|=minPrice]').val();
            theMaxPrice = ('#prices select [name|=maxPrice]').val();
        }
        var theStock = $('stock').data('value');

        // Preset the URL blocks
        var theMakeURL = '/xxxx';
        var theModelURL = '/xxxx';
        //        var theTrimURL = '/xxxx';
        var theTrimURL = ''; // When we implement Trim search unremark above.
        var theBodyURL = '';
        var theYearURL = '/xxxx';
        var theMaxPriceURL = '';
        var theMinPriceURL = '';
        var theMaxMileageURL = '';
        var theStockURL = '';

        // Preset the Listing URL with the condition and starting page.
        var theListingURL = 'inventory/listing/' + theCondition + '/1';

        // We establish the values in the URL before QueryString First.
        if(theMake != null){
            theMakeURL =  '/' + theMake;
        }

        if(theModel != null){
            theModelURL = '/' + theModel;
        }

        if(theTrim != null){
            theTrimURL = '/' + theTrim;
        }

        if((theMinYear != null) || (theMaxYear != null) ){
            theYearURL = '/' + 
            ( (theMinYear != null)?theMinYear:'' ) + '-' +
            ( (theMaxYear != null)?theMaxYear:'' );
        }

        // We establish the Query String next
        if(theBody != null){
            theBodyURL = '&body_style_id=' + theBody;
        }

        if(theStock != null){
            theStockURL = '&tock=' + theStock;
        }

        if(theMinPrice != null){
            theMinPriceURL = '&min_price=' + theMinPrice;
        }

        if(theMaxPrice != null){
            theMaxPriceURL = '&max_price=' + theMaxPrice;
        }

        if(theMaxMileage != null){
            theMaxMileageURL = '&max_mileage=' + theMaxMileage;
        }

        // construct the URL with the pieces above, default values will be in the varaibles that don't have
        // properties set.
        var theURL = theListingURL + theYearURL + theMakeURL + theModelURL + theTrimURL + theBodyURL 
        + theStockURL + theMinPriceURL + theMaxPriceURL + theMaxMileageURL;

        var regularExpress = /\s+/g;
        var fixedURL = theURL.replace(regularExpress, '+');
        
        // set the URL on the SEARCH list box.
        $('#newSearch').attr('href', fixedURL);

    }

    // This is the function we use to start the data fetch process.
    $.FetchData= function() {
        // This is the search criteria, default to null if not set.
        var theDealerId = $('#condition').data('dealerId');
        var theCondition = ( $('#condition').data('typeId') != null ) ? $('#condition').data('typeId') : 1;
        var theMake = $('#make').data('value');
        var theModel = $('#model').data('value');
        var theBody = $('#body').data('value');

        // since we do a form post, we define a Java script array that contains the data we have.
        var theFormData;
        theFormData = {
            dId: theDealerId,
            typeId: theCondition
        }

        if(theMake != null){
            theFormData.makeId = theMake;
        }

        if(theModel != null){
            theFormData.modelId = theModel;
        }

        if(theBody != null){
            theFormData.bodyId = theBody;
        }
        
        // We now send the data to teh server.  The configurated call backs handle the processing.
        $.ajax({
            data: theFormData
        });

    }

    $('#makes a').live('click', function() {
        $('#make').data('value', $(this).attr('value'));
        $('#make').data('desc', $(this).attr('desc'));
        $('#model, #year, #miles').removeData('value');
        if($('#condition').data('typeId') !=1 ) {
            $('#miles').data('allowed', 'true');
        }
        $('#model, #year').data('allowed', 'true');
        $('#makes a').removeClass('selected');
        $(this).addClass('selected');
        $('#model, #year, #miles').css('opacity', 1.0);
        $('#year').show();
        $('#make div.check').show();
        $('#model div.check, #year div.check, #miles div.check').hide();
        $('#models').show();

        $('#model').click();
        $.FetchData();

        return false;
    });

    $('#models a').live('click', function() {
        $('#model').data('value', $(this).attr('value'));
        $('#model').data('desc', $(this).attr('desc'));
        $('#year, #miles').removeData('value');
        if($('#condition').data('typeId') != 1){
            $('#miles').data('allowed', 'true');
            $('#miles').css('opacity', 1.0);
        }
        $('#models a').removeClass('selected');
        $(this).addClass('selected');
        $('#model div.check').show();
        $('#year div.check, #miles div.check').hide();

        $('#year').click();
        $.FetchData();

        return false;
    });

    $('#years [name$="Year"]').bind('change', function() {
        $('#year').data($(this).attr('name'), $(this).attr('value'));
        $('#year div.check').show();
        
        if($('#condition').data('typeId') != 1){
            $('#miles').data('allowed', 'true');
            $('#miles').css('opacity', 1.0);
        }

        $('#miles').data('allowed', 'true');
            
        $.constructURL();
        return false;
    });

    $('#mileage select[name=maxMileage]').bind('change', function() {
        $('#miles').data('maxMileage', $(this).attr('value'));
        $('#miles div.check').show();
        
        $.constructURL();
        return false;
    })

    $('.new .results [class ^=title]:data(allowed=true)').live('click', function () {
        $('.new .output').slideUp(600);
        $(this).next().slideDown(600);
        $('.new .results [class ^=title]').addClass('title_inactive');
        $('.new .results [class ^=title]').removeClass('title_active');
        $(this).addClass('title_active');
        $(this).removeClass('title_inactive');

        return false;
    });

    $('#condition a.newVehicle').live('click', function() {
        $('#condition').data('typeId', 1);
        $('#condition').data('desc', 'new');
        $('#condition #preOwnedVehicle').hide();
        $('#condition #newVehicle').show();
        $('#make, #model, #year, #miles').removeData('value');
        $('#make, #model, #year, #miles').removeData('desc');
        $('#year').removeData('minYear');
        $('#year').removeData('maxYear');
        $('#miles').removeData('maxMileage');
        $('.check').hide();
        $('#model, #year, #miles').css('opacity', .5);
        $('#make').data('allowed', 'true');
        $('#year, #miles, #model').data('allowed', 'false');
        $('a#viewall').attr('href', 'inventory/listing/new');
        
        $('#year, #miles').hide();
        
        $('#make').click();
        doAutoSelect = true;
        $.FetchData();

        return false;
    });

    $('#condition a.preOwnedVehicle').live('click', function () {
        $('#make, #model, #year, #miles').removeData('value');
        $('#make, #model, #year, #miles').removeData('desc');
        $('#year').removeData('minYear');
        $('#year').removeData('maxYear');
        $('#miles').removeData('maxMileage');
        $('#condition').data('typeId', 2);
        $('#condition').data('desc', 'pre-owned');
        $('#condition #newVehicle').hide();
        $('#condition #preOwnedVehicle').show();

        $('.check').hide();

        $('#model').css('opacity',.5);
        $('#year, #miles').css('opacity', 1.0);
        $('#make, #year, #miles').data('allowed', 'true');
        $('#year, #miles').show();

        $('a#viewall').attr('href', 'inventory/listing/pre-owned');

        $('#make').click();
        doAutoSelect = true;
        $.FetchData();

        return false;
    });

    $('#clearSearch').live('click', function() {
        $('#make, #model, #year, #miles').removeData('value');
        $('#make, #model').removeData('desc');
        $('#year').removeData('minYear');
        $('#year').removeData('maxYear');
        $('#miles').removeData('maxMileage');
        $('[name=maxMileage]').attr('value', '');
        $('.check').hide();
        $('#model').css('opacity',.5);
        if($('#condition').data('typeId') == 1){
            $('#model').css('opacity',.5);
            $('#make').data('allowed', 'true');
            $('#year, #miles, #model').data('allowed', 'false');

            $('#year, #miles').hide();

 
        } else {
            $('#make, #year, #miles').data('allowed', 'true');
            $('#year, #miles').show();
        }

        $('#make').click();

        $.FetchData();

        return false;

    });


    $('#model, #year, #miles').css('opacity',.5);
    $('#make').data('allowed', 'true');
    $('#year, #miles, #model').data('allowed', 'false');

    if($('#condition').data('typeId') == 1){
        $('#condition').data('desc', 'new');
        $('#year, #miles').hide();
    }
    
    // This is how we start the Query Process.
    $.FetchData();
}

