/// <reference path="js/jquery.intellisense.js"/>
$(document).ready(function() {

    if ($('#place_canvas').length > 0) {
        if (($('#place_canvas a.lat').length > 0) && ($('#place_canvas a.lon').length > 0)) { //deal with coords
            showPoint($('#place_canvas a.lat').attr('rel'), $('#place_canvas a.lon').attr('rel'), 13, 'place_canvas');
        } else { //deal with addr
            showAddress($('#place_canvas').text(), 'place_canvas', 13);
        }
    }

    if ($('#destMapHolder').length > 0) {
        $('#destGmap').css('background-color', 'none');
        if (($('#ctl00_mainContent_latitude').attr('value')) && ($('#ctl00_mainContent_longitude').attr('value')))
            loadMap($('#ctl00_mainContent_latitude').attr('value'), $('#ctl00_mainContent_longitude').attr('value'));
        else
            loadMap(55.75320187033113, 37.60963439941406);
    }

    if ($('#ctl00_mainContent_cityText').length > 0) {
        //        //$("#input_box").autocomplete("autocomplete_ajax.cfm");

        $('#ctl00_mainContent_region').bind('change', function() {
            if ($('#ctl00_mainContent_region').find('option[@selected]').attr('value'))
                regions.GetAutoCities($('#ctl00_mainContent_region').find('option[@selected]').attr('value'), onGetCitiesSuccess);
        });
        if ($('#ctl00_mainContent_region').find('option[@selected]').attr('value'))
            regions.GetAutoCities($('#ctl00_mainContent_region').find('option[@selected]').attr('value'), onGetCitiesSuccess);
    }

    /*
    $('#myContactsShow').bind('click', function() {
        $('#myContactsHolder').slideDown('fast');
        $(this).hide();
        return false;
    });
    */

    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function(elt) {
            var len = this.length;
            var from = Number(arguments[1]) || 0;
            from = (from < 0) ? Math.ceil(from) : Math.floor(from);
            if (from < 0) from += len;
            for (; from < len; from++) {
                if (from in this && this[from] === elt) return from;
            }
            return -1;
        }
	;
    }

    $('.filter-header a').toggle(function() {
        $('.filter-body').show();
        $(this).text('Скрыть фильтр');
        return false;
    }, function() {
        $('.filter-body').hide();
        $(this).text('Показать фильтр');
        return false;
    });

    var manager = [];

    $('body').append('<div id="links"></div>');

    // Remove the default value of text input

    //    $('input[type="text"]').change(function() {
    //        if($(this).hasClass('changed')) {}
    //        else { $(this).addClass('changed'); }   
    //    });
    //    
    //    $('input[type="text"]').focus(function() {
    //       if ($(this).hasClass('changed') == false) {
    //            $(this).attr('value', '');
    //        }
    //    });

    $('#mainContent .accordion').Accordion(
	{
	    header: 'a.title',
	    active: '.selected',
	    selectedClass: 'active',
	    alwaysOpen: false,
	    animated: false
	});

    $('#secondaryContent .block').each(function() {
        var id = $(this).attr('id');
        var cookie = $.cookie(id);
        if (cookie != null) {
            $(this).addClass('collapsed');
            $('.content', $(this)).hide();
            $('a.trigger', this).text('Развернуть');
        }
    });

    $('#searchForm .tabs a').bind('click', function() {
        $(this).blur();
        $('#searchForm .tabs div').removeClass();
        $(this).parent('div').addClass('here');
        var offerType = $(this).attr('rel');
        $('#dealType').attr('value', offerType);
        if (offerType == 'sale') {
            $('#buyPrices').show();
            $('#rentPrices').hide();
        } else {
            $('#buyPrices').hide();
            $('#rentPrices').show();
        }
        return false;
    });

    $('#search .searchInfo a.switcher').toggle(
            function() {
                $(this).blur();
                $('#searchWrap').removeClass();
                $('#searchWrap').addClass('expanded');
                var offerType = $('#dealType').attr('value');
                $('#searchForm .tabs div').removeClass();
                if (offerType == 'sale') {
                    $("#searchForm .tabs a[@rel='sale']").parent('div').addClass('here');
                    $('#buyPrices').show();
                    $('#rentPrices').hide();
                } else {
                    $("#searchForm .tabs a[@rel='rent']").parent('div').addClass('here');
                    $('#buyPrices').hide();
                    $('#rentPrices').show();
                }
                $('#searchForm').show();
                return false;
            },
            function() {
                $(this).blur();
                $('#searchWrap').removeClass();
                $('#searchWrap').addClass('collapsed');
                $('#searchForm').css({ "display": "none" });
                return false;
            }
        );

    // Display a shout :)

    var noShout = $('#content').hasClass('noshout');
    if ((noShout != true) && ($.cookie("shout") != 'collapsed')) {
        Shout.GetShout(OnShoutSuccess, OnShoutFailed);
    }

    //    $('#searchBox a.login').bind('click', function() {
    //               $(this).blur();
    //               $('#container').prepend('<div id="bigWrapper"></div>');
    //               $('#bigWrapper').css({"opacity" : "0.5"});
    //               $.ajax(
    //                       {
    //                           url: this.href,
    //                           async: true,
    //                           cache: false,
    //                           success: function(html) {
    //                               $('#container').prepend('<div id="auth"></div>');
    //                               $('#auth').html(html);
    //                               $('#auth a.submit').bind('click', function() {
    //                                       $(this).parents('form').submit();
    //                                       $.cookie('logged_in', 'true');
    //                                       $.cookie('user', $('#auth #login').attr('value'));
    //                                       return false;
    //                                   }
    //                               );
    //                               $('#auth a.close').bind('click', function() {
    //                                       $(this).blur();
    //                                       $('#auth, #bigWrapper').remove();
    //                                       return false;
    //                                   }
    //                               );
    //                           }
    //                       }
    //                      ); // ajax
    //               
    //               return false;
    //           }                           
    //       );

    //	$.getJSON("/domaplanety/shout.js", function(json) {
    //	        var count = 0;
    //            // please-please-please, rewrite this
    //	        $.each(json.items, function(i, item) {
    //	            count++;
    //	        });
    //	        var rand_no = Math.floor(count*Math.random());
    //	        $('#shout .right').html(json.items[rand_no]);
    //	        $('#shout .right').append('<a href="#" class="close">Закрыть</a>');

    //            $('#shout a.switcher').toggle( 
    //                function() {
    //                    $(this).blur();
    //                    $('#searchWrap').removeClass();
    //                    $('#searchWrap').addClass('expanded'); 
    //                    $('#searchWrap').animate({
    //                        height : "275px"
    //                    }, { "duration" : "fast" });
    //                    $('#searchForm').fadeIn(500);
    //                    return false;
    //                },
    //                function() {
    //                    $(this).blur();
    //                    $('#searchWrap').removeClass();
    //                    $('#searchWrap').addClass('collapsed');
    //                    $('#searchWrap').animate({
    //                        height : "97px"
    //                    }, { "duration" : "slow" });
    //                    $('#searchForm').css({ "display" : "none" });
    //                    return false;
    //                } // a.switcher toogle
    //            );
    //            
    //            $('#shout a.login').bind('click', function() {
    //                   $(this).blur();
    //                   $('#container').prepend('<div id="bigWrapper"></div>');
    //                   $('#bigWrapper').css({"opacity" : "0.5"});
    //                   $.ajax(
    //                           {
    //                               url: this.href,
    //                               async: true,
    //                               cache: false,
    //                               success: function(html) {
    //                                   $('#container').prepend('<div id="auth"></div>');
    //                                   $('#auth').html(html);
    //                                   $('#auth a.submit').bind('click', function() {
    //                                           $(this).parents('form').submit();
    //                                           $.cookie('logged_in', 'true');
    //                                           $.cookie('user', $('#auth #login').attr('value'));
    //                                           return false;
    //                                       }
    //                                   );
    //                                   $('#auth a.close').bind('click', function() {
    //                                           $(this).blur();
    //                                           $('#auth, #bigWrapper').remove();
    //                                           return false;
    //                                       }
    //                                   );
    //                               }
    //                           }
    //                    ); // ajax
    //                   
    //                   return false;
    //               }                           
    //           ); // searchBox toogle()
    //            
    //	        $('#shout a.close').bind('click', function() {
    //					$('#shout').fadeOut(600);
    //					$(this).blur();
    //                    
    //					return false;
    //				}
    //			);
    //	    }
    //	);



    var isLogged = $.cookie('logged_in');
    var userName = $.cookie('user');
    if (isLogged == "true") {
        $('#searchBox .um').html('<span>Здравствуйте,</span> <a href="#" class="user">' + userName + '</a> | <a href="" class="exit">Выход</a>');
        $('#searchBox a.exit').bind('click', function() {
            $(this).blur();
            $.cookie('logged_in', null);
            return this.href;
        }
        );
    }
    // Filter form from toolbar

    $('#mainContent .toolbar .filter a.configure').toggle(
        function() {
            $(this).blur();

            if ($(this).parents('.toolbar').hasClass('toolbar-expanded')) {
                $(this).blur();
                $(this).parents('.toolbar').removeClass('toolbar-expanded');
                return false;
            }
            else {
                $(this).parents('.toolbar').addClass('toolbar-expanded');
                return false;
            }
        },
            function() {
                $(this).blur();
                $(this).parents('.toolbar').removeClass('toolbar-expanded');
                return false;
            }
        );

    $('#mainContent .toolbar .filter a.scrolltop').bind('click', function() {
        $.scrollTo(150, 800, { queue: true });
        $('#mainContent .toolbar').addClass('toolbar-expanded');
        $.ajax({
            url: this.href,
            async: true,
            cache: false,
            success: function(html) {
                $('#mainContent .toolbar .extra').before(html);
            }
        });
        return false;
    });

    // Map behaviour goes here

    $('#expandMap .wrap a.expand').toggle(
		function() {
		    $(this).blur();
		    $('#expandMap div.expand').slideDown(500);
		    $(this).text('Свернуть карту');
		    return false;
		},
		function() {
		    $(this).blur();
		    $('#expandMap div.expand').slideUp(500);
		    $(this).text('Закрыть карту');
		    return false;
		}
	);

    $('#worldMap #map .wrap').append('<div id="highlight"></div>');

    $('#worldMap .tabs a').bind('click', function() {
        $('#worldMap .tabs a').removeClass('here');
        $(this).addClass('here');
        $(this).blur();
        $('#bubble .content').empty();
        $('#bubble').hide();
        $('#bubble').removeClass();
        var id = $(this).attr('id');
        $.ajax({
            url: this.href,
            cache: false,
            async: true,
            success: function(html) {
                $('#worldMap #map .wrap').html(html);
                $('#worldMap #map .wrap').append('<div id="highlight"></div>');
                $.ajax({
                    url: '/domaplanety/ajax/list/' + id + '.html',
                    cache: false,
                    async: true,
                    success: function(html) {
                        $('#listBox .wrap').html(html);
                    } //sucess()
                }); // ajax
                $('#worldMap #map .regions a').bind('click', function() {
                    $(this).blur();
                    // Remove the mouseout/mouseover events and disable regions clicking
                    $('#map .regions a').css({ "display": "none" });
                    $('#worldMap #map .regions a').unbind('mouseover');
                    $('#worldMap #map .regions a').unbind('mouseout');
                    $('#bubble .content').empty();
                    $('#bubble').removeClass();
                    $.ajax({
                        url: this.href,
                        cache: false,
                        async: true,
                        success: function(html) {
                            $('#bubble .content').html(html);
                            $('#bubble a.hide').bind('click', function() {
                                $('#bubble').hide(300);
                                // Bring back the regions mouseover/mouseout events
                                $('#map .regions a').bind('mouseover', function() {
                                    $('#highlight').addClass($(this).attr('id'));
                                });
                                $('#map .regions a').bind('mouseout', function() {
                                    $('#highlight').removeClass();
                                });
                                $('#map .regions a').css({ "display": "block" });
                                $('#highlight').removeClass();
                                return false;
                            }); // a.hide
                            // Display/hide the countries list in #bubble
                            $('#bubble a.list').toggle(
                                function() {
                                    $('#bubble ul.countries').show(200);
                                    $(this).blur();
                                    return false;
                                },
                                function() {
                                    $('#bubble ul.countries').hide(200);
                                    $(this).blur();
                                    return false;
                                }
                            ); // list toggle 
                        } // success function
                    });
                    var position = $(this).attr('id');
                    $('#bubble').addClass(position);
                    $('#bubble').show(300);

                    return false;
                }); // regions a bind function
                $('#worldMap #map .regions a').bind('mouseover', function() {
                    $('#highlight').addClass($(this).attr('id'));
                });
                $('#worldMap #map .regions a').bind('mouseout', function() {
                    $('#highlight').removeClass();
                });
            } // success
        }); // ajax

        return false;
    });

    $('#worldMap #map .regions a').bind('mouseover', function() {
        $('#highlight').addClass($(this).attr('id'));
    });

    $('#worldMap #map .regions a').bind('mouseout', function() {
        $('#highlight').removeClass();
    });

    $('#worldMap #map .regions a').bind('click', function() {
        $(this).blur();
        // Remove the mouseout/mouseover events and disable regions clicking
        $('#map .regions a').css({ "display": "none" });
        $('#worldMap #map .regions a').unbind('mouseover');
        $('#worldMap #map .regions a').unbind('mouseout');
        $('#bubble .content').empty();
        $('#bubble').removeClass();

        $.ajax({
            url: this.href,
            cache: false,
            async: true,
            success: function(html) {
                $('#bubble .content').html(html);
                $('#bubble a.hide').bind('click', function() {
                    $('#bubble').hide(300);
                    // Bring back the regions mouseover/mouseout events
                    $('#map .regions a').bind('mouseover', function() {
                        $('#highlight').addClass($(this).attr('id'));
                    });
                    $('#map .regions a').bind('mouseout', function() {
                        $('#highlight').removeClass();
                    });
                    $('#map .regions a').css({ "display": "block" });
                    $('#highlight').removeClass();
                    return false;
                }); // a.hide
                // Display/hide the countries list in #bubble
                $('#bubble a.list').toggle(
                    function() {
                        $('#bubble ul.countries').show(200);
                        $(this).blur();
                        return false;
                    },
                    function() {
                        $('#bubble ul.countries').hide(200);
                        $(this).blur();
                        return false;
                    }
                ); // list toggle 
            } // success function
        });

        var position = $(this).attr('id');
        $('#bubble').addClass(position);
        $('#bubble').show(300);

        return false;
    }); // regions a bind function

    // Map behaviour ends here

    // listing layout change

    $('#mainContent .toolbar .layout a').click(function() {
        $('#mainContent .toolbar .layout a').removeClass('this');
        var className = $(this).attr('class');
        $(this).addClass('this');
        $.ajax({
            url: this.href,
            cache: false,
            async: true,
            success: function(data) {
                $('#mainContent #items').removeClass();
                $('#mainContent #items').addClass(className);
                $('#mainContent #items').html(data);
            } // success
        }); // $.ajax
        $(this).blur();
        return false;
    }); //click

    function bindCheckBoxes() {
        $('#ctl00_mainContent_objectManager').find('option[@value="dump"]').attr('selected', 'selected');
        $('#ctl00_mainContent_objectManager1').find('option[@value="dump"]').attr('selected', 'selected');
        $('#ctl00_mainContent_messageManager').find('option[@value="dump"]').attr('selected', 'selected');
        $('#ctl00_mainContent_messageManager1').find('option[@value="dump"]').attr('selected', 'selected');
        $('#ctl00_mainContent_complexManager').find('option[@value="dump"]').attr('selected', 'selected');
        $('#ctl00_mainContent_complexManager1').find('option[@value="dump"]').attr('selected', 'selected');
        $('#mainContent.company .toolbar a.all').bind('click', function() {
            if ($(this).hasClass('selected')) {
                $('#mainContent.company a.all').each(function() {
                    $(this).removeClass('selected');
                });
                $('#mainContent.company #list .user, #mainContent.company #list .role, #mainContent.company #list .req, #mainContent.company #list .object, #mainContent.company #list .sub, #mainContent.company #list .msg').removeClass('selected');
                $('#mainContent.company .toolbar a.checkbox').removeClass('selected');
                manager.splice(0, manager.length);
            } else {
                $('#mainContent.company a.all').each(function() {
                    $(this).addClass('selected');
                });
                $('#mainContent.company #list .user, #mainContent.company #list .role, #mainContent.company #list .req, #mainContent.company #list .object, #mainContent.company #list .sub, #mainContent.company #list .msg').addClass('selected');
                $('#mainContent.company .toolbar a.checkbox').addClass('selected');
                $('#mainContent.company #list .object, #mainContent.company #list.messages .msg').each(function() {
                    manager.push($(this).attr('id'));
                });
            }
            $('#mainContent.company #ctl00_mainContent_manager').attr('value', manager);
            $(this).blur();
            return false;
        });

        $('#mainContent.company #list .user a.checkbox, #mainContent.company #list.roles .role a.checkbox, #mainContent.company #list .req a.checkbox, #mainContent.company #list .object a.checkbox, #mainContent.company #list .sub a.checkbox, #mainContent.company #list .msg a.checkbox').bind('click', function() {
            if ($(this).parent().hasClass('selected')) {
                $('#mainContent.company a.all').each(function() {
                    $(this).removeClass('selected');
                });

                $(this).parent().removeClass('selected');
                var index_value = $.inArray($(this).parent().attr('id'), manager);
                manager.splice(index_value, 1);
                $('#mainContent.company #ctl00_mainContent_manager').attr('value', manager);
            } else {
                $(this).parent().addClass('selected');
                manager.push($(this).parent().attr('id'));
                $('#mainContent.company #ctl00_mainContent_manager').attr('value', manager);
            }
            $(this).blur();
            return false;
        });
    } // bindCheckBoxes

    // userarea

    bindCheckBoxes();

    // Tabs behaviour start

    //	$('#mainContent .tabs-alt a').bind('click', function() {
    //        $('#mainContent .tabs-alt a').removeClass('here');
    //        $(this).addClass('here');
    //        $(this).blur();
    //        if($(this).attr('rel') == 'statusbar') {
    //            $.ajax({
    //                    url: this.href,
    //                    async: true,
    //                    cache: false,
    //                    success: function(html) {
    //                            $('#mainContent .tAjax .statusBar').html(html);
    //                        }
    //                });
    //        } // endif
    //        else {
    //            $.ajax({
    //                url: this.href,
    //                async: true,
    //                cache: false,
    //                success : function(html) {
    //                    $('#mainContent .tAjax').html(html);
    //                    $('#questions .item').after('<div class="sep"></div>');
    //                    bindCheckBoxes();
    //                }
    //            });
    //        } // end of else
    //        return false;
    //    });
    //    
    //    $('#mainContent .tabs-alt a.right').unbind('click');
    //    
    //	// Check all items
    //	
    //	$('#mainContent .toolbar .actions a.check-all').toggle(
    //		function() {
    //			$('#mainContent #items .item').each(function() {
    //				$(this).addClass('selected');
    //			});
    //			$(this).addClass('checked');
    //			$(this).blur();
    //			return false;
    //		}
    //		,
    //		function() {
    //			$('#mainContent #items .item').each(function() {
    //				$(this).removeClass('selected');
    //			});
    //			$(this).removeClass('checked');
    //			$(this).blur();
    //			return false;
    //		}
    //	);

    function tabClick() {
        $('#mainContent .tabs-qa a').removeClass('here');
        $(this).addClass('here');
        $(this).blur();
    }


    // Check the current item
    $('#mainContent #items .item .checkbox a').toggle(
		function() {
		    $(this).parents('.item').addClass('selected');
		    $(this).blur();
		    return false;
		},
		function() {
		    $(this).parents('.item').removeClass('selected');
		    $(this).blur();
		    return false;
		}
	);

    bindContactsBehavior();


    $('#contacts ul.dropdown a').bind('click', function() {
        if ($(this).parent().hasClass('home')) { $(this).blur(); return false; }
        $(this).blur();
        //$('#contacts ul.dropdown a').removeClass('');
        $('#contacts ul.dropdown li').removeClass('home');
        $(this).addClass('here');
        var text = $(this).text();
        var home = $('#contacts .sHome').text();
        if (text != home) { $(this).parent().addClass('home'); }
        $('#contacts b.sHome').text($(this).text());
        $('#contacts .ajax .office').each(function() {
            $(this).hide();
        });
        $('#contacts .ajax #office' + $(this).attr('rel')).animate({ height: "show" }, 300);
        //        alert($('#contacts .ajax #office' + $(this).attr('rel') + " span.addr").text());
        $('#map_canvas').empty();

        if ($(this).hasClass('point')) {
            var ar = $('#contacts .ajax #office' + $(this).attr('rel') + " span.coords").text().toString().split(';');
            showPoint(ar[0], ar[1], 14);
        } else {
            showAddress($('#contacts .ajax #office' + $(this).attr('rel') + " span.addr").text());
        }

        /*
        $.ajax({
        url: this.href,
        async: true,
        cache: false,
        success: function(html) {
        $('#contacts .ajax').html(html);
        bindRealtorContact();
        }
        });
        */
        return false;
    }
	);

    // Contacts all-cities behaviour end


    // Zoom the fucking photo
    /*
    $('a[rel=zoom]').bind('click', function() {
    $(this).blur();
    $('#container').prepend('<div id="zoomie"></div><div id="bigWrapper"></div>');
    var obj = $(this).parents('.item');
    var offset = $(this).offset();
    var src = $(this).attr('href');
    var oSrc = $('a.button', obj).attr('href');
    var html = '<a href="#" rel="close"><img src="' + src + '" alt="" /></a>';
    if ($(this).parent().is('.thumb')) { html += '<a href="' + oSrc + '" class="details">Подробнее об объеке</a>'; }
    $('#zoomie').html(html);
    $('#zoomie').show(300);
    $('#bigWrapper').css({ "opacity": "0.5" });
    $('#zoomie').css({ "top": offset.top - 250, "left": offset.left + 100 });
    $('#zoomie a[rel=close]').bind('click', function() {
    $('#zoomie').queue(function() {
    $('#zoomie').hide(300);
    $('#bigWrapper').remove();
    $('#zoomie').remove();
    $(this).dequeue();
    });
    return false;
    }
    );
    return false;
    }
    );
    */

    // Secondary navigation block behaviour

    $('#secondaryContent .block .header a.trigger').toggle(
		function() {
		    // $('#secondaryContent .block .content').fadeOut(300);
		    var hasClass = $(this).parents('.block').hasClass('collapsed');
		    // expand the block otherwise
		    if (hasClass == true) {
		        $(this).parents('.block').children('.content').fadeIn(300);
		        $(this).parents('.block').removeClass('collapsed');
		        $(this).blur();
		        $(this).text('Свернуть');
		        setCookie(this, 'unset');
		        return false;
		    }
		    else {
		        $(this).parents('.block').children('.content').fadeOut(300);
		        $(this).parents('.block').addClass('collapsed');
		        $(this).blur();
		        $(this).text('Развернуть');
		        setCookie(this);
		        return false;
		    }
		},
		function() {
		    var hasClass = $(this).parents('.block').hasClass('collapsed');
		    if (hasClass == true) {
		        $(this).parents('.block').children('.content').fadeIn(300);
		        $(this).parents('.block').removeClass('collapsed');
		        $(this).blur();
		        $(this).text('Свернуть');
		        setCookie(this, 'unset');
		        return false;
		    }
		    else {
		        $(this).parents('.block').children('.content').fadeOut(300);
		        $(this).parents('.block').addClass('collapsed');
		        $(this).blur();
		        $(this).text('Развернуть');
		        setCookie(this);
		        return false;
		    }
		}
	);

    $('#secondaryContent .block .content a.grow').toggle(
		function() {
		    $(this).parents('.block').children('.content').children('.list').animate({ "height": "380px" });
		    // $('#secondaryContent .block .list').animate({ "height" : "380px" });
		    $(this).blur();
		    return false;
		},
		function() {
		    $(this).parents('.block').children('.content').children('.list').animate({ "height": "164px" });
		    $(this).blur();
		    return false;
		}
	);

    $('#secondaryContent .block .content .list a.checkbox').toggle(
		function() {
		    $(this).parent('.item').addClass('selected');
		    manager.push($(this).parent().attr('id'));
		    $('#ctl00_secondaryContent_MyObjectsControl_myObjectsList').attr('value', manager);
		    $(this).blur();
		    return false;
		}
		,
		function() {
		    $(this).parent('.item').removeClass('selected');
		    $('#secondaryContent .block .content .actions a.check-all').removeClass('selected');
		    var index_value = $.inArray($(this).parent().attr('id'), manager);
		    manager.splice(index_value, 1);
		    $('#ctl00_secondaryContent_MyObjectsControl_myObjectsList').attr('value', manager);
		    $(this).blur();
		    return false;
		}
	);

    $('#secondaryContent .block .content .actions a.check-all').toggle(
		function() {
		    $('#secondaryContent .block .content .list .item').each(function() {
		        $(this).addClass('selected');
		    });
		    $('#secondaryContent .block .content .list .item').each(function() {
		        manager.push($(this).attr('id'));
		    });
		    $('#ctl00_secondaryContent_MyObjectsControl_myObjectsList').attr('value', manager);
		    $(this).blur();
		    $(this).addClass('checked');
		    return false;
		}
		,
		function() {
		    $('#secondaryContent .block .content .list .item').each(function() {
		        $(this).removeClass('selected');
		    });
		    manager.splice(0, manager.length);
		    $('#ctl00_secondaryContent_MyObjectsControl_myObjectsList').attr('value', manager);
		    $(this).blur();
		    $(this).removeClass('checked');
		    return false;
		}
	);

    function bindRealtorContact() {
        $('a#contact-realtor').bind('click', function() {
            $(this).blur();
            // $('body').append('<div id="realtorContact"></div><div id="bigWrapper"></div>');
            var rDiv = $('#realtorContact');
            var wrap = $('#bigWrapper');
            rDiv.show();
            wrap.show();
            // var objName = $('#content h1.object').html();
            // var lot = $('#content #lot').attr('value');
            wrap.css({ "opacity": "0.5" });
            //            $.ajax({
            //                url: this.href,
            //                async: true,
            //                cache: false,
            //                success: function(html) {
            //                    rDiv.html(html);
            //                    $('#objectName', rDiv).attr('value', objName);
            //                    $('#lotNumber').attr('value', lot);
            //                    $('#realtorContact a.close').bind('click', function() { rDiv.remove(); wrap.remove(); return false; })
            //                    $.scrollTo(50, 800, { queue: true });
            //                }
            //            });
            $('#realtorContact a.close').bind('click', function() { rDiv.hide(); wrap.hide(); return false; });
            return false;
        });
    }
    // we use this in #contacts all-cities behaviour
    bindRealtorContact();

    $('#mainContent #info .description .moreinfo h3').wrapInner('<span></span');

    $('#questions .item').after('<div class="sep"></div>');

    // Insert a supa-mega bubble popupy popup
    $('#map').append('<div id="bubble"><div class="top"><div class="bottom"><div class="bl"></div><!-- .bl --><div class="content"></div> <!-- .content --></div><!-- .bottom --></div> <!-- .top --></div>');

    $('.first-and-second-carousel').jcarousel();
    //$('#carousel').jcarousel();
    //    $('.photocomplex').removeClass('selected').removeClass('photocomplex');
    //    $('.photocomplexblock').hide();
    $('#carousel a').bind('click', function() {
        $(this).blur();
        $('#carousel li').removeClass('here');
        $(this).parent().addClass('here');
        $('#targetImage').attr('src', this.href);
        $('div.objectg a.zoom').attr('rel', $(this).attr('rel'));
        $('#targetImage').parent().attr('href', this.href.replace('/thumbs', ''));
        return false;
    }); // click

    //$('#ccarousel').jcarousel();
    $('#ccarousel a').bind('click', function() {
        $(this).blur();
        $('#ccarousel li').removeClass('here');
        $(this).parent().addClass('here');
        $('#ctargetImage').attr('src', this.href);
        $('div.complexg a.zoom').attr('rel', $(this).attr('rel'));
        $('#ctargetImage').parent().attr('href', this.href.replace('/thumbs', ''));
        return false;
    }); // click

    $('#changeSearchParams').bind('click', function() {
        $(this).blur();
        $('#searchWrap').removeClass();
        $('#searchWrap').addClass('expanded');
        $('#searchForm').show();
        //return false;
    });

    showPreview('.objectg a.zoom', '.nav #carousel');
    showPreview('.complexg a.zoom', '.nav #ccarousel');
});

function showPreview(targetControl, carouselHolder) {

    $(targetControl).bind('click', function () {

        var height = $('body').height();
        var width = $('body').width();

        if ($('#transparentBg').length > 0) {
            $('#transparentBg').remove();
        }

        $('body').append('<div id="transparentBg" style="position:absolute;z-index:100;opacity:0.5;filter: alpha(opacity=50);background:#eeeeff;"></div>');

        $('#transparentBg').css({ "left": 0 + "px", "top": 0 + "px", "width": width + "px", "height": height + "px" })
                                    .show();
        $('#transparentBg, #zoomie a.close').unbind().bind('click', function () {
            $('#zoomie').hide();
            $('#transparentBg').hide();
            return false;
        });

        $('#zoomie').show();

        var pos = $('#content').offset();
        var width = $('body').width();
        var zwidth = $('#zoomie').width();

        var left = (width - 650) / 2;
        var top = parseInt(pos.top) + 100;
        //var top = 0;
        $('#zoomie').css({ "left": left + "px", "top": top + "px" });


        changePreview($(targetControl).attr('rel'), $(targetControl).attr('href'), carouselHolder);
        return false;
    });
}

function changePreview(currentRel, currentSrc, carouselHolder) {
    $('#zoomie a.moveright, #zoomie #image, #zoomie a.moveleft').unbind();
    
    $('#zoomie img.view').attr('src', currentSrc);
    $('#zoomie #image').attr('rel', currentRel);

    $('#zoomie a.moveleft').bind('click', function() {

        var objInGallery = $(carouselHolder + ' a[@rel=' + (currentRel - 1) + ']');
        if (objInGallery.length > 0) {
            changePreview(objInGallery.attr('rel'), objInGallery.attr('href').replace('/thumbs', ''), carouselHolder);
        }

        return false;
    });

    $('#zoomie a.moveright, #zoomie #image').bind('click', function() {

        objInGallery = $(carouselHolder + ' a[@rel=' + (parseInt(currentRel) + 1) + ']');
        if (objInGallery.length > 0) {
            changePreview(objInGallery.attr('rel'), objInGallery.attr('href').replace('/thumbs', ''), carouselHolder);
        }

        return false;
    });

    return false;
}


function onGetCitiesSuccess(e, userContext, methodName){
    var data = e.split('|');
    $('#ctl00_mainContent_cityText').autocompleteArray(data);
}

function setCookie(object, state) {
    var o = $(object).parents('.block').attr('id');
    var minimized = $.cookie(o);
    if (minimized != 'null') { $.cookie(o, 'set', { expires: 7 }); }
    if (state == 'unset') { $.cookie(o, null); }
} // setCookie()

function bindContactsBehavior(){
    // Contacts block all-cities behaviour

    $('#contacts a.dropdown').toggle(
		function() {
		    $(this).blur();
		    $('#contacts ul.dropdown').show(200);
		    return false;
		},
		function() {
		    $(this).blur();
		    $('#contacts ul.dropdown').hide(200);
		    return false;
		}
	);
	
//    $('#contacts ul.dropdown a').bind('click', function() {
//        alert('1');
//        loadInfo();
//        alert('2');
//        return false;
//    });
};

/*************************/
 function OnShoutSuccess(e, userContext, methodName) {
    var result = eval('(' + e + ')'); 
    $('#content .wrap').prepend('<div id="shout"><div class="left"><div class="right">&nbsp;</div></div></div>');
    $('#shout .right').html(result.text);
    $('#shout .right').append('<a href="#" class="close">Закрыть</a>');
    $('#shout a.close').bind('click', function() {
		$('#shout').fadeOut(600);
		$(this).blur();
        $.cookie("shout", "collapsed", { expires: 7,  path: "/" });		
		return false;
	});    
    $('#shout').fadeIn(1000);
 }

 function OnShoutFailed(error, userContext, methodName) {
    $('#shout').hide();
 }        
/*************************/

 function isSet(variable) {
     return (typeof (variable) != 'undefined');
 }

 /***********common map functions**********/
 function showPoint(lat, lon, scale, canvas) {
     //console.log('showPoint (' + lat + ',' + lon + ',' + scale + ',' + canvas + ');');
     if (canvas == null)
         canvas = "map_canvas";

     point = new GLatLng(lon, lat);
     showMap(point, scale, canvas);
 }

 function showMap(p, scale, canvas) {
     //console.log('showMap (' + p.lat() + ',' + p.lng() + ',' + scale + ',' + canvas + ');');
     if (canvas == null)
         canvas = "map_canvas";

     var map = new GMap2(document.getElementById(canvas));

     map.setCenter(p, scale);
     var marker = new GMarker(p);
     map.addOverlay(marker);
     $("#" + canvas + " div[@dir]").hide();

 }

 function showAddress(address, canvas, scale) {
     //console.log('showAddress (' + address + ',' + scale + ',' + canvas + ');');
     if (canvas == null)
         canvas = "map_canvas";

     if (scale == null)
         scale = 9;
     var geocoder = new GClientGeocoder();

     geocoder.getLatLng(
                        address,
                        function(point) {
                            if (!point) {
                                $('#' + canvas).text('Адрес не найден на карте');
                            } else {
                                showMap(point, scale, canvas);
                            }
                        }
                      );
 }
 /*****************************************/
