jQuery.fn.updateTargetWithAction = function(settings){
    try{
        //default settings
        settings = jQuery.extend({
            action: '/',//default url for action
            sourceElm: $(this),//source element to get a value from: select, input, ...
            targetElm: null,//target element - it's inner html is replaced with result
            ajaxTimeout: 30,//time out for ajax request in seconds
            beforeAjax: function(){},//function to run before ajax request function starts
            afterAjax: function(){},//function to run after ajax request function is done
            afterAjaxSuccess: function(){},//function to run when ajax request is successfull and the xml is parsed
            afterAjaxError: function(){},//function to run when ajax request is unsuccessfull
            xmlContentElement: 'content',//element in the response which holds the HTML
            addToParams: ''//comma separated list of element id's to be posted in params(also param name can be defined, eg: parent_id=f_districts,f_cities)
        }, settings);

        var $sourceElm = $(settings.sourceElm);
        if($sourceElm.length == 0)
            $sourceElm = $('#'+settings.sourceElm);
        if($sourceElm.length == 0)
            return false;
        var $targetElm = $(settings.targetElm);
        if($targetElm.length == 0)
            $targetElm = $('#'+settings.targetElm);
        if($targetElm.length == 0)
            return false;
        var result = '';
        var params = '';
        action = settings.action;
        if(action.indexOf('?') > 0){
            params = action.substr(action.indexOf('?')+1);
            action = action.substr(0, action.indexOf('?'));
        }
        id = $sourceElm.val();
        if(typeof(id) != 'undefined')
            params += '&id='+id;
        addToParamsArr = settings.addToParams.split(',');
        for(key in addToParamsArr){
            param_id = addToParamsArr[key];
            if(param_id.length > 0){
                param_settings = param_id.split('=');
                if(param_settings.length == 2){
                    param_id = param_settings[0];
                    elm = $('#'+param_settings[1]);
                }else{
                    elm = $('#'+param_id);
                }
                if(elm.length > 0){
                    params += '&'+param_id+'=';
                    if($.trim(elm.val()) != ''){
                        params += $.trim(elm.val());
                    }else if($.trim(elm.text()) != ''){
                        params += $.trim(elm.text());
                    }
                }
            }
        }
        random = new Date().getTime();
        params += '&ajax=1&random='+random;
        try{
            settings.beforeAjax();
        }catch (e){
        }
        $.ajax({
            type: 'GET',
            timeout: settings.ajaxTimeout * 60,
            url: action,
            data: params,
            async: false,
            //dataType: 'xml',
            success: function(response){
              result = response;
              if($(settings.xmlContentElement, result).length < 0)
                  return false;
              else
                  result = $(settings.xmlContentElement, result).text();
              try{
                  settings.afterAjaxSuccess();
              }catch (e){
              }
            },
            error: function(){
                try{
                    settings.afterAjaxError();
                }catch (e){
                }
                return false;
            }
        });
        try{
            settings.afterAjax();
        }catch (e){
        }
        result = result.replace("\r",'');
        result = result.replace("\n",'');
        if(result.length > 0){
            $targetElm.html(result);
            if(!$targetElm.is(':visible'))
                $targetElm.show();
            $targetElm.focus();
        }else{
            $targetElm.html(result);
            if($targetElm.get(0).tagName.toLowerCase() != 'select')
                $targetElm.hide();
        }
        return true;
    }catch(e){
    }
    return false;
}

function updateMyaccountFavoriteOffersCount(newCount){
    $('.myaccountFavoriteOffersCount').html(parseInt(newCount));
}

/**
 * Making offer favorited at offer list.
 */
$(document).ready(function(){
   $('.star').click(function(){
       var starIcon = $(this);
       var offerId = parseInt(starIcon.attr('rel'));
       if (offerId <= 0) {
           return false;
       }
       if (starIcon.hasClass('starLoading')) {
           return false;
       }
       var starIcons = $('.star[rel="' + offerId + '"]');//all stars related to same offers
       params = 'id=' + offerId;
       $.ajax({
            type: 'GET',
            timeout: 30000,
            url: '/ajax/myaccountfavorite/',
            data: params,
            async: true,
            global: false,
            dataType: 'xml',
            beforeSend: function(){
                starIcons.addClass('starLoading');
            },
            complete: function(){
                starIcons.removeClass('starLoading');
            },
            success: function(response) {
                var result = $('result', response).text();
                if(result == '') {
                    return false;
                } else if (result == 'unknown_offer') {
                    return false;
                } else {
                    if(result == 'not_logged') {
                        window.location.href = '/myaccount/login/';
                    } else if(result == 'removed') {
                        starIcons.removeClass('starActive').attr('title', 'přidat do oblíbených nabídek');
                    } else if(result == 'added') {
                        starIcons.addClass('starActive').attr('title', 'odebrat z oblíbených nabídek');
                    }
                    if($('offersFavoritedCount', response).text() != '') {
                        updateMyaccountFavoriteOffersCount($('offersFavoritedCount', response).text());
                    }
                }
            },
            error: function(err){
                if ((err.status != 200) && (typeof(err.statusText) != 'undefined') && (err.statusText != '')) {
                   alert(err.statusText);
                }
                return false;
            }
       });
       return false;
   });
});

/**
 * Refresh captcha image on registration page.
 */
$(document).ready(function(){
   $('.register a#refresh_captcha').unbind('click').click(function(){
    	formVars = {};
        formVars['random'] = new Date().getTime();
        ajaxUrl = '/ajax/myaccountregistercaptcha/';
        /*ajaxUrl = '/specific/ajax/myaccountregistercaptcha/';
        if (typeof(languageCode) != 'undefined')
            ajaxUrl = '/' + languageCode + ajaxUrl;*/
    	$.ajax({
            type: 'POST',
            timeout: 30,
            url: ajaxUrl,
            data: formVars,
            async: false,
            dataType: 'xml',
            success: function(xmlResponse){
                if ($('response', xmlResponse).length <= 0) {
                    return false;
                } else {
                    if ($('imageUrl', xmlResponse).length > 0) {
                       $('#captcha_image').attr('src', '/data/captcha/' + $('imageUrl', xmlResponse).text() + '.png');
                    }
                }
            },
            error: function(err){
                if ((err.status != 200) && (typeof(err.statusText) != 'undefined') && (err.statusText != '')) {
                   alert(err.statusText);
                }
                return false;
            }
        });
    	return false;
    });
});

/**
 * Refresh captcha image on forgot pass page.
 */
$(document).ready(function(){
   $('.offerForm a#refresh_captcha').unbind('click').click(function(){
    	formVars = {};
        formVars['random'] = new Date().getTime();
        ajaxUrl = '/ajax/myaccountforgotpasscaptcha/';
        /*ajaxUrl = '/specific/ajax/myaccountforgotpasscaptcha/';
        if (typeof(languageCode) != 'undefined')
            ajaxUrl = '/' + languageCode + ajaxUrl;*/
    	$.ajax({
            type: 'POST',
            timeout: 30,
            url: ajaxUrl,
            data: formVars,
            async: false,
            dataType: 'xml',
            success: function(xmlResponse){
                if ($('response', xmlResponse).length <= 0) {
                    return false;
                } else {
                    if ($('imageUrl', xmlResponse).length > 0) {
                       $('#captcha_image').attr('src', '/data/captcha/' + $('imageUrl', xmlResponse).text() + '.png');
                    }
                }
            },
            error: function(err){
                if ((err.status != 200) && (typeof(err.statusText) != 'undefined') && (err.statusText != '')) {
                   alert(err.statusText);
                }
                return false;
            }
        });
    	return false;
    });
});

/* Autosuggest in demand form */
$(document).ready(function(){

    if (typeof($.fn.autoSuggest) == 'function') {

        var autoSuggestOptions = {
            selectedItemProp: "name",
            searchObjProps: "name",
            queryParam : 'string',
            minChars: 2,
            startText: "Zadejte město, okres nebo kraj",
            emptyText: "Žádný záznam",
            retrieveLimit : 10,
            asHtmlID : 11
        };

        $('.demandForm .as-selections input[type=text]').autoSuggest('/ajax/autosuggest/', autoSuggestOptions);

        $('a.as-close').click(function(){
            var value = $(this).prev().val();

            $('.as-values').val($('.as-values').val().replace(value + ",", ""));
            $('.as-input').focus();

            $(this).parent().remove();

            autoSuggestInput.reset();
            return false;
        });

    }

});

/**
 * Demand form estate types and subestate types handlers
 */
$(document).ready(function(){

    $('.demandForm #estateTypesHolder #subEstateTypesHolder div').hide();

    $('.demandForm #estateTypesHolder input:radio').click(function(){
        $myDiv = $('#subEstateTypesHolder div#' + $(this).attr('rel'));
        $visibleDiv = $('#subEstateTypesHolder div:visible');
        if ($myDiv.length == 0) {
            return false;
        }
        if ($visibleDiv.length > 0) {
            $visibleDiv.slideUp(200, function(){
                $(this).find('input:checkbox').removeAttr('checked');
                $myDiv.slideDown(200);
            });
        } else {
            $myDiv.slideDown(200);
        }

    });

});

/**
 * Offer form location selectors handlers
 */
$(document).ready(function(){

    $('.offerForm select#district').change(function(){
       $(this).updateTargetWithAction({
            action: '/ajax/myaccount/?ajaxAction=provideCities',
            targetElm: '#city',
            afterAjax: function(){
                $('#neighbourhood, #street, #postal_code, #cadastral_area').html('');
                $('#land_registry_number, #street_number').val('');
            }
        });
    });

    $('.offerForm select#city').change(function(){
        $(this).updateTargetWithAction({
            action: '/ajax/myaccount/?ajaxAction=provideNeighbourhoods',
            targetElm: '#neighbourhood',
            afterAjax: function(){
                $('#street, #postal_code, #cadastral_area').html('');
                $('#land_registry_number, #street_number').val('');
            }
        });
        $(this).updateTargetWithAction({
            action: '/ajax/myaccount/?ajaxAction=provideStreets',
            targetElm: '#street',
            afterAjax: function(){
                $('#postal_code, #cadastral_area').html('');
                $('#land_registry_number, #street_number').val('');
            }
        });
        if ($('#street option').length == 0) {
            $('#street_name_cover').show();
        } else {
            $('#street_name_cover').hide();
        }
        $(this).updateTargetWithAction({
            action: '/ajax/myaccount/?ajaxAction=provideCadastralAreas',
            targetElm: '#cadastral_area'
        });
    });

    $('.offerForm select#neighbourhood').change(function(){
        $(this).updateTargetWithAction({
            action: '/ajax/myaccount/?ajaxAction=providePostalCodes',
            targetElm: '#postal_code',
            addToParams: 'neighbourhood_id=neighbourhood,street_id=street'
        });
        /*if ($('#postal_code option').length == 0) {
            $('#postal_code_manual_cover').show();
        } else {
            $('#postal_code_manual_cover').hide();
        }*/
    });

    $('.offerForm select#street').change(function(){
        $(this).updateTargetWithAction({
            action: '/ajax/myaccount/?ajaxAction=providePostalCodes',
            targetElm: '#postal_code',
            addToParams: 'neighbourhood_id=neighbourhood,street_id=street'
        });
        if ($('#postal_code option').length == 0) {
            $('#postal_code_manual_cover').show();
        } else {
            $('#postal_code_manual_cover').hide();
        }
    });

});

/**
 * Hiding some fields in offer form - based on estate type id
 */
var blocks = new Array();

// KOMERCE
blocks[2]  = new Array('construction_type', 'balcony_type', 'object_location', 'total_area', 'usable_area',
                       'garden_area');
// POZEMKY
blocks[4]  = new Array('object_location', 'total_area');
// DOMY
blocks[10] = new Array('construction_type', 'balcony_type', 'object_location', 'object_situation', 'total_area',
                       'usable_area', 'garden_area');
// BYTY
blocks[11] = new Array('object_ownership', 'construction_type', 'balcony_type', 'object_location', 'total_area',
                       'usable_area', 'garden_area', 'annuity');
// GARAZE
blocks[203] = new Array('construction_type', 'balcony_type', 'object_situation', 'object_location', 'total_area',
                        'usable_area', 'garden_area');
//Sklady
blocks[213] = new Array('construction_type', 'object_location', 'total_area', 'usable_area', 'garden_area');
$(document).ready(function(){
    $('.offerForm select#estate_type').change(function(){
        var estateBlocks;
        estateTypeId = $(this).val();
        if ((typeof(blocks[estateTypeId]) == 'object') && (blocks[estateTypeId] instanceof Array)) {
            estateBlocks = blocks[estateTypeId];
        } else {
            estateTypeId = $(this).find(':selected').parent().attr('rel');
            if ((typeof(blocks[estateTypeId]) == 'object') && (blocks[estateTypeId] instanceof Array)) {
                estateBlocks = blocks[estateTypeId];
            } else {
                return false;
            }
        }

        $('.estateTypeToggle').each(function(i, elm) {
            found = false;
            for (i in estateBlocks) {
                if (!found && ($(elm).find('#' + estateBlocks[i]).length > 0)) {
                    found = true;
                }
            }
            if (!found) {
                $(elm).hide();
                $(elm).find("input:text").val('');
                $(elm).find("input:checkbox").removeAttr('checked');
                $(elm).find("option").removeAttr('selected')
                                     .find('option:first').attr('selected','selected');
                $(elm).find("input").attr('disabled','disabled');
                $(elm).find("select").attr('disabled','disabled');
            } else {
                $(elm).find("input").removeAttr('disabled');
                $(elm).find("select").removeAttr('disabled');
                $(elm).show();
            }
        });
    });

    $('.offerForm select#estate_type').trigger('change');
});

/**
 * Login form toggler for register form
 */
/*$(document).ready(function(){
	$("#newRegister").click(function(){
		$('.registerBlocks').slideToggle();
		return false;
	});
});*/

/**
 * Show captcha block after input above is focused
 */
$(function(){
	$('.registerForm .captchaBlock').css('display','none');
	$('.registerForm input.text').focus(function(){
		$('.registerForm .captchaBlock').slideDown(500);
	})
});

/**
 * How to pay offer help
 */
$(function(){
	if ($('a.howToPayOffer').length > 0) {
		$('a.howToPayOffer').fancybox();
	}
});
