
// Calculating offset of each video starting from its duration
for (i = 0; i < sync_offsets.length; ++ i) sync_offsets [i].offset = i ? (sync_offsets [i - 1].duration + sync_offsets [i - 1].offset) : 0;


// *****
//
//  Class syncronizer
//
// *****

function syncronizer (self_name)
{
    // ***  Class variables  ***
    this.my_name = self_name;  // Self reference
    this.step = 0;  // Corresponds to id_timeline in DB

    this.interval = 3;  // Actualize each 3 seconds

    this.onFI_position = 0;  // Saved onFI (timecode)
    this.onFI_last = 0;  // Actual onFI
    this.onFI_delta = 0;  // Actual onFI delta

    this.TIME_position = 0;  // Saved TIME
    this.TIME_last = 0;  // Actual TIME
    this.TIME_delta = 0;  // Actual TIME delta

    this.TIME_item = 0;  // TIME playlist item
    this.TIME_line = 0;  // TIME correspondent timeline

    // Receives TIME event from player
    this.TIME_handler = function (data)
    {
        // Checking for correct data
        if (isNaN (data.listIndex) || isNaN (data.position)) return;

        // Parsing data
        this.TIME_item = data.listIndex;
        this.TIME_last = parseInt (data.position);

        // Calculating more info
        this.TIME_delta = Math.abs (this.TIME_last - this.TIME_position);
        this.TIME_line = parseInt (this.TIME_last + sync_offsets [this.TIME_item].offset);
    }

    // Receives onFI event from player
    this.onFI_handler = function (data)
    {
        // Convertind and checking fields
        this.onFI_last = this.onFI_2_unixtime (data.sd, data.st);
        if (!this.onFI_last) return;

        // Calculating more info
        this.onFI_delta = Math.abs (this.onFI_last - this.onFI_position);
    }

    // Converti onFI (timecode) to unixtime
    this.onFI_2_unixtime = function (sd, st)
    {
        sd = sd.split ('-');
        for (i = 0; i < 3; ++ i) sd [i] = parseInt (sd [i], 10);

        st = st.split ('.');
        st [1] = parseInt (st [1], 10);

        st [0] = st [0].split (':');
        for (i = 0; i < 3; ++ i) st [0][i] = parseInt (st [0][i], 10);

        var timecode = new Date (sd [2], sd [1] - 1, sd [0], st [0][0], st [0][1], st [0][2], st [1]);
        return Math.round (timecode.getTime () / 1000) - (timecode.getTimezoneOffset () * 60);
    }

    // ***  Ajax call to update contents  ***
    this.update = function ()
    {
        // Variables for synchronization
        var timeline = 0;
        var timecode = 0;

        // TIME => timeline
        if (this.TIME_delta)
        {
            timeline = this.TIME_line;
            this.TIME_delta = 0;
            this.TIME_position = this.TIME_last;
        }

        // onFI => timecode
        if (this.onFI_delta)
        {
            timecode = this.onFI_last;
            this.onFI_delta = 0;
            this.onFI_position = this.onFI_last;
        }

        // Packing variables
        var sync_params =
        {
            id_event: id_event,
            id_lang: id_lang,
            step: this.step,
            timeline: timeline,
            timecode: timecode,
            rnd: Math.random ()
        }

        var this_ = eval (this.my_name);

        $.get ('_sync.php', sync_params, function (data)  // Ajax call
        {
            var result;
            try {  eval (data);  } catch (err) {  alert (err.description);  }

            if (!result.step  ||  this_.step == result.step) return;
            else
            {
                this_.step = result.step;
                this_.paint (result);
            }
        });  // $.get
    }  // this.update = function (timeline)

    // ***  Paint results of ajax call  ***
    this.paint = function (result)
    {
        for (key in result)  // Itering results
        {
            // Getting value and painting it
            var val = eval ('result.' + key);
            $('.el_' + key).html (val);

            // IE Patch when loading images
            val = String (val);
            val = val.split ('src="');
            if (val.length > 1)
            {
                val = val [1].split ('"');
                var img = new Image ();
                img.src = val [0];
/*
                var pic = $('div.el_picture img');
                if (pic) $('div.el_picture img').css('marginTop', Math.abs ((pic.parent ().attr('height') - pic.attr('height')) / 2) + 'px');
*/
            }  // if (val.length > 1)
        }  // for (key in result)
    }  // this.paint = function (result)
}  // function syncronizer ()



// *****
//
//  Class flash_player
//
// *****

function flash_player (self_name)
{
    // ***  Class variables  ***
    this.my_name = self_name;  // Self reference

    this.player = null;  // Player object
    this.player_id = null;  // Player ID

    // ***  Embedding player in page  ***
    this.embed = function (player, player_id, width, height, xml_path, installer, autoplug)
    {
        var flashvars =
        {
            path: xml_path,
            flashid: player_id
        }
//        if (vars) for (key in vars) eval ('flashvars.' + key + ' = ' +

        var params =
        {
            allowscriptaccess: 'always',
            allowfullscreen: true,
            wmode: 'opaque',
            id: player_id
        };

        swfobject.embedSWF (player, player_id, width, height, '9.0.115', installer, flashvars, params, {});
        if (autoplug) this.plug (player_id);
    }  // this.embed = function (player, player_id, width, height, xml_path, installer, autoplug)


    // ***  Plug the class to a phisical player  ***
    this.plug = function (player_id)
    {
        this.player = document.getElementById (player_id);  // Trying to get flash player
        if (this.player  &&  this.player.addModelListener) this.player_id = player_id;
        else
        {
            this.player = null;
            if (this.my_name) setTimeout (this.my_name + '.plug ("' + player_id + '");', 250);
            return false;
        }
    }  // this.plug = function (player_id, update_interval)

    // ***  Seek the player to a specific item + second
    this.seek = function (item, position)
    {
        if (!this.player) return false;
        try
        {
            this.player.seek (position, item);
        }
        catch (err)
        {
            alert ('Cannot jump to item ' + item + ', position ' + position);
        }
    }  // this.seek = function (item, position)

    // ***  Add a listener to the player  ***
    this.addModelListener = function (event_name, callback_function)
    {
        if (!this.player)
        {
            if (this.my_name) setTimeout (this.my_name + '.addModelListener ("' + event_name + '", "' + callback_function + '");', 250);
            return false;
        }
        try 
        {
            this.player.addModelListener (event_name, callback_function);
        }
        catch (e)
        {
            alert ('ERROR: ' + e);
        }
    }  // this.addModelListener = function (event_name, callback_function)
}

function player_jump (flashid, playlistNum, time)
{
    try {    oPlayer.seek (playlistNum, time);    } // Catching "TIME" event
    catch (err) {  alert ('Cannot jump to item ' + playlistNum);  }
}



var oSync = new syncronizer ('oSync');
var oPlayer = new flash_player ('oPlayer');

$(document).ready(function(){
/*
    if (!on_demand) oPlayer.embed ('http://hwcdn.net/x8p6d3s3/cds/ikunaPlayer.3_0_0.swf', 'ikunaPlayer', '100%', '100%', xml_path, media_path + 'expressInstall.swf', on_demand);
    else oPlayer.embed ('http://sincro.ikunamedia.com/media/ikunaPlayer.3_0_0.swf', 'ikunaPlayer', '100%', '100%', xml_path, media_path + 'expressInstall.swf', on_demand);
*/
    oPlayer.embed ('/media/ikunaPlayer.3_0_2.swf', 'ikunaPlayer', '100%', '100%', xml_path, media_path + 'expressInstall.swf', true);

    if (plug_db)
    {
        // If on demand, using player TIME
        if (on_demand) oPlayer.addModelListener ('TIME', 'oSync.TIME_handler');

        // Plugging onFI (timecode) handler
        oPlayer.addModelListener ('onFI', 'oSync.onFI_handler');

        // Setting interval for updates
        oSync.update ();
        setInterval ('oSync.update ();', oSync.interval * 1000);
    }

    $('div#div_tabs a').click(function(){

        $('.tab_content').hide();
        $('div#div_tabs li').removeClass('selected');

        $('#' + $(this).attr('rel')).show();
        $(this).parent().addClass('selected');

        return false;

    });

    $('#display_options a').click(function(){
        var new_style = $(this).attr('rel');
        if (new_style) {
            $('#main').removeClass('normal slide player only_player').addClass(new_style);
            setTimeout ("$('#main').addClass('" + new_style + "');", 0);
        }
    });

    $('.select_open').hover(
        function(){  $(this).parent().css('height','auto');  },
        function(){  $(this).parent().css('height','20px');  }
    );

    $('#txt_question').focus(function(){  if (this.value == this.defaultValue) this.value = '';  }).blur(function(){  if (this.value == '') this.value = this.defaultValue;  });
    $('#btn_question').click(function(){
//        if (!window.confirm ('¿Confirmas el envío?')) return;
//        alert (this.form.action);
        $('#answer').html('Enviando ...').fadeIn(200).load(this.form.action, {  r: Math.random(),  msg: this.form.txt_question.value  }, function(){
            // $('#answer').fadeIn(200);
            setTimeout ("$('#answer').fadeOut(200);", 5000);
        });
    });

    var nav_pos = 0;
    var nav_ul = $('div.thumbs div.img ul');
    var nav_count = nav_ul.find ('li').length;
    nav_ul.css({  position: 'absolute',  width: (92 * nav_count) + 'px',  left: '184px'  });

    $('div.thumbs div.nav a').click(function(){

        if ($(this).parent().hasClass('left')) nav_pos -= 1;
        if ($(this).parent().hasClass('right')) nav_pos += 1;

        if (nav_pos < 0) nav_pos = 0;
        if (nav_pos >= nav_count) nav_pos = nav_count - 1;

        nav_ul.animate({  left: ((2 - nav_pos) * 92) + 'px'  }, 150);

    });

    $('a.jumper').click(function(){

        var jump_item = 0;
        var jump_time = 0;
        var jump_abs_time = parseInt ($(this).attr('rel'));

        for (i = 0; i < sync_offsets.length; ++ i)
        {
            if ((sync_offsets [i].offset <= jump_abs_time)  &&  (jump_abs_time < sync_offsets [i].offset + sync_offsets [i].duration))
            {
                jump_item = i;
                jump_time = jump_abs_time - sync_offsets [i].offset;
            }
        }
        player_jump ('ikunaPlayer', jump_item, jump_time);

    });

});

