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

	  var self = this; self.name = "WebOsSystemController"; // MANDATORY
    this.service_id = "luna://com.lg.app.signage.webos/";
    this.rootDir = "/media/internal/";
    this.appDir = "";
    this.realDir = "";
    this.service_start_timer = 0;

    this.ready_callback = false;
    this.systemIsUpdating = false;
    this.device_has_internet = true;
    this.proxy_info = undefined;

    this.dataInfoSystem = null;
    this.sendInfoSystem = false;
    this.superEco = false;
    this.eco = false;
    this.screenshotServer = null;
    this.id_content_now = null;
    this.busy = false;

    this.infoPlus = null;
    this.timersSystem = {};
    this.os_loaded = false;

    this.uses_texture_graphics = false;
    this.SocketConnector = undefined;

    this.sync_master_supported = true;

    this.websocket_server = false;
    this.websocket_onOpenCallback = false;
    this.websocket_onMessageCallback = false;
    this.websocket_onTerminatedCallback = false;

    this.system_ip = "0.0.0.0";

    this.init = function(callback){
      self.log("WebOS Initiating ...");
      self.SocketConnector = new SocketConnector(self);
      self.log("SocketConnector Initiating ...");
        self.ready_callback = callback;
        self.log("Setting Callback for System ...");
        if(!self.os_loaded){
            self.os_loaded = true;
            self.service_start_timer = setTimeout(self.checkServiceIsUp,1000);
        }else{
          clearTimeout(EMERGENCY_TIMER);
          self.ready_callback();
          self.setKeepAliveModeOnMemoryLeak();
          try{
            self.setFailoverMode("OFF", "", function(r){self.log(r);});
          }catch(e){
            self.log("Could not set setFailoverMode = OFF");
          }
        }
    };

    this.checkServiceIsUp = function(){
      self.log("Waitting for Service to come up ...");
      clearTimeout(self.service_start_timer);
      if(self.realDir == ""){
        self.getRootDir();
        self.service_start_timer = setTimeout(self.checkServiceIsUp,1000);
      }else{
        clearTimeout(EMERGENCY_TIMER);
        self.log("Real Dir on Service Started OK is : "+self.realDir);
        self.log("Using URL : "+document.location.href);
        self.log("And path should is : "+self.realDir);
        if(document.location.href == "file:///media/cryptofs/apps/usr/palm/services/com.lg.app.signage.webos/app/webos3.html"
        || document.location.href == "file:///media/cryptofs/apps/usr/palm/services/com.lg.app.signage.webos/app/webos2.html"){
          self.log("Uses old school installation ...");
          self.rootDir = self.realDir+"/";
          self.ROUTES["STYLE"].path = "style/";
        }else{
          self.ROUTES["STYLE"].path = "app/style/";
          self.log("Uses new installation system");
          self.appDir = self.realDir+"/";
          self.copyOldConfigFile(self.ROUTES['LICENSE'].path);
          self.copyOldConfigFile(self.ROUTES['VER'].path);
          //self.copyVersionName();
        }
        self.log("RealPath is = "+self.realDir);
        self.log("RootDir is = "+self.rootDir);
        self.log("AppDir is = "+self.appDir);
        self.checkFolders();
        self.checkCoreFile();
      }
    };

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

    this.copyOldConfigFile = function(filename){
      self.fileExists(filename,function(exists,file_ref,params){
        if(!exists){
          self.readFile(self.realDir+filename,function(data,file_ref,params){
            if(data != ""){
              self.writeFile(filename,data,function(written,file_ref,params){
                if(written){
                  self.log("Old "+filename+" Found and installed");
                }else{
                  self.log("Old "+filename+" Found but not installed");
                }
              });
            }else{
              self.log("Old "+filename+" NOT Found. No data");
            }
          },{'absolute_path':true});
        }
      });
    };

    this.checkFolders = function(){
        self.log("Checking folders ...");
        var exists = false;
        for(var route in self.ROUTES){
            if(self.ROUTES[route].isFolder && !self.ROUTES[route].exists){
                self.makeDir(self.ROUTES[route].path);
                self.ROUTES[route].exists = exists;
            }
        }
        self.log("Folders checked ...");
    };

    this.checkCoreFile = function(){
        self.log("Checking core ...");
        self.fileExists(self.ROUTES['CORE'].path,function(exists,file_ref){
            self.log("Core checked ...");
            if(exists){
                self.checkConfigFile();
            }else{
                self.createCoreFile();
            }
        });
    };

    this.createCoreFile = function(){
        var xml_data = '<?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.writeFile(self.ROUTES['CORE'].path,xml_data,function(){
            self.checkConfigFile();
        });
        var style_data = '<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg  xmlns="http://www.w3.org/2000/svg"  version="1.1" id="SVG_1"  x="0px" y="0px" enable-background="new 0 0 100% 100%" style="background-color:#000"><circle cx="98%" cy="98%" r="0.5%" style="stroke: #68983F; fill: #68983F;"><animate id="animation1" attributeName="opacity" from="0" to="1" dur="1s" begin="0s;animation2.end" /><animate id="animation2" attributeName="opacity" from="1" to="0" dur="1s" begin="animation1.end" /></circle></svg>';
        self.writeFile(self.ROUTES['STYLE'].path+"logo.svg",style_data,function(){
           self.log("LOGO File created ! ");
        });

    };

    this.checkConfigFile = function(){
        self.log("Checking config ...");
        self.fileExists(self.ROUTES['CONFIG'].path,function(exists,file_ref){
            self.log("Config checked ...");
            if(exists){
                self.checkDataXmlFile();
            }else{
                self.createConfigFile();
            }
        });
    };

    this.createConfigFile = function(){
        self.log("Creating Config file ...");
        var xml_data = '<config><data file="datos.xml"/><paths multiplayer_delimiter="_" xmls="xmls/" content="content/" temp="temp/" modules="modules/" log="log/" stadistics="stats/"/><params bumper_content="assets/downloading.swf" bumper_duration="56" alwaysontop="1"/></config>';
        self.writeFile(self.ROUTES['CONFIG'].path,xml_data,function(){
            self.log("Config file created ...");
            self.checkDataXmlFile();
        });
    };

    this.checkDataXmlFile = function(){
        self.log("Checking XML file ...");
        var filename = self.getDayOfWeek()+".xml";
        self.fileExists(self.ROUTES['XML'].path+filename,function(exists,file_ref){
            self.log("XML file checked ...");
            if(exists){
                self.ready_callback();
                //self.log("READY");
            }else{
                self.createDataXmlFile();
            }
        });
    };

    this.createDataXmlFile = function(){
        self.log("Creating XML file ...");
        var filename = self.getDayOfWeek()+".xml";
        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>';
        self.writeFile(self.ROUTES['XML'].path+filename,xml_data,function(){
            self.log("XML file created ...");
            self.ready_callback();
        });
    }

    this.writeFile = function(filename,value,callback,params){
            var rootDir = self.rootDir;
            if(typeof(params) !== "undefined"){
              if(typeof(params.absolute_path) !== "undefined"){
                if(params.absolute_path){
                  rootDir = "";
                }
              }
            }
            var request = webOS.service.request(self.service_id,{
            method:"writeFile",
            parameters: {
                filename: rootDir+filename,
                data: value,
                append: false
            },
            onSuccess: function(inResponse){
                //self.log("writeFile success ... "+inResponse.returnValue);
                if(typeof(callback) !== "undefined"){
                    callback(inResponse.returnValue,filename,params);
                }
            },
            onFailure: function(inError){
                //self.log("writeFile fail ... "+inError.errorText);
                if(typeof(callback) !== "undefined"){
                    callback(false,filename,params);
                }
            },
            onComplete: function(inResponse) {
                //self.log("writeFile complete ... "+inResponse.returnValue);
            }
        });
    };

    this.appendFile = function(filename,value,callback,params){
        var request = webOS.service.request(self.service_id,{
            method:"writeFile",
            parameters: {
                filename: self.rootDir+filename,
                data: value,
                append: true
            },
            onSuccess: function(inResponse){
                self.log("appendFile success ... "+inResponse.returnValue);
                if(typeof(callback) !== "undefined"){
                    callback(inResponse.returnValue,filename,params);
                }
            },
            onFailure: function(inError){
                self.log("appendFile fail ... "+inError.errorText);
                if(typeof(callback) !== "undefined"){
                    callback(false,filename,params);
                }
            },
            onComplete: function(inResponse) {
                self.log("appendFile complete ... "+inResponse.returnValue);
            }
        });
    };

    this.readFile = function(filename,callback,params){
            var rootDir = self.rootDir;
            if(typeof(params) !== "undefined"){
              if(typeof(params.absolute_path) !== "undefined"){
                if(params.absolute_path){
                  rootDir = "";
                }
              }
            }
            var request = webOS.service.request(self.service_id,{
            method:"readFile",
            parameters: {
                filename: rootDir+filename
            },
            onSuccess: function(inResponse){
                //self.log("readFile success ... "+inResponse.returnValue);
                var data = "";
                var ok = inResponse.returnValue;
                if(ok){
                    data = inResponse.response;
                }
                if(typeof(callback) !== "undefined"){
                    callback(data,filename,params);
                }
            },
            onFailure: function(inError){
                //self.log("readFile fail ... "+inError.errorText);
                if(typeof(callback) !== "undefined"){
                    callback("",filename,params);
                }
            },
            onComplete: function(inResponse){
                //self.log("readFile complete ... "+inResponse.returnValue);
            }
        });
    };

    this.fileHash = function(filename,callback,params){
      self.log("### Actual Root Dir : "+self.rootDir);
      self.log("### Trying to read HASH from filename : "+filename);
      try{
        var request = webOS.service.request(self.service_id,{
            method:"fileHash",
            parameters: {
                filename: filename
            },
            onSuccess: function(inResponse){
                self.log("fileHash sucess ... filename: "+filename+" > "+inResponse.response);
                var hash = inResponse.response;
                if(typeof(callback) !== "undefined"){
                    callback(hash,filename,params);
                }
            },
            onFailure: function(inError){
                self.log("fileHash fail ... for filename: "+filename);
                self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+11,self.name+": Function fileHash() failed : could not get SHA1 from : "+filename);
                if(typeof(callback) !== "undefined"){
                    callback("",filename,params);
                }
            },
            onComplete: function(inResponse){
                //self.log("fileHash complete ... "+inResponse.returnValue +  "filename: "+filename);
            },
            subscribe : true
        });
      }catch(e){
        if(typeof(callback) !== "undefined"){
            callback("",filename,params);
        }
      }
    };

    this.fileExists = function(filename,callback,params){
        var rootDir = self.rootDir;
        if(typeof(params) !== "undefined"){
          if(typeof(params.absolute_path) !== "undefined"){
            if(params.absolute_path){
              rootDir = "";
            }
          }
        }
        var request = webOS.service.request(self.service_id,{
            method:"fileExists",
            parameters: {
                filename: rootDir+filename
            },
            onSuccess: function(inResponse){
                //self.log("fileExists sucess ... filename: "+filename);
                var ok = inResponse.returnValue;
                if(typeof(callback) !== "undefined"){
                    callback(ok,filename,params);
                }
            },
            onFailure: function(inError){
                //self.log("fileExists fail ... "+inError.errorText + "filename: "+filename);
                if(typeof(callback) !== "undefined"){
                    callback(false,filename,params);
                }
            },
            onComplete: function(inResponse){
                //self.log("fileExists complete ... "+inResponse.returnValue +  "filename: "+filename);
            }
        });
    };

    this.makeDir = function(path,callback,params){
        var request = webOS.service.request(self.service_id,{
            method:"makeDir",
            parameters: {
                filename: self.rootDir+path
            },
            onSuccess: function(inResponse){
                self.log("makeDir "+path+" success ... "+inResponse.returnValue);
                var ok = inResponse.returnValue;
                if(typeof(callback) !== "undefined"){
                    callback(ok,path,params);
                }
            },
            onFailure: function(inError){
                self.log("makeDir "+path+" fail ... "+inError.errorText);
                if(typeof(callback) !== "undefined"){
                    callback(false,path,params);
                }
            },
            onComplete: function(inResponse){
                //self.log("makeDir "+path+"  complete ... "+inResponse.returnValue);
            }
        });
    };

    this.modificationDate = function(filename,callback,params){
        try{
            var request = webOS.service.request(self.service_id,{
                method:"modificationDate",
                parameters: {
                    filename: self.rootDir+filename
                },
                onSuccess: function(inResponse){
                    //self.log("modificationDate onSuccess ... "+JSON.stringify(inResponse));
                    var data = 1;
                    var ok = inResponse.returnValue;
                    if(ok){
                        data = inResponse.response;
                    }
                    if(typeof(callback) !== "undefined"){
                        callback(data,filename,params);
                    }
                },
                onFailure: function(inError){
                    self.log("modificationDate fail ... "+inError.errorText);
                    if(typeof(callback) !== "undefined"){
                        callback("",filename,params);
                    }
                },
                onComplete: function(inResponse){
                    //self.log("modificationDate onComplete ... "+JSON.stringify(inResponse));
                }
            });
        }
        catch(e){
            self.log("modificationDate error catch "+JSON.stringify(e));
            if(typeof(callback) !== "undefined"){
                callback("",filename,params);
            }
        }

    };

    this.downloadFile = function(url,destFolder,callback,params){
        try{
          var timestamp = 1;
          var filename = url;
          var content_type = "";
          var content_id = 0;
          var file_ref = "";
          var stored_hash = "";
          filename = filename.substring(filename.lastIndexOf("/")+1,filename.length);
          if(typeof(params) !== "undefined"){
              if(typeof(params.filename) !== "undefined"){
                  filename = params.filename;
              }
              if(typeof(params.xml_timestamp) !== "undefined"){
                  timestamp = params.xml_timestamp;
              }
              if(typeof(params.content_id) !== "undefined"){
                  content_id = params.content_id;
              }
              if(typeof(params.content_type) !== "undefined"){
                  content_type = params.content_type;
              }
              if(typeof(params.file_ref) !== "undefined"){
                  file_ref = params.file_ref;
              }
              if(typeof(params.hash) !== "undefined"){
                  stored_hash = params.hash;
              }
          }

          self.log("downloadFile ... "+filename);
          var request = webOS.service.request(self.service_id,{
              method:"downloadFile",
              parameters: {
                  url: url,
                  destination: self.rootDir+destFolder,
                  temp: self.rootDir+self.ROUTES['TMP'].path,
                  filename: filename,
                  xml_timestamp:timestamp,
                  hash:stored_hash,
                  proxy:self.proxy_info
              },
              onSuccess: function(inResponse){
                  var hash = "";
                  if(typeof(inResponse.hash) !== "undefined"){
                      self.log("SHA1 Check passed XML = "+stored_hash+" Downloaded : "+inResponse.hash);
                      hash = inResponse.hash;
                  }
                  if(typeof(inResponse.finished) != "undefined"){
                    var finished = inResponse.finished;
                    if(!finished){
                      self.log("downloadFile percent : "+inResponse.response+"% for file : "+filename);
                    }else{
                      self.log("downloadFile success ... "+inResponse.returnValue);

                      var params = {'filename':filename,
                                    'xml_timestamp':inResponse.response,
                                    'content_id':content_id,
                                    'content_type':content_type,
                                    'file_ref':file_ref,
                                    'sha1':hash
                                   };
                      if(typeof(callback) !== "undefined"){
                          callback(true,url,params);
                      }
                    }
                  }else{
                    self.log("downloadFile success ... "+inResponse.returnValue);
                    var params = {'filename':filename,
                                  'xml_timestamp':inResponse.response,
                                  'content_id':content_id,
                                  'content_type':content_type,
                                  'file_ref':file_ref,
                                  'sha1':hash
                                 };
                    if(typeof(callback) !== "undefined"){
                        callback(true,url,params);
                    }
                  }
              },
              onFailure: function(inError){
                  self.log("downloadFile fail ... "+inError.errorText);
                  if(typeof(callback) !== "undefined"){
                      callback(false,url,params);
                  }
              },
              onComplete: function(inResponse){
                  self.log("downloadFile complete ... "+inResponse.returnValue);
              },
              subscribe : true
          });
        }catch(e){
          self.log("downloadFile failed ... ");
          if(typeof(callback) !== "undefined"){
              callback(false,url,params);
          }
        };
    };

    this.unzipFile = function(filename,destFolder,callback,params){
        try{
          self.log("Trying to unzip file : "+filename);
          var request = webOS.service.request(self.service_id,{
            method:"unzipFile",
            parameters: {
                filename: self.rootDir+filename,
                destination: self.rootDir+destFolder
            },
            onSuccess: function(inResponse){
                self.log("uzipped success to : "+self.rootDir+destFolder);
                if(typeof(inResponse.finished) != "undefined"){
                  var finished = inResponse.finished;
                  if(!finished){
                    self.log("unzipFile extracted : "+inResponse.extracted_zip_items+" / "+inResponse.total_zip_items);
                  }else{
                    var completed = inResponse.completed;
                    self.log("uzipped complete correctly : "+completed);
                    self.log("uzipped finished on : "+self.rootDir+destFolder);
                    if(typeof(callback) !== "undefined"){
                        callback(completed,filename,params);
                    }
                  }
                }else{
                  self.log("uzipped success to : "+self.rootDir+destFolder);
                  if(typeof(callback) !== "undefined"){
                      callback(true,filename,params);
                  }
                }
            },
            onFailure: function(inError){
              self.log("unzipFile fail ... "+inError.errorText);
              if(typeof(callback) !== "undefined"){
                  callback(false,filename,params);
              }
            },
            onComplete: function(inResponse){
                self.log("unzipFile complete ... "+inResponse.returnValue);
            },
            subscribe : true
        });
      }catch(e){
        self.log("unzipFile failed ... ");
        if(typeof(callback) !== "undefined"){
            callback(false,filename,params);
        }
      };
    };

    this.readDirectory = function(directory,callback,params){
        var rootDir = self.rootDir;
        if(typeof(params) !== "undefined"){
          if(typeof(params.absolute_path) !== "undefined"){
            if(params.absolute_path){
              rootDir = "";
            }
          }
        }
        var request = webOS.service.request(self.service_id,{
            method:"readDirectory",
            parameters: {
                filename: rootDir+directory
            },
            onSuccess: function(inResponse){
                var data = [];
                var ok = inResponse.returnValue;
                if(ok){
                    var data_string = inResponse.response.toString();
                    //self.log("readDirectory ...  data string : "+data_string);
                    data = data_string.split(",");
                }
                if(typeof(callback) !== "undefined"){
                    callback(data,directory,params);
                }
            },
            onFailure: function(inError){
                self.log("readDirectory fail ... "+inError.errorText);
                if(typeof(callback) !== "undefined"){
                    callback([],directory,params);
                }
            },
            onComplete: function(inResponse){
                //self.log("readDirectory complete ... ");
            }
        });
    };

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

    this.deleteFile = function(filename,callback,params){
            var rootDir = self.rootDir;
            if(typeof(params) !== "undefined"){
              if(typeof(params.absolute_path) !== "undefined"){
                if(params.absolute_path){
                  rootDir = "";
                }
              }
            }
            var request = webOS.service.request(self.service_id,{
            method:"deleteFile",
            parameters: {
                filename: rootDir+filename
            },
            onSuccess: function(inResponse){
                self.log("deleteFile success ... "+inResponse.returnValue);
                var ok = inResponse.returnValue;
                if(typeof(callback) !== "undefined"){
                    callback(ok,filename,params);
                }
            },
            onFailure: function(inError){
                self.log("deleteFile fail ... "+inError.errorText);
                if(typeof(callback) !== "undefined"){
                    callback(false,filename,params);
                }
            },
            onComplete: function(inResponse){
                self.log("deleteFile complete ... "+inResponse.returnValue);
            }
        });
    };

    this.deleteFileRecursive = function(filename,callback,params){
        var request = webOS.service.request(self.service_id,{
            method:"deleteFileRecursive",
            parameters: {
                filename: self.rootDir+filename
            },
            onSuccess: function(inResponse){
                self.log("deleteFileRecursive success ... "+inResponse.returnValue);
                var ok = inResponse.returnValue;
                if(typeof(callback) !== "undefined"){
                    callback(ok,filename,params);
                }
            },
            onFailure: function(inError){
                self.log("deleteFileRecursive fail ... "+inError.errorText);
                if(typeof(callback) !== "undefined"){
                    callback(false,filename,params);
                }
            },
            onComplete: function(inResponse){
                self.log("deleteFileRecursive complete ... "+inResponse.returnValue);
            }
        });
    };

    this.deleteFilesInDir = function(dir,filter,callback,params){
      // TODO
    };

    this.moveFile = function(source,destination,callback,params){
        var rootDir = self.rootDir;
        if(typeof(params) !== "undefined"){
          if(typeof(params.absolute_path) !== "undefined"){
            if(params.absolute_path){
              rootDir = "";
            }
          }
        }
        var request = webOS.service.request(self.service_id,{
            method:"moveFile",
            parameters: {
                source: rootDir+source,
                destination: rootDir+destination,
            },
            onSuccess: function(inResponse){
                self.log("moveFile success ... "+inResponse.returnValue);
                var ok = inResponse.returnValue;
                if(typeof(callback) !== "undefined"){
                    callback(ok,source,params);
                }
            },
            onFailure: function(inError){
                self.log("moveFile fail ... "+inError.errorText);
                if(typeof(callback) !== "undefined"){
                    callback(false,source,params);
                }
            },
            onComplete: function(inResponse){
              self.log("moveFile complete ... "+inResponse.returnValue);
            }
        });
    };

    this.copyFile = function(source,destination,callback,params){
        var rootDir = self.rootDir;
        if(typeof(params) !== "undefined"){
          if(typeof(params.absolute_path) !== "undefined"){
            if(params.absolute_path){
              rootDir = "";
            }
          }
        }
        var request = webOS.service.request(self.service_id,{
            method:"copyFilesRecursive",
            parameters: {
                source: rootDir+source,
                destination: rootDir+destination,
            },
            onSuccess: function(inResponse){
                self.log("copyFilesRecursive success ... "+inResponse.returnValue);
                self.log("copyFilesRecursive Response : "+inResponse.response);
                var ok = inResponse.returnValue;
                if(typeof(callback) !== "undefined"){
                    callback(ok,source,params);
                }
            },
            onFailure: function(inError){
                self.log("copyFilesRecursive fail ... "+inError.errorText);
                if(typeof(callback) !== "undefined"){
                    callback(false,source,params);
                }
            },
            onComplete: function(inResponse){
              self.log("copyFilesRecursive complete ... "+inResponse.returnValue);
            }
        });
    };

    this.systemUpdate = function(update_folder,platform){
        //TODO !!!
        // On updated systems copyFile will be available for Recursive copy ... but not since they are double updated (2 system updates)
        // For this reason we keep using moveFile method on coping update files from upgrade.zip
        // TODO is needed to detect if copyFile is available and use it instead of moveFile ... only if is available !! so it has to fallback to moveFile if it can not copyFile

        self.log("Updating the system .... : "+platform);
        self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+1,self.name+": Trying to update app ... is already updating ? = "+self.systemIsUpdating);
        if(!self.systemIsUpdating){
            self.systemIsUpdating = true;
            setTimeout(function(){
              // System updating timeout
              if(self.systemIsUpdating){
                self.log("Updating the system TIMEOUT !!");
                self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+1,self.name+": Updating the system TIMEOUT !! Impossible to copy files. Was updating : "+self.systemIsUpdating);
              }
              self.systemIsUpdating = false;
            },60000);
            self.deleteFileRecursive("app_backup/",function(ok,file_ref,params){
                self.log("app_backup deleted : "+ok);
                self.moveFile("app/","app_backup/",function(ok,file_ref,params){
                    self.log("app to app_backup moved : "+ok);
                    self.moveFile(self.ROUTES['MAIN_HTML'].path,self.ROUTES['MAIN_HTML'].path+".bck",function(){
                      self.moveFile(update_folder+"files/"+self.ROUTES['MAIN_HTML'].path,self.ROUTES['MAIN_HTML'].path,function(ok,file_ref,params){
                        self.log("main html moved : "+ok);
                        self.moveFile(update_folder+"files/app/","app/",function(ok,file_ref,params){
                          self.log(update_folder+"files/app/ to app/ :"+ok);
                            self.moveFile(update_folder+"files/webos-service/com.lg.app.signage.webos/services.json","services.json",function(ok,file_ref,params){
                              self.log("services.json moved : "+ok);
                              self.moveFile(update_folder+"files/webos-service/com.lg.app.signage.webos/WebOsService.js","WebOsService.js",function(ok,file_ref,params){
                                self.log("WebOsService.json moved : "+ok);
                                self.moveFile(update_folder+"files/webos-service/node_modules/","new_node_modules/",function(ok,file_ref,params){
                                  self.log("node_modules moved : "+ok);
                                  self.deleteFileRecursive(self.ROUTES['VER'].path,function(ok,file_ref,params){
                                     self.log("delete admira.ver : "+ok);
                                     self.moveFile(update_folder+"files/"+self.ROUTES['VER'].path,self.ROUTES['VER'].path,function(){
                                         self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+2,self.name+": App Update complete !");
                                         self.log("App Update complete !");
                                         self.systemIsUpdating = false;
                                         setTimeout(function(){
                                           self.rebootSystem();
                                         },2000);
                                     });
                                   });
                                });
                              });
                            });
                        });
                      });
                    });
                });
            });
        }
    };

    this.systemRepairUpdate = function(){
      self.fileExists("app_backup/",function(exists,file_ref,params){
        if(exists){
          self.deleteFileRecursive("app/",function(ok,file_ref,params){
            self.moveFile("app_backup/","app/",function(ok,file_ref,params){
              self.log("Repaired : app/");
              self.fileExists(self.ROUTES['MAIN_HTML'].path+".bck",function(exists,file_ref,params){
                if(exists){
                  self.moveFile(self.ROUTES['MAIN_HTML'].path+".bck",self.ROUTES['MAIN_HTML'].path,function(ok,file_ref,params){
                    self.log("Repaired : "+self.ROUTES['MAIN_HTML'].path);
                  });
                }
              });
              self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+2,self.name+": App Folder Repaired ! ... please try to update again");
              self.log("App Folder Repaired !");
              self.writeFile(self.ROUTES['VER'].path,"REPAIR",function(ok,file_ref,params){
                if(ok){
                  self.log("App Folder Repaired ! Version Name changed ... please try to update again");
                }
              });
            });
          });
        }else{
          self.log("Could NOT repair App Folder ! app_backup does not exist ");
        }
      });
    };

    this.setTimeZone1 = function(timestamp,callback,params){
        function successCb(cbObject) {
            self.log(JSON.stringify(cbObject))
            self.setSystemDateTime2(timestamp,callback,params);
        }

        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject))
            self.setSystemDateTime2(timestamp,callback,params);
        }

        /*var timeZone = {
            continent: "Europe",
            country: "United Kingdom",
            city: "London"
        };*/
        var timeZone = {
            continent: "Africa",
            country: "Senegal",
            city: "Dakar"
        };
        /*var timeZone = {
            continent: "Europe",
            country: "Spain",
            city: "Madrid"
        };*/
        var options = {
            timeZone: timeZone
        };
        self.log(JSON.stringify(timeZone))
        var configuration = new Configuration();
        configuration.setTimeZone(successCb, failureCb, options);
    }
    this.setSystemDateTime = function(timestamp,callback,params){
        self.getTimeZone1(timestamp,callback,params);
    };
    this.getTimeZone1 = function(timestamp,callback,params){
        function successCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            if(cbObject.timeZone.city == "Senegal"){
                self.setSystemDateTime2(timestamp,callback,params);
            }
            else{
                self.setSystemDateTime3(timestamp,callback,params);
            }
        }
        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            self.setSystemDateTime2(timestamp,callback,params);
        }
        var configuration = new Configuration();
        configuration.getTimeZone(successCb, failureCb);
    }
    this.setSystemDateTime2 = function(timestamp,callback,params){
      self.log("Setting WebOS Time 1: " + timestamp);
      var date = new Date(timestamp*1000); // In milliseconds
      var options = {};
      options.year = parseInt(moment.utc(date).format('YYYY'));
      options.month = parseInt(moment.utc(date).format('M'));
      options.day = parseInt(moment.utc(date).format('D'));
      options.hour = parseInt(moment.utc(date).format('H'));
      options.minute = parseInt(moment.utc(date).format('m'));
      options.sec = parseInt(moment.utc(date).format('s'));
      options.ntp = false;
      self.log(options);
      function successCb() {
        if(typeof(callback) !== "undefined"){
            callback(true,params);
        }
      }
      function failureCb(cbObject) {
          self.log("Error Code [" + errorCode + "]: " + errorText);
          if(typeof(callback) !== "undefined"){
              callback(false,params);
          }
      }
      var configuration = new Configuration();
      configuration.setCurrentTime(successCb, failureCb, options);
    };
    this.setSystemDateTime5 = function(timestamp,callback,params){
      self.log("Setting WebOS Time 5: " + timestamp);
      var date = new Date(timestamp*1000); // In milliseconds
      var options = {};
      options.year = parseInt(moment.utc(date).format('YYYY'));
      options.month = parseInt(moment.utc(date).format('M'));
      options.day = parseInt(moment.utc(date).format('D'));
      options.hour = parseInt(moment.utc(date).format('H'));
      options.minute = parseInt(moment.utc(date).format('m'));
      options.sec = parseInt(moment.utc(date).format('s'));
      options.ntp = false;
      self.log(options);
      function successCb() {
        if(typeof(callback) !== "undefined"){
            callback(true,params);
        }
        self.rebootSystem();
      }
      function failureCb(cbObject) {
          self.log("Error Code [" + errorCode + "]: " + errorText);
          if(typeof(callback) !== "undefined"){
              callback(false,params);
          }
          self.rebootSystem();
      }
      var configuration = new Configuration();
      configuration.setCurrentTime(successCb, failureCb, options);
    };
    this.setSystemDateTime3 = function(timestamp,callback,params){
      self.log("Setting WebOS Time 3 : " + timestamp);
      var date = new Date(timestamp*1000); // In milliseconds
      var options = {};
      options.year = parseInt(moment.utc(date).format('YYYY'));
      options.month = parseInt(moment.utc(date).format('M'));
      options.day = parseInt(moment.utc(date).format('D'));
      options.hour = parseInt(moment.utc(date).format('H'));
      options.minute = parseInt(moment.utc(date).format('m'));
      options.sec = parseInt(moment.utc(date).format('s'));
      options.ntp = true;
      self.log(options);
      function successCb() {
          self.setTimeZone1(timestamp,callback,params)
      }
      function failureCb(cbObject) {
          self.log(JSON.stringify(cbObject));
          self.setTimeZone1(timestamp,callback,params)
      }
      var configuration = new Configuration();
      configuration.setCurrentTime(successCb, failureCb, options);
    };
    this.setSystemDateTime4 = function(timestamp,callback,params){
      self.log("Setting WebOS Time 4 : " + timestamp);
      var date = new Date(timestamp*1000); // In milliseconds
      var options = {};
      options.year = parseInt(moment.utc(date).format('YYYY'));
      options.month = parseInt(moment.utc(date).format('M'));
      options.day = parseInt(moment.utc(date).format('D'));
      options.hour = parseInt(moment.utc(date).format('H'));
      options.minute = parseInt(moment.utc(date).format('m'));
      options.sec = parseInt(moment.utc(date).format('s'));
      options.ntp = true;
      self.log(options);
      function successCb() {
          self.setSystemDateTime5(timestamp,callback,params)
      }
      function failureCb(cbObject) {
          self.log(JSON.stringify(cbObject));
          self.setSystemDateTime5(timestamp,callback,params)
      }
      var configuration = new Configuration();
      configuration.setCurrentTime(successCb, failureCb, options);
    };

    this.takeScreenshot = function(callback,params){
        var options = {};
        options.save = false;
        options.thumbnail = true;
        if(self.dataInfoSystem && self.dataInfoSystem.webOSversion && self.dataInfoSystem.webOSversion != "2.0"){
            if(params){
                options.imgResolution = Signage.ImgResolution.HD;
            }
            else{
                options.imgResolution = Signage.ImgResolution.FHD;
            }
        }
        var signage = new Signage();
        signage.captureScreen(function(cbObject){
            var size = cbObject.size;
            var encoding = cbObject.encoding;
            var data = cbObject.data;

            if(typeof(callback) !== "undefined"){
                self.screenshotServer = data;
                callback(data,params);
            }
        }, function(cbObject){
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;
            if(typeof(callback) !== "undefined"){
                self.screenshotServer = null;
                callback(false,params);
            }
            self.log("Error Code [" + errorCode + "]: " + errorText);
        }, options);

    };
    this.getScreenshot = function(callback){
        var options = {};
        options.save = false;
        options.thumbnail = false;

        var signage = new Signage();
        signage.captureScreen(function(cbObject){
            var size = cbObject.size;
            var encoding = cbObject.encoding;
            var data = cbObject.data;

            if(typeof(callback) !== "undefined"){
                self.screenshotServer = data;
                callback(data);
            }
        }, function(cbObject){
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;
            if(typeof(callback) !== "undefined"){
                self.screenshotServer = null;
                callback(false);
            }
            self.log("Error Code [" + errorCode + "]: " + errorText);
        }, options);
    };

    this.rebootSystem = function(){
      if(!self.systemIsUpdating){
        var options = {};
        options.powerCommand = Power.PowerCommand.REBOOT;

        var power = new Power();
        power.executePowerCommand(function(){self.log("Rebooting ...")}, function(cbObject){
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;

            self.log ("Error Code [" + errorCode + "]: " + errorText);

        }, options);
      }else{
        self.log("System is Updating ... reboot temporaly unavailable ... please wait 60s.");
        self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+1,self.name+": System is Updating ... reboot temporaly unavailable ... please wait 60s.");
      }
    };

    this.haltSystem = function(){
        var options = {};
        options.powerCommand = Power.PowerCommand.SHUTDOWN;

        var power = new Power();
        power.executePowerCommand(function(){self.log("PowerOFF ...")}, function(cbObject){
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;

            self.log ("Error Code [" + errorCode + "]: " + errorText);

        }, options);
    };

    this.internetConnected = function() {

        var deviceInfo = new DeviceInfo();
        deviceInfo.getNetworkInfo(function(cbObject){
            self.log("Network Info : " + JSON.stringify(cbObject));
            self.device_has_internet = false;
            var status = cbObject;
            if(typeof(status) != "undefined"){
                if(typeof(status.wifi) != "undefined"){
                    if(typeof(status.wifi.state) != "undefined"){
                        if(status.wifi.state == "connected"){
                            self.device_has_internet = true;
                            self.system_ip = status.wifi.ipAddress;
                        }
                    }
                    if(typeof(status.wifi.connected) != "undefined"){
                        if(status.wifi.connected == "yes"){
                            self.device_has_internet = true;
                        }
                    }
                }
                if(typeof(status.wired) != "undefined"){
                    if(typeof(status.wired.state) != "undefined"){
                        if(status.wired.state == "connected"){
                            self.device_has_internet = true;
                            self.system_ip = status.wifi.ipAddress;
                        }
                        if(typeof(status.wired.connected) != "undefined"){
                            if(status.wired.connected == "yes"){
                                self.device_has_internet = true;
                            }
                        }
                    }
                }
            }
        }, function(cbObject) {
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;

            self.log("Error Code [" + errorCode + "]: " + errorText);
        });
        self.getProxyInfo();
        self.getSystemUsageInfo();

        return self.device_has_internet;
    };
    
    this.getProxyInfo = function(){
      try{
        var deviceinfo = new DeviceInfo();
        deviceinfo.getProxyInfo(function(cbObject) {;
            if(cbObject.enabled){
              self.proxy_info = {
                host : cbObject.ipAddress,
                port : cbObject.port
              }
            }else{
              self.proxy_info = undefined;
            }
          
            // Do something
        }, function(cbObject) {
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;
            console.log("Error Code [" + errorCode + "]: " + errorText);
        });
      }catch(e){
        console.log(e);
      }
    };

    this.getNetworkInfo = function(callback,params){
        // TODO
        var network_info = {
            ip: "0.0.0.0",
            netmask : "0.0.0.0",
            gateway : "0.0.0.0"
        };
        return network_info;
    };

    this.getRootDir = function(callback) {
        var request = webOS.service.request(self.service_id,{
            method:"getRootDir",
            parameters: {},
            onSuccess: function(inResponse){
              self.log("getRootDir success ... "+inResponse.returnValue);
              var data = "";
              var ok = inResponse.returnValue;
              if(ok){
                  data = inResponse.response;
              }
              if(typeof(callback) !== "undefined"){
                  callback(data);
              }
              self.realDir = data;
            },
            onFailure: function(inError){
                self.log("getRootDir fail ... "+inError.errorText);
            },
            onComplete: function(inResponse){
                self.log("getRootDir complete ... "+inResponse.returnValue);
            }
        });
    };

    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.alwaysOnTop = function(value){
        // OVERRIDE
        self.uses_texture_graphics = !value;
    };

    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.activateControl = function(core){
      self.debug = true;
        self.SocketConnector.createSocket(core);
    };
    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.getInfoSystem = function(callback){
        self.getPlatformInfo(function(err, result){
            if(!err){
                self.dataInfoSystem = {
                    newDate: new Date(),
                    getDate : self.getDate(),
                    getDateTrue : self.getDate(true),
                    firmwareVersion: result.firmwareVersion,
                    modelTV : result.modelName,
                    serialNumber : result.serialNumber
                };
                //if(typeof(callback) !== "undefined"){
                    self.getVersionWebos(callback);
                  //callback(JSON.stringify(self.dataInfoSystem));
                //}
            }
            else{
              if(typeof(callback) !== "undefined"){
                callback(JSON.stringify(err));
              }
            }
        });
    }
    this.getVersionWebos = function(callback){
        var custom = new Custom();
        custom.Signage.getwebOSVersion(
            function successCallback(successObject) {
                self.dataInfoSystem.webOSversion = successObject.webOSVersion;
                //console.log('webOS Signage version: ' + successObject.webOSVersion)
                if(typeof(callback) !== "undefined"){
                    self.getCurrentTime(callback);
                }
            },
            function failureCallback(failureObject) {
                self.log(JSON.stringify(failureObject))
                if(typeof(callback) !== "undefined"){
                    self.getCurrentTime(callback);
                }
            }
        );
    }
    this.getPlatformInfo = function(callback_getPlatformInfo) {
        function successCb(cbObject) {
            callback_getPlatformInfo(null, cbObject);
        }
        function failureCb(cbObject) {
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;
            callback_getPlatformInfo(JSON.stringify(cbObject))
        }

        var deviceInfo = new DeviceInfo();
        deviceInfo.getPlatformInfo(successCb, failureCb);
    }
    this.getUsageData = function(callback_getUsageData) {
      var successCb_getUsageData = function (cbObject) {
          callback_getUsageData(null, JSON.stringify(cbObject));
      };

      var failureCb_getUsageData = function (cbObject) {
          var errorCode = cbObject.errorCode;
          var errorText = cbObject.errorText;
          callback_getUsageData(JSON.stringify(cbObject));
      };

      var signage = new Signage();
      signage.getUsageData(successCb_getUsageData, failureCb_getUsageData);
    };
    this.getPowerOnOffHistory = function(callback_getPowerOnOffHistory){
      var custom = new Custom();
      custom.Configuration.getPowerOnOffHistory(
          function successCallback(successObject) {
              callback_getPowerOnOffHistory(null, JSON.stringify(successObject));
          },
          function failureCallback(failureObject) {
              callback_getPowerOnOffHistory(JSON.stringify(failureObject));
          }
      );
    };

    this.setKeepAliveModeOnMemoryLeak = function(){
      try{
        var custom = new Custom();
        custom.Configuration.setKAM(
            function successCallback() {
              if(typeof(callback) !== "undefined"){
                callback(true);
              }
            },
            function failureCallback(failureObject) {
              if(typeof(callback) !== "undefined"){
                callback(false,JSON.stringify(failureObject));
              }
                self.log('setKeepAliveModeOnMemoryLeak : [' + failureObject.errorCode + '] ' + failureObject.errorText);
            },
            {
                keepAliveMode : true
            }
        );
      }catch(e){
        if(typeof(callback) !== "undefined"){
          callback(false,JSON.stringify(e));
        }
      }
    };

    this.clearCache = function(callback) {
        function successCb() {
            self.log("------------------------------------------------ clear cache successful");
            if(typeof(callback) !== "undefined"){
              callback("clear cache successful")
            }
        }
        function failureCb(cbObject) {
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;
            self.log(JSON.stringify(cbObject));
            if(typeof(callback) !== "undefined"){
              callback(JSON.stringify(cbObject))
            }
        }
        var configuration = new Configuration();
        configuration.clearCache(successCb, failureCb);
    };

    this.getSystemUsageInfo = function (callback) {
        function successCb(cbObject) {
            if(typeof(cbObject) != "undefined"){
              if(typeof(callback) !== "undefined"){
                callback(null, cbObject);
              }
              self.log("memory.total : " + cbObject.memory.total);
              self.log("memory.used : " + cbObject.memory.used);
              self.log("memory.free : " + cbObject.memory.free);
              self.log("memory.buffer : " + cbObject.memory.buffer);
              self.log("memory.cached : " + cbObject.memory.cached);
              var actualFree = cbObject.memory.free + cbObject.memory.buffer + cbObject.memory.cached;
              var percent = Math.round(100*((cbObject.memory.total-actualFree)/cbObject.memory.total));
              self.log("Memory: "+percent+"%");
              if(percent >= 90){
                self.notifyError(self.ERROR['OPERATING_SYSTEM_CONTROLLER']+3,self.name+": Warning High Memory Usage : "+percent+"%");
              }
            }else{
                self.log("Memory: NO INFO");
            }
        }
        function failureCb(cbObject) {
          if(typeof(callback) !== "undefined"){
            callback(JSON.stringify(cbObject));
          }
        }
        var deviceInfo = new DeviceInfo();
        var options = {cpus : true, memory : true};
        deviceInfo.getSystemUsageInfo(successCb, failureCb, options);
    };
    this.getInfoStorage = function (callback){
        var successCb = function (cbObject){
            callback(null, cbObject);
        };
        var failureCb = function(cbObject){
           callback(JSON.stringify(cbObject));
        };
        var storage = new Storage();
        storage.getStorageInfo(successCb, failureCb);
    };
    this.getInfo  = function(callback_getInfo){
        var successCb = function (cbObject){
            callback_getInfo(null, cbObject)
        }
        var failureCb = function(cbObject){
            callback_getInfo(JSON.stringify(cbObject))
        };
        var signage = new Signage();
        signage.getSignageInfo(successCb, failureCb);
    };
    this.getInfoSystemPlus = function(callback){
      self.infoPlus = {}
      self.getSystemUsageInfo(function(err, result){
          if(err){
              self.log(JSON.stringify(err));
          }
          else{
              self.log(JSON.stringify(result));
              self.infoPlus.SystemUsageInfo = result;
          }
          self.getInfoStorage(function(err, result){
              if(err){
                  self.log(JSON.stringify(err));
              }
              else{
                  self.log(JSON.stringify(result));
                  self.infoPlus.InfoStorage = result;
              }
              self.getInfo(function(err, result){
                  if(err){
                      self.log(JSON.stringify(err));
                  }
                  else{
                      self.log(JSON.stringify(result));
                      self.infoPlus.SignageInfo = result;
                  }
                  self.getUsageData(function(err, result){
                      if(err){
                          self.log(JSON.stringify(err));
                      }
                      else{
                          self.log(JSON.stringify(result));
                          self.infoPlus.UsageData = result;
                      }
                      callback(JSON.stringify(self.infoPlus))
                  });
              });
          });
      });
    };



    this.getLIC = function(callback){
      self.readFile("admira.lic", function(resultR, file){
        if(resultR){
          callback("admira.lic = "+resultR);
        }
        else{
          callback("error read admira.lic");
        }
      });
    }
    this.createLIC = function(data, callback){
      self.writeFile("admira.lic", data.lic, function(resultR, file){
        if(resultR){
          callback("admira.lic ("+data.lic+") created");
        }
        else{
          callback("admira.lic not created");
        }
      });
    }
    this.deleteAll = function(callback){
      self.deleteFileRecursive("content/",function(err, result){
          self.deleteFileRecursive("xmls/",function(err, result){
              self.deleteFileRecursive("log/",function(err, result){
                  self.deleteFile("core.xml",function(err, result){
                      self.deleteFile("week.tstamp",function(err, result){
                        setTimeout(function(){
                          self.rebootSystem();
                        },2000);
                        if(err){
                          callback(JSON.stringify(err));
                        }
                        else{
                          callback(result);
                        }
                      });
                  });
              });
          });
      });
    }
    this.deleteAllAll = function(callback){
      self.deleteFileRecursive("content/",function(err, result){
          if(err){
              callback(JSON.stringify(err));
          }
          else{
              callback(result);
          }
      });
    };
    this.copyUSB = function (callback){
      callback("no function");
    };
    this.deleteAll2 =  function(callback){
      callback("no function");
    };

    //portraitMode - landscapeMode
    this.setContentRotation = function (options, callback_setContentRotation) {
      function successCb() {
        callback_setContentRotation(null, "success setContentRotation")
      }
      function failureCb(cbObject) {
        callback_setContentRotation(JSON.stringify(cbObject));
      }
      var video = new Video();
      video.setContentRotation(successCb, failureCb, options);
    }
    this.setPortraitMode = function (opt_setPortraitMode, callback_setPortraitMode){
        var options_setPortraitMode = {
            portraitMode: opt_setPortraitMode
        };

        var success_setPortraitMode = function (){
            self.log("Portrait Mode successfully Set");
            callback_setPortraitMode(null, "Portrait Mode successfully Set");
        };

        var failure_setPortraitMode = function(cbObject_setPortraitMode){
            var errorCode = cbObject_setPortraitMode.errorCode;
            var errorText = cbObject_setPortraitMode.errorText;
            self.log( " Error Code [" + errorCode + "]: " + errorText);
            callback_setPortraitMode(cbObject_setPortraitMode);
        };

        var signage = new Signage();
        signage.setPortraitMode(success_setPortraitMode, failure_setPortraitMode, options_setPortraitMode);
    };
    this.getVideoStatus = function (callback_getVideoStatus) {
        function successCb(cbObject) {
            callback_getVideoStatus(null, JSON.stringify(cbObject))
        }
        function failureCb(cbObject) {
             callback_getVideoStatus(JSON.stringify(cbObject))
        }
        var video = new Video();
        video.getVideoStatus(successCb, failureCb);
    };
    this.getContentRotation = function (callback_getContentRotation) {
      function successCb(cbObject) {
          callback_getContentRotation(null,JSON.stringify(cbObject))
      }
      function failureCb(cbObject) {
         callback_getContentRotation(JSON.stringify(cbObject));
      }
      var video = new Video();
      video.getContentRotation(successCb, failureCb);
    };
    this.setNativePortraitMode = function (data, mode, callback_setNative){
      var se=Custom.NATIVEPORTRAIT.DEGREE_90;
      if(mode == "off"){
        se = Custom.NATIVEPORTRAIT.OFF;
      }
      else{
        if(mode == "180"){
          se = Custom.NATIVEPORTRAIT.DEGREE_180;
        }
        else{
          if(mode == "270"){
            se = Custom.NATIVEPORTRAIT.DEGREE_270;
          }
          else{
            se = Custom.NATIVEPORTRAIT.DEGREE_90;
          }
        }
      }
        var custom = new Custom();
        custom.Configuration.setNativePortraitMode(
            function successCallback(cbObject) {
                callback_setNative(cbObject);
                self.rebootSystem();
            },
            function failureCallback(failureObject) {
                callback_setNative(failureObject);
            },
            {
                nativePortrait : se
            }
        );
    }
    this.getNativePortraitMode = function (callback_getNative){
        var custom = new Custom();
        custom.Configuration.getNativePortraitMode(
            function successCallback(successObject) {
                callback_getNative('Native portrait settings : ' + successObject.nativePortrait);
            },
            function failureCallback(failureObject) {
                callback_getNative('[' + failureObject.errorCode + '] ' + failureObject.errorText)
            }
        );
    }
    this.getDisplayOrientation = function(callback,params) {
      var video = new Video();
      video.getContentRotation(function successCb(cbObject) {
          var result = "landscape";
          self.log("getDisplayOrientation -> degree : " + cbObject.degree);
          self.log("getDisplayOrientation -> aspectRatio : " + cbObject.aspectRatio);
          if(cbObject.degree == "90"){
            result = "portrait90";
          }
          if(cbObject.degree == "270"){
            result = "portrait270";
          }
          if(typeof(callback) !== "undefined"){
            callback(result,params);
          }
        },function failureCb(cbObject) {
          var errorCode = cbObject.errorCode;
          var errorText = cbObject.errorText;
          self.log ("getDisplayOrientation -> Error Code [" + errorCode + "]: " + errorText);
        });
    }
    this.setMode = function(data, callback){
      if(data.mode == "on"){
          self.setPortraitMode(Signage.OsdPortraitMode.ON, function(err, result){
              if(err){
                  callback(err);
              }
              else{
                  main_webos.orientation = "V";
                  callback(result);
              }
          })
      }
      else{
          self.setPortraitMode(Signage.OsdPortraitMode.OFF, function(err, result){
              if(err){
                  callback(err);
              }
              else{
                  main_webos.orientation = "H";
                  callback(result);
              }
          })
      }
    };

    // FIRMWARE

    this.getFirmwareUpgradeStatus = function() {
        var successCb_getFirmwareUpgradeStatus = function (cbObject) {
            self.log("-------------------------------------------------status " + cbObject.status);
            self.log("-------------------------------------------------upgradeProgress " + cbObject.upgradeProgress);
            self.log("-------------------------------------------------downloadProgress " + cbObject.downloadProgress);
        };
        var failureCb_getFirmwareUpgradeStatus = function(cbObject) {
            self.log(cbObject);
        };
        var storage = new Storage();
        setInterval(function(){storage.getFirmwareUpgradeStatus(successCb_getFirmwareUpgradeStatus, failureCb_getFirmwareUpgradeStatus);}, 2000);
    }
    this.downloadFirmware = function(callback_downloadFirmware) {
        var successCb_downloadFirmware = function () {
          self.log("Download firmware is successful");
          self.upgradeFirmware(function(err, result){
            if(err){
              callback_downloadFirmware("Download successful -- upgrade failure: "+err);
            }
            else{
              callback_downloadFirmware(null, true);
            }
          });
        };
        var failureCb_downloadFirmware = function(cbObject) {
            callback_downloadFirmware(cbObject);
        };
        var options_downloadFirmware = {
            uri : "http://"
        };
        var storage = new Storage();
        storage.downloadFirmware(successCb_downloadFirmware, failureCb_downloadFirmware, options_downloadFirmware);
        self.getFirmwareUpgradeStatus();
    }

    this.upgradeFirmware = function(callback_upgradeFirmware) {
        var successCb_upgradeFirmware = function () {
          self.log("firmware upgrade is successful");
          callback_upgradeFirmware(null, true);
        };
        var failureCb_upgradeFirmware = function(cbObject) {
          self.log(cbObject);
          callback_upgradeFirmware(cbObject);
        };
        var storage = new Storage();
        storage.upgradeFirmware(successCb_upgradeFirmware, failureCb_upgradeFirmware);
    }

    // TIMERS
    this.insertTimerON = function(optionsInsertTimerON, callback_insertTimerON){
      function successCb() {
        self.log("-------------------------------------------addOnTimer successful -- "+ JSON.stringify(optionsInsertTimerON));
        callback_insertTimerON(null, true);
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callback_insertTimerON(cbObject);
      }
      self.log("optionsInsertTimerON");
      self.log(JSON.stringify(optionsInsertTimerON));
      var power = new Power();
      power.addOnTimer(successCb, failureCb, optionsInsertTimerON);
    };
    this.insertTimerOFF = function(optionsInsertTimerOFF, callback_insertTimerOFF){
      function successCb() {
        self.log("-------------------------------------------addOffTimer successful");
        callback_insertTimerOFF(null, true);
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callback_insertTimerOFF(cbObject);
      }
      self.log("optionsInsertTimerOFF");
      self.log(JSON.stringify(optionsInsertTimerOFF));
      var power = new Power();
      power.addOffTimer(successCb, failureCb, optionsInsertTimerOFF);
    }




    this.timersOnNews = [];
    this.timersOnOld = [];
    this.timersOffNews = [];
    this.timersOffOld = [];
    this.calculateTimersOn = function(timersOn, callbackCalculateTimersOn){
      self.log("calculateTimersOn");
      self.timersOnNews = [];
      var timersOnHour = new Array(24);
      //var timersOn = null;
      for(var i=0; i<timersOn.length; i++){
        self.log("timersOn[i].day: "+timersOn[i].day);
        switch(timersOn[i].day) {
          case 0:
            if(timersOnHour[timersOn[i].hour] == undefined){
              timersOnHour[timersOn[i].hour] = Power.TimerWeek.SUNDAY;
            }
            else{
              timersOnHour[timersOn[i].hour] = timersOnHour[timersOn[i].hour] + Power.TimerWeek.SUNDAY;
            }
            break;
          case 1:
            if(timersOnHour[timersOn[i].hour] == undefined){
              timersOnHour[timersOn[i].hour] = Power.TimerWeek.MONDAY;
            }
            else{
              timersOnHour[timersOn[i].hour] = timersOnHour[timersOn[i].hour] + Power.TimerWeek.MONDAY;
            }
            self.log("Power.TimerWeek.MONDAY: "+Power.TimerWeek.MONDAY);
            self.log("timersOnHour[timersOn[i].hour]: "+timersOnHour[timersOn[i].hour]);
            break;
          case 2:
            if(timersOnHour[timersOn[i].hour] == undefined){
              timersOnHour[timersOn[i].hour] = Power.TimerWeek.TUESDAY;
            }
            else{
              timersOnHour[timersOn[i].hour] = timersOnHour[timersOn[i].hour] + Power.TimerWeek.TUESDAY;
            }
            break;
          case 3:
            if(timersOnHour[timersOn[i].hour] == undefined){
              timersOnHour[timersOn[i].hour] = Power.TimerWeek.WEDNESDAY;
            }
            else{
              timersOnHour[timersOn[i].hour] = timersOnHour[timersOn[i].hour] + Power.TimerWeek.WEDNESDAY;
            }
            break;
          case 4:
            if(timersOnHour[timersOn[i].hour] == undefined){
              timersOnHour[timersOn[i].hour] = Power.TimerWeek.THURSDAY;
            }
            else{
              timersOnHour[timersOn[i].hour] = timersOnHour[timersOn[i].hour] + Power.TimerWeek.THURSDAY;
            }
            break;
          case 5:
            if(timersOnHour[timersOn[i].hour] == undefined){
              timersOnHour[timersOn[i].hour] = Power.TimerWeek.FRIDAY;
            }
            else{
              timersOnHour[timersOn[i].hour] = timersOnHour[timersOn[i].hour] + Power.TimerWeek.FRIDAY;
            }
            break;
          case 6:
            if(timersOnHour[timersOn[i].hour] == undefined){
              timersOnHour[timersOn[i].hour] = Power.TimerWeek.SATURDAY;
            }
            else{
              timersOnHour[timersOn[i].hour] = timersOnHour[timersOn[i].hour] + Power.TimerWeek.SATURDAY;
            }
            break;
        }
        if(i == timersOn.length-1){
          for(var j=0; j<24; j++){
            if(timersOnHour[j] != undefined && timersOnHour[j] != "undefined" && timersOnHour[j] != null){
              self.timersOnNews.push({
                "hour" : j,
                "minute" : 0,
                "week" :  timersOnHour[j],
                "inputSource" : "ext://hdmi:1"
              });
              /*self.insertTimerON({
                "hour" : j,
                "minute" : 0,
                "week" :  timersOnHour[j],
                "inputSource" : "ext://hdmi:1"
              });*/
            }
            if(j == 23){
              self.log(JSON.stringify(self.timersOnNews));
              callbackCalculateTimersOn();
            }
          }
        }
      }
    }
    this.calculateTimersOff = function(timersOff, callbackCalculateTimersOff){
      self.timersOffNews = [];
      var timersOffHour = new Array(24);
      for(var x=0; x<timersOff.length; x++){
        self.log(timersOff[x].day);
        switch(timersOff[x].day) {
          case 0:
            if(timersOffHour[timersOff[x].hour] == undefined){
              timersOffHour[timersOff[x].hour] = Power.TimerWeek.SUNDAY;
            }
            else{
              timersOffHour[timersOff[x].hour] = timersOffHour[timersOff[x].hour] + Power.TimerWeek.SUNDAY;
            }
            break;
          case 1:
            if(timersOffHour[timersOff[x].hour] == undefined){
              timersOffHour[timersOff[x].hour] = Power.TimerWeek.MONDAY;
            }
            else{
              timersOffHour[timersOff[x].hour] = timersOffHour[timersOff[x].hour] + Power.TimerWeek.MONDAY;
            }
            break;
          case 2:
            if(timersOffHour[timersOff[x].hour] == undefined){
              timersOffHour[timersOff[x].hour] = Power.TimerWeek.TUESDAY;
            }
            else{
              timersOffHour[timersOff[x].hour] = timersOffHour[timersOff[x].hour] + Power.TimerWeek.TUESDAY;
            }
            break;
          case 3:
            if(timersOffHour[timersOff[x].hour] == undefined){
              timersOffHour[timersOff[x].hour] = Power.TimerWeek.WEDNESDAY;
            }
            else{
              timersOffHour[timersOff[x].hour] = timersOffHour[timersOff[x].hour] + Power.TimerWeek.WEDNESDAY;
            }
            break;
          case 4:
            if(timersOffHour[timersOff[x].hour] == undefined){
              timersOffHour[timersOff[x].hour] = Power.TimerWeek.THURSDAY;
            }
            else{
              timersOffHour[timersOff[x].hour] = timersOffHour[timersOff[x].hour] + Power.TimerWeek.THURSDAY;
            }
            break;
          case 5:
            if(timersOffHour[timersOff[x].hour] == undefined){
              timersOffHour[timersOff[x].hour] = Power.TimerWeek.FRIDAY;
            }
            else{
              timersOffHour[timersOff[x].hour] = timersOffHour[timersOff[x].hour] + Power.TimerWeek.FRIDAY;
            }
            break;
          case 6:
            if(timersOffHour[timersOff[x].hour] == undefined){
              timersOffHour[timersOff[x].hour] = Power.TimerWeek.SATURDAY;
            }
            else{
              timersOffHour[timersOff[x].hour] = timersOffHour[timersOff[x].hour] + Power.TimerWeek.SATURDAY;
            }
            break;
        }
        if(x == timersOff.length-1){
          for(var h=0; h<24; h++){
            if(timersOffHour[h] != undefined && timersOffHour[h] != "undefined"){
              self.timersOffNews.push({
                "hour" : h,
                "minute" : 0,
                "week" :  timersOffHour[h]
              });
              /*self.insertTimerOFF({
                "hour" : h,
                "minute" : 0,
                "week" :  timersOffHour[h]
              });*/
            }
            if(h == 23){
              self.log(JSON.stringify(self.timersOffNews));
              callbackCalculateTimersOff();
            }
          }
        }
      }
    }

    this.obtainTimersOn = function(callbackObtainTimersOn){
      function successCb(cbObject) {
        self.timersOnOld = null;
        self.timersOnOld = cbObject.timerList;
        callbackObtainTimersOn(null, cbObject);
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callbackObtainTimersOn(cbObject)
      }
      var power = new Power();
      power.getOnTimerList(successCb, failureCb);
    }
    this.obtainTimersOff = function(callbackObtainTimersOff){
      function successCb(cbObject) {
        self.timersOffOld = null;
        self.timersOffOld = cbObject.timerList;
        callbackObtainTimersOff(null, cbObject);
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callbackObtainTimersOff(cbObject);
      }
      var power = new Power();
      power.getOffTimerList(successCb, failureCb);
    }

    this.compareTimersOn = function(callbackCompareTimersOn){
      var igual = 0;
      for(var i=0; i<self.timersOnNews.length; i++){
        for(var j=0; j<self.timersOnOld.length; j++){
          if(timersOnNews[i].hour == timersOnOld.timerList[j].hour && timersOnNews[i].week == timersOnOld.timerList[j].week){
            igual++;
          }
          if(j == self.timersOnOld.length-1){
            if(igual != 0){
              callbackCompareTimersOn(false);
            }
            else{
              callbackCompareTimersOn(true);
            }
          }
        }
      }
    }
    this.compareTimersOff = function(callbackCompareTimersOff){
      var igual = 0;
      for(var i=0; i<self.timersOffNews.length; i++){
        for(var j=0; j<self.timersOffOld.length; j++){
          if(timersOffNews[i].hour == timersOffOld.timerList[j].hour && timersOffNews[i].week == timersOffOld.timerList[j].week){
            igual++;
          }
          if(j == self.timersOffOld.length-1){
            if(igual != 0){
              callbackCompareTimersOff(false);
            }
            else{
              callbackCompareTimersOff(true);
            }
          }
        }
      }
    }

    this.deleteTimersOn = function(optionsDeleteTimersOn){
      function successCb(){
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
      }
      var power = new Power();
      power.deleteOnTimer(successCb, failureCb, optionsDeleteTimersOn);
    };
    this.deleteTimersOff = function(optionsDeleteTimersOff){
      function successCb(){
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
      }
      var power = new Power();
      power.deleteOffTimer(successCb, failureCb, optionsDeleteTimersOff);
    };

    this.obtainDeleteTimersOn = function(callbackObtainDeleteTimersOn){
      for(var i=0; i<timersOnOld.length; i++){
        deleteTimersOn(timersOnOld[i]);
        if(i == timersOnOld.length-1){
          callbackObtainDeleteTimersOn();
        }
      }
    };
    this.obtainDeleteTimersOff = function(callbackObtainDeleteTimersOff){
      for(var i=0; i<timersOffOld.length; i++){
        deleteTimersOn(timersOffOld[i]);
        if(i == timersOffOld.length-1){
          callbackObtainDeleteTimersOff();
        }
      }
    }

    this.controlFlowTempOff = 0;
    this.controlFlowOff = function(){
      if(self.controlFlowTempOff < self.timersOffNews.length){
        self.insertTimerOFF(self.timersOffNews[self.controlFlowTempOff], function(err, result){
          self.controlFlowTempOff++;
          self.controlFlowOff();
        });
      }
      else{
          self.enableAllOffTimer(function(err, result){
            self.log("--------------------------- FINISH INSERT TIMERS -----------------------------");
          });
      }
    }
    this.controlFlowTempOn = 0;
    this.controlFlowOn = function(){
      if(self.controlFlowTempOn < self.timersOnNews.length){
        self.insertTimerON(self.timersOnNews[self.controlFlowTempOn], function(err, result){
          self.controlFlowTempOn++;
          self.controlFlowOn();
        });
      }
      else{
          self.enableAllOnTimer(function(err, result){
            self.controlFlowTempOff = 0;
            self.controlFlowOff();
          });
      }
    }


    this.calculateTimers = function(timersOn, timersOff){
      self.deleteAllOnTimer(function(){
        self.deleteAllOffTimer(function(){
          self.calculateTimersOn(timersOn, function(){
            self.calculateTimersOff(timersOff, function(){
              self.controlFlowTempOn = 0;
              self.controlFlowOn();
            })
          })
        })
      })
    }

    this.enableAllOnTimer = function(callback_enableAllOnTimer) {
      var options = {};
      options.allOnTimer = true;
      options.clearOnTimer = false;
      function successCb() {
        self.log("enableAllOnTimer");
        callback_enableAllOnTimer(null, true);
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callback_enableAllOnTimer(cbObject);
      }
      var power = new Power();
      power.enableAllOnTimer(successCb, failureCb, options);
    }
    this.enableAllOffTimer = function(callback_enableAllOffTimer) {
      var options = {};
      options.allOffTimer = true;
      options.clearOffTimer = false;
      function successCb() {
        self.log("enableAllOffTimer");
        callback_enableAllOffTimer(null, true);
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callback_enableAllOffTimer(cbObject);
      }
      var power = new Power();
      power.enableAllOffTimer(successCb, failureCb, options);
    }

    this.deleteAllOnTimer = function(callbackDeleteAllOnTimer) {
      var options = {};
      options.allOnTimer = true;
      options.clearOnTimer = true;
      function successCb() {
          self.log("3-deleteAllOnTimer");
        self.log("deleteAllOnTimer");
        callbackDeleteAllOnTimer();
      }
      function failureCb(cbObject) {
          self.log("2-deleteAllOnTimer");
        self.log(JSON.stringify(cbObject));
        callbackDeleteAllOnTimer();
      }
        self.log("1-deleteAllOnTimer");
      var power = new Power();
      power.enableAllOnTimer(successCb, failureCb, options);
    }
    this.deleteAllOffTimer = function(callbackDeleteAllOffTimer) {
      var options = {};
      options.allOffTimer  = true;
      options.clearOffTimer = true;
      function successCb() {
        self.log("deleteAllOffTimer");
        callbackDeleteAllOffTimer();
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callbackDeleteAllOffTimer();
      }
      var power = new Power();
      power.enableAllOffTimer(successCb, failureCb, options);
    }
    this.deteleAllTimers = function(){
      self.deleteAllOnTimer(function(){
        self.deleteAllOffTimer(function(){
          self.log("--------------------------- deteleAllTimers -----------------------------");
        })
      })
    }

    this.getTimers = function(callback){
      self.timersSystem = {};
      self.obtainTimersOn(function(err, result){
        if(err){
          self.log(JSON.stringify(err));
        }
        else{
          self.log(JSON.stringify(result));
          self.timersSystem.OnTimers = result;
        }
        self.obtainTimersOff(function(err2, result2){
          if(err2){
              self.log(JSON.stringify(err2));
          }
          else{
            self.log(JSON.stringify(result2));
            self.timersSystem.OffTimers = result2;
          }
    		  callback(self.timersSystem);
        });
      });
    };




    this.calculateReboot = function(callback){
        var today = new Date();
        var tomorrow = new Date();
        tomorrow.setDate(today.getDate()+1);
        tomorrow.setHours(4);
        tomorrow.setMinutes(0);
        var t1 = tomorrow.getTime();
        var t2 = today.getTime();
        var rest = t1-t2;
        if(rest >= 0){
            setTimeout(function(){
                self.notifyError(transfer.ERROR['TRANSFER_SERVICE']+17,self.name+": Proceed to perform the scheduled reboot");
                self.log("------------------------------------------------ proceed to perform the scheduled reboot");
                setTimeout(function(){self.rebootSystem();},3000);
            }, rest);
            self.log("------------------------------------------------programing reboot in "+rest+" milliseconds");
            if(typeof(callback) !== "undefined"){
              callback("programing reboot in "+rest+" milliseconds");
            }
        }
        else{
            self.log("------------------------------------------------no programing reboot");
            if(typeof(callback) !== "undefined"){
              callback("no programing reboot");
            }
        }
    }
    this.insertTimersOrReboot = function(reboot){
        self.obtainTimersOn(function(err, result){
          self.log(JSON.stringify(result));
          if(!err){
            if(result.timerList.length > 1){
              if(result.timerList.length != 1 && result.timerList[0].hour != 4){
                self.calculateReboot();
              }
            }
            else{
              self.obtainTimersOff(function(errOff, resultOff){
                self.log(JSON.stringify(resultOff));
                if(!errOff){
                  if(resultOff.timerList.length > 1){
                    if(resultOff.timerList.length != 1 && result.timerList[0].hour != 4){
                      self.calculateReboot();
                    }
                  }
                  else{
                    if(reboot == 1){
                      self.insertTimerON({
                        "hour":4,
                        "minute":03,
                        "week":Power.TimerWeek.EVERYDAY,
                        "inputSource": "ext://hdmi:1"
                      }, function(err, result){
                        self.insertTimerOFF({
                          "hour":4,
                          "minute":0,
                          "week":Power.TimerWeek.EVERYDAY
                        }, function(errOFFi, resultOFFi){
                          self.enableAllOnTimer(function(err1, result1){
                            self.enableAllOffTimer(function(err2, result2){
                              self.log("------------------------------------------------PROGRAMADO APAGADO Y ENCENDIDO 4am - 4:03 am");
                            });
                          });
                        });
                      });
                    }
                    else{
                      self.log("------------------------------------------------ ¡¡NO!! PROGRAMADO APAGADO Y ENCENDIDO 4am - 4:03 am");
                    }
                  }
                }
                else {
                  self.calculateReboot();
                }
              });
            }
          }
          else{
            self.calculateReboot();
          }
        })
    }
    this.upgradeApplication = function (callback){
      var options = {};
      options.serverIp = "192.168.0.2";
      options.serverPort = 80;
      options.secureConnection = false;
      options.appLaunchMode = Configuration.AppMode.LOCAL;
      options.appType = Configuration.AppType.IPK;
      options.fqdnMode = true;
      options.fqdnAddr = "http://webos.admira.com/com.lg.app.signage.ipk";
      function successCb() {
        var options_upgradeApplication = {
          to : Storage.AppMode.LOCAL,
          recovery : false,
          type : "ipk"
        };
        var successCb_upgradeApplication = function (cbObject){
          setTimeout(function(){
            self.rebootSystem();
          },2000);
          self.log("____________________________ APP UPGRADE SUCESS");
          callback("http://webos.admira.com/com.lg.app.signage.ipk --- APP UPGRADE SUCESS")
        };
        var failureCb_upgradeApplication = function (cbObject){
          self.log(JSON.stringify(cbObject));
          callback(JSON.stringify(cbObject))
        };
        storage = new Storage();
        storage.upgradeApplication(successCb_upgradeApplication, failureCb_upgradeApplication, options_upgradeApplication);
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callback(JSON.stringify(cbObject))
      }
      var configuration = new Configuration();
      configuration.setServerProperty(successCb, failureCb, options);
    };
    this.upgradeApplicationInstall = function (callback){
      var options = {};
      options.serverIp = "192.168.0.2";
      options.serverPort = 80;
      options.secureConnection = false;
      options.appLaunchMode = Configuration.AppMode.LOCAL;
      options.appType = Configuration.AppType.IPK;
      options.fqdnMode = true;
      options.fqdnAddr = "http://install.admira.com/webos/com.lg.app.signage.ipk";
      function successCb() {
        var options_upgradeApplication = {
          to : Storage.AppMode.LOCAL,
          recovery : false,
          type : "ipk"
        };
        var successCb_upgradeApplication = function (cbObject){
          setTimeout(function(){
            self.rebootSystem();
          },2000);
          self.log("____________________________ APP UPGRADE SUCESS");
          callback("http://install.admira.com/webos/com.lg.app.signage.ipk --- APP UPGRADE SUCESS")
        };
        var failureCb_upgradeApplication = function (cbObject){
          self.log(JSON.stringify(cbObject));
          callback(JSON.stringify(cbObject))
        };
        storage = new Storage();
        storage.upgradeApplication(successCb_upgradeApplication, failureCb_upgradeApplication, options_upgradeApplication);
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callback(JSON.stringify(cbObject))
      }
      var configuration = new Configuration();
      configuration.setServerProperty(successCb, failureCb, options);
    };
    this.upgradeApplicationInsert = function (url, callback){
      var options = {};
      options.serverIp = "192.168.0.2";
      options.serverPort = 80;
      options.secureConnection = false;
      options.appLaunchMode = Configuration.AppMode.LOCAL;
      options.appType = Configuration.AppType.IPK;
      options.fqdnMode = true;
      options.fqdnAddr = url;
      function successCb() {
        var options_upgradeApplication = {
          to : Storage.AppMode.LOCAL,
          recovery : false,
          type : "ipk"
        };
        var successCb_upgradeApplication = function (cbObject){
          setTimeout(function(){
            self.rebootSystem();
          },2000);
          self.log("____________________________ APP UPGRADE SUCESS");
          callback(url+" --- APP UPGRADE SUCESS")
        };
        var failureCb_upgradeApplication = function (cbObject){
          self.log(JSON.stringify(cbObject));
          callback(JSON.stringify(cbObject))
        };
        storage = new Storage();
        storage.upgradeApplication(successCb_upgradeApplication, failureCb_upgradeApplication, options_upgradeApplication);
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        callback(JSON.stringify(cbObject))
      }
      var configuration = new Configuration();
      configuration.setServerProperty(successCb, failureCb, options);
    };
    this.upgradeApplicationNow = function (callback){
      var options_upgradeApplication = {
          to : Storage.AppMode.LOCAL,
          recovery : false,
          type : "ipk"
        };
        var successCb_upgradeApplication = function (cbObject){
          setTimeout(function(){
            self.rebootSystem();
          },2000);
          self.log("____________________________ APP UPGRADE SUCESS");
          callback("APP UPGRADE SUCESS")
        };
        var failureCb_upgradeApplication = function (cbObject){
          self.log(JSON.stringify(cbObject));
          callback(JSON.stringify(cbObject))
        };
        storage = new Storage();
        storage.upgradeApplication(successCb_upgradeApplication, failureCb_upgradeApplication, options_upgradeApplication);
    };

    var callback_upgradeApplicationR = null;
    this.updateFirmware = function(data, callback_updateFirmware){
      callback_upgradeApplicationR = callback_updateFirmware;
      var successCb_downloadFirmware = function () {
        self.upgradeFirmware(function(err, result){
          if(err){
            callback_upgradeApplicationR(null, "Download successful -- upgrade failure: "+err);
          }
          else{
            callback_upgradeApplicationR(null, "Download successful -- upgrade successful");
          }
        });
      };

      var failureCb_downloadFirmware = function(cbObject) {
        callback_upgradeApplicationR(JSON.stringify(cbObject));
      };

      var options_downloadFirmware = {
        uri : data.url
      };
      self.log(options_downloadFirmware.uri);
      var storage = new Storage();
      storage.downloadFirmware(successCb_downloadFirmware, failureCb_downloadFirmware, options_downloadFirmware);
      setInterval(function(){self.getFirmwareUpgradeStatus();}, 2000);
    };

    this.upgradeFirmware = function(callback_upgradeFirmware) {
        var successCb_upgradeFirmware = function () {
            self.log("firmware upgrade is successful");
            callback_upgradeFirmware(null, true);
        };

        var failureCb_upgradeFirmware = function(cbObject) {
            callback_upgradeFirmware(JSON.stringify(cbObject));
        };

        var storage = new Storage();
        storage.upgradeFirmware(successCb_upgradeFirmware, failureCb_upgradeFirmware);

    };
    this.getFirmwareUpgradeStatus = function() {
      var successCb = function (cbObject) {
          self.log("status " + cbObject.status);
          self.log("upgradeProgress " + cbObject.upgradeProgress);
          self.log("downloadProgress " + cbObject.downloadProgress);
      };

      var failureCb = function (cbObject) {
          var errorCode = cbObject.errorCode;
          var errorText = cbObject.errorText;
          self.log(" Error Code [" + errorCode + "]: " + errorText);
      };

      var storage = new Storage();
      storage.getFirmwareUpgradeStatus(successCb, failureCb);
    }

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

    this.getStatusPanel = function(callback_getStatusPanel){
        function successCb(cbObject) {
            self.log("displayMode : " + cbObject.displayMode);
            if(cbObject.displayMode == "Active"){
                callback_getStatusPanel(null, true);
            }
            else{
                callback_getStatusPanel(null, false);
            }
        }

        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            callback_getStatusPanel(JSON.stringify(cbObject));
        }

        var power = new Power();
        power.getPowerStatus(successCb, failureCb);
    }
    this.setPanelOff = function(callback_setPanelOff){
        var options = {};
        options.displayMode = Power.DisplayMode.DISPLAY_OFF;

        function successCb() {
          if(typeof(callback_setPanelOff) != "undefined"){
            callback_setPanelOff(null, false);
          }
        }

        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            if(typeof(callback_setPanelOff) != "undefined"){
              callback_setPanelOff(JSON.stringify(cbObject));
            }
        }

        var power = new Power();
        power.setDisplayMode(successCb, failureCb, options);
    }
    this.setPanelOn = function(callback_setPanelOn){
        var options = {};
        options.displayMode = Power.DisplayMode.DISPLAY_ON;

        function successCb() {
            if(typeof(callback_setPanelOn) != "undefined"){
              callback_setPanelOn(null, true);
            }
        }

        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            if(typeof(callback_setPanelOn) != "undefined"){
              callback_setPanelOn(JSON.stringify(cbObject));
            }
        }

        var power = new Power();
        power.setDisplayMode(successCb, failureCb, options);
    }
    this.listFilesDirectory = function(dd, callback_listFilesDirectory){
        /*var listOption = {};
        listOption.path = dd;

        function successCb(cbObject) {
          self.log(JSON.stringify(cbObject));
            callback_listFilesDirectory(JSON.stringify(cbObject));
        }

        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            callback_listFilesDirectory(JSON.stringify(cbObject));
        }

        var storage = new Storage();
        storage.listFiles(successCb, failureCb, listOption);*/
        self.readDirectory(dd,function(data, directory){
          self.log(JSON.stringify(data));
          callback_listFilesDirectory(JSON.stringify(data));
        })
    }
    this.changePictureMode = function(mode, callback_changePictureMode){
        var options = {};
        //options.mode = Configuration.PictureMode.STANDARD;
        switch (mode){
            case "APS":
                options.mode = Configuration.PictureMode.APS;
                break;
            case "CINEMA":
                options.mode = Configuration.PictureMode.CINEMA;
                break;
            case "EXPERT1":
                options.mode = Configuration.PictureMode.EXPERT1;
                break;
            case "EXPERT2":
                options.mode = Configuration.PictureMode.EXPERT2;
                break;
            case "GAME":
                options.mode = Configuration.PictureMode.GAME;
                break;
            case "SPORTS":
                options.mode = Configuration.PictureMode.SPORTS;
                break;
            case "STANDARD":
                options.mode = Configuration.PictureMode.STANDARD;
                break;
            case "VIVID":
                options.mode = Configuration.PictureMode.VIVID;
                break;
        }

        function successCb() {
            callback_changePictureMode("change ok");
        }

        function failureCb(cbObject) {
            callback_changePictureMode(JSON.stringify(cbObject));
        }

        var configuration = new Configuration();
        configuration.setPictureMode(successCb, failureCb, options);
    };
    this.setPictureProperty = function(){
        var options = {};
        options.backlight = 100;
        options.contrast = 100;
        options.brightness = 50;
        options.sharpness = 30;
        options.color = 75;
        options.tint = 50;
        options.colorTemperature = 100
        options.dynamicContrast = "high";
        options.superResolution = "medium";
        options.colorGamut = "extended";
        options.dynamicColor = "high";
        options.noiseReduction = "medium";
        options.mpegNoiseReduction = "medium";
        options.blackLevel = "high";
        options.gamma = "medium";
        function successCb() {
            self.log("setPictureProperty ok")
        }
        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject));
        }
        var configuration = new Configuration();
        configuration.setPictureProperty(successCb, failureCb, options);
    }
    this.getPictureProperty = function(callback_getPictureProperty) {
        function successCb(cbObject) {
            callback_getPictureProperty(JSON.stringify(cbObject))
        }

        function failureCb(cbObject) {
            callback_getPictureProperty(JSON.stringify(cbObject))
        }

        var configuration = new Configuration();
        configuration.getPictureProperty(successCb, failureCb);
    }
    this.getFailoverMode = function(callback_getFailoverMode){
        var successCb = function (cbObject) {
            callback_getFailoverMode(JSON.stringify(cbObject));
        };

        var failureCb = function (cbObject) {
            callback_getFailoverMode(JSON.stringify(cbObject));
        };

        var signage = new Signage();
        signage.getFailoverMode(successCb, failureCb);
    }
    this.setFailoverMode = function(mode, priorityI, callback_setFailoverMode){
        var options={failoverMode:Signage.FailoverMode.OFF}
        switch (mode){
            case "MANUAL":
                options.failoverMode = {
                    mode: Signage.FailoverMode.MANUAL,
                    priority: [
                        'ext://hdmi:1',
                        'ext://hdmi:2',
                        'ext://dvi:1',
                        'ext://internal_memory',
                        'ext://dp:1'
                    ]
                }

            break;
            case "AUTO":
                options.failoverMode = {
                    mode: Signage.FailoverMode.AUTO
                }
            break;
            case "OFF":
                options.failoverMode = {
                    mode: Signage.FailoverMode.OFF
                }
            break;
        }
        self.log(JSON.stringify(options))
        var successCb = function () {
            callback_setFailoverMode("change failoverMode ok");
        };

        var failureCb = function (cbObject) {
            self.log(JSON.stringify(cbObject))
            callback_setFailoverMode(JSON.stringify(cbObject));
        };

        var signage = new Signage();
        signage.setFailoverMode(successCb, failureCb, options);
    }
    var old_status = null;
    var IntervalTime;
    this.setIntervalTime = function(){
        document.getElementById("HDMIVideo").style.visibility = "hidden";
                    document.getElementById("HDMIScreen").style.visibility = "hidden";
        IntervalTime = setInterval(function(){self.checkHDMIstatus();},10000);
    }
    //check whether there is HDMI signal
    this.checkHDMIstatus = function(){
        function successCb(cbObject) {
            self.log(JSON.stringify(cbObject))
            if(cbObject.currentSignalState == 'bad'){
                if(old_status == "good"){
                    self.rebootSystem();
                }
                else{
                    self.log("22222222222222222222222222222222222222222222222222222222222222222222222")
                    document.getElementById("HDMIVideo").style.visibility = "hidden";
                    document.getElementById("HDMIScreen").style.visibility = "hidden";
                    $(".stage").show();
                }
            }
            else{
                if(cbObject.currentSignalState == "good"){
                    self.log("333333333333333333333333333333333333333333333333333333333333333333333333333")
                    document.getElementById("HDMIScreen").style.visibility = "visible";
                    document.getElementById("HDMIVideo").style.visibility = "visible";
                    $(".stage").hide();
                    old_status="good";
                }
            }
        }

        function failureCb(cbObject) {
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;

            self.log ("Error Code [" + errorCode + "]: " + errorText);
        }
        // The inputSource object that has already been initialized with initialize() method.
        var inputSource = new InputSource();
        inputSource.getInputSourceStatus(successCb, failureCb);
    }
    this.HDMIscreen = function(){
        var options = {};
        options.divId = "HDMIScreen"; // It should be matched to div tag name in an html page.
        options.videoId = "HDMIVideo";
        options.callback = self.setIntervalTime;
        options.src = "ext://hdmi:1";

        function successCb(cbObject) {
        }
        function failureCb(cbObject) {
            var errorCode = cbObject.errorCode;
            var errorText = cbObject.errorText;

            self.log ("Error Code [" + errorCode + "]: " + errorText);

        }
        var inputSource = new InputSource();
        inputSource.initialize(successCb, failureCb, options);
    }
    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.socketServerBroadcast = function(msg){
      if(self.websocket_server){
        var message = JSON.stringify(msg);
        var request = webOS.service.request(self.service_id,{
            method:"socketServerBroadcast",
            parameters: {
                msg: message
            },
            onSuccess: function(inResponse){
                self.log("socketServerBroadcast sucess ... "+inResponse.response);
            },
            onFailure: function(inError){
                self.log("socketServerBroadcast fail ... "+inError.errorText);
                self.log("socketObjectType = "+inError.object_type);
            },
            onComplete: function(inResponse){
                //self.log("fileExists complete ... "+inResponse.returnValue +  "filename: "+filename);
            },
            subscribe : false
        });
        message = null;
      }
    };

    this.socketServerStart = function(port,onOpenCallback,onMessageCallback,onTerminatedCallback){
      if(!self.websocket_server){
        if(typeof(onOpenCallback) !== "undefined"){
          self.websocket_onOpenCallback = onOpenCallback;
        }
        if(typeof(onMessageCallback) !== "undefined"){
         self.websocket_onMessageCallback = onMessageCallback;
        }
        if(typeof(onTerminatedCallback) !== "undefined"){
         self.websocket_onTerminatedCallback = onTerminatedCallback;
        }

        // NEEDS A VALID WS MODULE COMPATIBLE WITH STRICT MODE NODEJS V0.10 --- WS@1.0
        var request = webOS.service.request(self.service_id,{
            method:"socketServerStart",
            parameters: {
                port: port
            },
            onSuccess: function(inResponse){
                if(typeof(inResponse.response) !== "undefined"){
                  if(inResponse.response == "message"){
                    self.log("onSocketMessage : Message from client !!! ");
                    self.websocket_onMessageCallback(inResponse.message);
                  }else if(inResponse.response == "open"){
                    self.log("onSocketOpen : New Client Connect !!! ");
                    self.websocket_onOpenCallback();
                  }else if(inResponse.response == "close"){
                    self.log("onSocketClose : Client Closed !!! ");
                    self.websocket_onTerminatedCallback();
                  }else if(inResponse.response == "error"){
                    self.log("onSocketError : Client Closed with Error!!! ");
                    self.websocket_onTerminatedCallback();
                  }
                }
            },
            onFailure: function(inError){
                //self.log("socketServerStart fail ... "+inError.errorText);
                if(typeof(inError.response) !== "undefined"){
                  if(inError.response == "void"){
                    self.log("socketServerStart already started ... ");
                    self.websocket_server = true;
                  }else if(inError.response == "init"){
                    self.log("socketServerStart started ... ");
                    self.websocket_server = true;
                  }
                }
            },
            onComplete: function(inResponse){
                //self.log("fileExists complete ... "+inResponse.returnValue +  "filename: "+filename);
            },
            subscribe : true
        });
      }
    };

    this.findSyncIp = function (callback){
      var deviceInfo = new DeviceInfo();
      deviceInfo.getNetworkInfo(function(cbObject){
          var found = false;
          self.log("Found Sync IP : success");
          var status = cbObject;
          if(typeof(status) != "undefined"){
              if(typeof(status.wifi) != "undefined"){
                if(typeof(status.wifi.state) != "undefined"){
                  if(status.wifi.state == "connected"){
                    if(typeof(status.wifi.ipAddress) != "undefined"){
                      self.log("Found Sync IP : "+status.wifi.ipAddress);
                      if(typeof(callback) !== "undefined"){
                          found = true;
                          callback(status.wifi.ipAddress);
                      }
                    }
                  }
                }
              }
              if(!found){
                if(typeof(status.wired) != "undefined"){
                  if(typeof(status.wired.state) != "undefined"){
                    if(status.wired.state == "connected"){
                      if(typeof(status.wired.ipAddress) != "undefined"){
                        self.log("Found Sync IP : "+status.wired.ipAddress);
                        if(typeof(callback) !== "undefined"){
                            found = true;
                            callback(status.wired.ipAddress);
                        }
                      }
                    }
                  }
                }
              }
          }
          if(!found){
            if(typeof(callback) !== "undefined"){
                callback("0.0.0.0");
            }
          }
      }, function(cbObject) {
          var errorCode = cbObject.errorCode;
          var errorText = cbObject.errorText;

          self.log("Find Sync IP Error Code [" + errorCode + "]: " + errorText);
          if(typeof(callback) !== "undefined"){
              callback("0.0.0.0");
          }
      });
    };
    this.getPowerOnOffHistory = function(callback_getPowerOnOffHistory){
        var custom = new Custom();
        custom.Configuration.getPowerOnOffHistory(
            function successCallback(successObject) {
                callback_getPowerOnOffHistory(JSON.stringify(successObject));
            },
            function failureCallback(failureObject) {
                callback_getPowerOnOffHistory(JSON.stringify(failureObject));
            }
        );
    }
    this.getBrigthness = function(callback_getBrigthness){
        self.getPictureProperty(callback_getBrigthness)
    }
    this.setBrightness = function(brightness, callback_setBrightness){
        callback_setBrightness("no function");
    }
    this.getContrast = function(callback_getContrast){
        self.getPictureProperty(callback_getContrast)
    }
    this.setContrast = function(contrast, callback_setContrast){
        callback_setContrast("no function");
    }
    this.getBacklight = function(callback_getBacklight){
        self.getPictureProperty(callback_getBacklight)
    }
    this.setBacklight = function(backlight, callback_setBacklight){
        callback_setBacklight("no function");
    }
    this.geConfigPanel = function(callback_geConfigPanel){
      self.getPictureProperty(callback_geConfigPanel)
    }
    this.setConfigPanel = function(data, callback_setConfigPanel){
        callback_setConfigPanel("no function");
    }
    this.getStatusRemoteControl = function(callback_getStatusRemoteControl){
      var successCb = function (cbObject) {
          callback_getStatusRemoteControl(cbObject);
      };
      var failureCb = function (cbObject) {
          var errorCode = cbObject.errorCode;
          var errorText = cbObject.errorText;
          callback_getStatusRemoteControl(" Error Code [" + errorCode + "]: " + errorText);
      };
      var signage = new Signage();
      signage.getUsagePermission(successCb, failureCb);
    }
    this.setStatusRemoteControl = function(data, callback_setStatusRemoteControl){
      if(data == "OFF"){
        var options = {
            policy: {
                remoteKeyOperationMode: Signage.KeyOperationMode.POWER_ONLY,
                localKeyOperationMode: Signage.KeyOperationMode.ALLOW_ALL
            }
        };
      }
      else{
        var options = {
            policy: {
                remoteKeyOperationMode: Signage.KeyOperationMode.ALLOW_ALL,
                localKeyOperationMode: Signage.KeyOperationMode.ALLOW_ALL
            }
        };
      }
      var successCb = function () {
          callback_setStatusRemoteControl("successfully Set");
      };
      var failureCb = function (cbObject) {
          var errorCode = cbObject.errorCode;
          var errorText = cbObject.errorText;
          callback_setStatusRemoteControl(" Error Code [" + errorCode + "]: " + errorText);
      };
      var signage = new Signage();
      signage.setUsagePermission(successCb, failureCb, options);
    }

    this.getDPMWakeup = function(optionsDeleteTimersOn){
      function successCb(cbObject){
          self.log(JSON.stringify(cbObject));
          self.getCurrentTime()
      }
      function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        self.getCurrentTime()
      }
      var power = new Power();
      power.getDPMWakeup(successCb, failureCb);
    };
    this.getCurrentTime = function(callback){

      function successCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        self.dataInfoSystem.currentTime = cbObject
        self.getTimeZone(callback);
        // Do something
    }

    function failureCb(cbObject) {
        self.log(JSON.stringify(cbObject));
        self.dataInfoSystem.currentTime = cbObject
        self.getTimeZone(callback);
    }

    var configuration = new Configuration();
    configuration.getCurrentTime(successCb, failureCb);
    };

    this.getLocaleList = function(){
        /*function successCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            this.getTimeZone();
        }

        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            this.getTimeZone();
        }

        var configuration = new Configuration();
        configuration.getLocaleList(successCb, failureCb);*/
        self.getTimeZone();
    }
    this.getTimeZone= function(callback){
        function successCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            //self.getTimeZoneList()
            self.dataInfoSystem.timezone = cbObject;
            callback(JSON.stringify(self.dataInfoSystem))
        }

        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject));
            self.dataInfoSystem.timezone = cbObject;
            callback(JSON.stringify(self.dataInfoSystem))
        }

        var configuration = new Configuration();
        configuration.getTimeZone(successCb, failureCb);
    }

    this.getTimeZoneList= function(){
        function successCb(cbObject) {
            self.log(JSON.stringify(cbObject));

        }

        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject));
        }

        var configuration = new Configuration();
        configuration.getTimeZoneList(successCb, failureCb);
    }

    this.setSystemDateTimeNTP = function(ntp, callback){
      self.log("Setting WebOS Time : ");
      var date = new Date(); // In milliseconds
      var options = {};
      options.year = parseInt(moment.utc(date).format('YYYY'));
      options.month = parseInt(moment.utc(date).format('M'));
      options.day = parseInt(moment.utc(date).format('D'));
      options.hour = parseInt(moment.utc(date).format('H'));
      options.minute = parseInt(moment.utc(date).format('m'));
      options.sec = parseInt(moment.utc(date).format('s'));
      options.ntp = ntp;
      self.log(JSON.stringify(options));
      function successCb(cbObject) {
          self.log(JSON.stringify(cbObject))
          callback(JSON.stringify(cbObject))
      }
      function failureCb(cbObject) {
          self.log(JSON.stringify(cbObject))
          callback(JSON.stringify(cbObject))
      }
      var configuration = new Configuration();
      configuration.setCurrentTime(successCb, failureCb, options);
    };
    this.setTimeZoneSocket1 = function(timeZone, callback){
        function successCb(cbObject) {
            self.log(JSON.stringify(cbObject))
            callback(JSON.stringify(cbObject))
        }

        function failureCb(cbObject) {
            self.log(JSON.stringify(cbObject))
            callback(JSON.stringify(cbObject))
        }

    /*    var timeZone = {
            continent: "America",
            country: "United States of America",
            city: "Adak"
        };*/
        var options = {
            timeZone: timeZone
        };
        self.log(JSON.stringify(timeZone))
        var configuration = new Configuration();
        configuration.setTimeZone(successCb, failureCb, options);
    }
    this.setTimeZoneSocket = function(timeZone, callback){
        var date = new Date(); // In milliseconds
        var options = {};
        options.year = parseInt(moment.utc(date).format('YYYY'));
        options.month = parseInt(moment.utc(date).format('M'));
        options.day = parseInt(moment.utc(date).format('D'));
        options.hour = parseInt(moment.utc(date).format('H'));
        options.minute = parseInt(moment.utc(date).format('m'));
        options.sec = parseInt(moment.utc(date).format('s'));
        options.ntp = true;
        self.log(JSON.stringify(options));
        function successCb(cbObject) {
            self.log("weeeeeeeeeeeeeeeeeeeeeeeee")
            self.setTimeZoneSocket1(timeZone, callback)
        }
        function failureCb(cbObject) {
            self.log("wiiiiiiiiiiiiiiiiiiiiii")
            self.log(JSON.stringify(cbObject))
            self.setTimeZoneSocket1(timeZone, callback)
        }
        var configuration = new Configuration();
        configuration.setCurrentTime(successCb, failureCb, options);
    }
}
WebOsSystemController.prototype = new SystemController();
