function flagsSelection() {

    $("#countryList li").click( function() {
        $(this).removeClass('hover');

        if( $(this).hasClass('selected') &&  ! $("#countryList").hasClass('expand') ) {
            $("#countryList").addClass('expand');
            $("#countryList li").removeClass('hide');

            return false; //stop bubbling li click -> body click ( check below on body.click() )
        }

        $("#countryList li").removeClass('selected');
        $("#countryList li").addClass('hide');

        $(this).removeClass('hide');
        $(this).addClass('selected');

        $("#countryList").removeClass('expand');
        $("#countryList li > img.expand-list").addClass('hide');

        $(this).children("img.expand-list").removeClass('hide');

        $(this).clone(true).prependTo( $(this).parent() );
        $(this).remove();

        $("#selectedCountry").val( $(this).attr('id') );

    });

    $("#countryList li").hover( function() {
        if( !$("#countryList").hasClass('expand') ) {
            return;
        }

        $(this).addClass('hover');
    },
    function() {
        $(this).removeClass('hover');
    });

    $("#countryList .expand-list").click( function() {
        if( $("#countryList").hasClass('expand') ) {
            $("#countryList").removeClass('expand');
            $("#countryList li").addClass('hide');
        }
        else{
            $("#countryList").addClass('expand');
            $("#countryList li").removeClass('hide');
        }

        return false; //stop bubbling
    });

    $("body").click( function() {
        if( $("#countryList").hasClass('expand') ) {
            $("#countryList").removeClass('expand');
            $("#countryList li:not(.selected)").addClass('hide');
        }
    });
}

var cleard = false;
function keywordsInput(){
    $("#keywords").focus( function() {
        if( !cleard && $("#search_form").hasClass('can-clear') ) {
            $(this).val('');
            cleard = true;
        }
    });

    /*
    * Before submitting we should check if user have changed
    * keywords. If he have not, clear default keywords. Otherwise
    * search result will be surprising
    */
    $("#search_form").submit( function() {
        if( !cleard && $("#search_form").hasClass('can-clear') ) {
            $("#keywords").val('');
            cleard = true;
        }
    });
}

$(document).ready( function() {
    flagsSelection();
    keywordsInput();
});
