var scrollbarWidth = 0;
var tvmode = "horizontal";
var time_marker_current = 0;
var $tv_content, $tv_timeline, $tv_listin_inner, $tv_channels_list, $tv_time_marker, $tv_content_inner, $tv_content_holder, $tv_time_select, $tv_search_results, $tv_search_results_inner;

var tv_header_height = 0;
var tv_footer_height = 0;
var search_open = false;
var mousex = undefined;
var mousey = undefined;
var mousefirst = false;
$(document).ready(function() {

    // Post
    $(".btn").click(function() {
        $('#comment-form').submit();
        return false;
    });

    // Save tv guide settings
    $("#savesettings").click(function() {
        checkbox = document.getElementsByTagName("input");
        var channels = '';
        for (i = 0; i != checkbox.length; i++) {
            obj = checkbox[i];
            if (obj.name != obj.name.replace('cb_')) {
                if (checkbox[i].checked) {
                    channels += obj.name.replace('cb_', ':') + ":";
                }
            }
        }
        $.cookies.set("tvguidesettings", channels, { expiresAt: new Date(2014, 1, 1) });
        window.location = "/";
    });

    function checkKey(e) {
        var page;
        switch (e.keyCode) {
            case 27: // Escape key
                closeInfoBox();
                break;
            default:
                break;
        }
    }
    if ($.browser.mozilla) {
        $(document).keypress(checkKey);
    } else {
        $(document).keydown(checkKey);
    }

    // Infokasti sulgemine Escape klahviga
    function closeInfoBox() {
        var $infobox = $('#tv-infobox');
        if ($infobox.css('display') != 'none') {
            $infobox.hide();
        }
    }

    $.extend($.fn.disableTextSelect = function() {
        return this.each(function() {
            if ($.browser.mozilla) {//Firefox
                $(this).css('MozUserSelect', 'none');
            } else if ($.browser.msie) {//IE
                $(this).bind('selectstart', function() { return false; });
            } else {//Opera, etc.
                $(this).mousedown(function() { return false; });
            }
        });
    });

    if ($('#tv-vertical').length > 0) { tvmode = 'vertical'; }
    scrollbarWidth = $.getScrollbarWidth();

    $tv_content = $('#tv-content');
    if ($('#tv-listing').length > 0) {
        $tv_content_holder = $('#tv-content-holder');
        $tv_content_inner = $('#tv-content-inner');
        $tv_timeline = $('#tv-timeline');
        $tv_channels_list = $('#tv-channels-list');
        $tv_time_marker = $('#tv-time-marker');
        $tv_time_select = $('.tv-time-select');
        $tv_search_results = $('.tv-search-results');
        $tv_listing_inner = $('.tv-listing-inner');
        $tv_search_results_inner = $('.tv-search-results-inner');
        time_marker_current = parseInt($('#tv-time-marker').css('left'));

        // Telekaval liikukudes saatekasti tausta muutmine
        $('.tv-show').hover(function() {
            $(this).addClass('tv-show-type-8-active');
        }, function() {
            $(this).removeClass('tv-show-type-8-active');
        });

        if ($tv_content.length > 0 && $tv_timeline.length > 0 && $tv_channels_list.length > 0) {
            $tv_content.get(0).scrollLeft = 0;
            $tv_content.get(0).scrollTop = 0;
            $tv_timeline.get(0).scrollLeft = 0;
            $tv_timeline.get(0).scrollTop = 0;
            $tv_channels_list.get(0).scrollLeft = 0;
            $tv_channels_list.get(0).scrollTop = 0;

            $tv_content.height(320 + scrollbarWidth);
            if (tvmode == 'horizontal') {
                $tv_timeline.width(810 - scrollbarWidth);
            }
            else {
                $tv_channels_list.width(825 - scrollbarWidth);
                $tv_time_marker.width(825 - scrollbarWidth);
                var channels_count = $tv_channels_list.find('li').length;
                $tv_content_inner.width(channels_count * 120);

                if ($.browser.msie && $.browser.version < 7) {
                    $('.tv-content-column').eq($('.tv-content-column').length - 1).css('margin-right', '-3px');
                }
            }

            $tv_content_inner.disableTextSelect().mousedown(function(event) {
                event.preventDefault();

                $tv_content.css('cursor', 'move');
                $tv_content.bind('mousemove.drag', function(event) {
                    if (mousefirst) {
                        var x = mousex - event.pageX;
                        var y = mousey - event.pageY;
                        var tv_content_dom = $tv_content.get(0);

                        tv_content_dom.scrollLeft = tv_content_dom.scrollLeft + x * 5;
                        tv_content_dom.scrollTop = tv_content_dom.scrollTop + y * 5;
                    }
                    mousefirst = true;
                    mousex = event.pageX;
                    mousey = event.pageY;

                });
            });
            $(document).mouseup(function() {
                mousefirst = false;
                $tv_content.css('cursor', 'default');
                $tv_content.unbind('mousemove.drag');
            });
        }

        $tv_content.bind('scroll', function() {
            var ids = (tvmode == 'vertical') ? [$tv_channels_list, $tv_timeline] : [$tv_timeline, $tv_channels_list];
            var sl = $(this).get(0).scrollLeft;
            var st = $(this).get(0).scrollTop;
            ids[0].get(0).scrollLeft = sl;
            ids[1].get(0).scrollTop = st;

            if (tvmode == 'horizontal') {
                $tv_time_marker.css({
                    left: (time_marker_current - sl) + 'px'
                });
            }
            else {
                $tv_time_marker.css({
                    top: (time_marker_current - st) + 'px'
                });
            }
        });

        // Otsing
        $('#tv-listing .search .submit').click(function() {

            var showDate = $("#show-date").val();
            if (showDate == "") {
                var now = new Date();
                showDate = now.getDate() + "-" + now.getMonth() + 1 + "-" + now.getFullYear();
            }

            $('.tv-search-results').load("/tvshowquery/" + showDate + "/" + escape($("#show-query").val()));
            showTvSearchResults(300);
            return false;
        });


        $('.tv-search-results-title').click(function() { hideTvSearchResults(300); });

        $('#tv-listing-footer-right a').click(function() {
            var thisId = $(this).attr('id');
            var activeClass = thisId + '-active';
            if ($(this).hasClass(activeClass)) {
                $(this).removeClass(activeClass);
                $tv_content.find('.' + thisId).removeClass(activeClass);
            }
            else {
                $(this).addClass(activeClass);
                $tv_content.find('.' + thisId).addClass(activeClass);
            }
            return false;
        });

        if ($tv_time_marker.length > 0) { setCurrentTimePos(); }

        if ($('#fullview').length > 0) {

            tv_header_height = $('#tv-listing-header').outerHeight(true);
            tv_footer_height = $('#tv-listing-footer').outerHeight(true);
            setFullView();
            $(window).resize(setFullView);
        }
    }

    if ($('#gallery').length > 0) {
        var $gal = $('#gallery');
        var $gal_small = $('#gallery-small');
        var $gsmall_img = $('#gallery-small img');
        var $gal_big = $('#gallery-big');

        $gal_small.click(function() {
            $gal.hide();
            $gal.removeClass('gallery-small');
            $gal.addClass('gallery-big');
            $gal.show();
        });
        $gal_big.click(function() {
            if ($gsmall_img.length > 1) {
                galleryChange('next');
            }
            else {
                $gal.hide();
                $gal.removeClass('gallery-big');
                $gal.addClass('gallery-small');
                $gal.show();
            }
        });
        $('.gallery-buttons-right').click(function() { galleryChange('next'); });
        $('.gallery-buttons-left').click(function() { galleryChange('prev'); });
    }
});

function galleryChange(direction) {
    var $gsmall_img = $('#gallery-small img');
    var $gbig_img = $('#gallery-big img');
    var $gdesc = $('.gallery-desc-inner');

    var index = 0;
    if ($('#gallery-small').is(':hidden')) {
        index = $gbig_img.index($gbig_img.not(':hidden'));
    }
    else {
        index = $gsmall_img.index($gsmall_img.not(':hidden'));
    }

    var next = 0;
    if (direction == 'next') {
        if (index < $gsmall_img.length - 1) { next = index + 1; }
    }
    else {
        if (index == 0) { next = $gsmall_img.length - 1; }
        else { next = index - 1; }
    }


    $gsmall_img.hide().eq(next).show().css('display', 'block');
    $gbig_img.hide().eq(next).show().css('display', 'block');
    $gdesc.hide().eq(next).show();

}

function dragTVcontent() {

}

function setFullView() {
    //var ids = (tvmode == 'vertical') ? [$tv_channels_list,$tv_timeline] : [$tv_timeline,$tv_channels_list];
    if (tvmode == 'vertical') {
        var height = $(window).height() - 95 - 27 - 45 - 15 - 10 - 5 - tv_header_height - tv_footer_height - 20;
        $tv_time_select.height(height - 5 - scrollbarWidth);
        $tv_timeline.height(height - 41 - scrollbarWidth);
        $tv_content.height(height - 41);
        $tv_search_results.height(height - scrollbarWidth);
        $tv_search_results_inner.height(height - 50 - scrollbarWidth);

        var width = $(window).width() - 40 - 75;
        if (search_open) { width -= 160; }

        $tv_listing_inner.width(width);
        $tv_content_holder.width(width - 75);
        $tv_content.width(width - 75);
        $tv_channels_list.width(width - 75 - scrollbarWidth);

        $tv_time_marker.width(width - 75 - scrollbarWidth);
    }
    else {
        var height = $(window).height() - 95 - 27 - 45 - 15 - 10 - 5 - tv_header_height - tv_footer_height - 20;

        $tv_time_select.height(height - 5 - scrollbarWidth);
        $tv_channels_list.height(height - 25 - scrollbarWidth);
        $tv_content.height(height - 25);
        $tv_search_results.height(height - scrollbarWidth);
        $tv_search_results_inner.height(height - 50 - scrollbarWidth);
        $tv_time_marker.height(height - 25 - scrollbarWidth);

        var width = $(window).width() - 40 - 75;
        if (search_open) { width -= 160; }
        $tv_listing_inner.width(width);
        $tv_content_holder.width(width - 90);
        $tv_content.width(width - 90);
        $tv_timeline.width(width - 90 - scrollbarWidth);
    }
}

function setCurrentTimePos() {
    var current_ = new Date();
    setMarkerPosition(current_.getHours(), current_.getMinutes());
}
function setMarkerPosition(hours, minutes) {
    var pxls = 0;
    var ids = (tvmode == 'vertical') ? [$tv_channels_list, $tv_timeline] : [$tv_timeline, $tv_channels_list];

    if (tvmode == 'horizontal') {
        var pxls = Math.round((minutes / 60 + hours) * 240);
        time_marker_current = pxls;
        $tv_time_marker.css('left', pxls + 'px');
        ids[0].get(0).scrollLeft = pxls - 200;
        $tv_content.get(0).scrollLeft = pxls - 200;
    }
    else {
        var pxls = Math.round((minutes / 60 + hours) * 200);
        time_marker_current = pxls;
        $tv_time_marker.css('top', pxls + 'px');
        ids[0].get(0).scrollTop = pxls - 200;
        $tv_content.get(0).scrollTop = pxls - 200;
    }
}

function showTvSearchResults(speed) {
    if (!$('.tv-search-results').hasClass('tv-search-result-open')) {
        if (tvmode == 'horizontal') {
            $('#tv-content-holder,#tv-content,#tv-timeline').animate({
                width: '-=160'
            }, speed);
        }
        else {
            $('#tv-content-holder,#tv-content,#tv-channels-list').animate({
                width: '-=160'
            }, speed);
        }
        $('.tv-listing-inner').animate({
            width: '-=160'
        }, speed + 40);
        $('.tv-search-results').addClass('tv-search-result-open').width(0).show().animate({
            width: '160px'
        }, speed + 80);
        search_open = true;
    }
    else {
        hideTvSearchResults(speed);
    }

}
function hideTvSearchResults(speed) {
    if ($('.tv-search-results').hasClass('tv-search-result-open')) {
        $('.tv-search-results').removeClass('tv-search-result-open').width(0).show().animate({
            width: '0px'
        }, speed - 80);
        $('.tv-listing-inner').animate({
            width: '+=160'
        }, speed - 40);
        if (tvmode == 'horizontal') {
            $('#tv-content-holder,#tv-content,#tv-timeline').animate({
                width: '+=160'
            }, speed);
        }
        else {
            $('#tv-content-holder,#tv-content,#tv-channels-list').animate({
                width: '+=160'
            }, speed);
        }

        search_open = false;
    }
}
function toggleInfoBox(id, parent, date) {
    var $infobox = $('#tv-infobox');
    if ($infobox.css('display') == 'none') {
        var $tv_infobox_desc = $('.tv-infobox-description');
        var $tv_infobox_image = $('.tv-infobox-image');
        var $tv_infobox_inner = $('#tv-infobox-inner');
        var $parent = $(parent);
        $tv_infobox_desc.empty();
        $tv_infobox_image.empty();
        $tv_infobox_inner.hide();


        $infobox.css({
            'height': '0px',
            'width': '0px',
            marginLeft: '0px',
            marginTop: '0px'
        }).animate({
            'height': '270px',
            'width': '600px',
            marginLeft: '-300px',
            marginTop: '-135px'
        }, 200);

        $.getJSON("/tvshowdata/" + id,
            function(data) {
                var content = '<h2>' + data['Name'] + '</h2>';
                if (data['OriginalName']) { content = content + '<h3>' + data['OriginalName'] + '</h3>'; }
                if (date != null) {
                    content = content + '<div class="pad-10-0">' + date + ' | ' + data['ChannelName'] + '</div>' + data['Description'];
                }
                else {
                    content = content + '<div class="pad-10-0">' + data['Date'] + ' | ' + data['ChannelName'] + '</div>' + data['Description'];
                }

                $tv_infobox_desc.html(content);
                if (data['Image']) {
                    $('.tv-infobox-top .tv-infobox-left').css('width', '330px');
                    $('.tv-infobox-top .tv-infobox-right').show();
                    $tv_infobox_image.html('<img src="' + data['Image'] + '" width="210" alt="" />');
                }
                else {
                    $('.tv-infobox-top .tv-infobox-left').css('width', '100%');
                    $('.tv-infobox-top .tv-infobox-right').hide();
                }

                /* hinnangu tähekesed saab sarnaselt siin kohas luua */

                $tv_infobox_inner.show();

            });

        $infobox.show();
    }
    else {
        $infobox.hide();
    }
}

function toggleFullscreen(v, d) {
    if (v == 'h') {
        if ($('#fullview').length > 0) {
            window.location.href = '/index/h/' + d;
        }
        else {
            window.location.href = '/kava/h/' + d;
        }
    }
    else {
        if ($('#fullview').length > 0) {
            window.location.href = '/index/v/' + d;
        }
        else {
            window.location.href = '/kava/v/' + d;
        }
    }
}

function popup_window(url, w, h, scrollbars) {
    wh = 'height=' + h + ', width=' + w + '';
    newwindow = window.open(url, "mywindow", "location=0,status=0,scrollbars=" + scrollbars + ",width=" + w + ",height=" + h);
    if (window.focus) { newwindow.focus() }
    return false;
}

function FlameReport(commentId) {
    question = confirm('Sobimatu kommentaar\n\nKas oled kindel, et see kommentaar on sobimatu ja tuleks eemaldada?')
    if (question != "0") {
        $.post("/flamereport", { Id: commentId });
    }
}