$(document).ready(function(){
			$("a[rel^='prettyPhoto']").prettyPhoto();
			 $('.submenu').corner("cc:#eaeaea");
			 $('#company').limit('50','#ccompany');
			 $('#contact').limit('50','#ccontact');
			 $('#phone').limit('50','#cphone');
			 $('#fax').limit('50','#cfax');
			$('#email').limit('85','#cemail');
			$('#textf').limit('250','#ctextf');
			$('#price').limit('8','#cprice');
			$('#pricecom').limit('25','#cpricecom');
			$('#opis').limit('500','#copis');
			$('#adress').limit('85','#cadress');
			$('#tel').limit('50','#ctel');
			$('#fax').limit('50','#cfax');
			$('#worktime').limit('100','#cworktime');
			$('#web').limit('75','#cweb');
			$('#icq').limit('50','#cicq');
			$('#subj').limit('75','#csubj');
			
		});
<!--
function get_addr(Obj)
{
 var str,re;
 str = Obj.href;
 re = /\[at\]/g;
 str = str.replace(re, "@");
 this.location = str;
 return false;
}
//-->
$(function() {
$(".overlay").overlay({
	finish: {top: 'center'},
	expose: '#333333'
});});
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
//-->
function selectcountry(country, action) {
$("#cityselect_body").html('');
$("#okbutton").html('');
$("#okbutton").append('<input type="button" disabled="disabled" id="dosity" value="ок" onclick="cityselected('+action+');">');
$('#cityselect').overlay().load();
 JsHttpRequest.query('country.php',{'country': country}, function(result, errors) {
  $("#cityselect_body").append('<div id="contry">Страна:<select id="countryselect" onchange="if (this.value!=\'\') selectregion(this.value, \'\'); else {$(\'#region\').remove(); $(\'#city\').remove();};"><option value="">Выберите страну</option>'+result+'</select></div>'); 
  var cvalue=$("#countryselect").val();
  if (cvalue!='') selectregion (cvalue,'');   
});
}
 function selectregion(country, region) {
    JsHttpRequest.query('region.php',{'country': country,'region': region}, function(result, errors) {
     $("#region").remove();
     $("#city").remove();
     if (result>0 && result<255) {selectcity(result, "");} else {
    $("#cityselect_body").append('<div id="region">Регион:<select onchange="if (this.value!=\'\') selectcity(this.value, \'\'); else $(\'#city\').remove();"><option value="">Выберите регион</option>'+result+'</select></div>'); }
    });
    };
    
     function selectcity(region, city) {
    JsHttpRequest.query('city.php',{'region': region,'city': city}, function(result, errors) {
     $("#city").remove();
    $("#cityselect_body").append('<div id="city">Город:<select onchange="if (this.value!=\'\') $(\'#dosity\').removeAttr(\'disabled\'); else $(\'#dosity\').attr(\'disabled\', \'disabled\');" id="cselect"><option value="">Выберите город</option>'+result+'</select></div>'); 
    });
    };
    
    function cityselected(action) {
    var cityid = $("#cselect").val();
    var countryid = $("#countryselect").val();
    if (action==1) {
    JsHttpRequest.query('citylink.php',{'city': cityid}, function(result, errors) {
    document.location.href='/'+result+'/';  });
    } else if (action==2 || action==3) {
     JsHttpRequest.query('cityname.php',{'city': cityid, 'country': countryid}, function(result, errors) { 
    var city = (+cityid-1);
    $("#citydiv").html(result+'<input type="hidden" name="cityid" value="'+city+'">'); });
    JsHttpRequest.query('getmetro.php',{'citydescr': cityid}, function(result, errors) {
    if (result)
   if (action==2) $("#metrodiv").html('<table width="500"  border="0" cellspacing="3" cellpadding="3" align="center"><tr><td width="200" valign="top">*Станция метро:</td><td><select name="metroid" style="width:300px;"><option value="">Выберите метро</option>'+result+'</select></td></tr></table>'); else if (action==3) $("#metrodiv").html('Метро:&nbsp;<select name="metroid""><option value="">Любое</option>'+result+'</select>&nbsp;<input type="checkbox" value="1" name="near">&nbsp;Рядом с выбранной');  else 
    $("#metrodiv").html(''); 
    });
    
    }
    $('#cityselect').overlay().close();
    }
    
    function getmetrolist (cityid) {
  
      JsHttpRequest.query('getmetro.php',{'city': cityid}, function(result, errors) {
    if (result)
   $("#metrodiv").html('Метро:&nbsp;<select name="metroid"><option value="">Любое</option>'+result+'</select>&nbsp;<input type="checkbox" value="1" name="near">&nbsp;Рядом с выбранной'); else 
    $("#metrodiv").html(''); 
    });
    }

$().ready(function(){

       $("#zayavka").validate({

               rules : {

                       contact : {required : true, maxlength: 50},

                       phone : {required : true, maxlength: 50, digits: true},
                       email : {required : true, email : true, maxlength: 85},
                       cityid : "required",
                        code : {required : true},
                         text : {required : true, maxlength: 250}

               },

               messages : {

                       contact : {
                               required : "Введите ваше имя",
                               maxlength : "Максимальная длина 50 символов."
                           },
                           phone : {
                               required : "Введите номер телефона",
                               maxlength : "Максимальная длина 50 символов.",
                                digits : "Только цифры"
                           },
                            email : {
                               required : "Введите e-mail",
                               email : "Некорректный e-mail",
                               maxlength : "Максимальная длина 85 символов."
                           },

                       cityid : "Выберите город"
                       ,
                            code : {
                               required : "Введите код с рисунка"
                          
                           },
                           text : {
                               required : "Введите текст сообщения",
                               maxlength : "Максимальная длина сообщения 250 симолов"
                           }

               }

       });
       
       
        $("#msgform").validate({

               rules : {

                       contact : {required : true, maxlength: 50},

                       phone : {maxlength: 50},
                       email : {required : true, email : true, maxlength: 50},
                       subj : {required : true, maxlength: 75},
                         text : {required : true, maxlength: 150},
                          code : {required : true}

               },

               messages : {

                       contact : {
                               required : "Введите ваше имя",
                               maxlength : "Максимальная длина 50 символов."
                           },
                           phone : {
                               
                               maxlength : "Максимальная длина 50 символов."
                           },
                            email : {
                               required : "Введите e-mail",
                               email : "Некорректный e-mail",
                               maxlength : "Максимальная длина 50 символов."
                           },
                             subj : {
                               required : "Введите тему сообщение",
                               maxlength : "Максимальная длина 75 символов"
                           },
                      
                           text : {
                               required : "Введите текст сообщения",
                               maxlength : "Максимальная длина сообщения 150 симолов"
                           },
                            code : {
                               required : "Введите код с рисунка"
                          
                           }

               }

       });
       
               $("#regform").validate({

               rules : {

                      
                       email : {required : true, email : true, maxlength: 50}

               },

               messages : {

                       
                            email : {
                               required : "Введите e-mail",
                               email : "Некорректный e-mail",
                               maxlength : "Максимальная длина 50 символов."
                           }

               }

       });
       
        $("#sendmessageform").validate({

               rules : {

                      to_email : {email : true, maxlength: 75},
                       subj : {required : true, maxlength: 75}

               },

               messages : {

                       
                            to_email : {
                              
                               email : "Некорректный e-mail",
                               maxlength : "Максимальная длина 75 символов."
                           },
                             subj : {
                               required : "Введите тему сообщение",
                               maxlength : "Максимальная длина 75 символов"
                           }

               }

       });
       
        $("#addmsg").validate({

               rules : {

                       addntype : "required",
                      usertype : "required",
                       
                       cityid : "required",
                       price : {required : true, maxlength: 50, digits:true}, 
                         text : {required : true, maxlength: 500},
                         "imagefile[]" : {maxlength: 500}

               },

               messages : {

                       addntype : "Выберите тип недвижимости",
                       usertype : "Выберите тип операции",
                          

                       cityid : "Выберите город",
                       price : {
                               required : "Укажите стоимость аренды",
                               maxlength : "Максимальная длина поля 50 символов",
                               digits : "Только цифры"
                          
                           },
                           
                           text : {
                               required : "Введите текст сообщения",
                               maxlength : "Максимальная длина сообщения 500 симолов"
                           },
                           "imagefile[]" : "Максимальная длина сообщения 500 симолов"

               }

       });
       
         $("#agentform").validate({

               rules : {
                        "status[]" : "required",
                        company : {required : true, maxlength: 75},
                      cityid : "required",
                      metroid : "required",
                      adress : {maxlength: 85},
                       tel : {required : true, maxlength: 50},
                        fax : {maxlength: 50},
                        worktime : {maxlength: 100},
                        contact : {required : true, maxlength: 50},
                        web : {maxlength: 75},
                        icq : {maxlength: 50, digits:true}, 
                         descr : {required : true, maxlength: 500}

               },

               messages : {
                              "status[]" : "Укажите ваш статус",
                              company : {
                               required : "Введите навание компании",
                               maxlength : "Максимальная длина 75 симолов"
                           },
                       cityid : "Выберите город",
                       metroid : "Выберите метро",
                       adress : "Максимум 85 символов",
                        tel : {
                               required : "Введите номер телефона",
                               maxlength : "Максимальная длина 50 симолов"
                           },
                            fax : "Максимум 50 символов",
                             worktime : "Максимум 100 символов",
                             contact : {
                               required : "Укажите контактное лицо",
                               maxlength : "Максимальная длина 50 симолов"
                           },
                           web : "Максимум 75 символов",
                       
                       icq : {
                               maxlength : "Максимальная длина поля 50 символов",
                               digits : "Только цифры"
                            },
                            descr : {
                               required : "Введите текст сообщения",
                               maxlength : "Максимальная длина сообщения 500 симолов"
                           }

               }

       });
       
          $("#addadvform").validate({

               rules : {

                      
                       link : {required : true, url : true}

               },

               messages : {

                       
                            link : {
                               required : "Введите url",
                               url : "Некорректный url"
                           }

               }

       });

});


  function ReadOnly(obj,flag)
  {
    obj.readOnly = flag;
  }
  function SelectAll(obj)
  {
    obj.select();
  }
  function unSelectAll(obj)
  {
    obj.value=obj.value;
  }


function addfilefield(max) {
$("#fotos").append('<br /><input name="imagefile[]" type="file" maxlength="25" style="width:230px;">');
var a=0;
$("input:file").each( function () {
a=+a+1;
if (a==max) $("#fotosadd").remove();
});
}

function open_win( pageToLoad, winname, width, height ) {

        args = "width=" + width + ",height=" + height + ",location=0,menubar=0,resizable=1,scrollbars=1,status=0,titlebar=0,toolbar=0,hotkeys=0";
        popup_win = window.open( pageToLoad,winname,args );
        popup_win.name = winname;
        popup_win.window.focus();
        //popup_win.window.moveTo(0,0);
        return ;
}

function newwin( pageToLoad) {

        args = "location=1,menubar=1,resizable=1,scrollbars=1,status=1,titlebar=1,toolbar=1,hotkeys=1";
        popup_win = window.open( pageToLoad,'',args );
        //popup_win.name = winname;
        popup_win.window.focus();
        //popup_win.window.moveTo(0,0);
        return ;
}

function CheckString(aValue)
{
	var __value = aValue;
	
	while(__value.length)
	{
		if(__value.charAt(0) == ' ')
			__value = __value.substring(1, __value.length);
		else
			break;
	}
	
	if(!__value.length)
		return false;
	
	return true;
}

function CheckInt(aValue, aOpt)
{
	
	if(aOpt == null)
		aOpt = false;


	if(!String(aValue).length)
	{
		if(aOpt)
			return false;
		else
			return true;
	}
	
	var str = String(aValue);
	
	if (str.match(/[^\d]/))
	 return false;
	
	var __value = parseInt(aValue);

	//if(isNaN(__value) || String(__value) != String(aValue))
	if(isNaN(__value))
		return false;

	return true;	
}

function CheckForm(aForm)
{
	for(var j = 0;j < aForm.elements.length;j++)
	{
		if(aForm.elements[j].ftype == null)
			continue;
		
		var str = aForm.elements[j].ftype;

		var ftype = null;
		var alt = " ";
		var low = null;
		var high = null;
		
		var findex = 0;
		var index = str.indexOf(':');
		while(index != -1)
		{
			var s = str.substring(0,index);
			if(findex == 0)
				ftype = s;
			if(findex == 1)
				alt = s + " ";
			if(findex == 2)
				low = s;
			if(findex == 3)
				high = s;
			str = str.substring(index+1, str.length);
			index = str.indexOf(':');
			findex++;
		}
		var s = str;
		if(s.length)
		{
			if(findex == 0)
				ftype = s;
			if(findex == 1)
				alt = s + " ";
			if(findex == 2)
				low = s;
			if(findex == 3)
				high = s;
		}

		if(ftype == "str")
		{
			var str = String(aForm.elements[j].value);
			
			aForm.elements[j].value = str;
			
			if(!CheckString(aForm.elements[j].value))
			{
				alert('Please enter ' + alt + 'field');
				aForm.elements[j].focus();
				aForm.elements[j].select();
				return false;
			}
			if(low != null)
			{
				if(aForm.elements[j].value.length >= parseInt(low))
				{
					alert('Maximum field ' + alt + 'length is ' + low);
					aForm.elements[j].focus();
					aForm.elements[j].select();
					return false;
				}
			}
			
		}
		else if(ftype == "num")
		{
			var isLow = false;
			if(low == null || low == "")
				low = 0;
			else
				isLow = true;

			var svalue = aForm.elements[j].value;
	
			while(svalue.length)
			{
				if(svalue.charAt(0) == '0' && svalue.length > 1)
					svalue = svalue.substring(1, svalue.length);
				else
					break;
			}
			aForm.elements[j].value = svalue;


			if(!CheckInt(aForm.elements[j].value, true))
			{
				alert('Field ' + alt + 'should be a whole number');
				aForm.elements[j].focus();
				aForm.elements[j].select();
				return false;
			}

			if(parseInt(aForm.elements[j].value) > 2147483646)
			{
				alert('Field ' + alt + 'is too big');
				aForm.elements[j].focus();
				aForm.elements[j].select();
				return false;
			}

			if(parseInt(aForm.elements[j].value) < -2147483648)
			{
				alert('Field ' + alt + 'is too low');
				aForm.elements[j].focus();
				aForm.elements[j].select();
				return false;
			}


			if(low != null)
			{
				if(aForm.elements[j].name == "alcoholcontent")
				if(isLow)
				{
					if(parseInt(aForm.elements[j].value) <= parseInt(low))
					{
						alert('Field ' + alt + 'value should be more then ' + low);
						aForm.elements[j].focus();
						aForm.elements[j].select();
						return false;
					}
				}
				else
				{
					if(parseInt(aForm.elements[j].value) < parseInt(low))
					{
						alert('Field ' + alt + 'value should be more or equal then ' + low);
						aForm.elements[j].focus();
						aForm.elements[j].select();
						return false;
					}
				}
			}
			if(high != null)
			{
				if(parseInt(aForm.elements[j].value) > parseInt(high))
				{
					alert('Field ' + alt + 'value should be less or equal then ' + high);
					aForm.elements[j].focus();
					aForm.elements[j].select();
					return false;
				}
			}
		}
		else if(ftype == "text")
		{
			if(low != null && low > 0 && !CheckString(aForm.elements[j].value))
			{
				alert('Please enter ' + alt + 'field');
				aForm.elements[j].focus();
				aForm.elements[j].select();
				return false;
			}
			if(low != null && low > 0)
			{
				if(aForm.elements[j].value.length < parseInt(low))
				{
					alert('Please enter at least ' + low + ' symbols into ' + alt);
					aForm.elements[j].focus();
					aForm.elements[j].select();
					return false;
				}
			}

			if(high != null)
			{
				if(aForm.elements[j].value.length >= parseInt(high))
				{
					alert('Maximum ' + alt + 'length is ' + high);
					aForm.elements[j].focus();
					aForm.elements[j].select();
					return false;
				}
			}
		}
		else if(ftype == "date")
		{
			dv = aForm.elements[j].value;
			err = false;			
			if( low == "hour" && (dv < 1 || dv > 12))
			{
				alert('Please, enter correct hour value between 1 and 12');
				err = true;
			}
			else if( low == "min" && (dv < 0 || dv > 59))
			{
				alert('Please, enter correct minutes value between 0 and 59');
				err = true;
			}

			if( err )
			{
				aForm.elements[j].focus();
				aForm.elements[j].select();
				return false;
			}
		}
	}	

	return true;
}



function ShowText(aID, aFlag)
{

	if (!aFlag)
	{
	 document.all("stext_"+aID).style.display = 'none';
	 document.all("text_"+aID).style.display = '';
	}
	else
	{
	 document.all("stext_"+aID).style.display = '';
	 document.all("text_"+aID).style.display = 'none';
	}
}

function ShowSearchHelp()
{
	var aFlag = (document.all('search_help').style.display == '');
	
	if (!aFlag)
	{
		document.all('search_help').style.display = '';
	}
	else
	{
		document.all('search_help').style.display = 'none';
	}
}

function str_replace ( search, replace, subject ) {    // Replace all occurrences of the search string with the replacement string
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
 
    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }
 
    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }
 
    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }
 
    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }
 
    return subject;
 
}

function getBrowserInfo() {
 var t,v = undefined;
 if (window.opera) t = 'Opera';
 else if (document.all) {
  t = 'IE';
  var nv = navigator.appVersion;
  var s = nv.indexOf('MSIE')+5;
  v = nv.substring(s,s+1);
 }
 else if (navigator.appName) t = 'Netscape';
 return {type:t,version:v};
}
 
function bookmark(a){
 var url = window.document.location;
 var title = window.document.title;
 var b = getBrowserInfo();
 if (b.type == 'IE' && 7 > b.version && b.version >= 4) window.external.AddFavorite(url,title);
 else if (b.type == 'Opera') {
  a.href = url;
  a.rel = "sidebar";
  a.title = url+','+title;
  return true;
 }
 else if (b.type == "Netscape") window.sidebar.addPanel(title,url,"");
 else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
 return false;
}
