/*

"Would I rather be feared or loved? Um... Easy, both.
    I want people to be afraid of how much they love me."
            - Michael Scott

*/

var curr_catcode;
var page;
var order;
var order_asc;
var base_uri;

window.onload = function() {
    init();
    $("input#query").focus();
    $("input.txt_price").keypress(function(e) {
        var charCode = (e.which) ? e.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
        {
            return false;
        }
        return true;
    });
    $("#tagcloud a").click(function(e) {
            $("input#query").val($(this).text());
            $("form#searchform").submit();
            return false;
        });
}

function init()
{
    
    curr_catcode = -1;
    page = 1;
    order = "sales";
    order_asc = 0;
    base_uri = $("#base_uri").val();

    load_categories();
    
    $("#categories select").change( load_categories );
    
    $("form#searchform").submit( function() {
        new_search();
        return false;
    });

    if ($("#query").val())
    {
        new_search();
    }
}

function load_categories()
{
    var code        = $("#categories select").val();
    var country_id  = $("#country_id").val();
    var parent_of   = "";

    if (code == -1) return false;

    if (code == -2 && curr_catcode > 0)
    {
        parent_of = "&parent_of="+curr_catcode;
    }

    url = base_uri+"load_categories.php?catcode="+code+"&country_id="+country_id+parent_of;

    $.getJSON(url, function(json) {
        var tot = json.categories.length;
        var i;
        if (tot > 0)
        {

            curr_catcode = json.categories[0].code;

            opts = '';
            for (i=0; i<tot; i++)
            {
                opts+= '<option value="'+json.categories[i].code+'"';
                if (i == 0) opts+= ' class="hey"';
                opts+= '>'+json.categories[i].name+"</option>"
            }
            $("#categories select").html(opts);
            $("#categories select").val(curr_catcode);

            if (code && !json.toplevel)
            {
                if (country_id == 1)
                {
                    $("#catmess").html('<div class="subcatlbl">(você pode selecionar uma subcategoria)</div>');
                }
                else
                {
                    $("#catmess").html('<div class="subcatlbl">(usted puede seleccionar una subcategoría)</div>');
                }
            }
            else
            {
                $("#catmess").html("");
            }

        }
        else
        {
            $("#catmess").html("");
        }
    });
}

function new_search()
{
    page = 1;
    get_results();
}

function get_results()
{

    loading();

    var query           = $("#query").val();
    var catcode         = $("#categories select").val();
    var show_pictures   = ($("#show_pictures").is(':checked') ? 1 : 0);
    var title_only      = ($("#title_only").is(':checked') ? 1 : 0);
    var mpago           = ($("#mpago").is(':checked') ? 1 : 0);
    var fixed_price     = ($("#fixed_price").is(':checked') ? 1 : 0);
    var min_price       = $("#min_price").val();
    var max_price       = $("#max_price").val();
    var country_id      = $("#country_id").val();
    var country_name    = $("#country_name").val();


    url = base_uri+"get_results.php?query="+query+"&catcode="+catcode+"&show_pictures="+show_pictures;
    url+= "&title_only="+title_only+"&fixed_price="+fixed_price+"&mpago="+mpago;
    url+= "&min_price="+min_price+"&max_price="+max_price+"&page="+page+"&order="+order+"&order_asc="+order_asc;
    url+= "&is_ie="+(getInternetExplorerVersion() != -1 ? '1' : '0')+"&country_id="+country_id;

    $.get(url, function(data) {
        if (query.length > 0)
        {
            document.title = query + " - MercadoAjax "+country_name;
        }
        $("#results").html(data);
        if (!show_pictures)
        {
            $(".ptitle").hover(function() {
                $("#img"+$(this).attr("id")).show();
            }, function()
            {
                $("#img"+$(this).attr("id")).hide();
            });
        }
        $("#pages a").click(function() {
            go_to_page($(this).attr("id"));
            return false;
        });
        $("table th a").click(function() {
            order_results($(this).attr("id"));
            return false;
        });
        $("table td a").click(function() {
            window.open($(this).attr("href"));
            return false;
        });
        $("#result_start").ScrollTo(800);
    });

}

function go_to_page(pageid)
{
    page = pageid.replace("page", "");
    get_results();
}

function order_results(new_order)
{
    
    new_order = new_order.replace("order_", "");

    if (new_order == order)
    {
        if (order == "price")
        {
            if (order_asc == 0) order_asc = 1; else order_asc = 0;
        }
        else
        {
            alert("A lista já está ordenada por esta coluna.");
            return false;
        }
    }
    else
    {
        order = new_order;
        order_asc = 1;
    }

    get_results();

}

function loading()
{
	$('#results').html('<p id="loading"><img src="'+base_uri+'img/loading.gif" /></p>');
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
