
function jqEInit(f) {
	cId = document.getElementById('chatId').value;
	jqE = {
		'getChat': {'cId': cId},
		'private': {}
	}
	jqEngine(f);
}

function jqEngine(f) {
	$.post('/includes/jqEngine.php', {'a': jqE}, function(result) {
		if(result.clear) $.each(result.clear, function(aid, jqName) {delete jqE[jqName];});
		mTime = result.mTime;
		uTime = result.uTime;

		getChat(f, result['getChat']);
		userBalance(result.balance);
		handlePrivate(result.private);

		if(window.jqTimeout) clearTimeout(jqTimeout);
		jqTimeout = setTimeout('jqEngine()', 1500);
	}, 'json');
}

function handlePrivate(prv) {
	if(!prv) return false;

	switch(prv) {
		case 'start':
			messageBox();
			jqE['private']['startTime'] = uTime;
			jqE['private']['curTime'] = uTime;
		break;
		case 'in':
			jqE['private']['startTime'] = uTime;
			jqE['private']['curTime'] = uTime;
		break;
		case 'nomoney':
			messageBox('Your account is too low on money. Please add some credits.');
		break;
		case 'updCamera':
			cameraUpdate();
		break;
		case 'end':
			messageBox();
			jqE['private'] = {};
			$('#endPrivateImage').addClass('noDisplay');
			$('#goPrivateImage').removeClass('noDisplay');
			$('#peekPrivateImage').removeClass('noDisplay');
			$('.jamMain').fadeTo('fast', 1);
//			endPrivate();
		break;
	}
}

function submitChat(e) {
//	if(window.chatTimeOut) clearTimeout(chatTimeOut);
	text = e.text.value;
	cId = e.chatId.value;
	if(text == '') return false;
	e.text.value = '';
	if(!jqE.postMessage) jqE.postMessage = new Array;
	jqE.postMessage.push(text);
}

function getChat(first, result) {
	form = document.getElementById('chatForm');
	chatDiv = document.getElementById('chat');
	chatId = document.getElementById('chatId').value;
	var swf = document.getElementById("APP");
	time = (window.chatRefreshed ? chatRefreshed : '');
	lastId = (window.lastId ? lastId : '');

	if(!result) return false;

	htmlChat = '';

	$.each(result.chat, function(mid, r) {
		if(result.online && r[3] == 1) {
			// tip or special msg recieved
			soundManager.play('newTip');
		}
		if(r[4] == chatId) r[3] = 'P';
		htmlChat += '<div class="t' + r[3] + '"><a onclick="writeNick(\'' + r[0] + '\')">' + r[0] + '</a>: ' + r[1] + '</div>\n';
	});
	
	if(result.online) {
		htmlOnline = '';
		htmlGuests = '';
		curOnline = new Array();

		$.each(result.online, function(mid, r) {
			if(r[0] == chatId) r[2] = 'P';
			string = '<div class="t' + r[2] + '"><a onclick="muteUser(\'' + r[0] + '\')">' + r[0] + '</a> <small>$ ' + r[1] + '</small></div>';
			if(!r[0].match(/^guest([0-9]+)/)) {
				htmlOnline += string;
//				if(r[1] > 0 && r[0] != chatId) 
				curOnline[curOnline.length] = r[0];
			} else {
				htmlGuests += string;
			}
		});

//		console.log("CurOnline:" + curOnline.length + ". myPrev: " + myPrevOnline.length);
		if(curOnline.length > myPrevOnline.length) {
			// new member in room
//			console.log("CurOnline > myPrev. Newmember sound!");
			soundManager.play('newMember');
		}
		myPrevOnline = curOnline;

		$('#chatOnline').html(htmlOnline + '<hr size="1"><br/>' + htmlGuests);
		if(myAccess != result['inP'] && result['access'] == 2) {
			$('#myStatus').val('private');
			soundManager.play('jamStart');
			if(swf) cameraUpdate();
			htmlChat += '<div class="tP"><b>Private started!</b></div>';
			$('#smplHead').toggleClass('smplHeadPrv');
		} else if(myAccess != result['inP'] && result['access'] == 0) {
			soundManager.play('jamEnd');
			$('#myStatus').val('online');
			if(swf) cameraUpdate();
			htmlChat += '<div class="tP"><b>Private ended!</b></div>';
			$('#smplHead').toggleClass('smplHeadPrv');
	}
		myAccess = result['inP'];
	}

	$('#chat').append(htmlChat);

//	chatDiv.scrollTop = chatDiv.scrollHeight;
	if(first) {chatDiv.scrollTop = chatDiv.scrollHeight;}
	else {divScroll.activeScroll();}
	
	chatRefreshed = result.time;
	lastId = result.lastId;
	jqE['getChat']['lastId'] = lastId;
	jqE['getChat']['time'] = chatRefreshed;
}

function addSmile(smile) {
	curVal = $('#chatInput').val();
	$('#chatInput').val(curVal + '' + smile);
	$('#chatInput').focus();
}

function writeNick(nick) {
	$('#chatInput').val(nick + ': ');
	$('#chatInput').focus();
}

function showSmileList() {
	var pos = $("#smilesListImg").offset();
	var width = $("#smilesListImg").width();
	$("#blockSmileList").css( { "left": (pos.left - 160) + "px", "top":pos.top + "px" } );
	if($('#blockSmileList').css('display') == 'none') $('#blockSmileList').show('fast');
	else $('#blockSmileList').hide();
}

function payLink(e) {
	form = document.getElementById('payForm');
	form.credit_value.value = e;
	form.submit();
}

function updateProfile() {
	ee = document.getElementById('profileForm');
	var info = new Array(ee.name.value, ee.lastname.value, ee.street.value, ee.city.value, ee.zip.value, ee.state.value, ee.country.value);
	JsHttpRequest.query(
		"/includes/jsUserEngine.php",
		{ action: 'updateProfile', info: info},
		function(result, errors) {
			if(errors == '') alert('Page info updated!');
			else alert(errors);
		},
		false
	);
}


function jamLogin() {
	e = document.forms.loginForm;
	error = '';
	user = e.user.value;
	pass = e.password.value;
	if(user == '') error += '- Username not specified';
	if(pass == '') error += '- Password not specified';
	if(error == '') e.submit();
	else return false;
}

function checkLoginEnter() {
	if (window.event && window.event.keyCode == 13) {
		jamLogin();
	} else {
//		alert('not enter');
	}
}

function changePassDiv() {
	div1 = document.getElementById('passFormDiv');
	div2 = document.getElementById('passFormDivInput');
	if(div1.style.display == 'block') {
		div1.style.display = 'none';
		div2.style.display = 'block';
	} else {
		div1.style.display = 'block';
		div2.style.display = 'none';
	}
}


function changePassword(ee) {
	form = ee.form;
	error = '';
	pass = form.password.value;
	passChk = form.passwordConfirm.value;
	if(pass == '') error += '- Password is empty\n';
	if(pass != passChk) error += '- Passwords does not match\n';
	if(error != '') {
		alert('Following errors occured: \n' + error);
		return false;
	}
	md5pass = hex_md5(pass);
	JsHttpRequest.query(
		"/includes/jsUserEngine.php",
		{ action: 'changePass', pass: md5pass},
		function(result, errors) {
			alert('Password changed!');
		},
		false
	);
}

function checkAvail(user) {
	if(user == '') return;
	JsHttpRequest.query(
		"/includes/jsUserEngine.php",
		{ action: 'checkUser', user: user },
		function(result, errors) {
			document.getElementById('joinForm').user.style.color = (result ? 'red' : 'green');
		},
		false
	);
}

function checkEmail(email) {
	if(email == '') return;
	document.getElementById('joinForm').email.style.color = (!email.match(/([a-z0-9._-]+@[a-z0-9._-]+\.[a-z.]+)/i) ? 'red' : 'green');
}

function checkSubmitForm(ee) {
	form = ee.form;
	error = '';
	user = form.user.value;
	pass = form.password.value;
	passChk = form.passwordConfirm.value;
	email = form.email.value;
	if(user == '') error += '- Username is empty\n';
	if(form.user.style.color == 'red') error += '- Username is taken\n';
	if(pass == '') error += '- Password is empty\n';
	if(pass != passChk) error += '- Passwords does not match\n';
	if(email == '') error += '- Email not entered\n';
	if(email != '' && !email.match(/([a-z0-9._-]+@[a-z0-9._-]+\.[a-z.]+)/i)) error += '- Email format not valid\n';
	if(error != '') {
		alert('Following errors occured: \n' + error);
		return false;
	}
	form.submit();
	return true;
}

function checkEnter(ee) {
	if (window.event && window.event.keyCode == 13) return checkSubmitForm(ee);
  else
    return true;
}

function toggleBlock(blockId) {
	document.getElementById(blockId).style.display = (document.getElementById(blockId).style.display == 'block' ? 'none' : 'block');
}

function toggleRateBlock(w) {
	document.getElementById('cameraActRating').style.display = (w == 'on' ? 'block' : 'none');
	document.getElementById('cameraActButtons').style.display = (w == 'on' ? 'none' : 'block');
}

function cameraUpdate() {
  var swf = document.getElementById("APP");
  if(swf) swf.sendToActionScript();
}

function jamRate(cId, rate) {
	JsHttpRequest.query(
		"/includes/jsUserEngine.php",
		{ action: 'rateCam', cId: cId, rate: rate },
		function(result, errors) {
			if(errors == '') alert("Voted successfully!");
			else alert('You already voted for this performer!\nVote changed to ' + rate + '.');
		},
		false
	);
	toggleRateBlock('off');
}

function goPrivate() {
	jqE['goPrivate'] = true;
	$('.jamMain').fadeTo('slow', 0.1);
	$('#goPrivateImage').addClass('noDisplay');
	$('#peekPrivateImage').addClass('noDisplay');
	$('#endPrivateImage').removeClass('noDisplay');
	messageBox('Going private...');
//	userBalance(result['balance']);
//	if(confirm('Balance is empty.\nWould you like to add some funds?')) window.location = '/account/';
}

function endPrivate() {
	jqE['endPrivate'] = true;
	messageBox('Ending private...');
}

function giveATip() {
//	cId = $('#chatId').val();
	tip = $('#makeTipSize').val();
	if(cId) {
		jqE['giveATip'] = tip;
	}
	$('#cameraBlockTips').hide();
	$('#cameraBlockTip').show();
}

function messageBox(text) {
	if(text) {
		$('#messageBox').show();
		$('#messageBox p').html(text);
	} else {
		$('#messageBox').hide();
		$('#messageBox p').html();
	}
}

function userBalance(b) {
	bStr = '$' + b;
	if($('#userBalance').text() == bStr) return false;
	$('#userBalance').html(bStr);
	return true;
/*	$('#userBalance').hide('slow', function() {
		$('#userBalance').html(bStr);
		$('#userBalance').show('slow');
	});*/
}

// Scrolling
	var chatscroll = new Object();

	  chatscroll.Pane = function(scrollContainerId){
	    this.bottomThreshold = 20;
	    this.scrollContainerId = scrollContainerId;
	    this._lastScrollPosition = 100000000;
	  }
	
	  chatscroll.Pane.prototype.activeScroll = function(){
	
	    var _ref = this;
	    var scrollDiv = document.getElementById(this.scrollContainerId);
	    var currentHeight = 0;
	    
	    var _getElementHeight = function(){
	      var intHt = 0;
	      if(scrollDiv.style.pixelHeight)intHt = scrollDiv.style.pixelHeight;
	      else intHt = scrollDiv.offsetHeight;
	      return parseInt(intHt);
	    }
	
	    var _hasUserScrolled = function(){
	      if(_ref._lastScrollPosition == scrollDiv.scrollTop || _ref._lastScrollPosition == null){
	        return false;
	      }
	      return true;
	    }
	
	    var _scrollIfInZone = function(){
	      if( !_hasUserScrolled || 
	          (currentHeight - scrollDiv.scrollTop - _getElementHeight() <= _ref.bottomThreshold)){
	          scrollDiv.scrollTop = currentHeight;
	          _ref._isUserActive = false;
	      }
	    }
	
	
	    if (scrollDiv.scrollHeight > 0)currentHeight = scrollDiv.scrollHeight;
	    else if(scrollDiv.offsetHeight > 0)currentHeight = scrollDiv.offsetHeight;
	
	    _scrollIfInZone();
	
	    _ref = null;
	    scrollDiv = null;
	
	  }


//////////////////// Ratings /////////////////////////////
// Variables
var ratings_mouseover_image = new Image();
ratings_mouseover_image.src = "/static/images/starOn.png";

var cam_id = 0;
var cam_rating = 0;
var is_being_rated = false;
var ratings_max = 5;

function current_rating(id, rating) {
	if(!is_being_rated) {
		cam_id = id;
		cam_rating = rating;
			for(i = 1; i <= rating; i++) {
				document.images['rating_' + cam_id + '_' + i].src = eval("ratings_mouseover_image.src");
			}
	}
}

function ratings_off(rating_score) {
	if(!is_being_rated) {
		for(i = 1; i <= ratings_max; i++) {
			if(i <= rating_score) {
				document.images['rating_' + cam_id + '_' + i].src = '/static/images/starOn.png';
			} else {
				document.images['rating_' + cam_id + '_' + i].src = '/static/images/starOff.png';
			}
		}
	}
}

function write_stars (cam, score) {
	var out = '';
	for (i=1; i<= ratings_max; i++) {
	     if (i<=score) { state='On'; } else { state='Off'; }
	     out = out + '<img id="rating_'+cam+'_'+i+'" src="/static/images/star'+state+'.png" onmouseover="current_rating(\''+cam+'\', \''+i+'\');" onmouseout="ratings_off(\''+score+'\');" onclick="jamRate('+cam+', '+i+');" />\n';
	}
	return (out);
}
