// TODO : Needs a SWF Loader with ExternalInterface to control de SWF movie

function DisplayFlashElement(ContentElement){
    var self = this; self.name = "DisplayFlashElement"; // MANDATORY

    this.reference = -1;
    this.type = -1;
    this.switch = 0;
    this.relative_path = false;
    this.force_http_source = false;
    this.die = true;
    this.time_to_die = 1500;

    this.loaded = false;

    this.x = 0;
    this.y = 0;
    this.w = "100%";
    this.h = "100%";
    this.z = 1;

    this.ui = false;
    this.uiTimer = null;
    this.uiStartTime = 0;

    this.source = ContentElement.getSource();
    this.duration = ContentElement.getDuration();
    this.relative_path = ContentElement.relative_path;
    this.path = ContentElement.path;
    this.tag = "";
    this.timer = null;

    this.swf_timer = 0;
    this.loader_timer = 0;

    this.totalFrames = 0;
    this.max_frame = -1;
    this.max_loads_retry = 100;

    this.initiated = false;

    this.update = function(ContentElement){
        self.content = ContentElement;
        self.source = ContentElement.getSource();
        self.duration = ContentElement.getDuration();
        self.relative_path = ContentElement.relative_path;
        self.path = ContentElement.path;
    };
    
    this.createFlash = function(layer){
      try{
        $("#"+self.tag).hide();
        $("#"+self.tag).remove();
      }catch(e){
        self.log("TAG does not exist");
      }
      $(".stage").append('<div class="player-media" id="'+self.tag+'"></div>');
    };

    this.load = function(){
        self.loaded = false;
        self.createFlash();
        //if(!self.initiated){
            var base = self.path;
            base = base.substring(0,base.lastIndexOf('/'));

            if(self.platform == "WEB" ){
                if(!self.trim_path){
                    base +="/attachment/";
                }else{
                    base = "."
                }
            }

            var loop = true;
            // LOOP CONTROL ... should we use it ? when ?
            /*
            var loop = false;
            if(self.duration == -1){
                loop = true;
            }
            */

            var flash_data = $.flash.create({
                        swf: self.path,
                        width: self.w,
                        height: self.h,
                        play: false,
                        loop: loop,
                        wmode: 'transparent',
                        allowscriptaccess : 'always',
                        allownetworking: 'all',
                        salign : 'tl',
                        base : base+"/",
                        scale : 'exactfit',
                        quality : 'autohigh'
            });
            self.initiated = true;
        //}
        

        self.max_loads_retry = 100;
        self.log("Loading flash .. on tag : "+$("#"+self.tag).attr("id"));
        $("#"+self.tag).one("error",self.onElementLoadError);
        if($("#"+self.tag).find("object").length > 0){
            $("#"+self.tag).find("object").eq(0).remove();
        }
        //var base = self.path;
        //base = base.substring(0,base.lastIndexOf('/'));
        //self.log("Source : "+self.source);
        //self.log("Base : "+base+"/");
        //self.log("Path : "+self.path);
        if(flash_data){
          $("#"+self.tag).html(flash_data);
          $("#"+self.tag).css('visibility','hidden');
          $("#"+self.tag).css('display','inline');
          self.loader_timer = setTimeout(self.checkLoading,100);
        }else{
          self.onElementLoadError(null);
        }
    };

    this.checkLoading = function(){
        clearTimeout(self.loader_timer);
        if(self.max_loads_retry > 0){
            self.max_loads_retry--;
            $("#"+self.tag).find("object").flash(
                function() {
                  try{
                    var totalFrames = parseInt(this.TGetProperty('/',5));
                    var loadedFrames = parseInt(this.TGetProperty('/',12));
                    self.log("Loaded : "+loadedFrames+" of "+totalFrames);
                    
                    if(totalFrames == loadedFrames){
                        self.totalFrames = totalFrames;
                        self.loaded = true;
                        $(self).trigger("DisplayElementLoaded");
                    }else{
                        self.log("Trying to read TotalFrames for SWF file");
                        self.loader_timer = setTimeout(self.checkLoading,100);
                    }
                  }catch(e){
                    self.log("We have no access to Total Frames for SWF. Will use timeout duration");
                    self.loaded = true;
                    self.totalFrames = 1;
                    $(self).trigger("DisplayElementLoaded");
                  }
                }
            );
        }else{
            self.notifyError(self.ERROR['DISPLAY_FLASH_ELEMENT']+2,self.name+": Function checkLoading() failed : could not load TOTAL FRAMES for SWF. to many retries");
            $(self).trigger("DisplayElementLoaded");
        }
    };

    /*
    this.onElementLoadComplete = function(event){
        self.playstatus = "STOP";
        $(self).trigger("DisplayElementLoaded");
    };
    */

    this.onElementLoadError = function(event){
        self.notifyError(self.ERROR['DISPLAY_FLASH_ELEMENT']+1,self.name+": Function onElementLoadError() failed : could not load :"+self.source);
        self.disable();
        self.playstatus = "INVALID";
        $(self).trigger("DisplayElementError");
    };

    this.disable = function(){
        $("#"+self.tag).off("error");
        clearTimeout(self.timer);
        clearTimeout(self.loader_timer);
        clearTimeout(self.swf_timer);
        clearTimeout(self.timer);
        clearInterval(self.uiTimer);
    };

    this.play = function(){
        clearTimeout(self.swf_timer);
        if(isNaN(self.totalFrames) || self.totalFrames == 0){
            self.swf_timer = setTimeout(self.play,100);
        }else{
            self.play_on_ready();
        }
    };

    this.play_on_ready = function(){

        var duration = self.duration;
        self.log("Play : "+self.reference+" with duration : "+duration+" on tag :"+self.tag);

        if(duration > 0){
            duration = duration*1000;
            duration += 1500;
            self.log("Total Timeout Duration ms : "+duration);
            self.timer = setTimeout(self.timeout,duration);
        }

        $("#"+self.tag).find("object").flash(
            function() {
                //this.StopPlay();
                try{
                  this.GotoFrame(0);
                  var currentFrame = parseInt(this.TGetProperty('/', 4));
                  self.log("Start SWF from Frame : "+currentFrame+" with total Frames : "+self.totalFrames);
                  this.Play();
                }catch(e){
                  self.log("Start SWF started with unknown frame numbers");
                }
            }
        );
        $("#"+self.tag).show();
        $("#"+self.tag).css('visibility','visible');
        self.uiStartTime = Date.now();
        self.max_frame = -1;
        if(self.totalFrames > 1){
            self.swf_timer = setTimeout(self.checkPlaytime,100);
        }
        $(self).trigger("DisplayElementPlay");
    };

    this.checkPlaytime = function(){
        clearTimeout(self.swf_timer);
        $("#"+self.tag).find("object").flash(
            function() {
                var currentFrame = parseInt(this.TGetProperty('/', 4));
                self.log("SWF playing frame : "+currentFrame+" of "+self.totalFrames);
                if(currentFrame > self.max_frame){
                    self.max_frame = currentFrame;
                    self.swf_timer = setTimeout(self.checkPlaytime,100);
                }else{
                    self.max_frame = -1;
                    self.log("SWF Finished by totalFrames !");
                    self.playstatus = "STOP";
                    $(self).trigger("DisplayElementFinish");
                }
            }
        );
    };

    this.timeout = function(){
        self.log("Finished by timeout ! on tag :"+self.tag);
        clearTimeout(self.loader_timer);
        clearTimeout(self.swf_timer);
        clearTimeout(self.timer);
        clearInterval(self.uiTimer);
        if(self.die){
            $("#"+self.tag).find("object").flash(
                function() {
                  try{
                    this.GotoFrame(1);
                  }catch(e){
                    self.log("Start SWF died by timeout");
                  }
                }
            );
            self.playstatus = "STOP";
            $(self).trigger("DisplayElementFinish");
        }
    };

    this.connect = function(ui){
        /*
        self.ui = null;
        self.ui = ui;
        if(self.ui){
          self.uiTimer = setInterval(self.updateTime,200);
          self.ui.loadVolume();
        }
        */
    };

    this.disconnect = function(){
        /*
        clearInterval(self.uiTimer);
        if(self.ui){
            self.ui.unloadTime();
            self.ui.unloadVolume();
        }
        self.ui = null;
        */
    };

    this.updateTime = function(){
        if(self.ui){
            var current = (Date.now() - self.uiStartTime) / 1000;
            self.ui.loadTime(current,self.duration);
        }
    };

    this.clear_source = function(){
        clearInterval(self.uiTimer);
        if($("#"+self.tag).find("object").length > 0){
            $("#"+self.tag).find("object").eq(0).remove();
        }
        try{
          $("#"+self.tag).remove();
        }catch(e){
          self.log("TAG does not exist");
        }
    };

    // COMMON
    this.vanish = function(){
        $("#"+self.tag).hide();
        $("#"+self.tag).css("z-index","0");
        $("#"+self.tag).css("visibility","hidden");
        self.log("hide on tag : "+self.tag);
        //self.clear_source();
    };

    this.destroy = function(time){
        self.loaded = false;
        clearTimeout(self.timer);
        self.disconnect();
        if(typeof(time) === 'undefined'){ time = 0; }
        if(time == 0){
            self.vanish();
            self.clear_source();
        }else{
            setTimeout(function(){
                self.vanish();
                self.clear_source();
            },time);
        }
        self.disable();
        self.log(self.reference+" destroyed ... on tag : "+self.tag);
    };

    this.modifyViewer = function(x,y,w,h,z){
        if(typeof(z) === 'undefined'){z=1;}
        self.x = x;
        self.y = y;
        self.w = w;
        self.h = h;
        self.z = z;
    };

    this.setViewer = function(){
        $("#"+self.tag).css("left",self.x);
        $("#"+self.tag).css("top",self.y);
        $("#"+self.tag).css("width",self.w);
        $("#"+self.tag).css("height",self.h);
        $("#"+self.tag).css("z-index",self.z);
    };
}
DisplayFlashElement.prototype = new SystemController();
