function getSelectValue(select)
{
    return select.options[select.selectedIndex].value;
}

function clearSelect(select, options)
{
	select.options.length = 0
	select.options[select.options.length] = new Option('Select one', '');
}

function updateSelect(select, options)
{
	clearSelect(select);
        $(options).each(function(i) {
                select.options[select.options.length] = new Option(this.name, this.id);
        });
}

function FXFadeOutAndHide(node)
{
        $(node).css('opacity', '1');
        $(node).fadeOut(3000, function() {
                $(this).css('display', 'none');
            });
}

function FXFadeInFadeOutAndHide(node)
{
    $(node).css('opacity', '0');
    $(node).fadeIn(3000, function() {
            FXFadeOutAndHide(this);
        });
}

/*
 * Updates country/states select boxes
 */
function updateStates(data)
{
        var state	= $("#id_state")[0];
	updateSelect(state, data);
}
/*
 * Updates country/states select boxes (Ajax request)
 */
function refreshStates()
{
        var country = $("#id_country")[0];
        var state	= $("#id_state")[0];
	id = getSelectValue(country);
	if (id)
	{
            $.getJSON("/accounts/ajax/country/"+id+"/states/",
                      function(data, textStatus) {
                          if (textStatus == 'sucess')
                              updateStates(data);
                      });
	}
	else
	{
		updateSelect(state, []);
	}
}

// For edit flatpages
function doEdit(page)
{
 var day = new Date();
 var id = day.getTime();
 var editor = window.open(page, id , 'toolbar=0,scrollbars=0,location=no,statusbar=0,menubar=0,resizable=0,width=550,height=400,left = 470,top = 200');
 return true;    
}

// For Auto complete
function get_answers(v,cont){
  $.get('/search',{qt:v},
        function(obj){
          var res = [];
          var suggests = obj;
          for(var i=0;i<suggests.length;i++){
            res.push({ id:i, value:suggests[i] });
          }
          cont(res);
        },
        'json')
}
function init(input,multi){
    $(input).autocomplete({ get : get_random_suggs, callback: print_sugg, multi: multi});
}

$(function() {
    $('.err').tooltip({
            /* styling TBD */
        });
    });
