(function($){$.toJSON=function(o){if(typeof(JSON)=='object'&&JSON.stringify)return JSON.stringify(o);var type=typeof(o);if(o===null)return"null";if(type=="undefined")return undefined;if(type=="number"||type=="boolean")return o+"";if(type=="string")return $.quoteString(o);if(type=='object'){if(typeof o.toJSON=="function")return $.toJSON(o.toJSON());if(o.constructor===Date){var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+hours+':'+minutes+':'+seconds+'.'+milli+'Z"'}if(o.constructor===Array){var ret=[];for(var i=0;i<o.length;i++)ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]"}var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")name='"'+k+'"';else if(type=="string")name=$.quoteString(k);else continue;if(typeof o[k]=="function")continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val)}return"{"+pairs.join(", ")+"}"}};$.evalJSON=function(src){if(typeof(JSON)=='object'&&JSON.parse)return JSON.parse(src);return eval("("+src+")")};$.secureEvalJSON=function(src){if(typeof(JSON)=='object'&&JSON.parse)return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))return eval("("+src+")");else throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string){if(string.match(_escapeable)){return'"'+string.replace(_escapeable,function(a){var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16)})+'"'}return'"'+string+'"'};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'}})(jQuery);

$(document).ready(function() {
  if( $('#carousel').length && $('#carousel').is(':visible') ){ $('#carousel').jcarousel({ scroll: 1 }); }
  $('body').click(function() {
      $('.auth').fadeOut(200);
      if( $('DIV.region-list') ){
        $('.region-list').fadeOut(200);
        $('span.cregion').removeClass('select');
      }
  });
  $('DIV#call .stick').remove(); // spike
  if( $('A[href=#map]').length ){ $('A[href=#map]').bind('click', InitMapYandex); }
  $('span.cab, .auth').click(function(event){ event.stopPropagation(); $('.auth').fadeIn(180); });
  $('span.tour').click(function() { $('#tour3dwindow').show(); $('#overlay').show(); });
  $('span.close3d').click(function() { $('#tour3dwindow').hide(); $('#overlay').hide(); TourDisplay('', true); });
  $('span.feedback-link').click(function() { fn_getCaptcha('DIV#CaptchaImage'); $('.send-msg').show(); $('#overlay').show(); });

  $('A[href=#register]').click(show_area);
  $('A[href=#forgot]').click(show_area);

    $('span.cregion, .region-list').click(function(event) {
        event.stopPropagation();
        $('.region-list').show();
        $(this).addClass('select');
    });

  $('A.benefits-with-us').click(function(){ var b = $('DIV#popup-benefits-with-us'); if( $('DIV#call').length ){ b.css({'position' : 'fixed'}); } b.load('html/benefits.html').show(); $('#overlay').show(); return false; });
  $('A.guarantee').click(function(){ var b = $('DIV#popup-guarantee'); if( $('DIV#call').length ){ b.css({'position' : 'fixed'}); } b.load('html/guarantee.html').show(); $('#overlay').show(); return false; });
  $('BODY').delegate('SPAN.close-win-popup', 'click', function(event){ $(this).parents('DIV').eq(0).hide(); $('#overlay').hide(); });
  $('FORM#QuickAccess').attr({'method':'POST'}).bind('submit', function(){ window.location = '/kvartiry-posutochno/'+($(this).children('INPUT[type=text]').val())+'.html'; return false; });
  $('#rule_link').bind('click', function(e){ 
      var b = $('#SCrole', $(document.body));
      console.log(b.length);
      if( !b.length ){ 
        $(document.body).append($('<DIV />', { 'id' : 'SCrole', 'class' : 'popup-window rule_block'}).load('html/comments_rule.html'));
      } 
      $('#SCrole', $(document.body)).show();
      $('#overlay').show();

  });

  $("A[href$=#]").click(function(){ return false; });

    // Closure dynamic elements
    (function(window, undefined){
        var ajax = function(){
                return { async : false, cache : false, global : false, dataType : 'json', type : 'POST',
                contentType : 'application/x-www-form-urlencoded;charset=utf-8', url : '', timeout : 5000 }
            },
            err_msg = function(s){
                if( s == 'error' ){ s = 'Произошла ошибка!'; }
                else if( s == 'notmodified' ){ }
                else if( s == 'abort' ){ s = 'Соединение с сервером было разорвано... Повторите попытку.'; }
                else if( s == 'parsererror' ){ s = 'Не могу разобрать ответ...'; }
                else if( s == 'timeout' ){ s = 'Превышен интервал ожидания. Пожалуйста попробуйте позже.'; }
                else { s = 'Произошел сбой в работе. Приносим извинения за неудобства.'; }
                return s;
            },
            slideList = function(block, page, cols, cl){
                var it, vis;

                vis = block.filter(':visible');
                for( it = 0; it < vis.length; ++it ){ vis.eq(it).addClass(cl); }

                it = (page * cols) - cols;
                for( ; it < (page*cols); it++ ){ block.eq(it).removeClass(cl); }
                return 0;
            },
            actListSlide = function(block, list, pfx){
                var it = 0, vis = block.find('UL:visible LI:has(INPUT):visible');
                for( ; it < vis.length; it++ ){ $('LI#'+pfx+(vis.eq(it).find('INPUT').val()), list).find('INPUT').attr('checked','checked'); }
                return 0;
            };

        (function($){
            var noext = $('DIV#reserve-property'),
                form = noext.parent('FORM').attr({'id':'_searchform'}),
                ext = $('DIV.extra-filter', noext),
                addit = $('DIV.comfort-wrapper', ext),
                lpic = $('<IMG/>', {'src':'img/loader_aj.gif', 'id': '_pic_loader'}),
            //---
                fcf = $('DIV.filter-controls', noext),
                smbt = $('DIV.filter-controls > INPUT[type=submit]', noext),
            //--- no external search form ---//
                date = $('DIV.filter-item', noext),
                slider = $('DIV.slider-block', noext),
                apart = $('DIV.checkboxes', noext).eq(0),
                area = $('DIV.checkboxes', noext).eq(1),
                metro = $('DIV.metro-block-form', noext),
                a_param = $('DIV.a-param-form', noext),
                beds = $('SELECT[name=twin_beds], SELECT[name=double_beds]', a_param),
                ware = $('INPUT[name=ware]', a_param),
            //--- external search form ---//
                chars = $('DIV.comfort-filter', addit).eq(0),
                comft = $('DIV.comfort-filter', addit).eq(1),
                relax = $('DIV.comfort-filter', addit).eq(2),
                conds = $('DIV.comfort-filter', addit).eq(3),
            //---
                a = ajax();
            a.async = true;
            a.url = './cgi-bin/index.pl';
            a.beforeSend = function(){ fcf.append(lpic); };
            a.success = function(d, t, x){ smbt.val(d.text); };
            a.error = function(x, s, r){ smbt.val('Ничего не покажу'); };
            a.complete = function(){ $('IMG#_pic_loader', fcf).remove(); };
            //---
            var pkg = {},
                mtd = {
                    buildBox : function(k, o){
                        var inp = o.find(':input:checked').toArray();
                        if( !inp.length ){ delete pkg[k]; this.send(); return this; }
                        var a = [];
                        for(var it in inp){ a.push(inp[it].value); }
                        pkg[k] = a;
                        this.send();
                        return this;
                    },
                    buildText : function(k, o){
                        var inp = o.find('INPUT').toArray();
                        if( !inp.length ){ delete pkg[k]; this.send(); return this; }
                        var a = [];
                        for(var it in inp){ a.push(inp[it].value); }
                        pkg[k] = a;
                        this.send();
                        return this;
                    },
                    buildSelect : function(k, o){
                        var inp = o.find('SELECT').toArray();
                        if( !inp.length ){ delete pkg[k]; this.send(); return this; }
                        var a = [];
                        for(var it in inp){ a.push(inp[it].value); }
                        pkg[k] = a;
                        this.send();
                        return this;
                    },
                    send : function(){
                        a.data = 'jsp='+(encodeURIComponent($.toJSON(['search', pkg])));
                        $.ajax(a);
                    }
                };
            //---
            mtd.send();
            date.bind('change', function(){ mtd.buildText('date', date); });
            $('DIV#slider-range A', noext).bind('mouseup', function(event){ mtd.buildText('price', slider); });
            apart.delegate('INPUT[name=apartaments]', 'click', function(){ mtd.buildBox('apartaments', apart); });
            area.delegate('INPUT[name=district]', 'click', function(){ mtd.buildBox('district', area); });
            beds.bind('change', function(){ mtd.buildSelect('beds', a_param); });
            ware.bind('keyup', function(){ this.value = this.value.replace(/[^\d]/g,''); mtd.buildText('ware', a_param); });
            //---
            metro.delegate('INPUT[name=metro]', 'click', function(){ mtd.buildBox('metro', metro); });
            metro.delegate('INPUT[name=metro]', 'click', function(){ mtd.buildBox('metro', metro); });
            chars.delegate('INPUT[name=features]', 'click', function(){ mtd.buildBox('features', chars); });
            comft.delegate('INPUT[name=comfort]', 'click', function(){ mtd.buildBox('comfort', comft); });
            relax.delegate('INPUT[name=fortherest]', 'click', function(){ mtd.buildBox('forth', relax); });
            conds.delegate('INPUT[name=miscellaneous]', 'click', function(){ mtd.buildBox('other', conds); });
            //---
            fcf.find('BUTTON.reset').bind('click', function(){
                var sr = $('DIV#slider-range');
                sr.slider('values', [sr.slider('option', 'min'), sr.slider('option', 'max')]);
            });

            var list_area = { list : '', page : '', cols : 3 }, list_metro = { list : '', page : '', cols : 3 };
			(function(){
			  var a = ajax();
			  // -----------------------------------------
			  // -----------------
			  a.url = './cgi-bin/index.pl';
			  a.success = function(obj){
				  var it = 0, page = obj.length / list_metro.cols;
				  try{ page = (/\d+\.(\d)/.exec(page)[1]) > 5 ? (Math.floor(page))+1 : Math.floor(page); } catch(e){ }
				  list_metro.list = obj.join('');
				  for( ; it < page; ++it ){ list_metro.page += '<a href="javascript:void(0)">'+(it+1)+'</a>'; }
			  };
			  a.data = 'jsp='+(encodeURIComponent($.toJSON(['list', 'metro'])));
			  $.ajax(a);
			  // -----------------
			  // -----------------------------------------
			  metro.find('DIV.plus-red A')
				  .attr({'id':'_add_metro'})
				  .bind('click', function(event){
					  $('#overlay').show();
					  if( $('#_metro_list').length ){ $('#_metro_list').show(); return false; }
					  $(document.body).append(
						  $('<DIV/>', {'id':'_metro_list', 'class':'popup-window'})
							  .html('<span class="close-win-popup">&nbsp;</span> <h3 class="hb-16p">Метро города</h3> <div id="slide-metro">'+list_metro.list+'</div><div id="metro-page-bar">'+list_metro.page+'</div>')
							  .delegate('A', 'click', function(e){
								  slideList($('#slide-metro UL'), parseInt($(this).text()), list_metro.cols, 'block-slide-list');
							  })
							  .delegate('INPUT', 'change', function(e){
								  var inp = $('LI INPUT[value='+this.value+']', metro);
								  if( this.checked ){ inp.parent('LI').show(); }else { inp.removeAttr('checked').parent('LI').hide(); }
							  })
					  );
					  slideList($('#slide-metro UL'), 1, list_metro.cols, 'block-slide-list');
					  actListSlide(metro, $('#slide-metro'), 'metro_');
					  $('#_metro_list').show();
				  });
			}());
			(function(){
			var a = ajax();
			  // -----------------------------------------
			  // -----------------
			  a.url = './cgi-bin/index.pl';
			  a.success = function(obj){
				  var it = 0, page = obj.length / list_area.cols;
				  try{ page = (/\d+\.(\d)/.exec(page)[1]) > 5 ? (Math.floor(page))+1 : Math.floor(page); } catch(e){ }
				  list_area.list = obj.join('');
				  for( ; it < page; ++it ){ list_area.page += '<a href="javascript:void(0)">'+(it+1)+'</a>'; }
			  };
			  a.data = 'jsp='+(encodeURIComponent($.toJSON(['list', 'area'])));
			  $.ajax(a);
			  // -----------------
			  // -----------------------------------------
			  area.find('DIV.plus-red A')
				  .attr({'id':'_add_area'})
				  .bind('click', function(event){
					  $('#overlay').show();
					  if( $('#_area_list').length ){ $('#_area_list').show(); return false; }
					  $(document.body).append(
						  $('<DIV/>', {'id':'_area_list', 'class':'popup-window'})
							  .html('<span class="close-win-popup">&nbsp;</span> <h3 class="hb-16p">Районы города</h3> <div id="slide-area">'+list_area.list+'</div><div id="area-page-bar">'+list_area.page+'</div>')
							  .delegate('A', 'click', function(e){
								  slideList($('#slide-area UL'), parseInt($(this).text()), list_area.cols, 'block-slide-list');
							  })
							  .delegate('INPUT', 'change', function(e){
								  var inp = $('LI INPUT[value='+this.value+']', area);
								  if( this.checked ){ inp.parent('LI').show(); }else { inp.removeAttr('checked').parent('LI').hide(); }
							  })
					  );
					  slideList($('#slide-area UL'), 1, list_area.cols, 'block-slide-list');
					  actListSlide(area, $('#slide-area'), 'area_');
					  $('#_area_list').show();
				  });
			}())
        }(jQuery));

        (function($){
            var win = $('DIV#forgot', document.body),
                form = win.children('FORM'),
                a = ajax(), marks = new classFloatMarks({ code : { val : 'Код с картинки', re : RegExp('^[a-z0-9]+$', 'i'), err : 'Код на картинке состоит из букв латинского алфавита и цифр'}}, form);
                a.url = './cgi-bin/index.pl';
            form.bind({
                click : function(event){
                    var inpref = $('SPAN.area_captcha', this);
                    fn_getCaptcha(inpref, false); $(this).unbind('click');
                    $('.sert', inpref).show();
                    $('A', inpref).bind('click', function(event){fn_getCaptcha(inpref, false); });
                },
                submit : function(){
                    var i, inp = $(this).find('INPUT[type=text]'), err = [], msg = $(this).find('DIV.server-info').removeAttr('style').hide(),
                        captcha = $(this).find('INPUT[name=code]'), data = {};
                    for(i=0; i < inp.length; ++i ){
                        if( !($.trim(inp.eq(i).val())).length ){ err.push(0); }
                        data[inp.eq(i).attr('name')] = inp.eq(i).val();
                    }
                    if( err.length ){ msg.addClass('info-error').text('Заполнены не все поля!').show(); return false; }

                    if( !marks.check() ){
                        var self = $(this);
                        a.success = function(obj){
                            if( obj.status === 'error' ){ alert(obj.text); return false; }
                        };
                        a.data = 'jsp='+(encodeURIComponent($.toJSON(['forgot', data ])));
                        $.ajax(a);
                    }
                    return false;
                }
            });
        }(jQuery));

        (function($){
            var win = $('DIV#register', document.body),
                form = win.children('FORM'),
                a = ajax(), field, timeID = {}, time, marks = new classFloatMarks({ code : { val : 'Код с картинки', re : RegExp('^[a-z0-9]+$', 'i'), err : 'Код на картинке состоит из букв латинского алфавита и цифр'}}, form),
                validate = {}, sendAll;
                a.url = './cgi-bin/index.pl';
            form.bind({
                click : function(event){
                    var inpref = $('SPAN.area_captcha', this);
                    fn_getCaptcha(inpref, false); $(this).unbind('click');
                    $('.sert', inpref).show();
                    $('A', inpref).bind('click', function(event){fn_getCaptcha(inpref, false); });
                },
                submit : function(){
                    var i, inp = $(this).find('INPUT[type=text], INPUT[name=password]'), err = [], msg = $(this).find('DIV.server-info').removeAttr('style').hide(),
                        captcha = $(this).find('INPUT[name=code]'), data = {};
                    for(i=0; i < inp.length; ++i ){
                        if( !($.trim(inp.eq(i).val())).length ){ err.push(0); }
                        data[inp.eq(i).attr('name')] = inp.eq(i).val();
                    }
                    if( err.length ){ msg.addClass('info-error').text('Заполнены не все обязательные поля!').show(); return false; }

                    for(i in validate){ if( validate[i] ){ err.push(0); } }
                    if( err.length ){ msg.addClass('info-error').text('Не все поля заполнены корректно!').show(); return false; }

                    if( !marks.check() ){
                        var self = $(this);
                        a.success = function(obj){
                            if( obj.status === 'error' ){ alert('Произошла внутреняя ошибка!'); return false; }
                            if( obj.status === 'ok' ){ win.load('html/after_register.html'); return false; }
                        };
                        a.data = 'jsp='+(encodeURIComponent($.toJSON(['register', 'new', data ])));
                        $.ajax(a);
                    }
                    return false;
                }
            }).find('INPUT[name=login]').bind('blur keyup', function(event){
                clearTimeout(timeID.login);
                var self = $(this),
                    field = $(this).parent().find('DIV#_ilogin');
                field.removeAttr('class').text('');
                if( !field.length ){ $(this).parent().eq(0).append($('<DIV />', {id:'_ilogin'})); field = $('DIV#_ilogin'); }
                timeID.login = setTimeout(function(){
                    if( !self.val().length ){ return false; }
                    if( self.val().length <= 3 ){ field.text('короткий логин').addClass('message-error'); return false; }
                    else {
                        a.success = function(obj){
                            validate.login = obj.status === 'error' ? 1 : 0;
                            if( obj.status === 'error' ){ field.addClass('message-error'); }
                            else { field.addClass('message-success'); }
                            field.text(obj.text);
                        };
                        a.data = 'jsp='+(encodeURIComponent($.toJSON(['register', 'login', self.val()])));
                        $.ajax(a);
                    }
                    return false;
                }, 1500);
            }).end().find('INPUT[name=re_password]').bind('blur', function(event){
                clearTimeout(timeID.repass);
                var self = $(this),
                    info = $(this).parent().find('DIV#_repwd'),
                    pass = form.find('INPUT[name=password]');
                info.removeAttr('class').text('');
                if( !info.length ){ $(this).parent().eq(0).append($('<DIV />', {id:'_repwd'})); info = $('DIV#_repwd'); }
                if( pass.val().length < self.val().length-2 ){ return false; }
                timeID.repass = setTimeout(function(){
                    if( !self.val().length || (/\s+/.test(self.val())) ){ info.text('').removeAttr('style'); return false; }
                    if( pass.val() === self.val() ){
                        // OK
                        validate.repasswd = 0;
                        info.text('совпадают').addClass('message-success');
                    } else {
                        // ERROR
                        validate.repasswd = 1;
                        info.text('пароли не совпадают').addClass('message-error');
                    }
                    return false;
                }, 1500);
            }).end().find('INPUT[name=email]').bind('blur keyup', function(event){
                clearTimeout(timeID.email);
                var self = $(this),
                    field = $(this).parent().find('DIV#_imail');
                field.removeAttr('class').text('');
                if( !field.length ){ $(this).parent().eq(0).append($('<DIV />', {id:'_imail'})); field = $('DIV#_imail'); }
                timeID.email = setTimeout(function(){
                    if( !self.val().length ){ return false; }
                    if( !(/(?:[a-z0-9\_\-\.]+\@[a-z0-9\_\-]+(?:\.[a-z]{2,4}){1,4})/i.test(self.val())) ){ field.text('не верный формат e-mail').addClass('message-error'); return false; }
                    else {
                        a.success = function(obj){
                            validate.mail = obj.status === 'error' ? 1 : 0;
                            if( obj.status === 'error' ){ field.addClass('message-error'); }
                            else { field.addClass('message-success'); }
                            field.text(obj.text);
                        };
                        a.data = 'jsp='+(encodeURIComponent($.toJSON(['register', 'mail', self.val()])));
                        $.ajax(a);
                    }
                    return false;
                }, 1500);
            }).end().find('INPUT[name=phone]').bind('keyup blur', function(event){
                var self = $(this), field = $(this).parent().find('DIV#_iphone');
                field.removeAttr('class').text('').removeAttr('style');
                if( !self.val().length ){ return false; }
                if( !field.length ){ $(this).parent().eq(0).append($('<DIV />', {id:'_iphone'})); field = $('DIV#_iphone'); }
                if( !(/^(?:\+?[\d\-]+\,?\s?)+$/.test(self.val())) ){
                    // ERROR
                    field.addClass('message-error').text('некорректный номер телефона');
                    validate.phone = 1;
                }
                else {
                    // OK
                    field.text('", " - разделитель телефонов').css({'font-size' : '12px', color : 'gray'});
                    validate.phone = 0;
                }
            });

        }(jQuery));
        // Comments
        (function($, undefined){
            var form = $('FORM#formcomment');
            if( !form.length ) return 0;
            var a = ajax();
            var deft = {
                message : { val : 'Текст отзыва',   re : /.+/ },
                mail :    { val : 'Email адрес',    re : /(?:[a-z0-9\_\-\.]+\@[a-z0-9\_\-]+(?:\.[a-z]{2,4}){1,4})/i, err : 'Введенное вами значение не похоже на Email!' },
                name :    { val : 'Ваше имя',       re : /^[a-zа-я\s\-]+$/i },
                code :    { val : 'Код с картинки', re : /^[a-z0-9]+$/i, err : 'Код на картинке состоит из букв латинского алфавита и цифр' }
            };
            var marks = new classFloatMarks(deft, form);

            var tform = $('DIV#comments-area FORM.comment-form');
            var submarks = [];
            var subform = [];
            for( var i=0; i < tform.length; i++ ){
                subform[i] = tform.eq(i).attr({'fuid': i});
                submarks[i] = new classFloatMarks(deft, subform[i]);
            }
            var flag = false;

            a.url = './cgi-bin/index.pl';
            a.success = function(obj, status, xhr){
                var form_ = (obj.fuid == '' ? form : subform[obj.fuid]);
                $('DIV._comment_info', form_).addClass('info-success').text(obj.info).fadeIn(180);
                setTimeout(function(){ $('DIV._comment_info', form_).fadeOut(180, function(){ $('DIV._comment_info', form_).empty().removeClass('info-success'); $(document.body).dblclick(); });  }, 5000 );
            };
            a.error = function(x, s, r){
                if( x.responseText != '' ){
                    var obj = $.parseJSON(x.responseText);
                    var form_ = (obj.fuid == '' ? form : subform[obj.fuid]);
                    $('DIV._comment_info', form_).addClass('info-error').text(obj.info).fadeIn(180);
                    setTimeout(function(){ $('DIV._comment_info', form_).fadeOut(180, function(){ $('DIV._comment_info', form_).empty().removeClass('info-error'); });  }, 5000 );
                }
            };
            a.complete = function(xhr, status){
                if( status == 'success' ){
                    var obj = $.parseJSON(xhr.responseText);
                    var form_ = (obj.fuid == '' ? form : subform[obj.fuid]);
                    var inps = form_.find('INPUT[type=text], TEXTAREA');
                    for(var i=0; i < inps.length; ++i ){ var o = inps.eq(i); o.val( o.attr('defaultValue') ); }
                    $('DIV.ref-captcha IMG', form_).attr('src', 'img/empty.gif');
                    form_.bind('click', function(event){ fn_getCaptcha($('DIV.ref-captcha', form_), true); $(this).unbind('click'); } );
                    $('.comments_refresh', $('DIV.ref-captcha', form_)).hide();

                }
            };
            var bind_form = function(obj){
                var form_, marks_;
                var fuid = $(obj).attr('fuid') || -1;

                if( flag ){ form_ = subform[ fuid ]; marks_ = submarks[ fuid ]; }
                else { form_ = form; marks_ = marks; }
                var inps = form_.find('INPUT[name=intercom], INPUT[type=text], TEXTAREA');
                var data = inps.serializeArray();
                if( !marks_.check() ){
                    var Ad = {};
                    for( var it in data ){ Ad[ data[it]['name'] ] = $.trim(data[it]['value']); }
                    a.data = 'jsp='+(encodeURIComponent($.toJSON(['comment', form_.find('INPUT[name=cat]').val(), Ad, fuid ])));
                    $.ajax(a);
                } else { alert('Заполнены не все поля!'); }
                return false;
            };
            form.bind({
                submit : function(event){
                    flag = false;
                    bind_form(this);
                    return false;
                },
                click : function(event){
                    var inpref = $('SPAN.area_captcha', $('DIV.ref-captcha', this));
                    fn_getCaptcha(inpref, false); $(this).unbind('click');
                    $('.comments_refresh', inpref).show();
                    $('A', inpref).bind('click', function(){fn_getCaptcha(inpref, false); });
                }
            });
            tform.bind({submit : function(event){
                flag = true;
                bind_form(this);
                return false;
            }, click : function(event){
                    var inpref = $('SPAN.area_captcha', $('DIV.ref-captcha', this));
                    fn_getCaptcha(inpref, false); $(this).unbind('click');
                    $('.comments_refresh', inpref).show();
                    $('A', inpref).bind('click', function(){fn_getCaptcha(inpref, false); });
                }
            })

        }(jQuery));
        // Feedback
        (function($){
            var form = $('FORM#formfeedback');
            var block_this = $('FORM#formfeedback').parents('DIV.send-msg');
            block_this.delegate('.closefeed', 'click', function() { block_this.hide(); $('#overlay').hide(); });
            var a = ajax();
            var marks = new classFloatMarks({
                message : { val : 'Текст письма', re : /.+/ },
                mail :    { val : 'Email адрес', re : RegExp('(?:[a-z0-9\\_\\-\\.]+\\@[a-z0-9\\_\\-]+(?:\\.[a-z]{2,4}){1,4})', 'i'), err : 'Введенное вами значение не похоже на Email!' },
                code :    { val : 'Код с картинки', re : RegExp('^[a-z0-9]+$', 'i') },
                theme :   { val : 'Выберите тему письма' }
            }, form);
            a.url = './cgi-bin/index.pl';
            a.success = function(obj, status, xhr){ if( obj && obj.st == 'success' ){ alert(obj.info); } };
            a.error = function(x, s, r){ alert(err_msg(s)); };
            a.complete = function(xhr, status){
                if( status == 'success' ){
                    var inps = form.find('INPUT[type=text], TEXTAREA');
                    for(var i=0; i < inps.length; ++i ){ var o = $(inps[i]); o.val(''); }
                    block_this.load('html/after_feed.html');
                }
            };
            form.bind('submit', function(e){
                var inps = form.find('INPUT[type=text], TEXTAREA, SELECT');
                var data = inps.serializeArray();
                if( !marks.check() ){
                    var json = {};
                    for( var it in data ){ json[ data[it]['name'] ] = data[it]['value'].replace(/^\s*/, ''); }
                    a.data = 'jsp='+(encodeURIComponent($.toJSON(['feedback', json])));
                    $.ajax(a);
                } else { alert('Заполнены не все поля!'); }
                return false;
            }).find('A#RefreshCaptcha').bind('click', function(event){ fn_getCaptcha($('DIV#CaptchaImage', form)); });

        }(jQuery));
        // Reservation
        (function($){
            var form = $('DIV#reserve-form FORM').attr({'id':'_reserved'});
            if( !form.length ) return 0;
            var a = ajax();
            var marks = new classFloatMarks({
                r_name  : { val : 'Введите свое имя', re : /(:?[A-ZА-Я\s\-\_]+)/i, err : 'Вы не указали свое Имя' },
                r_phone : { val : 'Введите контактный номер телефона, по которому с вами свяжутся', re : /[\d\-\s\+]+/, err : 'Введенный вами телефон не совсем похож на телефон' },
                r_indate  : { val : '', re : /[0-3]\d\.[0-1]\d\.2\d+/, err : 'Вы не указали дату заезда' },
                r_outdate : { val : '', re : /[0-3]\d\.[0-1]\d\.2\d+/, err : 'Вы не указали дату выезда' }
            }, form);
            a.url = './cgi-bin/index.pl';
            a.success = function(d, t, x){
                if( d.type == 'data' ){ $('DIV#reserved-info').prepend($(d.info)); }
                $('DIV#reserve-property').remove();
            };
            a.error = function(x, s, r){ alert(err_msg(s)); };

            $('DIV#reserve-form A#_reserved_go').bind('click', function(event){ form.submit(); return false; });
            $('FORM#_reserved').bind('submit', function(){
                var data = $(':input:not(:disabled)', this).serializeArray();
                if( !marks.check() ){
                    a.data = ['reserved'];
                    for( var it in data ){ a.data.push(data[it]['value'].replace(/^\s*/, '')); }
                    a.data = 'jsp='+(encodeURIComponent($.toJSON(a.data)));
                    $.ajax(a);
                } else { alert('Заполнены не все поля!'); }
                return false;
            });
        }(jQuery));
        // Reservation info
        (function($){
            var block = $('DIV#reserved-info');
            if( !block.length ) return 0;
            var a = ajax();
            a.url = './cgi-bin/index.pl';
            a.async = true;
            a.data = 'jsp='+(encodeURIComponent($.toJSON(['rooms_info'])));
            a.success = function(d, t, x){ $('#reserved-info').html(d.info); };
            a.error = function(x, s, r){ alert(err_msg(s)); };
            $.ajax(a);
        }(jQuery));
        // load city list in file
        var BuildListCity = (function(it){
            var max_height_block = 415, max_count_elem = 14, t;
            while( t = it.shift() ){
                (function(base, items, ecp, c, mhb){
                    var watch_list = c || max_count_elem,
                        cout = 0,
                        max_height_block = mhb || max_height_block;
                        aList = $(items),
                        PHeight = $(base).height(),

                        aHeight = aList.eq(0).outerHeight(true),
                        aParent = aList.eq(0).parent(),
                        cParent = aParent.clone(true).empty(),

                        EcpHeightSum = (function(ecp){ var i = s = 0; for( ;i < ecp.length; ++i ){ s += $(ecp[i]).outerHeight(true); } return s; }(ecp));

                    cout = PHeight <= max_height_block ? Math.floor( ( PHeight - EcpHeightSum ) / aHeight ) : max_count_elem;
                    var len = Math.ceil( aList.length / cout ), i;
                    for( i=0; i < len; ++i ){ aParent.parent().append( $(cParent).clone(true).append( aList.splice(0, watch_list) ) ); }
                    $(aParent).remove();
                }.apply(this, t));
            }
        });
        
        $(window).resize(function(e){
            var items_len = 20, wout = window.outerWidth, mhb;
            if( wout < 1050 ){ items_len = 20; }
//             if( wout < 1400 && wout > 1200 ){ items_len = 20; } //1280*1024
//             else if ( wout < 1200 && wout > 1000 ){ items_len = 25; } // 1024*768
//             else if ( wout > 1400 ){  }
//             else { items_len = 30; }
            BuildListCity([["DIV#intro", "DIV#select-city UL.city-col> LI", ['DIV#select-city H3'], items_len]]);
        });
        (function($){

            var a = ajax();
            a.success = (function(d){
                $('DIV#region > DIV.region-list UL.city-col').html(d);
                $('DIV#intro DIV#select-city UL.city-col').html(d);
                $('DIV#left-col > UL.cities').html(d);
                // Build list city
                BuildListCity([["DIV.region-list", "DIV.region-list UL > LI", [], 25], ["DIV#intro", "DIV#select-city UL.city-col > LI", ['DIV#select-city H3'], 20]]);
                // City in site
                (function($){
                    var DIVReg = $('DIV#region'),
                        s = /(?:www\.)?(.+\.ru)/.exec(window.location.host).pop(),
                        tl = $('LI > A[href$='+s+']', $('DIV.region-list UL', DIVReg)),
                        ll = $('UL.cities LI A[href$='+s+']', $('DIV#left-col'));
                    if( tl ){ DIVReg.children('SPAN.cregion').html(tl.text()); }
                    if( ll ){ ll.parent('LI').addClass('active'); ll.replaceWith('<span>'+ll.text()+'</span>'); }
                }(jQuery));
            });
            a.dataType = 'html';
            a.async = true;
            a.url = './cgi-bin/index.pl';
            a.data = 'jsp='+($.toJSON(['city']));
            $.ajax(a);
        }(jQuery));
    }(window));

    // Closure a constant elements
    (function(window, undefined){
        // Description "rooms" after photos
        (function($){
            var places = $('DIV#content DIV.property-profile DIV.description DIV.places');
            var tblock = $('<DIV/>');
            var li = places.find('LI');
            var t = Math.ceil(li.length/3)+1;
            var s,e,i;
            for( s = i = 0, e = t; i < t+1; ++i, s+=t, e+=t ){ tblock.append( $('<UL/>').append(li.slice(s,e)) ); }
            places.html(tblock.html());
        }(jQuery));
        // Autorization form
        (function($){ var da = $('DIV.auth').attr({'id':'_auth'}).children('FORM').bind('submit', function(){ $('DIV#_auth').fadeOut(); }); }(jQuery));
        // Anchor reservation form
        (function($){
            var b = $('#reserve-form');
            var highlightingBlock = function(b, t){
                if( t < 0 ) return;
                while( t-- > 0 ){ b.animate({opacity: .1}, 400).animate({opacity: .9}, 400); }
            }
            var anim = function(){
                $("html:not(:animated)"+( ! $.browser.opera ? ",body:not(:animated)" : "")).animate({scrollTop: $('#reserve-form').position().top}, 'slow');
                highlightingBlock(b.children('H3'), 3);
            }
            $('A.anchor-link').bind('click', function(event){ if( /#reserve\-form$/.test($(this).attr('href')) ){ anim() } });
            if( /#reserve\-form$/.test(window.location.href) ){ anim() }
        }(jQuery));
        // Restore anchor links
        (function($){
            var a = $('A.anchor-link');
            if( a.length ){
                for( var i = a.length; --i >= 0; ){
                a.eq(i).attr('href', window.location.pathname+a.eq(i).attr('href'));
                }
            }
            var a = $('A.room-link');
            if( a.length ){
                for( var i = a.length; --i >= 0; ){
                    var href = a.eq(i).prev('DIV').find('P.ilot A').attr('href');
                    a.eq(i).attr('href', href+a.eq(i).attr('href'));
                }
            }
        }(jQuery));
        // History list "rooms"
        (function ($, undef) {
            var size = 12,
                list = new Queue(size),
                mtd = {
                    put : function () {
                        var res = /(\d+)/.exec(window.location.pathname),
                            num = res.pop(),
                            l = list.out,
                            i;
                        if (typeof res !== undef || res !== null) {
                            for (i = 0; i < l.length; ++i) { if (l[i][0] == num) { num = 0; return 0; } }
                            if (num) {
                                list.push([num, window.location.pathname]);
                                $.cookie('HistoryList', $.toJSON(list.out), { expires: 7, path: '/', domain: (window.location.host || window.location.hostname), secure: false });
                            }
                            return num;
                        }
                    },
                    show : function () {
                        var l = list.out, out = [], i = 0, str = '';
                        try {
                            for (i = 0; i < l.length; ++i) { if ((typeof l[i] == 'object') && (l[i] instanceof Array)) { out.push('<a href="' + l[i][1] + '">Лот №' + l[i][0] + '</a>'); } }
                            out = out.reverse();
                        } catch (e) { return 0; }
                        if (out.length) { str = out.join(', '); } else { str = 'Вы еще не просматривали лоты'; }
                        $('DIV#history-lot').html(str);
                        return 1;
                    },
                    take : function () {
                        var lt;
                        try { lt = $.parseJSON($.cookie('HistoryList')); } catch (e) { return 0; }
                        if ((typeof lt == 'object') && (lt instanceof Array)) { list.restore(lt); return 1; }
                        return 0;
                    }
                };
            if ((/kvartiry\-posutochno/.test(window.location.pathname)) || (/cab\/rooms/.test(window.location.pathname))) {
                mtd.take(); mtd.show();
                if (/kvartiry\-posutochno\/\d+\.html/.test(window.location.pathname)) { mtd.put(); }
            }
        }(jQuery));

        (function ($) {
            if (/\#tour_3d/.test(window.location.href)) {
                $('DIV#tabs A[href=#tour_3d]').click();
            }
        }(jQuery));
        
    }(window));

    function fn_getCaptcha(block, f){
        block = $(block);
        var img = block.find('IMG');
        if( img.length ){ img.remove(); }

        var rand = Math.floor(Math.random() * (9999 - 99 + 1)) + 99;
        img = $('<IMG />').attr({'src' : './cgi-bin/captcha.pl?s='+rand });
        if( !f ){ block.prepend(img); }
        else { block.append(img); }

        return false;
    }

    ;(function ($, struct, undefined) {
        var i, str, block, p, t, arr;
        block = $('DIV', $('DIV#schedule')).eq(0);
        if( struct === undefined ){ return 1; }
        if( !struct.length ){ $('DIV#schedule').hide(); return 1; }
        arr = ['График работы'];
    
        if (parseInt(struct.split('#')[0].split('/')[0]) === -1) {
            arr.push('Круглосуточно');
        } else {
            str = struct.split('#').reverse();
            while(i = str.pop()){
                p = i.split('/');
                t = p[1].split(':');
                arr.push(p[2] + ' с ' + (t[0] + ':' + t[1]) + ' до ' + (t[2] + ':' + t[3]));
            }
        }
        
        block.html(arr.join('<br />'));
        
        try {
            delete window.schedule_struct;
        } catch(e){
            window.schedule_struct = undefined;
        }
        
    }(jQuery, window.schedule_struct))


});



function TourDisplay(v, f, q){
    var t = $('DIV#tour3dwindow');
    t.find('IFRAME').attr('src', !f ? 'catalogs/projects3d/Project'+v+'/TourWeaver_Project'+v+'.html' : v);
    if( typeof q === 'undefined' ){ t.addClass('tour-small500'); }else{ t.removeClass('tour-small500'); }
    if( !f ){
        var itdsc = $('DIV.item-desc', $(q).parent('DIV')), data = [], tmp, link;
        if( itdsc.length ){
            link = $('P.ilot', itdsc);
            tmp = $('P.black', itdsc).last();
            data[0] = tmp.next('P');
            data[1] = data[0].next();
            data[2] = data[1].next();
            t.find('DIV.tour3d').html('<div class="tour-desc">\
                '+(link.html())+'<br>\
                <p><strong>'+($('P.black', itdsc).eq(0).html())+'</strong></p>\
                <p>'+data[0].text()+', '+data[1].text()+', '+data[2].text()+'</p>\
                <span>'+($('P.price', itdsc).html())+'</span>\
            </div>\
            <div class="tour-phones">\
                <p>8 800 200-30-21 (Россия)</p>\
                <p>+7 929 238-36-26 (Все страны)</p>\
                <a href="'+($('A', link).attr('href')+'#reserve-form')+'" class="red">ЗАБРОНИРОВАТЬ</a>\
            </div>');
            return true;
        }
    }

    return false;
}


function show_area(event){
    if( typeof(window.last_open) != 'undefined' ){ $(window.last_open).hide(); }
    var href = jQuery(this).attr('href');
    jQuery('DIV'+href).show();
    $('#overlay').show();
    window.last_open = href;
    return false;
}

/* Кабинет пользователя */
function togmenu ( id ){
    alert( $(id) )
    if( $(id).next('dl dt').eq(0).is(':hidden') ){
        var i = 1;
        $(id).next('dl dt').each( function(){ $(this).fadeIn(150*i); i++ } );
    }else{
        var i = 1;
        $(id).next('dl dt').each( function(){ $(this).fadeOut(150*i); i++ } );
    }
}

function classFloatMarks(flds, obj){
    var store = {};

    var init = function(flds, obj){
        var obj, f;
        if( typeof obj == 'string' ){ obj = obj ? obj+' ' : ''; };
        if( typeof obj == 'object' ){ f = 1; }

        for(var it in flds){
            var o = f ? $('[name='+ it +']', obj) : $(obj+'[name='+ it +']');
            store[it] = {
                tag : o.attr('tagName'),
                val : flds[it]['val'],
                re  : flds[it]['re'],
                obj : o,
                err : (flds[it]['err'] || false)
            };
        }
        fn_mark();
    }

    var fn_mark = function(){
        for( var it in store ){
            var fl = store[it]['obj'];
            var val = store[it]['val'];
            if( store[it]['tag'] != 'SELECT' ){ fl.val( val ); fl.attr('defaultValue', val ); }
            else { fl.prepend( $('<option />').addClass('def-select-option').attr({selected:'selected', disabled:'disabled'}).val(0).text(val) ); }
            fl.bind('focus', fn_focus); fl.bind('blur', fn_blur);
        }
        return false;
    }

    var handler_AlertOff = function(event){ $(this).removeClass('data-warning').unbind('focus', event.handler); return false; };
    var handler_AlertOn = function(obj){ $(obj).addClass('data-warning').bind('focus', handler_AlertOff); return false; };

    var fn_focus = function(){
        if( this.tagName == 'SELECT' ){
            var opt = store[ this.name ]['obj'].find('OPTION.def-select-option');
            if(opt.length){ opt.remove(); }
            return false;
        }
        if( this.value.toLowerCase() == this.defaultValue.toLowerCase() ){ this.value = ''; return false; }
    }

    var fn_blur = function(){
        if( this.tagName == 'SELECT' ){ return false; }

        var re = store[ this.name ]['re'];
        var val = store[ this.name ]['obj'].val();
        if( !this.value.length || (/^\s+$/.test(this.value)) || this.value == this.defaultValue){ this.value = store[ this.name ]['val']; return 0; }
        if( !re.test( val ) ){
            var err = store[ this.name ]['err'] || 'Вы неверно заполнили поле "'+ (store[ this.name ]['val'].toLowerCase()) +'"';
            handler_AlertOn(store[ this.name ]['obj']);
            alert(err);
        }
        return false;
    }
    this.check = function(){
            var err = [];
            for( var it in store ){
                var o = store[it]['obj'];
                if( store[it]['tag'] != 'SELECT' ){
                    if( !o.val().length
                        || /^\s+$/.test(o.val())
                        || o.val() == store[it]['val']
                        || !store[it]['re'].test( o.val() )
                    ){ err.push(1); handler_AlertOn(o); }
                } else { if( o.val() == '0' ){ err.push(1); handler_AlertOn(o); } }
            }
            return err.length;
        }
    $(function(){ init(flds, obj); });
}

function Queue(s){
   var size = s;
   var queue = [];

    return {
        push : function(x){
            if( queue.length > size ){ return this; }
            if( queue.length == size ){ queue.shift(); }
            queue.push(x);
            return this;
        },
        out : function(){ return queue; }(),
        size : function(){ return size; }(),
        destroy : function(){ queue = []; return queue; },
        restore : function(d){ for( var i in d ){ this.push(d[i]); } return this; }
    };

   return this;
}
