//
// Generates a css-styled dropdown
//

function refreshDropDown(id){
	$(id).val( $(location).attr('host') );
}

function createDropDown(id){
    var source = $(id);
    var parent = source.parent();
    var selected = source.find("option[selected]");
    var options = $("option", source);
    
    parent.append('<dl id="target" class="dropdown"></dl>')

	/* Create Selected Option. Use title attr for image icon */
    $("#target").append('<dt>' +
    	'<a href="#"><img src="' + source.find("option:selected").attr("title") + '">' + selected.text() + 
        '<span class="value">' + selected.val() + 
        '</span></a></dt>')
    $("#target").append('<dd><ul></ul></dd>')

	/* Create Each Option. Use title attr for image icon */
    options.each(function(){
        $("#target dd ul").append('<li><a href="#">' + 
        	'<img src="' + $(this).attr("title") + '">' + 
            $(this).text() + '<span class="value">' + 
            $(this).val() + '</span></a></li>');
    });
    
    /* Hide orignal select object */
    source.hide()
}

function bindDropdown(){ 
    $(".dropdown dt a").click(function() {
        $(".dropdown dd ul").toggle();
    });

    $(document).bind('click', function(e) {
        var $clicked = $(e.target);
        if (! $clicked.parents().hasClass("dropdown"))
            $(".dropdown dd ul").hide();
    });
                
    $(".dropdown dd ul li a").click(function() {
        var text = $(this).html();
        $(".dropdown dt a").html(text);
        $(".dropdown dd ul").hide();

		//change script page's subdomain
		var url =  "http://" + $(this).find(".value").html() + $(location).attr('pathname')
		window.location = url;
    });
}




$(document).ready(function() {
	refreshDropDown( "#subdomainMenu" );
    createDropDown( "#subdomainMenu" );   
    bindDropdown();
});


