function showEmailResendNote() {
    $('#settingNote_UserEmail').show('slow');
    $('#settingNote_UserEmail').attr('class','visible');
    $('#UserEmail').attr('disabled',false);
}

function sendRegisterChange() {
    if(!$('input#UserEmail').length) {
        $('#settingNoteError_UserEmail').show();
        return false;
    }
    
    $.postJSON('/communities/resendRegisterEmail/',
               {hncaptcha:$('#capcha_UserEmail').val(),public_key:$('#public_key').val(),private_key:$('#capcha_UserEmail').val(),subdomain:$('#subdomain').val(),email:$('#UserEmail').val()},
                function(response){
                    console.log(response.message);
                    if(response.capcha) 
                       $('#settingNote_capcha_UserEmail').html(response.capcha);
                    $('#settingNote_response_UserEmail').html(response.message);
                });
}

function swapImage(obj) {
    var imgPath     = obj.childNodes[0].src;
    var dotPos      = imgPath.lastIndexOf('.');
    var status      = imgPath.substr(dotPos-2, 2);
    var pathStart   = imgPath.substr(0, dotPos-2);
    var pathEnd     = imgPath.substr(dotPos, imgPath.length-dotPos);
    
    if(status == 'lo') {
        obj.childNodes[0].src = pathStart + 'hi' + pathEnd;
    } else {
        obj.childNodes[0].src = pathStart + 'lo' + pathEnd;
    }
}













currentID = "0";

//interval timer refs
curQuestTimer = null;
eventConsoleTimer = null;
pageTimer = null;
countDownTimer = null;
showCountDown = false;
leftTime = 0;

window.onbeforeunload = function(e) {
    freeQuestion(currentID);
}

function freeQuestion(currentID) {
    if(currentID>0)  $.get('/questions/freeQuestion/'+currentID);
}

function showAnswerForm(questionID){
    currentID = questionID;
    $.get('/questions/answerForm/' + questionID, function(response){
        $('#answerFormArea').hide();
        if ($('#answerBtn')) 
            $('#answerBtn').hide();
        $('#answerFormArea').html(response);
        $('#answerFormArea').show('slow');
        checkQuestionState(currentID);
    })
}

function insertAnswer(questionID) {
    if( !checkInputLength()) 
        return false;
    
    var myrxp = new RegExp('[0-9A-Za-z]');
    var rxpCheck = (myrxp.test($('textarea#answer').val()));
    if (rxpCheck != true) {
        $('#responseAreaBlankError').show('slow');
        return false;
    }
    currentID = questionID;
    $('#answerButton').removeAttr('onclick');
    $.post('/questions/addAnswer/'+questionID,$("#answerForm").serialize(),function(response) {
        $('#responseAreaCustomError').html(response);
        $('#responseAreaCustomError').show('slow');
        $('#answerFormElements').hide('slow');
        checkQuestionState(currentID);
    });
    return false;
}

function verifyAnswer(questionID, answer){
    if ($('#confirmButton')) 
        $('#confirmButton').removeAttr('onclick');
    if ($('#confirmButton_a1')) 
        $('#confirmButton_a1').removeAttr('onclick');
    if ($('#confirmButton_a2')) 
        $('#confirmButton_a2').removeAttr('onclick');
        $.get('/questions/confirmAnswer/' + questionID + '/' + answer, function(response){
        checkQuestionState(questionID);
    });
}

function vetoAnswers(questionID) {
    $('#vetoButton').removeAttr('onclick');
    $.get('/questions/vetoAnswers/' + questionID, function(response){
        checkQuestionState(questionID);
    });     
}

function questionBox(questionID) {
    currentID = questionID;
    
    $('.tdLeft').removeAttr('onclick');
    $('li .console').removeAttr('onclick'); 
    checkQuestionState(questionID,'init');
    curQuestTimer = window.setInterval("checkQuestionState("+questionID+",'refresh')", 5000);
}

function closeBox(questionID) {
    $('#layerOverlay').hide();
    $('#layerContainer').hide();
    location.href ='/questions/closeBox/'+questionID;
}    

function createBox(response) {
    clearInterval(eventConsoleTimer);
    clearInterval(pageTimer);
    $('#selectForm').hide();
    $('#hiogiBanner').hide();
    $('#hiogiBanner').hide();
    $('#bannerContainer').show();
    $('#playerContainer').hide();
    
    getWindowSize('#layerContainer');
    $('#layerOverlay').show();
    $('#layerContainer').show();
    $('#layer').html(response);
    $('#layerContainer').attr('class',$('boxState').html());
}    

function checkQuestionState(questionID,mode) {
    var url = '/questions/questionBox/'+ questionID;
    if (mode!='init') url = url+'/refresh';
    $.ajax({type: 'POST',data: {}, url: url,success: refreshQuestionBox});
}

function refreshQuestionBox(response) {
    if(response.substr(0,8) == 'redirect') {
       location=response.substr(10,response.length);
       return false;
    }      
    if(!$('#statusArea').length)  
       createBox(response);
    else       
        $('#statusArea').html(response);

    $('#layerContainer').attr('class',$('#boxState').html());

    if($('#boxState').html() == 'answered')
        clearInterval(curQuestTimer);
    
    if($('#questionCountDown')) {
       leftTime = $('#questionCountDown').html();
       if(leftTime <= 0) {
           if($('#answerFormArea')) {
                freeQuestion(currentID);  
                //if there is no success msg already  
                if($('#responseArea').html() == '') {
                    $('#responseAreaTime').show('slow');
                }                
                $('#answerFormElements').hide('slow');
           }           
       }
       clearInterval(countDownTimer);
       countDownTimer = setInterval('questionCountDown()',1000);
    }
    else 
        clearInterval(countDownTimer);
    
    $('#questionCountDown').html(updateCountDown(leftTime));
}   

function questionCountDown() {
    leftTime--; 
    $('#questionCountDown').html(updateCountDown(leftTime));
    if(leftTime <=0) {
       clearInterval(countDownTimer);
    }   
}

function eventConsoleRefresher() {
    clearInterval(eventConsoleTimer);
    eventConsoleTimer = setInterval('updateEventConsole()',12000);
}

function updateEventConsole(){
    $.ajax({
        url: '/questions/consoleRefresh',
        data: {},
        success: function(response){
            if (!response) 
                return false;
            $('#eventConsole').html(response);
        }
    });
}

function startRefresher() {
    clearInterval(pageTimer);
    pageTimer = setInterval('updateQuestions()',10000);
}

function updateQuestions() {
    $.getJSON('/questions/questListRefresh',refreshQuestions);
    
}    

function refreshQuestions(response) {
    if(response.newQuestionCount>0) {
        $('#newQuestionTicker').show();
        $('#newQuestionCount').html(response.newQuestionCount);
    }        
    else 
        $('#newQuestionTicker').hide();
    
    $.each( response.questionList, function(i, n){switchQuestionState(n);}); 
}

function switchQuestionState(questObj)
{
    $('#rating'+ questObj.id).attr('title',questObj.rank_name);
    $('#rating'+ questObj.id).attr('src',questObj.img);
    $('#rating'+ questObj.id).attr('alt',questObj.rank_name);
    
    $('#commentCount'+ questObj.id).text(questObj.comments);
    $('#questionState'+ questObj.id).html(questObj.questionStateName);
    
    premium = '';
    if(questObj.premium)
       premium = 'Premium'; 
    
           
    switch(questObj.questionState) {
        case 'virgin':
            $('#questionCard'+ questObj.id).attr('class','questionCard questionOpen'+premium);
            break;
        case 'waitForVerification_battle':
        case 'waitForVerification_single':
            $('#questionCard'+ questObj.id).attr('class','questionCard questionConfirm'+premium);
            break;
        case 'checkedOut':
            $('#questionCard'+ questObj.id).attr('class','questionCard questionChallenge'+premium);
            break;
        case 'inVerification_battle':
        case 'inVerification_single':
            $('#questionCard'+ questObj.id).attr('class','questionCard questionInConfirm'+premium);
            break;
        case 'battled_oneAnswer':
        case 'battled_noAnswer':
        case 'questionLock':
            $('#questionCard'+ questObj.id).attr('class','questionCard questionInChallenge'+premium);
            break;
        case 'answered':
            $('#questionCard'+ questObj.id).attr('class','questionCard questionAnswered'+premium);
            $('#questionLink'+ questObj.id).click(function() {location.href='question/-'+questObj.closed_q_id+'.html';});
            break;

    }            
}

function maxLength(field,maxChars) {
    $('#maxCharInfo').hide();
    if(field.value.length >= maxChars) 
        field.value = field.value.substring(0, maxChars);
    if( maxChars - (field.value.length) == 0 )
        $('#charCounter').html("0");
    else
        $('#charCounter').html(maxChars - (field.value.length));
}

function checkInputLength() {
    if($('#answer').val().length > 140) {
        $('#responseAreaErrorMaxChars').show('slow');
        $('#answer').focus();
        return false;
    } else {
        return true;
    }
}

function checkReview(form) {
    if($("input[@name='data[review][rating]']:checked").val()== undefined) {
        $('#errorBlankReview').show('slow');
        return false;
    }

    if($("input[@name='data[review][rating]']:checked").val()== -1 && !$('#review_comment').val().length) {
        $('#errorBlankCommentReview').show('slow');
        $('#errorBlankReview').hide('slow');
        return false;
    }
    form.submit();
    
}

function checkComment() {
    if(!$('#comment').val().length) {
        $('#errorBlankComment').show('slow');
        return false;
    }
    return true;
}

function hiogiRequest(name,url){
    
    $.get(url, function(response){ 
        $('#'+name+'Response').html(response);
        $('#'+name+'Response').show('slow');
    });
} 
function hiogiSwitchRequest(url,onElement,offElement,loadingElement){
    if(loadingElement) $('#'+loadingElement).show();
    $.get(url, function(response){ 
        if(loadingElement) $('#'+loadingElement).hide();
        if (response == 'off') {
            $('#'+onElement).hide();
            $('#'+offElement).show();
        }
        else {
            $('#'+offElement).hide();
            $('#'+onElement).show();
        }
    });
}   
    
function showArea(areaID,formFieldID) {
    if($('#'+areaID).css('display')== '') {
        $('#'+areaID).show('slow');
        $('#'+formFieldID).attr('disabled',true);
    }
    
    if($('#'+areaID).css('display')== 'none') {
        $('#'+areaID).show('hide');
        $('#'+formFieldID).attr('disabled',false);
    }
}

function addVote(){
     if($("input[@name='data[Poll][content]:checked").val()!= undefined) {
      $('#blankVoteError').show('slow');
        return false;
    }
    
    $('#pollBtn').removeAttr('onclick');
    
    $.post('/polls/add/',$('#pollForm').serialize(),function(response){
        $('#pollResponse').html(response);
    })
    return true;
}  

function showVotes(pollID) {
    $.get('/polls/show/'+pollID);
    return true;
}

function updateCountDown(timeLeft) {
    if(timeLeft>0)
        return  String(Math.floor(timeLeft/60+100)).substr(1,2)+':'+String(timeLeft%60+100).substr(1,2);
    else
        return  '00:00';
             
}

function filter(form,baseURL) {
    var index=form.selectedIndex;
    
    for(i=0;i<form.length;i++) {
       if(form[i].type == 'select-one')
            element = form[i];
    }
    location=baseURL+'filter:'+element.options[element.selectedIndex].value;
}


Array.prototype.contains = function(element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) 
            return true;
    }
    return false;
};


function showSettingNote(type) {
    $('#settingNote_UserPhone').hide('slow');
    $('#UserPhone').attr('disabled',true);
    $('#settingNote_UserEmail').hide('slow');
    $('#UserEmail').attr('disabled',true);
    
    $('#'+type).attr('disabled',false);
    $('#settingNote_'+type).show('slow');
}

function sendSettingChange(type){
    if (!$('input#' + type).length) {
        ($('#settingNote_' + type + '_blankError').show('slow'));
        return false;
    }
    
    $.postJSON('/users/changeBaseSetting/', {
        type: type,
        value: $('#'+type).val()
    }, function(response){
        $('#settingNote_' + response.type).html(response.message);
    })
}   

 
// initial script by Lokesh Dhakar - http://www.huddletogether.com
function getWindowSize(container) {
    
    var xScroll, yScroll;
    
    if (window.innerHeight && window.scrollMaxY) {  
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
        $(container).css('top',-100 + window.pageYOffset);
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
        $(container).css('top',-100 + document.body.scrollTop);
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
        $(container).css('top',-100 + document.documentElement.scrollTop);
    }
    
    var windowWidth, windowHeight;
    if (self.innerHeight) { // all except Explorer
        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 = windowWidth;
    } else {
        pageWidth = xScroll;
    }
    
    $('#layerOverlay').height(pageHeight);
}

// just for fixing problems with internet explorer
function fixedIE(tl, n, el){
    var sc = 'scroll'+tl, d = document, c = 'compatMode',
    b = d[c]&&d[c]=='CSS1Compat'? d.documentElement : d.body;
    n = n-0; if(typeof n!='number')return 0;
    if(/^(Top|Left)$/.test(tl))
       return b[sc]+n+'px';
    if(/^(Bottom|Right)$/.test(tl)&&typeof el=='object'){
       tl = tl=='Right'? 'Left' : 'Top', sc = 'scroll'+tl;
       var dim = 'client' + (tl=='Top'? 'Height' : 'Width');
       return b[sc]+b[dim]-el[dim]-n+'px';
    }
    return 0;
}


function showBookmarks() {
    if( $('#bookmarkDiv').css('display')== false || $('#bookmarkDiv').css('display')=='none') 
        $('#bookmarkDiv').show();
    else
        $('#bookmarkDiv').hide();
}

function checkEmail(email) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(email) ){
        return (true);
    }
    return false;
}

function requestRankingPage(ranking,page) {
    $.ajax({
        url: '/community/'+ranking+'/'+ranking+'Page:'+page,
        cache: false,
        success:function(html){
                $('#'+ranking).html(html);
        }                            
    });
}   

function requestPage(destination,url) {
    $.ajax({
        url: url,
        cache: false,
        success:function(html){
                $('#'+destination).html(html);
        }                            
    });
}

function showShortProfile(element,nickname) {
        wLeft = getAbsoluteLeft(element)+element.offsetWidth+4;
        wTop = getAbsoluteTop(element);
        $('body').append('<div id="shortProfile" style="left:'+wLeft+'px;top:'+wTop+'px"><img alt="loading" src="/img/loading.gif"/></div>');
        $('#shortProfile').load('/profiles/shortProfile/'+nickname);
}

function hideShortProfile(element) {
        $('#shortProfile').remove();
}

function getAbsoluteLeft(element) {
    // Get an object left position from the upper left viewport corner
    o = element;
    oLeft = o.offsetLeft;            // Get left position from the parent object
    while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
        oParent = o.offsetParent    // Get parent object reference
        oLeft += oParent.offsetLeft // Add parent left position
        o = oParent
    }
    return oLeft;
}


function getAbsoluteTop(element) {
    // Get an object top position from the upper left viewport corner
    o = element;
    oTop = 0;
    while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
        oParent = o.offsetParent    // Get parent object reference
        oTop += oParent.offsetTop // Add parent left position
        o = oParent
    }
    return oTop;
}

$.postJSON = function(url, data, callback){
    $.post(url, data, callback, 'json');
};

