//homeDir ustawiany automatycznie w szablonie
function displayWindow(url, title) {
    title = title || "displayWindow";
    var Win = window.open(url,title,'width=800,height=570,left=0,top=0,resizable=0,scrollbars=yes,menubar=no');
}

function displayWindowzdjecie(url,szerokosc,wysokosc) {
    var scroll = 'no';
    var max = 0.95;
    var screenwidth = screen.width;
    var screenheight = screen.height;
    if(szerokosc>max*screenwidth || wysokosc>max*screenheight)
    {
        scroll = 'yes';
    }

    var okno = window.open(url,"displayWindow",'width=' + szerokosc + ',height='+ wysokosc +',left=20,top=20,resizable=0,scrollbars='+ scroll +',menubar=no');
    okno.focus();
}

function autoWindow(url, width, height) {
    var params = 'resizable=1,scrollbars=yes,menubar=no'; //,menubar=1,toolbar=1';
    params += ',width=' + (typeof width != 'undefined' && width > 0 ? width : 800);
    params += ',height=' + (typeof height != 'undefined' && height > 0 ? height : 600);
    var win = window.open(url, "autoWindow", params);
    win.focus();
}

function displayWindow2(url) {
    var Win = window.open(url,"displayWindow",'width=600,height=620,left=20,top=20,resizable=1,scrollbars=yes,menubar=no');
}

function showWindow(url, title, width, height) {
    if (width == 0) {
        width = 300;
    }
    if (height == 0) {
        height = 300;
    }
    var left = (screen.width - width) / 2;
    var top = (screen.height - height) / 2;
    params = 'width=' + width + ',height=' + height + ',left=' + left + ',top=' + top;
    params += ',resizable=0,scrollbars=no,menubar=no';  
    var win = window.open(url, "displayWindow", params);
    $.post('/_ajax/show_window_notify.php', {
        url: url
    });
}

function openMap(url) {
    var mapWin = window.open(url,"mapWindow",'width=1200,height=750,left=0,top=0,resizable=1,scrollbars=0,menubar=no');
    mapWin.focus();
}
      
function zapal_gwiazdki(ile)
{
    for (i=1;i<=5;i++)
    {
        if (i<=ile)
            document.getElementById('ocena'+i).src='/_img/star_on.gif';
        else
            document.getElementById('ocena'+i).src='/_img/star_off.gif';
    }
}

function ocen_zdjecie_ngaleria(id_zdj,typ)
{

    $.getJSON("/_ajax/galeria/vote.php", {
        "id_zdj": id_zdj,
        "type": typ
    }, function(json)

    {
        if(json.answer == 1)
        {
            $(".result_plus").html('+'+json.plus);
            $(".result_minus").html('-'+json.minus);
        }
        else if(json.answer == 2)
        {
            alert('już głosowałe¶ na to zdjęcie!');
        }

    });

    return false;
}

function przewin_kalendarz(miesiac,rok,serwis)
{
    $.ajax({
        url: "/_ajax/kalendarz.php",
        data: {
            'miesiac': miesiac,
            'rok': rok,
            'serwis' : serwis
        },
        success: function(data){
            $('#kalendarz').html(data);
        }
    });
}

function laduj_kategorie_katalog(dzial, wybrana)
{
    var cat_select = $('#kat_select');
    $.ajax({
        url : '/_ajax/kategorie_katalog.php',
        data : {
            "section" : dzial,
            "req_cat" : wybrana   
        },
        beforeSend : function(){
            cat_select.attr('disabled', 'disabled');
            cat_select.css('cursor' , 'wait');
        },
        success : function(data, textStatus, jqXHR){
            $('#kategorie_katalog').html(data);
        },
        complete : function(){
            cat_select.removeAttr('disabled');
            cat_select.css('cursor' , 'default');
        }
    });
}

function zmien_zakladke(dzial)
{
    switch (dzial)
    {
        case 'news':
            advAJAX.get({
                url:/_ajax/+"zakladki.php?tab=1",
                onSuccess:function(obj) {
                    document.getElementById('glowne-zakladki').innerHTML=obj.responseText;
                }
            });
            //0,02 dnia = okolo 30m
            createCookie('indexTab',1,'0.02');
            break;

        case 'imprezy':
            advAJAX.get({
                url:/_ajax/+"zakladki.php?tab=2",
                onSuccess:function(obj) {
                    document.getElementById('glowne-zakladki').innerHTML=obj.responseText;
                }
            });
            createCookie('indexTab',2,'0.02');
            break;
  
        case 'nieruchomosci':
            advAJAX.get({
                url:/_ajax/+"zakladki.php?tab=3",
                onSuccess:function(obj) {
                    document.getElementById('glowne-zakladki').innerHTML=obj.responseText;
                }
            });
            createCookie('indexTab',3,'0.02');
            break;

        case 'foto':
            advAJAX.get({
                url:/_ajax/+"zakladki.php?tab=4",
                onSuccess:function(obj) {
                    document.getElementById('glowne-zakladki').innerHTML=obj.responseText;
                }
            });
            createCookie('indexTab',4,'0.02');
            break;
  
        case 'skrzydla':
        case 'wybory':
            advAJAX.get({
                url:/_ajax/+"zakladki.php?tab=5",
                onSuccess:function(obj) {
                    document.getElementById('glowne-zakladki').innerHTML=obj.responseText;
                }
            });
            createCookie('indexTab',5,'0.02');
            break;  
  
    }
}

function zmien_zakladke_po_indeksie(indeks) {
    advAJAX.get({
        url:/_ajax/+"zakladki.php?tab=" + indeks,
        onSuccess:function(obj) {
            document.getElementById('glowne-zakladki').innerHTML=obj.responseText;
        }
    });
}

function switch_tab(tab, page) {
    $.ajax({
        url: 'zakladki.php',
        data : {
            "tab" : tab
        },
        beforeSend : function(){
            $('#zakladki').css('cursor','wait');
        },
        success : function(data, textStatus, jqXHR){
            $('#zakladki').html(data);
        },
        complete : function(){
            $('#zakladki').css('cursor','default'); 
        }
        
    });
    createCookie(page + 'Tab', tab,'0.02');
}

//rozszerzona wersja - dla stron z wieksza iloscia zakladek
function switch_tab_plus(tab, page, script){

    var cookieTime = '0.02';
    $.ajax({
        url: '/_ajax/'+script+'.php',
        data : {
            "tab" : tab
        },
        beforeSend : function(){
            $('#'+script).css('cursor','wait');
        },
        success : function(data, textStatus, jqXHR){
            $('#'+script).html(data);
        },
        complete : function(){
            $('#'+script).css('cursor','default'); 
        }
        
    });
  
    if(page=='pogoda')
    {
        cookieTime = '30';  
    }
    createCookie(page + 'Tab', tab, cookieTime);
}


// Inicjacja formularzy wyszukiwania
function ajax_assign_form(form_id, container_id) {
    var container = document.getElementById(container_id);
    var form = document.getElementById(form_id);
    advAJAX.assign(form, {
        onSuccess : function(obj) {
            container.innerHTML = obj.responseText;
            if (form.getAttribute('reinit')) {
                ajax_assign_form(form_id, container_id);
            }
        }
    });
}
 
function init_forms() {
    var form;
    var container;
    for (i = 0; i < document.forms.length; i++) {
        form = document.forms[i];
        container = form.getAttribute('container');
        if (document.getElementById(container) != null) {
            ajax_assign_form(form.id, container);
        }
    }
}

function get_content(container_id, script, params) {
    var container = $('#'+container_id);
    $.ajax({
        url: script,
        data : params,
        beforeSend : function(){
            container.css('cursor','wait');
        },
        success : function(data, textStatus, jqXHR){
            container.html(data);
        },
        complete : function(){
            container.css('cursor','default'); 
        }
    });
} 

function close_info() {
    document.getElementById('info').style.visibility = "hidden";
}

function printWindow()  {
    print();	
}

function printDocument(url, szerokosc, wysokosc)  {
    newPopup = window.open(url, "PrintPage",'left=20,top=20,resizable=1,scrollbars=yes,menubar=yes');
    try {
        newPopup.focus();
        newPopup.setTimeout("print()", 2000);
    }
    catch (e) {}
    $.post('/_ajax/show_window_notify.php', {
        url: url
    });
}        
        
function moderacja(id,source) {
    if (source=='forum')
        confirm_text = 'Uważam, że ten post nie powinien się tu wy¶wietlać';
    else
        confirm_text = 'Uważam, że ta opinia nie powinna się tu pojawiać';

    if (confirm(confirm_text)) {
  
        $.get("/_ajax/do_moderacji.php?id_opinie="+id+"&source="+source, {},
            function(return_data)
            {
                alert(return_data);
            },'text');
    } 
}

function moderacja_imp(id) {
    if (confirm('Uważam, że ta opinia nie powinna się tu pojawiać')) {
        $.get(homeDir+"/do_moderacji_imp.php?id_opinie="+id,function(){});
    }
}     

/**
 * funkcja oceny opinii w newsach
 */
function opinionShift(id, val) {
    var targetId = (parseInt(val) == 1 ? "shiftUp" : "shiftDown") + id;
    var target = document.getElementById(targetId);
    try {
        target.onclick = '';
        setTimeout(function() {
            target.onclick = function() {
                opinionShift(id, val);
            };
        }, 3000);
    }
    catch (e) {}

    $.ajax({
        type: "GET",
        url: "/_ajax/opinion_shift.php",
        data: {
            id_opinie: id,
            val: val
        },
        success: opinionShiftCallback
    });
}

/**
 * funkcja oceny opinii w systemie forum
 */
function requestVote(id, vote) {
    $.ajax({
        type: "POST",
        url: "/_ajax/post_endorsement.php",
        data: {
            id: id,
            vote: vote
        },
        success: opinionShiftCallback
    });
}

function opinionShiftCallback(response) {
    var options = response.split('|');
    try {
        var optionID = options[0];
        var msgCont = document.getElementById('vmsg' + optionID);
        if (options[1]) {
            msgCont.innerHTML = options[1];
            msgCont.style.visibility = 'visible';
        }
        if (options[2]) {
            var votes = options[2].split(':');
            if (votes[0] > 0 || votes[1] > 0) {
                document.getElementById('vplus' + optionID).innerHTML = votes[0];
                document.getElementById('vminus' + optionID).innerHTML = votes[1];
            }
        }
    }
    catch (e) {
    }
}

function toggle_visibility(element)
{
    var container;
    container = document.getElementById(element);
    if (container.style.visibility == 'visible')
    {
        show(element, '');
    }
    else
    {
        show('', element);
    }

}

function show_top_movies(class_name, id)
{
    $('.'+class_name).hide();
    $('#'+id).show();
}

function show(ukryj, pokaz, param)
{
    if (!param) param = "block";
    var tab_ukryj = (ukryj) ? ukryj.split(",") : new Array();
    var tab_pokaz = (pokaz) ? pokaz.split(",") : new Array();
    var container;
  
    for (i = 0; i < tab_ukryj.length; i++)
    {
        container = document.getElementById(tab_ukryj[i]);
        if (undefined != container) {
            container.style.visibility = "hidden";
            container.style.display = "none";
        }
    }
    for (i = 0; i < tab_pokaz.length; i++)
    {
        container = document.getElementById(tab_pokaz[i]);
        if (undefined != container) {
            container.style.visibility = "visible";
            container.style.display = param;
        }
    }
}

function show_zdjecia(pokaz)
{		
    document.getElementById(pokaz).style.visibility="visible";
    document.getElementById(pokaz).style.display="block";	     
}

function hide_zdjecia(pokaz)
{		
    document.getElementById(pokaz).style.visibility="hidden";
    document.getElementById(pokaz).style.display="none";	     
}
/**
 *funkcja unifikujaca 2 ponizej
 */
function questionaire_ajax(form, id_box)
{
    var radio_buttons = form.l.length; 
    var is_radio = 0;
    
    for (i=0; i< radio_buttons; i++){
        if (form.l[i].checked){
            is_radio=1;	 
        } 
    }
     
    if (is_radio == 0){
        alert("Wybierz opcję!"); 
    }
    else { 
        $.ajax({
            url : $(form).attr('action'),
            type : $(form).attr('method'),
            data : $(form).serialize(),
            success : function(data, textStatus, jqXHR){
                $('#'+id_box).html(data)
            }
        });
    }
    return false; 
}
/**
 *Ankiety w calym serwisie
 */
function ankieta_ajax(form) {	
    questionaire_ajax(form,'ankieta_news'); 
}

/**
 *Ankiety w serwisie wborczym
 */
function ankieta_ajax_wybory(form, id_box) {	
    questionaire_ajax(form, id_box);
}

function przewinDo (name)
{    
    var obj=document.getElementById(name);       	
    var offset=getposOffset(obj,"top");
   
    scrollTo(0,offset)
    
}
 
function getposOffset(what, offsettype) { 
	
    var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
    var parentEl=what.offsetParent;
    while (parentEl!=null){
        totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;	
        parentEl=parentEl.offsetParent;
    }
    return totaloffset;
} 

function changeNewsFont(size)
{
    if (size=="big")
    {
        document.getElementById("article-content").className="content-big";
        document.getElementById("font_big").style.visibility="visible";
        document.getElementById("font_big").style.display="inline";
        document.getElementById("font_small").style.visibility="hidden";
        document.getElementById("font_small").style.display="none";
    }
    else
    {
        document.getElementById("article-content").className="content-small";
        document.getElementById("font_big").style.visibility="hidden";
        document.getElementById("font_big").style.display="none";
        document.getElementById("font_small").style.visibility="visible";
        document.getElementById("font_small").style.display="inline";
    }
    createCookie('newsFontSize',size,360);
}

 
function createCookie(name,value,days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    }
    else {
        expires = "";
    }
    if(name=='pogodaTab')
    {
        document.cookie = name+"="+value+expires+"; path=/; domain=trojmiasto.pl";
    }
    else
    {
        document.cookie = name+"="+value+expires+"; path=/; domain=.trojmiasto.pl";
    }
}

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 eraseCookie(name) {
    createCookie(name,"",-1);
}

function okno_relacja(url, id) 
{
    url = "http://www.trojmiasto.pl/live/"+url;
    var Win = window.open(url,"displayWindow"+id,"width=792,height=600,left=40,top=30,resizable=0,scrollbars=yes,menubar=no");
} 

function shiftfoto(typ,podtyp,pozycja,laczenie)
{
    advAJAX.get({
        url:/_ajax/+"fotoshift.php?typ="+typ+"&podtyp="+podtyp+"&pozycja="+pozycja+"&laczenie="+laczenie,
        onSuccess:function(obj) {
            document.getElementById('fotoshift').innerHTML=obj.responseText;
        }
    });
}

function shiftfoto_plus(typ, podtyp, pozycja, laczenie, ilosc, tpl)
{
    advAJAX.get({
        url:/_ajax/+"fotoshift.php?typ="+typ+"&podtyp="+podtyp+"&pozycja="+pozycja+"&laczenie="+laczenie+"&ilosc="+ilosc+"&tpl="+tpl,
        onSuccess:function(obj) {
            document.getElementById('fotoshift').innerHTML=obj.responseText;
        }
    });
}

function zlicz_polecamy_gora(id, url)
{
    url = url.replace (/\?/g,"[zap]");
    url = url.replace (/&/g,"[and]");
    url = url.replace (/#/g,"[hash]");
    var Win = window.location="http://www.trojmiasto.pl/zlicz_polecamy.phtml?id="+id+'&noHeader&url=http://'+url;
    
    return false;
}

function zlicz_polecamy(id,nowa_str,url )
{
    url = url.replace (/&/g,"[and]");
    url = url.replace (/#/g,"[hash]");

    if ( nowa_str == 1 )
        var Win = window.open("http://www.trojmiasto.pl/zlicz_polecamy.phtml?url="+url+"&id="+id,"adverisementWindow"); 
    else
        var Win = window.location="http://www.trojmiasto.pl/zlicz_polecamy.phtml?url="+url+"&id="+id  ;  
    
    Win.focus();
}

var currFormContainerId = '';
var gSpell = null;
function showAddOpForm(opinionId, threadId) {
    // inicjacja spell checker'a
    if (gSpell == null) {
        gSpell = new GoogieSpell("/_js/spellchecker/", "/_ajax/sendReq.php?lang=");
    }
    var formContainerId = (opinionId > 0) ? 'aofc' + opinionId 
    : (opinionId == 0) ? 'form_ao' 
    : 'form_ao2';
    var formContainer = document.getElementById(formContainerId);
    if (undefined == formContainer) {
        return false;
    }
    var currFormContainer = document.getElementById(currFormContainerId);
    
    if (formContainerId != currFormContainerId) {
        // wylaczenie z widoku poprzedniego i wlaczenie nowego       
        show(currFormContainerId, formContainerId);        
        
        // deaktywacja spelera
        if (gSpell.state == "resume_editing") {
            gSpell.resumeEditing();
        }

        // wykasowanie dotychczasowego formularza
        if (undefined != currFormContainer) {
            if (currFormContainerId == 'form_ao') {
                currFormContainer.style.display = 'none';
            }
            else {
                currFormContainer.innerHTML = '';
            }
        }
        // ustawienie zmiennych formularza
        document.getElementById('op_parent').value = (opinionId > 0) ? opinionId : 0;
        document.getElementById('op_thread').value = threadId;
        
        // uaktualnienie rejestru
        currFormContainerId = formContainerId;
        // wpisanie formularza w kontener (jezeli odpowiedz na konkretna opinie)
        var setSpellFields = true;
        var spellContentID = 'opis_dodaj';
        var spellContainerID = 'spell_container';
        if (opinionId > 0) {
            formContainer.innerHTML = document.getElementById('form_answer_op').innerHTML;//ansOpForm; //
        }
        else if (opinionId == -1) {
            if(document.getElementById('first'))
            {  
                document.getElementById('first').value = 0;
            }           
	    document.getElementsByName('validation_message').display = 'none';
            formContainer.innerHTML = document.getElementById('form_ao').innerHTML;//addOpForm; //                   
        }
        else {
            if(document.getElementById('first'))
            {  
                document.getElementById('first').value = 1;
            //spellContentID = 'content';
            }         
            setSpellFields = false;
        }

        if (setSpellFields) { 
            spellContentID = 'opis_dodaj_copy';
            spellContainerID = 'spell_container_copy';
            try {
                var descrElems = document.getElementsByName('content');
                if(descrElems.length==0)
                {   
                    descrElems = document.getElementsByName('opis_dodaj');             
                }

                if (descrElems.length > 0) {
                    var currElem = descrElems[descrElems.length - 1];
                    currElem.id = spellContentID;
                    var descrElemRightPos = getLeftPos(currElem) + 450;
                    var formContainerRightPos = getLeftPos(formContainer) + 578;
                    var margin = formContainerRightPos - 20 - descrElemRightPos ;
                    if (margin < 0) {
                        var newWidth = (currElem.clientWidth + margin);
                        currElem.style.width = newWidth + 'px';
                        var titleElems = document.getElementsByName('nazwa_dodaj');
                        if (titleElems.length > 0) {
                            titleElems[titleElems.length - 1].style.width = newWidth + 'px';
                        }
                        if (margin < -100) {
                            margin = Math.round((margin + 100) / 2) - 13;
                            var correctedShortWidth = 0;
                            var authorElems = document.getElementsByName('autor_dodaj');
                            if (authorElems.length > 0) {
                                correctedShortWidth = authorElems[authorElems.length - 1].clientWidth + margin;
                                authorElems[authorElems.length - 1].style.width = correctedShortWidth + 'px';
                            }
                            var emailElems = document.getElementsByName('email_dodaj');
                            if (emailElems.length > 0) {
                                correctedShortWidth = emailElems[emailElems.length - 1].clientWidth + margin;
                                emailElems[emailElems.length - 1].style.width = correctedShortWidth + 'px';
                            }
                        }
                    }
                }
                
                var spellContainers = document.getElementsByName('spell_container');
                if (spellContainers.length > 0) {
                    var currCont = spellContainers[spellContainers.length - 1];
                    currCont.id = spellContainerID;
                    if (margin < 0) {
                        var spellTables = document.getElementsByName('spell_table');
                        if (spellTables.length > 0) {
                            spellTables[spellTables.length - 1].style.width = newWidth + 'px';
                        }
                    //currCont.style.left = margin + 'px';
                    }
                }
            }
            catch (e) {
            //alert("Wyjatek '" + e.name + "': " + e.message);
            }
        }
        gSpell.setSpellContainer(spellContainerID);
        gSpell.decorateTextarea(spellContentID);
        //formContainer.scrollIntoView(true);
        return true;
    }
    else {
        if (currFormContainer.style.display == 'none') {
            // ponowne pokazanie formularza
            show('', currFormContainerId);
        }
        else {
            // schowanie formularza
            show(currFormContainerId, '');
        }
    }
    return false;
}

var addOpFormSubmitted = false;
function addOpFormSubmit(formElem)
{
    if (!addOpFormSubmitted) {
        try {
            formElem.submit();
            addOpFormSubmitted = true;
            return true;
        }
        catch(e) {
            return false;
        }
    }
    return false;
}

function openRankFormWindow(url) {
    var winWidth = 630;
    var offsetX = (screen.width - winWidth) / 2;
    var offsetY = 5;
    var params = 'width=600px, height=100px, ';
    params += 'left=' + offsetX + 'px, screenX=' + offsetX + 'px, ';
    params += 'top=' + offsetY + 'px, screenY=' + offsetY + 'px, ';
    params += 'location=no, menubar=no, resizable=yes, scrollbars=yes, ';
    params += 'status=no, toolbar=no';
    var newWin = window.open(url, 'trojmiasto', params);
    newWin.focus();
    return newWin;
}

function getLeftPos(elem) {
    var retValue = elem.offsetLeft;
    while((elem = elem.offsetParent) != null) {
        retValue += elem.offsetLeft;
    }
    return retValue;
}


function note_imp(id_imp, ocena, typ, info)
{
    $.ajax({
        type : 'POST',
        url: '/_ajax/ocena.php',
        data : {
            "id_imp" : id_imp,
            "ocena" : ocena,
            "typ" : typ
        },
        beforeSend : function(){
            $('#'+typ+'_box_'+id_imp).css('cursor','wait');
        },
        success : function(data, textStatus, jqXHR){
            if(info == undefined || info == 1){
                $('#'+typ+'_box_'+id_imp).html(data);
            }
        },
        complete : function(){
            $('#'+typ+'_box_'+id_imp).css('cursor','default'); 
        }
    });
}

function search_csl(string, type, params)
{

    if(string.length < 1) {
        return false;
    }
    string = form_type_encode(string);
    var link = homeDir + '/s/' + string + '/';
    
    if(type != undefined) {
        var get_values,search_type;
        //a - wyszukaj tylko w wybranych
        //d - wyszukaj we wszystkich z wyjatkiem
        search_type = (type == 'add') ? 'a' : 'd';

        get_values = '?'+search_type+'='+params;
        link = link+get_values;
    }    
    
    location.href = link;
    return false;
}

function form_type_encode(s)
{
    s = s.replace(/^\s+|\s+$/g, '');

    s = str_replace('&', '%26', s);
    s = str_replace("'", '%27', s);
    s = str_replace(' ', '+', s);
    s = str_replace('"', '%22', s);
    s = str_replace('?', '%3F', s);

    s = str_replace('±', '%B1', s);
    s = str_replace('ˇ', '%A1', s);

    s = str_replace('ć', '%E6', s);
    s = str_replace('Ć', '%C6', s);

    s = str_replace('ę', '%EA', s);
    s = str_replace('Ę', '%CA', s);

    s = str_replace('ó', '%F3', s);
    s = str_replace('Ó', '%D3', s);
    
    s = str_replace('¶', '%B6', s);
    s = str_replace('¦', '%A6', s);

    s = str_replace('ł', '%B3', s);
    s = str_replace('Ł', '%A3', s);

    s = str_replace('ż', '%BF', s);
    s = str_replace('Ż', '%AF', s);

    s = str_replace('Ľ', '%BC', s);
    s = str_replace('¬', '%AC', s);

    s = str_replace('ń', '%F1', s);
    s = str_replace('Ń', '%D1', s);

    return s;
}

function url_encode(s)
{
    s = str_replace(' ', '[1]', s);
    s = str_replace('-','[2]',s);
    s = str_replace('_','[3]',s);

    s = str_replace('[1]', '-', s);
    s = str_replace('[2]', '_', s);
    s = str_replace('[3]', '(_)', s);
    
    return s;
}

function url_decode(s)
{
    s = str_replace('_','[1]',s);
    s = str_replace('-', '[2]', s);
    s = str_replace('(_)', '[3]', s);

    s = str_replace('[1]', '-', s);
    s = str_replace('[2]', ' ', s);
    s = str_replace('[3]', '_', s);
    
    return s;
}

function str_replace(search, replace, subject, count)
{
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;
            }
        }
    }
    return sa ? s : s[0];
}

function get_polish_date(year, month, day)
{
    var date = new Date(year, month-1, day, 23, 59, 59, 999);
    var day = date.getDate();
    if (day < 10) {
        day = '0' + day;
    }
    var month = date.getMonth() + 1;
    if (month < 10) {
        month = '0' + month;
    }
    var polish_date = day + '.' + month + '.' + date.getFullYear();
    return polish_date;
}

function get_today()
{
    var date = new Date();
    return get_polish_date(date.getFullYear(), date.getMonth() + 1, date.getDate());
}

function get_weekend()
{
    var date = new Date();
    var day = date.getDay();
    if (day == 0) {
        day = 7;
    }
    var diff_start = day < 5 ? 5 - day : 0; 
    var diff_end = 7 - day;
    var week_start = get_polish_date(date.getFullYear(), date.getMonth() + 1, date.getDate() + diff_start);
    var week_end = (diff_end > 0) ? get_polish_date(date.getFullYear(), date.getMonth() + 1, date.getDate() + diff_end) : week_start;
    return [week_start, week_end];
}

var included_files = null;
function init_included_files() {
    if (included_files === null) {
        included_files = new Array();
        var script_nodes = document.getElementsByTagName('script');
        var base_name = '';
        for (var i = 0; i < script_nodes.length; i++) {
            if (script_nodes[i].src != 'uundefined' && script_nodes[i].src != '') {
                base_name = script_nodes[i].src.match(/\/_js\/[a-z0-9\._]+/);
                if (base_name) {
                    included_files.push(base_name);
                }
            }
        }
    }
}

/**
 * funkcja na wzor php, do dynamicznego ladowania potrzebnych skryptow
 * laduje skrypt tylko raz
 */
function include_once(script, callback) {
    // inicjacja listy includow
    if (included_files === null) {
        init_included_files();
    }
    if (script && included_files.indexOf(script) == -1) {
        included_files.push(script);
        include_dom(script, callback);
    }
}

function include_dom(script, callback) {
    var node;
    var type = script.substring(script.lastIndexOf('.') + 1);
    script += (script.lastIndexOf('?') == -1 ? '?' : '&') + 'rand=' + Math.random();
    switch (type) {
        case 'css' : // arkusz CSS
            node = document.createElement('link');
            node.rel = 'stylesheet';
            node.type = 'text/css';
            node.href = script;
            break;
        default : // domyslnie traktujemy script jako JS
            node = document.createElement('script');
            node.language = 'javascript';
            node.type = 'text/javascript';
            node.src = script;
    }
    var head = document.getElementsByTagName('head').item(0);
    head.appendChild(node);
    if (typeof callback == 'function') {
        node.onload = function () {
            eval(callback);
        }
    }
    return false;
}

if (typeof Array.prototype.indexOf != 'function') {
    Array.prototype.indexOf = function(value) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == value) {
                return i;
            }
        }
        return -1;
    }
}

//zasady musza byc identyczne jak Mail::validate_pl()
function mail_validate_pl(address) 
{
    var reg = /^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z-ęó±¶łżĽćńĘÓˇ¦ŁŻ¬ĆŃ]+\.)+[a-zA-Z]{2,6}$/;
    return reg.test(address);
}

function expandPlayer(id,h)
{
    var height = parseInt($('#'+id).height()) + h;
    $('#'+id).height(height+'px');
}

function collapsePlayer(id,h)
{
    var height = parseInt($('#'+id).height()) - h;
    $('#'+id).height(height+'px');
}
