if (typeof GR == "undefined" || !GR) { var GR = {};}

GR.notice = {};
GR.notice.add = function(msg, type) {
    var notice = '<div id="notifications"><ul id="notifications_list"><li class="'+type+'">'+msg+'</li></ul></div>';
    $('#notification_holder').empty().append(notice);
};

GR.table = {};
GR.table.linked_row = function(row) {
    try {
        the_url = $(row).find('a')[0].href;
        document.location.href = the_url;
    } catch (error) {}
};

GR.filters = {};
GR.filters.add = function(action_filter, display_filter, hide_filter, related_filter, selected_class) {
    hide_filter = hide_filter || false;
    related_filter = related_filter || 'a.filter';
    selected_class = selected_class || 'selected_filter';
    $(action_filter).click(function(event) {
        event.preventDefault();
        $(this).blur();
        if (hide_filter) {
          $(hide_filter).hide();
        }
        $(display_filter).show();
        $(related_filter).removeClass(selected_class);
        $(this).addClass(selected_class);
        $.publish("filtered", this);
    });
};

GR.filters.update_count = function(selector, change_amount) {
    var count_span = $('span#favorite_count');
    var current_count = parseInt($(selector).html(), 10) || 0;
    count_span.html((current_count + change_amount)+'');
};

GR.printf = function() { 
  var num = arguments.length; 
  var oStr = arguments[0];   
  for (var i = 1; i < num; i++) { 
    var pattern = "\\{" + (i-1) + "\\}"; 
    var re = new RegExp(pattern, "g"); 
    oStr = oStr.replace(re, arguments[i]); 
  } 
  return oStr; 
} 

GR.preview = {};
GR.preview.init = function(args) {
    // The first time this function is called it will initialize the next/previous links
    // After the first time we don't want to keep adding the keypress as it will
    // 'click' and load the page for each of the times the binding is added.
    $(document).keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 37) {
            $('div#previous_asset a').click();
        }
        if (code == 39) {
            $('div#next_asset a').click();
        }
        e.keyCode ? e.keyCode : e.which;
    });

    // Reassinging the GR.preview.init to the below so the above isn't run again
    GR.preview.init = function(args) {
        /*
            Arguments
            ids: list of the ids, used for the next/previous links
            selector: the selector for jquery to know where to bind the click event to
            url: the base url that that the preview ajax should load, 
            template: the js template that should be used for rendering the preview link
        */
        var selector = args.selector || '.preview';
        var url = args.url || '{0}/';
        var template = args.template || 'preview_link_template';

        $(selector).live("click", function(e) {
            if ($(this).parents('div#prev_next').length > 0) {
                // Already in the lightbox so just swap out the current content for the loading graphic
                $("#TB_ajaxContent").html($('#thickbox_loader').html());
            } else {
                // Link from on the page so we need to show the lightbox
                var t = this.title || this.name || null;
                var a = this.href || this.alt;
                var g = this.rel || false;
                tb_show(t,a,g);
            }
            this.blur();
        
            var id = this.id;
            
            $("#TB_ajaxContent").load(GR.printf(url, id), function() {
                if (typeof args.ids == "string") {
                    var ids = window[args.ids];
                } else {
                    var ids = args.ids;
                }
                var current_index = $.inArray(parseInt(id, 10), ids);
                if (current_index < (ids.length - 1)) {
                    var next_link = tmpl(template, {id: ids[current_index + 1]});
                    $('#next_asset').html(next_link +'Next &gt;</a>');
                }
                if (current_index > 0) {
                    var previous_link = tmpl(template, {id: ids[current_index - 1]});
                    $('#previous_asset').html(previous_link +'&lt; Previous</a>');
                }
                if(ids.length > 0 && current_index > -1) {
                    $("#preview_count").html((current_index+1) + " of " + ids.length);
                }
                
                // Re-initializing the previous next links in the lightbox
                // Have to re-initilize as the ids may of changed
                args.selector = 'div#prev_next .preview';
                GR.preview.init(args);
            });
            return false;
        });
    };
    // Running the new version of the init function
    GR.preview.init(args);
};



// Subscribe/Publish functions
// Example:
//    var test = function(msg, msg2) {
//        alert(msg2);
//    };
//    $.subscribe("show_message", window, 'test');
//    $.publish( "show_message", 'the message is', 'this message');
jQuery.subscribe = function(signal, scope, fnName) {
    var curryArgs = Array.prototype.slice.call(arguments, 3);
    $(window).bind(signal, function () {
        var normalizedArgs = Array.prototype.slice.call(arguments, 1);
        scope[fnName].apply(signal, curryArgs.concat(normalizedArgs));
    });
    return jQuery;
};

jQuery.publish = function(signal) {
    $(window).trigger(signal, Array.prototype.slice.call(arguments, 1));
    return jQuery;
};


// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();
