function createCarousel() {
    //xxx it seems to be hard-coded
    var index_carousel = 0;
    var num_carousel_pages =  Math.ceil($(".carousel_element_holder > .tinyPropertyBlock").length / 2) + 0;
    var item_width = $(".carousel_element_holder > .tinyPropertyBlock").width();
    var pages_buttons = '';
    for(i = 0;i < num_carousel_pages; i++) {pages_buttons += (i == 0)?'<a href="#" class="carousel_button active">'+ i +'</a>':'<a href="#" class="carousel_button">' + i + '</a>'}
    $("h1.carousel").append('<div class="carousel_nav_holder">' + pages_buttons + '</div>');
    $("div.carousel").append('<a href="#" class="carousel_nav left">&lt;</a><a href="#" class="carousel_nav right">&gt;</a>');

    /* live click on input-like href*/
    $(".carousel_button").live("click", function(e){
        e.preventDefault();
        $(".carousel_button").removeClass("active");
        $(this).addClass("active");
        index_carousel = $(".carousel_button").index($(this));
        $(".carousel_element_holder").stop().animate({"left": (index_carousel * (-(item_width*2 + 20))) + "px"}, 1200);
    })
    /* live click on buttons "left" and  "right"*/
    $(".carousel_nav").live("click", function(e){
        e.preventDefault();
        if (index_carousel != (num_carousel_pages-1) && index_carousel != 0) {
            index_carousel = ($(this).hasClass("left"))?index_carousel-1:index_carousel+1;				
        } else if (index_carousel == 0) {
            index_carousel = ($(this).hasClass("left"))?num_carousel_pages-1:index_carousel+1;
        } else {
            index_carousel = ($(this).hasClass("left"))?index_carousel-1:0;
        }
        $(".carousel_button").removeClass("active");
        $(".carousel_button").eq(index_carousel).addClass("active");
        $(".carousel_element_holder").stop().animate({"left": (index_carousel * (-(item_width*2 + 20))) + "px"}, 1200);			
    })
}

function createSliders() {
    //actually create sliders
    $('.sliderbody').each( function(){
        createSlider( $(this).attr('id') );
    });
    
    // add custom left-right arrows for sliders
    $(".ui-slider").each( function() {
        var a = $(this).children('a');
        a.eq(0).addClass("left-arrow");
        a.eq(1).addClass("right-arrow");
    });

}

function createSlider( baseId ) {
	var 
        max = parseInt( $('#'+baseId+'-max').val(), 10),
        min = parseInt( $('#'+baseId+'-min').val(), 10),
        left  = $('#'+baseId+'-left').length  ? parseInt( $('#'+baseId+'-left').val(),  10) : min,
        right = $('#'+baseId+'-right').length ? parseInt( $('#'+baseId+'-right').val(), 10) : max;
    

    $( '#'+baseId ).slider({
            range: true,
            min: min,
            max: max,
            values: [ left, right ],
            slide: function(event, ui) {
                $('#'+baseId+'-left').val( ui.values[0] );
                $('#'+baseId+'-right').val( ui.values[1] );
            }
        });
    
    $( 'input#'+baseId+'-left' ).change( function(event) {
        var val = parseInt( $(this).val(), 10);
        if( val > parseInt( $('input#'+baseId+'-right').val(), 10) ) return;
        $('#'+baseId).slider( 'values' , 0, val );
    });

    $( 'input#'+baseId+'-right' ).change( function(event) {
        var val = parseInt( $(this).val(), 10);
        if( val < parseInt( $('input#'+baseId+'-left').val(), 10) ) return;
        $('#'+baseId).slider( 'values' , 1, val );
    });

}

function send_to_friend() {
    var fields = {
        'sendf_name': 'Please enter your name',
        'sendf_email': 'Please enter your e-mail address',
        'sendf_fremail': 'Please enter your friend\'s  e-mail address',
        'sendf_mes': 'Don\'t you want to add a note?'
    }
    
    var data = { 'id': $('#sendf_id').val() };
    
    for( var id in fields ) {
        var inp = $( '#' + id );
        var val = jQuery.trim( inp.val() );
        if( '' == val ) {
            var msg = lang(fields[id]);
            inp.focus();
            alert( msg );
            return false;
        }
        data[id] = val;
    }
    
    var url = '/ajax/send-to-friend/';
    
    $.post( url, data, function ( response, status ) {
		if (status != 'success') return;
        
		if ( !response ) {
            alert('An error occurred. Try again later.');
            return;
        }
        
		if ( !response.ok ) {
            alert(response.msg);
            return;
        }
        
        $('#send_friend_content').slideUp('fast');
        $('#send_friend_email_value').html(data['sendf_fremail']);
        $('#send_friend_sent').fadeIn('fast');
	}, 'json');

    return true;
}


var WaitDialog = {
    show: function(){
        if (!$("#message_holder").length){
            $("body").prepend('<div id="message_holder" style="height:' + $("body").height() + 'px"><div class="message_box"></div></div>');
        $(".message_box").empty();
        
        $(".message_box").append('<img width="273" height="72" alt="SunnyRentals" src="/images/i/logo.gif"/><br /><div id="progressbar"></div><p>'+
            lang('Updating search results') +
            '</p><a href="#" class="message_cancel" id="message_box_close" onclick="RefineResults.isCancelled = true; WaitDialog.hide(); return false;">'+
            lang('Cancel')+'</a>');
        }
        
        
        var pb = $("#progressbar");
        if( pb.length && pb.progressbar) {
            pb.progressbar({value: 100});
        }
        $("#message_holder").fadeIn("fast");
    
    },
    hide: function(){
        $("#message_holder").fadeOut("fast");
    }
}

function createCurrencySwitch() {
    $("#currency_select").bind("click",function(e){	
        if ($(".cur").css('display') == 'none') {			
            $(".holder_inv").slideUp('fast');
            $(".cur").slideDown('fast');
        } else {
            $(".holder_inv").slideUp('fast');
        }
    })
}

function createLanguageSwitch() {
    $("#country_select").bind("click",function(e){
        if ($(".country").css('display') == 'none') {			
            $(".holder_inv").slideUp('fast');
            $(".country").slideDown('fast');
        } else {
            $(".holder_inv").slideUp('fast');
        }
    })
}


function isIE6() {
    return (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1 && navigator.appVersion.indexOf("MSIE 8.0") == -1);
}

function construct_ul(data, name, level, country_name) {
    var temp = '';	
    var prefixes = [ 'co', 'ct', 'r', 'a', 's', 't' ];
    if ($(data).length){
        $(data).each(function(e,i){  //XXX can be done without (anonymous) functions
            var prop_class = ((e%2) == 1)?'class="second"':'';
            if( null == i.name ) return;
            temp += '<li ' + prop_class + '><a href="/' + window.languageCode + '/search/' + 
                ( null != country_name ? tokenize(country_name) + '/' : '' ) + 
                tokenize(i.name) + '/' + 
                prefixes[level] + i.id + '">' + 
                i.name +  '</a></li>';
        })
        if (temp != '') {
            if ($("ul." + name).length){
                $("ul." + name).html(temp);
            }  else {
                $("#wrapper").append("<ul class=\"holder_inv " + name +"\">" + temp + "</ul>");
            }
            if (jQuery.browser.msie && (isIE6()) && ($("ul." + name).height() > 300)) {
              $("ul." + name).css("height","300px");
            }
        }
    }
}

function breadcrump_li_click(element, parent_breadcrump_id) {
    $(element).live("click",function(){
        href = $(this).children('a:first').attr('href');
        $(".holder_inv").slideUp('fast');
    })
}



function breadcrump_element_click(element_id, child_ul) {
    $(element_id).click(function(){
        if ($(child_ul).css('display') == 'none') {			
            $(".holder_inv").slideUp('fast');
            $(child_ul).css("left",$(element_id).offset().left - $(".breadcrumbs").offset().left + 35).css("top",$(element_id).offset().top - $(".breadcrumbs").offset().top + 35).slideDown('fast');
            if (jQuery.browser.msie && (isIE6())) {
                $(".content select, .content object, .content input").css("visibility","hidden");
            }
        } else {
            $(".holder_inv").slideUp('fast');
            if (jQuery.browser.msie && (isIE6())) {
                $(".content select, .content object, .content input").css("visibility","visible");
            }
        }
    })
}

function createGeoBreadcrumbs(geo, country_name) {
	construct_ul(geo['continents'],"continent_ajax_holder", 0);
	
	construct_ul(geo['countries'], "country_ajax_holder", 1);
	construct_ul(geo['regions'], "region_ajax_holder", 2, country_name);
	construct_ul(geo['areas'], "area_ajax_holder", 3, country_name);
	construct_ul(geo['subareas'], "subarea_ajax_holder", 4, country_name);
	construct_ul(geo['cities'], "city_ajax_holder", 5, country_name);
    
	breadcrump_element_click("#bc_continent",".continent_ajax_holder");
	breadcrump_element_click("#bc_country",".country_ajax_holder");
	breadcrump_element_click("#bc_region",".region_ajax_holder");
	breadcrump_element_click("#bc_area",".area_ajax_holder");
	breadcrump_element_click("#bc_subarea",".subarea_ajax_holder");
	breadcrump_element_click("#bc_city",".city_ajax_holder");
    
	breadcrump_li_click(".continent_ajax_holder > li", "bc_continent");
	breadcrump_li_click(".country_ajax_holder > li", "bc_country");
	breadcrump_li_click(".region_ajax_holder > li", "bc_region");
	breadcrump_li_click(".area_ajax_holder > li", "bc_area");
	breadcrump_li_click(".subarea_ajax_holder > li", "bc_subarea");
	breadcrump_li_click(".city_ajax_holder > li", "bc_city");
}

function getCountriesPhones(){
    return {"AF":"93","AX":"+358-18","AL":"355","DZ":"213","AS":"+1-684","AD":"376","AO":"244","AI":"+1-264","AQ":"","AG":"+1-268","AR":"54","AM":"374","AW":"297","AU":"61","AT":"43","AZ":"994","BS":"+1-242","BH":"973","BD":"880","BB":"+1-246","BY":"375","BE":"32","BZ":"501","BJ":"229","BM":"+1-441","BT":"975","BO":"591","BA":"387","BW":"267","BV":"","BR":"55","IO":"246","VG":"+1-284","BN":"673","BG":"359","BF":"226","BI":"257","KH":"855","CM":"237","CA":"1","CV":"238","KY":"+1-345","CF":"236","TD":"235","CL":"56","CN":"86","CX":"61","CC":"61","CO":"57","KM":"269","CK":"682","CR":"506","HR":"385","CU":"53","CY":"357","CZ":"420","CD":"243","DK":"45","DJ":"253","DM":"+1-767","DO":"+1-809","TL":"670","EC":"593","EG":"20","SV":"503","GQ":"240","ER":"291","EE":"372","ET":"251","FK":"500","FO":"298","FJ":"679","FI":"358","FR":"33","GF":"594","PF":"689","TF":"","GA":"241","GM":"220","GE":"995","DE":"49","GH":"233","GI":"350","GR":"30","GL":"299","GD":"+1-473","GP":"590","GU":"+1-671","GT":"502","GG":"+44-1481","GN":"224","GW":"245","GY":"592","HT":"509","HM":" ","HN":"504","HK":"852","HU":"36","IS":"354","IN":"91","ID":"62","IR":"98","IQ":"964","IE":"353","IM":"+44-1624","IL":"972","IT":"39","CI":"225","JM":"+1-876","JP":"81","JE":"+44-1534","JO":"962","KZ":"7","KE":"254","KI":"686","KW":"965","KG":"996","LA":"856","LV":"371","LB":"961","LS":"266","LR":"231","LY":"218","LI":"423","LT":"370","LU":"352","MO":"853","MK":"389","MG":"261","MW":"265","MY":"60","MV":"960","ML":"223","MT":"356","MH":"692","MQ":"596","MR":"222","MU":"230","YT":"269","MX":"52","FM":"691","MD":"373","MC":"377","MN":"976","ME":"381","MS":"+1-664","MA":"212","MZ":"258","MM":"95","NA":"264","NR":"674","NP":"977","NL":"31","AN":"599","NC":"687","NZ":"64","NI":"505","NE":"227","NG":"234","NU":"683","NF":"672","KP":"850","MP":"+1-670","NO":"47","OM":"968","PK":"92","PW":"680","PS":"970","PA":"507","PG":"675","PY":"595","PE":"51","PH":"63","PN":"","PL":"48","PT":"351","PR":"+1-787","QA":"974","CG":"242","RE":"262","RO":"40","RU":"7","RW":"250","BL":"590","SH":"290","KN":"+1-869","LC":"+1-758","MF":"590","PM":"508","VC":"+1-784","WS":"685","SM":"378","ST":"239","SA":"966","SN":"221","RS":"381","CS":"+381","SC":"248","SL":"232","SG":"65","SK":"421","SI":"386","SB":"677","SO":"252","ZA":"27","GS":"","KR":"82","ES":"34","LK":"94","SD":"249","SR":"597","SJ":"47","SZ":"268","SE":"46","CH":"41","SY":"963","TW":"886","TJ":"992","TZ":"255","TH":"66","TG":"228","TK":"690","TO":"676","TT":"+1-868","TN":"216","TR":"90","TM":"993","TC":"+1-649","TV":"688","VI":"+1-340","UG":"256","UA":"380","AE":"971","GB":"44","US":"1","UM":"","UY":"598","UZ":"998","VU":"678","VA":"379","VE":"58","VN":"84","WF":"681","EH":"212","YE":"967","ZM":"260","ZW":"263"};;
}

//lowercased URL-friendly string
function tokenize(str) {
    return str.toLowerCase().replace(/[ \'\,]/g, '-').replace(/\-\-/g, '-');
}

function formatSuggestItem(row) {
    return row;
}

function initLocationSuggestForm() {
	$('#se_location').autocomplete('/ajax/location/', {
        'delay': 10,
        'minCahrs': 1,
        'matchSubset': 0,
        'matchContains': 0, 
        'cacheLength': 100, 
        'json': true, 
        'width': 300, 
        'loadingClass':'loadingSuggestionG', 
        //'formatItem': formatSuggestItem, 
        'onSelect':searchFormSelected, 
        'onChange':function(){ $('#se_id').attr ('value', ''); $('#se_level').attr ('value', '');}
    });
	
	$('#se_location').keydown (function (e) {
		var lastKeyCode = e.keyCode;
		if (lastKeyCode != 38 && lastKeyCode != 40 && lastKeyCode != 9 && lastKeyCode != 13) {
			$('#se_id').attr ('value', ''); 
			$('#se_level').attr ('value', '');
		}
	});
    
	if ($('#se_location').val () == '') {
    	$('#se_location').example(lang('Country or town'));
    }
    
    $('#se_form').bind('submit', function () {
        if( $('#se_location').hasClass('example') || ('' == jQuery.trim( $('#se_location').val()) ) ) {
            return false;
        }
            
        var id = parseInt( $('#se_id').val(), 10 );
        if( id > 0 ) {
            var list = [window.languageCode, 'search'];
            
            if( $('#se_country').val() ) {
                list.push( tokenize( $('#se_country').val() )  );
            }
            
            var admPresent = ('' != $('#se_adm').val() );
            if( admPresent ) {
                list.push( tokenize( $('#se_adm').val() ) );
            }
            
            if( $('#se_location').val() ) {
                list.push( tokenize( $('#se_location').val() ) );
            }
            
            var levelCodes = getGeoLevelsCodes();
            var level = parseInt($('#se_level').val(), 10);
            list.push( levelCodes[level] + id );
            
            top.document.location.href = '/' + list.join('/');
            return false;
        }
        return true;
    });
}


var DetailedSearch = {
    apartmentTypes: [],
    
    preLoad : function() {
        $('#detailed-search-ajax-loader').show();
    },
    
    postLoad : function() {
        $('#detailed-search-ajax-loader').hide();
    },
    
    onSubmit: function() {
        if( !DetailedSearch.checkCountrySelected() ) {
            return false;
        }
        
        if( 0 == $('#apartment-type').val() ) {
            $('#apartment-type').attr('disabled', 1);
        }
    },
    
    checkCountrySelected: function() {
        var country_id = $('#country-select').val();
        if( 0 == country_id || null === country_id ) {
            alert('Please select a country');
            $('#country-select').focus();
            return false;
        }
        return true;
    },
    
    countryChanged : function() {
        var country_id = $('#country-select').val();
        if( 0 == country_id || null === country_id ) {
            $('#region-select').empty().attr('disabled', 1);
            $('#city-select').empty().attr('disabled', 1);
            return false;
        }
        var countryName = $('#country-select option:selected').text();
        
        DetailedSearch.preLoad();
        $('form#detailed-search').attr( 'action', '/search/' + tokenize(countryName) + '/c' +  country_id );
        $('#region-select').val(0).attr('disabled', 1);
        $('#city-select').val(0).attr('disabled', 1);
        $.getJSON('/ajax/get-country-regions', {'country-id': country_id}, function (data, status) {
                DetailedSearch.postLoad();
                
                if ( 'success' != status) return;
                
                $('#region-select').empty().append('<option value="0">- ' + lang('select') + ' -</option>');
                for(var i in data.list) {
                    $('#region-select').append('<option value="' + i + '">' + data.list[i] + '</option>')
                }
                $('#region-select').attr('disabled', 0);
                
                $('#apartment-type').val(0);
                
                //initialization of the apartment types list
                if( !DetailedSearch.apartmentTypes.length ) {
                    $('#apartment-type option').each(function(){
                        DetailedSearch.apartmentTypes.push( $(this).text() );
                    });
                }
                
                $('#apartment-type option[value!=0]').each(function(){
                    $(this).remove();
                });
                
                for(var i in data.types) {
                    i = parseInt( i, 10 );
                    $('#apartment-type').append('<option value="'+i+'">' + DetailedSearch.apartmentTypes[i] + '</option>' );
                }
            }
        );

    },
    
    regionChanged : function() {
        var country_id = $('#country-select').val();
        var region_id = $('#region-select').val();
        if( 0 == region_id || null === region_id || 0 == country_id || null === country_id) {
            $('#city-select').empty().attr('disabled', 1);
            return false;
        }
        var countryName = $('#country-select option:selected').text();
        var regionName  = $('#region-select  option:selected').text();
        
        DetailedSearch.preLoad();
        $('form#detailed-search').attr( 'action', '/search/'+tokenize(countryName)+'/'+tokenize(regionName)+'/r' +  region_id );
        $('#city-select').val(0).attr('disabled', 1);
        $.getJSON('/ajax/get-region-cities', {'region-id': region_id, 'country-id': country_id}, function (data, status) {
                DetailedSearch.postLoad();
                
                if ( 'success' != status) return;
                
                $('#city-select').empty().append('<option value="0">- ' + lang('select') + ' -</option>');
                for(var i in data.list) {
                    $('#city-select').append('<option value="' + i + '">' + data.list[i] + '</option>')
                }
                $('#city-select').attr('disabled', 0);
                
                $('#apartment-type').val(0);
                $('#apartment-type option[value!=0]').each(function(){
                    $(this).remove();
                });
                
                for(var i in data.types) {
                    i = parseInt( i, 10 );
                    $('#apartment-type').append('<option value="'+i+'">' + DetailedSearch.apartmentTypes[i] + '</option>' );
                }
            }
        );

    },
    
    cityChanged : function() {
        var city_id    = $('#city-select').val();
        var country_id = $('#country-select').val();
        var region_id = $('#region-select').val();
        if( 0 == region_id || null === region_id || 0 == country_id || null === country_id || 0 == city_id || null === city_id ) {
            return false;
        }
        var countryName = $('#country-select option:selected').text();
        var regionName  = $('#region-select  option:selected').text();
        var cityName    = $('#city-select    option:selected').text();
        
        DetailedSearch.preLoad();
        $('form#detailed-search').attr( 'action', '/search/'+tokenize(countryName)+'/'+tokenize(regionName)+'/'+tokenize(cityName)+'/t' +  city_id );
        $.getJSON('/ajax/get-city-data', {'city-id': city_id}, function (data, status) {
                DetailedSearch.postLoad();
                
                if ( 'success' != status) return;
                
                $('#apartment-type').val(0);
                $('#apartment-type option[value!=0]').each(function(){
                    $(this).remove();
                });
                
                for(var i in data.types) {
                    i = parseInt( i, 10 );
                    $('#apartment-type').append('<option value="'+i+'">' + DetailedSearch.apartmentTypes[i] + '</option>' );
                }

            }
        );
        DetailedSearch.postLoad();
    }
};

