var duel_need_height;
var curtainStep_duel;
var moving_digit_duel;
function razvorot_duel(obj, height1, height2, started){		
	var goon = '1';
	if (height1 < height2)
		if (started == 0)
		{ 
			moving_digit_duel = height1;	
			moving_digit_duel += curtainStep_duel;				
		}
		else 
		{
			if (moving_digit_duel < height2 && moving_digit_duel<=(height2 - curtainStep_duel))	
			{ 		
				moving_digit_duel += curtainStep_duel;
				goon = 1;
			}
			else 
			{ 
				gebi(obj+'_innerdiv').style.display = 'block';
				moving_digit_duel = 'auto';			
				goon = 0;
				gebi('duel_active_img').onclick = function onclick(event) { open_duel('duel_active')};
			}	
		}
	if (height1 > height2)
		if (started == 0)
		{ 		
			moving_digit_duel = height1;	
			gebi(obj).style.height = moving_digit_duel;
			gebi(obj+'_innerdiv').style.display = 'none'; 
			moving_digit_duel -= curtainStep_duel;
		}
		else 
		{
			if (moving_digit_duel > height2 && moving_digit_duel>=curtainStep_duel)	
			{ 		
				moving_digit_duel -= curtainStep_duel;
				goon = 1;						
			}
			else
			{
				moving_digit_duel = 0;
				goon = 0;
				gebi('duel_active_img').onclick = function onclick(event) { open_duel('duel_active')};
			}
		}	
		gebi(obj).style.height = moving_digit_duel;	
		if(goon == 1) setTimeout(function() { razvorot_duel(obj, height1, height2, 1) }, 1); 
} 

var duel_opened = 1;

function open_duel(obj) {	
	if (duel_opened == 1){
		duel_need_height = gebi('duel_active').offsetHeight;		
		curtainStep_duel = parseInt(duel_need_height / 7);
		gebi('duel_active_img').src='http://img.mail.ru/r/blogs/calendar_maximize.gif';
		gebi('duel_active_img').onclick = function onclick(event) { return false};
		duel_opened = 0;
		razvorot_duel(obj, gebi(obj).offsetHeight, 0, 0);
	}else{
	gebi('duel_active_img').src='http://img.mail.ru/r/blogs/calendar_minimize.gif';
	gebi('duel_active_img').onclick = function onclick(event) { return false};
	duel_opened = 1;
	razvorot_duel(obj, 0, duel_need_height, 0);
	}
}

function getClientWidth()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}

function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

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);
}

function confirm_duel()
{
	gebi('shadow_div').style.height = document.body.scrollHeight;
	gebi('shadow_div').style.display= '';
	gebi('duel_confirm_div').style.left=parseInt(document.body.scrollWidth/2)-200+'px';
	gebi('duel_confirm_div').style.top = parseInt(getClientHeight()/2)+getBodyScrollTop()-75+'px';
	gebi('duel_confirm_div').style.display = '';
}

function check_throw_length(textarea) {
    var max = 200;
    if (textarea.value.length > max) {
        textarea.value = textarea.value.substring(0, max);
    }
}

function hide_challenge_divs() {
    gebi('shadow_div').style.display = 'none';
    gebi('duel_confirm_div').style.display = 'none';
}

function perl_challenge_offer_callback(status, UserID) {
    if (status && UserID) {
        var link_left = gebi('challenge_throw_linkleft_'+UserID);
        var succ_left = gebi('challenge_throw_successleft_'+UserID);
        if (link_left && succ_left) {
            link_left.style.display = 'none';
            succ_left.style.display = '';
        } else {
            var link_right = gebi('challenge_throw_linkright_'+UserID);
            var succ_right = gebi('challenge_throw_successright_'+UserID);
            if (link_right && succ_right) {
                link_right.style.display = 'none';
                succ_right.style.display = '';
            }
        }
    }
}

function perl_challenge_possible_callback(status, UserID) {
    if (!status) return;
    if (status == 'OK') {
        var div_content = gebi('challenge_throw_divcontent_'+UserID);
        if (div_content) {
            gebi('duel_confirm_div').innerHTML = div_content.innerHTML;
        } else {
            var div_content = gebi('challenge_throw_divcontentdefault_'+UserID);
            if (div_content) gebi('duel_confirm_div').innerHTML = div_content.innerHTML;
        }
        confirm_duel();
    } else {
        var text;
        status = -status;
        switch(status) {
            case 1:
                text = 'Вы не можете вызвать более трёх пользователей.';
                break;
            case 2:
                text = 'Противник уже участвует в максимальном количестве дуэлей.';
                break;
            case 3:
                text = 'Вы уже соревнуетесь.';
                break;
            case 4:
                text = 'Вы уже предложили дуэль этому пользователю.';
                break;
            case 5:
                text = 'Ваш блог создан менее двух недель назад или в нём меньше двух записей.';
                break;
            case 6:
                text = 'Блог противника создан менее двух недель назад или в нём менее двух записей, и поэтому он не может участвовать в дуэлях.';
                break;
        }
        if (text) show_error(errorEvent, text);
    }
    return;
}

var errorEvent = new Object;
function call_on_challenge(UserID, event) {
    if (!event) event = window.event;
    errorEvent = { target: event.target, srcElement: event.srcElement };
    perl_challenge_possible(UserID, perl_challenge_possible_callback);
}

function accept_challenge(ChallengeID, duration) {
    var div_content = gebi('challenge_accept_divcontent');
    if (!div_content) return;
    gebi('duel_accept_div').innerHTML = div_content.innerHTML;

    gebi('shadow_div').style.height = document.body.scrollHeight;
	gebi('shadow_div').style.display= '';
	gebi('duel_accept_div').style.left=parseInt(document.body.scrollWidth/2)-325+'px';
	gebi('duel_accept_div').style.top = parseInt(getClientHeight()/2)+getBodyScrollTop()-75+'px';
	gebi('duel_accept_div').style.display = '';

    gebi('chaccrem_'+duration).style.display='';
    gebi('chaccduration').value = duration;
}

function challenge_vote_callback(status, ChallengeID, JournalID, gradeLeft, gradeRight, is_left) {
    if (status==-1) {
        // rate-limit
    } else if (!status) {
        // wtf
    } else if (status=='OK') {
        if (JournalID==new String(0)) { // sequence vote
            window.location.reload(true);
            return;
        }

        var vote1_lc = gebi('challenge_leftcolumn_leftvote_'+ChallengeID);
        var vote2_lc = gebi('challenge_leftcolumn_rightvote_'+ChallengeID);
        var grade1_lc = gebi('challenge_leftcolumn_leftgrade_'+ChallengeID);
        var grade2_lc = gebi('challenge_leftcolumn_rightgrade_'+ChallengeID);
        if (vote1_lc && vote2_lc && grade1_lc && grade2_lc) {
            grade1_lc.innerHTML = gradeLeft;
            grade2_lc.innerHTML = gradeRight;
            var succ1 = gebi('challenge_leftcolumn_success_'+ChallengeID);
            if (succ1) {
                succ1.style.display = '';
                setTimeout( function() { succ1.style.display='none' }, 1000);
            }
        }

        var vote1_rc = gebi('challenge_rightcolumn_'+JournalID+'_leftvote_'+ChallengeID);
        var vote2_rc = gebi('challenge_rightcolumn_'+JournalID+'_rightvote_'+ChallengeID);
        var grade1_rc = gebi('challenge_rightcolumn_'+JournalID+'_leftgrade_'+ChallengeID);
        var grade2_rc = gebi('challenge_rightcolumn_'+JournalID+'_rightgrade_'+ChallengeID);
        if (vote1_rc && vote2_rc && grade1_rc && grade2_rc) {
            grade1_rc.innerHTML = gradeLeft;
            grade2_rc.innerHTML = gradeRight;
            var pos = is_left ? 'left' : 'right';
            var succ2 = gebi('challenge_rightcolumn_'+JournalID+'_'+pos+'_success_'+ChallengeID);
            if (succ2) {
                succ2.style.display = '';
                setTimeout( function() { succ2.style.display='none' }, 1000);
            }
        }
    }
}

function challenge_vote(ChallengeID, UserID, JournalID, Magick, do_vote10) {
    perl_challenge_vote(ChallengeID, UserID, JournalID, Magick, do_vote10, challenge_vote_callback);

    if (!JournalID) return true; // sequence vote

    var vote1_lc = gebi('challenge_leftcolumn_leftvote_'+ChallengeID);
    var vote2_lc = gebi('challenge_leftcolumn_rightvote_'+ChallengeID);
    var grade1_lc = gebi('challenge_leftcolumn_leftgrade_'+ChallengeID);
    var grade2_lc = gebi('challenge_leftcolumn_rightgrade_'+ChallengeID);
    if (vote1_lc && vote2_lc && grade1_lc && grade2_lc) {
        vote1_lc.style.display = 'none';
        vote2_lc.style.display = 'none';
    }

    var vote1_rc = gebi('challenge_rightcolumn_'+JournalID+'_leftvote_'+ChallengeID);
    var vote2_rc = gebi('challenge_rightcolumn_'+JournalID+'_rightvote_'+ChallengeID);
    var grade1_rc = gebi('challenge_rightcolumn_'+JournalID+'_leftgrade_'+ChallengeID);
    var grade2_rc = gebi('challenge_rightcolumn_'+JournalID+'_rightgrade_'+ChallengeID);
    if (vote1_rc && vote2_rc && grade1_rc && grade2_rc) {
        vote1_rc.style.display = 'none';
        vote2_rc.style.display = 'none';
    }
}

function check_challenge_capcha(ChallengeID, UserID, JournalID, Magick) {
    var ImageID = document.getElementById('ImageID_id').value;
    var ImageAnswer = document.getElementById('ImageAnswer_id').value;
    perl_challenge_check_capcha(
        ImageID, ImageAnswer,
        function(ok) {
            if (ok) {
                challenge_vote(ChallengeID, UserID, JournalID, Magick);
                hide_capcha();
            } else {
                perl_challenge_get_capcha(
                    function (id) {
                        if (id) {
                            document.getElementById('Image_id').src = 'http://' + PerlVar_BlogsPerlHost + '/cgi-bin/journal/get_image?id='+id;
                            document.getElementById('ImageID_id').value = id;
                        }
                    }
                );
                alert('Неверно введён код защиты');
            }
        }
    );
    return false;
}

function hide_capcha() {
    document.getElementById('capcha_popup').style.visibility="hidden";
}

function show_challenge_capcha(event, JournalDir, ChallengeID, UserID, JournalID, Magick, do_vote10) {
    if (!JournalDir || !ChallengeID || !UserID || !Magick)
        return;
    if (!event) event = window.event;
    var element = event.target || event.srcElement;
    var div = document.getElementById('capcha_popup');
    if (element && div) {
        perl_challenge_get_capcha(
            function(id) {
                if (id) {
                    var coor = get_position(element);
                    var HTML = new Array();
                    HTML.push('<div><a onclick="hide_capcha(); return false;" href=""><img src="http://img.mail.ru/mail/ru/images/blogs/close_help.gif" height="7" width="7" border="0" style="margin: 5px; float: right;"/></a>');
                    HTML.push('<div style="clear:both;"><img src="http://' + PerlVar_BlogsPerlHost + '/cgi-bin/journal/get_image?id='+id+'" width="151" border="0" vspace="0" hspace="0" height="51" alt="" id="Image_id" /></div>');
                    HTML.push('<div style="clear:both;">Число на картинке:</div>');
                    HTML.push('<div style="clear:both; display:inline;"><form action="http://' + PerlVar_BlogsPerlHost +JournalDir+'jchallenge" method="get" id="capchaForm" onsubmit="return check_challenge_capcha(\''+ChallengeID+'\', '+UserID+', \''+JournalID+'\', \''+Magick+'\');"><input type="hidden" name="action" value="vote" />');
                    if (do_vote10) {
                        HTML.push('<input type="hidden" name="do_vote10" value="1" />');
                    }
                    HTML.push('<input type="hidden" name="back" value="' +  PerlVar_back_value + '" /><input type="hidden" name="Magick" value="' + Magick + '" /><input type="hidden" name="ChallengeID" value="'+ChallengeID+'" /><input type="hidden" name="ImageID" value="'+id+'" id="ImageID_id" /><input type="text" name="ImageAnswer" id="ImageAnswer_id" /><input type="submit" value="OK" /></form></div></div>');
                    div.innerHTML = HTML.join('');
                    div.style.top = (coor.top+element.offsetHeight)+"px";
                    div.style.visibility = "visible";
                    var left = coor.left - div.offsetWidth + element.offsetWidth;
                    if (left<0) left = 0;
                    div.style.left = left+"px";
                    event.cancelBubble = true;
                } else {
                    challenge_vote(ChallengeID, UserID, JournalID, Magick, do_vote10);
                }
            }
        );
    }
    return false;
}

function challenge_code_show(event,id) {
	event = event || window.event;
    var element = event.target || event.srcElement;
	if (element) {	
		var coor = get_position(element);
		var div = document.createElement('div');
		div.innerHTML = gebi(id).innerHTML;
		div.className = 'challenge_codes';
		div.style.top = coor.top;
		div.style.left= coor.left;		
		document.body.appendChild(div);
	}
	return false;
}
function challenge_code_hide(obj) {
	var div = obj.parentNode;	
	if(div) document.body.removeChild(div);
	return false;
}
