
// prevent debug code from trigerring errors by creating a console placeholder when none exists
//if(typeof(console) == 'undefined') console = new (_class({methods:{log:function(){}}}));

dynwin_path = 'http://editor.com/dynwin/'
dynwin_images = {sys:'/home/web/editor.com/images/', url:'http://editor.com/images/'}

dynwin_cache = []
modules = []

function $(id){
    return document.getElementById(id)
}

function $$(el, doc){
    if(doc == null) return document.getElementsByTagName(el);
    else return doc.getElementsByTagName(el)
}

function _(el, doc){
    if(doc == null) return document.createElement(el);
    else return doc.createElement(el);
}

Function.prototype.bind = function(object){
    var __self = this
    return function() {
	return __self.apply(object, arguments);
    }
}

function fromCache(module, tmpl){
    for(var i in dynwin_cache){function printGrid(module, action, config, grid, callback) {

    var store = grid.getStore();

    application.startLoad();
    
    console.log(grid.initialConfig);

    var data = [];
    for(var i = 0; i < store.getCount(); i++) data.push(store.getAt(i).data);
    
    var doc = new JSON.Document('packet', JSON.DefaultPacket(module, action));
    doc.packet.xmldata = {
        config: config,
        data: data
    };
    
    var req = new JSON.Request(function(response) {
        application.stopLoad();
        if(callback != null) callback();
    }.bind(this));
    req.send(application.server, doc);
}
        if(dynwin_cache[i].tmpl == tmpl && 
    	    dynwin_cache[i].module == module)
		return dynwin_cache[i]
    }; return null
}

function moduleLoaded(module){
    for(var i in module.tmpls) if(fromCache(module, module.tmpls[i]) == null) { alert(module + " : "+module.tmpls[i]); return 0}
    for(var i in module.confs) if(fromCache(module, module.confs[i]) == null) { alert(module + " : "+module.tmpls[i]); return 0}
    for(var i in module.images){
	if(typeof(module.images[i]) != 'object' || module.images[i].loaded == 0)
	    return 0
    }
    return 1
}

function initStyle(module){
    var styles = $$('LINK'); for(var i in styles){
	if(styles[i].href == module.style){
	    styles[i].parentNode.removeChild(styles[i])
	} 
    }
    
    var style = _('LINK'); style.rel = 'stylesheet'; style.type = 'text/css';
    style.href = module.style; style.title = 'dynwin'
    $$('HEAD')[0].appendChild(style)
}

function browser(){
    var agent = 'unknown'
    navigator.userAgent.indexOf("Firefox") != -1 ? agent = 'ff' :
    navigator.userAgent.indexOf("Opera") != -1 ? agent = 'opera' : 
    navigator.userAgent.indexOf("MSIE") != -1 ? agent = 'ie' : agent = 'unknown'
    return agent
}

function position(obj) {
    var pos  = {x:obj.offsetLeft, y:obj.offsetTop||0}
    while(obj = obj.offsetParent) {
        pos.x += obj.offsetLeft; pos.y += obj.offsetTop
	if(obj.nodeName == 'TABLE' && browser() == 'ie') {pos.x -= 1;};
    } return pos;
}

function random(){
    return (Math.floor(Math.random()*100000)).toString()
}

function addEvent(event, object, method){
    if(object.addEventListener){
	object.addEventListener(event, method, false)
    } else object.attachEvent('on'+event, method)
}

String.prototype.htmlspecialchars = function() {
	var strlength = this.length;
	var newstr = '';
	for (var i = 0; i < strlength; i++) {
		switch(this.charCodeAt(i)) {
			case 34 : newstr += '&quot;'; break;
			case 38 : newstr += '&amp;' ; break;
			case 39 : newstr += '&#39;' ; break;
			case 60 : newstr += '&lt;'  ; break;
			case 62 : newstr += '&gt;'  ; break;
			default : newstr += this.charAt(i);
		}
	}
	return newstr;
}

function breakFilepath(path) {

	// very poor implementation, will do for now

	path = path.split('/');
	path[path.length - 1] = path[path.length - 1].split('.');

	return {
		path: path.slice(0, -1),
		basename: path[path.length - 1][0],
		extension: path[path.length - 1][1]
	};
}

// calling these two 'undefined' and 'defined' completely fucks extjs
// so hence the '_' prefix
function _undefined(obj) { return (typeof(obj) == 'undefined'); }
function _defined(obj) { return (typeof(obj) != 'undefined'); }

function relinkScriptById(id) {
    var old_script = $(id);
    var src = old_script.src;
    old_script.parentNode.removeChild(old_script);
    var script = document.createElement('script');
    script.setAttribute('id', id);
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', src);
    document.body.appendChild(script);
}


function recordArrayToArray(recordArray) {

    var array = [];
    for(var i = 0; i < recordArray.length; i++) array.push(recordArray[i].data);
    return array;
}

function collectDirtyRecords(store) {

    var records = store.getRange();
    var dirtyRecords = [];
    for(var i = 0; i < records.length; i++)
        if(records[i].dirty)
            dirtyRecords.push(records[i]);
    return dirtyRecords;
}

function slideInMsg(title, msg, seconds) {

    if(!this.msgCt) this.msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
    msgCt.alignTo(document, 't-t');
    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(seconds).ghost("t", {remove:true});
} 

function createBox(t, s) {
    return ['<div class="msg">',
            '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
            '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
            '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
            '</div>'].join('');
}

function _$(id) {

    return document.getElementById(id);
}

function array_merge(destination, source){
    for (var property in source)
        destination[property] = source[property];
    return destination;    
}

function rgbToHex(r, g, b) {

    return (byteToHex(r) + byteToHex(g) + byteToHex(b));
}

function byteToHex(value) {

    var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
    var digit1 = Math.floor(value / 16);
    var digit2 = value - (digit1 * 16);
    return (hex[digit1] + hex[digit2]);
}

function filterProperties(obj, propertyList) {

    var filtered = {};
    for(var i = 0; i < propertyList.length; i++)
        if(_defined(obj[propertyList[i]]))
            filtered[propertyList[i]] = obj[propertyList[i]]
    return filtered;
}

function msie()
{
	var rv = 0;
	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;
}

function mysqlTimeStampToDate(timestamp) {
    var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}

function dateToMysqlTimeStamp(date) {
    var ts = date.getFullYear() + '-';
    var month = date.getMonth() + 1;
    ts += (month < 10 ? '0' : '') + month + '-';
    var day = date.getDate();
    ts += (day < 10 ? '0' : '') + day + ' ';
    var hours = date.getHours();
    ts += (hours < 10 ? '0' : '') + hours + ':';
    var minutes = date.getMinutes();
    ts += (minutes < 10 ? '0' : '') + minutes + ':';
    var seconds = date.getSeconds();
    ts += (seconds < 10 ? '0' : '') + seconds;
    return ts;
}

function strPadLeft(str, l, c) {

	if(!str) str = '';
    var pad = '';
    for(var i = 0; i < (l - str.length); i++) pad += c;
    return (pad + str);
}

function strPadRight(str, l, c) {

	if(!str) str = '';
    var pad = '';
    for(var i = 0; i < (l - str.length); i++) pad += c;
    return (str + pad);
}

function strTrim(str, c) {

	var trimLeft = 0;
	while(trimLeft < str.length && str.charAt(trimLeft) == c) trimLeft++;
	
	var trimRight = 0;
	while((str.length - trimRight - 1) >= trimLeft && str.charAt(str.length - trimRight - 1) == c) trimRight++;
	
	return str.substr(trimLeft, (str.length - trimLeft - trimRight));
}