
core = {
    jstemplates: {},
    scriptNodes: {}
};

/*
    Application object.
    Keeps all windows descriptors
*/  
function Application(server) {
    this.tempxml = []
    this.logger = []
    this.autosave = 60000
    this.autorefresh = 0
    this.findDelay = 3000
    this.editMode = 0
    this.templates = []
    this.server = server+'server.php'
    this.host = server
    this.windows = []
    this.docking = []
    //this.customer = new Customer(this)
    //this.employee = new Employee(this)
    this.permission = new Permission(this)
    //this.company = new Company(this)
    //this.country = new Country(this)
    //this.currency = new Currency(this)
    //this.language = new Language(this)
    //this.admin = new Admin(this)
    this.themeSwitcher = new ThemeSwitcher(this);
    this.core_files = new core_files(this);
    this.core_perms = new core_perms(this);
    this.core_print = new core_print(this);
    this.auth = new Auth(this);
    
    // initialize user modules
    for(var i in core.modules) this[i] = eval('new ' + core.modules[i] + '(this);');
  
    this.__init()
    
    this.loadCount = 0;
}

Application.prototype.setWindowActive = function(win) {

    for(var i = 0; i < this.windows.length; i++) {
        if(this.windows[i].extwin.id == win.extwin.id) this.windows[i].active = true;
        else this.windows[i].active = false;
    }
}

Application.prototype.toggleTaskbarButton = function(button, state) {

    var buttons = Ext.getCmp('taskbar').findByType('button');
    for(var i = 0; i < buttons.length; i++) {
        if(buttons[i].id == button.id) buttons[i].toggle(true);
        else buttons[i].toggle(false);
    }
}

Application.prototype.broadcast = function(data) {

	for(var i = 0; i < this.windows.length; i++) this.windows[i].processBroadcast(data);
	for(var i = 0; i < this.docking.length; i++) this.docking[i].processBroadcast(data);
}


Application.prototype.addlog = function(xml){
  this.logger.push(xml)
}

Application.prototype.__preload = function(){
  if(this.timer) clearTimeout(this.timer)
  for(var i=0; i < this.templates.length; i++){
    if(!XML.Cache[this.templates[i]]){
      this.timer = setTimeout(this.__preload.bind(this), 50)
      return 0
    }
  } this.__auth()
}

Application.prototype.startLoad = function() {
    this.loadCount++;
    if(this.loadCount == 1){
        document.body.className = document.body.className + ' wait';
        this.status('<table border="0" cellpadding="0" cellspacing="0"><tr><td><img src="library/client/ext-3.0.0/resources/images/default/grid/loading.gif" /></td><td valign="middle" style="padding-left:7px;">Loading...</td></tr></table>');
    }
}

Application.prototype.stopLoad = function() {

	// safeguard
	if(this.loadCount == 0) return;

    this.loadCount--;
    if(this.loadCount == 0) {
        document.body.className = document.body.className.replace('wait','');
        this.status('');
    }
}

Application.prototype.status = function(text){
  //$('statusBar').innerHTML = text
  Ext.getCmp('statusBar').setText(text);
}

Application.prototype.__init = function(){
    var tmpl = new XML.Template()
    for(var i=0; i<this.templates.length; i++)
      tmpl.load(this.templates[i], this.server, 'template', 'get')
    this.status('Loading templates...')
  this.__preload()

}

Application.prototype.__auth = function() {

	this.status('Check user session...');
	var doc = new XML.Document('packet', XML.DefaultPacket('session', 'check'));
	(new XML.Request( function(response) {

		if(response.packet.xmldata.cdata == "1") this.restore();
		else this.showLogin();

	}.bind(this))).send(this.server, doc);
}

Application.prototype.showLogin = function(){
    this.status('')
    var win = new Window(this, 'Login');
    win.setContent({login:'login.js'},null,function(){}.bind(this))
}

Application.prototype.login = function(form, win) {

	var doc = new JSON.Document('packet', JSON.DefaultPacket('auth', 'login'));
	doc.packet.xmldata = this.parseForm(form);

	(new JSON.Request( function(response) {

		if(response.packet.type == "error") {
			this.showError(response.packet.xmldata,'Login failed');
			this.status('Authentication failed');
		} else {
			win.close();
			this.restore();
		}

	}.bind(this))).send(this.server, doc);
}

Application.prototype.statusMsg = function(title, format) {

	slideInMsg(title, format, 1.5);

    //var 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:application.createMsgBox(title, s)}, true);
    //m.slideIn('t').pause(1.5).ghost("t", {remove:true});

}

Application.prototype.createMsgBox = function(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('');

}

Application.prototype.displayLogoutButton = function(location, fname, lname) {

	var button_logout = Ext.getCmp('button_logout');
	button_logout.setText(location + ' - ' + fname + ' ' + lname);
	button_logout.show();
}

Application.prototype.checkAlerts = function(){
  //listing of all alert modules
  //price modification alerts
  //application.price.checkForPriceAlerts();
}

Application.prototype.logout = function(){
      this.status('Saving session...')
    var document = new XML.Document('packet', XML.DefaultPacket("session", "save"))
    document.packet.xmldata.window = []
    for(var i in this.docking){
        if(this.docking[i].param){
            document.packet.xmldata.window.push(this.docking[i].param.xmldata)
        }
    }
    var req = new XML.Request(function(){
  this.status("")
   if(this.timer) clearInterval(this.timer)
   var req = new XML.Request( function(response){
      if(response.packet.type == "response"){
        window.location.href = ""
      }
   })
   var doc = new XML.Document('packet', XML.DefaultPacket('auth', 'logout'))
   req.send(application.server, doc)
  }.bind(this))
    req.send(this.server, document);

}


Application.prototype.parseForm = function(form) {

	var fields = form.getValues();
	
	// append the disabled values to remain compatible with the server side code
	// do this only for the textfields fo now
	for(var i = 0; i < form.items.getCount(); i++) {
	    var item = form.items.itemAt(i);
	    if(item.xtype == 'textfield' && item.disabled && typeof(item.name) != 'undefined' && item.name != '') fields[item.name] = item.value;
	}
	
	for(var field in fields) fields[field] = {cdata : htmlspecialchars(fields[field])};
	return fields;
}


Application.prototype.save = function(){
    this.status('Saving session...')
    var doc = new XML.Document('packet', XML.DefaultPacket("session", "save"))
    doc.packet.xmldata.window = []
    for(var i in this.docking){
        if(this.docking[i].param){
            doc.packet.xmldata.window.push(this.docking[i].param.xmldata)
        }
    }
    var req = new XML.Request(function(){ this.status("")}.bind(this))
  req.send(this.server, doc);
}

Application.prototype.restore = function() {

    this.status('Restore session...');
    var document = new JSON.Document('packet', JSON.DefaultPacket("session", "restore"));
    //this.timer = setInterval(this.save.bind(this), this.autosave);

    (new JSON.Request( function(response) {
        //if(response.packet.xmldata.window) {
        
            this.permission_group = response.packet.xmldata.permission.group;
			
			var einfo = response.packet.xmldata.einfo;
			core.user = {
				uid: parseInt(einfo.uid),
				pgroup: einfo.pgroup
			};
			
			core.perms = response.packet.xmldata.perms;

            var application_bar = Ext.getCmp('application_bar');
            application_bar.add(core.jstemplates.toolbar.fill.call(this, response.packet.xmldata.perms, core.user.pgroup));
            application_bar.doLayout();

            this.displayLogoutButton(einfo.locationname, einfo.fname, einfo.lname);
            

            //$('__fname').innerHTML = response.packet.xmldata.einfo.fname
            //$('__lname').innerHTML = response.packet.xmldata.einfo.lname
            //$('__company').innerHTML = response.packet.xmldata.einfo.locationname
            //$('__logo').innerHTML = "<img src='images/logos/mx.png' width='60' height='45'/>";
            //$('__logo').innerHTML = "<img src='"+response.packet.xmldata.einfo.thumb+"' />";

            /*var win = response.packet.xmldata.window;
            if(!win.length) win = [win];
            for(var i=0; i < win.length; i++) {
                if(!win[i].options) break
                var conf = new XML.Document('xmldata', win[i]);
                var block = new Block(this, conf);
                var request = new XML.Document('packet', {});
                request.packet.query = win[i].query;
                block.loadContent(win[i].options.tmpl, request,function(responce) {

                    block= $(responce.xmldata.id);
                    if(block.param.xmldata.options.limit) this.createPager(responce.xmldata,block,'open');

                    if(block.param.xmldata.options.autorefresh) {
                        //block.autorefresh();
                        setSelectIndex($(block.param.xmldata.id+'_auto_refresh'),block.param.xmldata.options.autorefresh);
                        if(this.editMode == 0)$(block.param.xmldata.id+'_autorefresh').style.visibility="hidden";
                        else $(block.param.xmldata.id+'_autorefresh').style.visibility="visible";
                    }
                    if(block.param.xmldata.options.showfoxed) {
                        //block.autorefresh();
                        setSelectIndex($(block.param.xmldata.id+'_auto_refresh'),block.param.xmldata.options.autorefresh);
                        if(this.editMode == 0) $(block.param.xmldata.id+'_autorefresh').style.visibility="hidden";
                        else $(block.param.xmldata.id+'_autorefresh').style.visibility="visible";
                    }

                }.bind(this))
            }*/

            //SET THEME
            application.themeSwitcher.setTheme(einfo.settings.theme);
            //application.themeSwitcher.setBg(einfo.settings.bgUrl);

            application.status('');
        //}
    }.bind(this))).send(this.server, document);

    this.checkAlerts();
}

Application.prototype.getWindowByName = function(name){

    for(var i = 0; i < this.windows.length; i++)
        if(this.windows[i].name == name)
            return this.windows[i];
    
    for(var i = 0; i < this.docking.length; i++)
        if(this.docking[i].name == name)
            return this.docking[i];
    
    return null;
}
Application.prototype.saveState = function(name,xml){
  this.tempxml[name] = xml
}
Application.prototype.compareState = function(name,xml){
  if(this.tempxml[name] == xml){
    return true
  }else{
    if(confirm("You will loose all changes, Ok to proceed, Cancel to return to editing."))
      return false;
    else
      return true;
  }
  delete this.tempxml[name];
}
Application.prototype.findWindow = function(name){
  var wnd = this.getWindowByName(name)
   if(wnd){
    wnd.moveOnTop();
    wnd.refresh();
    return true
   }else return false

}
Application.prototype.setBlocker = function(){
  document.onkeydown=BlockKey;
  document.onkeydown=BlockKey;
    var overlay = _('div')
    var height = 0
    overlay.id = 'screensaver__'
    var height = (document.documentElement.clientHeight > document.body.clientHeight) ?
  document.documentElement.clientHeight : document.body.clientHeight
    overlay.style.height = height +  "px"
    overlay.className = 'overlay'
  overlay.style.backgroundColor='#CCCCCC';
    document.body.appendChild(overlay)
}
Application.prototype.removeBlocker = function(){
  document.onkeydown=null;
  var t = document.getElementById('screensaver__');
  t.parentNode.removeChild(t)
}
function BlockKey(e) {
    if(!e) e = window.event;
    var ctrl = e.ctrlKey;
    var code = e.keyCode;
  var r = String.fromCharCode(code).toLowerCase()
    if(ctrl && r == 'r' || code == 116) return false
}

Application.prototype.delay = function(event,field, value, module){
  if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)){
    application.find(field,value,module);
    clearTimeout(this.timer)
    return false;
  }
  else{
    if(this.timer) clearTimeout(this.timer)
    this.timer = setTimeout("application.find('"+field+"','"+value+"','"+module+"')", this.findDelay)
  }
  
}

Application.prototype.find = function(field, value, module){
  var doc = new XML.Document('packet', XML.DefaultPacket(module, 'search'))
  win = this.getWindowByName(module+'List')
  doc.packet.query.field = field
  doc.packet.query.value = value
  //  doc.packet.query.autorefresh = this.autorefresh 
  win.loadContent(module+'/list.xsl', doc, function(){ ///new 30.08.2007 ----------------------
    if(win.tagName == 'DIV'){
    if(this.editMode==0){
      win.autorefresh();         
      $(win.id+'_autorefresh').style.visibility= 'hidden'}
    else{
      win.autorefresh();         
      $(win.id+'_autorefresh').style.visibility= 'visible'}}  
  }.bind(this));
}


Application.prototype.sort = function(field, type, module){
  var doc = new XML.Document('packet', XML.DefaultPacket(module, 'sort'))
  win = this.getWindowByName(module+'List')
  doc.packet.query.field = field
  doc.packet.query.type = type
  //doc.packet.query.autorefresh = autorefresh
  win.loadContent(module+'/list.xsl', doc, function(){///new 30.08.2007 ----------------------
    if(win.tagName == 'DIV'){
      if(this.editMode==0){
        win.autorefresh();         
        $(win.id+'_autorefresh').style.visibility= 'hidden'}
      else{
        win.autorefresh();         
        $(win.id+'_autorefresh').style.visibility= 'visible'}}  
  }.bind(this));
}

Application.prototype.changerefresh = function(id,sel){   
  if(this.editMode==0)return;
  var b = $(id);
  p = this.getWindowByName(b.param.xmldata.options.name+'List')
  b.param.xmldata.options.autorefresh = sel.options[sel.selectedIndex].value
  //b.refresh();  
  if(b.timer) clearInterval(b.timer)
  b.interval = b.param.xmldata.options.autorefresh;
  b.timer = setInterval(b.autorefresh.bind(b), b.param.xmldata.options.autorefresh * 60000)
  this.autorefresh = sel.options[sel.selectedIndex].value
}

Application.prototype.showError = function(data,title){
    if(_defined(data.error))
        if(_defined(data.error.cdata))
            var data = data.error.cdata;
    Ext.MessageBox.show({
    title: title ? title : 'Error',
    msg: data,
    buttons: Ext.MessageBox.OK,
    icon: Ext.MessageBox.ERROR
    });
}


Application.prototype.accessDenied = function(){
  this.showError({error:{cdata:'You don\'t have permission to perform this task'}}, 'Access denied');
}

Application.prototype.createPager = function(xmldata,win,action){
  if(parseInt(win.param.xmldata.options.limit) > parseInt(xmldata.pager._count)) return;
  var pages = win.form.pager.parentNode;
  
  var d = _('div');
  var p = xmldata.pager;
  var count = parseInt(p._count);
  var links = parseInt(count / p.limit);
  var currPage =parseInt(win.param.xmldata.options.currPage)
  var l = links;
  var lk_plu = ((count % p.limit) != 0)?true:false;
  var pg=0;
  var ii=1;
  var i=0;
  if(l > 5){
    //d.innerHTML += "<a href='#'> &lt;&lt; </a>  ";
    //ii = parseInt(p._curr);
    //pg =  ii -1;
    //if((ii + 5) <= links) links = ii + 4;     
  } 
  //win.param.xmldata.options.currPage;
  
//  if(lk_plu && links+1 > currPage)currPage = 1;
  //else if(links+1 > currPage)currPage = 1;
  
  var o_z = lk_plu?1:0; 
  if(links < (currPage-o_z)){
    currPage = 1;
    win.param.xmldata.options.currPage = '1';
  }
  
  for(i=ii; i <= links; i++){   
  /*  var a = CreateNode('A',{href:'javascript:_void();'})
    a.innerHTML = pg+"-"+i*p.limit;
    d.appendChild(a);*/
    //d.innerHTML += "<a href='javascript:application."+win.param.xmldata.query.module+"."+param.action+"()'>"+pg+"-"+i*p.limit+"</a> ";
    if(i == currPage)   
    d.innerHTML += "<a style='text-decoration:none;font-size:9px;font-weight:bold' href='javascript:_void();'>"+pg+"-"+i*p.limit+"</a> ";
    else d.innerHTML += "<a style='font-size:9px'  href='javascript:application.goToPage(\""+i+"\",\""+win.id+"\",\""+action+"\")''>"+pg+"-"+i*p.limit+"</a> ";
    pg = i*p.limit;
  }
  if(lk_plu){
    if(i == currPage)   
       d.innerHTML += "<a style='text-decoration:none;font-size:9px;font-weight:bold' href='javascript:_void();'>"+pg+"-"+count+"</a> ";  
    else d.innerHTML += "<a style='font-size:9px' href='javascript:application.goToPage(\""+i+"\",\""+win.id+"\",\""+action+"\")''>"+pg+"-"+count+"</a> ";  
    
  }
  //if(l > 5)   d.innerHTML += "<a href='#'> &gt;&gt; </a> ";
  pages.appendChild(d);
}
Application.prototype.goToPage = function(page,win_id,ation){
  var win = $(win_id)
  var q =win.param.xmldata.query;
  win.param.xmldata.options.currPage = page
  var mtd ="application."+q.module+"."+ation;
  switch(q.action){
    case 'list':
    case 'open':
     mtd+="('',"+page+")";
    break;
    case 'itemList':
     mtd="application."+q.module+"._addItem('"+win.form.oid.value+"','',"+page+")";
    break;
    case 'inventorySort':
     mtd+="('"+q.field+"','','"+q.uid+"','"+win.form.oid.value+"')";
    break;
    case 'inventorySearch':
     mtd+="('"+q.field+"','"+q.value+"','"+q.uid+"','"+win.form.oid.value+"')";
    break;    
    case 'search':
     mtd+="('"+q.field+"','"+q.value+"','"+win_id+"','"+q.uid+"')";
    break;
    case 'sort':
     mtd+="('"+q.field+"','"+q.type+"','"+win_id+"','"+q.uid+"')";
    break;
  }
  eval(mtd) 
}

Application.prototype.error = function(code,response){
  if(code == 10001){
    title = 'Database error'; 
    var conf = new XML.Document('xmldata', {})
    conf.xmldata.options = {title: title, modale:"1"}
    conf.xmldata.button = [{image:'close.gif', action:'close'}]
    conf.xmldata.style = {width:'300px', height:'150px', position: 'absolute'}
    var win = new Window(this, conf)
    var doc = new XML.Document('xmldata', data)
    win.setContent('errors/databaseError.xsl', doc)
  }
}
