
(function($) {
$.extend({

        debounce : function(fn, timeout, invokeAsap, context) {

                if(arguments.length == 3 && typeof invokeAsap != 'boolean') {
                        context = invokeAsap;
                        invokeAsap = false;
                }

                var timer;

                return function() {

                        var args = arguments;

                        if(invokeAsap && !timer) {
                                fn.apply(context, args);
                        }

                        clearTimeout(timer);

                        timer = setTimeout(function() {
                                if(!invokeAsap) {
                                        fn.apply(context, args);
                                }
                                timer = null;
                        }, timeout);

                };

        },

        throttle : function(fn, timeout, context) {

                var timer, args;

                return function() {

                        args = arguments;

                        if(!timer) {
                                (function() {
                                        if(args) {
                                                fn.apply(context, args);
                                                args = null;
                                                timer = setTimeout(arguments.callee, timeout);
                                        }
                                        else {
                                                timer = null;
                                        }
                                })();
                        }

                };

        }

});

})(jQuery);



window.is_object = function(_var){
    return typeof _var == 'object';
}
window.createElementE = function(t, a, s){
    el = document.createElement(t);

    if(is_object(a))
        for(_a in a)
            el[_a] = a[_a];

    if(is_object(s))
        for(_s in s)
            el.style[_s] = s[_s];

    return el;
}


$(document).ready(function(){
  $('#kvaLogo').click(function(){location.href='/';}).css("cursor","pointer");  
  $('#peoplesOpinion p').click(function(){location.href='/ratings/';}).css("cursor","pointer");  
  $("#menu_country").click(function(){if($('#menu_country+span').css("display") != "block"){$('#menu_country+span').css("display","block");}else{$('#menu_country+span').css("display","none");}return false;}).css("cursor","pointer");
  $("#menu_second").click(function() {
				if ($('#menu_second+span').css("display") != "block") {
					$('#menu_second+span').css("display", "block");
				} else {
					$('#menu_second+span').css("display", "none");
				}
				return false;
			}).css("cursor", "pointer");
  $("#menu_information").click(function(){if($('#menu_information+span').css("display") != "block"){$('#menu_information+span').css("display","block");}else{$('#menu_information+span').css("display","none");}return false;}).css("cursor","pointer");  
  $('table.colored-table').find('tr:even').css('background-color', '#f5f9dd');
  $('table.colored-table').find('tr:odd').css('background-color', '#e8f1b3');
  
  $('table.color-table').find('tr:even[className!="asd"]').addClass('color-1');
  $('table.color-table').find('tr:odd').addClass('color-2');
  
  $('input.remember-default').each(function(){
  	this._defaultValue = $(this).attr('title');  	
  }).change(function(){  	
  	if ($(this).val() == '') {  		
  		$(this).val(this._defaultValue).addClass('default-value');
  	}
  }).click(function(){  	
  	if ($(this).val() == this._defaultValue) {
  		$(this).val('').removeClass('default-value');
  	}   
  }).blur(function(){  	
  	if ($(this).val() == '') {
  		$(this).val(this._defaultValue).addClass('default-value');
  	}
  }).focus(function(){  	
   	$(this).trigger('click');
  });  
});

  function showbig(picname){
    window.open('/includes/foto.php5?pic='+picname,'_blank','scrollbars=yes,taskbar=no,resizeable=no,status=no,menubar=no,top=30,left=30,width=30,height=30');
  }



  function showMap(mapUrl){
    window.open(mapUrl,'_blank','scrollbars=yes,taskbar=no,resizeable=no,status=no,menubar=no,top=30,left=30,width=730,height=470');
  }

   function showSpbMap(mapUrl){
    window.open(mapUrl,'_blank','scrollbars=no,taskbar=no,resizeable=no,status=no,menubar=no,top=30,left=30,width=561,height=780');
  }

  function PreLoad(source){
    var NewImage = new Image();
    NewImage.src = source;
  }

  function prepareSubmit(frm){
    var len = frm.all("editbox").length; if (!len) len = 1;
    for (var i=0; i<len; i++)
      frm.all("codebox", i).innerText = frm.all("codebox", i).style.display ? borderOn(frm.all("codebox", i).innerText) : borderOn(frm.all("editbox", i).innerHTML);
  }

 function menuProcess(menuId){
   menuId = document.getElementById(menuId);
    if(menuId.style.display == 'none'){
     menuId.style.display = 'block';
   }else{
      menuId.style.display = 'none';
   }
 }

 function btShowFunctionArguments(name){
   btChangeFunctionArgumentsBlock(name,'none','block','block');
 }

 function btHideFunctionArguments(name){
   btChangeFunctionArgumentsBlock(name,'block','none','none');
 }

 function btChangeFunctionArgumentsBlock(name,plus,minus,arguments){
    document.getElementById('backtrace_img_plus_'+name).style.display = plus;
    document.getElementById('backtrace_img_minus_'+name).style.display = minus;
    document.getElementById('backtrace_arguments_'+name).style.display = arguments;
 }


 function showObject(pathToObject){
   window.open(pathToObject,'_blank','scrollbars=yes,taskbar=no,resizeable=no,status=no,menubar=no,top=30,left=30,width=510,height=300');
 }

 function ge(id){
   return document.getElementById(id);
 }

 function printSelected(){
   if(ge('obj_form')){
     var ids = new Array();
     var _count = 0;

     form = ge('obj_form');
     objCount = form.elements.length - 1;

     for(i=0; i <= objCount; i++){
       formElement = form.elements[i];
       if(formElement.type && formElement.type == 'checkbox' && formElement.value && formElement.checked){
         ids[_count] =formElement.value;
         _count ++;
       }
     }
     if(ids.lenght == 0){
       alert('Не выбрано не одного объекта!');
       return false;
     }
     newWindow = window.open('','_blank','scrollbars=yes,taskbar=yes,resizeable=yes,status=yes,menubar=yes,top=30,left=30,width=1024,height=1000');
     wDoc = newWindow.document;
     wDoc.write ('<html>');
     wDoc.write ('Загрузка данных...');
     wDoc.write ('<form action="/estate/second/print/" method="POST" id="ids_form">');
     for(i=0 ; ids[i] ; i++)
       wDoc.write ('<input type="hidden" value="' +ids[i] +'" name="id[]">');
    wDoc.write ('</form>');
     wDoc.getElementById('ids_form').submit();;
   }
 }

 function validateCommentForm(formName, withAuth){
  if(document.forms(formName).comment_text.value == ''){
    alert('Введите текст комментария');
    return false;
  }
  if(document.forms(formName).username.value == '' && withAuth){
    alert('Введите имя');
    return false;
  }
  if(document.forms(formName).password.value == '' && withAuth){
    alert('Введите пароль');
    return false;
  }
}

  function voteForObject(mark){
    url = location.href + '?mark=' + mark;

     JsHttpRequest.query(
           url,'',
            function(result, msg) {
              $('#vote_rezult').html(msg);
         },
            true
        );
  }
  
  function voteForObject(mark){
    url = location.href + '?mark=' + mark;

     JsHttpRequest.query(
           url,'',
            function(result, msg) {
              $('#vote_rezult').html(msg);
         },
            true
        );
  }
  
   function voteForObjectExtended(cId, objPath, mark, pref, id, base){     
     if(base == undefined)
        base = 'estate';
     switch(cId){
         case 5:
            section = 'new_buildings';
         break;
         case 7:
            section = 'settlements';
         break;
         default:
            return;            
     }
     $('#' + pref + 'mark_' + id + '_vote').html('').addClass('load');     
     url = '/' + base + '/' + section + '/'+objPath+'/?mark='+mark+'&getJSON';
     
     $.getJSON(url, {}, function(data){
         
         if(data['status'] && data['status'] == 1){
         
             $('#' + pref + 'mark_' + id + '_vote').html('Спасибо, Ваш голос учтён!<br>Всего проголосовало: ' + data['opinions'] + '<br>Рейтинг: ' + data['rating']).removeClass('load');
             _r = parseFloat(data['rating']);
             if(_r < 4 && _r >= 0) _r = 'least'; else if(_r >= 4 && _r < 8) _r = 'medium'; else if(_r >= 8) _r = 'highest';
             $('#' + pref + 'wrapper_' + id + ' .mark').removeClass('highest').removeClass('medium').removeClass('least');
             $('#' + pref + 'wrapper_' + id + ' .mark').addClass(_r);
             $('#' + pref + 'wrapper_' + id + ' .mark .txt').html(data['rating']);
         }
     });
     /*JsHttpRequest.query(
           url,'',
            function(result, msg) {
              $('#' + div).html(msg).removeClass('load');
         },
            true
        );*/
  }

  function ShowLogin(yes){
    if(yes){
      document.getElementById('site_enter_link').style.display = 'none';
      document.getElementById('site_enter_form').style.display = 'block';
    }
    else{
      document.getElementById('site_enter_link').style.display = 'block';
      document.getElementById('site_enter_form').style.display = 'none';
    }
  }
  
 if(!pages_list_class_list){
	var pages_list_class_list = new Array();
}
var pages_list_class = function(name){
	this.name = name;
	this.global = "pages_list_class_list['"+name+"']";
	this.count = 0;
	this.selected = 0;
	this.url = '';
	this.move_index = null;	
	
// Определяем браузеры
	var ua = navigator.userAgent.toLowerCase();
	this.isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1);
	this.isGecko = (ua.indexOf("gecko") != -1);
	
//Выводит код всего блока
	this.build = function(id){
		//$('#'+name+'_pages_list .wrapper ul').html('<li>'+this.get_list_HTML().join('</li><li>')+'</li>');
		var div = document.getElementById(name+'_wrapper');
		div.innerHTML = this.get_list_HTML().join('&nbsp;');
		if(div.offsetWidth>600) div.style.width = 300;
		//alert(div.offsetWidth);
		
		$('#'+name+'_pages_list .previous').mouseover(function(){
			pages_list_class_list[''+name].move_left();
		}).mouseout(function(){
			pages_list_class_list[''+name].move_stop();
		});
		
		$('#'+name+'_pages_list .next').mouseover(function(){
			pages_list_class_list[''+name].move_right();
		}).mouseout(function(){
			pages_list_class_list[''+name].move_stop();
		});
		this.move_this();
		
		//this.set_ctrl_move();
	}
	
	this.calculateObjectFullWidth = function(objectId){
		styles = new Array('width', 'margin-left', 'margin-right', 'padding-left', 'padding-right');
		width = 0;
		for (sId in styles) {        		
			width += parseInt($('#' + objectId).css(styles[sId]));
		}
		return width;
	}
	
//Выводит код всего блока
	/*this.build = function(id){
		if(id){
			document.getElementById(id).innerHTML = this.get_HTML();
		}else{
			document.write(this.get_HTML());
		}
		this.move_this();
		this.set_ctrl_move();
	}*/
	
//Возвращает код всего блока
	/*
	this.get_HTML = function(){
		if(this.count < 2) return '';
		return ''+
		'<table cellpadding="0" cellspacing="0" class="pages_list">'+
			'<tr>'+
				'<td class="previous" onmouseover="'+this.global+'.move_left()" onmouseout="'+this.global+'.move_stop()">'+
					(this.selected!=1?'<a href="'+this.get_link(this.selected-1)+'">предыдущая</a>':'предыдущая')+
				'</td>'+
				'<td class="list"><div id="'+this.name+'_div">'+this.get_list_HTML().join('')+'</div></td>'+
				'<td class="next" onmouseover="'+this.global+'.move_right()" onmouseout="'+this.global+'.move_stop()">'+
					(this.selected!=this.count?'<a href="'+this.get_link(this.selected+1)+'">следующая</a>':'следующая')+
				'</td>'+
			'</tr>'+
			'<tr>'+
				'<td class="first">'+(this.selected!=1?'<a href="'+this.get_link(1)+'">первая</a>':'')+'</td>'+
				'<td class="ctrl">Ctrl</td>'+
				'<td class="last">'+(this.selected!=this.count?'<a href="'+this.get_link(this.count)+'">последняя</a>':'')+'</td>'+
			'</tr>'+
		'</table>';
	}*/
	
//Возвращает список страниц
	this.get_list_HTML = function(){
		if(this.count < 2) return '';
		var arr = new Array(this.count);
		for(var i = 1; i<=this.count; i++){
			arr[i-1] = i == this.selected ? this.get_selected_page_HTML(i) : this.get_page_HTML(i);			
		}
		return arr;
		//return arr.join('');
		//return '<table cellpadding="0" cellspacing="0"><tr><td>'+arr.join("</td><td>")+'</td></tr></table>'
	}
	
//Возвращает код текущей страницы
	this.get_selected_page_HTML = function(i){
		return '<a href="'+this.get_link(i)+'" class="selected">'+i+'</a>';
	}
	
//Возвращает код страницы-ссылки
	this.get_page_HTML = function(i){
		return '<a href="'+this.get_link(i)+'">'+i+'</a>';
	}
	
//Возвращает ссылку по номеру страницы
	this.get_link = function(i){
		return this.url.replace(/\$page/g, i);
	}
	
//Проматывает на текущий пункт
	this.move_this = function(){
		this.move_stop();
		var div = document.getElementById(name+'_wrapper');
		n_len = 8;
		p_len = 8; 
		n_count = this.selected + (this.selected>9 ? this.selected-9 : 0) + (this.selected>99 ? this.selected-99 : 0) + (this.selected>999 ? this.selected-999 : 0);
		p_count = this.selected;
		div.scrollLeft = n_count * n_len + p_count * p_len - div.clientWidth / 2;
	}
	
//Начинает мотать влево
	this.move_left = function(){
		//$('#'+name+'_pages_list .wrapper').animate({left:0}, 2000);
		this.move_stop();
		var div = document.getElementById(name+'_wrapper');
		if(div.scrollLeft>0){
			div.scrollLeft-=3;
		}
		this.move_index = window.setTimeout(this.global+'.move_left()', 20);
	}
	
//Начинает мотать вправо
	this.move_right = function(){
		//pagesList = $('#'+name+'_pages_list .wrapper ul');
		//lastPageId = pagesOffsets.length - 1;
		//offset = -pagesOffsets[lastPageId] + pagesList.parent().width() - this.calculateObjectFullWidth('page_' + lastPageId);	
		//pagesList.animate({left: offset}, 2000);
		//$('#'+name+'_pages_list .wrapper').animate({left:document.getElementById('wrapper').scrollWidth}, 2000);
		this.move_stop();
		var div = document.getElementById(name+'_wrapper');
		if(div.scrollLeft < div.scrollWidth){
			div.scrollLeft+=3;
		}
		this.move_index = window.setTimeout(this.global+'.move_right()', 20);
	}
	
//Останавливает промотку
	this.move_stop = function(){
		//$('#'+name+'_pages_list .wrapper').stop();
		if(this.move_index){
			window.clearTimeout(this.move_index);
		}
		this.move_index = null;
	}

//Включает переход по ctrl
	this.set_ctrl_move = function(){
		if (this.isIE){ 
			$(document).keydown(function(evt){pages_list_class_list[''+name].key_press(evt)}); 
		}else{ 
			$(document).keypress(function(evt){pages_list_class_list[''+name].key_press(evt)});
		}
	}
	
//Обработка нажатия клавиши
	this.key_press = function(evt){
		evt = evt || window.event;
		var key = evt.keyCode || evt.which;
		if(evt.ctrlKey && ((key==37 && this.selected!=1) || key==39 && (this.selected!=this.count))){
			if(evt.preventDefault) evt.preventDefault();
			evt.returnValue = false;
			location.href = this.get_link(key==37 ? this.selected-1 : this.selected+1);
		}
	}
	
	pages_list_class_list[''+name] = this;
}



