function SoCSystemController(){
    if(arguments.callee._singletonInstance){
	    return arguments.callee._singletonInstance;
	}
	arguments.callee._singletonInstance = this;

	var self = this; self.name = "SoCSystemController"; // MANDATORY

    this.ready_callback = false;

    this.baseDir = "";
    this.rootDir = "";
    this.appDir = "";
    this.homeDir = "";
    this.commonDir = "/mtd_down/common/";
    this.userDir = "/mtd_down/widgets/user/";
    this.systemDownDir = "/mtd_down/";
    this.browser = "HospitalityBrowser";
    this.browserDir = "/mtd_down/common/HospitalityBrowser/";

    this.downloader = {};
    this.systemUpdater = {};
    this.soc_api = {};
    this.lfd_api = {};
    this.nnavi_api = {};
    this.lfd_api1 = null;
    this.lfd_api2 = null;
    this.lfd_api3 = null;
    this.soc_api1 = null;
    this.lic = null;
    this.dataRead = null;

    this.FS = {};
    this.WIDGET = {};
    this.TV = {};
    this.PLUGIN = {};

    this.internet_connection = false;
    this.internet_check_busy = false;
    this.systemIsUpdating = false;

    this.os_loaded = false;

    this.sssp_version = 2;
    this.launcher_url = "";


    /* info system */
    this.pluginGetSoftwareVersion = null;
    this.pluginSerialNumber = null;
    this.nnavi_api = null;
    this.TVPlugin = null;
    this.firmwareVersion = null;
    this.subMicomVersion = null;
    this.modelTV = null;
    this.id_screen = "00";
    this.serialNumber = null;
    this.dataInfoSystem = null;
    this.sendInfoSystem = false;

    this.pluginPanel = null;
    this.screenshotServer = null;

    this.id_content_now = null;

    this.superEco = false;
    this.eco = false;
    this.debug = false;

    this.busy = false;
    this.SocketConnector = undefined;

    this.sync_master_supported = false;

    this.init = function(callback){
      self.SocketConnector = new SocketConnector(self);
        self.ready_callback = callback;
        if(!self.os_loaded){
            self.os_loaded = true;

            self.FS = new FileSystem();
            self.WIDGET = new Common.API.Widget();
            self.TV = new Common.API.TVKeyValue();
            self.PLUGIN = new Common.API.Plugin();
            self.PLUGIN.setOffWatchDog();

            self.downloader = document.getElementById('downloadPlugin');
            self.systemUpdater = document.getElementById('systemUpdatePlugin');
            self.lfd_api2 = document.getElementById('lfdPlugin2');
            self.lfd_api = document.getElementById('lfdPlugin');
            self.lfd_api.Open('LFD', '1.000', 'LFD');

            self.lfd_api.OnEvent = function(event, a, b) {
                self.log("LFD Plugin :  Event Type : " + event + " A : " + a + " B :" + b + "]") ;
            };
            self.lfd_api3 = document.getElementById('lfdPlugin3');
            self.lfd_api3.OnEvent = function(event, a, b) {
                self.log("LFD Plugin :  Event Type : " + event + "]") ;
            };
            self.lfd_api3.Open('LFD', '1.000', 'LFD');

            self.soc_storage = document.getElementById('storagePluginSef');
            self.soc_storage.Open("Storage", "1.000", "Storage");
            self.soc_api = document.getElementById('socPlugin');
            self.soc_api.Open('FileSystem', '1.000', 'FileSystem');
            self.soc_api.Execute('SetWidgetInfo',2,"/");
            self.soc_api.OnEvent = function(event, a, b) {
                self.log("FileSystem Plugin :  Event Type : " + event + " A : " + a + " B :" + b + "]") ;
            };
            self.lfd_api1 = document.getElementById('lfdPlugin1');
            self.lfd_api1.Open('LFD', '1.000', 'LFD');
            self.lfd_api1.OnEvent = function(event, a, b) {};
            self.soc_api1 = document.getElementById('socPlugin1');
            self.soc_api1.Open('FileSystem', '1.000', 'FileSystem');
            self.soc_api1.Execute('SetWidgetInfo',2,"/");
            self.soc_api1.OnEvent = function(event, a, b) {};
            self.enableTVKeys();
            self.WIDGET.sendReadyEvent();

            self.sssp_version = self.getSSSPVersion();
            //socketConnector.sssp_version = self.sssp_version;
            var executes_offline = false;
            if(location.href.indexOf("offline.html") > 0){
                executes_offline = true;
            }
            self.log("SSSP Version : "+self.sssp_version+" Executes Offline : "+executes_offline);


            /**************/
            self.nnavi_api = document.getElementById('nnaviPlugin');
            self.nnavi_api.ActivateReady();

            self.homeDir = widget.id+"/";
            self.baseDir = self.commonDir+widget.id+"/";
            self.rootDir = "file://"+self.baseDir;

            if(self.sssp_version == 1){
                self.appDir = self.baseDir;
            }else{
                self.appDir = self.userDir+widget.id+"/";
            }
            /**************/
            if(self.sssp_version > 1){
                var numUsb = self.soc_storage.Execute('GetUSBListSize');
                try{
                    if(numUsb > 0){
                        self.usb = true;
                        self.usbDir = '/$USB_DIR/sda1/';
                        var contentsSD = self.soc_api.Execute("GetListFiles",self.usbDir);

                        if(contentsSD != "" && contentsSD != null){
                            contentsSD = JSON.parse(contentsSD);
                            for (var i = 0; i < contentsSD.length - 1; i++) {
                                if(contentsSD[i] == "offline.data.zip"){
                                    self.unzipFile(self.usbDir+"offline.data.zip",self.usbDir+"offline.data/", function(ok,file_ref,params){
                                        if(ok){
                                            var exists = self.soc_api.Execute("IsExistedPath",self.usbDir+"offline.data/xmls/week.tstamp");
                                            if(exists){
                                                $.ajax({
                                                    url:self.usbDir+"offline.data/xmls/week.tstamp",
                                                    dataType:'text',
                                                    cache: false,
                                                    success: function( dataUSB ) {
                                                        if(dataUSB.length > 0){
                                                            exists = self.soc_api.Execute("IsExistedPath",self.baseDir+self.ROUTES['XML'].path+self.ROUTES['TIMESTAMP'].path);
                                                            if(exists){
                                                                self.readFile(self.ROUTES['XML'].path+self.ROUTES['TIMESTAMP'].path,function(data,file_ref,params){
                                                                    var tst_in = parseInt(data);
                                                                    var tst_usb = parseInt(dataUSB);
                                                                    if(tst_usb > tst_in){
                                                                        self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/1.xml", self.baseDir+self.ROUTES['XML'].path+"1.xml");
                                                                        self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/2.xml", self.baseDir+self.ROUTES['XML'].path+"2.xml");
                                                                        self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/3.xml", self.baseDir+self.ROUTES['XML'].path+"3.xml");
                                                                        self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/4.xml", self.baseDir+self.ROUTES['XML'].path+"4.xml");
                                                                        self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/5.xml", self.baseDir+self.ROUTES['XML'].path+"5.xml");
                                                                        self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/6.xml", self.baseDir+self.ROUTES['XML'].path+"6.xml");
                                                                        self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/7.xml", self.baseDir+self.ROUTES['XML'].path+"7.xml");
                                                                        var contenSD = self.soc_api.Execute("GetListFiles",self.usbDir+"offline.data/content/");
                                                                        if(contenSD != "" && contenSD != null){
                                                                            contenSD = JSON.parse(contenSD);
                                                                            for (var j = 0; j < contenSD.length - 1; j++) {
                                                                                self.soc_api.Execute("Copy", self.usbDir+"offline.data/content/"+contenSD[j], self.baseDir+self.ROUTES['CONTENT'].path+contenSD[j]);
                                                                            }
                                                                        }
                                                                    }
                                                                });
                                                            }
                                                            else{
                                                                self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/1.xml", self.baseDir+self.ROUTES['XML'].path+"1.xml");
                                                                self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/2.xml", self.baseDir+self.ROUTES['XML'].path+"2.xml");
                                                                self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/3.xml", self.baseDir+self.ROUTES['XML'].path+"3.xml");
                                                                self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/4.xml", self.baseDir+self.ROUTES['XML'].path+"4.xml");
                                                                self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/5.xml", self.baseDir+self.ROUTES['XML'].path+"5.xml");
                                                                self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/6.xml", self.baseDir+self.ROUTES['XML'].path+"6.xml");
                                                                self.soc_api.Execute("Copy", self.usbDir+"offline.data/xmls/7.xml", self.baseDir+self.ROUTES['XML'].path+"7.xml");
                                                                var contenSD = self.soc_api.Execute("GetListFiles",self.usbDir+"offline.data/content/");
                                                                if(contenSD != "" && contenSD != null){
                                                                    contenSD = JSON.parse(contenSD);
                                                                    for (var j = 0; j < contenSD.length - 1; j++) {
                                                                        self.soc_api.Execute("Copy", self.usbDir+"offline.data/content/"+contenSD[j], self.baseDir+self.ROUTES['CONTENT'].path+contenSD[j]);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    },
                                                    error: function(e){
                                                        self.log("Error read de usb");
                                                        $("#starter").html("Error read de usb");
                                                    }
                                                });
                                            }
                                            else{
                                                self.log("xmls/week.tstamp in usb not exists");
                                                $("#starter").html("xmls/week.tstamp in usb not exists");
                                            }
                                        }
                                        else{
                                            self.log("Error unzip offline.data");
                                            $("#starter").html("Error unzip offline.data");
                                        }
                                    });
                                }
                            }
                        }
                    }
                }
                catch(e){
                    self.log(e);
                    $("#starter").html("Error usb -  offline.data");
                }
            }

            if(executes_offline && self.sssp_version > 1){
                $("#starter").html("System started abnormally ... rebooting in 5s");
                self.readFile(self.ROUTES['REBOOT'].path,function(value,file_ref,params){
                    if(value != "" && value != undefined && value != "undefined" && value != null && value != "null"){
                        try{
                            if(value.length > 0){
                                var reboots = parseInt(value);
                                if(reboots < 5){
                                    self.writeFile(self.ROUTES['REBOOT'].path,(reboots+1),function(ok,file_ref,params){
                                        self.notifyError(self.ERROR['TRANSFER_SERVICE']+17,self.name+": Rebood required for SOC. System started abnormally ... rebooting in 10s.");
                                        setTimeout(function(){
                                            self.rebootSystem(self.platform);
                                        }, 10000);
                                    });
                                }
                                else{
                                    var ob='<img  width="1920" height="1080" src="'+self.ROUTES['STYLE'].path+'contactTechnicalSupport.jpg">';
                                    document.getElementById("emergency").innerHTML=ob;
                                }
                            }
                            else{
                                self.writeFile(self.ROUTES['REBOOT'].path,1,function(ok,file_ref,params){
                                    self.notifyError(self.ERROR['TRANSFER_SERVICE']+17,self.name+": Rebood required for SOC. System started abnormally ... rebooting in 10s.");
                                    setTimeout(function(){
                                        self.rebootSystem(self.platform);
                                    }, 10000);
                                });
                            }
                        }catch(e){
                            self.notifyError(self.ERROR['TRANSFER_SERVICE']+17,self.name+": Rebood required for SOC. System started abnormally ... rebooting in 10s.");
                            setTimeout(function(){
                                self.rebootSystem(self.platform);
                            }, 10000);

                        }
                    }
                    else{
                        self.writeFile(self.ROUTES['REBOOT'].path,1,function(ok,file_ref,params){
                            self.notifyError(self.ERROR['TRANSFER_SERVICE']+17,self.name+": Rebood required for SOC. System started abnormally ... rebooting in 10s.");
                            setTimeout(function(){
                                self.rebootSystem(self.platform);
                            }, 10000);
                        });
                    }
                });
            }else{
                //self.writeFile(self.ROUTES['REBOOT'].path,0,function(ok,file_ref,params){});
                self.deleteFile(self.ROUTES['REBOOT'].path);


                $("#starter").html("Checking system ...");
                self.checkFolders();
                self.checkFiles();

                var total_storage = parseInt(self.soc_api.Execute("GetTotalSize"));
                var free_storage = parseInt(self.soc_api.Execute("GetFreeSize"));
                total_storage = parseInt(total_storage/1024/1024);
                free_storage = parseInt(free_storage/1024/1024);

                self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+10,self.name+": Using LFD SSSP"+self.sssp_version+" Version with Total Storage : "+total_storage+"Mb & Free Storage : "+free_storage+"Mb launcher URL : "+self.launcher_url);

                $("#starter").html("System : SSSP"+self.sssp_version+" Version with Total Storage : "+total_storage+"Mb & Free Storage : "+free_storage+"Mb - Executes Offline : "+executes_offline+" Starting ...");

                if(self.sssp_version == 1){
                    self.launcher_url = location.href;
                    self.installOfflineApp(executes_offline);
                }else{
                    self.pluginLFDControl = document.getElementById("pluginSEF_FW");
                    self.pluginLFDControl.Open("LFDControl", "1.000", "LFDControl");

                    var test= self.pluginLFDControl.Execute("GetURLLauncherAddress")
                    if(test){
                      self.launcher_url = test;
                    }
                    else{
                      self.launcher_url = "Using SSSP v"+self.sssp_version;
                    }
                    self.copyAppToBrowserDir();
                    self.ready();
                }
            }
        }else{
            self.ready();
        }
    };

    this.ready = function(){
        self.ready_callback();
    };

    this.getSSSPVersion = function(){
        var info = navigator.userAgent || navigator.vendor || window.opera;
        if(info.indexOf('Linux/SmartTV+2015') > 0){
            return 3;
        }else if (info.indexOf('Linux/SmartTV+2014') > 0){
            return 2;
        }else if (info.indexOf('Linux/SmartTV') > 0){
            return 1;
        }else{
            return 0;
        }
    };

    this.enableTVKeys = function(){
        document.getElementById("anchor").focus();
    };

    this.createTrayIcon = function(){
        // none
    };

    this.checkFolders = function(){
        var FS = new FileSystem();
        var exists = false;
        for(var route in self.ROUTES){
            if(self.ROUTES[route].isFolder && !self.ROUTES[route].exists){
                exists = self.soc_api.Execute("IsExistedPath", self.baseDir+self.ROUTES[route].path);
                if(!exists){
                    var result = FS.createCommonDir(self.homeDir+self.ROUTES[route].path);
                    self.log("Create result : "+result+" for dir : "+self.homeDir+self.ROUTES[route].path);
                }else{
                    self.log(self.baseDir+self.ROUTES[route].path+" folder EXISTS");
                }
                self.ROUTES[route].exists = exists;
            }
        }
    };

    this.checkFiles = function(){
        var old_root_folder = "";
        // COMPATIBILITY OLD SOC
        exists = self.soc_api.Execute("IsExistedPath","core.json");
        if(exists){
            old_root_folder = self.homeDir;
        }else{
            exists = self.soc_api.Execute("IsExistedPath","/mtd_down/common/mtd_down/common/"+self.homeDir+"core.json");
            if(exists){
                old_root_folder = "/mtd_down/common/"+self.homeDir;
                self.log("OLD Core Exists ... in : "+old_root_folder);
            }
        }

        if(exists){
            self.log("Old Core Exists ... ");
            exists = self.soc_api.Execute("IsExistedPath",self.homeDir+self.ROUTES['LICENSE'].path);
            if(!exists){
                self.log("Admira License NO Exists ... looking for : "+old_root_folder+"core.json");
                var fileEntry = self.FS.openCommonFile(old_root_folder+"core.json",'r');
                if(fileEntry){
                    var data = fileEntry.readAll();
                    self.log("Reading old license info  ... "+data);
                    self.FS.closeCommonFile(fileEntry);
                    var old_core = JSON.parse(data);
                    if(typeof(old_core.apiKey) !== "undefined"){
                        fileEntry = self.FS.openCommonFile(self.homeDir+self.ROUTES['LICENSE'].path,'w');
                        if(fileEntry){
                            fileEntry.writeAll(""+old_core.apiKey);
                            self.FS.closeCommonFile(fileEntry);
                            self.log("Old Info copied to Admira license file with key  ... "+old_core.apiKey);
                            fileEntry = self.FS.openCommonFile(self.homeDir+self.ROUTES['CORE'].path,'w');
                            if(fileEntry){
                                var core_xml = '<?xml version="1.0" encoding="utf-8" ?><core><config><id>'+old_core.plvID+'</id><api_ver>'+old_core.apiVer+'</api_ver><api_url>'+old_core.apiURL+'</api_url></config><server url="'+old_core.filesURL+'"/></core>';
                                fileEntry.writeAll(""+core_xml);
                                self.FS.closeCommonFile(fileEntry);
                            }
                        }
                    }
                }else{
                    self.log("COULD NOT OPEN Old Core JSON file ... ");
                    self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+1,self.name+": Function checkFiles() failed : COULD NOT OPEN Old Core JSON file ...");
                }
            }
        }else{
            var exists = self.soc_api.Execute("IsExistedPath", self.baseDir+self.ROUTES['CORE'].path);
            if(!exists){
                var core_xml = self.FS.openCommonFile(self.homeDir+self.ROUTES['CORE'].path,'w');
                if(core_xml){
                    self.log("Writting core file ... ");
                    core_xml.writeAll('<?xml version="1.0" encoding="utf-8" ?><core><config><id>0</id><api_ver>3.0</api_ver><api_url>apilb.admira.com</api_url></config><server url="apilb.admira.com"/></core>');
                    self.FS.closeCommonFile(core_xml);
                    self.log("Writting core file ... completed");
                }else{
                    self.log("Writting core file ... NOT ok");
                }
            }else{
                self.log("Core XML file ... OK");
            }
            var filename = self.getDayOfWeek()+".xml";
            exists = self.soc_api.Execute("IsExistedPath", self.baseDir+self.ROUTES['XML'].path+filename);
            if(!exists){
                var xml_data = '<?xml version="1.0"?><admira timestamp="1" version="1.0" status="ok"><archive/><playlist><loop/></playlist><screens /><config volume="100" fullscreen="true" mode="1" always_on_top="true" plv_name="Debug Name" project_name="Debug Project" time="30" plv_id="0" quit_on_click="true" activated="false" domain="" api_key="" live_url="" live_recheck_seconds="" live_send_id=""><resolution x="100" y="100" width="300" height="300" /></config></admira>';
                var xml_file = self.FS.openCommonFile(self.homeDir+self.ROUTES['XML'].path+filename,'w');
                if(xml_file){
                    self.log("Writting xml file ... ");
                    xml_file.writeAll(xml_data);
                    self.FS.closeCommonFile(xml_file);
                    self.log("Writting xml file ... completed");
                }else{
                    self.log("Writting xml file ... NOT ok");
                }
            }else{
                self.log("XML day file ... OK");
            }
            exists = self.soc_api.Execute("IsExistedPath",self.baseDir+self.ROUTES['XML'].path+self.ROUTES['TIMESTAMP'].path);
            if(!exists){
                var tstamp_file = self.FS.openCommonFile(self.homeDir+self.ROUTES['XML'].path+"/"+self.ROUTES['TIMESTAMP'].path,'w');
                if(tstamp_file){
                    self.log("Writting timestamp file ... ");
                    tstamp_file.writeAll('1');
                    self.FS.closeCommonFile(tstamp_file);
                    self.log("Writting timestamp file ... completed");
                }else{
                    self.log("Writting timestamp file ... NOT ok");
                }
            }else{
                self.log("Timestamp file ... OK");
            }
        }

    };

    this.installOfflineApp = function(executes_offline){
      if(!executes_offline){
          $.get("./admira.ver",function(new_version){
              var installed_version = self.readFile("installed.ver");
              installed_version = installed_version.replace(/[^a-zA-Z0-9]/g, '');
              new_version = new_version.replace(/[^a-zA-Z0-9]/g, '');
              self.log("Package Ver : "+new_version+" Installed Ver: "+installed_version);
              if(new_version != installed_version){
                  $("#starter").html("System : SSSP"+self.sssp_version+" Version - Executes Offline : "+executes_offline+" Downloading Offline App ...");
                  var options = {'filename':'install.zip'}; self.downloadFile(self.launcher_url+"install.zip",self.ROUTES['TMP'].path,self.onAppDownloadComplete,options);
              }else{
                  location.href = self.rootDir+"offline.html";
              }
          }).fail(function(){
              var installed = self.readFile("installed.ver");
              self.log("Offline App : System started offline mode with ver : "+installed);
              self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+14,self.name+": Offline App : System started offline mode via offline.html local file");
              self.rootDir="";
              self.ready();
          });
      }else{
          var installed = self.readFile("installed.ver");
          self.log("Offline App : System started offline mode with ver : "+installed);
          self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+14,self.name+": Offline App : System started offline mode via offline.html local file");
          self.rootDir="";
          self.ready();
          
      }
  };

    this.onAppDownloadComplete = function(ok,url,params){
        if(ok){
            $("#starter").html("System : SSSP"+self.sssp_version+" Version - Installing Offline App ...");
            self.unzipFile(self.ROUTES['TMP'].path+"install.zip",self.ROUTES['TMP'].path+"install/", function(ok,file_ref,params){
                self.deleteFile(self.ROUTES['TMP'].path+"install.zip");
                if(ok){
                    var exists = self.soc_api.Execute("IsExistedPath",self.baseDir+self.ROUTES['TMP'].path+"install/app/");
                    if(exists){
                        self.deleteFile("app/");
                        self.soc_api.Execute("Move", self.baseDir+self.ROUTES['TMP'].path+"install/app/", self.baseDir);
                        self.deleteFile(self.ROUTES['VER'].path);
                        self.soc_api.Execute("Move", self.baseDir+self.ROUTES['TMP'].path+"install/"+self.ROUTES['VER'].path, self.baseDir);
                        self.soc_api.Execute("Copy", self.baseDir+self.ROUTES['VER'].path,self.baseDir+"installed.ver");
                        self.deleteFile("offline.html");
                        self.soc_api.Execute("Move", self.baseDir+self.ROUTES['TMP'].path+"install/"+self.ROUTES['MAIN_HTML'].path, self.baseDir+"offline.html");
                        self.log("Offline App Installed / Updated : "+self.rootDir+"offline.html");
                        self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+14,self.name+": Offline App : installed correctly");
                        location.href = self.rootDir+"offline.html";
                        self.ready();
                    }else{
                        self.log("Installation App NOT FOUND !!!");
                        self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+14,self.name+": Offline App : app/ folder not found !");
                        location.href = self.rootDir+"offline.html";
                        self.ready();
                    }
                }else{
                    self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+14,self.name+": Offline App : unable to unzip install.zip file");
                    self.log("Install App NOT unzipped !");
                    location.href = self.rootDir+"offline.html";
                    self.ready();
                }
                //location.href = self.rootDir+"offline.html";
            });
        }else{
            self.systemIsUpdating = false;
            self.log("Installation Package not found !");
            self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+14,self.name+": Offline App : install.zip file not found !!!");
            self.ready();
        }
    };

    this.writeFile = function(filename,value,callback,params){
        //self.log("Trying to write file : "+self.homeDir+"/"+filename);
        var fileEntry = self.FS.openCommonFile(self.homeDir+"/"+filename, 'w');
        if(fileEntry){
            fileEntry.writeAll(value);
            self.FS.closeCommonFile(fileEntry);
            fileEntry = null;
            if(typeof(callback) !== "undefined"){
                callback(true,filename,params);
            }
        }else{
            fileEntry = null;
            if(typeof(callback) !== "undefined"){
                callback(false,filename,params);
            }
        }
    };

    this.readFile = function(filename,callback,params){
        //self.log("File Read ? "+filename);
        try{
        var data = "";
        var fileEntry = self.FS.openCommonFile(self.homeDir+filename,'r');
        if(fileEntry){
            data = fileEntry.readAll();
            self.FS.closeCommonFile(fileEntry);
        }
        fileEntry = null;
    	if(typeof(callback) !== "undefined"){
            callback(data,filename,params);
        }else{
            return data;
        }
        }
        catch(err){
            self.log(e);
            return undefined;
        }
    };
    this.readFile2 = function(filename,callback,params){
        //self.log("File Read ? "+filename);
        self.log("Read file filename: "+filename);

        var data = "";
        var fileEntry = self.FS.openCommonFile(filename,'r');
        if(fileEntry){
            data = fileEntry.readAll();
            self.FS.closeCommonFile(fileEntry);
        }
        fileEntry = null;
        if(typeof(callback) !== "undefined"){
            callback(data,filename,params);
        }else{
            return data;
        }
    };

    this.appendFile = function(filename,value,callback,params){
        var data = "";
        var fileEntry = self.FS.openCommonFile(self.homeDir+filename,'a');
        if(fileEntry){
            fileEntry.writeAll(value);
            self.FS.closeCommonFile(fileEntry);
            if(typeof(callback) !== "undefined"){
                callback(true,filename,params);
            }
        }else{
            if(typeof(callback) !== "undefined"){
                callback(false,filename,params);
            }
        }
        fileEntry = null;
    };

    this.makeDir = function(path,callback,params){
        self.FS.createCommonDir(self.homeDir+path);
        if(typeof(callback) !== "undefined"){
            callback(true,path,params); // COMPATIBILITY
        }
    };

    this.fileHash = function(filename,callback,params){
      // TODO
      if(typeof(callback) !== "undefined"){
          callback("0",filename,params);
      }
    };

    this.fileExists = function(filename,callback,params){
        //self.log("File Exists ? "+filename);
	    var result = self.FS.isValidCommonPath(self.homeDir+filename);
        //var result = self.soc_api.Execute("IsExistedPath", self.homeDir+filename);
        var ok = false;
        if(result === 1 || result === 2){
            ok = true;
        }
        result = null;
    	if(typeof(callback) !== "undefined"){
            callback(ok,filename,params);
        }
    };

    this.modificationDate = function(filename,callback,params){
        // THIS SYSTEM DOES NOT HAVE THIS FUNCTIONALITY
    };

    this.downloadFile = function(url,destFolder,callback,params){
        var upgrade_file = "";
        var filename = url;
        filename = filename.substring(filename.lastIndexOf("/")+1,filename.length);
        if(typeof(params) !== "undefined"){
            if(typeof(params.filename) !== "undefined"){
                filename = params.filename;
                upgrade_file = filename;
            }
        }

        if(upgrade_file == "upgrade.zip"){
            self.downloadSystemUpdate(url,destFolder,callback,params);
        }else if(upgrade_file == "install.zip"){
            self.downloadSystemUpdate(url,destFolder,callback,params);
        }else{
             self.downloader.OnComplete = function(message) {
                var status = message.split("?");
                if(status[0] == 1001){
                    self.log(filename+" "+status[1] + "%");
                    return;
                }

                if(status[0] == 1000) {
                    var ok = false;
                    if(status[1] == 1){
                        self.log("Download Complete : "+filename+" msg: " + message);
                        try{
                            var source = self.baseDir+self.ROUTES['TMP'].path+filename;
                            var destination = self.baseDir+destFolder+filename;
                            self.soc_api.Execute("Move", source, destination);
                            ok = true;
                        }catch(ex){
                            self.log("Can't move file  :"+self.homeDir+self.ROUTES['TMP'].path+filename);
                            self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+2,self.name+": Function downloadFile() failed : Can not move file  :"+self.homeDir+self.ROUTES['TMP'].path+filename);
                        }
                    }else{
                        self.log("Download Error !!! = "+filename+" msg: " + message);
                        self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+3,self.name+": Function downloadFile() failed : Download Error !!! = "+filename+" msg: " + message);
                    }
                    if(typeof(callback) !== "undefined"){
                        callback(ok,url,params);
                    }
                }
            };

            self.soc_api.Execute("Delete",self.baseDir+self.ROUTES['TMP'].path+filename);
            self.log("Start Download = "+filename+" from : " + url);
            self.downloader.StartDownFile(url + "?" + new Date().getTime(),self.baseDir+self.ROUTES['TMP'].path+filename,0,10);
        }
    };

    this.downloadSystemUpdate = function(url,destFolder,callback,params){
        self.systemIsUpdating = true;
        var filename = url;
        filename = filename.substring(filename.lastIndexOf("/")+1,filename.length);
        if(typeof(params) !== "undefined"){
            if(typeof(params.filename) !== "undefined"){
                filename = params.filename;
            }
        }
        self.systemUpdater.OnComplete = function(message) {
            var status = message.split("?");
            if(status[0] == 1001){
                self.log("System Update Downloading ... "+filename+" : "+status[1] + "%");
                return;
            }

            if (status[0] == 1000) {
                var ok = false;
                if(status[1] == 1){
                    self.log("System Update Download Complete : "+filename+" msg: " + message);
                    try{
                        var source = self.baseDir+self.ROUTES['TMP'].path+filename;
                        var destination = self.baseDir+destFolder+filename;
                        self.soc_api.Execute("Move", source, destination);
                        ok = true;
                        self.log("File : "+source+" moved to : "+destination);
                    }catch(ex){
	                    self.log("Can't move file  :"+self.homeDir+self.ROUTES['TMP'].path+filename);
                        self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+4,self.name+": Function downloadSystemUpdate() failed : Can not move file  :"+self.homeDir+self.ROUTES['TMP'].path+filename);
	                }
                }else{
                    self.log("Download Error !!! = "+filename+" msg: " + message+" status: "+status[1]);
                    self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+5,self.name+": Function downloadSystemUpdate() failed : Download Error !!! = "+filename+" msg: " + message);
                }
                if(typeof(callback) !== "undefined"){
                    callback(ok,url,params);
                }
            }
        };
        self.soc_api.Execute("Delete", self.baseDir+self.ROUTES['TMP'].path+filename);
        self.systemUpdater.StartDownFile(url,self.baseDir+self.ROUTES['TMP'].path+filename,0,10);
    };

    this.unzipFile = function(filename,destFolder,callback,params){
        self.log("Try unzip "+self.baseDir+filename+" to : "+self.baseDir+destFolder);
        var status = parseInt(self.soc_api.Execute("Unzip",self.baseDir+filename,self.baseDir+destFolder));
        if(typeof(callback) !== "undefined"){
            callback(Boolean(status),filename,params);
        }
    };

    this.readDirectory = function(directory,callback,params){
        //self.log("ReadDir ? "+directory);
        var files = [];
        var filesList = self.soc_api.Execute('GetListFiles',self.baseDir+directory);
        if(typeof(filesList) !== "undefined" && filesList.length !== undefined && filesList.length !== "undefined" ){
            filesList = filesList.substring(1,filesList.length-3);
            files = filesList.split(",");
            files.pop(); // WARNING ... can conflict other functions ... ensure there's no affected elements or it's always a void element in SOC.
        }
        else{
            var result = self.FS.createCommonDir("/mtd_down/common/HospitalityBrowser/"+directory);
            self.log("Create result : "+result+" for dir : "+self.homeDir+directory);
            if(result == false){
                self.soc_api.Execute("Delete","/mtd_down/common/HospitalityBrowser/"+directory);
            }
        }

        if(typeof(callback) !== "undefined"){
            callback(files,directory,params);
        }
        files = null;
        filesList = null;
    };

    this.watchDirectory = function(directory,compare_files,callback,params){
        // TODO
    };

    this.deleteFile = function(filename,callback,params){
        var result = self.soc_api.Execute("Delete",self.baseDir+filename);
        var ok = false;
        if(result === 1){
            ok = true;
        }
        if(typeof(callback) !== "undefined"){
            callback(ok,filename,params);
        }
    };

    this.moveFile = function(source,destination,callback,params){
        self.log("Moving : "+source+" to "+destination);
        var result = self.soc_api.Execute('Move', source, destination);
        self.log("Result = "+result);
        var ok = false;
        if(result === 1){
            ok = true;
        }
        if(typeof(callback) !== "undefined"){
            callback(ok,"",params);
        }
    };

    this.systemUpdate = function(update_folder){
        self.log("Updating the system .... ");
        var result = 0;
        var errors = false;
        self.log("Check backup : "+self.baseDir+"app_backup/");
        var exists = self.soc_api.Execute("IsExistedPath",self.baseDir+"app_backup/");
        if(exists === 1){
            self.log("Delete Backup");
            self.soc_api.Execute("Delete",self.baseDir+"app_backup");
        }else{
            self.log("No previous Backup.... Createng");
        }
        result = self.soc_api.Execute('Move',self.appDir+"app",self.baseDir+"app_backup");
        self.log(result+" : Moving "+self.appDir+"app"+" to "+self.baseDir+"app_backup");
        if(result === 1){
            self.log("Backup Created");
            result = self.soc_api.Execute('Move',self.baseDir+update_folder+"files/"+self.ROUTES['VER'].path,self.baseDir+self.ROUTES['VER'].path);
            self.log(result+" : Moving "+self.baseDir+update_folder+"files/"+self.ROUTES['VER'].path+" to "+self.baseDir+self.ROUTES['VER'].path);
            if(result !== 1){errors = true;}
            self.log("Move VER result : "+result);

            result = self.soc_api.Execute('Move', self.baseDir+update_folder+"files/"+self.ROUTES['MAIN_HTML'].path,self.appDir+self.ROUTES['MAIN_HTML'].path);
            self.log(result+" : Moving "+self.baseDir+update_folder+"files/"+self.ROUTES['MAIN_HTML'].path+" to "+self.appDir+self.ROUTES['MAIN_HTML'].path);
            if(result !== 1){
                errors = true;
            }else{
                result = self.soc_api.Execute('Copy',self.appDir+self.ROUTES['MAIN_HTML'].path,self.appDir+"offline.html");
                self.log(result+" : Copying "+self.appDir+self.ROUTES['MAIN_HTML'].path+" to "+self.appDir+"offline.html");
            }
            self.log("Move HTML result : "+result);

            result = self.soc_api.Execute('Move', self.baseDir+update_folder+"files/app",self.appDir);
            self.log(result+" : Moving "+self.baseDir+update_folder+"files/app"+" to "+self.appDir);
            if(result !== 1){errors = true;}
            self.log("Move App result : "+result);

            self.deleteFile(update_folder);
        }else{
            self.log("Can not create backup ... avoiding ... ");
            self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+6,self.name+": Function systemUpdate() failed : Can not create backup ... avoiding ... ");
        }

        if(errors){
            self.log("Errors Updating Software ... rollback");
            self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+7,self.name+": Function systemUpdate() failed : Errors Updating Software ... rollback");
            result = self.soc_api.Execute('Move',self.baseDir+"app_backup/app",self.appDir+"app");
            self.log("Move App result : "+result);
            result = self.soc_api.Execute('Move',self.baseDir+"app_backup/"+self.ROUTES['MAIN_JS'].path,self.appDir+self.ROUTES['MAIN_JS'].path);
            self.log("Move JS result : "+result);
            result = self.soc_api.Execute('Move',self.baseDir+"app_backup/"+self.ROUTES['MAIN_HTML'].path,self.appDir+self.ROUTES['MAIN_HTML'].path);
            self.log("Move HTML result : "+result);
            result = self.soc_api.Execute('Move',self.baseDir+"app_backup/"+self.ROUTES['VER'].path,self.appDir+self.ROUTES['VER'].path);
            self.log("Move VER result : "+result);
        }else{
            self.log("System Update complete ! rebooting !");
            self.rebootSystem();
        }
        self.systemIsUpdating = false;
    };

    this.systemRepairUpdate = function(){
      // TODO
    };

    this.copyAppToBrowserDir = function(){
        var exists = self.soc_api.Execute("IsExistedPath",self.browserDir+self.ROUTES['VER'].path);
        if(exists){
            self.soc_api.Execute("Delete",self.browserDir+self.ROUTES['VER'].path);
        }
        self.soc_api.Execute('Copy',self.appDir+self.ROUTES['VER'].path,self.browserDir+self.ROUTES['VER'].path);
        exists = self.soc_api.Execute("IsExistedPath",self.browserDir+self.ROUTES['MAIN_HTML'].path);
        if(exists){
            self.soc_api.Execute("Delete",self.browserDir+"offline.html");
        }
        self.soc_api.Execute('Copy',self.appDir+self.ROUTES['MAIN_HTML'].path,self.browserDir+"offline.html");
        exists = self.soc_api.Execute("IsExistedPath",self.browserDir+"app/");
        if(exists){
            self.soc_api.Execute("Delete",self.browserDir+"app/");
        }
        self.soc_api.Execute('Copy',self.appDir+"app/",self.browserDir);
    };

    this.deleteFilesInDir = function(dir,filter,callback,params){
        if(typeof(filter) === "undefined"){filter = "";}
        var files = [];
        var filesList = self.soc_api.Execute('GetListFiles', self.baseDir+dir);

        if(typeof(filesList) !== "undefined"){
            filesList = filesList.substring(1,filesList.length-3);
            files = filesList.split(",");
            files.pop(); // WARNING ... can conflict other functions ... ensure there's no affected elements or it's always a void element in SOC.
        }

        var deleted_files = [];
        for(var i=0;i<files.length;i++){
            if(filter != ""){
                var index = files[i].lastIndexOf(filter);
                if(index >= 0){
                    self.log(files[i]+" contains : "+filter+" delete");
                    self.soc_api.Execute("Delete",self.baseDir+dir+files[i]);
                    deleted_files.push(files[i]);
                }
            }else{
                self.log("delete temp dir file : "+self.baseDir+dir+files[i]);
                self.soc_api.Execute("Delete",self.baseDir+dir+files[i]);
                deleted_files.push(files[i]);
            }
        }

        if(typeof(callback) !== "undefined"){
            callback(deleted_files,dir,params);
        }

    };

    this.takeScreenshot = function(callback,params){
        if(self.sssp_version > 1){
            try{
                var fullsize = false;
                var source = self.lfd_api.Execute("GetScreenCapture");
                var destination = '/mtd_down/common/capture.jpg';
                if(typeof(params) !== "undefined"){
                  if(typeof(params.fullsize) !== "undefined"){
                    fullsize = params.fullsize;
                  }
                  if(typeof(params.poster) !== "undefined"){
                    destination = self.baseDir+params.poster;
                  }
                }
                self.soc_api.Execute("Copy", source, destination);
                var result = self.soc_api.Execute("IsExistedPath",destination);
                if(result === 1){
                    var img = new Image();
                    img.crossOrigin = 'Anonymous';
                    img.onload = function(){
                        var base64 = false;
                        var canvas = document.createElement('CANVAS');
                        var context = canvas.getContext('2d');
                        if(fullsize){
                          context.drawImage(img, 0, 0,canvas.width,canvas.height);
                        }else{
                          //250x140 Screenshot size
                          var width = 250;
                          var height = 140;
                          if (img.height > img.width){
                              width = 140;
                              height = 250;
                          }
                          canvas.height = height;
                          canvas.width = width;
                          context.drawImage(img, 0, 0,width,height);
                        }
                        canvas.height = height;
                        canvas.width = width;
                        context.drawImage(img, 0, 0,width,height);
                        if(params){
                            base64 = canvas.toDataURL("image/jpeg", params);
                        }
                        else{
                            base64 = canvas.toDataURL("image/jpeg", 1.0);
                        }
                        if(typeof(callback) !== "undefined"){
                            self.screenshotServer = base64.substring(23);
                            callback(base64.substring(23),params);
                        }
                        canvas = null;
                    };
                    var d = new Date();
                    img.src = destination+"?time="+d;
                }else{
                    if(typeof(callback) !== "undefined"){
                        self.screenshotServer = null;
                        callback(false,params);
                    }
                }
            }catch(ex){
                self.log("screenshot ex: "+ex);
            }
        }
    };
    
    this.takePosterImage = function(callback,params){
      if(self.sssp_version > 1){
          try{
              var source = self.lfd_api.Execute("GetScreenCapture");
              var destination = '/mtd_down/common/poster.jpg';
              if(typeof(params) !== "undefined"){
                if(typeof(params.poster) !== "undefined"){
                  destination = self.baseDir+params.poster;
                }
              }
              self.soc_api.Execute("Copy", source, destination);
              var result = self.soc_api.Execute("IsExistedPath",destination);
              if(result === 1){
                if(typeof(callback) !== "undefined"){
                    callback(true,params);
                }
              }else{
                if(typeof(callback) !== "undefined"){
                    callback(false,params);
                }
              }
          }catch(ex){
              self.log("takePosterImage ex: "+ex);
          }
      }
    };

    this.setSystemDateTime = function(timestamp,callback,params){
        self.log("Setting SOC Time : " + timestamp);
        var date = new Date(timestamp*1000); // In milliseconds
        var _day = parseInt(moment.utc(date).format('D'));
        var _hour = parseInt(moment.utc(date).format('h'));
        var _minute = parseInt(moment.utc(date).format('m'));
        var _seconds = parseInt(moment.utc(date).format('s'));
        var _month = parseInt(moment.utc(date).format('M'));
        var _year = parseInt(moment.utc(date).format('YYYY'));
        var _amPm = (moment.utc(date).format('A') == "AM" ? "01" : "00");

        self.nnavi_api.SetBannerState(8);

        _day = _day.toString(16).length == 2 ? _day.toString(16) : "0" + _day.toString(16);
        _hour = _hour.length == 2 ? _hour.toString(16) : "0" + _hour.toString(16);
        _minute = _minute.toString(16).length == 2 ? _minute.toString(16) : "0" + _minute.toString(16);
        _seconds = _seconds.toString(16).length == 2 ? _seconds.toString(16) : "0" + _seconds.toString(16);
        _month = _month.toString(16).length == 2 ? _month.toString(16) : "0" + _month.toString(16);
        _year = (_year.toString(16).length < 4 ? "0" : "") + _year.toString(16).substring(0, 2) + _year.toString(16).substring(2, 4);

        var dateStr = _day + _hour + _minute + _month + _year + _amPm;

        self.lfd_api.Execute('SendLFDMsg','A71107'+dateStr.toUpperCase());
        self.lfd_api.Execute('SendLFDMsg','A70000');

        if(typeof(callback) !== "undefined"){
            callback(true,params);
        }
    };

    this.rebootSystem = function(){
        self.lfd_api3.Execute("rebootSystemCmd", "restart");
    };

    this.haltSystem = function(){
         // TODO
    };
    this.firstCheckSystem = true;
    this.internetConnected = function() {
        var internet = false;
        if(!self.internet_check_busy){
            self.internet_check_busy = true;
            //self.log("Checking internet .... ");
            var network_api = document.getElementById('networkPlugin');
            network_api.Open('Network', '1.000', 'Network');

            var connection_type = network_api.Execute("GetActiveType");
            //self.log("Connection type : "+connection_type);
            var connection_is_physical = 0;
            var connection_gateway = 0;
            var connection_dns = 0;
            var connection_http = 0;
            if (connection_type != -1){
                connection_is_physical = network_api.Execute("CheckPhysicalConnection", connection_type);
                //self.log("Connection is physical : "+connection_is_physical);
                if (connection_is_physical === 1 || connection_is_physical == 1) {
                    connection_gateway = network_api.Execute("CheckGateway",connection_type);
                    //self.log("Connection gateway : "+connection_gateway);
                    if(connection_gateway == 1){
                        connection_dns = network_api.Execute("CheckDNS", connection_type);
                        //self.log("Connection DNS : "+connection_dns);
                        if(connection_dns == 1){
                            connection_http = network_api.Execute("CheckHTTP", connection_type);
                            //self.log("Connection HTTP : "+connection_http);
                            if(connection_http == 1){
                                internet = true;
                            }
                        }
                    }
                }
            }
            self.log("Checking internet .... "+internet+" Type: "+connection_type+" Physical: "+connection_is_physical+" Gateway: "+connection_gateway+" DNS: "+connection_dns+" HTTP: "+connection_http);
            if(self.firstCheckSystem == true){
              self.checkSystem();
            }
            connection_type = null;
            connection_is_physical = null;
            connection_gateway = null;
            connection_dns = null;
            connection_http = null;
            network_api.Close();
            network_api = null;
            setTimeout(function(){
              self.internet_check_busy = false;
            }, 60000)
            self.internet_connection = internet;
            return internet;
            //self.internet_check_busy = false;
        }else{
            internet = self.internet_connection;
            return internet;
        }


    };
    this.checkSystemBusy = false;
    this.total_storage = null;
    this.free_storage = null;
    this.cpu_usage = null;
    this.ram_usage = null;
    this.uptime = null;
    this.checkSystemTimer = 0;
    function pluginuptime_OnEvent(eventType, param1, param2){
    	self.uptime=eventType;
    	self.lfd_api2.Close();
      self.log("System Uptime : "+self.uptime+" CPU : "+self.cpu_usage+"% & USED_RAM : "+self.ram_usage);
      self.total_storage = null;
      self.free_storage = null;
      self.cpu_usage = null;
      self.ram_usage = null;
      self.uptime = null;
      self.checkSystemBusy = false;
      self.checkSystemTimer = setTimeout(function(){
        self.checkSystem();
      }, 300000);
    };
    function pluginRAMusage0_OnEvent(eventType, param1, param2){
    	self.ram_usage=eventType;
    	self.lfd_api2.Close();
      self.lfd_api2.OnEvent = pluginuptime_OnEvent;
    	self.lfd_api2.Open("LFD","1.000","LFD");
    	self.lfd_api2.Execute('getSystemUpTime', "Get Total System Uptime in Seconds");
    };
    function pluginCPUusage0_OnEvent(eventType, param1, param2){
    	self.cpu_usage=eventType;
    	self.lfd_api2.Close();
      self.lfd_api2.OnEvent = pluginRAMusage0_OnEvent;
    	self.lfd_api2.Open("LFD","1.000","LFD");
    	self.lfd_api2.Execute('getRamUsage', "Percentage of RAM Usage");
    };

    this.checkSystem = function(){
      if(self.checkSystemBusy == false){
        self.checkSystemBusy = true;
        self.firstCheckSystem = false;
        self.total_storage = parseInt(self.soc_api.Execute("GetTotalSize"));
        self.free_storage = parseInt(self.soc_api.Execute("GetFreeSize"));
        self.total_storage = parseInt(self.total_storage/1024/1024);
        self.free_storage = parseInt(self.free_storage/1024/1024);
        self.log("System SSSPv"+self.sssp_version+" Total Storage : "+self.total_storage+"Mb & Free Storage : "+self.free_storage+"Mb launcher URL : "+self.launcher_url);
        self.lfd_api2.OnEvent = pluginCPUusage0_OnEvent;
      	self.lfd_api2.Open("LFD","1.000","LFD");
      	self.lfd_api2.Execute('getCPUUsage', "Percentage of CPU Usage");
      }
    }


    this.getNetworkInfo = function(callback,params){
        var network_api = document.getElementById('networkPlugin');
        network_api.Open('Network', '1.000', 'Network');

        var network_info = {
            ip: "0.0.0.0",
            netmask : "0.0.0.0",
            gateway : "0.0.0.0"
        };

        var cType = network_api.Execute("GetActiveType");
        if (cType != -1){
            network_info.ip = network_api.Execute("GetIP",cType);
            network_info.netmask = network_api.Execute("GetNetMask",cType);
            network_info.gateway = network_api.Execute("GetGateway",cType);
        }
        network_api.Close();
        network_api = null;

        if(typeof(callback) !== "undefined"){
            callback(network_info,params);
        }
    };


    this.getScreens = function(){
        // OVERRIDE
        var screens = [];
        screens[0] = {id:0,bounds:{x:0,y:0,width:400,height:300,scaleFactor:1}};
        return screens;
    };

    this.setWindow = function(x,y,w,h){
        // OVERRIDE
    };

    this.setProxyConfig = function(config){
        // OVERRIDE
    };

    this.getProxyForURL = function(url){
        // OVERRIDE
        return "";
    };

    this.getAddWhiteList = function(sourceOrigin, destinationProtocol, destinationHost, allowDestinationSubdomains){
        // OVERRIDE
    };

    this.getRemoveWhiteList = function(sourceOrigin, destinationProtocol, destinationHost, allowDestinationSubdomains){
        // OVERRIDE
    };

    this.getDataPath = function(){
         // OVERRIDE
    };

    this.setCrashDumpPath = function(folderPath){
         // OVERRIDE
    };

    this.quit = function(){
        // OVERRIDE
    };
    
    this.reload = function(){
      try{
        location.reload(true);
      }catch(e){
        console.log(e);
      }
    };

    this.clearCache = function(){
        // OVERRIDE
    };

    this.alwaysOnTop = function(value){
        // OVERRIDE
    };

    this.focusWindow = function(){
        // OVERRIDE
    };

    this.disableRemoteControl = function(platform){
        self.deactivateControl();
    };

    this.enableRemoteControl = function(platform,tunnels){
        self.activateControl();
    };

    this.keepAwake = function(platform){
        // TODO : Keeps Screen Awake
    };

    this.socketServerStart = function(port,onOpenCallback,onMessageCallback,onTerminatedCallback){
      // TODO : NOT AVAILABLE
    };

    this.socketServerBroadcast = function(msg,exclude){
      // TODO : NOT AVAILABLE
    };


    this.existsLIC = function(){
        exists1 = self.soc_api.Execute("IsExistedPath","admira.lic");
        exists2 = self.soc_api.Execute("IsExistedPath","/ADmiraSoC/admira.lic");
        exists3 = self.soc_api.Execute("IsExistedPath","/mtd_down/common/ADmiraSoC/admira.lic");
        exists4 = self.soc_api.Execute("IsExistedPath","/mtd_down/common/HospitalityBrowser/admira.lic");
        exists5 = self.soc_api.Execute("IsExistedPath","/mtd_down/widgets/user/ADmiraSoC/admira.lic");
        self.log("Existe lic:  1: "+exists1+"  2: "+exists2+ "   3: "+exists3 + "  4: "+exists4 + "   5: "+exists5);

    }
    this.existsCORE = function(){
        exists1 = self.soc_api.Execute("IsExistedPath","core.xml");
        exists2 = self.soc_api.Execute("IsExistedPath","/ADmiraSoC/core.xml");
        exists3 = self.soc_api.Execute("IsExistedPath","/mtd_down/common/ADmiraSoC/core.xml");
        exists4 = self.soc_api.Execute("IsExistedPath","/mtd_down/common/HospitalityBrowser/core.xml");
        exists5 = self.soc_api.Execute("IsExistedPath","/mtd_down/widgets/user/ADmiraSoC/core.xml");
        self.log("Existe core:  1: "+exists1+"  2: "+exists2+ "   3: "+exists3 + "  4: "+exists4 + "   5: "+exists5);

    }
    this.existsVER = function(){
        exists1 = self.soc_api.Execute("IsExistedPath","admira.ver");
        exists2 = self.soc_api.Execute("IsExistedPath","/ADmiraSoC/admira.ver");
        exists3 = self.soc_api.Execute("IsExistedPath","/mtd_down/common/ADmiraSoC/admira.ver");
        exists4 = self.soc_api.Execute("IsExistedPath","/mtd_down/common/HospitalityBrowser/admira.ver");
        exists5 = self.soc_api.Execute("IsExistedPath","/mtd_down/widgets/user/ADmiraSoC/admira.ver");
        self.log("Existe ver:  1: "+exists1+"  2: "+exists2+ "   3: "+exists3 + "  4: "+exists4 + "   5: "+exists5);

    }
    this.existsXMLS = function(){
        exists1 = self.soc_api.Execute("IsExistedPath","xmls");
        exists2 = self.soc_api.Execute("IsExistedPath","/ADmiraSoC/xmls/");
        exists3 = self.soc_api.Execute("IsExistedPath","/mtd_down/common/ADmiraSoC/xmls/");
        exists4 = self.soc_api.Execute("IsExistedPath","/mtd_down/common/HospitalityBrowser/xmls/");
        exists5 = self.soc_api.Execute("IsExistedPath","/mtd_down/widgets/user/ADmiraSoC/xmls/");
        self.log("Existe xml:  1: "+exists1+"  2: "+exists2+ "   3: "+exists3 + "  4: "+exists4 + "   5: "+exists5);
    }
    this.copyFile = function(source,destination,callback,params){
        self.log("Copi : "+source+" to "+destination);
        var result = self.soc_api.Execute('Copy', source, destination);
        self.log("Result = "+result);
        var ok = false;
        if(result === 1){
            ok = true;
        }
        if(typeof(callback) !== "undefined"){
            callback(ok,"",params);
        }
    };
    this.getLIC = function(callback){
      if(self.sssp_version === "1" || self.sssp_version === 1){
          $.ajax({
              url:"/mtd_down/common/HospitalityBrowser/admira.lic",
              dataType:'text',
              cache: false,
              success: function( dataLIC ) {
                  if(dataLIC.length > 0){
                      self.lic = dataLIC;
                      callback("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/HospitalityBrowser/admira.lic AJAX: "+dataLIC);
                  }
              },
              error: function(e){
                  self.lic = self.internalReadFile("admira.lic");
                  if(self.lic.length > 0 ){
                      callback("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/HospitalityBrowser/admira.lic read: "+self.lic);
                  }
                  else{
                      callback("lic.length <= 0");
                  }
              }
          });
      }
      else{
          $.ajax({
              url:"/mtd_down/common/ADmiraSoC/admira.lic",
              dataType:'text',
              cache: false,
              success: function( dataLIC ) {
                  if(dataLIC.length > 0){
                      self.lic = dataLIC;
                      callback("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/ADmiraSoC/admira.lic AJAX: "+dataLIC);
                  }
              },
              error: function(e){
                  callback("Error con el ajax de /mtd_down/common/ADmiraSoC/admira.lic");
              }
          });
      }
    };

    this.createLIC = function (data, callback){
      if(self.sssp_version === "1" || self.sssp_version === 1){
          self.overwrite_Filesystem("admira.txt", data.lic);
          self.soc_api1.Execute("Move", "/mtd_down/common/HospitalityBrowser/admira.txt", "/mtd_down/common/HospitalityBrowser/admira.lic");
          $.ajax({
              url:"/mtd_down/common/HospitalityBrowser/admira.lic",
              dataType:'text',
              cache: false,
              success: function( dataLIC ) {
                  if(dataLIC.length > 0){
                      self.lic = dataLIC;
                      self.log("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/HospitalityBrowser/admira.lic AJAX: "+dataLIC);
                      if(callback){
                        callback("admira.lic ("+dataLIC+") created");
                      }
                  }
              },
              error: function(e){
                  self.log("Error con el ajax de /mtd_down/common/HospitalityBrowser/admira.lic");
                  if(callback){
                    callback("admira.lic not created");
                  }
              }
          });
      }
      else{
          self.overwrite_Filesystem("admira.txt", data.lic);
          self.soc_api1.Execute("Move", "/mtd_down/common/ADmiraSoC/admira.txt", "/mtd_down/common/ADmiraSoC/admira.lic");
          $.ajax({
              url:"/mtd_down/common/ADmiraSoC/admira.lic",
              dataType:'text',
              cache: false,
              success: function( dataLIC ) {
                  if(dataLIC.length > 0){
                      self.lic = dataLIC;
                      self.log("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/ADmiraSoC/admira.lic AJAX: "+dataLIC);
                      if(callback){
                        callback("admira.lic ("+dataLIC+") created");
                      }
                  }
                  else{
                    if(callback){
                      callback("admira.lic not created");
                    }
                  }
              },
              error: function(e){
                  self.log("Error con el ajax de /mtd_down/common/ADmiraSoC/admira.lic");
                  if(callback){
                    callback("admira.lic not created");
                  }
              }
          });
      }
    }

    this.activateControl = function(){
        self.debug = true;
        self.SocketConnector.createSocket();
    };
    this.deactivateControl = function(){
        self.debug = false;
        self.SocketConnector.disconnectSocket();
    };
    this.sendControlLog = function(ori, name, text){
      if(typeof(self.SocketConnector) !== "undefined"){
        self.SocketConnector.logsSocket(ori, (new Date()).toTimeString().split(' ')[0] +" .. " + name+ "--"+text);
      }
    };
    this.changeCore = function(id){
      self.SocketConnector.changeCore(id);
    };
    this.saveIdContent = function(idContent){
        self.id_content_now = idContent;
    };
    this.get_tunnels_params = function(){
        //self.api_connector.get(self.api_url,self.api_ver,"player/get_tunnels_params/id",self.core_id,self.remoteResponse);
    };

    this.callbackGetInfoSystem = null;
    this.getInfoSystem = function(callback){
      if(callback){
        self.callbackGetInfoSystem = callback;
      }
      else{
        self.callbackGetInfoSystem = null;
      }
        self.pluginGetSoftwareVersion = document.getElementById('pluginGetSoftwareVersion');
        self.pluginSerialNumber = document.getElementById('pluginSerialNumber');
        self.TVPlugin = document.getElementById('getModelplugin');

        self.pluginGetSoftwareVersion.Open("LFD","1.000","LFD"); /* Abrimos el plugin SEF modo LFD */
        self.firmwareVersion = self.pluginGetSoftwareVersion.Execute('getSoftwareVersion'); /* getSoftwareVersion */
        self.subMicomVersion = self.pluginGetSoftwareVersion.Execute("getSoftwareVersion",1);
        //self.pluginGetSoftwareVersion.Close(); /* Abrimos el plugin SEF modo LFD */

        self.modelTV = self.TVPlugin.GetProductCode(1); /* getSoftwareVersion */
        self.pluginSerialNumber.OnEvent = pluginSerialNumber0_OnEvent; /* Añadimos el nombre de la función que se ejecutará cuando se resuelva el evento mandado a la LFD */
        self.pluginSerialNumber.Open("LFD","1.000","LFD"); /* Abrimos el plugin SEF modo LFD */
        self.pluginSerialNumber.Execute('SendLFDMsg', '0B0000'); /* Serial Number */
    }

    function pluginSerialNumber0_OnEvent(eventType, param1, param2){
        if(param1.substring(0,2)=="FF" && param1.substring(6,8)=="41"){
            self.serialNumber = "";
            var x =10;
            while(x<39){
                self.serialNumber += String.fromCharCode(parseInt(param1.substring(x,(x+2)),16));
                x=x+2;
            }
            self.pluginSerialNumber.Close(); /* Abrimos el plugin SEF modo LFD */
        }
        else{
            self.serialNumber = null;
            self.pluginSerialNumber.Close(); /* Abrimos el plugin SEF modo LFD */
        }
        if(self.sssp_version == 1){
          self.dataInfoSystem = null;
          self.firmwareVersion = null;
          self.pluginSerialNumber.OnEvent = firmwareVersion_OnEvent;
          self.pluginSerialNumber.Open("LFD","1.000","LFD");
          self.pluginSerialNumber.Execute('SendLFDMsg', '0E0000');
        }
        else{
          self.dataInfoSystem = {
              firmwareVersion: self.firmwareVersion,
              subMicomVersion : self.subMicomVersion,
              modelTV : self.modelTV,
              serialNumber : self.serialNumber
          };
          self.log(JSON.stringify(self.dataInfoSystem));
          if(self.callbackGetInfoSystem){
            self.callbackGetInfoSystem(JSON.stringify(self.dataInfoSystem));
          }
        }
    };
    function firmwareVersion_OnEvent(eventType, param1, param2){
        self.log("firmwareVersion_OnEvent: "+ param1);
        self.firmwareVersion = self._parseSoftwareVersionHex(param1);
        self.log("self.firmwareVersion: "+ self.firmwareVersion);
        self.dataInfoSystem = {
            firmwareVersion: self.firmwareVersion,
            subMicomVersion : self.subMicomVersion,
            modelTV : self.modelTV,
            serialNumber : self.serialNumber
        };
        self.log(JSON.stringify(self.dataInfoSystem));
        if(self.callbackGetInfoSystem){
          self.callbackGetInfoSystem(JSON.stringify(self.dataInfoSystem));
        }
    };
    this._parseSoftwareVersionHex = function (message) {
      //remove the headers(start at pos 10), and parse to ascii
      var version = self._hexPairs2ascii(message.substr(10, message.length));

      //conforms 2013 LFD's response to 2014 LFD method response format (removes Main Micom wording)
      version = version.replace('Main Micom:', '').trim();
      return version;
    };

    this._hexPairs2ascii = function (hexPairString) {
      //split up the hex pairs
      var results = self._splitEveryN(2, hexPairString);
      for (var i = 0; i < results.length; i++) {
        //replace the array value with the converted character
        results[i] = String.fromCharCode(parseInt(results[i], 16));
      }
      //combine the char array into a string
      return results.join('');
    };
    this._splitEveryN = function (n, toSplit) {
      return toSplit.trim().match(new RegExp('.{1,' + n + '}', 'g'));
    };




    this.create_FileSystem = function (){
        /* instanciar FileSystem() API.*/
        self.fileSystemObj = new FileSystem();
        /* comprobar si el directorio existe.*/
        var dValid = self.fileSystemObj.isValidCommonPath(curWidget.id);
        if(dValid==0){
            var dResult = self.fileSystemObj.createCommonDir(curWidget.id); //crear directorio para filesystem
        }
        self.log("curWidget.id: "+curWidget.id);
    };
    this.overwrite_Filesystem = function (archivo, texto){
        self.create_FileSystem();
        var jsFileObj = self.fileSystemObj.openCommonFile(curWidget.id+"/"+archivo,"w");
        jsFileObj.writeAll(texto);
        /*<-----------Escritura finalizada----------->*/
        self.fileSystemObj.closeCommonFile(jsFileObj);
    };
    this.internalReadFile = function (archivo){
        var data;
        self.create_FileSystem();
        var jsFileObj = self.fileSystemObj.openCommonFile(curWidget.id+"/"+archivo,"r");
        if(jsFileObj){
            data = jsFileObj.readAll();
        }
        self.fileSystemObj.closeCommonFile(jsFileObj);
        return data;
    }
    this.deleteAll =  function(callback){
        var contents = self.soc_api1.Execute('GetListFiles', '/mtd_down/common/');
        contents = JSON.parse(contents);
        self.log(contents.length);
        self.log(contents);


        if(self.sssp_version === "1" || self.sssp_version === 1){
            $.ajax({
                url:"/mtd_down/common/HospitalityBrowser/admira.lic",
                dataType:'text',
                cache: false,
                success: function( dataLIC ) {
                    if(dataLIC.length > 0){
                        self.lic = dataLIC;
                        self.log("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/HospitalityBrowser/admira.lic AJAX: "+dataLIC);
                        for (var i = 0; i < contents.length - 1; i++) {
                            var itemPath = '/mtd_down/common/' + contents[i];
                                self.log("Deleted: "+itemPath);
                                self.soc_api1.Execute('Delete', itemPath);
                            if(i == contents.length-2){
                                self.log("---------------------------------------------------------------------------------------------------------");
                                self.overwrite_Filesystem("admira.txt", self.lic);
                                self.soc_api1.Execute("Move", "/mtd_down/common/HospitalityBrowser/admira.txt", "/mtd_down/common/HospitalityBrowser/admira.lic");
                                self.log("write license: "+self.lic);
                                callback("deleteAll Completed -- Write admira.lic Completed ("+self.lic+") -- Reboot");
                                setTimeout(function(){self.rebootSystem();},5000);
                            }
                        }
                    }
                    else{
                      callback("deleteAll Error -- dataLIC.length < 0");
                    }
                },
                error: function(e){
                    self.log("Error con el ajax de /mtd_down/common/HospitalityBrowser/admira.lic");
                    self.lic = self.internalReadFile("admira.lic");
                    if(self.lic.length > 0 ){
                        self.log("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/HospitalityBrowser/admira.lic read: "+self.lic);
                        for (var i = 0; i < contents.length - 1; i++) {
                            var itemPath = '/mtd_down/common/' + contents[i];
                                self.log("Deleted: "+itemPath);
                                self.soc_api1.Execute('Delete', itemPath);
                            if(i == contents.length-2){
                                self.log("---------------------------------------------------------------------------------------------------------");
                                self.overwrite_Filesystem("admira.txt", self.lic);
                                self.soc_api1.Execute("Move", "/mtd_down/common/HospitalityBrowser/admira.txt", "/mtd_down/common/HospitalityBrowser/admira.lic");
                                self.log("write license: "+self.lic);
                                callback("deleteAll Completed -- Write admira.lic Completed ("+self.lic+") -- Reboot");
                                setTimeout(function(){self.rebootSystem();},5000);
                            }
                        }
                    }
                    else{
                        self.log("lic.length <= 0");
                        callback("deleteAll Error -- lic.length <= 0");
                    }
                }
            });
        }
        else{
            $.ajax({
                url:"/mtd_down/common/ADmiraSoC/admira.lic",
                dataType:'text',
                cache: false,
                success: function( dataLIC ) {
                    if(dataLIC.length > 0){
                        self.lic = dataLIC;
                        self.log("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/ADmiraSoC/admira.lic AJAX: "+dataLIC);
                        for (var i = 0; i < contents.length - 1; i++) {
                            var itemPath = '/mtd_down/common/' + contents[i];
                            self.log("Deleted: "+itemPath);
                            self.soc_api1.Execute('Delete', itemPath);
                            if(i == contents.length-2){
                                self.log("---------------------------------------------------------------------------------------------------------");
                                self.writeFiles(callback);
                            }
                        }

                    }
                    else{
                      callback("deleteAll Error -- dataLIC.length < 0");
                    }
                },
                error: function(e){
                    self.log("Error con el ajax de /mtd_down/common/ADmiraSoC/admira.lic");
                }
            });
        }
    }
    this.deleteAll2 =  function(callback){
      callback("see logs");
        var contents = self.soc_api1.Execute('GetListFiles', '/mtd_down/common/');
        contents = JSON.parse(contents);
        self.log(contents.length);
        self.log(contents);


        if(self.sssp_version === "1" || self.sssp_version === 1){
            $.ajax({
                url:"/mtd_down/common/HospitalityBrowser/admira.lic",
                dataType:'text',
                cache: false,
                success: function( dataLIC ) {
                    if(dataLIC.length > 0){
                        self.lic = dataLIC;
                        self.log("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/HospitalityBrowser/admira.lic AJAX: "+dataLIC);
                        for (var i = 0; i < contents.length - 1; i++) {
                            var itemPath = '/mtd_down/common/' + contents[i];
                                self.log("Deleted: "+itemPath);
                                self.soc_api1.Execute('Delete', itemPath);
                            if(i == contents.length-2){
                                self.log("---------------------------------------------------------------------------------------------------------");
                                self.overwrite_Filesystem("admira.txt", self.lic);
                                self.soc_api1.Execute("Move", "/mtd_down/common/HospitalityBrowser/admira.txt", "/mtd_down/common/HospitalityBrowser/admira.lic");
                                self.log("write license: "+self.lic);
                                try{
                                    var usbDir = '/$USB_DIR/sda1/';
                                    var ok = self.soc_api1.Execute("Unzip",usbDir+"offline.data.zip",usbDir+"offline.data/")
                                    if(parseInt(ok)){
                                        self.log("Unzip complete.");
                                        self.log("/mtd_down/common/"+curWidget.id+"/xmls/");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/1.xml", "/mtd_down/common/"+curWidget.id+"/xmls/1.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/2.xml", "/mtd_down/common/"+curWidget.id+"/xmls/2.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/3.xml", "/mtd_down/common/"+curWidget.id+"/xmls/3.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/4.xml", "/mtd_down/common/"+curWidget.id+"/xmls/4.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/5.xml", "/mtd_down/common/"+curWidget.id+"/xmls/5.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/6.xml", "/mtd_down/common/"+curWidget.id+"/xmls/6.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/7.xml", "/mtd_down/common/"+curWidget.id+"/xmls/7.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/week.tstamp", "/mtd_down/common/"+curWidget.id+"/xmls/week.tstamp");
                                        var contenSD = self.soc_api1.Execute("GetListFiles",usbDir+"offline.data/content/");
                                        if(contenSD != "" && contenSD != null){
                                            contenSD = JSON.parse(contenSD);
                                            for (var j = 0; j < contenSD.length - 1; j++) {
                                                self.soc_api1.Execute("Copy", usbDir+"offline.data/content/"+contenSD[j], "/mtd_down/common/"+curWidget.id+"/content/"+contenSD[j]);
                                                self.log("copy to "+"/mtd_down/common/"+curWidget.id+"/content/"+contenSD[j]);
                                                if(j = contenSD.length - 2){
                                                    //self.lfd_api1.Execute("rebootSystemCmd", "Reboot");
                                                    self.rebootSystem();
                                                }
                                            }
                                        }
                                    }
                                    else{
                                        self.log("Error unzip offline.data");
                                    }
                                }
                                catch(e){
                                    self.log(JSON.stringify(e));
                                }
                            }
                        }

                    }
                },
                error: function(e){
                    self.log("Error con el ajax de /mtd_down/common/HospitalityBrowser/admira.lic");
                    self.lic = self.internalReadFile("admira.lic");
                    if(self.lic.length > 0 ){
                        self.log("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/HospitalityBrowser/admira.lic read: "+self.lic);
                        for (var i = 0; i < contents.length - 1; i++) {
                            var itemPath = '/mtd_down/common/' + contents[i];
                                self.log("Deleted: "+itemPath);
                                self.soc_api1.Execute('Delete', itemPath);
                            if(i == contents.length-2){
                                self.log("---------------------------------------------------------------------------------------------------------");
                                self.overwrite_Filesystem("admira.txt", self.lic);
                                self.soc_api1.Execute("Move", "/mtd_down/common/HospitalityBrowser/admira.txt", "/mtd_down/common/HospitalityBrowser/admira.lic");
                                self.log("write license: "+self.lic);
                                try{
                                    var usbDir = '/$USB_DIR/sda1/';
                                    var ok = self.soc_api1.Execute("Unzip",usbDir+"offline.data.zip",usbDir+"offline.data/")
                                    if(parseInt(ok)){
                                        self.log("Unzip complete.");
                                        self.log("/mtd_down/common/"+curWidget.id+"/xmls/");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/1.xml", "/mtd_down/common/"+curWidget.id+"/xmls/1.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/2.xml", "/mtd_down/common/"+curWidget.id+"/xmls/2.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/3.xml", "/mtd_down/common/"+curWidget.id+"/xmls/3.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/4.xml", "/mtd_down/common/"+curWidget.id+"/xmls/4.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/5.xml", "/mtd_down/common/"+curWidget.id+"/xmls/5.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/6.xml", "/mtd_down/common/"+curWidget.id+"/xmls/6.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/7.xml", "/mtd_down/common/"+curWidget.id+"/xmls/7.xml");
                                        self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/week.tstamp", "/mtd_down/common/"+curWidget.id+"/xmls/week.tstamp");
                                        var contenSD = self.soc_api1.Execute("GetListFiles",usbDir+"offline.data/content/");
                                        if(contenSD != "" && contenSD != null){
                                            contenSD = JSON.parse(contenSD);
                                            for (var j = 0; j < contenSD.length - 1; j++) {
                                                self.soc_api1.Execute("Copy", usbDir+"offline.data/content/"+contenSD[j], "/mtd_down/common/"+curWidget.id+"/content/"+contenSD[j]);
                                                self.log("copy to "+"/mtd_down/common/"+curWidget.id+"/content/"+contenSD[j]);
                                                if(j = contenSD.length - 2){
                                                    //self.lfd_api3.Execute("rebootSystemCmd", "Reboot");
                                                    self.rebootSystem();
                                                }
                                            }
                                        }
                                    }
                                    else{
                                        self.log("Error unzip offline.data");
                                    }
                                }
                                catch(e){
                                    self.log(JSON.stringify(e));
                                }
                            }
                        }
                    }
                    else{
                        self.log("lic.length <= 0");
                    }
                }
            });
        }
        else{
            $.ajax({
                url:"/mtd_down/common/ADmiraSoC/admira.lic",
                dataType:'text',
                cache: false,
                success: function( dataLIC ) {
                    if(dataLIC.length > 0){
                        self.lic = dataLIC;
                        self.log("------------ FICHERO ADMIRA.LIC DE /mtd_down/common/ADmiraSoC/admira.lic AJAX: "+dataLIC);
                        for (var i = 0; i < contents.length - 1; i++) {
                            var itemPath = '/mtd_down/common/' + contents[i];
                            self.log("Deleted: "+itemPath);
                            self.soc_api1.Execute('Delete', itemPath);
                            if(i == contents.length-2){
                                self.log("---------------------------------------------------------------------------------------------------------");
                                self.writeFiles2();
                            }
                        }

                    }
                },
                error: function(e){
                    self.log("Error con el ajax de /mtd_down/common/ADmiraSoC/admira.lic");
                }
            });
        }
    }
    this.deleteAllAll = function(callback){
      var contents = self.soc_api1.Execute('GetListFiles', '/mtd_down/common/');
      contents = JSON.parse(contents);
      self.log(contents.length);
      self.log(contents);
      for (var i = 0; i < contents.length - 1; i++) {
          var itemPath = '/mtd_down/common/' + contents[i];
          self.log("Deleted: "+itemPath);
          self.soc_api1.Execute('Delete', itemPath);
          if(i == contents.length-2){
            callback("deleteAllAll Completed -- Reboot");
            //self.lfd_api3.Execute("rebootSystemCmd", "Reboot");
            self.rebootSystem();
          }
      }
    };
    this.deleteFileAndSave = function (){
      if(self.sssp_version === "1" || self.sssp_version === 1){
          self.log("------------ Es un text -- "+data.file);
          $.ajax({
              url:"/mtd_down/common/HospitalityBrowser/"+data.file,
              dataType:'text',
              cache: false,
              success: function( dataRead ) {
                  self.dataRead = dataRead;
                  self.log("------------ FICHERO leido /mtd_down/common/HospitalityBrowser/"+data.file+": "+dataRead);
                  var deleteStatus = self.soc_api1.Execute('Delete', "/mtd_down/common/HospitalityBrowser/"+data.file);
                  if(deleteStatus){
                      self.overwrite_Filesystem(data.file+".txt", self.dataRead);
                      self.log("Write file: "+data.file+".txt");
                      self.soc_api1.Execute("Move", "/mtd_down/common/HospitalityBrowser/"+data.file+".txt", "/mtd_down/common/HospitalityBrowser/"+data.file);
                      $.ajax({
                          url:"/mtd_down/common/HospitalityBrowser/"+data.file,
                          dataType:'text',
                          cache: false,
                          success: function( dataRead1 ) {
                              self.log("------------ FICHERO leido "+data.file+": "+dataRead1);
                          },
                          error: function(e){
                              self.log("Error read file");
                          }
                      });
                  }
                  else{
                      self.log("Error delete file");
                  }
              },
              error: function(e){
                  self.log("Error read file");
              }
          });
      }
      else{
          if(data.file.substring(data.file.lastIndexOf(".")+1, data.file.length) == "xml"){
              self.log("------------ Es un xml -- "+data.file);
              $.ajax({
                  url:"/mtd_down/common/ADmiraSoC/"+data.file,
                  dataType:'xml',
                  cache: false,
                  success: function( dataRead ) {
                      self.dataRead = dataRead;
                      self.log("------------ FICHERO leido /mtd_down/common/"+data.file+": "+dataRead);
                      self.log("------dddddddd------ FICHERO ---- : "+dataRead.getElementsByTagName('config')[0].getElementsByTagName('api_url')[0].childNodes[0].nodeValue);

                      var deleteStatus = self.soc_api1.Execute('Delete', "/mtd_down/common/ADmiraSoC/"+data.file);
                      if(deleteStatus){
                          self.overwrite_Filesystem(data.file+".txt", self.dataRead);
                          self.log("Write file: "+data.file+".txt");
                          self.soc_api1.Execute("Move", "/mtd_down/common/ADmiraSoC/"+data.file+".txt", "/mtd_down/common/ADmiraSoC/"+data.file);
                         $.ajax({
                              url:"/mtd_down/common/ADmiraSoC/"+data.file,
                              dataType:'xml',
                              cache: false,
                              success: function( dataRead1 ) {
                                  self.log("------------ FICHERO leido "+data.file+": "+dataRead1);
                              },
                              error: function(e){
                                  self.log("Error read file2");
                              }
                          });
                      }
                      else{
                          self.log("Error delete file");
                      }
                  },
                  error: function(e){
                      self.log("Error read file");
                  }
              });
          }
          else{
              self.log("------------ Es un text -- "+data.file);
              $.ajax({
                  url:"/mtd_down/common/ADmiraSoC/"+data.file,
                  dataType:'text',
                  cache: false,
                  success: function( dataRead ) {
                      self.dataRead = dataRead;
                      self.log("------------ FICHERO leido /mtd_down/common/"+data.file+": "+dataRead);
                      self.log("self.dataRead : "+self.dataRead);
                      var deleteStatus = self.soc_api1.Execute('Delete', "/mtd_down/common/ADmiraSoC/"+data.file);
                      if(deleteStatus){
                          self.overwrite_Filesystem(data.file+".txt", self.dataRead);
                          self.log("Write file: "+data.file+".txt");
                          self.soc_api1.Execute("Move", "/mtd_down/common/ADmiraSoC/"+data.file+".txt", "/mtd_down/common/ADmiraSoC/"+data.file);
                          $.ajax({
                              url:"/mtd_down/common/ADmiraSoC/"+data.file,
                              dataType:'text',
                              cache: false,
                              success: function( dataRead1 ) {
                                  self.log("------------ FICHERO leido "+data.file+": "+dataRead1);
                              },
                              error: function(e){
                                  self.log("Error read file");
                              }
                          });
                      }
                      else{
                          self.log("Error delete file");
                      }
                  },
                  error: function(e){
                      self.log("Error read file");
                  }
              });
          }
      }
    }
    this.getScreenshot = function(callback){
        if(self.sssp_version > 1){
            try{
                var source = self.lfd_api.Execute("GetScreenCapture");
                var destination = '/mtd_down/common/capture.jpg';
                self.soc_api.Execute("Copy", source, destination);
                var result = self.soc_api.Execute("IsExistedPath",destination);
                if(result === 1){
                    var img = new Image();
                    img.crossOrigin = 'Anonymous';
                    img.onload = function(){
                        var base64 = false;
                        var canvas = document.createElement('CANVAS');
                        var context = canvas.getContext('2d');
                        //250x140 Screenshot size
                        var width = 250;
                        var height = 140;
                        if (img.height > img.width){
                            width = 140;
                            height = 250;
                        }
                        canvas.height = height;
                        canvas.width = width;
                        context.drawImage(img, 0, 0,width,height);
                        base64 = canvas.toDataURL("image/jpeg", 1.0);
                        //self.log(base64.substring(23));
                        callback(base64.substring(23));
                        canvas = null;
                    };
                    var d = new Date();
                    img.src = destination+"?time="+d;
                }else{
                    callback(false);
                }
            }catch(ex){
              callback(false);
            }
        }
        else{
            callback(false);
        }
    };
    this.copyUSB = function (callback){
      try{
          var usbDir = '/$USB_DIR/sda1/';
          var ok = self.soc_api1.Execute("Unzip",usbDir+"offline.data.zip",usbDir+"offline.data/")
          if(parseInt(ok)){
              self.log("Unzip complete.");
              self.log("/mtd_down/common/"+curWidget.id+"/xmls/");
              self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/1.xml", "/mtd_down/common/"+curWidget.id+"/xmls/1.xml");
              self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/2.xml", "/mtd_down/common/"+curWidget.id+"/xmls/2.xml");
              self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/3.xml", "/mtd_down/common/"+curWidget.id+"/xmls/3.xml");
              self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/4.xml", "/mtd_down/common/"+curWidget.id+"/xmls/4.xml");
              self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/5.xml", "/mtd_down/common/"+curWidget.id+"/xmls/5.xml");
              self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/6.xml", "/mtd_down/common/"+curWidget.id+"/xmls/6.xml");
              self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/7.xml", "/mtd_down/common/"+curWidget.id+"/xmls/7.xml");
              self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/week.tstamp", "/mtd_down/common/"+curWidget.id+"/xmls/week.tstamp");
              var contenSD = self.soc_api1.Execute("GetListFiles",usbDir+"offline.data/content/");
              if(contenSD != "" && contenSD != null){
                  contenSD = JSON.parse(contenSD);
                  for (var j = 0; j < contenSD.length - 1; j++) {
                      self.soc_api1.Execute("Copy", usbDir+"offline.data/content/"+contenSD[j], "/mtd_down/common/"+curWidget.id+"/content/"+contenSD[j]);
                      self.log("copy to "+"/mtd_down/common/"+curWidget.id+"/content/"+contenSD[j]);
                  }
                  callback("copying")
              }
          }
          else{
              self.log("Error unzip offline.data");
              callback("Error unzip offline.data")
          }
      }
      catch(e){
          self.log(JSON.stringify(e));
          callback(JSON.stringify(e));
      }
    };

    this.writeFiles = function(callback){
        self.log("Internal memory deleted");
        self.log("---------------------------------------------------------------------2");
        self.overwrite_Filesystem("admira.txt", self.lic);
        self.soc_api1.Execute("Move", "/mtd_down/common/ADmiraSoC/admira.txt", "/mtd_down/common/ADmiraSoC/admira.lic");
        self.log("write license: "+self.lic);
        callback("deleteAll Completed -- Write admira.lic Completed ("+self.lic+") -- Reboot");
        setTimeout(function(){self.rebootSystem();},5000);

    };
    this.writeFiles2 = function(){
        self.log("Internal memory deleted");
        self.log("---------------------------------------------------------------------2");
        self.overwrite_Filesystem("admira.txt", self.lic);
        self.soc_api1.Execute("Move", "/mtd_down/common/ADmiraSoC/admira.txt", "/mtd_down/common/ADmiraSoC/admira.lic");
        self.log("write license: "+self.lic);

        try{
            var usbDir = '/$USB_DIR/sda1/';
            var ok = self.soc_api1.Execute("Unzip",usbDir+"offline.data.zip",usbDir+"offline.data/")
            if(parseInt(ok)){
                self.log("Unzip complete.");
                self.log("/mtd_down/common/"+curWidget.id+"/xmls/");
                self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/1.xml", "/mtd_down/common/"+curWidget.id+"/xmls/1.xml");
                self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/2.xml", "/mtd_down/common/"+curWidget.id+"/xmls/2.xml");
                self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/3.xml", "/mtd_down/common/"+curWidget.id+"/xmls/3.xml");
                self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/4.xml", "/mtd_down/common/"+curWidget.id+"/xmls/4.xml");
                self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/5.xml", "/mtd_down/common/"+curWidget.id+"/xmls/5.xml");
                self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/6.xml", "/mtd_down/common/"+curWidget.id+"/xmls/6.xml");
                self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/7.xml", "/mtd_down/common/"+curWidget.id+"/xmls/7.xml");
                self.soc_api1.Execute("Copy", usbDir+"offline.data/xmls/week.tstamp", "/mtd_down/common/"+curWidget.id+"/xmls/week.tstamp");
                var contenSD = self.soc_api1.Execute("GetListFiles",usbDir+"offline.data/content/");
                if(contenSD != "" && contenSD != null){
                    contenSD = JSON.parse(contenSD);
                    for (var j = 0; j < contenSD.length - 1; j++) {
                        self.soc_api1.Execute("Copy", usbDir+"offline.data/content/"+contenSD[j], "/mtd_down/common/"+curWidget.id+"/content/"+contenSD[j]);
                        self.log("copy to "+"/mtd_down/common/"+curWidget.id+"/content/"+contenSD[j]);
                        if(j = contenSD.length - 2){
                            //self.lfd_api1.Execute("rebootSystemCmd", "Reboot");
                            self.rebootSystem();
                        }
                    }
                }
            }
            else{
                self.log("Error unzip offline.data");
            }
        }
        catch(e){
            self.log(JSON.stringify(e));
        }
    };
    this.setContentRotation = function(options, callback_setContentRotation) {
    }

    this.getDisplayOrientation = function(callback,params) {

    }
    this.getInfoSystemPlus = function(callback){
      self.pluginLFDControl = document.getElementById("pluginSEF_FW");
      self.pluginLFDControl.Open("LFDControl", "1.000", "LFDControl");
      var result = {
        urlLauncher: null,
        menuOrientation: null,
        sourceOrientation : null
      }
      result.urlLauncher = self.pluginLFDControl.Execute("GetURLLauncherAddress")
      var nAngle = self.pluginLFDControl.Execute("GetMenuOrientation");
			var strangle = nAngle.toString();
			var getmenu;
			if(strangle == 0){ getmenu = "Landscape";}else { getmenu = "Portrait";}
      result.menuOrientation = getmenu;
      var nAngle2 =self.pluginLFDControl.Execute("GetSourceOrientation");
      var strangle2 = nAngle2.toString();
      var getsource;
      if(strangle2 == 0){ getsource = "Landscape";}else { getsource = "Portrait";}
      result.sourceOrientation = getsource;

      callback(result)
    };
    this.clearCache = function(callback) {
      callback("no function");
    };
    this.calculateReboot = function(callback) {
      callback("no function");
    };























    this.timerOnNew = [[],[],[],[],[],[],[]];
    this.timerOffNew = [[],[],[],[],[],[],[]];
    this.timers1 = [];
    this.timerDef = [];
    this.contadorClear = 0;
    this.lfdPluginTimer = document.getElementById('lfdPluginTimer');
    this.insertTimer = function(timerI, callback_insertTimer){
      self.log("insert timer: "+JSON.stringify(timerI));
      self.lfdPluginTimer.OnEvent = function(eventType, param1, param2){
        self.log("------------------------- OnEvent -------------------------");
        if(param1.substring(6,8)=="41"){
          if(param1.substring(8,10) == "A4" || param1.substring(8,10) == "A5" || param1.substring(8,10) == "A6" || param1.substring(8,10) == "AB" || param1.substring(8,10) == "AC"){
            self.log("insertTimer success: ");
          }
          else{
            if(param1.substring(8,10) == "AD" || param1.substring(8,10) == "AE"){
              self.log("insertTimer success: ");
            }
            else{
              self.log("insertTimer error: "+param1);
            }
          }
        }
        else{
          self.log("insertTimer error: "+param1);
        }
        self.log("------------------------- callback_insertTimer -------------------------");
        self.lfdPluginTimer.Close();
        callback_insertTimer();
      }
      //self.lfdPluginTimer.OnEvent =eventDD;
	    self.lfdPluginTimer.Open("LFD","1.000","LFD");
      self.log("------------------------- vamos a instart -------------------------");
	    self.lfdPluginTimer.Execute('SendLFDMsg', timerI);
    }
    this.calculateTimersOn = function(timersOn, callbackCalculateTimersOn){
      self.timerOnNew = [[],[],[],[],[],[],[]];
      for(var i=0;i<timersOn.length;i++){
        switch (timersOn[i].day) {
          case 1:
            self.timerOnNew[1].push(timersOn[i].hour);
            break;
          case 2:
            self.timerOnNew[2].push(timersOn[i].hour);
            break;
          case 3:
            self.timerOnNew[3].push(timersOn[i].hour);
            break;
          case 4:
            self.timerOnNew[4].push(timersOn[i].hour);
            break;
          case 5:
            self.timerOnNew[5].push(timersOn[i].hour);
            break;
          case 6:
            self.timerOnNew[6].push(timersOn[i].hour);
            break;
          case 0:
            self.timerOnNew[0].push(timersOn[i].hour);
            break;
        }
        if(i == timersOn.length-1){
          callbackCalculateTimersOn();
        }
      }
    }
    this.calculateTimersOff = function(timersOff, callbackCalculateTimersOff){
      self.timerOffNew = [[],[],[],[],[],[],[]];
      for(var i=0;i<timersOff.length;i++){
        switch (timersOff[i].day) {
          case 1:
            self.timerOffNew[1].push(timersOff[i].hour);
            break;
          case 2:
            self.timerOffNew[2].push(timersOff[i].hour);
            break;
          case 3:
            self.timerOffNew[3].push(timersOff[i].hour);
            break;
          case 4:
            self.timerOffNew[4].push(timersOff[i].hour);
            break;
          case 5:
            self.timerOffNew[5].push(timersOff[i].hour);
            break;
          case 6:
            self.timerOffNew[6].push(timersOff[i].hour);
            break;
          case 0:
            self.timerOffNew[0].push(timersOff[i].hour);
            break;
        }
        if(i == timersOff.length-1){
          callbackCalculateTimersOff();
        }
      }
    }
    this.createTimers = function(callback_createTimers){
      self.timers1 = [];
      for(var i=0; i<7; i++){
        if(self.timerOnNew[i].length >= self.timerOffNew[i].length){
          for(var j=0; j<self.timerOnNew[i].length;j++){
            var exist = _.findIndex(self.timers1, {"hourOn":self.timerOnNew[i][j], "hourOff":self.timerOffNew[i][j]});
            if(exist == (-1)){
              //creamos el timer
              self.timers1.push({"hourOn":self.timerOnNew[i][j], "hourOff":self.timerOffNew[i][j], "days":[i]});
            }
            else{
              //añadimos el día al timer
              //self.timer1[exist].days = self.timer1[exist].days + ""+i;
              self.timers1[exist].days.push(i);
            }
          }
        }
        else{
          for(var j=0; j<self.timerOffNew[i].length;j++){
            var exist = _.findIndex(self.timers1, {"hourOn":self.timerOnNew[i][j], "hourOff":self.timerOffNew[i][j]})
            if(exist == -1){
              //creamos el timer
              self.timers1.push({"hourOn":self.timerOnNew[i][j], "hourOff":self.timerOffNew[i][j], "days":[i]});
            }
            else{
              //añadimos el día al timer
              //self.timer1[exist].days = self.timer1[exist].days + ""+i;
              self.timers1[exist].days.push(i);
            }
          }
        }
        if(i == 6){
          self.log(JSON.stringify(self.timers1));
          callback_createTimers();
        }
      }
    }
    this.transformTimers = function(callback_transformTimers){
      self.timerDef = [];
      for(var i=0; i<self.timers1.length; i++){
        var hOn = null;
        var mOn = "00";
        var am_pmOn = null;
        var actOn = null;
        var repeat_On = "05";
        var days = [0,0,0,0,0,0,0,0];
        var hOff = null;
        var mOff = "00";
        var am_pmOff = null;
        var actOff = null;
        var repeat_Off = "05";
        var numberTimer = null;
        if(self.timers1[i].hourOn){
          if(self.timers1[i].hourOn > 12){
            hOn = self.timers1[i].hourOn - 12;
            hOn = parseInt(hOn).toString(16);
          	if(hOn.length == 1){
          		hOn = "0"+hOn;
          	}
            am_pmOn = "00";
          }
          else{
            if(self.timers1[i].hourOn == 0){
              hOn = 12;
              hOn = parseInt(hOn).toString(16);
            	if(hOn.length == 1){
            		hOn = "0"+hOn;
            	}
              am_pmOn = "01";
            }
            else{
              if(self.timers1[i].hourOn == 12){
                hOn = self.timers1[i].hourOn;
                hOn = parseInt(hOn).toString(16);
              	if(hOn.length == 1){
              		hOn = "0"+hOn;
              	}
                am_pmOn = "00";
              }
              else{
                hOn = self.timers1[i].hourOn;
                hOn = parseInt(hOn).toString(16);
              	if(hOn.length == 1){
              		hOn = "0"+hOn;
              	}
                am_pmOn = "01";
              }
            }
          }
          actOn = "01";
        }
        else{
          actOn = "00";
        }
        if(self.timers1[i].hourOff){
          if(self.timers1[i].hourOff > 12){
            hOff = self.timers1[i].hourOff - 12;
            hOff = parseInt(hOff).toString(16);
          	if(hOff.length == 1){
          		hOff = "0"+hOff;
          	}
            am_pmOff = "00";
          }
          else{
            if(self.timers1[i].hourOff == 0){
              hOff = 12;
              hOff = parseInt(hOff).toString(16);
            	if(hOff.length == 1){
            		hOff = "0"+hOff;
            	}
              am_pmOff = "01";
            }
            else{
              if(self.timers1[i].hourOff == 12){
                hOff = self.timers1[i].hourOff;
                hOff = parseInt(hOff).toString(16);
              	if(hOff.length == 1){
              		hOff = "0"+hOff;
              	}
                am_pmOff = "00";
              }
              else{
                hOff = self.timers1[i].hourOff;
                hOff = parseInt(hOff).toString(16);
              	if(hOff.length == 1){
              		hOff = "0"+hOff;
              	}
                am_pmOff = "01";
              }
            }
          }
          actOff = "01";
        }
        else{
          actOff = "00";
        }
        for(var j=0;j<self.timers1[i].days.length; j++){
          switch(self.timers1[i].days[j]) {
            case 0:
              days[7]=1;
              break;
            case 1:
              days[6]=1;
              break;
            case 2:
              days[5]=1;
              break;
            case 3:
              days[4]=1;
              break;
            case 4:
              days[3]=1;
              break;
            case 5:
              days[2]=1;
              break;
            case 6:
              days[1]=1;
              break;
          }
        }

        var daysHx = parseInt(days.join(""), 2).toString(16);
        if(daysHx.length == 1){
          daysHx = "0"+daysHx;
        }
        switch(i){
      		case 0:
      			numberTimer = "A4";
      		break;
      		case 1:
      			numberTimer = "A5";
      		break;
      		case 2:
      			numberTimer = "A6";
      		break;
      		case 3:
      			numberTimer = "AB";
      		break;
      		case 4:
      			numberTimer = "AC";
      		break;
      		case 5:
      			numberTimer = "AD";
      		break;
      		case 6:
      			numberTimer = "AE";
      		break;
      	}
        var id = "00";
        var volume = "00";
        var source = "14";
        var holiday = "00";
        self.timerDef.push(numberTimer + id + "0F" + hOn + mOn + am_pmOn + actOn + hOff + mOn + am_pmOff + actOff + repeat_On + daysHx + repeat_Off + daysHx + volume + source + holiday);
        if(i == self.timers1.length-1){
          callback_transformTimers();
        }
      }
    }
    this.controlFlowTemp = 0;
    this.controlFlow = function(){
      if(self.controlFlowTemp < self.timerDef.length){
        self.insertTimer(self.timerDef[self.controlFlowTemp], function(err, result){
          self.controlFlowTemp++;
          self.controlFlow();
        });
      }
      else{
        self.log("--------------------------- FINISH INSERT TIMERS -----------------------------");
      }
    }
    this.clearTimers = function(callback_clearTimers){
      self.log("------------------------- clearTimers -------------------------");
      self.lfdPluginTimer.OnEvent = function(eventType, param1, param2){
        if(param1.substring(6,8)=="41"){
      		self.contadorClear++;
      		if(self.contadorClear >= 7){
      			self.log("Deleted timers");
            self.lfdPluginTimer.Close();
            callback_clearTimers(null, true);
      		}
      		else{
            self.log("Timers borrandose. "+self.contadorClear);
      		}
      	}
        else{
          callback_clearTimers(false);
        }
      }
      self.log("------------------------- clearTimers 2 -------------------------");
      self.lfdPluginTimer.Open("LFD","1.000","LFD");
      self.log("------------------------- clearTimers 3-------------------------");
      self.contadorClear = 0;
      self.log("------------------------- clearTimers 4-------------------------");
	    self.lfdPluginTimer.Execute('SendLFDMsg', "A4000F000000000000000000000000001400");
      self.log("------------------------- clearTimers 5-------------------------");
      self.lfdPluginTimer.Execute('SendLFDMsg', "A5000F000000000000000000000000001400");
      self.log("------------------------- clearTimers 6-------------------------");
      self.lfdPluginTimer.Execute('SendLFDMsg', "A6000F000000000000000000000000001400");
      self.lfdPluginTimer.Execute('SendLFDMsg', "AB000F000000000000000000000000001400");
      self.lfdPluginTimer.Execute('SendLFDMsg', "AC000F000000000000000000000000001400");
      self.lfdPluginTimer.Execute('SendLFDMsg', "AD000F000000000000000000000000001400");
      self.lfdPluginTimer.Execute('SendLFDMsg', "AE000F000000000000000000000000001400");
      self.log("------------------------- clearTimers 7-------------------------");
    };
    this.calculateTimers = function(timersOn, timersOff){
      self.log("--------------------------- calculateTimers -----------------------------");
      self.log(timersOn);
      self.calculateTimersOn(timersOn, function(){
        self.calculateTimersOff(timersOff, function(){
          self.createTimers(function(){
            self.transformTimers(function(){
              self.clearTimers(function(err, result){
                if(!err){
                  self.controlFlowTemp = 0;
                  self.controlFlow();
                }
                else{
                  self.log("--------------------------- ERROR CLEAR TIMERS -----------------------------");
                }
              })
            })
          })
        })
      })
    }
    this.deteleAllTimers = function(){
      self.clearTimers(function(err, result){
        if(!err){
          self.log("--------------------------- ERROR deteleAllTimers -----------------------------");
        }
        else{
          self.log("--------------------------- deteleAllTimers -----------------------------");
        }
      })
    }
    this.getTimersI = function(timerGet, callback){
      self.log(timerGet);
      self.lfdPluginTimer.OnEvent = function(eventType, param1, param2){
        self.log("------------------------- OnEvent -------------------------");
        if(param1.substring(6,8)=="41"){
          var on_H = parseInt(param1.substring(10,12),16).toString();
  				if(on_H.length == 1){
  					on_H = "0"+on_H;
  				}
  				var on_M = parseInt(param1.substring(12,14),16).toString();
  				if(on_M.length == 1){
  					on_M = "0"+on_M;
  				}
  				var on_AM_PM = param1.substring(14,16);
  				var on_act = param1.substring(16,18);
  				var off_H = parseInt(param1.substring(18,20),16).toString();
  				if(off_H.length == 1){
  					off_H = "0"+off_H;
  				}
  				var off_M = parseInt(param1.substring(20,22),16).toString();
  				if(off_M.length == 1){
  					off_M = "0"+off_M;
  				}
  				var off_AM_PM = param1.substring(22,24);
  				var off_act = param1.substring(24,26);
  				var repeat_on = param1.substring(26,28);
  				var repeat_off = param1.substring(30,32);
  				var manualWeekday_on = parseInt(param1.substring(28,30),16).toString(2).split("");
  				var manualWeekday_off = parseInt(param1.substring(32,34),16).toString(2).split("");
  				var holiday = param1.substring(38,40);
  				if(repeat_on == "05"){
  					if(manualWeekday_on.length <= 8){
  						var newAdd = 8 - manualWeekday_on.length;
  						for (var i=0; i<newAdd; i++){
  							manualWeekday_on.unshift(0);
  						}
  					}
  				}
  				if(repeat_off == "05"){
  					if(manualWeekday_off.length <= 8){
  						var newAdd = 8 - manualWeekday_off.length;
  						for (var i=0; i<newAdd; i++){
  							manualWeekday_off.unshift(0);
  						}
  					}
  				}
  				var text={
  					on_H:on_H,
  					on_M:on_M,
  					on_AM_PM:on_AM_PM,
  					on_act:on_act,
  					off_H:off_H,
  					off_M:off_M,
  					off_AM_PM:off_AM_PM,
  					off_act:off_act,
  					repeat_on:repeat_on,
  					repeat_off:repeat_off,
  					manualWeekday_on:manualWeekday_on,
  					manualWeekday_off:manualWeekday_off,
  					holiday:holiday
  				};
          self.log(text);
          callback(null, text);
        }
        else{
          self.log("getTimer error: "+param1);
          callback(param1);
        }
        self.lfdPluginTimer.Close();
      }
	    self.lfdPluginTimer.Open("LFD","1.000","LFD");
	    self.lfdPluginTimer.Execute('SendLFDMsg', timerGet+"0000");
    };
    this.controlFlowTempGET = 0;
    this.resultGetTimers = [];
    this.valueTimers = ["A4", "A5", "A6", "AB", "AC", "AD", "AE"];
    this.controlFlowGET = function(){
      if(self.controlFlowTempGET < 7){
        self.log("----------------------------------------------- "+self.valueTimers[self.controlFlowTempGET])
        self.getTimersI(self.valueTimers[self.controlFlowTempGET], function(err, result){
          if(!err){
            self.log("...............................")
            self.log(JSON.stringify(result));
            self.resultGetTimers.push(result);
          }
          else{
            self.log("..................................E"+ JSON.stringify(err));
          }
          self.controlFlowTempGET++;
          self.controlFlowGET();
        });
      }
      else{
        self.log("--------------------------- FINISH GET TIMERS -----------------------------");
        self.log("123456789------------------");
        this.callback_getTimersV(self.resultGetTimers);
      }
    }
    this.getTimers = function(callback_getTimers){
      self.callback_getTimersV = callback_getTimers;
      self.resultGetTimers = [];
      self.controlFlowTempGET = 0;
      self.controlFlowGET();
    };



    this.pluginLFDControl;
    this.upgradeApplication = function (callback_upgradeApplication){
      callback_upgradeApplication("no function");
    };
    this.upgradeApplicationInsert = function(url, callback_upgradeApplicationInsert){
        self.pluginLFDControl = document.getElementById("pluginSEF_FW");
        self.pluginLFDControl.Open("LFDControl", "1.000", "LFDControl");
        self.pluginLFDControl.Execute("SetURLLauncherAddress",url)
        callback_upgradeApplicationInsert("URLLauncherAddress has been set : [ "+url+" ] Your system is going to reboot within 10 Seconds");
        setTimeout(function(){
            self.rebootSystem();
        }, 10000);
    }
    this.upgradeApplicationInstall = function(callback_upgradeApplicationInstall){
      self.pluginLFDControl = document.getElementById("pluginSEF_FW");
      self.pluginLFDControl.Open("LFDControl", "1.000", "LFDControl");
      self.pluginLFDControl.Execute("SetURLLauncherAddress","http://install.admira.com/soc/")
      callback_upgradeApplicationInstall("URLLauncherAddress has been set : [ http://install.admira.com/soc/ ] Your system is going to reboot within 10 Seconds");
      setTimeout(function(){
          self.rebootSystem();
      }, 10000);
    }
    this.upgradeApplicationNow = function(callback_upgradeApplicationNow){
        callback_upgradeApplicationNow("no function");
    }
    this.updateApplicationS = function(callback_updateApplicationS){
        callback_updateApplicationS("no function");
    }

    this.generateNewScreenController = function ( screen ){
    	var controller = false;
		return controller;
	}

    this.getStatusPanel = function(callback_getStatusPanel){
        self.pluginPanel = document.getElementById('pluginPanel');
        self.pluginPanel.OnEvent = function(eventType, param1, param2){
            self.pluginPanel.Close();
            if(param1.substring(6,8)=="41"){
                if(param1.substring(10,12) == "01"){
                    self.log("Panel Off");
                    callback_getStatusPanel(null, false);
                }
                else{
                    self.log("Panel On");
                    callback_getStatusPanel(null, true);
                }
            }
            else{
                callback_getStatusPanel("error");
            }
        };
        self.pluginPanel.Open("LFD","1.000","LFD");
        self.pluginPanel.Execute('SendLFDMsg', 'F90000');
    }
    this.setPanelOff = function(callback_setPanelOff){
        self.pluginPanel = document.getElementById('pluginPanel');
        self.pluginPanel.OnEvent = function(eventType, param1, param2){
            self.pluginPanel.Close();
            if(param1.substring(6,8)=="41"){
                if(param1.substring(10,12) == "01"){
                    self.log("Panel Off");
                    if(typeof(callback_setPanelOff) != "undefined"){
                      callback_setPanelOff(null, true);
                    }
                }
                else{
                    self.log("Panel On");
                    if(typeof(callback_setPanelOff) != "undefined"){
                      callback_setPanelOff(null, true);
                    }
                }
            }
            else{
              if(typeof(callback_setPanelOff) != "undefined"){
                callback_setPanelOff("error");
              }
            }
        };
        self.pluginPanel.Open("LFD","1.000","LFD");
        self.pluginPanel.Execute('SendLFDMsg', 'F9000101');
    }
    this.setPanelOn = function(callback_setPanelOn){
        self.pluginPanel = document.getElementById('pluginPanel');
        self.pluginPanel.OnEvent = function(eventType, param1, param2){
            self.pluginPanel.Close();
            if(param1.substring(6,8)=="41"){
                if(param1.substring(10,12) == "01"){
                    self.log("Panel Off");
                    callback_setPanelOn(null, false);
                }
                else{
                    self.log("Panel On");
                    if(typeof(callback_setPanelOn) != "undefined"){
                      callback_setPanelOn(null, true);
                    }

                }
            }
            else{
                if(typeof(callback_setPanelOn) != "undefined"){
                  callback_setPanelOn("error");
                }
            }
        };
        self.pluginPanel.Open("LFD","1.000","LFD");
        self.pluginPanel.Execute('SendLFDMsg', 'F9000100');
    }
    this.pluginLFD_FW = null;
    this.pluginDown_FW = null;
    this.callback_upgradeApplicationR = null;
    this.updateFirmware = function(data, callback_updateFirmware){
        //self.callback_upgradeApplicationR = callback_updateFirmware;
        self.log("data.url: "+data.url);
        self.pluginLFD_FW = document.getElementById("pluginSEF_FW");
    	self.pluginLFD_FW.Open("LFD", "1.000", "LFD");
    	self.pluginDown_FW = document.getElementById('pluginDownload_FW');
    	self.pluginDown_FW.OnComplete = function(msg){
            self.log("estamos en OnComplete");
            var arrParam = msg.split("?");
            if(arrParam.length == 2){
                if (arrParam[0]==1000 ) {
                    if(arrParam[1] == 1){
                        self.log('FW downloaded -- We proceed to installation');
                        self.pluginLFD_FW.Execute("setUpdate","/mtd_down/common/upgrade.msd");
                        callback_updateFirmware('FW downloaded -- We proceed to installation');
                    }
                    else{
                        self.log('Error FW download');
                        callback_updateFirmware("Error: "+arrParam[1]);
                    }
                }
                else if (arrParam[0]==1001 ){ //- download status check event
                    self.log("Descargando FW: "+arrParam[1] + "%");
                }
            }
            else {
                self.log(JSON.stringify(arrParam));
            }
        };
    	self.pluginDown_FW.StartDownFile(data.url, "/mtd_down/common/upgrade.msd", 0, 1);
    }
    this.changePictureMode = function(callback_changePictureMode){
        callback_changePictureMode("no function");
    }
    this.getPictureProperty = function(callback_getPictureProperty){
        callback_getPictureProperty("no function");
    }
    this.setPortraitMode = function(data, callback_setPortraitMode){
        callback_setPortraitMode("no function");
    }
    this.getContentRotation = function(callback_getContentRotation){
      self.pluginLFDControl = document.getElementById("pluginSEF_FW");
      self.pluginLFDControl.Open("LFDControl", "1.000", "LFDControl");
      var result = {
        menuOrientation: null,
        sourceOrientation : null
      }
      var nAngle = self.pluginLFDControl.Execute("GetMenuOrientation");
      var strangle = nAngle.toString();
      var getmenu;
      if(strangle == 0){ getmenu = "Landscape";}else { getmenu = "Portrait";}
      result.menuOrientation = getmenu;
      var nAngle2 =self.pluginLFDControl.Execute("GetSourceOrientation");
      var strangle2 = nAngle2.toString();
      var getsource;
      if(strangle2 == 0){ getsource = "Landscape";}else { getsource = "Portrait";}
      result.sourceOrientation = getsource;
      callback_getContentRotation(result);
    }
    this.setContentRotation = function(data, callback_setContentRotation){
        callback_setContentRotation("no function");
    }
    this.getVideoStatus = function(callback_getVideoStatus){
        callback_getVideoStatus("no function");
    }
    this.checkSize = function(filename,callback,params){
        callback(false)
    };
    this.shellExec = function(command,callback,params){
      var result = "";
      if(typeof(callback) !== "undefined"){
          callback(result,command,params);
      }
    };

    this.findSyncIp = function (callback){
      var info = self.getNetworkInfo();
      if(typeof(callback) !== "undefined"){
        callback(info.ip);
      }
    };
    this.getPowerOnOffHistory = function(callback_getPowerOnOffHistory){
        callback_getPowerOnOffHistory("no function");
    }
    this.getBrigthness = function(callback_getBrigthness){
        callback_getBrigthness("no function");
    }
    this.setBrightness = function(brightness, callback_setBrightness){
        callback_setBrightness("no function");
    }
    this.getContrast = function(callback_getContrast){
        callback_getContrast("no function");
    }
    this.setContrast = function(contrast, callback_setContrast){
        callback_setContrast("no function");
    }
    this.getBacklight = function(callback_getBacklight){
        callback_getBacklight("no function");
    }
    this.setBacklight = function(backlight, callback_setBacklight){
        callback_setBacklight("no function");
    }
    this.geConfigPanel = function(callback_geConfigPanel){
        callback_geConfigPanel("no function");
    }
    this.setConfigPanel = function(data, callback_setConfigPanel){
        callback_setConfigPanel("no function");
    }
    this.setNativePortraitMode = function(data, mode, callback_setNativePortraitMode){
      self.pluginLFDControl = document.getElementById("pluginSEF_FW");
      self.pluginLFDControl.Open("LFDControl", "1.000", "LFDControl");
      if(mode == "off"){ // off equivale a 0
        var str = self.pluginLFDControl.Execute("SetMenuOrientation", "0");
        var str2 = self.pluginLFDControl.Execute("SetSourceOrientation", "0");
        callback_setNativePortraitMode("SetMenuOrientation [Landscape] : "+str + "  "+str2)
      }
      else{
        if(mode == "90"){
          var str = self.pluginLFDControl.Execute("SetMenuOrientation", "1");
          var str2 = self.pluginLFDControl.Execute("SetSourceOrientation", "1");
          callback_setNativePortraitMode("SetMenuOrientation [Portrait] : "+str+ "  "+str2)
        }
        else{
          callback_setNativePortraitMode("giro no soportado")
        }
      }
    }
    this.getStatusRemoteControl = function(callback_getStatusRemoteControl){
      self.pluginLFDControl = document.getElementById("pluginSEF_FW");
      self.pluginLFDControl.Open("LFDControl", "1.000", "LFDControl");
      callback_getStatusRemoteControl(self.pluginLFDControl.Execute("GetRemoteControlStatus"))
    }
    this.setStatusRemoteControl = function(data, callback_setStatusRemoteControl){
        self.pluginLFDControl = document.getElementById("pluginSEF_FW");
        self.pluginLFDControl.Open("LFDControl", "1.000", "LFDControl");
        var re;
        if(data == "OFF"){
          re = self.pluginLFDControl.Execute("SetRemoteControlOnOff", "OFF");
        }
        else{
          re = self.pluginLFDControl.Execute("SetRemoteControlOnOff", "ON");
        }
        callback_setStatusRemoteControl(re);
    }
}
SoCSystemController.prototype = new SystemController();
