var COMIC_PANEL_WIDTH = 160;
var spot;
var quiz_correct_count = 0;
var login_focus = false;
var hangman_max_guess = 6;
var pulsator;
var hm_timer;
var hangman_focus;
var comic_step = 1;
var max_comic_step = 5;
var quiz_current_question = 1;
var hp_slide_width = 540;
var allow_slidemove = true;
var main_nav_minwidth = 138;
var main_nav_maxwidth = 181;
var valid;

function make_adventure(question_id, choice_id){
    if(comic_step > max_comic_step){
        comic_step = 1;
    }
    if(question_id == 'init'){
        $('comic_finish_message').hide();
        for(var i=2; i<=5; i++){
            var panelname = 'panel' + i;
            $(panelname).setStyle({
                'backgroundImage': 'none'
            });
        }
    }
    var qid = '';
    var cid = '';
    if(question_id){
       qid = question_id; 
    }
    if(choice_id){
        cid = choice_id;
    }
    
    new Ajax.Request('XHR_coya_goahead', {
        onCreate: function(){
            $('comic_spinner').show();
        },
        method: 'post',
        asynchronous: true,
        parameters: {
            question_id: qid,
            choice_id: cid
        },
        onSuccess:  complete_make_adventure
    });
}

function complete_make_adventure(req){
    var jsonObj = eval('(' + req.responseText + ')');
	if(jsonObj.error)
	{
		alert(jsonObj.error);
	}
	
	ret = jsonObj.data;
	
	var question_contents = ret.question;
    var comic_panel = ret.comic_panel;
    var qid = ret.question_id;
    var cid = ret.choice_id;
    var comic_id = ret.comic_id;
    
    
    $('comic_id').value = comic_id;
    $('play_area_container').innerHTML = '';
    $('play_area_container').insert(question_contents);
    $('panel' + comic_step).setStyle({
       'backgroundImage': 'url(' + comic_panel + ')' 
    });
    $('comic_spinner').hide();
    
    if(comic_step >= max_comic_step){
        $('comic_finish_message').show();
    }
    
    
    comic_step++;
}
function delcomic_restart(){
    var comic_id = $('comic_id').value;
    if(comic_id != ''){
        new Ajax.Request('XHR_remove_comic', {
            method: 'post',
            asynchronous: true,
            parameters: {
                comic_id: comic_id
            },
            onSuccess:  function(){
                make_adventure('init');
            }
        });
    }
    
}

function reset_adventure(){
    var reset_content = '<a href="#" onclick="make_adventure(\'init\'); return false;">Start Your Adventure</a>';
    $('play_area_container').innerHTML = '';
    $('play_area_container').insert(reset_content);
    $('cyoa_comic_container').innerHTML = '';
    $('cyoa_comic_container').setStyle({
        'width': '1px'   
    })
}

function login(){
    var username = $('username').value;
    var password = $('password').value;
    
    new Ajax.Request('XHR_check_login', {
        method: 'post',
        asynchronous: true,
        parameters: {
            username: username,
            password: password
        },
        onSuccess:  function(req){
            var jsonObj = eval('(' + req.responseText + ')');
            if(jsonObj.error){
                alert(jsonObj.error);
            }
            else{
                ret = jsonObj.data;
                var mode = ret.mode;
                if(mode == 'fail'){
                    $('login_area').innerHTML = '';
                    $('login_area').insert(ret.contents);
                }
                else{
                    sh_login(username, password);
                }
            }
        }
    });
}

function sh_login(username, password){
    new Ajax.Request('XHR_loggin_in', {
        method: 'post',
        asynchronous: true,
        parameters: {
            SiteHandler_Username: username,
            SiteHandler_Password: password
        },
        onSuccess:  complete_login
    });
}

function logoff(){
    new Ajax.Request('XHR_logout', {
        method: 'post',
        asynchronous: true,
        onSuccess:  function(req){
            var jsonObj = eval('(' + req.responseText + ')');
            ret = jsonObj.data;
            var auth_contents = ret.auth_contents;
            $('login_area').innerHTML = '';
            $('login_area').insert(auth_contents);
            if($('username')){
                setup_username_listener();
            }
            if($('password')){
                setup_password_listener();
            }
            $('profile').hide();
            window.location.href = window.location.href;
        }
    });
}

function complete_login(req){
    var jsonObj = eval('(' + req.responseText + ')');
	if(jsonObj.error){
		//$('login_message').innerHTML = jsonObj.error;
        alert(jsonObj.error);
	}
	else{
        ret = jsonObj.data;
		var auth_contents = ret.auth_contents;
        $('login_area').innerHTML = '';
        $('login_area').insert(auth_contents);
        $('profile').show();
        login_focus = false;
        
        // reloading the page after login for now.  Need a slicker way
        // of having content become aware of the session change...
        window.location.href = window.location.href;
    }
}

function show_postcomment(div_id){
    if($(div_id).visible()){
        new Effect.BlindUp(div_id, {
           duration: 0.3 
        });
    }
    else{
        new Effect.BlindDown(div_id, {
           duration: 0.3 
        });
    }
}
function report_comment(page_id,content_id,comment_id){
    
}
function submit_comment(page_id, content_id, contententry_id, show_popup_id, popup_id, comment_tab_id, comment_tab_iter){
    var comment_contents = $(contententry_id).value;
    var show_popup = $(show_popup_id).value;
    new Ajax.Request('XHR_post_comment', {
        method: 'post',
        asynchronous: true,
        parameters: {
            comment: comment_contents,
            content_id: content_id,
            page_id: page_id
        },
        onSuccess:  function(){
            $(contententry_id).value = '';
            if(show_popup == '1'){
                new Effect.Appear(popup_id, {
                    duration: 0.3/*,
                    afterFinish: function(){
                        $(popup_id).setStyle({
                           opacity: 0.9
                        });
                    }*/
                });
            }
            comment_tabs(comment_tab_id, comment_tab_iter, '1')
            
        }
    });
}

function reply_comment(comment_id){
    var reply_container_id = 'reply' + comment_id;
    var reply_link_id = 'reply_link' + comment_id;
    if($(reply_container_id).visible()){
        $(reply_link_id).removeClassName('active');
        new Effect.BlindUp(reply_container_id, {
           duration: 0.3 
        });
    }
    else{
        new Effect.BlindDown(reply_container_id, {
           duration: 0.3 
        });
        $(reply_link_id).addClassName('active');
    }
}

function submit_reply(page_id, content_id, reply_to_id){
    var reply_contents = $('reply_contents' + reply_to_id).value;
    $('reply_contents' + reply_to_id).value = '';
    new Ajax.Request('XHR_post_comment', {
        method: 'post',
        asynchronous: true,
        parameters: {
            comment: reply_contents,
            content_id: content_id,
            page_id: page_id,
            reply_to_id: reply_to_id
        },
        onSuccess:  function(){
            reply_comment(reply_to_id);
        }
    });
}

function start_quiz(){
    if(!$('popup_container').visible()){
        var quizdiv_id = 'quiz_contents';
        new Ajax.Request('XHR_get_quiz', {
            method: 'post',
            asynchronous: true,
            parameters: {
                group_id: '1',
                num_questions: '5'
            },
            onSuccess:  function(ret){
                var quiz = ret.responseText;
                $(quizdiv_id).innerHTML = '';
                $(quizdiv_id).insert(quiz);
                $$('.quiz_question').each(function(item){
                   item.hide(); 
                });
                show_quiz();
            }
        });
    }
}
function restart_quiz(){
    $('quiz_message_container').hide();
    $('quiz_score_container').hide();
    $$('td.quiz_answer_icon').each(function(item){
        item.setStyle({
            'opacity': '1'
        });
    });
    quiz_correct_count = 0;
    var quizdiv_id = 'quiz_contents';
    new Ajax.Request('XHR_get_quiz', {
        method: 'post',
        asynchronous: true,
        parameters: {
            group_id: '1',
            num_questions: '5'
        },
        onSuccess:  function(ret){
            var quiz = ret.responseText;
            $(quizdiv_id).innerHTML = '';
            $(quizdiv_id).insert(quiz);
        }
    });
}
function begin_quiz(){
    $('quiz_intro').hide();
    $('quiz_questions').show();
    $('quiz_question1').show();
    quiz_current_question = 1;
    $('quiz_nextbtn').show();
}
function show_quiz(){
    var dimmerdiv_id = 'popup_fader';
    var quizdiv_id = 'quiz_container';
	var winnerdiv_id = 'top10_winner_container';
	$(quizdiv_id).show();
	var arrayPageSize = getPageSize();
	
	$(dimmerdiv_id).show();
	$(dimmerdiv_id).setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px', opacity: 0.7 });
	$('popup_container').show();
	document.location.href = '#';
}



function quiz_answer(question_id,answer_id,answercounter,question_number){
    var answer_div_id = 'qa_' + question_id + answer_id;
    var icon_div_id = 'qaicon_' + question_id + answer_id;
    var answered_link = $(answer_div_id).down();
    if(!(answered_link.hasClassName('answered'))){
        new Ajax.Request('XHR_quiz_answer', {
            method: 'post',
            asynchronous: true,
            parameters: {
                question_id: question_id,
                answer_id: answer_id
            },
            onSuccess:  function(ret){
                var res = ret.responseText;
                
                var str_selector = '#quiz_question' + question_number + ' a.quiz_answer';
                $$(str_selector).each(function(item){
                    item.addClassName('answered');
                });
                
                str_selector = '#quiz_question' + question_number + ' td.quiz_answer_icon';
                $$(str_selector).each(function(item){
                    item.setStyle({
                       'opacity': '0.5' 
                    });
                });
                
                if(res == '1'){
                    $(answer_div_id).addClassName('correct');
                    $(icon_div_id).removeClassName('quiz_question' + answercounter);
                    $(icon_div_id).addClassName('quiz_correct' + answercounter);
                    $(icon_div_id).setStyle({
                       'opacity': '1' 
                    });
                    quiz_correct_count++;
                }
                else{
                    $(answer_div_id).addClassName('incorrect');
                    $(icon_div_id).removeClassName('quiz_question' + answercounter);
                    $(icon_div_id).addClassName('quiz_wrong' + answercounter);
                    $(icon_div_id).setStyle({
                       'opacity': '1' 
                    });
                }
                
                quiz_current_question = question_number;
                
                $('quiz_nextbtn').show();
                
                
                
                var answered_num = $('answered_quiz_questions').value;
                answered_num = parseInt(answered_num) + 1;
                $('answered_quiz_questions').value = answered_num;
                
                var total_q = $('num_quiz_questions').value;
                
                //if(answered_num == total_q){
                //    $('quiz_nextbtn').hide();
                //    finish_quiz();
                //}
                
            }
        });
    }
}

function quiz_nextquestion(){
    
    $$('.quiz_question').each(function(item){
        item.hide();
    });
    
    var answered_num = $('answered_quiz_questions').value;
    var total_q = $('num_quiz_questions').value;
    
    if(answered_num == total_q){
        $('quiz_nextbtn').hide();
        finish_quiz();
    }
    else{
        var nextquestion = parseInt(quiz_current_question) + 1;
        
        $('quiz_question' + nextquestion).show();
        $('quiz_qnum_container').removeClassName('question_label' + quiz_current_question);
        $('quiz_qnum_container').addClassName('question_label' + nextquestion);
    }
}

function finish_quiz(){
    $$('.quiz_question').each(function(item){
        item.hide();
    });
    $('quiz_qnum_container').hide();
    var total_q = $('num_quiz_questions').value;
    var percentage = Math.round((parseInt(quiz_correct_count)/parseInt(total_q)) * 100);
    var str_score = quiz_correct_count + '/' + total_q;
    $('quiz_score').innerHTML = str_score;
    $('quiz_score_container').show();
    //$('quiz_message').innerHTML = 'Your Score: ' + str_score;
    new Effect.Appear('quiz_message_container', {
        duration: 0.3
    });
    
}

function save_quiz_score(){
    var total_q = $('num_quiz_questions').value;
    new Ajax.Request('XHR_quiz_score', {
        method: 'post',
        asynchronous: true,
        parameters: {
            num_correct: quiz_correct_count,
            total_questions: total_q
        },
        onSuccess:  function(ret){
            quiz_correct_count = 0;
            closequiz();
        }
    });
}

function closequiz(){
    $('popup_container').hide();
    $('popup_fader').hide();
    //spot.hide();
    //$('quiz_message').innerHTML = '';
    $('quiz_message_container').hide();
    quiz_correct_count = 0;
}

function close_top10winner(){
	$('popup_container').hide();
    $('popup_fader').hide();
    $('top10_winner_container').hide();
}

function start_hangman(){
    var game_area_id = 'hangman_game_area';
    var game_link_id = 'hangman_start_link';
    var phrase_area_id = 'long_phrase';
    var play_area_id = 'hangman_play_area';
    var guess_letters_id = 'letter_list';
    var winner_id = 'hangman_winner';
    var lose_id = 'hangman_lose';
    var time_lose_id = 'hangman_lose_time';
    num_wrong = 0;

	document.getElementById('char').value = '';

    $(winner_id).hide();
    $(lose_id).hide();
    $(time_lose_id).hide();
    $$('.key_overlay').each(
        function(item){
            for(var i=1; i<=6; i++){
                item.removeClassName('wrong' + i);
            }
            item.hide();
        }
    );
    
    for(var i=1; i<=6; i++){
       $('try' + i).hide(); 
    }

    // get game contents
    new Ajax.Request('XHR_get_hangman_stuff', {
        method: 'post',
        asynchronous: true,
        onSuccess:  function(req){
            var jsonObj = eval('(' + req.responseText + ')');
            if(jsonObj.error)
            {
                alert(jsonObj.error);
            }
            
            ret = jsonObj.data;
            
            var question_contents = ret.question;
            var playarea_contents = ret.play_area;
            $(phrase_area_id).innerHTML = question_contents;
            $(play_area_id).innerHTML = playarea_contents;
            
            if(!$(game_area_id).visible()){
                new Effect.Appear(game_area_id, {
                    duration: 0.4   
                });
                //$(game_link_id).innerHTML = 'Restart Game';
                $('start_hangup').hide();
            }
            
            hangman_timer(10, 0, 1);
        }
    });

    hangman_focus = window.setInterval(
	function()
	{
		document.getElementById('char').focus();
	}, 20);
					   
	document.onkeyup = hangman_keys;
	//document.onkeyup = hangman_keys_reset;
}



function setup_username_listener(){
    Event.observe('username', 'blur', function(event){
        login_focus = false;
    });
    Event.observe('username', 'focus', function(event){
        login_focus = true;
    });
}

function setup_password_listener(){
    Event.observe('password', 'blur', function(event){
        login_focus = false;
    });
    Event.observe('password', 'focus', function(event){
        login_focus = true;
    });
}

function hangman_keys(e){
    if(!login_focus){
		var theletter = document.getElementById('char').value;
		hangman_guess(theletter);
		document.getElementById('char').value = '';

    }
}


var num_wrong = 0;
function hangman_guess(guess){
    var winner_id = 'hangman_winner';
    var lose_id = 'hangman_lose';
    new Ajax.Request('XHR_hangman_guess', {
        onCreate: show_hangman_guess_spinner('show'),
        method: 'post',
        asynchronous: true,
        parameters: {
            guess: guess
        },
        onSuccess:  function(req){
            var guess_result = req.responseText;
            if(guess_result == ''){
                hangman_wrong_guess(guess);
            }
            else{
                if(guess_result.indexOf(',') == -1){
                    $('answer' + guess_result).innerHTML = guess.toUpperCase();
                }
                else{
                    
                    var arr_letter_positions;
                    arr_letter_positions = guess_result.split(',');
                    var arr_length = arr_letter_positions.length;
                    for(var i=0;i<arr_length;i++){
                        letter_position = arr_letter_positions[i];
                        $('answer' + letter_position).innerHTML = guess.toUpperCase();
                    }
                }
            }
            show_hangman_guess_spinner('hide');
            
            // see if they've got too many wrong.  Say too bad, so sad, buh bye
            
            if(num_wrong >= hangman_max_guess){
                $(lose_id).show();
				document.onkeyup = '';
				clearInterval(hangman_focus);
                hangman_timer('','','stop');
            }
            
            
            var num_blank = 0;
            $$('.hangman_guess').each(
                function(item){
                    if(item.innerHTML == '&nbsp;'){
                        num_blank++;
                    }
                }
            );
            
            if(num_blank == 0){
                $(winner_id).show();
				clearInterval(hangman_focus);
                hangman_timer('','','stop');
				document.onkeyup = '';
                
                seconds = $('timer_seconds').innerHTML;
                centiseconds = $('timer_centiseconds').innerHTML;
                
                time_left = seconds + '.' + centiseconds;
                
                new Ajax.Request('XHR_hangman_savescore', {
                    method: 'post',
                    asynchronous: true,
                    parameters: {
                        timeleft: time_left
                    }
                });
                
            }
        }
    });
}

function show_hangman_guess_spinner(mode){
    
    var div_id = 'answering_spinner';
    if(mode == 'hide'){
        $(div_id).hide();
    }
    else{
        $(div_id).setOpacity(0.8);
        $(div_id).show();
    }
}

function hangman_wrong_guess(guess){
    num_wrong = parseInt(num_wrong) + 1;
	if(guess.match(/[A-Za-z0-9é]/))
	{
		$('hk' + guess + '_overlay').addClassName('wrong' + num_wrong);
		$('hk' + guess + '_overlay').show();
	}
    $('try' + num_wrong).show();
}



function pulsate_timer(action){
    var current_color = '';
    var new_color = '';
    if(action == 'stop'){
        clearTimeout(pulsator);
        $('hangman_timer').setStyle({
            'color':'rgb(0,0,0)'
        });

    }
    else{
        new Effect.Morph('hangman_timer', {
            duration: 0.2,
            style: {
                'color': 'rgb(255,0,0)'
            },
            afterFinish: function(){
                new Effect.Morph('hangman_timer', {
                   duration: 0.2,
                   style: {
                        'color': 'rgb(0,0,0)'
                    },
                    afterFinish: function(){
                        pulsator = setTimeout('pulsate_timer(\'\')', 600);
                    }
                });
            }
        });
    }
}

function hangman_timer(current_sec, current_csec, mode){
    
    if(mode != 'stop'){
        var timeup = false;
        var lose_id = 'hangman_lose_time';
        var seconds = current_sec;
        var centiseconds = current_csec;
        if(seconds > 0){
            if(centiseconds > 0){
                centiseconds = centiseconds - 1;
            }
            else{
                if(seconds == 5){
                    pulsate_timer('');
                }
                centiseconds = 9;
                seconds = seconds - 1;
            }
            
            
        }
        else{
            if(centiseconds > 0){
                centiseconds = centiseconds - 1;
            }
            else{
                timeup = true;
            }
        }
        
        if(timeup){
            pulsate_timer('stop');
            $(lose_id).show();
        }
        else{
            $('timer_seconds').innerHTML = seconds;
            $('timer_centiseconds').innerHTML = centiseconds;
            var timer_exp = 'hangman_timer(' + seconds + ', ' + centiseconds + ')';
            hm_timer = setTimeout(timer_exp, 100);
        }
    }
    else{
        
        clearTimeout(hm_timer);
		document.onkeyup = '';
		clearInterval(hangman_focus);
        pulsate_timer('stop');
    }
}

function check_username_avail(username, spinner_id, message_container_id){
    if(username != ''){
        new Ajax.Request('XHR_username_avail', {
            onCreate: function(){
                $(message_container_id).hide();
                $(spinner_id).show();
            },
            method: 'post',
            asynchronous: true,
            parameters: {
                username: username
            },
            onSuccess:  function(req){
                $(spinner_id).hide();
                var result = req.responseText;
                var message = '';
                if(result == 'available'){
                    $(message_container_id).removeClassName('unavailable');
                    $(message_container_id).addClassName('available');
                    $(message_container_id).innerHTML = '';
                }
                else{
                    $(message_container_id).removeClassName('available');
                    $(message_container_id).addClassName('unavailable');
                    $(message_container_id).innerHTML = username + ' is already in use.  Please try another username.';
                    $('new_username').value = '';
                }
                $(message_container_id).show();
            }
        });
    }
}

function select_avatar(thelink, avatar){
    
    $$('.overlay').each(
      function(item){
        item.hide();
      }
    );
    
    var theoverlay = $(thelink.id).down(0);
    theoverlay.setStyle({
       opacity: 0.7 
    });
    
    theoverlay.show();
    $('selected_avatar').value = avatar;
    
}

function disp_expander_item(expander_id, link_id){
    if($(expander_id).visible()){
        //$(expander_id).hide();
        new Effect.SlideUp(expander_id, {
           duration: 0.4 
        });
        $(link_id).setStyle({
            'backgroundImage': 'url(/images/expander_closed.png)'
        });
    }
    else{
        //$(expander_id).show();
        new Effect.SlideDown(expander_id, {
           duration: 0.4 
        });
        $(link_id).setStyle({
            'backgroundImage': 'url(/images/expander_open.png)'
        });
    }
}

function start_slideshow_rotation(direction, mover_divid){
    var strfunc = 'move_slide(\'' + direction + '\', \'' + mover_divid + '\', true)';
    setTimeout(strfunc, 8000);
}

function move_slide(direction, mover_divid, use_timer){
    $('slideshow_nav_container').hide();
    
    current_x = parseInt($(mover_divid).getStyle('left'));
    
    if(direction == 'left'){
        new_x = parseInt(current_x) - parseInt(hp_slide_width);
    }
    else{
        new_x = parseInt(current_x) + parseInt(hp_slide_width);
    }
    
    var current_slides = $('current_slides').value;
    
    new Effect.Morph(mover_divid, {
        style: {
            'left': new_x + 'px'
        },
        duration: 0.4,
        afterFinish: function(){
            var arr_current_slides = current_slides.split(',');
            var num_slides = $('num_slides').value;
            var num_slides_for_random = num_slides + 1;
            var randomnumber = Math.floor(Math.random()*num_slides) + 1;
            var mayday_counter = 0;
            while(in_array(arr_current_slides, randomnumber)){
                if(mayday_counter >= 10){
                    break;
                }
                randomnumber = Math.floor(Math.random()*num_slides) + 1;
                mayday_counter++;
            }
                        
            var slide_contents = $('slideholder_' + randomnumber).innerHTML;
            var slide_id = randomnumber;
            
            var first_slide = $(mover_divid).down();
            var last_slide = $(mover_divid).down().next(1);
            if(direction == 'left'){
                first_slide.remove();
                $(mover_divid).setStyle({
                   'left': current_x + 'px' 
                });
                
                $(mover_divid).insert(slide_contents);
                arr_current_slides.shift();
                arr_current_slides.push(slide_id);
            }
            else{
                
                
                $(mover_divid).insert({
                   'top': slide_contents 
                });
                $(mover_divid).setStyle({
                   'left': current_x + 'px' 
                });
                last_slide.remove();
                
                arr_current_slides.pop();
                arr_current_slides.splice(0,0,slide_id);
                
            }
            new_slides = arr_current_slides.join(',');
            $('current_slides').value = new_slides;
            
            
            //new Ajax.Request('XHR_get_slide', {
            //    method: 'post',
            //    asynchronous: true,
            //    parameters: {
            //        current_slides: current_slides
            //    },
            //    onSuccess:  function(req){
            //        var jsonObj = eval('(' + req.responseText + ')');
            //        if(jsonObj.error){
            //            alert(jsonObj.error);
            //        }
            //        ret = jsonObj.data;
            //        var slide_contents = ret.slide;
            //        var slide_id = ret.id;
            //        var arr_current_slides = current_slides.split(',');
            //        var first_slide = $(mover_divid).down();
            //        var last_slide = $(mover_divid).down().next(1);
            //        if(direction == 'left'){
            //            first_slide.remove();
            //            $(mover_divid).setStyle({
            //               'left': current_x + 'px' 
            //            });
            //            
            //            $(mover_divid).insert(slide_contents);
            //            arr_current_slides.shift();
            //            arr_current_slides.push(slide_id);
            //        }
            //        else{
            //            
            //            
            //            $(mover_divid).insert({
            //               'top': slide_contents 
            //            });
            //            $(mover_divid).setStyle({
            //               'left': current_x + 'px' 
            //            });
            //            last_slide.remove();
            //            
            //            arr_current_slides.pop();
            //            arr_current_slides.splice(0,0,slide_id);
            //            
            //        }
            //        new_slides = arr_current_slides.join(',');
            //        $('current_slides').value = new_slides;
            //    }
            //});
            $('slideshow_nav_container').show();
        }
    });
    if(use_timer){
        var strfunc = 'move_slide(\'' + direction + '\', \'' + mover_divid + '\', true)';
        setTimeout(strfunc, 8000);
    }
}

function submit_txt_msg(game_id){
    var txt_message = $('top10_answer').value;
    //var slide_coord = '-14px';
	var slide_coord = '18px';
    if(game_id == '2'){
        slide_coord = '20px';
    }
    new Ajax.Request('XHR_top10_savemsg', {
        method: 'post',
        asynchronous: true,
        parameters: {
            message: txt_message,
            game_id: game_id
        },
        onSuccess:  function(req){
            $('top10_answer').value = '';
            $('new_message_contents').innerHTML = txt_message.replace(/\n/g,'<br />');
            new Effect.Morph('phone_messages', {
                style: {
                    'top': slide_coord   
                },
                duration: 0.2,
                afterFinish: function(){
                    $('phone_arrow').hide();
                    new Effect.Fade('top10_phone_entry', {
                       duration: 0.2,
                       afterFinish: function(){
                            new Effect.Appear('new_message', {
                                duration: 0.2
                            });    
                       }
                    });
                }
            });
        }
    });
}

function vote_txtmsg(votetype,item_id){
    var spinner_id = 'txt_spinner' + item_id;
    if(votetype == 'up'){
        vote_type = '1';
    }
    else{
        vote_type = '0';
    }
    new Ajax.Request('XHR_top10_vote', {
        onCreate: function(){
            $(spinner_id).setStyle({
               'opacity': '0.7' 
            });
            $(spinner_id).show();
        },
        method: 'post',
        asynchronous: true,
        parameters: {
            message_id: item_id,
            vote_type: vote_type
        },
        onSuccess:  function(req){
            $(spinner_id).hide();
            var voted_item_id = 'txt_msg' + item_id;
            $(voted_item_id).remove();
        }
    });
}

function comment_tabs(current_tab, iter, tabnumber){
    if(!$(current_tab).hasClassName('active')){
        $('tab1' + iter).removeClassName('active');
        $('tab2' + iter).removeClassName('active'); 
        $(current_tab).addClassName('active');
        if(tabnumber == '1'){
            $('comment_area' + iter).show();
            $('comment_post_area' + iter).hide();
        }
        else{
            $('comment_area' + iter).hide();
            $('comment_post_area' + iter).show();
        }
    }
}

function add_question(question_div_id){
    if(!($(question_div_id).visible())){
        new Effect.Grow(question_div_id, {
           direction: 'top-left',
           duration: 0.4
        });
    }
    else{
        new Effect.Shrink(question_div_id, {
           direction: 'top-left',
           duration: 0.4
        });
    }
}

function submit_question(question_div_id, content_box_id, show_popup_id, popup_id){
    var thecontent = $(content_box_id).value;
    var anonpost = 0;
    var show_popup = $(show_popup_id).value;
    if($('set_anon_q').hasClassName('checked')){
        anonpost = 1;
    }
    new Ajax.Request('XHR_new_question', {
        method: 'post',
        asynchronous: true,
        parameters: {
            question_content: thecontent,
            anonpost: anonpost
        },
        onSuccess:  function(req){
            new Effect.Shrink(question_div_id, {
                direction: 'top-left',
                duration: 0.4
            });
            $(content_box_id).value = '';
            if(show_popup == '1'){
                new Effect.Appear(popup_id, {
                    duration: 0.3//,
                    //afterFinish: function(){
                    //    $(popup_id).setStyle({
                    //       opacity: 0.9
                    //    });
                    //}
                });
            }
        }
    });
}

function submit_acronym(entry_div_id,acro_box_id,long_box_id, show_popup_id, popup_id){
    var theacro = $(acro_box_id).value;
    var thelong = $(long_box_id).value;
    var show_popup = $(show_popup_id).value;
    
    new Ajax.Request('XHR_new_acro', {
        method: 'post',
        asynchronous: true,
        parameters: {
            new_acro: theacro,
            new_long: thelong
        },
        onSuccess:  function(req){
            new Effect.Shrink(entry_div_id, {
                direction: 'top-left',
                duration: 0.4
            });
            $(acro_box_id).value = '';
            $(long_box_id).value = '';
            if(show_popup == '1'){
                new Effect.Appear(popup_id, {
                    duration: 0.3/*,
                    afterFinish: function(){
                        $(popup_id).setStyle({
                           opacity: 0.9
                        });
                    }*/
                });
            }
        }
    });
}

function avatar_scroll(direction, scroller_div_id){
    var screenful = 288;
    var max_left = -864;
    
    var current_x = parseInt($(scroller_div_id).getStyle('left'));
    var new_x = 0;
    var moveit = true;
    
    if(direction == 'left'){
        if(current_x > max_left){
            new_x = current_x - screenful;
        }
        else{
            moveit = false;
        }
    }
    else{
        if(current_x < 0){
            new_x = current_x + screenful;
        }
        else{
            moveit = false;
        }
    }
    
    if(moveit){
        $('avatar_browser_nav').hide();
        new Effect.Move(scroller_div_id, {
            x: new_x,
            mode: 'absolute',
            duration: 0.3,
            afterFinish: function(){
                $('avatar_browser_nav').show();
            }
        });
    }
}

function change_avatar(browser_container_id){
    new Effect.Appear(browser_container_id, {
        duration: 0.3 
    });
}

function update_avatar(avatar_img_path, avatar_img_id, new_avatar_box, browser_div_id){
    var avatar_file = $(new_avatar_box).value;
    var new_avatar = avatar_img_path + avatar_file;
    
    
    new Ajax.Request('XHR_update_avatar', {
        method: 'post',
        asynchronous: true,
        parameters: {
            new_avatar: avatar_file
        },
        onSuccess:  function(req){
            $(avatar_img_id).src = new_avatar;
            new Effect.Fade(browser_div_id, {
                duration: 0.3 
            });
        }
    });
}

function sign_declaration(signature_box, date_id, id_to_hide, id_to_show){
    var signature = $(signature_box).value;
    
    new Ajax.Request('XHR_sign_declaration', {
        method: 'post',
        asynchronous: true,
        parameters: {
            signature: signature
        },
        onSuccess:  function(req){
            var sign_time = req.responseText;
            $(date_id).innerHTML = sign_time;
            $(id_to_hide).hide();
            $(id_to_show).show();
        }
    });
}

function setup_main_menu_rolls(){
    $$('#leftmenu a').each(
        function(item){
            Event.observe(item, 'mouseover', function(event){
                if(!(item.hasClassName('active'))){
                    item.addClassName('over');
                    new Effect.Morph(item.id, {
                        style: {
                            'width': main_nav_maxwidth + 'px'
                        },    
                        duration: 0.1
                    });
                }
            });
            Event.observe(item, 'mouseout', function(event){
                item.removeClassName('over');
                if(!(item.hasClassName('active'))){
                    item.setStyle({
                        'width': main_nav_minwidth + 'px'  
                    });
                }
            });
        }
    )
}

function set_anon_q(thecheckbox){
    var thebox = $(thecheckbox);
    if(thebox.hasClassName('checked')){
        thebox.removeClassName('checked');
    }
    else{
        thebox.addClassName('checked');
    }
}

function set_checkbox(thecheckbox){
    var thebox = $(thecheckbox);
    if(thebox.hasClassName('checked')){
        thebox.removeClassName('checked');
    }
    else{
        thebox.addClassName('checked');
    }
}

function subform(formid){
    $(formid).submit();
}

function new_acronym(div_id){
    if(!($(div_id).visible())){
        new Effect.Grow(div_id, {
           direction: 'top-left',
           duration: 0.4
        });
    }
    else{
        new Effect.Shrink(div_id, {
           direction: 'top-left',
           duration: 0.4
        });
    }
}

function getPageSize(){
	        
    var xScroll, yScroll;
   
   if (window.innerHeight && window.scrollMaxY) {	
       xScroll = window.innerWidth + window.scrollMaxX;
       yScroll = window.innerHeight + window.scrollMaxY;
   } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
       xScroll = document.body.scrollWidth;
       yScroll = document.body.scrollHeight;
   } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
       xScroll = document.body.offsetWidth;
       yScroll = document.body.offsetHeight;
   }
   
   var windowWidth, windowHeight;
   
   if (self.innerHeight) {	// all except Explorer
       if(document.documentElement.clientWidth){
           windowWidth = document.documentElement.clientWidth; 
       } else {
           windowWidth = self.innerWidth;
       }
       windowHeight = self.innerHeight;
   } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
       windowWidth = document.documentElement.clientWidth;
       windowHeight = document.documentElement.clientHeight;
   } else if (document.body) { // other Explorers
       windowWidth = document.body.clientWidth;
       windowHeight = document.body.clientHeight;
   }	
   
   // for small pages with total height less then height of the viewport
   if(yScroll < windowHeight){
       pageHeight = windowHeight;
   } else { 
       pageHeight = yScroll;
   }

   // for small pages with total width less then width of the viewport
   if(xScroll < windowWidth){	
       pageWidth = xScroll;		
   } else {
       pageWidth = windowWidth;
   }

   return [pageWidth,pageHeight];
}

function close_post_popup(item_id, noshow_checkbox_id, show_popup_id){
    if($(noshow_checkbox_id).hasClassName('checked')){
        new Ajax.Request('XHR_set_post_popup_disp', {
        method: 'post',
        asynchronous: true,
		parameters: {
            show_popup: '0'
        },
        onSuccess:  function(req){
            $(show_popup_id).value = '0';
            hide_item(item_id);
        }
        });
    }
    else{
        hide_item(item_id);
    }
    
}

function hide_item(item_id){
    $(item_id).hide();
}

function get_qanda_answer(intQuestionID, aCurrent){
    new Ajax.Request('XHR_get_qanda_answer', {
        method: 'post',
        asynchronous: true,
		parameters: {
            question_id: intQuestionID
        },
        onSuccess:  function(req){
            var jsonObj = eval('(' + req.responseText + ')');
            if(jsonObj.error)
            {
                alert(jsonObj.error);
            }
            
            var ret = jsonObj.data;
            
			$("pQuestion").innerHTML = aCurrent.innerHTML;
            $("pAnswer").innerHTML = '';
            $("pAnswer").innerHTML = ret.answer;
			$("spanUsername1").innerHTML = ret.username;
			$("spanUsername2").innerHTML = ret.username;
        }
    });
}

function get_comment_page(strPageNum, page_id, content_id){
    new Ajax.Request('XHR_get_comment_page', {
        method: 'post',
        asynchronous: true,
		parameters: {
            page_num: strPageNum,
            page_id: page_id,
            content_id: content_id
        },
        onSuccess:  function(req){
            var jsonObj = eval('(' + req.responseText + ')');
            if(jsonObj.error)
            {
                alert(jsonObj.error);
            }
            
            var ret = jsonObj.data;
            
			$("comment_area").innerHTML = ret.comments;
        }
    });
}

function delpost(post_id){
    if(confirm("Are you sure you want to delete this item?")){
        new Ajax.Request('XHR_remove_post', {
            method: 'post',
            asynchronous: true,
            parameters: {
                post_id: post_id
            },
            onSuccess:  function(req){
                $('post' + post_id).remove();
            }
        });
    }
}

function sub_teacherpromo(form_id){
    var name = $('name').value;
    var school_name = $('school_name').value;
    var email = $('email').value;
    var phone = $('phone').value;
    var comments = $('comments').value;
	var address = $('address').value;
	var city = $('city').value;
	var province = $('province').value;
	var postal_code = $('postal_code').value;
	var theform = $(form_id);
    var res =  valid.validate();
    if(res === true){
        new Ajax.Request('XHR_add_teacher_promo', {
			method: 'post',
			asynchronous: true,
			parameters: {
				name: name,
				school_name: school_name,
				email: email,
				phone: phone,
				comments: comments,
				address: address,
				city: city,
				province: province,
				postal_code: postal_code
			},
			onSuccess:  function(req){
				$('teacher_form').hide();
				$('submit_message').show();
			}
		});
    }
    
}

function in_array(array, value){
    for(var i = 0, l = array.length; i < l; i++) {
		if(array[i] == value) {
			return true;
		}
	}
	return false;
}



function sub_new_profile(formid){
   
    var theform = $(formid);
    var res =  valid.validate();
    if(res === true){
        theform.submit();
    }
}

function check_otherbox(show, otherbox_container_id){
	if(show){
		$(otherbox_container_id).show();
	}
	else{
		$(otherbox_container_id).hide();
	}
}

function submit_eval(form_id){
	var theform = $(form_id);
    var res =  valid.validate();
    if(res === true){
        theform.submit();
    }
}

function submit_needhelp(form_id){
	$('hform').hide();
	$('hsubmsg').show();
	//subform('frmNeedHelp')
	
}
function stop_needhelp(){
	new Ajax.Request('XHR_log_stop_needhelp', {
		method: 'post',
		asynchronous: true,
		onSuccess:  function(req){
			$('hsubmsg').hide();
			$('hstopmsg').show();
		}
	});
}

function scroll_view(scroller_id, scroll_amt, scroll_dir){
	var current_x = parseInt($(scroller_id).getStyle('left'));
	var current_y = parseInt($(scroller_id).getStyle('top'));
	var newx = 0;
	var newy = 0;
	var scroller_height = $(scroller_id).getHeight();
	var max_vert_scroll = (parseInt(scroller_height) - parseInt(scroll_amt)) * -1;
	
	switch(scroll_dir){
		case 'left':{
			newx = parseInt(current_x) - parseInt(scroll_amt);
			newy = current_y;
		}
		break;
		case 'right':{
			newx = parseInt(current_x) + parseInt(scroll_amt);
			newy = current_y;
		}
		break;
		case 'up':{
			newy = parseInt(current_y) - parseInt(scroll_amt);
			if(newy < max_vert_scroll){
				newy = max_vert_scroll;
			}
			newx = current_x;
		}
		break;
		case 'down':{
			newy = parseInt(current_y) + parseInt(scroll_amt);
			if(newy > 0){
				newy = 0;
			}
			newx = current_x;
		}
		break;
	}
	
	new Effect.Move(scroller_id, {
		x: newx,
		y: newy,
		mode: 'absolute',
		duration: 0.3
	});
}

function move_top10_votingitem(direction, current_vote_fieldid, game_id){
	var current_number = $(current_vote_fieldid).value;
	var fieldlist = $('items_list_g' + game_id).value;
	var arr_fieldlist = fieldlist.split(',');
	
	var currentitem_id = '';
	var next_itemid = '';
	var makeitso = false;
	var new_number = 0;
	var current_index = 0;
	var max_index = arr_fieldlist.length - 1;
	
	
	for(var i=0; i<arr_fieldlist.length; i++){
		if(arr_fieldlist[i] == current_number){
			current_index = i;
			break;
		}
	}
	
	switch(direction){
		case 'next':{
			
			if(current_index < max_index){
				new_index = parseInt(current_index) + 1;
				makeitso = true;
			}
		}
		break;
		case 'prev':{
			if(current_index > 0){
				new_index = parseInt(current_index) - 1;
				makeitso = true;
			}
		}
		break;
	}
	
	if(makeitso){
		new_number = arr_fieldlist[new_index];
		currentitem_id = 'finalvote_item_' + current_number + '_container_g' + game_id;
		next_itemid = 'finalvote_item_' + new_number + '_container_g' + game_id;
		
		$(current_vote_fieldid).value = new_number;
		
		Effect.Fade(currentitem_id, {
			duration:0.3,
			from:1.0,
			to:0.0
		});
		
		Effect.Appear(next_itemid, {
			duration:0.3,
			from:0.0, to:1.0
		});
	}
}

function cast_finalvote(votetype, current_vote_fieldid, game_id){
	var current_number = $(current_vote_fieldid).value;
	var id_fieldid = 'finalvote_itemid_' + current_number + '_g' + game_id;
	var item_id = $(id_fieldid).value;
	var vote_type = 0;
	var fieldlist = $('items_list_g' + game_id).value;
	var arr_fieldlist = fieldlist.split(',');
	var current_index = 0;
	var max_index = arr_fieldlist.length - 1;
	var spinner_id = 'finalvote_spinner_g' + game_id;
	
	for(var i=0; i<arr_fieldlist.length; i++){
		if(arr_fieldlist[i] == current_number){
			current_index = i;
			break;
		}
	}
	
	if(votetype == 'up'){
        vote_type = '1';
    }
    else{
        vote_type = '0';
    }
	new Ajax.Request('XHR_top10_finalvote', {
        onCreate: function(){
            $(spinner_id).setStyle({
               'opacity': '0.7' 
            });
            $(spinner_id).show();
        },
        method: 'post',
        asynchronous: true,
        parameters: {
            message_id: item_id,
            vote_type: vote_type
        },
        onSuccess:  function(req){
			
            $(spinner_id).hide();
            var voted_item_id = 'finalvote_item_' + current_number + '_container_g' + game_id;
			
			
			var direction = 'next';
			if(current_index == max_index){
				direction = 'prev';
			}
			if(max_index > 0){
				move_top10_votingitem(direction, current_vote_fieldid, game_id);
			}
			for(var i = 0; i<arr_fieldlist.length; i++){
				if(arr_fieldlist[i] == current_number){
					arr_fieldlist.splice(i, 1);
					break;
				}
			}
			$('items_list_g' + game_id).value = arr_fieldlist.join(',');
            $(voted_item_id).remove();
			if(max_index == 0){
				$('thanks_g' + game_id).show();
				$('voteitems_container_g' + game_id).hide();
			}
        }
    });
}

function show_top10_winner(){
    var dimmerdiv_id = 'popup_fader';
    var winnerdiv_id = 'top10_winner_container';
	    
    var arrayPageSize = getPageSize();
    
    $(dimmerdiv_id).show();
    $(dimmerdiv_id).setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px', opacity: 0.7 });

    $('popup_container').show();
    document.location.href = '#';

}