var lang = location.href.substr(location.href.indexOf('/', location.href.indexOf('//')+2 )+1, 2);
var calendarJSloaded = false;

function popupImg( src )
{
	var html = { title:'Base Project', style:'', body:'' };	
	html.style = 'BODY {padding:0; margin:0;}';
	html.body = '<A HREF="/" onClick="opener.focus(); self.close(); return false;">' + 
		'<IMG SRC="'+ src +'" BORDER="0" TITLE="Закрыть" ID="resizeBy"/>' + 
		'</A>';			
	popupPro( html, null );
}

function popupPro( html, args ) 
{    	
    args = (args && args.length == 7) ? args : ['no','no','no','no','no','no','no'];	
	try	{ if ( popup ) popup.close(); } catch ( e ) {}
	var win;	
	popup = window.open( '','popup','top=0,left=0,toobar='+args[0]+',location='+args[1]+',directories='+args[2]+',status='+args[3]+',resizable='+args[4]+',scrollbars='+args[5]+',copyhistory='+args[6]+',width=1,height=1' );			
	doc = popup.document;
	var str ='<HTML><HEAD><TITLE>' + html.title + '</TITLE>' +    
	'<STYLE>'+html.style+'</STYLE><SCRIPT>function resize() {var resizeByObj = document.getElementById( "resizeBy" ); if ( resizeByObj ) { resizeTo( resizeByObj.width, resizeByObj.height ); var top = parseInt( (window.screen.height  - ( window.screen.height - window.screen.availHeight ) - resizeByObj.height) / 2); var left = parseInt( (window.screen.width - ( window.screen.width - window.screen.availWidth ) - resizeByObj.width) / 2); moveTo( left, top );}	window.focus();}</SCRIPT></HEAD>' +
	'<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1251">' + 
    '<BODY onLoad="resize(); self.focus();">' + html.body + '</BODY></HTML>';
	doc.write(str);
	doc.close();	
	self.win = popup;
}

var Http =
{
    cookies: document.cookie.split('; '),

    getCookies: function()
    {
        var result = new Array();
        for( i in this.cookies )
        {
            var cookie = this.cookies[i].split('=');
            result[i] = new Http.Cookie( cookie[0], ( cookie[1] ) ? cookie[1] : '' );
        }
        return result;
    },

    getCookieByName: function( name )
    {
        for( i in this.cookies )
        {		
            var cookie = this.cookies[i].split('=');			
            if( cookie[0].toUpperCase() === name.toUpperCase() )
            {
                return new Http.Cookie( cookie[0], ( cookie[1] ) ? cookie[1] : '' );
            }
        }

        return null;
    }
};

Http.Cookie = function( name, value, maxAge, path, domain, secure )
{
    if ( name )
    {
        this.setName( name );
    }
    if ( value )
    {
        this.setValue( value );
    }
    if ( maxAge instanceof Date )
    {
        this.setMaxAge( maxAge );
    }
    if ( path )
    {
        this.setPath( path );
    }
    if ( domain )
    {
        this.setDomain( domain );
    }

    if ( secure instanceof Boolean )
    {
        this.setSecure( secure );
    }
};
Http.Cookie.prototype =
{
    name: '',
    value: '',
    maxAge: null,
    path: '/',
    domain: location.hostname,
    secure: false,

    getDomain: function()
    {
        return this.domain;
    },

    getMaxAge: function()
    {
        return this.maxAge;
    },

    getName: function()
    {
        return this.name;
    },

    getPath: function()
    {
        return this.path;
    },

    getSecure: function()
    {
        return this.secure;
    },

    getValue: function()
    {
        return unescape( this.value );
    },

    setMaxAge: function( maxAge )
    {
        this.maxAge = new Date( maxAge );
    },

    setDomain: function( domain )
    {
        this.domain = domain;
    },

    setName: function( name )
    {
        this.name = name;
    },

    setPath: function( path )
    {
        this.path = path;
    },

    setSecure: function( secure )
    {
        this.secure = secure;
    },

    setValue: function( value )
    {
        this.value = escape( value );
    },

    destroy: function()
    {
        document.cookie = this.name + "=" +
                          ( ( this.path ) ? '; path=' + this.path : '' ) +
                          ( ( this.domain ) ? '; domain=' + this.domain : '' ) +
                          '; expires=' + ( new Date(1970, 00, 01) ).toGMTString();
    },

    save: function()
    {
        document.cookie = this.name + "=" +
                          ( ( this.value ) ? this.value : '' ) +
                          ( ( this.expires ) ? '; expires=' + this.expires.toGMTString() : '' ) +
                          ( ( this.path ) ? '; path=' + this.path : '' ) +
                          ( ( this.domain ) ? '; domain=' + this.domain : '' ) +
                          ( ( this.secure ) ? '; secure' : '' );

        return true;
    }
};

function changeSearchType( elem )
{
	if( parseInt( elem.value ) == 1 )
	{
		elem.form.action = '/'+ lang +'/yandex.wbp';
		elem.form.elements[0].name = 'text';
	}
	else
	{
		elem.form.action = '/'+ lang +'/search.wbp';
		elem.form.elements[0].name = 'search.query';
	}
}
function checkType( form )
{
	if( form.choose[1].checked )
	{
		form.action = '/'+ lang +'/yandex.wbp';
		form.elements[0].name = 'text';
	}
	new FormCheckPro(form);
}

var User = 
{
	name: '',
	isLogged: false
};

if ( Http && Http.getCookieByName( 'WB.UserName' ) )
{
	var userName = Http.getCookieByName( 'WB.UserName' ).getValue();
	if ( userName ) 
	{
		var logged = ( Http.getCookieByName( 'WB.IsUserLogged' ).getValue() == 'true' ) ? true : false;
		User.name = userName;
		User.isLogged = logged;
	}
}


function addBanner(id) {
  var seed = Math.random();
  var headerObj = document.getElementById('header');
  if (headerObj) {
    var bannersObj = null;
    for (i=0; i<headerObj.getElementsByTagName('div').length; i++) 
      if (headerObj.getElementsByTagName('div')[i].className && headerObj.getElementsByTagName('div')[i].className=='banners') bannersObj = headerObj.getElementsByTagName('div')[i];
    if (bannersObj) {
      var seed = Math.random();
      var anc = document.createElement('A');
      anc.href = "/servlet/link?id="+ id +"&seed="+ seed;
      // anc.target = "_blank";
      var img = document.createElement('IMG');
      img.src = "/servlet/image?id="+ id +"&seed="+ seed;
      img.width = 174;
      img.height = 100;
      anc.appendChild(img);
      bannersObj.appendChild(anc);
    }
  }
}

function checkedImgBorder() {
  var ie = (navigator.userAgent.indexOf("Gecko")==-1 && navigator.userAgent.indexOf("Opera")==-1);
  var h = location.href.substring(location.href.indexOf('?')+1);
  var gets = new Array();
  var i, i2 = 0;
  if (document.getElementById("left")) {
    var o, o2 = false;
    var tags = document.getElementById("left").getElementsByTagName("div");
    var tagsL = tags.length;
    for (i=0; i<tagsL; i++) if ( tags[i].className && tags[i].className=="content" && tags[i].getElementsByTagName('img') ) {
      for (i2=0;i2<tags[i].getElementsByTagName('img').length; i2++) {
        o = tags[i].getElementsByTagName('img')[i2];
        if ( o.getAttribute('align') && (o.getAttribute('align').toLowerCase()=="left" || o.getAttribute('align').toLowerCase()=="right") ) {
          o.setAttribute('hspace', '0');
          o.setAttribute('vspace', '0');
          o2 = document.createElement('div');
          o2.className = "imgBorders";
          o2.style.width = o.width +'px';
          o2.style.height = o.height +'px';
          if (o.getAttribute('align').toLowerCase()=="right") o2.className += " imgBordersRight";
          o2.appendChild(o.cloneNode(false));
          o.parentNode.insertBefore(o2, o);
          o.parentNode.removeChild(o);
        }
      }
    }
  }
  checkedPNG();
  var subjectIsLast = ( location.href.indexOf('president/letter')>-1 );
  while (h.indexOf('=')>-1){
    i = gets.length;
    gets[i] = new Object;
    gets[i].url = (h.indexOf('&')>-1) ? h.substring(0, h.indexOf('&') ) : h;
    gets[i].name = gets[i].url.substring(0, gets[i].url.indexOf('='));
    gets[i].value = gets[i].url.substring(gets[i].url.indexOf('=')+1);
    h = h.substring(gets[i].url.length+1);
    if ( gets[i].name.indexOf('subject')>-1 ) subjectIsLast = false;
  }
  tags = document.getElementsByTagName("div");
  tagsL = tags.length;
  for (i=0; i<tagsL; i++) if ( tags[i].className && tags[i].className.indexOf("img")>-1 && tags[i].className.indexOf("Borders")>-1 ) createBorder(tags[i], "", 9, 9);
  tags = document.getElementsByTagName("select");
  tagsL = tags.length;
  for (i=0; i<tagsL; i++) {
    for (i2=0; i2<gets.length; i2++) {
      if ( tags[i].name==gets[i2].name ) {
        tags[i].selectedIndex = gets[i2].value;
        changeValue(tags[i]);
      }
    }
    if (subjectIsLast && tags[i].name.indexOf("subject")>-1) {
      tags[i].selectedIndex = tags[i].options.length-1;
      changeValue(tags[i]);
    }
  }
  if (calendarJSloaded) {
    tags = document.getElementsByTagName("input");
    tagsL = tags.length;
    for (i=0; i<tagsL; i++) {
      if (tags[i].getAttribute('format') && tags[i].getAttribute('format').indexOf('date')==-1 ) {
        if (ie) {
          tags[i].attachEvent("onfocus", hideCalendars );
        } else {
          tags[i].addEventListener("focus", hideCalendars, false);
        }
      }
    }
  }
}

function checkedPNG() {
  var ie = (navigator.userAgent.indexOf("Gecko")==-1 && navigator.userAgent.indexOf("Opera")==-1);
  var imgs = document.getElementsByTagName('img');
  var i = 0;
  while (i<imgs.length) {
    if (ie && imgs[i].src.toUpperCase().indexOf(".PNG")>-1) {
      imgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgs[i].src + "',sizingMethod='crop')";
      imgs[i].src= "/media/img/b.gif";
    }
    if (imgs[i].className && imgs[i].className.indexOf("gifToPNG")>-1) {
      if (ie) {
        imgs[i].runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgs[i].src.substring(0, imgs[i].src.toUpperCase().indexOf(".GIF")) + ".png',sizingMethod='crop')";
        imgs[i].src= "/media/img/b.gif";
      } else {
        imgs[i].src= imgs[i].src.substring(0, imgs[i].src.toUpperCase().indexOf(".GIF")) + ".png";
      }
    }
    i++;
  }
}

function createBorder(div, prefix, width, height) {
  var corner = false;
  var img = div.getElementsByTagName('img')[0];
  corner = createBorderCorner("img"+ prefix +"BorderDownLeft", width, height);
  if (img && img.height && height) corner.style.top = (img.height - height) + 'px'; 
  div.appendChild(corner);
  corner = createBorderCorner("img"+ prefix +"BorderDownRight", width, height);
  // if (img && img.height && height) corner.style.top = (img.height - height) + 'px'; 
  // if (img && img.width && width) corner.style.left = (img.width - width) + 'px';
  div.appendChild(corner);
  div.appendChild(createBorderCorner("img"+ prefix +"BorderTopLeft", width, height));
  div.appendChild(createBorderCorner("img"+ prefix +"BorderTopRight", width, height));
}

function createBorderCorner(className, width, height) {
  var el = document.createElement("img");
  el.src = "/media/img/b.gif";
  el.className = className;
  el.setAttribute("width", ""+width+"");
  el.setAttribute("height", ""+height+"");
  return el;
}

function createBorderCornerInnerHTML(to, className, width, height) {
  to.innerHTML += "<IMG SRC='/media/img/b.gif' CLASS='"+className+"' WIDTH='"+width+"' HEIGHT='"+height+"' ALT='' />";
}

function clearForm(formId) {
  var form = document.getElementById(formId);
  var i = 0, i2 = 0;
  var s = "";
  if (form) {
    var textFields = new Array();
    var t = form.getElementsByTagName('input');
    var tl = t.length;
    var tal = form.getElementsByTagName('textarea').length;
    for (i=0; i<tl; i++) 
      if ( 
        t[i].type 
        && (t[i].type.toUpperCase()=="TEXT" || t[i].type.toUpperCase()=="HIDDEN") 
        && t[i].name.indexOf(".xt")==-1 
        && t[i].name.toUpperCase().indexOf("SUBJECT")==-1 
        && t[i].name.toUpperCase().indexOf("MAILTO")==-1
        && t[i].id.toUpperCase().indexOf("DATE")==-1
      ) textFields[textFields.length] = t[i]; 
    for (i=0; i<tal; i++) textFields[textFields.length] = form.getElementsByTagName('textarea')[i];
    tfl = textFields.length;
    for (i=0; i<tfl; i++) {
      if (textFields[i].value) textFields[i].value = ""; 
      if (textFields[i].text) textFields[i].text = "";
      changeValue(textFields[i]);
    }
    var selectFields = form.getElementsByTagName('select');
    var sl = selectFields.length;
    for (i=0; i<sl; i++) {
      selectFields[i].selectedIndex = 0;
      for (i2=0; i2<selectFields[i].options.length; i2++) if (selectFields[i].options[i2].defaultSelected==true) selectFields[i].selectedIndex = i2;
      changeValue(selectFields[i]);
    }
  }
} 

function changeValue(obj) {
  var formItem = (obj.parentNode.tagName) ? obj.parentNode : obj.parentNode.parentNode;
  var i = 0;
  var dl = document.getElementsByTagName('div').length;
  var o = null;
  var check = false;
  var c = "";
  while ( !check && formItem.tagName.toUpperCase()!="BODY" ) {
    check = (formItem.id && formItem.id.indexOf("DIV-")>-1);
    if (!check) formItem = (formItem.parentNode.tagName) ? formItem.parentNode : formItem.parentNode.parentNode;
  }
  var objId = formItem.id.substring(4);
  
  i = 0;
  check = false;
  while( i<dl ) {
    o = document.getElementsByTagName('div')[i];
    c = o.className;
    if ( o.className && o.className.indexOf(objId)>-1 ) {
      if ( c.indexOf("showOnIndex")>-1 ) ( (o.parentNode.tagName) ? o.parentNode : o.parentNode.parentNode ).style.display = (obj.selectedIndex==parseInt(  c.substring(c.indexOf("showOnIndex")+ "showOnIndex".length)  )) ? "block" : "none";
      if ( o.className.indexOf("getValue")>-1 && o.className.indexOf("getValueText")==-1 ) { o.parentNode.style.display = 'none'; o.getElementsByTagName('input')[0].value = obj.options[obj.selectedIndex].value; }
      if ( o.className.indexOf("getValueText")>-1 ) { o.parentNode.style.display = 'none'; o.getElementsByTagName('input')[0].value = obj.options[obj.selectedIndex].innerHTML; }
    }
    i++;
  }
}

function showBigFoto(path, bytes, width, height, title, lang) {
    title =  (title.length > 0) ? title : ( (lang=="rus") ? "Фотогаллерея" : "Photogallery" );
    var close = (lang=="rus") ? "Закрыть окно" : "Close window";
    var content = "";
    content += '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">';
    content += '<HTML>';
    content += '<HEAD>';
    content += '<TITLE>'+ title +'</TITLE>';
    content += '<STYLE TYPE="text/css">html, body, * {margin: 0px; padding: 0px;}</STYLE>';
    content += '</HEAD>';
    content += '<BODY><IMG SRC="'+ path +'" WIDTH="'+ width +'" HEIGHT="'+ height +'" TITLE="'+ close +'" ONCLICK="window.close()" /></BODY>';
    content += '</HTML>';
    var w = ( width <= screen.availWidth ) ? width : screen.availWidth;
    var h = ( height <= screen.availHeight ) ? height : screen.availHeight-100;
    var x = Math.ceil((screen.availWidth / 2) - (w / 2)); // горизонтальная координата для центровки окна
    var y = Math.ceil((screen.availHeight / 2) - (h / 2)); // горизонтальная координата для центровки окна
    var extra = "height="+ h +", width="+ w +", left="+ x +", top="+ y +",scrollbars="+ ( ( height >= screen.availHeight-100 ) ? "1" : "0" );
    var popUp = window.open("", "gallery", extra);
    var doc = popUp.document;
    doc.write(content);
    doc.close();
}

