function getWidth(){
  if(window.innerWidth){ return window.innerWidth; }
  else if(document.documentElement && document.documentElement.clientWidth){
    return document.documentElement.clientWidth;
  }
  else if(document.body && document.body.clientWidth){
    return document.body.clientWidth;
  }
}

isDOM=document.getElementById?true:false
isOpera=isOpera5=window.opera && isDOM
isOpera6=isOpera && window.print
isOpera7=isOpera && document.readyState
isMSIE=isIE=document.all && document.all.item && !isOpera
isStrict=document.compatMode=='CSS1Compat'
isNN=isNC=navigator.appName=="Netscape"
isNN4=isNC4=isNN && !isDOM
isMozilla=isNN6=isNN && isDOM

function ge(id) {return document.getElementById(id)}
function getBody(w){if(!w) w=window;if(isStrict) return w.document.documentElement;else return w.document.body}
function getDocHeight() {var D=document;return Math.max(Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),Math.max(D.body.clientHeight, D.documentElement.clientHeight));}
function getDocWidth() {var D=document;return Math.max(Math.max(D.body.scrollWidth, D.documentElement.scrollWidth),Math.max(D.body.offsetWidth, D.documentElement.offsetWidth),Math.max(D.body.clientWidth, D.documentElement.clientWidth));}
function getWinHeight() {return window.innerHeight || (document.compatMode == "CSS1Compat" && document.documentElement.clientHeight || document.body.clientHeight);}
function getWinWidth() {return window.innerWidth || (document.compatMode == "CSS1Compat" && document.documentElement.clientWidth || document.body.clientWidth);}
function getBodyScrollTop(){return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop)}
function getBodyScrollLeft(){return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft)}

window.onload=function(){
 if (document.location.pathname=='/') init();
}

function scr(eid,h){
 var t=this;
 t.css=document.getElementById(eid).style;t.height=h;t.time=10;t.step=10;
 t.down=function(){var h=parseInt(t.css.height);if(h<t.height){t.css.height=(h+t.step>t.height?t.height:h+t.step)+'px';setTimeout(t.down,t.time)}}
 t.up=function(){var h=parseInt(t.css.height);if(h>1){t.css.height=(h-t.step<=0?1:h-t.step)+'px';setTimeout(t.up,t.time)}}
}
scr.init=function(eid,h){var el=new this(eid,h);if(parseInt(el.css.height)<=1)el.down();else el.up();}
scr.hide=function(eid,h){var el=new this(eid,h);el.up();}

function validForm(f){
 var msg='',sign=true;
  if(f.fio.value==''){sign=false;msg=msg+" Необходимо заполнить поле «ФИО».\n";}
  if(f.phone.value==''){sign=false;msg=msg+" Необходимо заполнить поле «Телефон».\n";}
  if(check_email(f.mail.value)) {sign=false;msg=msg+" Поле «E-mail» заполненно не верно.\n";}
  if(!sign) {alert(msg); return false;} else return true;
}

function sendForm(f){
 if (!validForm(f)) return false;
 JsHttpRequest.query('/jsAjax.php',{'fio':f.fio.value,'phone':f.phone.value,'email':f.mail.value},
   function(result,error){
    if (error) {alert(error); return}
    f.fio.value='';f.phone.value='';f.mail.value='';
    scr.hide('d1',150);
    document.getElementById('orderAnswer').appendChild(document.createTextNode('Заявка принята'));
   },false
  );
}

function check_email(email) {
 if (email=='') return true;
 var r, re;
 re = "[0-9a-zA-Z_]+@[0-9a-zA-Z_^.]+\\.[a-zA-Z]";
 r = email.match(re);
 if(r==null) return true; else return false;
}

function openPrint(url){
window.open(url,'pp',"width=770,height=580,copyhistory=no,status=no,directories=no,menubar=yes,location=no,resizable=yes,scrollbars=yes,toolbar=yes");}

function wopen(url,width,height) {
 window.open(url,'win',"width="+width+",height="+height+",copyhistory=no,status=no,directories=no,menubar=yes,location=no,resizable=yes,scrollbars=yes,toolbar=yes");
}

function showProgram(id,obj) {
 var o=ge(id);
 var s=o.style.display;
 s=(s=='block'?'none':'block');
 obj.innerHTML=(s=='none'?'В программе':'Свернуть');
 o.style.display=s;
}

function ltrim(s) {return s.replace(/^\s+/,'')}
function rtrim(s) {return s.replace(/\s+$/,'')}
function trim(s) {return ltrim(rtrim(s))}

function check_mail(e){
 e=trim(e.toLowerCase());
 if (e.length<6 || e.indexOf('@')<1 || (e.length-(e.indexOf('@')+1))<4 || e.indexOf(' ')>0 || substr_count(e,'@')>1) return false;
 var re = /^[a-z0-9]+((_+|(\.|\-){1})[a-z0-9]+)*@[a-z0-9]+([\.\-]{1}[a-z0-9]+)*\.[a-z]{2,4}$/;
 return re.test(e);
}

function substr_count( haystack, needle, offset, length ) {
   var pos = 0, cnt = 0;
   if(isNaN(offset)) offset = 0;
   if(isNaN(length)) length = 0;
   offset--;
   while( (offset = haystack.indexOf(needle, offset+1)) != -1 ){
       if(length > 0 && (offset+needle.length) > length){ return false; } else { cnt++; }
   }
   return cnt;
}

function sendInvite(f) {
 var err=false;
 if (document.URL.indexOf('moscow-expert.ru/s'+f.pid.value+'.html') == -1) {alert('Произошла ошибка. Попробуйте позже.'); err=true;}
 else if (trim(f.un.value).length<3) {alert('Представьтесь!'); f.un.focus(); err=true;}
 else if (!check_mail(f.ue.value)) {alert('Укажите Ваш E-mail!'); f.ue.focus(); err=true;}

 if (!err) {
 JsHttpRequest.query(
   '/ajax.php', {'action':'invite','email': f.ue.value,'fio': f.un.value,'pid':f.pid.value,'url':document.URL},
      function(result, errors) {
       if (result) {
        if (result['error']) alert(result['error']);
        else if (result['res']){
         ge('inviteForm').style.display='none';
         ge('inviteReport').innerHTML=result['res'];
         ge('inviteReport').style.display='block';
        }
       }
      },
     false
  );
 }
 return false;
}

var Overlay={
	div:null,
	attr: {'position':isMSIE ? 'absolute':'fixed','display':'block','zoom':1,'left':0,'top':0,'zIndex':3000,'backgroundColor':'#000','background':'url(/i/square_bg.gif) repeat left top'},
	show: function(){
		var t=this.attr, div=this.div;
		t.width=Math.max(getWinWidth(),getDocWidth())+'px';
		t.height=Math.max(getWinHeight(),getDocHeight())+'px';
		t.opacity=t.MozOpacity=t.KHTMLOpacity=0.7;
        t.filter='alpha(opacity=70)';
        getBody().style.overflowY='hidden';
        if (div) div.style.display='block';
        else {
        	div=document.createElement('div'); div.id='overlay';
        	div.onclick=function() {Dialog.close()}
        	for (var e in t) div.style[e]=t[e];
			document.body.appendChild(div);
			this.div=div;
        }
	},
	close: function(){
		this.div.style.display='none';
		getBody().style.overflowY='auto';
	}

};

var ImgPhone={
 div:null,
 attr: {'position':isIE ? 'absolute':'fixed','bottom':'0','left':'0','width':'273px','height':'400px','zIndex':'3001'},
 show: function(){
  var t=this.attr, div=this.div;
   div=document.createElement('div'); div.id='iphone';
   for (var e in t) div.style[e]=t[e];
   var img = document.createElement('img');
   img.src='/i/telefon.png';
   img.style.width='273px';
   img.style.height='400px';
   div.appendChild(img);
   document.body.insertBefore(div,document.body.lastChild);
   this.div=div;
 },
 close: function(){
  document.body.removeChild(this.div);
 }
}

var Dialog={
	fb:null,
	x:null,
	show: function(){
		this.fb=ge('fb');
		var style={'position':isIE ? 'absolute':'fixed','display':'none','width':'400px','height':'375px','background':'#FFF','border':'1px solid #000','zIndex':'3002','borderRadius':'10px','mozBorderRadius':'10px','webkitBorderRadius':'10px','boxShadow':'0 0 15px #000','webkitBoxShadow':'0 0 15px #000','mozBoxShadow':'0 0 15px #000'};
		if(isIE) {style.top = parseInt((getWinHeight()-parseInt(style.height,10))/2,10)+getBodyScrollTop() + 'px';}
		else {style.top = parseInt((getWinHeight()-parseInt(style.height,10))/2,10)+'px';}
		style.left= parseInt((getWinWidth()-parseInt(style.width,10))/2,10)+'px';
		for (var key in style) this.fb.style[key]=style[key];
		if (!this.x) {
		 this.x=document.createElement('a'); this.x.href='#';
		 this.x.onclick=function(){Dialog.close(); return false;}
		 var s=this.x.style; s.color='#0080C0'; s.position="absolute"; s.right='10px';s.top='5px';
		 this.x.appendChild(document.createTextNode('Закрыть'));
		 this.fb.appendChild(this.x);
	     var f='<h1 style="font:bold 16px Arial;">Обратная связь</h1><p style="margin:0">Здесь вы можете оставить ваши вопросы и комментарии. Мы обязательно ответим на все ваши предложения.</p><form name="fb" action="" style="margin:0;padding-top:5px" method="post"><div><b>Ваше имя:</b></div><div><input name="fb_n" class="fb_i" type="text" value=""/></div><div class="fb_t"><b>Ваш вопрос:</b></div><div><textarea name="fb_q" rows="8" class="fb_i" cols="20"></textarea></div><div class="fb_t"><b>Ваш Email:</b></div><div><input name="fb_e" class="fb_i" type="text" value=""/></div><div class="fb_t" style="float:left"><input type="button" value="Отправить" onclick="Dialog.send(this.form)" /></div><div style="margin-top:15px;float:right"><a href="http://moscow-expert.ru/content/contact/index.html">адрес и схема проезда</a></div></form>';
	     var form=document.createElement('div'); form.id='fb_form';
	     form.innerHTML=f;
	     this.fb.appendChild(form);
		}

		Overlay.show();
		ImgPhone.show();
		this.fb.style.display='block';

        window.onresize=function(){
         var o=ge('overlay');
         if (o) {
	  	 	o.style.width=Math.max(getWinWidth(),getDocWidth())+'px';
 		 	o.style.height=Math.max(getWinHeight(),getDocHeight())+'px';
         	ge('fb').style.left=parseInt((getWinWidth()-parseInt(style.width,10))/2,10)+'px';
         	if (isIE) ge('fb').style.top = parseInt((getWinHeight()-parseInt(style.height,10))/2,10)+getBodyScrollTop() + 'px';
         	else ge('fb').style.top = parseInt((getWinHeight()-parseInt(style.height,10))/2,10)+'px';
         }
        }
	},
	close: function(){
		this.fb.style.display='none';
		ImgPhone.close();
		Overlay.close();
	},
	send: function(t){
		if (check_mail(t.fb_e.value)==false) { alert('Ошибка в Email'); return; }
		var text=trim(t.fb_q.value);
		if (text.length<10) { alert('Ошибка!\nНапишите ваш вопрос'); return; }
		JsHttpRequest.query(
			'/ajax.php', {'action':'fb','email': t.fb_e.value,'name': t.fb_n.value,'text':text,'url':document.URL},
			function(result, errors) {
				if (result) {
					if (result['error']) alert(result['error']);
					else if (result['res']){
	                   Dialog.close();
					   alert(result['res']);
					}
				}
			},
			false
		);
	}
};

