currentID = "0";

//interval timer refs
curQuestTimer = null;
eventConsoleTimer = null;
pageTimer = null;
countDownTimer = null;
showCountDown = false;
leftTime = 0;


function freeQuestion(currentID) {
    if(currentID>0)  $.get('/questions/freeQuestion/'+currentID);
}


window.onbeforeunload = function(e) {
    freeQuestion(currentID);
}

function checkQuestionState(questionID,mode) {
	var url = '/questions/questionBox/'+ questionID;
    if (mode!='init') url = url+'/refresh';
    $.ajax({type: 'POST',data: {}, url: url,success: refreshQuestionBox});
}

function showAnswerForm(questionID){
	currentID = questionID;
	$.get('/questions/answerForm/' + questionID, function(response){
		$('#answerFormArea').hide();
		if ($('#answerBtn')) 
			$('#answerBtn').hide();
		$('#answerFormArea').html(response);
		$('#answerFormArea').slideDown('slow',function(){ogiPos();});
		checkQuestionState(currentID);
	});
}

function insertAnswer(questionID) {
    var myrxp = new RegExp('[0-9A-Za-z]');
    var rxpCheck = (myrxp.test($('textarea#answer').val()));
	if (rxpCheck != true) {
        $('#responseAreaBlankError').show('slow',function(){ogiPos();});
        return false;
    }
	currentID = questionID;
    $('#answerButton').removeAttr('onclick');
    $.post('/questions/addAnswer/'+questionID,$("#answerForm").serialize(),function(response) {
		$('#responseAreaCustomError').html(response);
		$('#responseAreaCustomError').show('slow');
        $('#answerFormElements').slideUp('fast',function(){ogiPos();});
        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) {
    try {_gaq.push(['_trackEvent', 'website', 'open', 'questionBox']);}catch(err) {}
	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 ogiPos(){
	// position des ogis
    var bh = $('#bubble').height(); // *1 to work in safari
    var cbT=$('#closeQuestionBoxLink').position().top;
    var top = cbT-bh+10;
    
    
    $('#bubble').css({'top':top+'px'});
    $('#bubble').show();
    
}

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());
    ogiPos();//ogi position setzen im Antwortfenster
    
}    



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);
       ogiPos();//ogi position setzen im Antwortfenster
    }
    
    $('#layerContainer').attr('class',$('#boxState').html());

    if($('#boxState').html() == 'answered')
        clearInterval(curQuestTimer);
   
    if($('#questionCountDown')) {
    	
       leftTime = $('#questionCountDown').text();
	   if(leftTime <= 0) {
	       if($('#answerFormArea')) {
	            freeQuestion(currentID);  
	            //if there is no success msg already  
	            if($('#responseArea').html() == '') {
	                $('#responseAreaTime').show('slow');
	            }                
	            $('#answerFormElements').slideUp('slow',function(){ogiPos();});
	       }           
	   }
       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 max_Length(field,maxChars) {
    $('#maxCharInfo').hide();
    var obj= $(field);
    var count = obj.val().length;
	var available = maxChars - count;
	if(available <= 10){
		$('#charCounter').addClass('redFont');
	} else {
		$('#charCounter').removeClass('redFont');
	}
	if(available <= 0){
		var text=obj.val();
			text=text.substring(0,maxChars);
		obj.val(text);
		$('#charCounter').html('0');
	}else{ 
		$('#charCounter').html(available);
	}
}

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 editFeedbackPost(obj,threatID,postID){
	var inhalt=$(obj).parents('td').next('td');
	if( threatID > 0 && postID >0){
	
		$.ajax({
			url: '/feedbacks/edit',
			data: {'threadID':threatID,'postID':postID},
			success: function(response){
				if (!response) 
					return false;
				inhalt.html(response);
			}
		});
	
	
	}else{
		$(obj).parents('td').next('td').css('background-color', 'red');
	}
	return false;
}
function submitEditForm(postID,threatID){
	$.post('/feedbacks/edit',
			$('#feedback-'+postID).serialize(),
			function(response){
				if (!response) 
					return false;
				var spalte = $('#feedback-'+postID).parents('td');
				spalte.html(response);
			}
	);

	return false;
}
function closeFeedbackEditForm(id){
	var headline = $("input[name='data[Feedback][headline]']").val();
	var res="";
	if(!headline){
		headline = $('#feedback-'+id).parents('tr').prev().find('.greenFont').text();
		if(headline.substr(0,3) != 'Re:')
			headline = 'Re: '+headline;
	}
	res+='<p class="greenFont">'+headline+'</p>';
	$.ajax({
		url: '/feedbacks/edit',
		data: {'close':'1','postID':id},
		success: function(response){
			res+=response;
			$('#feedback-'+id).parents('td').html(res);
		}
	});
	return false;
}


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 toggleMyState(eleID){
	
	$('#'+eleID).toggle();
	
}

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+element.options[element.selectedIndex].value;
}


function namedFilter(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 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;
    }
}

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,secureUrl){
	if (!$('input#' + type).length) {
		($('#settingNote_' + type + '_blankError').show('slow'));
		return false;
	}
	
	url = '/users/changeBaseSetting/';
    if(secureUrl != 'nope')
       url = secureUrl+'/secure/changeBaseSetting/'; 
    $.postJSON(url, {
		type: type,
		value: $('#'+type).val()
	}, function(response){
		$('#settingNote_' + response.type).html(response.message);
	});
}	
	
function showEmailResendNote() {
    $('#settingNote_UserEmail').show('slow');
    $('#settingNote_UserEmail').attr('class','visible');
    $('#UserEmail').attr('disabled',false);
}

function sendRegisterChange(secureUrl) {
    if(!$('input#UserEmail').length) {
        $('#settingNoteError_UserEmail').show();
        return false;
    }
    url = '/users/resendUnlockData/';
	if(secureUrl != 'nope')
	   url = secureUrl+'/secure/resendUnlockData/'; 
    $.postJSON(url,
	           {hncaptcha:$('#capcha_UserEmail').val(),public_key:$('#public_key').val(),private_key:$('#capcha_UserEmail').val(),userID:$('#userID').val(),mailType:$('#mailType').val(),type:'UserEmail',value:$('#UserEmail').val()},
        		function(response){
					if(response.capcha) 
                       $('#settingNote_capcha_UserEmail').html(response.capcha);
                    $('#settingNote_response_UserEmail').html(response.message);
				});
} 
 
// initial script by Lokesh Dhakar - http://www.huddletogether.com
function getWindowSize(container) {
	// layer auf aktuelle scroll hoehe setzen und nach oben etwas abziehen
	var top = $(window).scrollTop()-100;
	$(container).css({ 'top': top+'px'});
	// set document background
	var docHeight=$(document).height();
	$('#layerOverlay').height(docHeight);
}

// 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');
};

