Ext.BLANK_IMAGE_URL = '/static/scripts/resources/images/default/s.gif';
function hideBox(){
	var box = Ext.get('msg-div');
        if(box){
            box.slideOut("t", {remove:false, useDisplay: true});
        }
}
Ext.example = function(){
    var msgCt;

    function createBox(t, s){
        return [
    		'<div class="'+t+'"><div class="x-box-mr2"><div class="x-box-mc2"><div style="float: right;"><a href="javascript: hideBox();" class="msg-close"><img src="/static/images/icon_close_sm.gif" alt="x" title="Close this message"/></a></div>', s,
            '</div>'].join('');
    }
    return {
        msg : function(title, format){
            if(!msgCt){
            	msgCt = Ext.DomHelper.insertFirst('content', {id:'msg-div'}, true);
	        }
	        //msgCt.alignTo('main', 'tl',[222,4]);
	        var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
	        var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
	        //m.slideIn('t').pause(15).slideOut("t", {remove:true});
	        m.slideIn('t',{useDisplay: true});
        },

        init : function(){
            var t = Ext.get('exttheme');
            if(!t){ // run locally?
                return;
            }
            var theme = Cookies.get('exttheme') || 'aero';
            if(theme){
                t.dom.value = theme;
                Ext.getBody().addClass('x-'+theme);
            }
            t.on('change', function(){
                Cookies.set('exttheme', t.getValue());
                setTimeout(function(){
                    window.location.reload();
                }, 250);
            });

            var lb = Ext.get('lib-bar');
            if(lb){
                lb.show();
            }
        }
    };
}();

Ext.example.shortBogusMarkup = '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales non, iaculis ac, lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet tincidunt quam turpis vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla vel, urna.';
Ext.example.bogusMarkup = '<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales non, iaculis ac, lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet tincidunt quam turpis vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla vel, urna.<br/><br/>Aliquam commodo ullamcorper erat. Nullam vel justo in neque porttitor laoreet. Aenean lacus dui, consequat eu, adipiscing eget, nonummy non, nisi. Morbi nunc est, dignissim non, ornare sed, luctus eu, massa. Vivamus eget quam. Vivamus tincidunt diam nec urna. Curabitur velit.</p>';

Ext.onReady(Ext.example.init, Ext.example);


// old school cookie functions grabbed off the web

var Cookies = {};
Cookies.set = function(name, value){
     var argv = arguments;
     var argc = arguments.length;
     var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : '/';
     var domain = (argc > 4) ? argv[4] : null;
     var secure = (argc > 5) ? argv[5] : false;
     document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
};

Cookies.get = function(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	var j = 0;
	while(i < clen){
		j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return Cookies.getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0)
			break;
	}
	return null;
};

Cookies.clear = function(name) {
  if(Cookies.get(name)){
    document.cookie = name + "=" +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
};

Cookies.getCookieVal = function(offset){
   var endstr = document.cookie.indexOf(";", offset);
   if(endstr == -1){
       endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
};
/* */
Ext.data.DjangoJsonReader = function(meta, recordType){
    Ext.data.DjangoJsonReader.superclass.constructor.call(this, meta, recordType);
};
Ext.extend(Ext.data.DjangoJsonReader, Ext.data.JsonReader, {
    readRecords : function(o){
        this.jsonData = o;
        var s = this.meta;
    	var sid = s.id;
    	var recordType = this.recordType, fields = recordType.prototype.fields;

    	var totalRecords = 0;
    	if(s.totalProperty){
            var v = parseInt(eval("o." + s.totalProperty), 10);
            if(!isNaN(v)){
                totalRecords = v;
            }
        }
        var records = [];
    	var root = s.root ? eval("o." + s.root) : o;
	    for(var i = 0; i < root.length; i++){
		    var n = root[i];
	        var values = {};
	        var id = (n[sid] !== undefined && n[sid] !== "" ? n[sid] : n['pk']);
	        for(var j = 0, jlen = fields.length; j < jlen; j++){
	            var f = fields.items[j];
	            var map = f.mapping || f.name;
	            var v = n['fields'][map] !== undefined ? n['fields'][map] : f.defaultValue;
	            v = f.convert(v);
	            values[f.name] = v;
	        }
	        var record = new recordType(values, id);
	        record.json = n;
	        records[records.length] = record;
	    }
	    return {
	        records : records,
	        totalRecords : totalRecords || records.length
	    };
    }
});

/*
 * Ext JS Library 2.0.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

/**
  * Ext.ux.data.PagingMemoryProxy.js
  *
  * A proxy for local / in-browser data structures
  * supports paging / sorting / filtering / etc
  *
  * @file	Ext.ux.PagingMemoryProxy.js
  * @author	Ing. Ido Sebastiaan Bas van Oostveen
  *
  * @changelog:
  * @version    1.4
  * @date       21-Februari-2008
  *             - added filter prototype method for array's
  * @version    1.3
  * @date       30-September-2007
  *             - added customFilter config option
  * @version	1.2
  * @date	29-September-2007
  *		- fixed several sorting bugs
  * @version	1.1
  * @date	30-August-2007
  * @version	1.0
  * @date	22-August-2007
  *
  */

Ext.namespace("Ext.ux");
Ext.namespace("Ext.ux.data");

/* Fixes for IE/Opera old javascript versions */
if(!Array.prototype.map){
    Array.prototype.map = function(fun){
	var len = this.length;
	if(typeof fun != "function"){
	    throw new TypeError();
	}
	var res = new Array(len);
	var thisp = arguments[1];
	for(var i = 0; i < len; i++){
	    if(i in this){
		res[i] = fun.call(thisp, this[i], i, this);
	    }
	}
        return res;
     };
}

if (!Array.prototype.filter){
  Array.prototype.filter = function(fun /*, thisp*/){
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++){
      if (i in this){
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }
    return res;
  };
}

/* Paging Memory Proxy, allows to use paging grid with in memory dataset */
Ext.ux.data.PagingMemoryProxy = function(data, config) {
	Ext.ux.data.PagingMemoryProxy.superclass.constructor.call(this);
	this.data = data;
	Ext.apply(this, config);
};

Ext.extend(Ext.ux.data.PagingMemoryProxy, Ext.data.MemoryProxy, {
	customFilter: null,

	load : function(params, reader, callback, scope, arg) {
		params = params || {};
		var result;
		try {
			result = reader.readRecords(this.data);
		} catch(e) {
			this.fireEvent("loadexception", this, arg, null, e);
			callback.call(scope, null, arg, false);
			return;
		}

		// filtering
		if (this.customFilter!=null) {
			result.records = result.records.filter(this.customFilter);
			result.totalRecords = result.records.length;
		} else if (params.filter!==undefined) {
			result.records = result.records.filter(function(el){
			    if (typeof(el)=="object"){
					var att = params.filterCol || 0;
					return String(el.data[att]).match(params.filter)?true:false;
			    } else {
					return String(el).match(params.filter)?true:false;
			    }
			});
			result.totalRecords = result.records.length;
		}

		// sorting
		if (params.sort!==undefined) {
		    // use integer as params.sort to specify column, since arrays are not named
		    // params.sort=0; would also match a array without columns
		    var dir = String(params.dir).toUpperCase() == "DESC" ? -1 : 1;
        	    var fn = function(r1, r2){
			    return r1==r2 ? 0 : r1<r2 ? -1 : 1;
        	    };
		    var st = reader.recordType.getField(params.sort).sortType;
		    result.records.sort(function(a, b) {
				var v = 0;
				if (typeof(a)=="object"){
				    v = fn(st(a.data[params.sort]), st(b.data[params.sort])) * dir;
				} else {
				    v = fn(a, b) * dir;
				}
				if (v==0) {
				    v = (a.index < b.index ? -1 : 1);
				}
				return v;
		    });
		}

		// paging (use undefined cause start can also be 0 (thus false))
		if (params.start!==undefined && params.limit!==undefined) {
			result.records = result.records.slice(params.start, params.start+params.limit);
		}

		callback.call(scope, result, arg, true);
	}
});



Ext.namespace('Ext.ux.plugins');

Ext.ux.plugins.ProportionalWindows = function(config) {
    Ext.apply(this, config);
};

Ext.extend(Ext.ux.plugins.ProportionalWindows, Ext.util.Observable, {
    init:function(win) {
        Ext.apply(win, {
            onRender:win.onRender.createSequence(function(ct, position) {
                var ctr = this.container;
                var ctrW = ctr.getWidth();
                var ctrH = ctr.getHeight();
                if (this.aspect) {
                // maintain aspect ratio
                var ratio = this.height / this.width;
                    var newWidth = Math.round(ctrW * this.percentage);
                var newHeight = Math.round(newWidth * ratio);
                } else {
                    var newWidth = Math.round(ctrW * this.percentage);
                    var newHeight = Math.round(ctrH * this.percentage);
                }
                newWidth = (newWidth > this.width)?newWidth:this.width;
                newHeight = (newHeight > this.height)?newHeight:this.height;
                this.setSize(newWidth, newHeight);
            })// End onRender
            }
        );
    } // end of function init
}); // end of extend


/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */
/*
Ext.Spotlight = function(config){
    Ext.apply(this, config);
}
Ext.Spotlight.prototype = {
    active : false,
    animate : true,
    animated : false,
    duration: .25,
    easing:'easeNone',

    createElements : function(){
        var bd = Ext.getBody();

        this.right = bd.createChild({cls:'x-spotlight'});
        this.left = bd.createChild({cls:'x-spotlight'});
        this.top = bd.createChild({cls:'x-spotlight'});
        this.bottom = bd.createChild({cls:'x-spotlight'});

        this.all = new Ext.CompositeElement([this.right, this.left, this.top, this.bottom]);
    },

    show : function(el, callback, scope){
        if(this.animated){
            this.show.defer(50, this, [el, callback, scope]);
            return;
        }
        this.el = Ext.get(el);
        if(!this.right){
            this.createElements();
        }
        if(!this.active){
            this.all.setDisplayed('');
            this.applyBounds(true, false);
            this.active = true;
            Ext.EventManager.onWindowResize(this.syncSize, this);
            this.applyBounds(false, this.animate, false, callback, scope);
        }else{
            this.applyBounds(false, false, false, callback, scope); // all these booleans look hideous
        }
    },

    hide : function(callback, scope){
        if(this.animated){
            this.hide.defer(50, this, [callback, scope]);
            return;
        }
        Ext.EventManager.removeResizeListener(this.syncSize, this);
        this.applyBounds(true, this.animate, true, callback, scope);
    },

    doHide : function(){
        this.active = false;
        this.all.setDisplayed(false);
    },

    syncSize : function(){
        this.applyBounds(false, false);
    },

    applyBounds : function(basePts, anim, doHide, callback, scope){

        var rg = this.el.getRegion();

        var dw = Ext.lib.Dom.getViewWidth(true);
        var dh = Ext.lib.Dom.getViewHeight(true);

        var c = 0, cb = false;
        if(anim){
            cb = {
                callback: function(){
                    c++;
                    if(c == 4){
                        this.animated = false;
                        if(doHide){
                            this.doHide();
                        }
                        Ext.callback(callback, scope, [this]);
                    }
                },
                scope: this,
                duration: this.duration,
                easing: this.easing
            };
            this.animated = true;
        }

        this.right.setBounds(
                rg.right,
                basePts ? dh : rg.top,
                dw - rg.right,
                basePts ? 0 : (dh - rg.top),
                cb);

        this.left.setBounds(
                0,
                0,
                rg.left,
                basePts ? 0 : rg.bottom,
                cb);

        this.top.setBounds(
                basePts ? dw : rg.left,
                0,
                basePts ? 0 : dw - rg.left,
                rg.top,
                cb);

        this.bottom.setBounds(
                0,
                rg.bottom,
                basePts ? 0 : rg.right,
                dh - rg.bottom,
                cb);

        if(!anim){
            if(doHide){
                this.doHide();
            }
            if(callback){
                Ext.callback(callback, scope, [this]);
            }
        }
    },

    destroy : function(){
        this.doHide();
        Ext.destroy(
                this.right,
                this.left,
                this.top,
                this.bottom);
        delete this.el;
        delete this.all;
    }
};

*/
Ext.Spotlight = function(config){
Ext.apply(this, config);
}
Ext.Spotlight.prototype = {
active : false,
animate : false,
animated : false,
duration: .25,
easing:'easeNone',

createElements : function(){
var bd = Ext.getBody();

this.right = bd.createChild({cls:'x-spotlight'});
this.left = bd.createChild({cls:'x-spotlight'});
this.top = bd.createChild({cls:'x-spotlight'});
this.bottom = bd.createChild({cls:'x-spotlight'});

this.all = new Ext.CompositeElement([this.right, this.left, this.top, this.bottom]);
},

show : function(el, callback, scope){
if(this.animated){
this.show.defer(50, this, [el, callback, scope]);
return;
}
this.el = Ext.get(el);
if(!this.right){
this.createElements();
}
if(!this.active){
this.all.setDisplayed('');
this.applyBounds(true, false);
this.active = true;
Ext.EventManager.onWindowResize(this.syncSize, this);
this.applyBounds(false, this.animate, false, callback, scope);
}else{
this.applyBounds(false, false, false, callback, scope); // all these booleans look hideous
}
this.all.fadeIn({duration: .6, endOpacity: .9});
},

hide : function(callback, scope){
if(this.animated){
this.all.fadeOut({duration: .6});
//this.hide.defer(50, this, [callback, scope]);
return;
}
Ext.EventManager.removeResizeListener(this.syncSize, this);
this.applyBounds(true, this.animate, true, callback, scope);
//this.all.fadeOut();
},

doHide : function(){
this.active = false;
this.all.setDisplayed(false);
},

syncSize : function(){
this.applyBounds(false, false);
},

applyBounds : function(basePts, anim, doHide, callback, scope){

var rg = this.el.getRegion();

var dw = Ext.lib.Dom.getViewWidth(true);
var dh = Ext.lib.Dom.getViewHeight(true);

var c = 0, cb = false;
if(anim){
cb = {
callback: function(){
c++;
if(c == 4){
this.animated = false;
if(doHide){
this.doHide();
}
Ext.callback(callback, scope, [this]);
}
},
scope: this,
duration: this.duration,
easing: this.easing
};
this.animated = true;
}

this.right.setBounds(
rg.right,
basePts ? dh : rg.top,
dw - rg.right,
basePts ? 0 : (dh - rg.top),
cb);

this.left.setBounds(
0,
0,
rg.left,
basePts ? 0 : rg.bottom,
cb);

this.top.setBounds(
basePts ? dw : rg.left,
0,
basePts ? 0 : dw - rg.left,
rg.top,
cb);

this.bottom.setBounds(
0,
rg.bottom,
basePts ? 0 : rg.right,
dh - rg.bottom,
cb);

if(!anim){
if(doHide){
this.doHide();
}
if(callback){
Ext.callback(callback, scope, [this]);
}
}
},

destroy : function(){
this.doHide();
Ext.destroy(
this.right,
this.left,
this.top,
this.bottom);
delete this.el;
delete this.all;
}
};

/**
 * @class Ext.grid.TableGrid
 * @extends Ext.grid.Grid
 * A Grid which creates itself from an existing HTML table element.
 * @constructor
 * @param {String/HTMLElement/Ext.Element} table The table element from which this grid will be created -
 * The table MUST have some type of size defined for the grid to fill. The container will be
 * automatically set to position relative if it isn't already.
 * @param {Object} config A config object that sets properties on this grid and has two additional (optional)
 * properties: fields and columns which allow for customizing data fields and columns for this grid.
 * @history
 * 2007-03-01 Original version by Nige "Animal" White
 * 2007-03-10 jvs Slightly refactored to reuse existing classes
 */
Ext.grid.TableGrid = function(table, config) {
  config = config || {};
  Ext.apply(this, config);
  var cf = config.fields || [], ch = config.columns || [];
  table = Ext.get(table);

  var ct = table.insertSibling();

  var fields = [], cols = [];
  var headers = table.query("thead th");
  for (var i = 0, h; h = headers[i]; i++) {
    var text = h.innerHTML;
    var name = 'tcol-'+i;

    fields.push(Ext.applyIf(cf[i] || {}, {
      name: name,
      mapping: 'td:nth('+(i+1)+')/@innerHTML'
    }));

    cols.push(Ext.applyIf(ch[i] || {}, {
      'header': text,
      'dataIndex': name,
      'width': h.offsetWidth,
      'tooltip': h.title,
      'sortable': true
    }));
  }

  var ds  = new Ext.data.Store({
  	storeId: 'r-table',
    reader: new Ext.data.XmlReader({
      record:'tbody tr'
    }, fields)
  });

  ds.loadData(table.dom);

  var cm = new Ext.grid.ColumnModel(cols);

  if (config.width || config.height) {
    ct.setSize(config.width || 'auto', config.height || 'auto');
  } else {
    ct.setWidth(table.getWidth());
  }

  if (config.remove !== false) {
    table.remove();
  }

  Ext.applyIf(this, {
    'ds': ds,
    'cm': cm,
    'sm': new Ext.grid.RowSelectionModel(),
    autoHeight: true,
    autoWidth: false
  });
  Ext.grid.TableGrid.superclass.constructor.call(this, ct, {});
};

Ext.extend(Ext.grid.TableGrid, Ext.grid.GridPanel);




/**
* @class Ext.ux.GridPrinter
* @author Ed Spencer (edward@domine.co.uk)
* Helper class to easily print the contents of a grid. Will open a new window with a table where the first row
* contains the headings from your column model, and with a row for each item in your grid's store. When formatted
* with appropriate CSS it should look very similar to a default grid. If renderers are specified in your column
* model, they will be used in creating the table. Override headerTpl and bodyTpl to change how the markup is generated
*
* Usage:
*
* var grid = new Ext.grid.GridPanel({
* colModel: //some column model,
* store : //some store
* });
*
* Ext.ux.GridPrinter.print(grid);
*
*/
Ext.ux.GridPrinter = {
  /**
* Prints the passed grid. Reflects on the grid's column model to build a table, and fills it using the store
* @param {Ext.grid.GridPanel} grid The grid to print
*/
  print: function(grid) {
    //We generate an XTemplate here by using 2 intermediary XTemplates - one to create the header,
    //the other to create the body (see the escaped {} below)
    var columns = grid.getColumnModel().config;

    //build a useable array of store data for the XTemplate
    var data = [];
    grid.store.data.each(function(item) {
      var convertedData = [];

      //apply renderers from column model
      for (var key in item.data) {
        var value = item.data[key];

        Ext.each(columns, function(column) {
          if (column.dataIndex == key) {
            convertedData[key] = column.renderer ? column.renderer(value) : value;
          }
        }, this);
      }

      data.push(convertedData);
    });

    //use the headerTpl and bodyTpl XTemplates to create the main XTemplate below
    var headings = Ext.ux.GridPrinter.headerTpl.apply(columns);
    var body = Ext.ux.GridPrinter.bodyTpl.apply(columns);

    var html = new Ext.XTemplate(
      '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
      '<html>',
        '<head>',
          '<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />',
          '<link href="' + Ext.ux.GridPrinter.stylesheetPath + '" rel="stylesheet" type="text/css" media="screen,print" />',
          '<title>' + grid.title + '</title>',
        '</head>',
        '<body>',
          '<table>',
            headings,
            '<tpl for=".">',
              body,
            '</tpl>',
          '</table>',
        '</body>',
      '</html>'
    ).apply(data);

    //open up a new printing window, write to it, print it and close
    var win = window.open('', 'printgrid');

    win.document.write(html);

    win.print();
    win.close();
  },

  /**
* @property stylesheetPath
* @type String
* The path at which the print stylesheet can be found (defaults to '/stylesheets/print.css')
*/
  stylesheetPath: '/stylesheets/print.css',

  /**
* @property headerTpl
* @type Ext.XTemplate
* The XTemplate used to create the headings row. By default this just uses <th> elements, override to provide your own
*/
  headerTpl: new Ext.XTemplate(
    '<tr>',
      '<tpl for=".">',
        '<th>{header}</th>',
      '</tpl>',
    '</tr>'
  ),

   /**
* @property bodyTpl
* @type Ext.XTemplate
* The XTemplate used to create each row. This is used inside the 'print' function to build another XTemplate, to which the data
* are then applied (see the escaped dataIndex attribute here - this ends up as "{dataIndex}")
*/
  bodyTpl: new Ext.XTemplate(
    '<tr>',
      '<tpl for=".">',
        '<td>\{{dataIndex}\}</td>',
      '</tpl>',
    '</tr>'
  )
};

