/* based on the jNice jQuery plugin by Sean Mooney */
$j(document).ready(function() {
  
  $j('select#ojoo-browser-sort', this).each(function(index) {
    var $select = $j(this);
    $j(this).wrap('<div class="styled-dropdown"></div>');
  
    var $wrapper = $j(this).parent().css({zIndex: 100-index});

    $wrapper.prepend('<div><span></span></div><ul></ul>');
    var $ul = $j('ul', $wrapper);
    
    $j('option', this).each(function(i) {
      $ul.append('<li><a href="#" index="'+ i +'">'+ this.text +'</a></li>');
    });

    $ul.hide().find('a').click(function() {
      $j('a.selected', $wrapper).removeClass('selected');
      $j(this).addClass('selected');	

      if ($select[0].selectedIndex != $j(this).attr('index') && $select[0].onchange) { 
        $select[0].selectedIndex = $j(this).attr('index'); 
        $select[0].onchange(); 
      }
      
      $select[0].selectedIndex = $j(this).attr('index');
      
      $j('span:eq(0)', $wrapper).html($j(this).html());
      
      $ul.hide();
      
      return false;
    });
    
    $j('a:eq('+ this.selectedIndex +')', $ul).click();
  });

  // CRG: Horrid hack, but IE7 and Chrome do not care for dynamic img URL loading
  //  - Reading CSS and loading dynamically does NOT work well IN IE7
  var img = new Image;
  img.src = '/modules/contrib/samatason/styled_dropdowns/images/select-button-off.gif';
  img.src = '/modules/contrib/samatason/styled_dropdowns/images/select-button-on.gif';

  $j('.styled-dropdown span').mouseover(function() {
    showSelect();
    return false;
  });

  var showSelect = function() {
    var $ul = $j('.styled-dropdown span').parent().siblings('ul');
    
    if ($ul.css('display') == 'block') {
      return false;
    }
    
    if ($ul.css('display') == 'none') {
      hideSelect(); 
    } 
    
    $ul.show();
    //apanag
    //$j('.styled-dropdown div span').addClass('over');
    $j('.styled-dropdown span').addClass('over');
    var offSet = ($j('a.selected', $ul).offset().top - $ul.offset().top);
    $ul.animate({ scrollTop: offSet });
  }
  
  var hideSelect = function() {
		$j('.styled-dropdown ul:visible').hide();
		$j('.styled-dropdown div span').removeClass('over');
	};
	
	var checkExternalClick = function(event) {
		if ($j(event.target).parents('.styled-dropdown').length === 0) {
		  hideSelect();
		}
	};

	$j(document).mouseover(checkExternalClick);

});
