// tłumaczenia
var lang = {
    en: {
        read_more: 'Read more:',
        page_number: 'Page: ',
        page_from: ' from ',
        bad_search_criteria: 'No press releases found.',
        bad_search_criteria2: 'No press releases found.',
        checkAgree: 'Please check agreement field',
        fillRequiredFields: 'Please fill in required fields',
        next_page: 'next',
        back_page: 'previous',
        moreText: 'more',
        search_result: 'Search results'
    },
    pl: {
        read_more: 'Czytaj więcej:',
        page_number: 'Strona: ',
        page_from: ' z ',
        bad_search_criteria: 'Brak komunikatów spełniających kryteria wyszukiwania.',
        bad_search_criteria2: 'Brak notatek lokalnych spełniających wybrane kryteria.',
        checkAgree: 'Zgoda na przetwarzanie danych osobowych jest wymagana',
        fillRequiredFields: 'Proszę wypełnić wymagane pola',
        next_page: 'następna',
        back_page: 'poprzednia',
        moreText: 'więcej',
        search_result: 'Wyniki wyszukiwania'
    }
};

//equalize cols + center logo
function equalizeEntryCols() {

    function centerLogo(logo) {
        var logoH = logo.height(), logoW = logo.width();

        logo.css({
            color: "pink",
            left: "50%",
            margin: "-"+logoH/2+"px 0 0 -"+logoW/2+"px"
        });
    }

    $("#mainList .entry").each(function(){
        var  H=0, h,
        me = $(this),
        cols = me.find(".entryCol"),
        logo = me.find(".entryBranding img");

        if(logo.height()>1) {
            centerLogo(logo);
        } else {
            logo.one("load",function(e){
                centerLogo($(e.currentTarget));
            });
        }

        //teaser.height(lead.height());

        cols.each(function(i){
            h = cols.eq(i).height();
            if (h>H){
                H=h;
            }
        });
        cols.height(H);

    });
}

function attachVideoPlayer() {
    var width = 512;
    var ratio = 16/9;
    var height = width/ratio + 33;

    $('body').append(['<div class="videoPlayer" style="text-align: center;"><div style="position: relative; width: ', width,
        '; height:', height + 80, 'px;"><div style="width: ', width, 'px; margin: 0 auto 6px auto; text-align: left; position: relative; z-index: 99999; color: #909090; font: bold 18px Arial">',
        $(this).attr('title'), '</div><div class="videoContainer" style="position: relative; z-index: 999"></div></div></div>'].join(''));

    $('.videoPlayer').jOverlay({
        color: '#000',
        opacity: 0.75
    });

    $('.videoPlayer .videoContainer').flash({
        allowfullscreen: true,
        allowscriptaccess: 'always',
        height: height,
        flashvars: {
            config: '/flash/player/flashvars.xml',
            file: $(this).attr('href')
        },
        src: '/flash/player/player.swf',
        width: width
    }, {
        version: '10.0.0'
    });

    return false;
}

function trackReleaseClick() {
    if (this.href.match(/\/generic\//)) {
        return;
    }
    
    var match = this.href.match(/\/pr\/([0-9]+)\/(.*)/);
    if (match) {
        _gaq.push(['_trackEvent', 'Release', 'Click', match[1] + ': ' + match[2], 0, true]);
    }
}

$(document).ready(function() {
    equalizeEntryCols();

    $('.entryTeaser a').click(attachVideoPlayer);
    $('#mainList .entry h2 a, #mainList .entry .readon a').click(trackReleaseClick);

    //porusz zielony guzik
    $("#public-relations").hover(function(){
        $(this).animate({
            top: "0"
        },150);
    },function(){
        $(this).animate({
            top: "-5px"
        },150);
    });
});

$(window).load(function(){
    //*
    // prześlij do znajomego, digg, gwar
    $(".przeslij-icon").after("<div class='send-pop'><ul><li><span class='share-icon'><a href='#'>Prześlij znajomemu</a></span></li><li><span class='digg-icon'><a href='#'>Dodaj do Digg</a></span></li><li><span class='gwar-icon'><a href='#'>Dodaj do Gwar</a></span></li></ul></div>");

    $(".send").mouseover(function() {
        $(this).addClass('send-over');
    }).mouseout(function() {
        $(this).removeClass('send-over');
    });
    // */

    //*
    // kasuje margines ostatniego paragrafu
    $("div.content p:last-child").css({
        margin:"0"
    });
    $("div.content .entry:last-child").css({
        margin:"0"
    });
    $(".shortList li:last-child").css({
        background:"none"
    });
    // */

    //*
    // funkcja slide+fade
    jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
        return this.animate({
            opacity: 0.9,
            height: 'toggle'
        }, speed, easing, callback);
    };

    $('div.whyRegister').hide();

    $('h2.whyRegister').click(function() {
        $('div.whyRegister').slideFadeToggle('slow');
    });
    // */

    //*
    // zamykanie dolnej zajawki
    $('#overlay .close').click(function() {
        $('#overlay').slideFadeToggle('slow');
    });

    $('#overlay .closeDestroy').click(function() {
        $('#overlay').slideFadeToggle('slow', function () {
            $(this).remove();
        });
    });
    // */

    //*
    // wrap do buttonów
    $('#registrationSecondStep_press_registration_button_save, #registrationSecondStep_press_registration_button_submit, #passwdRemaind_remaind_password_form_send').wrap("<div class='inputBtn'></div>");

    $(".inputBtn input").mouseover(function() {
        $(this).parent().addClass('overBtn');
    }).mouseout(function() {
        $(this).parent().removeClass('overBtn');
    });

    $(".inputBtn").parent().addClass('spaced');
    // */

    $("#registrationSecondStep_press_zwrot").after($("#imgregistrationSecondStep_press_zwrotOk, #imgregistrationSecondStep_press_zwrotNo"));
    $("#registrationSecondStep_press_imie").after($("#imgregistrationSecondStep_press_imieOk, #imgregistrationSecondStep_press_imieNo"));
    $("#registrationSecondStep_press_nazwisko").after($("#imgregistrationSecondStep_press_nazwiskoOk, #imgregistrationSecondStep_press_nazwiskoNo"));
    $("#registrationSecondStep_press_mail").after($("#imgregistrationSecondStep_press_mailOk, #imgregistrationSecondStep_press_mailNo"));
    $("#registrationSecondStep_press_jezyk").after($("#imgregistrationSecondStep_press_jezykOk, #imgregistrationSecondStep_press_jezykNo"));
    $("#registrationSecondStep_press_krajUzytkownika").after($("#imgregistrationSecondStep_press_krajUzytkownikaOk, #imgregistrationSecondStep_press_krajUzytkownikaNo"));
    $("#registrationSecondStep_press_typUzytkownika").after($("#imgregistrationSecondStep_press_typUzytkownikaOk, #imgregistrationSecondStep_press_typUzytkownikaNo"));
    $("#changeUserData tr td:even").addClass("firstCol");
    $(".validOrNot").remove();
// */

});

function trim(str) {
    return str.replace(/^\W+/, '').replace(/\W+$/, '');
}

function checkForm(formName, fieldNames, prompts) {
    var fieldArray = fieldNames.split(":");
    var promptArray = prompts.split(":");
    var i = 0;
    for (i = 0; i < fieldArray.length; i++) {
        if (trim(document.forms[formName][fieldArray[i]].value) === '') {
            alert(promptArray[i]);
            document.forms[formName][fieldArray[i]].focus();
            return false;
        }
    }
    return true;
}

function renderMainNotes(response) {
    var html = [];
    if (response.results) {
        for (var i = 0; i < response.results.length; i++) {
            var node = response.results[i];

            html.push('<div class="entry">');
            html.push('<div class="entryBranding entryCol"><img src="/logo/', node.clientId.clientId, '" title="', node.clientId.firma, '" alt="" /></div>');
            html.push('<div class="entryContent entryCol', (!node.thumbnailForTeaser && !node.video ? ' noTeaser' : '' ), '">');
            html.push('<h2><a href="http://', node.url, '" title="', lang[interface_language].read_more, '">', node.temat, '</a></h2>');
            html.push('<div class="entry-stats"><span class="date-icon">',  node.pubDate.substring(8, 10), '/', node.pubDate.substring(5, 7), '/', node.pubDate.substring(0, 4), '</span> | <span>', node.czas.substring(11, 16), '</span> | <span>', node.clientId.firma, '</span></div>');
            html.push('<div class="entry-data">');

            if (node.video) {
                html.push('<div class="entryTeaser"><a href="http://', node.video, '" title="', node.temat, '"><div class="filePreviewIcon"></div><img src="http://', node.videoThumbnail, '" height="', node.thumbnailHeight, '" width="', node.thumbnailWidth, '" alt=""/></a></div>');
            }
            else if (node.thumbnailForTeaser) {
                html.push('<div class="entryTeaser"><img src="http://', node.thumbnailForTeaser, '" height="', node.thumbnailHeight, '" width="', node.thumbnailWidth, '" alt=""/></div>');
            }

            html.push('<div class="entryLead">');
            html.push('<p>', node.opis, '</p>');
            html.push('<div class="readon"><a href="http://', node.url, '" title="', lang[interface_language].read_more, ': ', node.temat, '"><span class="throwAway">', lang[interface_language].read_more, '</span></a></div>');
            html.push('</div>'); // entryLead

            html.push('<div class="clr"></div>');
            html.push('</div>'); // entry-data
            html.push('</div>'); // entryContent
            html.push('<div class="clr"></div>');
            html.push('</div>'); // entry
        }
    }

    $('#mainList .entry').remove();
    $('#mainList').append(html.join(''));
    $('#mainList .entryTeaser a').click(attachVideoPlayer);
    $('#mainList .entry h2 a, #mainList .entry .readon a').click(trackReleaseClick);
    equalizeEntryCols();
}

function refreshLocalNotesMain(value, page) {
    $('#loading').show();
    $.getJSON('/s2/listRelease.action', {
        county: value,
        limit: 25,
        currentPage: page
    }, function(response) {
        renderMainNotes(response);
        if (response.allPages > 0) {
            var i, nav = ['<span class="page-sum-up">', lang[interface_language].page_number, ' ', page, ' ', lang[interface_language].page_from, response.allPages, '</span> '];
            if (page > 1) {
                nav.push('<a href="#" onclick="refreshLocalNotesMain(', value, ',', page - 1, ');">', lang[interface_language].back_page, '</a>');
            }
            for (i = Math.max(1, page - 2); i < page; i++) {
                nav.push('<a href="#" onclick="refreshLocalNotesMain(', value, ',', i, ');">', i, '</a>');
            }
            nav.push('<span>', page, '</span>');
            for (i = page + 1; i <= Math.min(response.allPages, page + 2); i++) {
                nav.push('<a href="#" onclick="refreshLocalNotesMain(', value, ',', i, ');">', i, '</a>');
            }
            if (page < response.allPages) {
                nav.push('<a href="#" onclick="refreshLocalNotesMain(', value, ',', page + 1, ');">', lang[interface_language].next_page, '</a>');
            }
            $('#navigation').html(nav.join(''));
        }
        else {
            $('#navigation').html(lang[interface_language].bad_search_criteria);
        }

        $('#loading').hide();
    });
}

var timer, searchOptions;
function search() {
    if (timer) {
        clearTimeout(timer);
    }

    var form = $('#searchForm')[0];
    searchOptions = {
        limit: 25,
        searchText: form.searchText.value,
        lang: form.lang.value
    };

    timer = setTimeout("searchReleases(1)", 1000);
}

function searchReleases(page) {
    searchOptions.currentPage = page || 1;

    $('#loading').show();
    $.getJSON('/s2/listRelease.action', searchOptions, function(response) {
        $('div.menu li').removeClass('on');
        var list = $('#column-wrap .content h1');
        if (list.length) {
            list[0].innerHTML = lang[interface_language].search_result;
        }

        renderMainNotes(response);
        if (response.allPages > 0) {
            var i, nav = ['<span class="page-sum-up">', lang[interface_language].page_number, ' ', page, ' ', lang[interface_language].page_from, response.allPages, '</span> '];
            if (page > 1) {
                nav.push('<a href="#" onclick="searchReleases(', page - 1, ');">', lang[interface_language].back_page, '</a>');
            }
            for (i = Math.max(1, page - 2); i < page; i++) {
                nav.push('<a href="#" onclick="searchReleases(', i, ');">', i, '</a>');
            }
            nav.push('<span>', page, '</span>');
            for (i = page + 1; i <= Math.min(response.allPages, page + 2); i++) {
                nav.push('<a href="#" onclick="searchReleases(', i, ');">', i, '</a>');
            }
            if (page < response.allPages) {
                nav.push('<a href="#" onclick="searchReleases(', page + 1, ');">', lang[interface_language].next_page, '</a>');
            }
            $('#navigation').html(nav.join(''));
        }
        else {
            $('#navigation').html(lang[interface_language].bad_search_criteria);
        }

        $('#loading').hide();
    });
}

function refreshLocalNotesSide(selected) {
    $.getJSON('/s2/listRelease.action', {
        county: selected,
        lang: '',
        limit: 10,
        offset: 0
    }, localRenderer);
}

function refreshLocalNotesSideGeneric(selected) {
    $.getJSON('localReleases.action', {
        county: selected,
        onlyLocalReleases:true,
        lang: '',
        limit: 20,
        offset: 0
    }, function(resp) {
        localRenderer(resp, true)
    });
}

function localRenderer(response, noDomain) {
    if (response.success !== true) {
        alert(response.message || 'Wystąpił problem z zapytaniem.');
        return;
    }

    var html = ['<ul class="shortList">'];
    if (response.results) {
        for (var i = 0; i < response.results.length; i++) {
            var node = response.results[i];
            html.push('<li>');
            html.push('<div class="time">', node.pubDate.substring(8, 10), '/', node.pubDate.substring(5, 7), ' | ', node.czas.substring(11, 16), '</div>');
            html.push('<div><a href="', noDomain === true ? '' : 'http://', node.url, '.html" title="', lang[interface_language].read_more, ': ', node.temat, '">', node.temat, '</a></div>');
            html.push('</li>');
        }
    }
    html.push('</ul>');

    if (response.results.length === 0) {
        html.push(bad_search_criteria2);
    }

    document.getElementById("local_info").innerHTML = html.join('');

    var countyId = selected == 0 ? -1 : selected;
    var el = document.getElementById("readMore");
    if (response.results.length > 0) {
        var link = el.innerHTML;
        if (link === '') {
            link = '<a href="getPR.po?tc=rss20&amp;enc=UTF&amp;lang=pl&amp;mc=1&amp;county=-1" title="RSS">RSS</a>';
        }
        link = link.split('county=');
        el.innerHTML = link[0] + 'county=' + countyId + '"><span class="throwAway">' + lang[interface_language].moreText + '</span></a>';
    }
    else {
        el.innerHTML = '';
    }

    el = document.getElementById("rss_link");
    link = el.innerHTML
    link = link.split('county=');
    if (!link[1]) {
        link = el.innerHTML;
        link = link.split('" title');
        link[0] += '&amp;';
    }

    el.innerHTML = link[0] + 'county=' + countyId + '"' + ' title="RSS">RSS</a>';
}

function validateNotEmpty(id) {
    var isHidden = $('#' + id)[0].type === 'hidden';
    if( trim( $('#' + id).val() ).length > 0 && $('#' + id).val() !== 0) {
        if (!isHidden) {
            $('#img' + id + 'Ok').show();
            $('#img' + id + 'No').hide();
        }
        return true;
    }
    else {
        if (!isHidden) {
            $('#img' + id + 'No').show();
            $('#img' + id + 'Ok').hide();
        }
        return false;
    }
}

function validateRegisterForm() {

    var ret = validateNotEmpty('registrationSecondStep_press_imie');
    ret = validateNotEmpty('registrationSecondStep_press_nazwisko') && ret;
    ret = validateNotEmpty('registrationSecondStep_press_mail') && ret;

    if (!ret) {
        alert(lang[interface_language].fillRequiredFields);
        return false;
    }

    if (!$('#registrationSecondStep_registration_agree').prop('checked')) {
        alert(lang[interface_language].checkAgree);
        return false;
    }

    return true;
}

