﻿(function(jQuery) {

    /* jQuery Program Control plugin for TVKaista to display program information and actions
     * - Dependent on dropShadow
     */
    jQuery.fn.programControl = function(options) {
        var defaults = {
            hideDelay        : 200,
            playbackFunction : false
        };

        var settings = $.extend({}, defaults, options);

        return this.each(function() {
            var hideDelayTimer = null;
            var showDelayTimer = null;

            var link = '';
            var text = '';
            var showing = false;

            var trigger = $(this);
            var id      = trigger.attr('id').substr(3);
            var el      = trigger.hasClass('programtime') ? $('#pid' + id) : $(this);

            $(trigger.get(0)).mouseover(function() {
                if (hideDelayTimer) {
                    clearTimeout(hideDelayTimer);
                }
                if (showDelayTimer) {
                    clearTimeout(showDelayTimer);
                }

                showDelayTimer = setTimeout(function() {
                    if (!showing) {
                        showing = true;

                        // Is it a program or recording control?
                        // Programs cannot be played while recordings can
                        var isRecording = !el.hasClass("incomplete");

                        // extract values
                        link = el.attr('href');
                        text = el.html();

                        var org_w = el.width();
                        var org_h = el.height();
                        var w = Math.max(160, org_w);


                        // If the description includes an image we want to increase the size of the popup
                        // The image url is stored in a span with the class .poster to prevent all
                        // posters to get loaded. We'll only show a poster if the recording is complete.

                        if (isRecording) {
                            $('#pinfo' + id + ' .img').show();
                            $('#pinfo' + id + ' .poster').show();
                            if ($('#pinfo' + id + ' img').length > 0) {
                                w += 100;
                            } else if ($('#pinfo' + id + ' .poster').length > 0) {
                                w += 100;
                                $('#pinfo' + id + ' .poster:first').replaceWith([
                                    '<table style="float: left;">',
                                        '<tr>',
                                            '<td>',
                                                '<img id="posterplayback', id, '" src="', $('#pinfo' + id + ' .poster:first').html(), '" class="poster" />',
                                            '</td>',
                                        '</tr>',
                                        '<tr>',
                                            '<td>',
                                                '<a href="javascript:;" id="rci', id, '" class="reportproblem">'+ _('feedback_report_problem') + '</a>',
                                            '</td>',
                                        '</tr>',
                                    '</table>'].join(''));
                            }
                        } else {
                            $('#pinfo' + id + ' .img').hide();
                            $('#pinfo' + id + ' .poster').hide();
                        }

                        var desc = $('#pinfo' + id).html();

                        var links, pclass = '';
                        if (isRecording) {
                            links = $('#rlinks' + id).html();
                            pclass = "playback";
                        } else {
                            links = $('#plinks' + id).html();
                            pclass = "incomplete";
                        }
                        // Replace IDs to make them unique for the popup, we can not just copy the ones from the programs table
                        links = links.replace('id="ply', 'id="pup'); // Play option
                        links = links.replace('id="dwn', 'id="pud'); // Download option
                        links = links.replace('id="plr', 'id="pul'); // Playlist option
                        el.removeAttr('href');
                        el.css('position', 'relative');

                        // Create popup either to the right, left, top or bottom depending on where we are on the screen

                        var positionProps = {
                            id               : id,
                            titleWidth       : org_w,
                            top              : ( /Opera/.test(navigator.userAgent) ? (-7 + $(window).scrollTop()) : -7 ),
                            left             : ( /Opera/.test(navigator.userAgent) ? (-6 + $(window).scrollLeft()) : -6 ),
                            padding          : 5,
                            paddingRight     : 6,
                            width            : (w + 5)
                        };

                        el.html([
                            text,
                            '<div id="link-text', positionProps.id, '" class="programinfo">',
                                '<div class="', pclass, '" id="ply', positionProps.id, '" style="',
                                        'cursor: pointer; ',
                                        'width: ', positionProps.titleWidth, 'px;">',
                                    text,
                                '</div>',
                                '<div style="padding-top: 4px;">',
                                    links,
                                '</div>',
                                '<div style="padding-top: 4px;">',
                                    desc,
                                '</div>',
                            '</div>'
                        ].join(''));

                        $('#link-text' + id).css({
                            top          : positionProps.top + 'px',
                            left         : positionProps.left + 'px',
                            padding      : positionProps.padding + 'px',
                            paddingRight : positionProps.paddingRight + 'px',
                            width        : positionProps.width + 'px'
                        });

                        var toRight = (el.offset().left + $('#link-text' + id).width() + 6 - $(window).scrollLeft() < $(window).width());
                        if (!toRight) {
                            $('#ply' + id).css( 'padding-left', (w - org_w - 6) );
                            $('#link-text' + id).css('left', ( /Opera/.test(navigator.userAgent) ? (-(w - org_w) + $(window).scrollLeft()) : -(w - org_w) ) );
                        }

                        var textTop = $('#link-text' + id).offset().top;
                        if ( /Opera/.test(navigator.userAgent) ) {
                        	textTop = $('#link-text' + id).offset().top - $('#link-text' + id).parent().offset().top;
                        }
                        var toBottom = ( (textTop + $('#link-text' + id).height() + 6) - $(window).scrollTop() < $(window).height() );
                        if (!toBottom) {
                            $('#link-text' + id).css('top', ( /Opera/.test(navigator.userAgent) ? (-($('#link-text' + id).height() + 6 - org_h) + $(window).scrollTop()) : -($('#link-text' + id).height() + 6 - org_h) ) );
                        }

                        // Shadows disabled in opera. They were too buggy.
                        // buggy in general
                        if (!(/Opera/.test(navigator.userAgent))) {
                            $('#link-text' + id).dropShadow({
                                blur: 0,
                                opacity: 0.25
                            });
                            $( '#' + $('#link-text' + id).shadowId() ).css('zIndex', 0);
                        }

                        $('#link-text' + id).css('zIndex', 1);

                        // Add quickplay when pressing title or poster
                        if (options.playbackFunction) {
                            $('#playback' + id).click(function() {
                                options.playbackFunction(id);
                            });
                            $('#posterplayback' + id).click(function() {
                                options.playbackFunction(id);
                            });
                        }

                    }

                }, settings.hideDelay);
            }).mouseout(function() {
                if (hideDelayTimer) {
                    clearTimeout(hideDelayTimer);
                }
                if (showDelayTimer) {
                    clearTimeout(showDelayTimer);
                }

                hideDelayTimer = setTimeout(function() {
                    hideDelayTimer = null;
                    if (showing) {
                        el.html(text).attr('href', link);
                        el.css('position', 'static');
                        if (!(/Opera/.test(navigator.userAgent))) {
                            $('#link-text' + id).removeShadow();
                        }
                        showing = false;
                    }
                }, settings.hideDelay);
            });
        });
    };
})(jQuery);
