if (typeof (console) == 'undefined') var console = { log: function () { } }


if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; }

(function($) {

    function dropdownV2(options) {
        var self = this;
        this.settings = {
            'postback':false,
            'selected':[],
            'input':''
        }

        this.Inventory = {}

        this.replaceAll = function(txt, replace, with_this) {
            return txt.replace(new RegExp(replace, 'g'),with_this);
        }

        this.HideOption = function(option){ 
            option.wrap('<span style="display:none;" />');
        }

        this.ShowOption = function(target){ 
             target.unwrap();                                                     
        }

        this.HideAllOptions = function(select){
            $("option",select).wrap('<span style="display:none;" />');            
        }
        
        this.ShowAllOptions = function(select){
            $('span option',select).unwrap();            
        }

        this.Submit = function(){
            var value = $("#dd-make").find("option:selected").val()+","+$("#dd-model").find("option:selected").val()+","+$("#dd-year").find("option:selected").val()+","+$("#dd-type").find("option:selected").val()+","+$("#dd-price").find("option:selected").val()+","+$("#txtKeyword").val();

            $("#"+self.settings.input).val(value);

            if(self.settings.postback!="") __doPostBack(self.settings.postback, '');
            else{
                location.href = self.settings.url + $("#dd-make").find("option:selected").val() + "-" + $("#dd-model").find("option:selected").val() + "-" + $("#dd-year").find("option:selected").val() + "-p0.aspx";//?price=" + $("#dd-price").val() + "&type=" + $("#dd-type").val();
            }
            return false;
        }

        this.onChange = function(target,forced){
            console.log(target);
            
            if(typeof($(target).attr('child'))!='undefined' && (self.settings.postback=='' || (forced && self.settings.postback!=''))){
                self.ShowAllOptions($('#'+$(target).attr('child')));
                        
                if($(target).val()!=""){
                    self.HideOption($('option[parent!="'+$(target).val()+'"][parent!=""]','#'+$(target).attr('child')));
                }
            }

            if(typeof($(target).attr('parent'))!='undefined' && (self.settings.postback=='' || (forced && self.settings.postback!=''))){
                //$('option',$('#'+$(this).attr('child'))).show();

                //if($(this).val()!="") $('option[parent!="'+$(this).val()+'"][parent!=""]',$('#'+$(this).attr('child'))).hide();

                //$('#'+$(this).attr('child')+' option:first-child').attr("selected", "selected");
            }

            if(typeof($('option:selected',target).attr('years'))!='undefined' && (self.settings.showcontrols == '' || self.settings.showcontrols.indexOf('year')>=0) && (self.settings.postback=='' || (forced && self.settings.postback!=''))){
                self.ShowAllOptions($('#dd-year'));
                self.HideAllOptions($('#dd-year'));
                        
                var years = $('option:selected',target).attr('years').split( "," );

                if(years.length==1 && years[0]=='') years = $('option:selected',$('#dd-make')).attr('years').split( "," );

                //console.log(years);

                self.ShowOption($('option[value=""]','#dd-year'));

                $.each(years,function(y,year){
                    if(!isNaN(year) && year > 0) self.ShowOption($('option[value="'+year+'"]','#dd-year'));                            
                });

                $('#dd-year').val("");
                
            }

            
            if(typeof($('option:selected',target).attr('types'))!='undefined' && (self.settings.showcontrols == '' || self.settings.showcontrols.indexOf('type')>=0) && (self.settings.postback=='' || (forced && self.settings.postback!=''))){
                self.ShowAllOptions($('#dd-type'));
                self.HideAllOptions($('#dd-type'));
                
                var types = $('option:selected',target).attr('types').split( "," );

                
                if(types.length==1 && types[0]=='') types = $('option:selected',$('#dd-make')).attr('types').split(",");

                self.ShowOption($('option[value="0"]','#dd-type'));
                                
                $.each(types,function(y,type){
                    if(!isNaN(type) && type > 0) self.ShowOption($('option[value="'+type+'"]','#dd-type'));                    
                });

                $('#dd-type').val("");                
                
            }

            
        }

        this.CreateHtml = function() {
            self.empty = {
                'make':{'key':$('li:first-child','#ul-make').attr('key'),'label':($('li:first-child a','#ul-make').length?$('li:first-child a','#ul-make').text():$('li:first-child','#ul-make').text())},
                'model':{'key':$('li:first-child','#ul-model').attr('key'),'label':($('li:first-child a','#ul-model').length?$('li:first-child a','#ul-model').text():$('li:first-child','#ul-model').text())},
                'year':{'key':$('li:first-child','#ul-year').attr('key'),'label':($('li:first-child a','#ul-year').length?$('li:first-child a','#ul-year').text():$('li:first-child','#ul-year').text())}
            }

            self.Inventory[self.empty.make.key]={
                'key':self.empty.make.key,
                'label':self.empty.make.label,
                'childs':[{
                    'key':self.empty.model.key,
                    'label':self.empty.model.label,
                    'years':Array(),
                    'types':Array()
                }],
                'years':Array(),
                'types':Array()
            }
            
            
            $(self.settings.data).each(function(i,c){
                var key_make = self.replaceAll(self.replaceAll(self.replaceAll(c[0],"&","_")," ","_"),"-","__");
                var key_model = self.replaceAll(self.replaceAll(self.replaceAll(c[1],"&","_")," ","_"),"-","__");

                if(typeof(self.Inventory[key_make])=='undefined'){
                    self.Inventory[key_make] = {
                        'key':key_make,
                        'label':c[0],
                        'childs':[],
                        'years':Array(),
                        'types':Array()
                    }
                }

                if(typeof(self.Inventory[key_make]['childs'][key_model])=='undefined'){
                    self.Inventory[key_make]['childs'][key_model] = {
                        'key':key_model,
                        'label':c[1],
                        'years':Array(),
                        'types':Array()
                    }
                }

                if(self.Inventory[self.empty.make.key]['types'].indexOf(c[3])<0){
                    self.Inventory[self.empty.make.key]['types'].push(c[3]);
                    self.Inventory[self.empty.make.key]['types'].sort();
                }

                if(self.Inventory[self.empty.make.key]['years'].indexOf(c[2])<0){
                    self.Inventory[self.empty.make.key]['years'].push(c[2]);
                    self.Inventory[self.empty.make.key]['years'].sort();
                }

                if(self.Inventory[key_make]['years'].indexOf(c[2])<0){
                    self.Inventory[key_make]['years'].push(c[2]);
                    self.Inventory[key_make]['years'].sort();
                }

                if(self.Inventory[key_make]['types'].indexOf(c[3])<0){
                    self.Inventory[key_make]['types'].push(c[3]);
                    self.Inventory[key_make]['types'].sort();
                }

                if(self.Inventory[key_make]['childs'][key_model]['years'].indexOf(c[2])<0){
                    self.Inventory[key_make]['childs'][key_model]['years'].push(c[2]);
                    self.Inventory[key_make]['childs'][key_model]['years'].sort();
                }

                if(self.Inventory[key_make]['childs'][key_model]['types'].indexOf(c[3])<0){
                    self.Inventory[key_make]['childs'][key_model]['types'].push(c[3]);
                    self.Inventory[key_make]['childs'][key_model]['types'].sort();
                }

            });

            $('ul',self.settings.selector).each(function(){
                var select = $('<select></select>').attr({
                    'id':'dd-'+$(this).attr('dd'),
                    'dd':$(this).attr('dd'),
                    'parent':typeof($(this).attr('parent'))!='undefined'?$(this).attr('parent'):null,
                    'child':typeof($(this).attr('child'))!='undefined'?$(this).attr('child'):null
                }).addClass($(this).attr('dd'));

                switch($(this).attr('dd')){
                    case 'make':
                        $.each(self.Inventory,function(i,make){
                            var option = $('<option></option>');

                            option.text(make.label);

                            option.attr({
                                'label':make.label,
                                'value':make.key,
                                'years':make.years,
                                'types':make.types,
                                'count':0
                            });

                            select.append(option);
                        });
                    break;

                    case 'model':
                        for(make in self.Inventory){
                            for(model in self.Inventory[make].childs){
                                var option = $('<option></option>');
                                
                                option.text(self.Inventory[make].childs[model].label);

                                option.attr({
                                    'parent':self.Inventory[make].key,
                                    'label':self.Inventory[make].childs[model].label,
                                    'value':self.Inventory[make].childs[model].key,
                                    'years':self.Inventory[make].childs[model].years,
                                    'types':self.Inventory[make].childs[model].types,
                                    'count':0
                                });

                                select.append(option);
                            }
                        }
                    break;

                    case 'year':
                        select.append($('<option value="'+self.empty.year.key+'">'+self.empty.year.label+'</option>'));


                        for(year in self.Inventory[self.empty.make.key].years){
                            var option = $('<option></option>');

                            option.text(self.Inventory[self.empty.make.key].years[year]);

                            option.attr({
                                'value':self.Inventory[self.empty.make.key].years[year],
                                'count':0
                            });

                            select.append(option);
                        }
                    break;

                    default:

                        /*
                        for(type in self.Inventory[self.empty.make.key].types){
                            var option = $('<option></option>');

                            option.text(self.settings.types[type]);

                            option.attr({
                                //'parent':Inventory[make].key,
                                //'label':Inventory[make].childs[model].label,
                                'value':self.Inventory[self.empty.make.key].types[type],
                                //'years':Inventory[make].childs[model].years,
                                //'types':Inventory[make].childs[model].types,
                                'count':0
                            });

                            select.append(option);
                        }
                        */

                       $('li','#ul-'+$(this).attr('dd')).each(function(){
                            var option = $('<option></option>');

                            if($('a',this).length) option.text($('a',this).text());
                            else option.text($(this).text());

                            option.attr({
                                'url':$('a',this).attr('href'),
                                'label':$(this).attr('label'),
                                'parent':$(this).attr('parent'),
                                'child':$(this).attr('child'),
                                'value':$(this).attr('key'),
                                'count':$(this).attr('count')
                            });

                            select.append(option);
                        });
                    break;
                }

                /*
                if($('li',this).length){
                    $('li',this).each(function(){
                        var option = $('<option></option>');

                        if($('a',this).length) option.text($('a',this).text());
                        else option.text($(this).text());

                        option.attr({
                            'url':$('a',this).attr('href'),
                            'label':$(this).attr('label'),
                            'parent':$(this).attr('parent'),
                            'child':$(this).attr('child'),
                            'value':$(this).attr('key'),
                            'count':$(this).attr('count')
                        });

                        select.append(option);
                    });
                }else{
                    
                }
                */

                select.change(function(){
                    if(self.settings.postback!='') self.Submit();                    
                    else self.onChange(this,false);
                });

                $(this).after(select);
                $(this).hide();
            });

            if(self.settings.selected[0]!=""){
                $("#dd-make").val(self.settings.selected[0]);
                self.onChange("#dd-make",true);
            }

            if(self.settings.selected[1]!=""){
                $("#dd-model").val(self.settings.selected[1]);
                self.onChange("#dd-model",true);
            }
            
            if(self.settings.selected[2]!=""){
                $("#dd-year").val(self.settings.selected[2]);
                self.onChange("#dd-year",true);
            }
                    
            $("#dd-type").val(self.settings.selected[3]);
            $("#dd-price").val(self.settings.selected[4]);
            $("#txtKeyword").val(self.settings.selected[5]);
            
            //alert(self.settings.selected);

            if(self.settings.showcontrols!=""){
                $("select,input",self.settings.selector).hide();
                
                var controls = self.settings.showcontrols.split(',');
                
                for(i in controls){
                    if(typeof(controls[i])=='string') $("."+controls[i],self.settings.selector).show();
                }
            }
            
        }

        this.CreateBindings = function(){            
        
            $("a.submit",self.settings.selector).click(function(){
                self.Submit();
                return false;
            });

            //console.log(self.Inventory);
        }

        this.Init = function(){
            self.CreateHtml();
            self.CreateBindings();
        }

        if (options) $.extend(true, self.settings, options);

        self.Init();

    }

    var methods = {
        init: function(options) {
            options.selector = $(this).selector;

            return this.each(function() {

                var $this = $(this),
                data = $this.data('dropdownV2'),
                menu = $('<div />', {
                    text: $this.attr('title')
                });

                //debugger;

                //$(window).bind('resize.tooltip', methods.reposition);

                //if ( options ) $.extend( settings, options );

                var DropdownObj = new dropdownV2(options);

                // If the plugin hasn't been initialized yet
                if (!data) {}

                $(this).data('dropdownV2', DropdownObj);
            });
        },
        destroy: function() {
            return this.each(function() {

                var $this = $(this),
                data = $this.data('dropdownV2');

                $(window).unbind('.dropdownV2');

                data.menu.remove();

                $this.removeData('dropdownV2');
            });
        }
    }

    $.fn.dropdownV2 = function(method) {

        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.menuV2');
        }

    };
})(jQuery);
