$(document).ready(function() {
    $('#countrylist').autocomplete({
        source: function(request, response) {
            $.ajax({
			
                type: "GET",
                url: '/countrySuggest.php',
                data: 'c=' + request.term,
                success: function(data) {
                    response(data.split("\n"));
                }
            });		
        },
        close: function(event, ui) {
				
            searchFunction(event, true);
				
        }
    });

    $('#closediv a').click(function() {           
        $('#search_suggest').fadeOut('medium');
        $('#ir_wrapper').fadeOut('medium');
    });
	
    $('#countrySearch').click(function(e) {
        searchFunction(e, true);
    });

});

function searchFunction(e, blnShowCompetitors) {
    e.preventDefault();
    
    var countryStr = $('#countrylist').val();
    var getStr = '/countryRates.php?c=' + countryStr;
    var getVonageStr = '/countryRates.php?vc=' + countryStr;
    if(blnShowCompetitors) {
        getStr += '&co=1';
    }
    if(countryStr != '') {
        $.get(getStr, function(data) {
            if(data.length > 0) {

                $('#ir_rates').html(data);				
            //$('#closediv').show();

            } else {								
                $('#ir_wrapper').fadeOut('medium', function() {
                    alert("A match was not found. Please be sure to check your spelling of '" + newc + "'.");
                });
				
                var cstr = countryStr;
                var c = cstr.substring(0,1);
                var fl = c.toUpperCase();
                var newc = fl.concat(cstr.substr(1,50));
                //$('#closediv').hide();
                $('#ir_rates').html("");
				
            }
        });
		
        $.get(getVonageStr, function(data) {
            if(data.length > 0) {

                $('#virates').html(data);				
                $('#ir_wrapper').fadeIn('slow');

            } else {
                //alert("A match was not found. Please be sure to check your spelling of '" + newc + "'.");				
                //$('#ir_wrapper').fadeOut('medium');
                var cstr = countryStr;
                var c = cstr.substring(0,1);
                var fl = c.toUpperCase();
                var newc = fl.concat(cstr.substr(1,50));
                //$('#closediv').hide();
                $('#virates').html("");
				
            }
        });
    }
}
