$(function(){	   
	var userAgent = navigator.userAgent.toLowerCase();
	
	$.browser = {
        version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
        safari: /webkit/.test( userAgent ),
        opera: /opera/.test( userAgent ),
        msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
        mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
    };
		
    $('input').keydown(function(e){								
        if (e.keyCode == 13) {			
            valid_submission(this);
            return false;
        }
    });
});

function valid_submission(inp){
	if($(inp).val()!='') {
		$(inp).parents('form').submit();
	}
	
}

function openGallery(type,ID,filename) {
var img = new Image();
img.src = "properties/"+type+"-"+ID+"/"+filename+".jpg";
mywidth = img.width;
myheight = img.height;
if((type=='apartments')||(type=='village')||(type=='apartment')) {mywidth=640; myheight=480;}
window.open('/gallery.html?type='+type+'&ID='+ID+'&filename='+filename+'','gallery','width='+mywidth+',height='+myheight+',toolbar=0,menubar=0,scrollbars=0,status=0,resizable=0');
}

function openHGallery(type,ID,nr) {
var img = new Image();
img.src = "http://www.daoreal.com/icon/"+type+"/"+ID+"/"+nr+".jpg";
mywidth = img.width;
myheight = img.height;
window.open('/gallery.html?type='+type+'&ID='+ID+'&filename='+nr+'','gallery','width='+mywidth+',height='+myheight+',toolbar=0,menubar=0,scrollbars=0,status=0,resizable=0');
}

function openLGallery(type,location,nr) {
var img = new Image();
img.src = "/images/locations/"+location+"-"+nr+".jpg";
mywidth = img.width;
myheight = img.height;
window.open('/gallery.html?type='+type+'&location='+location+'&nr='+nr+'','gallery','width='+mywidth+',height='+myheight+',toolbar=0,menubar=0,scrollbars=0,status=0,resizable=0');
}

function openMGallery(type,map) {
var img = new Image();
img.src = "/images/maps/"+map+".jpg";
mywidth = img.width;
myheight = img.height;
window.open('/gallery.html?type='+type+'&map='+map+'','gallery','width='+mywidth+',height='+myheight+',toolbar=0,menubar=0,scrollbars=0,status=0,resizable=0');
}

function openCallback() {
window.open('/callback.html','callback','width=270, height=440, toolbar=0,menubar=0,scrollbars=0,status=0,resizable=0');
}

function openInfoRequest() {
window.open('/info-request.html','infoRequest','width=300, height=590, toolbar=0,menubar=0,scrollbars=0,status=0,resizable=0');
}

function openCatalog() {
window.open('/catalogue.html','catalogue','width=800, height=600, toolbar=0,menubar=0,scrollbars=0,status=0,resizable=0');	
}

function common_search_form_submit(form) {

if (document.common_search_form_a.property_type.options[0].selected) {document.common_search_form_a.action="/Bulgaria-apartments-search.html?page=1&numBegin=1&begin=0&order=price#focus";}
if (document.common_search_form_a.property_type.options[1].selected) {document.common_search_form_a.action="/Bulgaria-houses-search.html?page=1&numBegin=1&begin=0&order=ID&type=0#focus";}
if (document.common_search_form_a.property_type.options[2].selected) {document.common_search_form_a.action="/Bulgaria-private-villages.html#focus";}
if (document.common_search_form_a.property_type.options[3].selected) {document.common_search_form_a.action="/Bulgaria-lands-search.html?page=1&numBegin=1&begin=0&order=ID&type=0#focus";}
if (document.common_search_form_a.property_type.options[4].selected) {document.common_search_form_a.action="/Bulgaria-hotels.html";}
if (document.common_search_form_a.property_type.options[5].selected) {document.common_search_form_a.action="/Bulgaria-buildings-investment.html";}
if (document.common_search_form_a.property_type.options[6].selected) {document.common_search_form_a.action="/Bulgaria-commercial-premises.html";}
	document.common_search_form_a.submit();

}

function price_range_submit(formName,url,min_p,max_p) {
	$("form[name='"+formName+"']").attr('action',url);
	$("#price_min").val(min_p);
	$("#price_max").val(max_p);
	$("form[name='"+formName+"']").submit();
}

function info_request_submit() {
var name=document.info_request.name.value;
var mail=document.info_request.mail.value;
var comment=document.info_request.comment.value;
if(name=='') {
	document.getElementById('noname').innerHTML=""; 
	document.getElementById('noname').innerHTML="Вы не написали Ваше имя !";
} 
else {
	document.getElementById('noname').innerHTML="";
	document.getElementById('noname').innerHTML="";
}
if(!emailCheck(mail)) {
	document.getElementById('nomail').innerHTML="";
	document.getElementById('nomail').innerHTML+="Вы не написали Ваш e-mail / невалидный e-mail !";
} 
else {
	document.getElementById('nomail').innerHTML="";
	document.getElementById('nomail').innerHTML+="";
}
if(!filterSpam(comment)) {
	document.getElementById('invcomment').innerHTML="";
	document.getElementById('invcomment').innerHTML+="Невалидный символ в тексте коментария. Возможна попытка спама";
} 
else {
	document.getElementById('invcomment').innerHTML="";
	document.getElementById('invcomment').innerHTML+="";
}

if((name!='')&&(emailCheck(mail))&&filterSpam(comment)){document.info_request.submit();}	

}

function callback_submit() {
var name=document.callback.name.value;
var mail=document.callback.mail.value;
var phone=document.callback.phone.value;

if(name=='') {document.getElementById('noname').innerHTML="Вы не написали Ваше имя !";} else {document.getElementById('noname').innerHTML="";}
if(phone=='') {document.getElementById('nophone').innerHTML="Вы не написали Ваш телефон !";} else {document.getElementById('nophone').innerHTML="";}
if(!emailCheck(mail)) {document.getElementById('nomail').innerHTML="Вы не написали Ваш e-mail /<br/>невалидный e-mail !";} else {document.getElementById('nomail').innerHTML="";}
if((name!='')&&(phone!='')&&(emailCheck(mail))){document.callback.submit();}	

}

function common_info_request_submit() {
var name=document.common_info_request.name.value;
var mail=document.common_info_request.mail.value;

if(name=='') {document.getElementById('noname').innerHTML="Вы не написали Ваше имя !";} else {document.getElementById('noname').innerHTML="";}
if(!emailCheck(mail)) {document.getElementById('nomail').innerHTML="Вы не написали Ваш e-mail / невалидный e-mail !";} else {document.getElementById('nomail').innerHTML="";}
if((name!='')&&(emailCheck(mail))){document.common_info_request.submit();}	

}

function forum_search_submit(page,numBegin,begin) {
	document.forum_search_form.action="/real-estates-Bulgaria-forum.html?search=1&page="+page+"&numBegin="+numBegin+"&begin="+begin;
	document.forum_search_form.submit();
}

function search_form_submit(formName,url,page,numBegin,begin,order,type)
{
	var containerName = "focus";
	$("form[name='"+formName+"']").attr('action',url+"?page="+page+"&numBegin="+numBegin+"&begin="+begin+"&order="+order+"&type="+type+"#"+containerName);
	$("form[name='"+formName+"']").submit();
}

validateForm = function(formdata) {
										
					field_OK_classname = "fieldstatus-ok";
					field_error_classname = "fieldstatus-error";
					status_icon_suffix = "_status";
					html_regexp = /<[a-zA-Z\/][^>]*>/g;
					error_message = "Ошибки при заполнении полей формы !";
					success_message = "";
					error_icon = "/images/icons/validate-error.png";
					success_icon = "/images/icons/validate-ok.png";
					mail_success = "";
					mail_error = "";
					
					if(formdata.formID) 
					{
						form = $("#"+formdata.formID+"");
						formAction = formdata.formAction;
						mailtype = formdata.mailtype;
					}			
										
					$.validation = {
						
						
						process: function(field)
						{
							var valid = false;
							$.each(field.validations, function(i, type) {
								valid = false;
    							switch(type)
								{
									case 'minlength':
										if( $("[name='"+field.field_name+"']").val().length  >= field.min_length )
										{
											valid = true;
										}
									break;
									case 'mail':
										emailStr = $("[name='"+field.field_name+"']").val();
																	
										var validmail = true;
										var emailPat=/^(.+)@(.+)$/;
										var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
										var validChars="\[^\\s" + specialChars + "\]";
										var quotedUser="(\"[^\"]*\")";
										var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
										var atom=validChars + '+'
										var word="(" + atom + "|" + quotedUser + ")";
										var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
										var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
										var matchArray=emailStr.match(emailPat);
	
										if (emailStr=='') {
												validmail = false; 
										}
										
										if (matchArray==null) {
											validmail = false;
										}								
										else
										{
											var user=matchArray[1];
											var domain=matchArray[2];	
										
											if (user.match(userPat)==null) {
    											validmail = false;
											}
											var IPArray=domain.match(ipDomainPat);
											if (IPArray!=null) {
    										// this is an IP address
	  											for (var i=1;i<=4;i++) {
	    											if (IPArray[i]>255) {
														validmail = false;
	   												}
    											}
   												validmail = true;
											}
											var domainArray=domain.match(domainPat);
											if (domainArray==null) {
    											validmail = false;
											}
											var atomPat=new RegExp(atom,"g");
											var domArr=domain.match(atomPat);
											var len=domArr.length;
											if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>6) {
  	 											validmail = false;
											}
											if (len<2) {
  												var errStr="This address is missing a hostname!";
   												validmail = false;
											}
										
										}
										
										if(validmail) {valid = true;}
									break;
									
									case 'html':
										
										var matchhtml=$("[name='"+field.field_name+"']").val().match(html_regexp);
										if (matchhtml==null) {
											valid = true;
										}		
									break;
								}
							});
							
							if( $("#"+field.field_name+status_icon_suffix) )
							{
								
								icon = $("#"+field.field_name+status_icon_suffix);
								icon.removeClass(field_OK_classname);
								icon.removeClass(field_error_classname);
								
								var arr = [ "required", "required-ok", "required-err" ];
								
								if($.inArray( $("[name='"+field.field_name+"']").attr("title"), arr )!=-1 )
								{
									title = "required-";
								}
								else
								{
									title = "";
								}
								
								if(valid)
								{
									icon.addClass(field_OK_classname);
									$("[name='"+field.field_name+"']").attr("title",title+"ok");
								}
								else
								{
									icon.addClass(field_error_classname);
									$("[name='"+field.field_name+"']").attr("title",title+"err");
									
								}
							}
						}
					}
	
					if(formdata.mode == 'field')
					{
						//console.log("da");
						var field = formdata.fields[0];
						$.validation.process(field);
					}
					else
					{
						var arrValidation = [];
						form = $("#"+formdata.formID);
						form.find("input,textarea").each(
							function(i,Element)
							{
								var result = $(Element).trigger('blur');
								
								if(Element.title == "required-ok")
								{
									arrValidation.push(0);
								}
								else if(Element.title == "required-err")
								{
									arrValidation.push(1);
								}
									
								else
								{
									if($(Element).val().length>0 && Element.title == "err")
									{
										arrValidation.push(1);
									}
									else
									{
										arrValidation.push(0);
										$("#"+Element.name+status_icon_suffix).attr("class","fieldstatus png");
									}
								}
							}
						);
						
					
						h = $(document).height();
						closePopup = function() {
							$("#popup-container").remove();
							$("#popup-dialog").remove();
						}
						
						$(document).keydown(function(e){								
        					if (e.keyCode == 27) {
								closePopup();
        					}
   						 });
						
						if($.inArray(1,arrValidation)==-1)
						{
							mail_success = formdata.UI.mail_success;
							mail_error = formdata.UI.mail_error;
							
							message = mail_success;
							icon = success_icon;
							
							mailer(form,formAction,mailtype);
							/* 
							if(message=="1")
							{
								message = mail_success;
								icon = success_icon;
							}
							else
							{
								message = mail_error;
								icon = error_icon;
							}
							*/
						}
						else
						{
							icon = error_icon;
							message = error_message;
						}
						
						var popup = "<div id='popup-container' style='height:"+h+"px;'></div><div id='popup-dialog'><img src='"+icon+"' /><span>"+message+"</span><a onclick='closePopup()'>ЗАКРЫТЬ ОКНО</a></div>";
						$("body").prepend(popup);
					}
				}
				
				mailer = function(form,formAction,mailtype)
				{
					data = $(form).serialize();
					data += "&mailtype="+mailtype;
					
					$.ajaxSetup({
  						cache:false
					});
					
					$.mailer = { ajaxMail:function(){
					
						$.post( formAction, data, function(reply){
							//message = reply;
						} );
					
					} };
					
					$.mailer.ajaxMail();

					//return message;
				}
function vscroller()
{
	
				
					var scrollPane = $(".scroll-pane"), scrollContent = $(".scroll-content");
					
					var scrollbar = $(".scroll-bar").slider({
						orientation: 'vertical',
						showArrows: 'true',
						value:100,
						slide: function( event, ui ) {

						h = (100 - ui.value)/100*(-1);	
							
						if( h*(-100) <= (100 - (scrollPane.height() / scrollContent.height())*100) )
						{
							if ( scrollContent.height() > scrollPane.height() ) 
							{
								scrollContent.css( 
									"bottom", 
									Math.round( h * ( scrollPane.height() - scrollContent.height() )) + "%" 
								);
							} 
							else 
							{
								scrollContent.css( "bottom", "0%" );
							}	
						} 
						else 
						{
							$(scrollbar).disable();
						}
						
						},
						change: function(event, ui) 
						{ 
							h = (100 - ui.value)/100*(-1);
							if( h*(-100) <= (100 - (scrollPane.height() / scrollContent.height())*100) )
							{
								if ( scrollContent.height() > scrollPane.height() ) 
								{
									scrollContent.css( 
										"bottom", 
										Math.round( h * ( scrollPane.height() - scrollContent.height() )) + "%" 
									);
								} 
								else 
								{
									scrollContent.css( "bottom", "0%" );
								}	
							}
						}
						
					});
				
				
				var handleHelper = scrollbar.find( ".ui-slider-handle" );
				
				function sizeScrollbar() {
						speed = 10;
						var remainder = scrollContent.height() - scrollPane.height();
						var proportion = remainder / scrollContent.height() / 2;
						var handleSize = scrollPane.height() - ( proportion * scrollPane.height() );
						handleHelper.height( "" ).height( scrollbar.height() - handleSize );
						if( $( scrollbar ).slider( "option", "showArrows" ) )
						{
							arrowHeight = $(".triangle-wrap:first").height();
							
							$(".triangle-wrap:first").bind('click', function() {
								
								$(scrollbar).slider( "value", $(scrollbar).slider( "option", "value")+(1*speed) )	
							});
							$(".triangle-wrap:last").bind('click', function() {								
								if( $(scrollbar).slider("value") > (scrollPane.height() / scrollContent.height())*100 )
								{
									$(scrollbar).slider( "value", $(scrollbar).slider( "option", "value")-(1*speed) )
								}	
							});
							
							$(scrollbar).css('height', ($(scrollbar).parent().height() - (arrowHeight + 1)*2 - handleHelper.height()-4));
							$(scrollbar).css('margin-top', handleHelper.height()+3+'px');
						}
				}

				setTimeout( sizeScrollbar, 10 );		
}
