jQuery(document).ready(function($){
 
  var str_url = '/scripts/search.ashx';
  var cbo_type = $('#search-type');
  var cbo_brand = $('#search-brand');
  
  $('#search form').submit(function(){
    var opt_type = cbo_type.find('option:gt(0):selected');
    if(opt_type.length==0){alert('Please select a product type to search'); return false; }
    
    var url = '/' + opt_type.attr('title') + '/products.aspx'
    var query = [];
    if(opt_type.attr('lang')=='1') query[query.length] = 'subtype=' + opt_type.attr('value');
    var brand = cbo_brand.find('option:selected').val();
    if(brand && brand!='0') query[query.length] = 'brand=' + brand;
    
    if(query.length > 0) url += '?' + query.join('&');
    
    document.location=url;
    
    return false;
  });
  
  $.getJSON(str_url,function(data){
    if(data && data.length > 0){
      $.each(data,function(){
        var type = this;
        cbo_type.append('\n<option value="'+type.id+'" title="'+type.name+'">'+type.text+'</option>');
        if(type.children && type.children.length > 0){
          $.each(type.children,function(subtype){
            var subtype = this;
            cbo_type.append('\n<option value="'+subtype.id+'" lang="1" title="'+type.name+'">....'+subtype.text+'</option>');
          });
        }
      });
    }
  });
  
  cbo_type.change(function(){
    cbo_brand.find('option:gt(0)').remove();  
    cbo_brand.get(0).selectedIndex = 0;
    $.getJSON(str_url+'?type='+cbo_type.val(),function(data){
      if(data && data.length > 0){
        $.each(data,function(){
          cbo_brand.append('\n<option value="'+this.id+'">'+this.text+'</option>');
        });
      }
    });
  });
  if(cbo_type.get(0).selectedIndex>0) cbo_type.change();
  
});