 var contacts_default = {'artpop_shad':0, 'contacts_search_popup':0, 'text_center_progress':1, 'text_center_error':0, 'text_center_reply':0, 'form_block':0, 'added_success':0};

 function boot()
 {
	profilePopup();
	return ;
 }

/* 
 if (typeof window.onload != 'function')
 {
	window.onload = boot;
 }
 else
 {
	window.onload = function()
	{
		boot();
	}
 }
*/ 

 function winSize() {
    var winW = 0, winH = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        winW = window.innerWidth;
        winH = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        winW = document.documentElement.clientWidth;
        winH = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        winW = document.body.clientWidth;
        winH = document.body.clientHeight;
    }
    return [winW, winH];
 }
 
 function winScroll() {
    var scrOfY = 0, scrOfX = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [scrOfX, scrOfY];
 }

 function getTarget(e) {
    var target;

    if (!e) var e = window.event;
    if (e.target) target = e.target;
    else if (e.srcElement) target = e.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = targ.parentNode;

    return target;
 }


 function switchFriend( id, func, noAnswer )
 {
    noAnswer = noAnswer || 0;

    var Aj = new XHConn();
    Aj.connect(
    "/exec/micro/friend.php",
    "POST",
    'id=' + id + '&func=' + func + '&noAnswer=' + noAnswer,
    function ( res ){
        if (res && res.responseText) {

            _('switchFriend' + id).innerHTML = res.responseText;

            var r = _('jsAnswer');
            if (r)
            {
                var js = r.innerHTML;
                r.parentNode.removeChild(r);
                eval(js);
            }
        }
    });
 }

 function switchFavAuthor( id, func, type, noAnswer )
 {
    noAnswer = noAnswer || 0;
	type = type || '';
	
    var Aj = new XHConn();
    Aj.connect(
    "/exec/micro/favauthor.php",
    "POST",
    'id=' + id + '&func=' + func + '&type=' + type + '&noAnswer=' + noAnswer,
    function ( res ){
        if (res && res.responseText) {
        	
        	if( type == 4 ) {
				eval("ajaxResult="+res.responseText);
				if( ajaxResult["success"] && ajaxResult["success"] == 1 ) { 
					window.location.reload();
				}
        	} else {

	            _('switchFavAuthor' + type + id).innerHTML = res.responseText;
	
	            var r = _('jsAnswer');
	            if (r)
	            {
	                var js = r.innerHTML;
	                r.parentNode.removeChild(r);
	                eval(js);
	            }
        	}
        }
    });
 }

 function switchFavourite( type, id, category, func, showText )
 {
    var Aj = new XHConn();
    Aj.connect(
    "/exec/micro/switchFavourite.php",
    "POST",
    'id=' + id + '&type=' + type + '&category=' + category + '&func=' + func + '&showText=' + showText,
    function ( res ){
        if (res && res.responseText) {
            _('switchFavourite' + id).innerHTML = res.responseText;
            var bookmark = _( 'bookmark_' + id );
            if( bookmark && func == 'delete' ) {
            	bookmark.parentNode.removeChild( bookmark );
            }
        }
    });
 }

 function showHideMyComments( type )
 {
    var Aj = new XHConn();
    Aj.connect(
    "/exec/micro/showHideComments.php",
    "POST",
    '&type=' + type,
    function ( res ){
        if (res && res.responseText) {
            _('comments_property').innerHTML = res.responseText;
        }
    });
 }
 
 function hideFirstMessage( val )
 { 
    var Aj = new XHConn();
    Aj.connect(
    "/exec/micro/hideFirstMessage.php",
    "POST",
    '&val=' + val,
    function ( res ){
        if (res && res.responseText) { 
            _('firstmess').innerHTML = '';
        }
    });
 }
 
 function hideFirstHMessage( val )
 { 
    var Aj = new XHConn();
    Aj.connect(
    "/exec/micro/hideFirstHMessage.php",
    "POST",
    '&val=' + val,
    function ( res ){
        if (res && res.responseText) { 
            _('headerfirstmess').innerHTML = '';
        }
    });
 }
 
 function refreshRecommends() {
    var Aj = new XHConn();
    Aj.connect(
    "/exec/micro/refreshRecommends.php",
    "POST",
    '',
    function ( res ) {
        if (res && res.responseText) {
            _('refreshRecommends').innerHTML = res.responseText;
        } else {
        	_('refreshRecommendsBlock').style.display = 'none';
        }
    });
 }
 
 
 function switchEvent( type, id, func, rel )
 {
    if (rel == 'undefined')
    {
        rel = '';
    }
    var Aj = new XHConn();
    Aj.connect(
    "/exec/micro/switchEvent.php",
    "POST",
    'id=' + id + '&type=' + type + '&func=' + func + '&rel=' + rel ,
    function ( res ){
        if (res && res.responseText) {
            _('switchEvent' + id).innerHTML = res.responseText;

            var r = _('jsAnswer');
            if (r)
            {
                var js = r.innerHTML;
                r.parentNode.removeChild(r);
                var div = _('userCount_' + type + '_' + id);
                if (div)
                {
                    div.innerHTML = js;
                }
            }
        }
    });
 }

 function favouriteCookie( v )
 {
    createCookie('fav_no_notify', v, 1000);
 }

 function friendship( func, id, obj )
 {
    var Aj = new XHConn();
    Aj.connect(
    "/exec/micro/friendship.php",
    "POST",
    'id=' + id + '&func=' + func,
    function ( res ){
        if (res && res.responseText) {

                var tr = obj.parentNode.parentNode;

                tr.style.display = 'none';
                tr.style.visibility = 'hidden';

                tr.parentNode.removeChild(tr);
        }
    });
    return false;
 }

 function profilePopup() 
 {
    var time    = 1000;
    var timeout = null;
    var that    = this;

    var target  = null;
    var posx, posy;

    this.mouseover = function() {

        if (timeout != null)
            clearTimeout(timeout);

        var user   = target.attributes.user.nodeValue;

        if (user == '') {
            return false;
        }

        var Aj = new XHConn();
        Aj.connect(
        "/exec/micro/popup.php",
        "POST",
        'id=' + user,
        function ( res ) {
            if (res && res.responseText) {

                popup.innerHTML = res.responseText;

                if (popup.style.display == 'none')
                    popup.style.display = '';

                var left = posx - 30;
                var top  = posy - 30;

                var s = winScroll();
                var w = winSize();

                var popW = popup.offsetWidth;
                var popH = popup.offsetHeight;

                if ((left + popW) > (w[0] + s[0])) 
                {
                    left = w[0] + s[0] - popW;
                }

                if ((top + popH) > (w[1] + s[1]))
                {
                    top = w[1] + s[1] - popH;
                }

                popup.style.left = left + 'px';
                popup.style.top  = top + 'px';
            
            }
        });

    };

    this.mouseout = function(e) {

        if (timeout != null)
            clearTimeout(timeout);

        if (!e) var e = window.event;
        var el = (e.relatedTarget) ? e.relatedTarget : e.toElement;

        while(el != popup && el.tagName.toLowerCase() != 'body')
            el = el.parentNode;

        if (el == popup) return;

        if (popup.style.display == '')
            popup.style.display = 'none';
    };
    /**
    * find popup and mouseout events
    */
    var popup = document.getElementById('profilePopup');

    if (! popup)
    {
        return false;
    }
    popup.onmouseout = this.mouseout;

    /**
    * search for link elements with atrribute 'user'
    */
    var links = document.getElementsByTagName('a');
    for(var i = 0, cnt = links.length; i < cnt; i++) {
        if (typeof links[i].attributes.user == 'undefined') continue;
		
        links[i].onmouseover = function(e) {

            target = getTarget(e);
            while(typeof target.attributes.user == 'undefined' && target.tagName.toLowerCase() != 'body') {
                target = target.parentNode;
            }

            if (!e) var e = window.event;
            if (e.pageX || e.pageY)     {
                posx = e.pageX;
                posy = e.pageY;
            }
            else if (e.clientX || e.clientY)    {
                posx = e.clientX + document.body.scrollLeft
                    + document.documentElement.scrollLeft;
                posy = e.clientY + document.body.scrollTop
                    + document.documentElement.scrollTop;
            }

            timeout = setTimeout(function(){that.mouseover.call(that)}, time);
        };

        links[i].onmouseout = function(e) {
            clearTimeout(timeout);
        };
    }
 }

 // friends search

 function open_search_form(obj, main)
 {
	set_default_displaying();

 	_('socialcode').value = obj.id;

	_('bm').className = '';
	_('gm').className = '';
	obj.className = 'current';	

	if (main == true) {
		_('form_block').style.display = 'block';
	}
 }

 
 function showTabContacts( obj ){
	
 	_('whatshow').value = obj.id;
 	
 	_('authors').className = '';
	_('readers').className = '';
	obj.className = 'current';

	if( obj.id == 'readers' ) {
		_('authorsnav').style.display = 'none';
		_('readersnav').style.display = 'block';
	}

	if( obj.id == 'authors' ) {
		_('readersnav').style.display = 'none';
		_('authorsnav').style.display = 'block';
	}
	
 	return true;
	
 }
 
 
 function show_hide(id)
 {
	if ( typeof(id) == 'object' && (id instanceof Array) ) {
		for(unique_id in id) {
			_(id[unique_id]).style.display = (_(id[unique_id]).style.display == 'block' || _(id[unique_id]).style.display == '') ? 'none' : 'block';
		}
	}
	else {
		_(id).style.display = (_(id).style.display == 'block' || _(id).style.display == '') ? 'none' : 'block';
	}
	return false;
 }

 function set_default_displaying()
 {
	for(id in contacts_default) 
	{
		_(id).style.display = (contacts_default[id] == '0') ? 'none' : 'block' ;
	}
 }

 function search_contacts(obj)
 {
	if (validate() == false) 
	{
		return false;
	}

	show_hide('artpop_shad');
	show_hide('contacts_search_popup');

	var vp = new XHConn();

	email 	= _('email').value;
	pswd 	= _('pswd').value;

	vp.connect("/exec/g_contacts.php", "POST", "email=" + escape(email) + "&pswd=" + escape(pswd), 
	function ( res ) { 
		if (res && res.responseText) { 
			var reply;
			var fav_out = '';
			var invite_out = '';

			var error_html = 'Ошибка ввода email или пароля.';
			var error_message = 'При импорте адресной книги возникла ошибка.';

			// скрыли прогресс и показали блок с ответом сервака
			show_hide('text_center_progress');					

			try
			{
				// распарсили джейсон от сервера
				reply = JSON.parse(res.responseText);

				// если распарсился нормально
				if (reply !== false)
				{

					if (reply.error == '')
					{
						if(parseInt(reply.count))
						{
					// юзеру - нотифай
					_('user_message').innerHTML = 'Из Вашей адресной книги уже зарегистрированы на Корреспондент.net : <b>' + parseInt(reply.count) + '</b>. Вы также можете пригласить остальных.';
						}
					
			
					// отрисовали контакты на фав.
					for(contact in reply.contacts_valid )
					{
						fav_out += '			<tr>' +
													'<td class="vtop pdl_page" style="width:1%;">' +
														'<div class="clear_small"></div>' +
														'<input type="checkbox" class="inp_check" id="fav_'+contact+'" />' +
													'</td>' +
													'<td class="pdr_small" colspan="2">' +
														'<div class="clear"></div>' +
														'<label for="fav_sel_'+contact+'">' +
															'<span class="img_box fl pazorfix_img4 mrt_small pointer">' +
																'<img src="'+reply.contacts_valid[contact].img+'" class="fl" width="50" height="50" alt="" title="" />' +
																'<span class="corner_lt o_corn"></span>' +
																'<span class="corner_rt o_corn"></span>' +
																'<span class="corner_lb o_corn"></span>' +
																'<span class="corner_rb o_corn"></span>' +
															'</span>' +
														'</label>' +
														'<b>'+reply.contacts_valid[contact].name+'</b><br />' +
														reply.contacts_valid[contact].email +
														'<div class="clear_medium"></div>' +
													'</td>' +
												'</tr>' + "\n";

					}
					_('fav_list').innerHTML = fav_out;

					// отрисовали контакты на инвайт.
					for(contact in reply.contacts_invite )
					{
						invite_out += '			<tr class="'+((parseInt(contact)%2 == 1) ? 'trline_gray' : '')+'">' +
													'<td class="pdl_page"><input type="checkbox" class="inp_check" id="invite_'+contact+'" /><input type="hidden" name="invite_val_'+contact+'" id="invite_val_'+contact+'" value="'+reply.contacts_invite[contact].email+'" /></td>' +
													'<td style="width:30%;"><label for="invite_'+contact+'" class="pointer">'+reply.contacts_invite[contact].email+'</label></td>' +
													'<td class="pdr_small pdl_small">&nbsp;</td>' +
												'</tr>' + "\n";
					}
					_('invite_list').innerHTML = invite_out;
					_('sel_all').checked = false;

					show_hide('text_center_reply');					
					} else {
					// нормально не распарсилось - юзеру еррор.
						_('user_message').innerHTML = error_message;
						_('error_message').innerHTML = reply.error;
						show_hide('text_center_error');					
					}
				} else {
					// нормально не распарсилось - юзеру еррор.
					_('user_message').innerHTML = error_message;
					_('error_message').innerHTML = error_html;
					show_hide('text_center_error');					
				}
            }
			catch(err)
			{
				// ащще пц ошибка - юзеру еррор.
				_('user_message').innerHTML = error_message;
				_('error_message').innerHTML = error_html;
				show_hide('text_center_error');
			}
		} 
	} 
	);
	
	return false;
 }

 function checkAll()
 {
	var main_was_checked = (_('sel_all').checked == true) ? true : false ; 
	var f = _('fav_list').getElementsByTagName('INPUT');
	var i = _('invite_list').getElementsByTagName('INPUT');

	for(inp in f)
		f[inp].checked = (main_was_checked == true) ? true : false;
	for(inp in i)
		i[inp].checked = (main_was_checked == true) ? true : false;
 }

 function submitContactForm()
 {
	var f = _('fav_list').getElementsByTagName('INPUT');
	var i = _('invite_list').getElementsByTagName('INPUT');

	f_list = [];
	i_list = [];

	for (inp in f) {
		if ((f[inp].checked == true) && (typeof(f[inp]) == 'object')) {
			f_list[inp] = f[inp].id.substr(4);
		}
	}

	var j=0;
	for (inp in i) {
		if ((i[inp].checked == true) && (typeof(i[inp]) == 'object') && (i[inp].className == 'inp_check')) {
			var val_i = i[inp].id.substr(7);

			if ((_('invite_val_' + val_i) != false) && (_('invite_val_' + val_i).value != 'undefined')) {
				i_list[j] = _('invite_val_' + val_i).value;
				j++;
			}
		}
	}

	var p = new XHConn();
	p.connect("/exec/micro/contacts_inviter.php", "POST", "favs=" + f_list.join(",") + "&invites=" + i_list.join(","), function ( res ) { if (res && res.responseText) { } });	

	show_hide(['contacts_search_popup','artpop_shad','text_center_progress','text_center_reply','form_block','added_success']);

//	show_hide(['contacts_search_popup','artpop_shad','text_center_reply','form_block','added_success']);

	return false;
 }

 function validate() 
 {
	if (validate_email('email') == false) {
		alert('Введён не корректный email-адрес');
		_('email').focus();
		return false;
	}

	if (_('pswd').value.length == 0) {
		alert('Пустой пароль');
		_('pswd').focus();
		return false;
	}

	return true;
 }

 function  validate_email(email)
 {
	var s = _(email).value;

	if ( s.search ) {
		return (s.search(new RegExp("^([-!#\$%&'*+./0-9=?A-Z^_`a-z{|}~])+@([-!#\$%&'*+/0-9=?A-Z^_`a-z{|}~]+\.)+[a-zA-Z]{2,4}$","gi"))>=0);
	}

	if(s.indexOf) {
		at_character=s.indexOf('@')
		if(at_character<=0 || at_character+4>s.length)
			return false
	}

	if(s.length<6)
		return false

	return true;
 }
