$(document).ready(function()
{

	function carouselCallback(carousel)
    {
        carousel.buttonNext.bind('click', function() {
            carousel.startAuto(3);
        });

        carousel.buttonPrev.bind('click', function() {
            carousel.startAuto(3);
        });

        carousel.clip.hover(function() {
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });
    };


	$("#offersSlide").jcarousel({
    	auto: 3,
    	scroll: 1,
    	wrap: 'circular',
    	easing: 'easeOutQuart',
    	initCallback: carouselCallback
    });
    
    $("#advRotator").jcarousel({
    	auto: 6,
    	scroll: 1,
    	wrap: 'circular',
    	easing: 'easeInQuart',
    	initCallback: carouselCallback
    });

    $("a.modal:not(.map_sync)").fancybox({
        'titleShow'     : true,
        'titlePosition' : 'inside',
        'transitionIn'	: 'elastic',
        'transitionOut'	: 'elastic',
        'easingIn'      : 'easeOutBack',
        'easingOut'     : 'easeInBack'
	});

	$("a[rel^=advertise_group]").each(function() {
        var title = this.title;
		var picture_data = $(this).parent().siblings('.title:first');
		$(this).fancybox({
			'titleShow'     : true,
			'titlePosition' : 'inside',
		    'titleFormat'   : function(){
                if(picture_data.length!==0) {
                    $(picture_data).find('.original_title').html(title);
                    return picture_data.html();
                }
                return title;
		    },
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			'easingIn'      : 'easeOutBack',
			'easingOut'     : 'easeInBack'
		});
	});

    $("a[rel^=statistics]").each(function() {
        var title = this.title;
		//var picture_data = $(this).parent().siblings('.title:first');
		$(this).fancybox({
			'titleShow'     : true,
			'titlePosition' : 'inside',
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			'easingIn'      : 'easeOutBack',
			'easingOut'     : 'easeInBack'
		});
	});
	
	$(".tab a").click(function(e){
			e.preventDefault();
			$(".pane").hide();
			$(".tab a").removeClass('active');
			$($(this).attr('href')).show('fadeIn');
			$(this).addClass('active');
	});


    if (typeof openlayer_map_init=="function")
        openlayer_map_init();
});

$.datepicker.regional['pl'] = {
closeText: 'Zamknij',
prevText: '&#x3c;Poprzedni',
nextText: 'Następny&#x3e;',
currentText: 'Dziś',
monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec',
'Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
monthNamesShort: ['Sty','Lu','Mar','Kw','Maj','Cze',
'Lip','Sie','Wrz','Pa','Lis','Gru'],
dayNames: ['Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota'],
dayNamesShort: ['Nie','Pn','Wt','Śr','Czw','Pt','So'],
dayNamesMin: ['N','Pn','Wt','Śr','Cz','Pt','So'],
weekHeader: 'Tydz',
dateFormat: 'yy-mm-dd',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};

$.datepicker.setDefaults($.datepicker.regional['pl']);

function html_entity_decode(str) {
    var ta = document.createElement("textarea");
    ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
    toReturn = ta.value;
    ta = null;
    return toReturn
}

function strip_tags(html){

    //PROCESS STRING
    if(arguments.length < 3) {
        html=html.replace(/<\/?(?!\!)[^>]*>/gi, '');
    } else {
        var allowed = arguments[1];
        var specified = eval("["+arguments[2]+"]");
        if(allowed){
            var regex='</?(?!(' + specified.join('|') + '))\b[^>]*>';
            html=html.replace(new RegExp(regex, 'gi'), '');
        } else{
            var regex='</?(' + specified.join('|') + ')\b[^>]*>';
            html=html.replace(new RegExp(regex, 'gi'), '');
        }
    }
    var clean_string = html;
    return clean_string;
}

function copy_to_description(form_name, from, to)
{
    form = document.forms.namedItem(form_name);
    desc = form.elements[to];
    body = form.elements[from];
    ret = body.value;
    ret = html_entity_decode(ret);
    ret = strip_tags(ret);
    ret = ret.substr(0,252);
    ret = ret+"...";
    desc.value = ret;
}

function copy_to_url(mform, from, to)
{
    url = mform[to];
    title = mform[from];
    title_t = title.value.toLowerCase();
    allowed_chars = 'aąbcćdeęfghijklłmnoópqrsśtuvwxyzżź0123456789';
    chars_from_switch = 'ąćęłóśżź';
    chars_to_switch = 'aceloszz';
    ret = "";
    for(i=0;i<title_t.length;i++)
    {
        if(allowed_chars.indexOf(title_t.charAt(i))!=-1)
        {
            index = chars_from_switch.indexOf(title_t.charAt(i));
            if(index==-1)
            {
                ret = ret+(title_t.charAt(i));
            }
            else
            {
                ret = ret+(chars_to_switch.charAt(index));
            }
        }
        else
        {
            ret = ret+"_";
        }
    }
    url.value = ret;
}

function select_box(box_to_select)
{
    form = document.forms.namedItem("input_form");
    img = document.getElementById("box");
    img.src="/images/box"+box_to_select+".jpg";
    form["Box_Category[box_number]"].value = box_to_select;
}

/**
 * Funkcja zamienia vartości formularza w kolejne parametry oddzielone slaszami i robi przekierowanie.
 * Przykład użycia w akcji "/account/list/".
 * @param {String} form_id Id formularza, który chcemy "wysłać"-przekierować.
 * @param {String} link_without_parameters Link akcji, do której chcemy przekierować, bez parametrów.
 * @param {Bool} has_more_pages Jeśli używamy paginacji ustawiamy na true.
 */
function post_to_params(form_id, link_without_parameters, has_more_pages) {
    jQuery('#'+form_id).submit(function() {
        var params = "";
        var empty = true;
        var a = jQuery(this).serializeArray();
        for (var i in a) {
            if(a[i].value == "") params+="all/";
            else {
                params+=a[i].value+"/";
                empty = false;
            }
        }
        if(empty == false) {
            if(has_more_pages == true) window.location.replace(link_without_parameters+params+"1");
            else window.location.replace(link_without_parameters+params);
        }
        else window.location.replace(link_without_parameters);
        return false; // Konieczne, inaczej zosanie wysłany post zamiast przekierowania.
    });
}

/**
 * Funkcja autocomplete wypełniająca pola formularza
 * @param town DOM ID inputa miasta
 * @param postal_code DOM ID inputa kodu pocztowego
 * @param postal_search_source_path - ścieżka do akcji szukającej po kodzie pocztowym (optio::$router->find_by_path('gis/Gis_Search_Postal_Code'))
 * @param city_search_source_path - ścieżka do akcji szukającej po mieście (optio::$router->find_by_path('gis/Gis_Search_City'))
 * @param voivodeship <OPTIONAL> DOM ID selecta województw
 */
function search_gis(town,postal_code,postal_search_source_path,city_search_source_path,voivodeship) {
    if(voivodeship != 'undefined') {
        $('#'+voivodeship).change(function(){
            $('#'+town).val('');
            $('#'+postal_code).val('');
        });
    }    
    $('#'+postal_code).autocomplete({
        minLength:2,
        select: function(event, ui) {
            $('#'+town).val(ui.item.additional['town']);
            $('#'+postal_code).val(ui.item.value);
            if(voivodeship != 'undefined') {
                $('#'+voivodeship).val(ui.item.additional['voivodeship']);
            }
        },
        source: postal_search_source_path+'/'
    });
    $('#'+town).autocomplete({
        minLength:2,
        select: function(event, ui) {
            $('#'+town).val(ui.item.value);
            $('#'+postal_code).val(ui.item.additional['postal_code']);
            if(voivodeship != 'undefined') {
                $("#"+voivodeship).val(ui.item.additional['voivodeship']);
            }
        },
        source: city_search_source_path+'/'
    });
}
/**
 * Funkcja autocomplete wypełniająca pola formularza
 * @param title DOM ID inputa tytułu
 * @param id DOM ID inputa id
 * @param title_search_source_path - ścieżka do akcji szukającej po tytule (optio::$router->find_by_path('articles/search/Article_Search_Title'))
**/
function article_search_title(title,id,title_search_source_path)
{
    $('#'+title).autocomplete({
        minLenght:2,
        select: function(event, ui) {
            $('#'+id).val(ui.item.additional['id']);
            $('#'+title).val(ui.item.value);
        },
        source: title_search_source_path+'/'
    });
}

function to_clipboard(offer_id,path,load_box_path)
{
    $('#clipboard_'+offer_id).html('<img src="/images/loading.gif" />');
    $.ajax(
        {
            url: path,
            type: "GET",
            dataType: 'json',
            success: function(data)
            {
                $('#clipboard_'+offer_id).html(data);
                if(load_box_path != 'undefined') {
                    load_clipboard_box(load_box_path);
                }
            }
        }
    );
}

function off_clipboard(offer_id,path,load_box_path)
{
    $.ajax(
        {
            url: path,
            type: "GET",
            dataType: 'json',
            success: function(data)
            {
                if(data == 'OK') {
                    $('#clipboard_'+offer_id).remove();
                    if(load_box_path != undefined) {
                        load_clipboard_box(load_box_path);
                    }
                }
                if(data == 'EMPTY') {
                    if(load_box_path != undefined) {
                        load_clipboard_box(load_box_path);
                        return true;
                    } else {
                        $('#clipboard_'+offer_id).parent().html('Brak ofert w schowku<div class="tail"></div>');
                    }
                }
            }
        }
    );
}
/**
 * Funkcja wypełnia clipboard_boxa danymi z funkcji php
 *
*/
function load_clipboard_box(path) {
    $.ajax({
        'url'         : path,
        'dataType'    : 'text',
        'success'     : function(data) {
            $('#clipboard_box').html(data);
        }
    });
};

/**
 * Funkcja usuwa kolumnę tabeli o podanym id (uwaga: znaczniki td i th muszą się znajdować w tr!)
 * @param string table_id - DOM ID tabeli
 * @param int column - numer tabeli do usunięcia
 */
function remove_table_column(table_id,column) {
    $('#'+table_id+' tr td:nth-child('+column+'),tr th:nth-child('+column+')').remove();
}

/**
 * Funkcja wysyła posta do wybranego urla. Wynik posta jest treścią wybranego diva.
 *
 * @param string url
 * @param string div_id Id diva, do którego będą wczytywane/usuwane dane.
 * @param array post_array Tablica, która zostanie przesłana postem.
 */
function load_data(url, div_id, post_array) {
    div = jQuery('#'+div_id);
    div.html('<img src="/images/loading.gif" />');

    jQuery.post(url, post_array, function(data) {
          div.html(data);
    });
}

/**
 * Funkcja pobiera content z okna tinymce i wrzuca skrócony tekst do opisu
 * @param string DOM ID textarea tinymce
 * @param string DOM ID textarea descriptionu
 */
function get_description(input,output) {
      ret = $('#'+input).tinymce().getContent();
      ret = html_entity_decode(ret);
      ret = strip_tags(ret);
      ret = ret.substr(0,252);
      ret = ret+"...";
      $('#'+output).val(ret);
}

function session_timer_update(url_to_session_timer)
{
    jQuery.get(url_to_session_timer, function(data){
        var recived = jQuery(data);
        jQuery('#session_lifetime').html(recived.find('#session_lifetime').html());

        var page_login_box = jQuery('#session_login_box');
        var page_refresh_box = jQuery('#session_refresh_box');

        var refresh_box = recived.find('#session_refresh_box');
        if(refresh_box.length===1)
        {
            if(page_login_box.dialog('isOpen')===true)
            {
                page_login_box.dialog('close');
            }
            if(page_refresh_box.dialog('isOpen')!==true)
            {
                page_refresh_box.dialog('open');
            }
        }

        var login_box = recived.find('#session_login_box');
        if(login_box.length===1)
        {
            if(page_refresh_box.dialog('isOpen')===true)
            {
                page_refresh_box.dialog('close');
            }
            if(page_login_box.dialog('isOpen')!==true)
            {
                page_login_box.dialog('open');
                page_login_box.find('input#login_input').focus();
            }
        }

        if(login_box.length===0 && refresh_box.length===0)
        {
            if(page_login_box.dialog('isOpen')===true)
            {
                page_login_box.dialog('close');
            }
            if(page_refresh_box.dialog('isOpen')===true)
            {
                page_refresh_box.dialog('close');
            }
        }
    });
}

function session_timer_start(url_to_session_timer, frequency) {
    setInterval(
        function() {
            session_timer_update(url_to_session_timer);
        } ,frequency*1000 // setInterval pobiera częstotliwość w milisekundach
    );
    session_timer_update(url_to_session_timer);
}

