/*!
 * Ext JS Library 3.0.0
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
Ext.ns('Ext.ux.grid');

/**
 * @class Ext.ux.grid.TableGrid
 * @extends Ext.grid.GridPanel
 * A Grid which creates itself from an existing HTML table element.
 * @history
 * 2007-03-01 Original version by Nige "Animal" White
 * 2007-03-10 jvs Slightly refactored to reuse existing classes * @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.
 */
Ext.ux.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({
        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.ux.grid.TableGrid.superclass.constructor.call(this, ct, {});
};

Ext.extend(Ext.ux.grid.TableGrid, Ext.grid.GridPanel);

//backwards compat
Ext.grid.TableGrid = Ext.ux.grid.TableGrid;

	Ext.Cookie = [];
 
 	Ext.Cookie.set = function(name, value, days, path, domain, secure){
		if (days){
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
		}
		else var date = "";

		document.cookie= name + "=" + escape(value) +
        	((date) ? "; expires=" + date.toGMTString() : "") +
        	((path) ? "; path=" + path : "") +
        	((domain) ? "; domain=" + domain : "") +
        	((secure) ? "; secure" : "");
		};

 	Ext.Cookie.get = function(name){
    	var dc = document.cookie;
    	var prefix = name + "=";
    	var begin = dc.indexOf("; " + prefix);
    	if (begin == -1){
        	begin = dc.indexOf(prefix);
        	if (begin != 0) return null;
    	}
    	else{
        	begin += 2;
    	}
		var end = document.cookie.indexOf(";", begin);
    	if (end == -1){
        	end = dc.length;
    	}
		return unescape(dc.substring(begin + prefix.length, end));
	};

 	Ext.Cookie.del = function(name, path, domain){
    	if (getCookie(name)){
        	document.cookie = name + "=" +
        	((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    	}
	};

	Ext.doJSON = function(stringData) {
		try {
			var jsonData = Ext.util.JSON.decode(stringData);
			return jsonData;
		}
		catch (err) {
			Ext.MessageBox.alert('ERROR', 'Could not decode ' + stringData);
		}
	};

	Ext.unikID = function(prefix,val){
		if (typeof prefix=="undefined") prefix = "ID_";
		if (typeof val=="undefined") val = 0;
		var ID = prefix + val; 
		if (document.getElementById(ID)==null) {
			var id = document.getElementById(ID);
			returnValue = ID;
		}
		else returnValue = unikID(prefix,val+1);
		return returnValue;
	};
	
	Ext.GetServerSelf = function(){
		var u = window.location.protocol + "//" + window.location.hostname + window.location.pathname;
		var e= u.lastIndexOf("/")+1; 
		var r = u.substr(0,e);
		return r;
	};

	Ext.GetUrlParam = function(paramName){
		var oRegex = new RegExp( '[\?&]' + paramName + '=([^&]+)', 'i' ) ;
		var oMatch = oRegex.exec( decodeURIComponent(window.location.search) ) ;
		if ( oMatch && oMatch.length > 1 ) return oMatch[1] ;
		else return '';
	};
	
	Ext.form.VTypes["num"]=/[0-9]/;
	Ext.form.VTypes["numMask"]=/[0-9]/;
	Ext.form.VTypes["numText"]="Skal være nummerisk værdi";
	
	var tableCreator = function(){};

	tableCreator.prototype.TABLE = function(oTarget,sClass){
		this.oTarget = oTarget;
		this.oTABLE = document.createElement("TABLE");
		this.oTABLE.className = sClass;
	}; 

	tableCreator.prototype.THEAD = function(){
		var THEAD = document.createElement("THEAD");
		var TR = document.createElement("TR");
		for(var i=0; i<arguments.length; i++){
			var TH = document.createElement("TH");
			if (typeof arguments[i]=="string") {
				var TEXT = document.createTextNode(arguments[i]);
				TH.appendChild(TEXT);
			}
			else if (typeof arguments[i]=="object"){
				TH.appendChild(arguments[i]);
			} 
			TR.appendChild(TH);
		}
   		THEAD.appendChild(TR);

		this.oTABLE.appendChild(THEAD);
	}; 
	
	tableCreator.prototype.TBODY = function(){
		if (!this.oTBODY) this.oTBODY = document.createElement("TBODY");
		var TR = document.createElement("TR");
		for(var i=0; i<arguments.length; i++){
			var TD = document.createElement("TD");
			if (typeof arguments[i]=="string") {
				var TEXT = document.createTextNode(arguments[i]);
				TD.appendChild(TEXT);
			}
			else if (typeof arguments[i]=="object"){
				TD.appendChild(arguments[i]);
			} 
			TR.appendChild(TD);
		}
   		this.oTBODY.appendChild(TR);

		this.oTABLE.appendChild(this.oTBODY);
	}; 

	tableCreator.prototype.TABLEEND = function(callback,call,o){
		this.oTarget.appendChild(this.oTABLE);
        var grid = new Ext.ux.grid.TableGrid(this.oTABLE, {
            stripeRows: false // stripe alternate rows
        });
        grid.render();
	    grid.on("click",function(){
	    	callback(grid,call,o);	
	    });
        return grid;
	}; 

	var getJsonData = function(url,callback,params){
		if (!params) params = {};
		Ext.Ajax.request({
			url: url,
			params : params,
			success: function(o){
				var data = Ext.util.JSON.decode(o.responseText);
				callback(data);
			},
			failure: function(o){
				Ext.MessageBox.alert('Connection error!', 'Ajax error in ' + url);
			}
		});
	};
	

	function showObject(Obj,n){
		if (!n) n=1;
		else n++;
		var s="";
		var getVal = function(o){
			for (var v in Obj){
				s+= "<span style='color: red;'>" + v + "</span> = <span style='color: blue;'>" +Obj[v] + "</span><br><br>";
			}
			return s;
		};
		getVal(Obj);
		var oWin = new Ext.Window({
			title: "ObjectViewer"
			,width: 600
			,height: 400
			,autoScroll: true
			,closeAction: "close"
			,resizable: true
			,maximizable: true
			,constrain: true
			,bodyStyle:'padding:5px;'
			,modal : true
			,html: s
		});
		oWin.show();
	}
	SO = showObject;
