// core functions


var _hash = null;

function handleHash() {
    var hash = window.location.hash;
    _hash = new Array();
    // kazdy browser vracia nieco ine, tak pre istotu odstranim #
    hash = hash.replace('#', '');
    var parts = hash.split('&');
    var key = null;
    var value = null;
    for (var i in parts) {
        try {
            key = parts[i].split('=')[0];
            value = parts[i].split('=')[1];
            _hash[key] = value;
        } catch (e) { };
    }
}

function handleHashAndGo() {
    handleHash();
    switch (_hash['action']) {
        case 'program':
            if (_hash['c'] != undefined) setHash('action=program&c=' + _hash['c'] + '');
            else setHash('action=program');
            handleApp_program();
            break;
        case 'mojenahravky':
            handleApp_mojenahravky();
            break;
        case 'kategorie':
            setHash('action=kategorie&k=' + _hash['k'] + '');
            //handleApp_kategorie();
            getShows(_hash['k']);
            break;
        case 'promo':
            handleApp_promo();
            break;
        case 'vyhladavanie':
            handleApp_vyhladavanie();
            break;
        case 'reset':
            handleApp_reset();
            break;
        default:
            handleApp_promo();
    }
}

// nastavi hash
function setHash(hash, std) {
    var h = '';
    if (typeof (hash) == 'Array') {
        for (var i in hash) {
            if (h != '') h += '&' + i + '=' + hash[i];
            else h += i + '=' + hash[i];
        }
    } else if (typeof (hash) == 'String') {
        h = hash;
    }
    if (std != undefined && std == true) return hash;
    else window.location.hash = hash;
}

// vytvori url
function getFullURI() {

    return window.location.protocol + '//' + window.location.host + ''
        + window.location.pathname;

}

// posledny zobrazeny screen
var _l = null;

// navigacia
function navigation(app) {
    handleHash();
    setHash('action=' + _hash['action']);
    setActiveMenu(app);
    doAction(app);
    return false;
}

// aktivuje polozku menu
function setActiveMenu(app) {
    generateMenu();
    $('#' + app + "-btn").attr('className', app + '-btn-sel');
    if (_l != null) {
        _l.css('display', 'none');
        _l = null;
    }
    //alert("setActiveMenu: _hash['action']: " + _hash['action'] + '; setActiveMenu: app: ' + app);

    if (_hash['action'] != app) {
        handleHash();
        setHash('action=' + app);
    }
}

// vytvori navigacne menu
function generateMenu() {
    $('#navi').empty();
    for (var i in menu) {
        if (menu[i].enabled) var item = '<li id="' + i + '-btn" class="' + i + '-btn"><a href="#action=' + i + '" onclick="' + menu[i].link + '" title="' + menu[i].title + '"></a></li>';
        else var item = '<li id="' + i + '-btn" class="' + i + '-btn"><a href="#action=' + i + '" onclick="' + menu[i].link + '" title="' + menu[i].title + '"></a></li>';
        $('#navi')[0].innerHTML += item;
    }
}

// spracuje akciu z menu
function doAction(app) {
    if (eval('window.handleApp_' + app) != undefined) {
        //alert('doAction: window.handleApp_' + app + '()');
        eval('window.handleApp_' + app + '()');
    }
}

// koniec navigacia

// cookies
function createCookie(name, value, minutes) {
    if (minutes) {
        var date = new Date();
        date.setTime(date.getTime() + (minutes * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


function isLoggedCheck() {
    var user = readCookie('user');
    var mail = readCookie('mail');
    var key = readCookie('key');

    if (user != null && mail != null && key != null) {
        return true;
    } else {
        return false;
    }


}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

// end cookies

// loader

// zobrazenie loader
function showLoader() {
    var arrPageSizes = ___getPageSize();
    var left = (arrPageSizes[0] / 2) - 24 + 'px';
    var top = (arrPageSizes[1] / 2) - 24 + 'px';


    $('#loader-overlay').css({
        backgroundColor: '#000000',
        opacity: 0.20,
        width: arrPageSizes[0],
        height: arrPageSizes[1]
    }).fadeIn('fast');

    $('#loader').css('left', left);
    $('#loader').css('top', top);

}

// skrytie loadera
function hideLoader() {
    $('#loader-overlay').fadeOut('fast');
}

// koniec loader

// vsetky tv
//nastavenie hashu na vsetkyTv button .... volam z fillGenres a getShows
function handleVsetkyTvHref() {
    var hash = window.location.hash;
    hash = hash.replace('#', '');
    $("a.kategorie-channel-picker").attr('href', '#' + hash);
    $("a.kategorie-channel-link").attr('href', '#' + hash);
}

// kalendar
var calendarHolder = null;
var calendarHandler = null;
function generateCalendar(holder, def, handler) {

    if (holder != undefined && calendarData != undefined && $('#calendar-container').length == 0) {
        var today = null;

        $('<div class="cal-cal" id="cal-cal"></div>').appendTo('#' + holder);
        $('<a href="#" class="cal-prev" id="cal-prev"></a>').appendTo('#cal-cal');
        $('<a href="#" class="cal-date" id="cal-date"></a>').appendTo('#cal-cal');
        $('<a href="#" class="cal-next" id="cal-next"></a>').appendTo('#cal-cal');

        $('#cal-prev').hover(
            function () { $(this).css('background-position', '0 -24px'); },
            function () { $(this).css('background-position', '0 0'); }
        );
        $('#cal-date').hover(
            function () { $(this).css('background-position', '0 -24px'); },
            function () { $(this).css('background-position', '0 0'); }
        );
        $('#cal-next').hover(
            function () { $(this).css('background-position', '0 -72px'); },
            function () { $(this).css('background-position', '0 -48px'); }
        );
        $('#cal-date').unbind('click');
        $('#cal-prev').unbind('click');
        $('#cal-next').unbind('click');

        $('#cal-date').click(function () { $("div.cal-table").fadeIn("fast"); return false; });
        $('#cal-prev').click(function () { return setDatePrev(); });
        $('#cal-next').click(function () { return setDateNext(); });

        $('<div class="cal-table" id="calendar-container"></div>').appendTo('#' + holder);
        $('<span class="date" id="calendar-choosen-date"></span>').appendTo('#calendar-container');

        // vygenerujem tabulku s kalendarom
        var table = '<table cellpadding="0" cellspacing="0"><tr>';
        for (var i in calendarData) {
            table += '<td><a href="#" id="d' + i + '" class="' + calendarData[i].css + '" onclick="return setDate(' + i + ');">' + calendarData[i].dix + '</a></td>';
            if (i > 0 && ((parseInt(i) + 1) % 7) == 0) {
                table += '</tr><tr>';
            }
            if (def != undefined && def == calendarData[i].day) today = i;
        }
        table += '</tr></table>';


        $(table).appendTo('#calendar-container');
        if (holder != undefined) {
            if ($('#' + holder + '-date').length == 0) $('<input type="hidden" value="" name="' + holder + '-date" id="' + holder + '-date" />').appendTo('#calendar-container');
            calendarHolder = $('#' + holder + '-date');
        }
        calendarHandler = undefined;
        if (today != null) { calendarHolder.val(calendarData[today].day); setDate(today); };
        $('#calendar-container').unbind('click');
        $('#calendar-container').click(function () { $('#calendar-container').fadeOut("fast"); return false; });
        $('#calendar-container').hide();
        if (handler != undefined) calendarHandler = handler;
    }
}

// nastavim zvoleny datum
var calendarIndex = 0;
function setDate(idx) {
    if (idx != undefined && calendarData[idx] != undefined && calendarData[idx].css != 'inactive' && calendarHolder != null) {
        calendarHolder.val(calendarData[idx].day);
        $('span#calendar-choosen-date').html('<strong>' + calendarData[idx].dnl + '</strong>, ' + calendarData[idx].dix + '. ' + calendarData[idx].mn);
        $('a#cal-date').html('<strong>' + calendarData[idx].dnl + '</strong>, ' + calendarData[idx].dix + '. ' + calendarData[idx].mn);
        $('#calendar-container a').removeClass('selected');
        $('#d' + idx + '').addClass('selected');
        calendarIndex = idx;
        if (calendarHandler != undefined) calendarHandler();
    }
    return false;
}

function setDatePrev() {
    setDate(calendarIndex - 1);
    return false;
}

function setDateNext() {
    setDate(parseInt(calendarIndex) + 1);
    return false;
}
// end kalendar

// vyhladavanie

// inicializacia vyhladavacieho boxu
function searchInitialization() {
    $('#search-input-field').focus(searchFocus);
    $('#search-input-field').blur(searchBlur);
    $('#search-input-field').keyup(searchKeyUp);
    $('#search-input-field').attr('title', msg[24]);
    if ($('#search-input-field').val() == '') $('#search-input-field').val(texts[9]);
}

// vykona sa pri aktivacii textoveho pola
function searchFocus() {
    if ($('#search-input-field').val() == texts[9]) $('#search-input-field').val('');
}

// vykona sa pri deaktivacii textoveho pola
function searchBlur() {
    if ($('#search-input-field').val() == '') $('#search-input-field').val(texts[9]);
}

// vykona sa pri stlaceni klavesy
function searchKeyUp(event) {
    if (event.keyCode == 13) sDoSearch();
}

// natiahnem pri obnoveni stranky
function handleApp_vyhladavanie() {
    //alert('vyhladavanie');
    if (_hash['q'] != undefined) $('#search-input-field').val(unescape(_hash['q']));
    sDoSearch();
}

// odosle hladany vyraz na server
var _searchResult = null;
var _searchPager = 9;
function sDoSearch() {
    var q = $('#search-input-field').val();
    if (q != '' && q != texts[9]) {
        setHash('action=vyhladavanie&q=' + q);
        q = Base64.encode(q);
        var url_main = appBaseHref;
        var url_addon = 'Search/GetResults?q=' + q;
        var url_complete = url_main + url_addon;
        showLoader();
        $.get(url_complete, null, function (data) {
            //alert(data);
            _searchResult = data;
            sShowResults();
            hideLoader();
        }, 'json');
    } else {
        return;
        _searchResult = null;
        sShowResults();
    }
}

// zobrazenie vysledku vyhladavania
function sShowResults(startIndex) {
    $('#search-input-field').val(texts[9]);
    generateMenu();
    $('#app-container').attr('className', 'app-bcg');
    // vycistenie obsahu kontainera app-container
    $('#app-container').empty();
    if ($('#app-container-search').length == 0) {
        $('<div class="app-container-search" id="app-container-search"></div>').appendTo('#app-container');
        $('<div class="search-title" id="search-title"></div>').appendTo('#app-container-search');
        $('<div class="search-notice" id="search-notice"></div>').appendTo('#app-container-search');
        $('<div class="search-results-list" id="search-result"></div>').appendTo('#app-container-search');

        // pager
        $('<div class="search-pager" id="search-pager"></div>').appendTo('#app-container-search');

        $('#vyhladavanie-notice').hide();
    } else {
        $('#app-container-vyhladavanie').css('display', 'block');
    }

    handleHash();
    if (_searchResult != undefined && _searchResult.length > 0) {
        // vykreslim vysledky
        $('#search-result').hide();
        var html = '<ul>';
        // zobrazim vysledky, ale maximalne _searchPager zaznamov na stranku
        if (_hash['p'] != undefined) startIndex = parseInt(_hash['p']);
        if (startIndex == undefined) startIndex = 1;
        //alert(startIndex);
        for (var i = startIndex - 1; i < _searchPager + startIndex - 1; i++) {
            if (_searchResult[i] == undefined) break;
            html += '<li><a href="#action=vyhladavanie&q=' + _hash['q'] + '&s=' + _searchResult[i].ID + '"'
            + ' onclick="return sGetShowDetail(' + _searchResult[i].ID + ');"'
            + ' class="' + _searchResult[i].CLASS + '">'
            + '<span class="search-date">' + _searchResult[i]['DATE'] + '</span>'
            + '<span class="time">' + _searchResult[i]['TIME'] + '</span>'
            + '<span class="title">' + _searchResult[i]['SHORT_TITLE'] + '</span>'
            + '<span class="lenght">' + _searchResult[i]['DURATION'] + ' min</span>'
            + '<span class="channel">' + _searchResult[i]['SHORT_NAME'] + '</span>'
            + '</a></li>';
        }
        html += '</ul>';
        $('#search-result').html(html);
        $('#search-result').show();
        $('#search-notice').hide();
        sGetPager(startIndex);
    } else {
        // vypisem hlasenie, ze sa nic nenaslo
        $('#search-notice').html(msg[23]);
        $('#search-notice').show();
        $('#search-result').hide();
    }
    $('#search-title').html('<strong>' + msg[36] + '</strong> ' + unescape(_hash['q']));
    return false;
}

function sGetShowDetail(id) {
    getShowDetail(id, sCancelShowDetail);
    return true;
}

function sCancelShowDetail() {
    handleHash();
    setHash('action=vyhladavanie&q=' + _hash['q']);
    return false;
}

// zobrazenie strankovania vo vyhladavani
function sGetPager(startIndex) {
    if (_searchResult == undefined || _searchResult.length == 0) $('#search-pager').hide();
    else {
        if ($('#search-pager').length > 0) {
            var stopIndex = 0;
            var prevIndex = 1;
            var nextIndex = 1;
            var itemsCount = _searchResult.length;
            if (startIndex == undefined) startIndex = 1;
            else if (startIndex > itemsCount) startIndex = itemsCount - 1;
            prevIndex = startIndex - _searchPager;
            nextIndex = startIndex + _searchPager;
            if (prevIndex < 1) prevIndex = 1;
            if (nextIndex > itemsCount) {
                nextIndex = startIndex;
                stopIndex = itemsCount;
            } else stopIndex = nextIndex - 1;
            //alert('c: ' + itemsCount + ', s: ' + startIndex + ', p: ' + prevIndex + ', n: ' + nextIndex);
            var html = '<a href="#action=vyhladavanie&q=' + _hash['q'] + '&p=' + prevIndex
               + '" class="pager-prev" id="pager-prev"></a>'
               + '<span class="pager-num"><span><b>' + startIndex + ' - ' + stopIndex
               + '</b> ' + msg[25] + ' ' + itemsCount + '</span></span>'
               + '<a href="#action=vyhladavanie&q=' + _hash['q'] + '&p=' + nextIndex
               + '" class="pager-next" id="pager-next"></a>';
            $('#search-pager').html(html);

            $('a#pager-prev').unbind('click');
            $('a#pager-next').unbind('click');

            $('a#pager-prev').click(function () { return sShowResults(prevIndex); });
            $('a#pager-next').click(function () { return sShowResults(nextIndex); });
        }
    }
}

// end vyhladavanie

// vypisanie prvkov na zadanie datumu a casu
function getDateTimeFields(name, def) {
    if (name == undefined) return '';
    var date = new Date();
    if (def == undefined) def = new Array();
    if (def['day'] == undefined) def['day'] = date.getDate();
    if (def['month'] == undefined) def['month'] = date.getMonth() + 1;
    if (def['year'] == undefined) def['year'] = date.getFullYear();
    if (def['hour'] == undefined) def['hour'] = date.getHours();
    if (def['minute'] == undefined) def['minute'] = date.getMinutes();

    var selected = '';
    var html = '<select name="' + name + '-day" id="' + name + '-day">';
    for (var i = 1; i <= 31; i++) {
        if (i == def['day']) selected = ' selected="selected"';
        else selected = '';
        html += '<option value="' + i + '"' + selected + '>' + ('0' + i).substr(('0' + i).length - 2) + '</option>';
    }
    html += '</select> <select name="' + name + '-month" id="' + name + '-month">';
    for (var i in monthsNames) {
        if (i == def['month']) selected = ' selected="selected"';
        else selected = '';
        html += '<option value="' + (i - 1) + '"' + selected + '>' + monthsNames[i] + '</option>';
    }
    html += '</select> <select name="' + name + '-year" id="' + name + '-year">';
    for (var i = date.getFullYear(); i <= date.getFullYear() + 1; i++) {
        if (i == def['year']) selected = ' selected="selected"';
        else selected = '';
        html += '<option value="' + i + '"' + selected + '>' + i + '</option>';
    }
    html += '</select>&nbsp;&mdash;&nbsp; <select name="' + name + '-hour" id="' + name + '-hour">';
    for (var i = 0; i <= 23; i++) {
        if (i == def['hour']) selected = ' selected="selected"';
        else selected = '';
        html += '<option value="' + i + '"' + selected + '>' + ('0' + i).substr(('0' + i).length - 2) + '</option>';
    }
    html += '</select>: <select name="' + name + '-minute" id="' + name + '-minute">';
    for (var i = 0; i <= 59; i++) {
        if (i == def['minute']) selected = ' selected="selected"';
        else selected = '';
        html += '<option value="' + i + '"' + selected + '>' + ('0' + i).substr(('0' + i).length - 2) + '</option>';
    }
    html += '</select>';

    return html;
}



// ---------------------------------
// dialog
// ---------------------------------

// zobrazenie dialogoveho okna s nejakou informaciou
// Priklad: showDialog('text', meno_funkcie);
var globHideDialogStatus = true;
function showDialog(msg, func) {
    var arrPageSizes = ___getPageSize();
    if ($('#dialog-box').length == 0) {
        $('#app-holder').append('<div class="dialog-box" id="dialog-box">'
            + '<span class="dialog-box-text" id="dialog-box-text"></span>'
            + '<a href="#" class="ok-button" id="dialog-ok-button"></a></div>');
    }
    $('#dialog-overlay').css({
        backgroundColor: '#000000',
        opacity: 0.30,
        width: arrPageSizes[0],
        height: arrPageSizes[1]
    }).fadeIn();
    $('#dialog-box-text').html(msg);
    //$('#dialog-box').css('top', -365);
    $('#dialog-box').fadeIn();
    $('#dialog-ok-button').unbind('click');
    $('#dialog-ok-button').click(function () {
        //alert(globHideDialogStatus);
        if (globHideDialogStatus) hideDialog(func);
        globHideDialogStatus = false;
        return false;
    });
    // If window was resized, calculate the new overlay dimensions
    $(window).resize(function () {
        // Get page sizes
        var arrPageSizes = ___getPageSize();
        // Style overlay and show it
        $('#dialog-overlay').css({
            width: arrPageSizes[0],
            height: arrPageSizes[1]
        });
    });
    globHideDialogStatus = true;
    //alert('skuska');
}

// skyritie dialogoveho okna
function hideDialog(func) {
    $('#dialog-overlay').fadeOut();
    $('#dialog-box').hide();
    if (func != undefined) {
        func();
    }
    //alert('hideDialog');
    return false;
}

function ___getPageSize() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) { // all except Explorer
        if (document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }
    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }
    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
    return arrayPageSize;
}

// ---------------------------------
// koniec dialog
// ---------------------------------

