var resizeElements;

$(document).ready(function(){

var bar = ".search_bar.advanced";
var input = bar + " input[type='text']";
var button = bar + " button[type='submit']";

var tray = bar + " .search_tray";
var traySections = tray + " > div";

var dropdown = bar + " .search_dropdown";
var dropdownLabel = dropdown + " > span";
var dropdownList = dropdown + " ul";
var dropdownListItems = dropdownList + " li";

resizeElements = function(){
var barWidth = $(bar).outerWidth();

var labelWidth = $(dropdownLabel).outerWidth();
$(dropdown).width(labelWidth);

var dropdownWidth = $(dropdown).outerWidth();
var buttonWidth= $(button).outerWidth();
var inputWidth = barWidth - dropdownWidth - buttonWidth;
var inputWidthPercent = inputWidth / barWidth * 100 + "%";

var trayWidth = barWidth - buttonWidth + 3;
var trayWidthPercent = trayWidth / barWidth * 100 + "%";

$(input).css({'margin-left':dropdownWidth,'width':inputWidthPercent });
$(tray).css('width',trayWidthPercent);
}

function dropdownOn(){
$(dropdownList).fadeIn(25);
$(dropdown).addClass("active");
}

function dropdownOff(){
$(dropdownList).fadeOut(25);
$(dropdown).removeClass("active");
}




resizeElements();

$(dropdown).click(function(event){
if ($(dropdown).hasClass("active")){
dropdownOff();
}else{
dropdownOn();
}

event.stopPropagation();
return false;
});

$("html").click(dropdownOff);

$(dropdownListItems).click(function(){
$(this).siblings("li.selected").removeClass("selected");
$(this).addClass("selected");
$(this).parents("form.search_bar:first").find("input[type=text]").focus();
var newValue = $(this).attr("data-value");
var setElement = $(this).parents("form.search_bar:first").find("input[name=set]");
setElement.val(newValue);


var labelText = $(this).clone().children().remove().end().text();

$(dropdownLabel).text(labelText);

resizeElements();

$(traySections).hide();

if ($(this).attr("rel")){
var type = $(this).attr("rel");

$(traySections + "#" + type).show();
$(tray).slideDown(60);
$(bar).addClass("tray_active");
var newValue = $(traySections + " select option:selected").val();
setElement.val(newValue);

}else{
$(bar).removeClass("tray_active");
$(tray).slideUp(60);
}
});

$(traySections + " select").change(function(){
var newValue = $(this).val();
var setElement = $(this).parents("form.search_bar:first").find("input[name=set]");
setElement.val(newValue);


});

$(window).resize(function(){
resizeElements();
});
});