var timestamp;
if(window.location.hash == ''){
    window.location.hash = '#home';
}
var backend = '';
var currentHash = window.location.hash;
var hashBeforeLogin = window.location.hash;
var homeRefreshTO = null;
var currentPage = {'data': false};
var ptimeout = null;
var ttimeout = null;
function loading(){
    Ext.Ajax.abort();
    Ext.fly('loadingimg').radioClass('show');
}
function loaded(){
    Ext.fly('okimg').radioClass('show');
}
function error(_, err){
    errimg = Ext.fly('errorimg');
    errimg.radioClass('show');
    errimg.dom.title = err.status + ' ' + err.statusText;
    errimg.dom.alt = err.status;
}

function editDomain(did){
    row = Ext.get('domain-'+did).dom;
    row.childNodes[0].innerHTML = '<input type="text" id="domain-edit-' + did + '" value="' + row.childNodes[0].innerHTML + '" />';
    row.childNodes[1].innerHTML = '<a href="javascript:saveDomain(\'' + did + '\');" class="ic-tick ic"></a>';
    var it = document.getElementById('domain-edit-' + did);
    it.focus();
    it.select();
}
function saveDomain(did){
    var dname = Ext.get('domain-edit-' + did).getValue();
    document.getElementById('domain-'+did).childNodes[1].innerHTML = '<img alt="..." src="img/loading.gif" />';
    Ext.Ajax.request({
	url: backend + 'domains/0',
	params: {'id': did, 'name': dname},
	success: function(res){

	    var r = Ext.decode(res.responseText);
	    if(r.success){
		refresh();
	    }else{
		var tds = document.getElementById('domain-'+did).childNodes;
		tds[0].innerHTML = r.name;
		document.getElementById('domain-'+did).childNodes[1].innerHTML = '<span style="white-space: nowrap; color: #8A1F11;"><a href="javascript:editDomain(\''+r.id+'\');" class="ic-error ic"></a> ' + r.error + '</span>';
	    }
	},
	failure: function(){
	    document.getElementById('domain-'+did).childNodes[1].innerHTML = '<img alt="error" src="img/icons/error.png" /> error contact admin!';
	}
    });
}
function removeDomain(did){
    Ext.Ajax.request({
	url: backend + 'domains/0',
	params: {'id': did, 'delete': 1},
	success: function(res){
	    var r = Ext.decode(res.responseText);
	    refresh();
	}
    });
}
function importText(listid){
    Ext.select('.tabc').setStyle('display', 'none');
    Ext.get('tab-text').setStyle('display', 'block');
}
function importFile(listid){
    Ext.select('.tabc').setStyle('display', 'none');
    Ext.get('tab-file').setStyle('display', 'block');
}
function uploadText(listid){
    Ext.Ajax.request({
	url: backend + 'lists/'+listid+'/subscribers/import',
	params: {'text': Ext.fly('import-text').getValue()},
	success: asyncUploadSuccess
    });
}

function uploadFile(listid){
    Ext.Ajax.request({
	url: backend + 'lists/'+listid+'/subscribers/import',
	form: 'file-form',
	isUpload: true,
	success: asyncUploadSuccess
    });
}
function showerrorlines(){
    Ext.get('errorlines').show();
}
function showduplines(){
    Ext.get('duplines').show();
}
var asyncuploadto = null;
function asyncUploadSuccess(response){
    var r = Ext.decode(response.responseText);
    if(r.statusid){
	if(r.status != 'done'){
	    //set progress
	    if(r.status == 'working'){
		if(r.good == undefined){
		    r.good = 0;
		}
		if(r.time == undefined){
		    r.time = 0;
		}
		if(r.duplicate == undefined){
		    r.duplicate = 0;
		}
		if(r.error == undefined){
		    r.error = 0;
		}
	        var e = Ext.get('import-notice');
	        e.dom.innerHTML = 'Working... Imported ' + r.good + ' subscribers in ' + r.time + '. There were ' + r.duplicate + ' duplicates and ' + r.error + ' errors.';
	        e.setStyle('display', 'block');
	    }
	    if(asyncuploadto){
	        clearTimeout(asyncuploadto);
	    }
	    asyncuploadto = setTimeout(function(){
		Ext.Ajax.request({
		    url: backend + 'status/' + r.statusid,
		    success: asyncUploadSuccess
		});
	    }, r.status == 'working' ? 2000 : 500);
	}else{
	    uploadSuccess(response);
	}
    }
}
function uploadSuccess(response){
    var r = Ext.decode(response.responseText);
    if(r.success){
	if(r.good > 0){
	    var e = Ext.get('import-success');
	    Ext.get('import-error').setStyle('display', 'none');
	}else{
	    var e = Ext.get('import-error');
	    Ext.get('import-success').setStyle('display', 'none');
	}
	Ext.get('import-notice').setStyle('display', 'none');
	if(r.error > 0){
	    var errorlines = '<a href="javascript:showerrorlines();">Show errors</a><br /><textarea readonly="readonly" rows="5" cols="80" style="width: 98%; height: 85px; display: none;" id="errorlines">';
	    for(var i=0;i<r.error;i++){
		errorlines += 'line ' + r.errorlines[i].num + ': "' + r.errorlines[i].text + "\"";
		if(r.errorlines[i]['error'] != undefined){
		    errorlines += ' (' + r.errorlines[i].error + ')';
		}
		errorlines += "\n";
	    }
	    errorlines += '</textarea>';
	}else{
	    errorlines = "";
	}
	if(r.duplicate > 0){
	    var duplines = '<a href="javascript:showduplines();">Show duplicates</a><br /><textarea readonly="readonly" rows="5" cols="80" style="width: 98%; height: 85px; display: none;" id="duplines">';
	    for(var i=0;i<r.duplicate;i++){
		duplines += 'line ' + r.duplines[i].num + ': "' + r.duplines[i].text + "\"\n";
	    }
	    duplines += '</textarea>';
	}else{
	    duplines = "";
	}
	e.dom.innerHTML = 'Done. Imported ' + r.good + ' subscribers in ' + r.time + '. There were ' + r.duplicate + ' duplicates and ' + r.error + ' errors. <a href="javascript:refresh();">View subscribers</a><br /> ' + errorlines + ' ' + duplines;
	e.setStyle('display', 'block');
    }
}
function removeBouncedFromList(list, bounces){
    var c = confirm('Are you sure');
    if(!c){
	return;
    }
    Ext.Ajax.request({
	method: 'GET',
	url: backend + '/removebounced/' + list + '/' + bounces,
	success: function(){
	    refresh();
	}
    });
}
function deleteSubscriber(list, id){
    var reason = prompt('Reason:');
    if(reason == null){
	return;
    }
    Ext.Ajax.request({
	method: 'POST',
	params: {'reason': reason},
	url: backend + '/subscribers/' + list + '/' + id,
	success: function(){
	    refresh();
	}
    });
}
function createList(){
    Ext.Ajax.request({
	url: backend + '/lists/new',
	success: function(response){
	    r = Ext.decode(response.responseText);
	    window.location.hash = '#lists/' + r.id;
	}
    });
}
function addCategory(){
    Ext.Ajax.request({
	url: backend + '/categories',
	method: 'POST',
	params: {'name': Ext.get('new-category-name').getValue()},
	success: function(){
	    refresh();
	}
    });
}
function deleteCategory(id){
    Ext.Ajax.request({
	url: backend + '/categories/' + id,
	method: 'DELETE',
	success: function(){
	    refresh();
	}
    });
}
function createMessage(){
    Ext.Ajax.request({
	url: backend + '/messages/new',
	success: function(response){
	    r = Ext.decode(response.responseText);
	    window.location.hash = '#messages/' + r.id;
	}
    });
}
function deleteList(id){
    var c = confirm('Are you sure you want to delete this list?');
    if(!c){
	return;
    }
    Ext.Ajax.request({
	method: 'DELETE',
	url: backend + '/lists/' + id,
	success: function(){
	    window.location.hash = '#lists';
	}
    });
}
function deleteMessage(id){
    var c = confirm('Are you sure you want to delete this message?');
    if(!c){
	return;
    }
    Ext.Ajax.request({
	method: 'DELETE',
	url: backend + '/messages/' + id,
	success: function(){
	    window.location.hash = '#messages';
	}
    });
}
function saveUser(){
    var f = ['username', 'name', 'email', 'password'];
    var params = {};
    for(var i=0;i<f.length;i++){
	params[f[i]] = Ext.fly(f[i]).getValue();
    }
    params['admin'] = Ext.fly('admin').dom.checked;
    Ext.Ajax.request({
	url: backend + '/admin/user/' + Ext.fly('id').getValue(),
	params: params,
	success: function(response){
	    var r = Ext.decode(response.responseText);
	    if(r.success){
		window.location.hash = '#admin/users';
	    }else{
		var err = Ext.fly('addusererror');
		err.update(r.error);
		err.show();
	    }
	}
    });
}
function deleteUser(id){
    var c = confirm('Are you sure you want to delete this user?');
    if(!c){
	return;
    }
    Ext.Ajax.request({
	method: 'DELETE',
	url: backend + '/admin/user/' + id,
	success: function(){
	    refresh();
	}
    });
}
function enterSubscriberSearch(e){
    if(e.keyCode == 13){
	subscriberSearch();
    }
}
function subscriberSearch(){
    window.location.hash = '#lists/search/' + Ext.fly('subsearchbox').getValue();
}
function enterFilter(id, e){
    if(e.keyCode == 13){
	changeFilter(id);
    }
}
function changeFilter(id){
    window.location.hash = '#lists/' + id + '/subscribers/1/' + Ext.fly('filterbox').getValue();
}

function pager(res){
    p = '<br />';
    if(res.records){
	size = res.size;
	basepath = currentHash;
	li = basepath.lastIndexOf('/');
	bpp = basepath.substr(li + 1);
	if(parseInt(bpp) == bpp){
	    basepath = basepath.substr(0, li);
	}
	filterval = res.p3;
	if(res.page > 1){
//	    p += '<a href="' + basepath + '/' + (res.page - 1) + '">&lt; Previous</a>';
	    p += '<a href="#lists/' + res.list.id + '/subscribers/' + (res.page - 1) + '/' + filterval + '">&lt; Previous</a>';
	}
	end = (size * res.page)
	end = end > res.count ? res.count : end;
	p += ' <b>' + (size * (res.page - 1) + 1) + ' - ' + end + ' of ' + res.count + '</b> ';
	if(res.page < (res.count / size)){
//	    p += '<a href="' + basepath + '/' + (res.page + 1) + '">Next &gt;</a>';
	    p += '<a href="#lists/' + res.list.id + '/subscribers/' + (res.page + 1) + '/' + filterval + '">Next &gt;</a>';
	}
    }
    res['pager'] = p;
    return res;
}

function getPage(path){
    Ext.Ajax.request({
	url: backend + path,
	success: function(response){
	    r = Ext.decode(response.responseText);
	    if(r.error == 'auth'){
		hashBeforeLogin = window.location.hash;
		window.location.hash = '#login';
		return;
	    }
	    var nb = Ext.get('namebox');
	    var lo = Ext.get('logout');
	    if(r.username){
		nb.update(r.username);
		lo.show();
	    }else{
		nb.update('');
		lo.hide();
	    }
	    var at = Ext.fly('admin-tab');
	    if(r.level == 1){
		at.show();
	    }else{
		at.hide();
	    }
	    currentPage.data = r;
	    for(i=0,tl=templates.length;i<tl;i++){
		var rere = templates[i][1].exec(path)
		if(rere != null){
		    try {
			for(var p=1;p<rere.length;p++){
			    r['p'+p] = rere[p] || '';
			}
			if(templates[i][4]){
			    r = templates[i][4](r);
			}
			domel = Ext.fly('tcontainer').dom;
			mc = templates[i][2].expand(r);
			domel.className = templates[i][0];
		        domel.innerHTML = mc;
		        ldomel = Ext.fly('lcontainer').dom;
		        if(templates[i][3]){
			    lc = templates[i][3].expand(r);
			    Ext.fly('lc').show();
			}else{
			    lc = '&nbsp;';
			    Ext.fly('lc').hide();
			}
		        ldomel.className = templates[i][0];
		        ldomel.innerHTML = lc;
		        if(templates[i][5]){
		    	    templates[i][5](r);
		    	}
			break;
		    }catch(err){
//			console.log(err);
			alert(err.message);
		    }
		}
	    }
	    if(homeRefreshTO){
		clearTimeout(homeRefreshTO);
	    }
	    if(currentHash == '#home'){
		homeRefreshTO = setTimeout(function(){
		    if(currentHash == '#home'){
			refresh();
		    }
		}, 30000);
	    }
	},
	timeout: 60000
    });
}
function refresh(){
    hashChanged(currentHash);
}
function hashChanged(newhash){
    getPage(newhash.substr(1));
}
function activateTab(){
    Ext.select('div.tabs ul li a').each(function(el){
	h = el.dom.href;
	h = h.substr(h.lastIndexOf('#'));
	if(h == currentHash.substr(0, h.length)){
	    el.up('li').addClass('active');
	}else{
	    el.up('li').removeClass('active');
	}
    });
}
Ext.onReady(function(){
    Ext.Ajax.on('beforerequest', loading);
    Ext.Ajax.on('requestcomplete', loaded);
    Ext.Ajax.on('requestexception', error);
    hashChanged(currentHash);
    Ext.select('div.tabs ul li').on('click', function(e, t){
	Ext.get(t.id).up('li').radioClass('active');
    });
    activateTab();
    setInterval(function(){
	if(window.location.hash != currentHash){
	    currentHash = window.location.hash;
	    hashChanged(currentHash);
	}
    }, 50);
    setInterval(function(){
	timestamp += 1;
	Ext.select('span.tp').each(function(el){
	    el.dom.innerHTML = time_past(el.dom.title, timestamp);
	});
    }, 1000);
//    setInterval(function(){
//	if(currentHash == '#home'){
//	    refresh();
//	}
//    }, 30000);
});

function login(){
    Ext.Ajax.request({
	url: backend + 'login',
	params: {'username': Ext.fly('username').getValue(), 'password': Ext.fly('password').getValue()},
	success: function(response){
	    var r = Ext.decode(response.responseText);
	    if(r.success){
		window.location.hash = (hashBeforeLogin == "#login" || hashBeforeLogin == "#logout") ? "#home" : hashBeforeLogin;
		currentHash = window.location.hash;
		hashChanged(currentHash);
		activateTab();
	    }else{
		Ext.fly('login-error').dom.style.display = 'block';
	    }
	}
    });
}
function saveList(id){
    Ext.Ajax.request({
	url: backend + 'lists/' + id,
	params: {'name': Ext.fly('list-name').getValue(), 'category': Ext.fly('list-category').getValue(), 'visibility': Ext.fly('list-visibility').dom.checked ? 1 : 0},
	success: refresh
    });
}
function saveMessage(id){
    var lists = [];
    Ext.select('.message-lists').each(function(el){
	if(el.dom.checked){
	    lists.push(el.getValue());
	}
    });
    var flags = 0;
    if(Ext.fly('message-embed').dom.checked){
	flags += 1;
    }
    if(Ext.fly('message-receipt').dom.checked){
	flags += 2;
    }
    Ext.Ajax.request({
	url: backend + 'messages/' + id,
	params: {
	    'name': Ext.fly('message-name').getValue(),
	    'category': Ext.fly('message-category').getValue(),
	    'fromname': Ext.fly('message-fromname').getValue(),
	    'fromaddress': Ext.fly('message-fromaddress').getValue(),
	    'fromdomain': Ext.fly('message-fromdomain').getValue(),
	    'subject': Ext.fly('message-subject').getValue(),
//	    'embed': Ext.fly('message-embed').dom.checked ? 1 : 0,
	    'flags': flags,
	    'html': Ext.fly('message-html').getValue(),
	    'text': Ext.fly('message-text').getValue(),
	    'lists': lists.join('|')
	},
	success: refresh
    });
}
function sendMessage(id){
    Ext.Ajax.request({
	url: backend + 'messages/' + id + '/send',
	success: function(response){
	    r = Ext.decode(response.responseText);
	    ok = confirm("The message will be sent to " + r.count + " email addresses.\nContinue?");
	    if(ok){
		Ext.Ajax.request({
		    url: backend + 'messages/' + id + '/send',
		    params: {
			'confirmed': true
		    },
		    success: asyncSendSuccess
		});
	    }
	}
    });
}
var asyncsendto = null;
function asyncSendSuccess(response){
    var r = Ext.decode(response.responseText);
    if(r.statusid){
	if(r.status != 'done'){
	    if(r.status == 'working'){
	        var e = Ext.get('send-notice');
	        e.dom.innerHTML = 'Working... <br />' + r.message;
	        e.setStyle('display', 'block');
	    }
	    if(asyncsendto){
		clearTimeout(asyncsendto);
	    }
	    asyncsendto = setTimeout(function(){
		Ext.Ajax.request({
		    url: backend + 'status/' + r.statusid,
		    success: asyncSendSuccess
		});
	    }, r.status == 'working' ? 1000 : 500);
	}else{
	    if(r.success){
		window.location.hash = '#campaigns/' + r.campaignid;
	    }else{
		Ext.get('send-notice').setStyle('display', 'none');
		var err = Ext.get('send-error');
		err.update(r.error);
		err.setStyle('display', 'block');
	    }
	}
    }
}
	
function showChart(ic, id){
    var icon = Ext.get(ic);
    var img = Ext.get(id + '-chart');
    img.setStyle('display', 'block');
    img.setXY(icon.getXY());
}
function hideChart(id){
    Ext.get(id + '-chart').setStyle('display', 'none');
}
function removeBounced(id){
    Ext.Ajax.request({
	url: backend + 'campaigns/' + id + '/removebounced',
	success: function(response){
	    r = Ext.decode(response.responseText);
	    ok = confirm("Are you sure you want to remove " + r.count + " subscribers?");
	    if(ok){
		Ext.Ajax.request({
		    url: backend + 'campaigns/' + id + '/removebounced',
		    params: {
			'confirmed': true
		    },
		    success: function(response){
			r = Ext.decode(response.responseText);
			e = Ext.get('removebounced-success');
			e.dom.innerHTML = "Successfully removed " + r.removed + " subscribers.";
			e.setStyle('display', 'block');
		    }
		});
	    }
	}
    });
}
function pauseCampaign(id){
    Ext.Ajax.request({
	url: backend + 'campaigns/' + id + '/pause',
	success: refresh
    });
}
function resumeCampaign(id){
    Ext.Ajax.request({
	url: backend + 'campaigns/' + id + '/start',
	success: refresh
    });
}
























var restore = [];
function addProperty(code, section){
    Ext.Ajax.request({
	url: backend + 'atc/property/' + code + '/' + section,
	success: function(response){
	    r = Ext.decode(response.responseText);
	    if(r.success){
		    Ext.get('section-' + section).addClass('hasproperties');
		    Ext.DomHelper.insertBefore(Ext.get('sep-' + section), '<div class="property editing type' + r.type + '" id="prop-'+r.insertid+'"><table><tr>' +
                        '<td class="prop-actions">' +
                            '<a class="normal" href="javascript:edit' + (r.type == 1 ? 'Simple' : '') + 'Property('+r.insertid+');"><img src="img/icons/pencil.png" alt="Edit" title="Edit" /></a>' +
                            '<a class="normal" href="javascript:delete' + (r.type == 1 ? 'Simple' : '') + 'Property('+r.insertid+');"><img src="img/icons/delete.png" alt="Delete" title="Delete" /></a>' +
                            '<a class="editing" href="javascript:save' + (r.type == 1 ? 'Simple' : '') + 'Property('+r.insertid+');"><img src="img/icons/tick.png" alt="Save" title="Save" /></a>' +
                            '<a class="editing" href="javascript:restore' + (r.type == 1 ? 'Simple' : '') + 'Property('+r.insertid+');"><img src="img/icons/cross.png" alt="Cancel" title="Cancel" /></a>' +

                        '</td>' + (r.type == 2 ? '<td class="prop-name"><textarea>New Property</textarea></td>' : '') + '<td class="prop-val"><textarea></textarea></td></tr></table></div>');

	    }
	}
    });
}
function addSimpleProperty(code, section){
    Ext.Ajax.request({
	url: backend + 'atc/property/' + code + '/' + section,
	success: function(response){
	    r = Ext.decode(response.responseText);
	    if(r.success){
		if(r.type == 2){
		    document.getElementById('section-'+section).innerHTML += '<div class="property editing" id="prop-'+r.insertid+'"><table><tr><td class="prop-actions"><a href="javascript:saveProperty('+r.insertid+');"><img src="img/icons/tick.png" alt="Save" title="Save" /></a><a href="javascript:deleteProperty('+r.insertid+', 1);"><img src="img/icons/cross.png" alt="Cancel" title="Cancel" /></a></td><td class="prop-name"><textarea>New property</textarea></td><td class="prop-val"><textarea></textarea></td></tr></table></div>';
		}
	    }
	}
    });
}    
function editProperty(propid){
    prop = Ext.get('prop-' + propid);
    prop.addClass('editing');
    propname = prop.child('.prop-name');
    propval = prop.child('.prop-val');
    restore[propid] = {'name': propname.dom.innerHTML, 'val': propval.dom.innerHTML};
    Ext.DomHelper.overwrite(propname, {
	tag: 'textarea',
	html: propname.dom.innerHTML
    });
    Ext.DomHelper.overwrite(propval, {
	tag: 'textarea',
	html: propval.dom.innerHTML
    });
}
function editSimpleProperty(propid){
    prop = Ext.get('prop-' + propid);
    prop.addClass('editing');
    propval = prop.child('.prop-val');
    restore[propid] = {'val': propval.dom.innerHTML};
    propactions = prop.child('.prop-actions');
    Ext.DomHelper.overwrite(propval, {
	tag: 'textarea',
	html: propval.dom.innerHTML
    });
}
function saveProperty(propid){	
    var prop = Ext.get('prop-' + propid);
    var propname = prop.child('.prop-name');
    var propval = prop.child('.prop-val');
    var pn = propname.down('textarea').getValue();
    var pv = propval.down('textarea').getValue();
    Ext.Ajax.request({
	url: backend + 'atc/property/' + propid,
	params: {'name': pn, 'content': pv},
	success: function(response){
	    r = Ext.decode(response.responseText);
	    if(r.success){
		prop.removeClass('editing');
		propname.dom.innerHTML = pn;
		propval.dom.innerHTML = pv;
	    }
	}
    });
}
function saveSimpleProperty(propid){	
    var prop = Ext.get('prop-' + propid);
    var propval = prop.child('.prop-val');
    var pv = propval.down('textarea').getValue();
    Ext.Ajax.request({
	url: 'backend.php/atc/property/' + propid,
	params: {'name': '', 'content': pv},
	success: function(response){
	    r = Ext.decode(response.responseText);
	    if(r.success){
		prop.removeClass('editing');
		propval.dom.innerHTML = pv;
	    }
	}
    });
}
function deleteProperty(propid, a, callback){
    if(a == 1){
	Ext.Ajax.request({
	    url: 'backend.php/atc/property/' + propid,
	    method: 'DELETE',
	    success: function(response){
		r = Ext.decode(response.responseText);
		if(r.success){
		    if(callback){
			callback.call(this, propid);
		    }
		    Ext.fly('prop-' + propid).remove();
		}
	    }
	});		    
    }else if(a == 2){
	Ext.fly('confirm-' + propid).remove();
    }else{
	p = Ext.get('prop-' + propid);
	box = '<div id="confirm-'+propid+'" class="confirm"><a href="javascript:void(0);" id="yes-'+propid+'">Yes</a><a href="javascript:deleteProperty('+propid+', 2);">No</a></div>';
	p.dom.innerHTML += box;
	Ext.fly('confirm-'+propid).setXY([p.getX(), p.getY() + 25]);
	Ext.fly('yes-'+propid).on('click', function(){
	    deleteProperty(propid, 1, callback);
	});
    }
}
function deleteSimpleProperty(propid, a){
    deleteProperty(propid, a, function(propid){
	section = Ext.get('prop-' + propid).up('div');
	section.removeClass('hasproperties');
    });
}    
function restoreProperty(propid){
    if(restore[propid]){
	prop = Ext.get('prop-' + propid);
        prop.removeClass('editing');
        propname = prop.child('.prop-name');
        propval = prop.child('.prop-val');
        propname.dom.innerHTML = restore[propid].name;
        propval.dom.innerHTML = restore[propid].val;
    }else{
	deleteProperty(propid, 1);
    }
}
function restoreSimpleProperty(propid){
    if(restore[propid]){
	prop = Ext.get('prop-' + propid);
        prop.removeClass('editing');
        propval = prop.child('.prop-val');
        propval.dom.innerHTML = restore[propid].val;
    }else{
	deleteSimpleProperty(propid, 1);
    }
}
function preview(code){
    if(ptimeout){
	clearTimeout(ptimeout);
    }
    //xhr to get preview data or cache ^^
    c = Ext.get('mc');
    p = Ext.get(Ext.DomHelper.append(c, {
	id: 'previewbox',
	tag: 'div',
	cls: 'preview',
	html: '<h3>Preview <a href="javascript:closePreview();" class="ic ic-pencil">Edit</a></h3>' + previewtemplates[currentPage.data.item.level].expand(currentPage.data)
    }));
    p.dom.style.width = (p.getWidth() - 20) + 'px';
    b = Ext.get('tcontainer');
    x = b.getX();
    p.dom.style.position = 'relative';
    p.setY(b.getY());
    p.setX(x + c.getWidth());
    b.setX(0 - c.getWidth(), true);
    p.setX(x, true);
}
function closePreview(){
    c = Ext.get('mc');
    p = Ext.get('previewbox');
    b = Ext.get('tcontainer');
    x = p.getX();
    p.setX(x);
    p.setX(x + c.getWidth(), true);
    b.setX(x, true);
    ptimeout = setTimeout(function(){
	p.remove();
    }, 500);
}
function getDate(str, format){
    if(str == null){
	str = '1970-01-01 00:00:01';
    }
    var dt = str.split(' ');
    var d = dt[0].split('-');
    var t = dt[1].split(':');
    return d[2] + '/' + d[1] + '/' + d[0];
    var date = new Date(parseInt(d[0]), parseInt(d[1])-1, parseInt(d[2]), parseInt(t[0]), parseInt(t[1]), parseInt(t[2]));
    if(format){
	return dateFormat(date, format);
    }
    return date;
}
function expandCategory(id){
    Ext.fly('category-' + id).setDisplayed(true);
    Ext.fly('catcontrol-' + id).set({href: 'javascript:collapseCategory('+id+');'});
}
function collapseCategory(id){
    Ext.fly('category-' + id).setDisplayed(false);
    Ext.fly('catcontrol-' + id).set({href: 'javascript:expandCategory('+id+');'});
}

function select_lists(cat){
    var div = document.getElementById('lists-' + cat);
    var cbs = div.getElementsByTagName('input');
    for(var i=0;i<cbs.length;i++){
	cbs[i].checked = div.className != 'allchecked';
    }
    if(div.className == 'allchecked'){
	div.className = '';
    }else{
	div.className = 'allchecked';
    }
}

function time_past(time, now){
    var d = now - time;
    if(d < 2){
	return 'now';
    }else if(d < 60){
	var dd = [d, 'second'];
    }else if(d < 3600){
	var dd = [Math.floor(d/60), 'minute'];
    }else if(d < 86400){
	var dd = [Math.floor(d/3600), 'hour'];
    }else{
	var dd = [Math.floor(d/86400), 'day'];
    }
    if(dd[0] != 1){
	dd[1] += 's';
    }
    return dd[0] + ' ' + dd[1] + ' ago';
}
function nice_size(b){
    var d = ["B", "KB", "MB", "GB", "TB"];
    var s = 1;
    for(var i=0;i<d.length;i++){
	s = Math.pow(1024, i);
	if(b < (s * 1024)){
	    return '<b>' + (Math.round(b / s * 100) / 100) + '</b> ' + d[i];
	}
    }
    return '<b>' + (Math.round(b / s * 100) / 100) + '</b> ' + d[i];
}
function nice_number(n){
    n += '';
    x = n.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while(rgx.test(x1)){
	x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
function filterCampaign(){
    var w = Ext.fly('campaignfilter').getValue();
    createCookie('campaignfilter', w, 365);
    refresh();
}
function filterHome(w){
    var c = readCookie('homefilter');
    if(c == null){
	var a = ['read', 'link', 'bounce', 'subscribe', 'unsubscribe'];
	createCookie('homefilter', a.join('|'), 365);
    }else{
	if(c == ''){
	    var a = [];
	}else{
	    var a = c.split('|');
	}
    }
    if(w == undefined){
	for(var i=0;i<a.length;i++){
	    Ext.select('div.toggle div.' + a[i]).item(0).addClass('selected');
	}
	return;
    }
    var el = Ext.select('div.toggle div.' + w).item(0);
    if(el.hasClass('selected')){
	el.removeClass('selected');
	a.remove(w);
    }else{
	el.addClass('selected');
	if(a.indexOf(w) == -1){
	    a[a.length] = w;
	}
    }
    var ga = [];
    for(var i=0;i<a.length;i++){
	if(a[i] != ''){
	    ga[ga.length] = a[i];
	}
    }
    createCookie('homefilter', ga.join('|'), 365);
    if(a.length == 0){
	Ext.select('table.activity').item(0).hide();
    }else{
	refresh();
    }
}
function createCookie(name,value,days){
    if(days){
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
    }else{
	var expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name){
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++){
	var c = ca[i];
	while(c.charAt(0)==' '){
	    c = c.substring(1,c.length);
	}
	if(c.indexOf(nameEQ) == 0){
	     return c.substring(nameEQ.length,c.length);
	}
    }
    return null;
}
function eraseCookie(name){
    createCookie(name, "", -1);
}
function resizePreview(){
    var iframe = document.getElementById('previewiframe');
    var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document;
    iframe.style.height = doc.body.scrollHeight + 'px';
}
