function setCookie(cookieName, cookieValue, nDays) {
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0) {
        nDays=1;
    }
    expire.setTime(today.getTime() + (3600000 * 24 * nDays));
    document.cookie = cookieName + "=" + escape(cookieValue) + ";path=/;expires=" + expire.toGMTString();
}

function disableAll() {
	var Nodes = document.getElementsByTagName("INPUT");
	var max = Nodes.length;
	var i = 0;
	for(i = 0;i < max;i++) {
		var nodeObj = Nodes.item(i);
		if(nodeObj.type == 'hidden') continue;
		classname = nodeObj.className;
		if(classname=='inputtext') classname='inputtextreadonly';
		else {
			classname = classname.replace(/inputtext /gi, 'inputtextreadonly ');
		}
        nodeObj.style.background = '';
		nodeObj.className = classname;
		nodeObj.disabled=true;
	}
	var Nodes = document.getElementsByTagName("SELECT");
	var max = Nodes.length;
	var i = 0;
	for(i = 0;i < max;i++) {
	var nodeObj = Nodes.item(i);
        nodeObj.style.background = '';
	//document.write(nodeObj.name+'<br>');
		nodeObj.disabled=true;
	}
}

function disable(idArray) {
    var max = idArray.length;
    for (i = 0; i < max; i++) {
        obj = document.getElementById(idArray[i]);
        if(obj.type == 'hidden') continue;
		classname = obj.className;
		if(classname=='inputtext') classname='inputtextreadonly';
		else {
			classname = classname.replace(/inputtext /gi, 'inputtextreadonly ');
		}
        obj.style.background = '';
		obj.className = classname;
		obj.disabled=true;
    }
}

function enableAll() {
	var Nodes = document.getElementsByTagName("INPUT");
	var max = Nodes.length;
	var i = 0;
	for(i = 0;i < max;i++) {
		var nodeObj = Nodes.item(i);
		if(nodeObj.type == 'hidden') continue;
		classname = nodeObj.className;
		if(classname=='inputtextreadonly') classname='inputtext';
		else {
			classname = classname.replace(/inputtextreadonly /gi, 'inputtext ');
		}
		nodeObj.className = classname;
		nodeObj.disabled=false;
	}
	var Nodes = document.getElementsByTagName("SELECT");
	var max = Nodes.length;
	var i = 0;
	for(i = 0;i < max;i++) {
	var nodeObj = Nodes.item(i);
	//document.write(nodeObj.name+'<br>');
		nodeObj.disabled=false;
	}
}

function enable(idArray) {
    var max = idArray.length;
    for (i = 0; i < max; i++) {
        obj = document.getElementById(idArray[i]);
        if(obj.type == 'hidden') continue;
		classname = obj.className;
		if(classname=='inputtextreadonly') classname='inputtext';
		else {
			classname = classname.replace(/inputtextreadonly /gi, 'inputtext ');
		}
		obj.className = classname;
		obj.disabled=false;
    }
}

function setRequired(arr) {
	for(i=0; i<arr.length; i++) {
		$("#"+arr[i]).addClass("required");
	}
}
function setDisabled(field_id) {
	$('#'+field_id).addClass('disabledfield');
	$('#'+field_id).attr('disabled', 'disabled');
}
function unsetDisabled(field_id) {
	$('#'+field_id).removeClass('disabledfield');
	$('#'+field_id).removeAttr('disabled');
}
function showHide(elId) {
	$('#'+elId).toggle(500);
}
function show(elId) {
	$('#'+elId).show(500);
}
function showImmediate(elId) {
	$('#'+elId).show(0);
}
function hide(elId) {
	$('#'+elId).hide(500);
}

function showHideServices()
{
    showServices = !showServices;
    if (showServices) {
        document.getElementById('categoryList').style.display = '';
    }
    else {
        document.getElementById('categoryList').style.display = 'none';
    }
}

function selectServiceFromList(serviceId, serviceName, submitForm)
{
	//submitujemy ZAWSZE WSZYSTKO
	submitForm=1;
    
	if (selectionForNewOffer) {
        return selectServiceForNewOffer(serviceId, serviceName);
    } else {
        return selectServiceForSearch(serviceId, serviceName, submitForm);
	}
    return false;
}

function selectServiceForSearch(serviceId, serviceName, submitForm)
{
	var sId = $('#serviceId').attr('name');
	var usId = $('#useServiceId').attr('name');
	var sN = $('#serviceName').attr('name');
	if (sId && usId && sN) {
	
	    // pobranie poprzednikow w drzewie uslug - rozwiniete galezie
	    var path = getServiceAncestors(serviceId);
	    setOpenedNodePathCookie(path);
	
	    // wyroznienie przycisku wyszukaj w wysz zaawansowanej
	    if ($('#advOfferSearchFormSubmit') && $('#advOfferSearchFormSubmit2')) {
	        setAdvancedSearchChange();
	    }
	
	    if ($('#serviceNameHint')) {
	        $('#serviceNameHint').val('0');
	    }
	    $('#serviceName').addClass('mark');
	    document.getElementById('serviceId').value = serviceId;
	    document.getElementById('useServiceId').value = 1;
	    document.getElementById('serviceName').value = serviceName;
	    document.getElementById('serviceName').focus();
	    tb_remove();
	    
	    if (submitForm) {
	    	return submitSearchForm();
	    }
	    
	} else {
		lastSpot = getCookie('lastSpot').split('|');
		
		document.location = module_base + 'offerSearch/index?mainSearch=1&serviceId=' + serviceId + '&useServiceId=1&serviceName=' + serviceName + '&spotId=' + lastSpot[0] + '&useSpotId=1&isDistrict=' + lastSpot[2] + '&locationName=' + lastSpot[1];
		
	    return false;
	}
}

function submitSearchForm()
{
    if ($('#advOfferSearch').attr('name')) {
        // wyszukiwarka zaawansowana
        $('#announcementPhone').val( $('#an_phone_c').val() );
        $('#announcementEmail').val( $('#an_email_c').val() );
        $('#announcementDesc').val( $('#an_desc_t').val() );
        $('#advOfferSearch').submit();
        return false;
    } else {
        // wyszukiwarka na stronie glownej
        document.getElementById('offerSearchForm').submit();
        return false;
    }
}


function selectServiceForNewOffer(serviceId, serviceName)
{
    var fName = $('#addeditOfferForm').attr('name');
    var sName = $('#serviceName').attr('name');
    var sId = $('#serviceId').attr('name');
    var usId = $('#useServiceId').attr('name');
    
    if (fName && sName && sId && usId) {
        $('#serviceName').val(serviceName);
        $('#serviceId').val(serviceId);
        $('#useServiceId').val(1);
        tb_remove();
    } else {
	    document.location = module_base + 'providerregistration/addeditofferform?offerId=0&serId=' + serviceId + '&useSerId=1&serName=' + serviceName;
	}
    return false;
}

//function showMore(serviceName, spuLogged)
function showMore(serviceName)
{
    $.ajax({
	    type: "POST",
	    url: module_base+"module/ajaxsetopenednodepathcookie",
	    cache: false,
	    data: 'serviceName=' + serviceName,
	    success: function(nodes){
    		if (nodes.length) {
		        // ustawienie cookie z rozwinietymi galeziami
	            setOpenedNodePathCookie(nodes);
	            // zwiniecie wszystkich galezi i rozwiniecie wybranych
	            resetOpenedNodesInServiceTree(nodes);
    		}

            var sId = $('#serviceId').attr('name');
		    var usId = $('#useServiceId').attr('name');
		    var sN = $('#serviceName').attr('name');
		    if (sId && usId && sN) {
		        tb_show(null, '#TB_inline?height=450&amp;width=565&amp;inlineId=categoryList', false);
		        return false;
		    } else {
		    	if (requestUri.indexOf('providerregistration') == -1 && providerSite != 1) {
		    		// strony klienta
		    		document.location = module_base + 'index/index?showThickbox=categoryList';
		    	} else {
		    		// strony uslugodawcy
		    		document.location = module_base + 'providerregistration/addeditofferform?offerId=0&showThickbox=categoryList';
		    	}
		        return false;
		    }
        }
    });
    return false;
}

function toggleNodeChildren(currentId, path, nodes)
{
    var nodesArray = nodes.split(",");
    var open = true;
    for (i = 0; i < nodesArray.length; i++) {
        if ( $('#node' + nodesArray[i] + '').is(':visible') ) {
            open = false;
        }
        $('#node' + nodesArray[i] + '').toggle('fast');
    }
    if (open) {
        $('#node' + currentId + '').removeClass('base');
        $('#node' + currentId + '').addClass('basedown');
        setOpenedNodePathCookie(path);
    } else {
        $('#node' + currentId + '').removeClass('basedown');
        $('#node' + currentId + '').addClass('base');
    }
}

function selectSpotFromList(spotId, spotName, isDistrict)
{
    // wyroznienie przycisku wyszukaj w wysz zaawansowanej
    if ($('#advOfferSearchFormSubmit') && $('#advOfferSearchFormSubmit2')) {
            setAdvancedSearchChange();
    }
    
    if ($('#locationNameHint')) {
        $('#locationNameHint').val('0');
    }
    $('#inputString').addClass('mark');
    document.getElementById('spotId').value = spotId;
    document.getElementById('useSpotId').value = 1;
    document.getElementById('isDistrict').value = isDistrict;
    document.getElementById('inputString').value = spotName;
    document.getElementById('inputString').focus();
    tb_remove();
    submitSearchForm();
}

function autoSelectSpotFromList(spotId, spotName, isDistrict)
{
    selectSpotFromList(spotId, spotName, isDistrict);
    //addSpotToList();
    $('#spotId').val(0);
    $('#useSpotId').val(0);
    $('#isDistrict').val(isDistrict);
    $('#inputString').removeClass('mark');
}

function offerSearchFormSubmit()
{
    //document.getElementById('serviceName').disabled = false;
}

function styleInputFile(img) {
    $(".inputfile").filestyle({
        image: img,
        imageheight : 22,
        imagewidth : 82,
        width: 150
    });
    $(".inputfile2").filestyle({
        image: img,
        imageheight : 22,
        imagewidth : 82,
        width : 260
    });
}


function toggleTimeFields(className) {
    var classSelector = '.' + className;
    
	var actual = $(classSelector).attr("disabled");
    
    if (actual == true) {
        $(classSelector).attr("disabled", "");
        $(classSelector).toggleClass("disabled");
        $("#" + className + "_from_h").val("00");
        $("#" + className + "_from_m").val("00");
        $("#" + className + "_to_h").val("23");
        $("#" + className + "_to_m").val("59");
    } else {
        $(classSelector).attr("disabled", "disabled");
        $(classSelector).toggleClass("disabled");
        $(classSelector).val("");
    }
    
    $('#toggle_all').attr("checked", false);
}

function toggleAllTimeFields()
{
	days = new Array('mo', 'tu', 'we', 'th', 'fr', 'sa', 'su');
	
	daysLength = days.length;
	
	for( i = 0; i < daysLength; i++)
	{
		var classSelector = '.' + days[i];
		
		if ( !$(classSelector).attr("disabled") )
		{
			$('#chk_' + days[i]).attr("checked", false);
			
			$(classSelector).attr("disabled", "disabled");
			$(classSelector).toggleClass("disabled");
			$(classSelector).val("");
		}
	}
}

$(document).ready(function() {
    $('#advOfferSearchFormSpotSubmit').click(function() {
        $('#spot_serviceId').val($('#serviceId').val());
        $('#spot_serviceName').val($('#serviceName').val());
        $('#advOfferSearchFormSpot').submit();
    });
    
    $('#advOfferSearchFormTimeSubmit').click(function() {
        $('#time_serviceId').val($('#serviceId').val());
        $('#time_serviceName').val($('#serviceName').val());
        $('#advOfferSearchFormTime').submit();
    });
    
    $('#advOfferSearchFormPersonSubmit').click(function() {
        $('#person_serviceId').val($('#serviceId').val());
        $('#person_serviceName').val($('#serviceName').val());
        $('#advOfferSearchFormPerson').submit();
    });
    
    $('#advOfferSearchFormDescSubmit').click(function() {
        $('#desc_serviceId').val($('#serviceId').val());
        $('#desc_serviceName').val($('#serviceName').val());
        $('#advOfferSearchFormDesc').submit();
    });
    
    $('.maskHour, .maskMinute').focus(function() {
        $(this).val('');
    });
    
    $('#sample_offer_1').click(function() {
    	$('#sample_offers').slideUp("slow");
        $('#sample_offer_1_full').slideDown("slow");
    });
    
    $('#sample_offer_2').click(function() {
    	$('#sample_offers').slideUp("slow");
        $('#sample_offer_2_full').slideDown("slow");
    });
    
    $('#sample_offer_1_full').click(function() {
    	$('#sample_offer_1_full').slideUp("slow");
    	$('#sample_provider_label').slideDown("slow");
    	$('#sample_offers').slideDown("slow");
    });
    
    $('#sample_offer_2_full').click(function() {
    	$('#sample_offer_2_full').slideUp("slow");
    	$('#sample_provider_label').slideDown("slow");
    	$('#sample_offers').slideDown("slow");
    });
    
    $('#showSampleOffersBtn').click(function() {
    	$('#showSampleOffersBtn').css('display', 'none');
    	$('#sample_offer_1_full').slideUp("slow");
    	$('#sample_offer_2_full').slideUp("slow");
    	$('#sample_provider_label').slideToggle("slow");
    	$('#sample_offers').slideToggle("slow");
    	return false;
    });
    
    $('#showSampleWherewhenBtn').click(function() {
    	$('#showSampleWherewhenBtn').css('display', 'none');
    	$('#sample_provider_label').slideToggle("slow");
    	$('#sample_wherewhen').slideToggle("slow");
    	return false;
    });
    
    $('#showSampleExtrasBtn').click(function() {
    	$('#showSampleExtrasBtn').css('display', 'none');
    	$('#sample_provider_label').slideToggle("slow");
    	$('#sample_extras').slideToggle("slow");
    	return false;
    });
    
    $('#showSampleReferencesBtn').click(function() {
    	$('#showSampleReferencesBtn').css('display', 'none');
    	$('#sample_provider_label').slideToggle("slow");
    	$('#sample_references').slideToggle("slow");
    	return false;
    });
    
    $('#showNotebookExampleBtn').click(function() {
    	$('#sample_notebook').slideToggle("slow");
    	$('#showNotebookExampleBtn').hide();
    	return false;
    });
    
    enableServiceListButton();
    
});

function addComment(ref_id_s, label) {
    var comment = prompt(label,"");
    if ((comment!=null) && (comment!="")) {
        document.getElementById('com_ref_id_k').value = ref_id_s;
        document.getElementById('com_desc_t').value = comment;
        document.getElementById('add_comment_form').submit();
    }
}

function setACResultsPosition(className) {
    $('#ac_results').hide();
    $('#ac_results').html('');
    $('#ac_results').removeClass();
    $('#ac_results').addClass('ac_results');
    $('#ac_results').addClass(className);
    if (className == 'mainSearch_services') {
        // wysz. glowna - nazwa uslugi
        if (($('#serviceNameHint').val() * 1) == 1) {
            // podpowiedz jest wyswietlona - nalezy ja wykasowac
            $('#serviceNameHint').val('0');
            $('#serviceName').val('');
        }
    } else if (className == 'mainSearch_spots') {
        // wysz. glowna - nazwa lokalizacji
        if (($('#locationNameHint').val() * 1) == 1) {
            // podpowiedz jest wyswietlona - nalezy ja wykasowac
            $('#locationNameHint').val('0');
            $('#inputString').val('');
        }
    }
}

function autocompleterShowFullList(inputId) {
    $('.ac_hidden').removeClass('ac_hidden');
    $('.ac_more').addClass('ac_hidden');
    $('#ac_show_results').val(1);
    $('#ac_results').show();
    $('#' + inputId).focus();
}

// maski dla wyszukiwarki zaawansowanej
jQuery(function($){
   $(".maskHour, .maskMinute").mask("99", {placeholder:" "});
});

function addReference(ref_o_id_k) {
    var rating = prompt("Podaj ocenę usługi/usługodawcy:","5");
    var description = prompt("Opis referencji:","");
    if ((rating!=null) && (rating!="") && (description!=null) && (description!="")) {
        document.getElementById('ref_o_id_k').value = ref_o_id_k;
        document.getElementById('ref_rating_f').value = rating;
        document.getElementById('ref_desc_t').value = description;
        document.getElementById('add_reference_form').submit();
    }
}

function sendContactByEmail(offerId, baseUrl, confirmLabel, infoLabel) {
    var send = window.confirm(confirmLabel);
    if (send == true) {
        $.ajax({
            type: "POST",
            url: baseUrl+"notebook/ajaxsendemail",
            cache: false,
            data: 'offerId=' + offerId
        });
        alert(infoLabel);
    }
}

function deleteOfferFromNotebook(offerId, confirmLabel) {
    var del = window.confirm(confirmLabel);
    if (del == true) {
        $("#deleteOfferId").val(offerId);
        $("#deleteOfferForm").submit();
        return false;
    } else if (del == false) {
        $("#deleteOfferId").val(0);
        return false;
    }
    return false;
}

function clearElementValue(elementId) {
    $('#' + elementId).val('');
}

function showElementInThickbox(elementId, controller, action, paramName, paramValue)
{
	setThickboxContentBackup('#' + elementId);
	
    $.ajax({
       type: "POST",
       url: module_base + controller + '/' + action,
       data: paramName + '=' + paramValue,
       success: function(content){
           $('#' + elementId).html(content);
           tb_show(null, '#TB_inline?height=450&amp;width=565&amp;inlineId=' + elementId, false);
           return false;
       }
    });
    return false;
}

function showElementInThickboxWithMultipleParams(elementId, controller, action, paramArray, reloadThickbox, loaderImg)
{
	setThickboxContentBackup('#' + elementId);
	
    if ((!reloadThickbox) && (loaderImg != '')) {
        $('#TB_ajaxContent').html('<div class="ajax_loader_container"><img src="' + loaderImg + '" alt="" border="0" /></div>');
    }

    paramString = '';
	for (var param in paramArray) {
	   paramString = paramString + param + '=' + paramArray[param] + '&';
	}
	
    $.ajax({
       type: "POST",
       url: module_base + controller + '/' + action,
       data: paramString,
       success: function(content){
           if (reloadThickbox) {
               $('#' + elementId).html(content);
               tb_show(null, '#TB_inline?height=450&amp;width=565&amp;inlineId=' + elementId, false);
           } else {
               $('#TB_ajaxContent').html(content);
           }
           return false;
       }
    });
    return false;
}

function showElementInThickboxWithoutAjax(elementId)
{
    $("#TB_window #TB_ajaxContent").text($("#" + elementId).val());
    return false;
}

function setSpuEnabled(value, confirmLabel)
{
    var change = window.confirm(confirmLabel);
    if (change == true) {
        $.ajax({
            type: "POST",
            url: module_base+"providerregistration/ajaxsetenabled",
            cache: false,
            data: 'enabled=' + value,
            success: function(content)
            {
                $('#spuEnabled').html(content);
            }
        });
    }
}

function loadSpotList(elementId, controller, action, paramName, paramValue, loaderImg)
{
	
    if (loaderImg != '') {
    	// backupujemy tylko jesli pojawia się "klepsydra" - wywolanie nieautomatyczne
    	setThickboxContentBackup('#' + elementId);
        $('#' + elementId).html('<div class="ajax_loader_container"><img src="' + loaderImg + '" alt="" border="0" /></div>');
    }
    
    var dataStr = '';
    if (objIsArray(paramName) && objIsArray(paramValue) && (paramName.length == paramValue.length)) {
        for (var i=0; i < paramName.length; i++) {
            dataStr += paramName[i] + '=' + paramValue[i] + '&'
        }
        dataStr = dataStr.substr(0, (dataStr.length - 1));
    } else {
        dataStr = paramName + '=' + paramValue;
    }
    
    $.ajax({
        type: "POST",
        url: module_base + controller + '/' + action,
        data: dataStr,
        success: function(content){
    	   	cleanThickboxContentBackup();
    	   
	   		$('#' + elementId).html(content);
           
    	   	enableSpotListButton();
    	   	copyAjaxContentToAjaxWindowTitle();
           
    	   	return false;
       	}
    });
    return false;
}

function setOpenedNodePathCookie(path)
{
    var today = new Date();
    var expire = new Date();
    expire.setTime(today.getTime() + 3600000 * 24);
    document.cookie = "openedNodePath="+ path + ";expires="+expire.toGMTString()+";path=/";
}

function deleteOpenedNodePathCookie()
{
    var today = new Date();
    var expire = new Date();
    expire.setTime(today.getTime() - 3600000 * 24);
    document.cookie = "openedNodePath='';expires="+expire.toGMTString()+";path=/";
}

function setAdvancedSearchChange()
{
    if (!advancedSearchChanged) {
        $('#advOfferSearchFormSubmit').attr('src', newAdvancedSearchImg);
        $('#advOfferSearchFormSubmit2').attr('src', newAdvancedSearchImg2);
        advancedSearchChanged = 1;
    }
}

// funkcja czyszczaca domyslna tresc z pol nazwa uslugi i lokalizacja
function checkSearchFormNames(serviceName, locationName)
{
    if ($('#serviceName').val() == serviceName) {
        $('#serviceName').val('');
    }
    
    if ($('#inputString').val() == locationName) {
        $('#inputString').val('');
    }
}

function objIsArray(obj)
{
	if (typeof arguments[0] == 'object') {
	    var criterion = arguments[0].constructor.toString().match(/array/i); 
	    return (criterion != null);
	}
	return false;
}

function checkAvailableDates(dateMask)
{
	//empty
}

function getServiceAncestors(serviceId) {
    var elem = $('#node' + serviceId);
    
    var path = '';
    
    if (elem.length == 0) {
    	return path;
    }
    
    while (elem != null && elem.parent()) {
        elem = elem.parent();
        if (elem.attr('id') != undefined) {
            // jesli przodek ma zdefiniowany atrybut id
            var id = new String(elem.attr('id').toString());
            if (id.length && (id.substr(0, 4) == 'node')) {
                // jesli atrybut id ma wartosc nodeID to pobieramy ID
                path = id.substr(4, id.length) + ',' + path;
            }
        }
        if (elem.is('.firstlevel') || elem.attr('id') == 'dhtmlgoodies_tree2') {
            /* - jesli element jest klasy firstlevel to znaczy,
               ze dotarlismy do galezi glownej;
               - jesli element ma id rowne dhtmlgoodies_tree2
               w obu wypadkach nastepuje koniec pobierania przodkow
            */
            elem = null;
        }
    }
    if (path.length) {
        // usuniecie przecinka za ostatnim elementem
        path = path.substr(0, (path.length-1));
    }
    return path;
}

function resetOpenedNodesInServiceTree(nodes)
{
    $('#dhtmlgoodies_tree2 li.basedown').addClass('base');
    $('#dhtmlgoodies_tree2 li').removeClass('basedown');
    $('#dhtmlgoodies_tree2 li.nextlevel').css('display', 'none');
    
    var nodesArray = nodes.split(",");
    for (i = 0; i < nodesArray.length; i++) {
        var id = nodesArray[i];
        $('#node' + id + '').removeClass('base');
        $('#node' + id + '').addClass('basedown');
        $('#node' + id + '').css('display', 'block');
        $('#node' + id + ' li').css('display', 'block');
    }
}

function showAboutUs()
{
    document.getElementById('topInfoFrameTitle').innerHTML = document.getElementById('aboutusInfoTitle').innerHTML;
    document.getElementById('topInfoFrameContents').innerHTML = document.getElementById('aboutusInfo').innerHTML;
    $('#topInfoFrame').slideDown();
}

function showHowToProvideServicesAndEarnMoney(label)
{
    $.ajax({
       type: "POST",
       url: module_base + 'module/ajaxgethowtoprovideservicesandearnmoney',
       success: function(content){
    	   if (label.length > 0) {
    		   $('#topInfoFrameTitle').html(label);
    	   } else {
    		   $('#topInfoFrameTitle').hide();
    		   $('#topInfoFrameTitle').next().hide();
    	   }
           $('#topInfoFrameContents').html(content);
           $('#topInfoFrame').slideDown();
           return false;
       }
    });
    return false;
}

function clearValue(id)
{
    $('#' + id).val('');
}

function copyAjaxContentToAjaxWindowTitle()
{
    $("#TB_ajaxWindowTitle").html('');
    
    var str = $("#thickbox_back_backup").html();
    var backup = 0;
    if (str == null || !str.length) {
        $("#thickbox_back_title").html('');
        var backup = 0;
    } else {
        var backup = 1;
    }
    
    $("#TB_ajaxWindowTitle").html($("#TB_window #TB_ajaxContent > h1:first-child").html());
    var str = $("#TB_window #TB_ajaxContent > h1:first-child").text();
    if ((str.length * 1) == 0) {
        $("#TB_ajaxWindowTitle").hide();
    } else {
        $("#TB_ajaxWindowTitle").show();
    }
    $("#TB_window #TB_ajaxContent > h1:first-child").hide();

	if (backup) {
	    var element = '#TB_ajaxContent #thickbox_back_backup';
	} else {
	    var element = '#TB_ajaxContent #thickbox_back';
	}

    if ($(element).text()) {
        var parents = $(element).parent();
        if (parents != undefined) {
            var parent = $(parents).get(0);
            parents = $(parent).parent();
            parent = $(parents).get(0);
            var html = $(parent).html();
            if (!backup) {
                $("#TB_ajaxContent #thickbox_back").attr('id', 'thickbox_back_backup');
            } else {
                var newhtml = html.replace('thickbox_back_backup', 'thickbox_back');
                html = newhtml;
            }
            $("#thickbox_back_title").html(html);
        }
    }

	var str = $("#thickbox_back").html();
	if (str) {
		if ((str.length * 1) == 0) {
		    $("#thickbox_back_title").hide();
		} else {
		    $("#thickbox_back_title").show();
		}
	} else {
	    $("#thickbox_back_title").hide();
	}
	//$("#thickbox_back").hide();
}

/*
 *  Odpowiednik metody Label::getAgeLabel() - zwraca labelke "lat" lub "lata".
 *  Metoda sluzy do wyswietlenia odpowiedniej etykiety wieku: "lat" lub "lata".
 *  Algorytm dziala w ten sposob, ze jesli wiek konczy sie cyfra 2, 3 lub 4
 *  to zwracana jest labelka "lata", w kazdym innym przypadku "lat"
 *  (wyjatkiem jest wiek 12, 13 i 14 "lat").
 */
function getAgeLabel(age, latLabel, lataLabel)
{
    var label = "";
    var ageObj = new String(age);
    if (!ageObj.length) {
        return label;
    }
    var lastChar = ageObj.substr((ageObj.length-1), 1);
	if ((ageObj.valueOf() != '12')
	   && (ageObj.valueOf() != '13')
	   && (ageObj.valueOf() != '14')
	   &&
	   (lastChar == '2' || lastChar == '3' || lastChar == '4')) {
	    // lata
	    $label = lataLabel;
	} else {
	    // lat
	    $label = latLabel;
	}
	return $label;
}

function enableSpotListButton()
{
    $('#spotListButton').hide();
    $('#spotListButtonLink').show();
}

function enableServiceListButton()
{
    $('#serviceListButton').hide();
    $('#serviceListButtonLink').show();
}

function showElementInThickboxWithTitle(title, controller, action, paramName, paramValue)
{
	tb_remove();
    $.ajax({
       type: "POST",
       url: module_base + controller + '/' + action,
       data: paramName + '=' + paramValue,
       success: function(content){
    	   $('#thickBoxDiv').html(content);
    	   tb_show(null, '#TB_inline?height=450&amp;width=565&amp;inlineId=thickBoxDiv', false);
    	   $("#TB_ajaxWindowTitle").html('<span>' + title + '</span>');
    	   $("#TB_ajaxWindowTitle").show();
           return false;
       }
    });
    return false;
}

function suggestServiceFormSubmit(serviceNameLabel, serviceDescLabel, nameLabel, emailLabel, newWindowTitle, standardTitleContainer)
{
	// czyszczenie wartosci domyslnych pol
	if ($("#suggestServiceName").val() == serviceNameLabel) {
		$("#suggestServiceName").val('');
	}
	if ($("#suggestServiceDesc").val() == serviceDescLabel) {
		$("#suggestServiceDesc").val('');
	}
	if ($("#suggestName").val() == nameLabel) {
		$("#suggestName").val('');
	}
	if ($("#suggestEmail").val() == emailLabel) {
		$("#suggestEmail").val('');
	}
	
	$.ajax({
       type: "POST",
       url: module_base + 'module/ajaxprocesssuggestnewservice',
       data: 'serviceName=' + $("#suggestServiceName").val()
       		 + '&' + 'serviceDesc=' + $("#suggestServiceDesc").val()
       		 + '&' + 'popularity=' + $("input[@name='formData[popularity]']:checked").val()
       		 + '&' + 'name=' + $("#suggestName").val()
       		 + '&' + 'email=' + $("#suggestEmail").val()
       		 + '&' + 'requestUri=' + $("#requestUri").val()
       		 ,
       success: function(content){
           $("#TB_ajaxContent").html(content);
           substituteAjaxWindowTitle(newWindowTitle, standardTitleContainer);
           return false;
       }
    });
    return false;
}

function suggestSpotFormSubmit(spotNameLabel, zipcodeLabel, nameLabel, emailLabel, agglomerationView, newWindowTitle, standardTitleContainer)
{
	// czyszczenie wartosci domyslnych pol
	if ($("#suggestSpotName").val() == spotNameLabel) {
		$("#suggestSpotName").val('');
	}
	if ($("#suggestZipcode").val() == zipcodeLabel) {
		$("#suggestZipcode").val('');
	}
	if ($("#suggestName").val() == nameLabel) {
		$("#suggestName").val('');
	}
	if ($("#suggestEmail").val() == emailLabel) {
		$("#suggestEmail").val('');
	}
	
	$.ajax({
       type: "POST",
       url: module_base + 'module/ajaxprocesssuggestnewspot',
       data: 'spotName=' + $("#suggestSpotName").val()
       		 + '&' + 'zipcode=' + $("#suggestZipcode").val()
       		 + '&' + 'name=' + $("#suggestName").val()
       		 + '&' + 'email=' + $("#suggestEmail").val()
       		 + '&' + 'requestUri=' + $("#requestUri").val()
       		 + '&' + 'agglomerationView=' + agglomerationView
       		 ,
       success: function(content){
           $("#TB_ajaxContent").html(content);
           substituteAjaxWindowTitle(newWindowTitle, standardTitleContainer);
           return false;
       }
    });
    return false;
}

function clearElementValueOnceIfDefaultValue(id, event, defaultValue)
{
	if ($('#' + id).val() == defaultValue) {
		// jesli element ma wartosc defaultowa to ja usuwamy
		clearElementValue(id);
	}
	
	$('#' + id).attr(event, '');
}

function showCategoryListInThickbox()
{
	tb_remove();
	showElementInThickbox('categoryList', 'module', 'ajaxshownodesdiv', '', '');
	return false;
}

function showSpotListInThickbox()
{
	tb_remove();
	showElementInThickbox('spotList', 'module', 'ajaxgetagglomerationsandregions', '', '');
	return false;
}

/**
 * Funkcja pozwalajaca na przeladowanie zawartosci okna AJAX bez jego wylaczania.
 * @param elementId
 * @param controller
 * @param action
 * @param paramArray
 * @param reloadThickbox
 * @param loaderImg
 * @return
 */
function substituteAjaxWindowContent(elementId, newWindowTitle, standardTitleContainer, controller, action, paramArray, reloadThickbox, loaderImg)
{
	setThickboxContentBackup('#TB_ajaxContent');
	
    if ((!reloadThickbox) && (loaderImg != '')) {
        $('#TB_ajaxContent').html('<div class="ajax_loader_container"><img src="' + loaderImg + '" alt="" border="0" /></div>');
    }

    paramString = '';
	for (var param in paramArray) {
	   paramString = paramString + param + '=' + paramArray[param] + '&';
	}
	
    $.ajax({
       type: "POST",
       url: module_base + controller + '/' + action,
       data: paramString,
       success: function(content){
    	
    	   cleanThickboxContentBackup();
    	
           if (reloadThickbox) {
               $('#' + elementId).html(content);
               tb_show(null, '#TB_inline?height=450&amp;width=565&amp;inlineId=' + elementId, false);
           } else {
               $('#TB_ajaxContent').html(content);
           }
           substituteAjaxWindowTitle(newWindowTitle, standardTitleContainer)
           return false;
       }
    });
    return false;
}

/**
 * Funkcja pozwalajaca na podmiane naglowka okna AJAX bez jego ponownego
 * otwierania, ale podczas wymiany zawartosci. 
 * @return
 */
function substituteAjaxWindowTitle(newTitle, standardTitleField)
{
	if (document.getElementById('TB_ajaxWindowTitle')) {
		if (document.getElementById(standardTitleField)) {
			if (newTitle == '') {
				newTitle = document.getElementById(standardTitleField).innerHTML;
			}
			document.getElementById(standardTitleField).style.display = 'none';
		}
	    document.getElementById('TB_ajaxWindowTitle').innerHTML = '<span>' + newTitle + '</span>';
	}
}


//Obsluga przywracania zawartosci thickboxa podczas przeladowywania
//wykorzystywać należy tak:
//1. Podczas rzopoczęcia przeładowywania zapisać aktualną zawartość thickboxa za pomocą setThickboxContentBackup
//2. Wyczyścić thickboxa po przeładowaniu cleanThickboxContentBackup() 
//3. Przywróceniem zapisanej wartości zajmuje się tb_remove(), wykorzystując revertThickboxContentBackup()
//ustawienie zmiennych globalnych

var thickboxContentBackupId = '';
var thickboxContentBackup = '';

function setThickboxContentBackup(id)
{
	var id = id;
	var val = $(id).html();
	
	if(id.length>0 && val.length>0) {
		thickboxContentBackupId = id;
		thickboxContentBackup = val;
	}
	else {
		thickboxContentBackupId = '';
		thickboxContentBackup = '';
	}
}

function cleanThickboxContentBackup()
{
	setThickboxContentBackup('');
}

function revertThickboxContentBackup()
{
	if(thickboxContentBackupId.length>0 && thickboxContentBackup.length>0)
		$(thickboxContentBackupId).html(thickboxContentBackup);
}

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
