var online_stream_check_time = 10000;
var user_check_time =  10000;
var model_check_time = 5000;
var chat_update_time = 2500;

/* utility functions */
function control_in(control, text){ if (text == control.value) control.value = ''; }
function control_out(control, text){ if ('' == control.value) control.value = text;}

function notice(text)
{
	$('#notice').html('~ ' + text + ' ~').removeClass('error').css('display', '');
	setTimeout("$('#notice').fadeOut();", 5000);
}

function notice_error(text)
{
	$('#notice').html('~ ' + text + ' ~').addClass('error').css('display', '');
	setTimeout("$('#notice').fadeOut();", 5000);
}

function notice_error_clear()
{
	$('#notice').html('').css('display', 'none');
	
}

function init_notice()
{
	if ($('#notice').html() && $('#notice').html().length > 0)
	{
		setTimeout("$('#notice').fadeOut();", 5000);
	}
	if ($('#notice').html() && $('#notice').html().length > 0)
	{
		setTimeout("$('#notice').fadeOut();", 5000);
	}	
}

function strip_tags(tags) 
{
  return tags.replace(/\</g, '').replace(/\>/g, ''); 
}


/* AJAX functions */

function post(form, selector, data_selector, success_function) 
{
	data_selector = data_selector || form;
	
	$.post( 
		$(form).attr('action'), 
		$(data_selector).serialize(), 
		function(data){ 
			$(selector).html(data); 
			
			var noticetext = $(selector+'notice');
			var noticeerror = $(selector+'error');
			
			if(null != noticetext && null != noticetext.html() && "" != noticetext.html()) notice(noticetext.html()); 
			if(null != noticeerror && null != noticeerror.html() && "" != noticeerror.html()) notice_error(noticeerror.html()); 
			
			if (success_function) success_function();
		}
	);
	return false;
}

function flag(model)
{
	$.ajax({
		url: "/profile/flag/model/" + model + "/flag/" + $('#flag').val(),
		success: function(data)
		{
			$('.flag-area').html(data);
		}
	});

	return false;
}

function bio_open()
{
	if ($('.bio-photos').hasClass('open'))
	{		
		$('.bio-photos').animate({left:"388px"}, 700, "linear", function(){$('.bio-photos').removeClass('open');});
		$('.bio-photos').css('height', '550px');
	}
	else
	{
		if ($('.bio-photos').height() < $('.bio-params').height())
		{
			$('.bio-photos').css('height', $('.bio-params').height() + 'px')
		}
	
		$('.bio-photos').addClass('open');
		$('.bio-photos').animate({left:"35px"}, {duration: 700})
	}
}


function message_send(model, text)
{
	if (0 == text.length)
		return false;
	 	
	$.ajax({
		type: 'POST',

		url: '/messages/add/model/' + model,
		data: { data: encodeURI(text) },
		success: function(data)
		{
			$('.bio-messages ul').prepend(data);
			$('#bio-messages-up').addClass('enabled');
			$('#bio-messages-down').addClass('enabled');
		}		
	});
	
	return false;
}

rating = function()
{

	$('.rating a').click(function(){
		$('.rating a').unbind('click');
		
		v = this.className.replace('r', '');
		
		$.ajax({
			url: '/profile/rate/model/' + model + '/v/' + v,		
			success: function(data)
			{
				$('.rating').html(data);			
				$('.rating').addClass('stop');
			}
		});
	});
	$('.rating.stop a').unbind('click');
}

function scroll_column_vertical(elem, dx, maxheight)
{
	elem_top = parseInt($(elem).css('top').replace('px', ''));
			
	if(dx < 0)
	{
		
		if (Math.abs(elem_top + dx) < ($(elem).height() - maxheight))
		{
			$(elem).stop().animate({top: elem_top + dx + 'px'}, 500);
		}
		else
		{
			if (Math.abs(elem_top) < ($(elem).height() - maxheight))
				$(elem).stop().animate({top: - $(elem).height() + maxheight + 'px'}, 500);
		}
	}
	else
	{
		if ((elem_top + dx) < 0 )
			$(elem).stop().animate({top: elem_top + dx + 'px'}, 500);	
		else
		{
			if (elem_top < 0 )
				$(elem).stop().animate({top: '0px'}, 500);	
		}
	}
}

function scroll_column_horizontal(elem, dx, maxwidth)
{
	elem_left = parseInt($(elem).css('left').replace('px', ''));

	if(dx < 0)
	{		
		if (Math.abs(elem_left + dx) < ($(elem).width() - maxwidth))
		{
			$(elem).stop().animate({left: elem_left + dx + 'px'}, 500);
		}
		else
		{
			if (Math.abs(elem_left) < ($(elem).width() - maxwidth))
				$(elem).stop().animate({left: - $(elem).width() + maxwidth + 'px'}, 500);
		}
	}
	else
	{
		if ((elem_left + dx) < 0 )
			$(elem).stop().animate({left: elem_left + dx + 'px'}, 500);	
		else
		{
			if (elem_left < 0 )
				$(elem).stop().animate({left: '0px'}, 500);	
		}
	}
}

function control_limit(control, countdown, maxlimit)
{	
	if ($(control).val().length > maxlimit)
		$(control).val($(control).val().substring(0, maxlimit));
	else
		$('#' + countdown).html((maxlimit - $(control).val().length) + ' symbols left');
} 

function perfomer_payment_type()
{
	if (1 == $('#payment_type').val())
	{
		$('.ps-info-right').css('display', 'none');
		$('.ps-edit-right').css('display', 'none');
	}
	else
	{
		$('.ps-info-right').css('display', '');
		$('.ps-edit-right').css('display', '');
	}
}

/* broadcast functions */

var online_stream_ready_count = 0;

function online_stream_ready()
{
	$.ajax({
		type: 'POST',
		url: "/index/checkstream/?id=" + online_check_name +"&t=" + Math.random(),
		success: function(data)
		{
			if (1 == data)
			{
				swf();
				init_time();
			}
			else
			{
				if (online_stream_ready_count < 5)
				{
					setTimeout("online_stream_ready()", online_stream_check_time);
					online_stream_ready_count = online_stream_ready_count + 1;
				}
				else
				{
					$('#video-player h3').html('sorry model is not available');
				}
			}
		}
	});
}

function user_check()
{
	$.ajax({
		type: 'POST',	
		url: "/service/status.php?model=" + online_model_id +"&t=" + Math.random(),
		dataType: "json",				
		success: function(data)
		{
			try {
				if (onlinestatus != data['model_status'])
				{
					window.location = "/wait/" + online_model; 
					return;
				}
				
			} catch(e) {}
			
			setTimeout("user_check()", user_check_time);

		}
	});
}

function model_check()
{
	$.ajax({
		type: 'POST',	
		url: "/service/status.php?model=" + online_model_id +"&t=" + Math.random(),
		dataType: "json",		
		success: function(data)
		{
			try {
				var members = 'members';
				if (1 == data['user_count']) members = 'member';
				
				$('#user-count').html(data['user_count'] + ' ' + members);
				$('#user-count').parent().show();
				
				if (0 == data['user_count']) $('#private-user').html('<b>0 members</b> in this chat');
				if (1 == data['user_count']) $('#private-user').html('<b>' + data.users[0].display_name + '</b> with You in this chat');

				
				ids = new Array();
				for (var i in data.users) 
				{
					ids.push('user_' + data.users[i].id); 
					if(!document.getElementById('user_' + data.users[i].id)) 
					{
						$('#user-bar-scroll').append('<div class="avatar" id="user_' + data.users[i].id + '"><img alt="' + data.users[i].display_name + '" src="' + data.users[i].pic + '"/><span>' + data.users[i].display_name + '</span></div>');
					}
				}
				
				$('#user-bar-scroll').find("div.avatar").each(function () { 
					if ("" != $(this).attr('id'))
					{
						var is = false;
						for (var j in ids) 
						{ 
							if ( (ids[j]) == $(this).attr('id') ) is = true; 
						}
						if (!is) 
						{
							$(this).detach();						
						}
					}
				});
				
				if ((onlinestatus != data['model_status']) && (data['model_status'] > onlinestatus))
				{
					switch(data['model_status'])
					{
						case '2': window.location = "/broadcast/pay"; break;
						case '3': window.location = "/broadcast/private"; break;
					}
				}
			} catch(e) {}
			
			setTimeout("model_check()", model_check_time);
						
		}
	});		
}

/* self init functions */

function init_favorite()
{
	$('.to-favorites').click(function(){
		if (0 == $(this).attr('rel').length)
		{
			window.location = '/login';
			return false;
		}
		
		if ($(this).hasClass('from'))
		{
			$(this).removeClass('from');
			$.ajax({url: '/favorites/remove/model/' + $(this).attr('rel')});			
		}
		else
		{
			$(this).addClass('from');
			$.ajax({url: '/favorites/add/model/' + $(this).attr('rel')});			
		}
	});
	
	$('.favorite-remove').click(function(){
		if (confirm('This will remove model from your favorites')) 
		{
			$.ajax({url: '/favorites/remove/model/' + $(this).attr('rel')});			
			$('#favcount').html($('favorite-item').length);
			$(this.parentNode).detach();
			
		}
	});

}

function init_lists()
{
	$('#month').bind('change', function(event) {
		var value = "";
		$(this).find("option:selected").each(function () { value = $(this).attr('value') + " "; });		
		value = value.split(',');
		var month = value[0];
		var year = value[1];
		
		$.ajax({
			url: $('#month_ajax_url').attr('href') + month + '/' + year,
			success: function(data)
			{	
				$('#list-data').html(data);
				$('tr.total').hide();
				$('#totalfor'+month+year).show();
			}
		});		
	});	
};

var chat_last_id = 0;

function chat_add(result, id, text, login, type)
{	
	if ($('#p' + id).size() > 0)
		return result;
		
	type = type + '';
					
	switch(type)
	{
		case '1': result = result + '<p id="p' + id + '"><i>You</i>: ' +  text + '</p>'; break;
		case '2': result = result + '<p id="p' + id + '"><b>' + login + '</b>: ' +  text + '</p>'; break;
		default:
			result = result + '<p id="p' + id + '" class="other">' + login + ': ' +  text + '</p>'; break;
	}
		
	return result;
}

function chat_update()
{
	$.ajax({
		type: 'POST',
		url: '/service/chat.php?room=' + online_model_id + '&type=' + onlinestatus + '&last_id=' + chat_last_id +'&t=' + Math.random(),
		dataType: "json", 
		success: function(messages)
		{
			try {
				result = '';
				
				for (var key in messages)
				{
					result = chat_add(result, key, messages[key].d, messages[key].l, messages[key].t);
					
					if (key > chat_last_id)
						chat_last_id = key;
				}
				
				if (result)
				{
					$('#chat-content').append($(result));
					$("#chat-slider").slider('value', '0');
				}
			} catch(e) {}
			
			setTimeout("chat_update()", chat_update_time);

		}
	});

}

function init_chat()
{
	if (0 == $("#chat-slider").size())
		return;
		
	// init chat scroll	
	function handleSliderChange(e, ui)
	{
	  var maxScroll = $("#chat-frame").attr("scrollHeight") - $("#chat-frame").height();
	  $("#chat-frame").animate({scrollTop: (100 - ui.value) *	 (maxScroll / 100) }, 1000);
	}

	function handleSliderSlide(e, ui)
	{
	  var maxScroll = $("#chat-frame").attr("scrollHeight") - $("#chat-frame").height();

	  $("#chat-frame").attr({scrollTop: (100 - ui.value) * (maxScroll / 100) });
	}

	$("#chat-slider").slider({
		orientation: 'vertical',
		animate: true,
		change: handleSliderChange,
		slide: handleSliderSlide,
		value: 100
	});
	
	// init chat form
	$('.chat-input a').click(function()
	{
		v = $('#chat-text').val();
		
		if(v)
		{		
			$.ajax({
				type: 'POST',
				url: '/chat/add',
				data: { data: v, room: online_model_id, type: onlinestatus},
				success: function(data){
					if (data > 0)
					{
						$('#chat-content').append($(chat_add('', data, v, '', 1)));				
						$("#chat-slider").slider('value', '0');
					}
					else
					{
						$('#chat-content').append($(chat_add('', data, "message didn't recorded " + v, '', 1)));				
						$("#chat-slider").slider('value', '0');					
					}
				}
			});						
		}
		
		$('#chat-text').val('');
	});
	
	$('.chat-input input').keypress(function(event) {
		if ('13' == event.keyCode) 
		{
			$('.chat-input a').click();
		}
	});

	// init chat update	
	chat_update();	
}

function init_tabs()
{
	// init tabs
	$('.tabs a').click(function()
	{
		$('.tab').css('display', 'none');
		$('.tabs li').removeClass('selected');
			
		$('#' + $(this).attr('id') + 'data').css('display', '');
		$(this.parentNode).addClass('selected');
		
		return false;
	});
}

var start_time;

function update_time()
{
	minutes = Math.floor(((new Date()).getTime() - start_time) / 60000);
	
	hours   = Math.floor(minutes / 60);
	minutes = minutes - hours * 60;
	
	if (minutes < 10)
	{
		minutes = '0' + minutes;
	}
	
	$('#time').html(hours + ':' + minutes);
	
	setTimeout("update_time()", 1000);
}

function init_time()
{	
	start_time = (new Date()).getTime(); 
	
	setTimeout("update_time()", 1000);
}

function init_home()
{
	$('.pagination a').click(function()
	{
		elem = $(this);
	
		if ($(this).hasClass('more'))
		{
			elem = $(this.parentNode).find('.selected').next();
			
			if (elem.hasClass('more'))
				return;
		}
		
		elem.parent().parent().parent().find('.home-page').css('display', 'none');
		elem.parent().find('a').removeClass('selected');
			
		$('#' + elem.attr('rel')).fadeIn();
		elem.addClass('selected');
	});
	
	$('.mi-popup').click(function(e)
	{	
		if ('A' == e.target.tagName && 'more' != e.target.className)
		{
			window.location = $(e.target).attr('href');
		}
		else
		{		
			window.location = $(this).find('.more').attr('href');
		}
		
		return false;
	});
	
	$('#follow-us-left').bind('click',function(event){
		scroll_column_horizontal(document.getElementById('follow-us-data'), 58, 315);
		
		
		event.preventDefault();
	});
	
	$('#follow-us-right').bind('click',function(event){
		scroll_column_horizontal(document.getElementById('follow-us-data'), -58, 315);
		
		event.preventDefault();
	});	
	
}
function init_bio_info()
{

	$('#bio-messages-up').bind('click',function(event){
		scroll_column_vertical(document.getElementById('bio-messages-data'), 100, 270);
		
		event.preventDefault();
	});
	
	$('#bio-messages-down').bind('click',function(event){
		scroll_column_vertical(document.getElementById('bio-messages-data'), -100, 270);
		
		event.preventDefault();
	});	
	
	$('#bio-share-left').bind('click',function(event){		
		scroll_column_horizontal(document.getElementById('bio-share-data'), 100, 460);
		
		event.preventDefault();
	});
	
	$('#bio-share-right').bind('click',function(event){
		scroll_column_horizontal(document.getElementById('bio-share-data'), -100, 460);
		
		event.preventDefault();
	});	
}

function init_user_bar()
{
	$('#user-bar-left').bind('click',function(event) {

		scroll_column_horizontal(document.getElementById('user-bar-scroll'), 195, 910);
		
		
		event.preventDefault();
	});
	
	$('#user-bar-right').bind('click',function(event) {

		scroll_column_horizontal(document.getElementById('user-bar-scroll'), -195, 910);
		
		event.preventDefault();
	});	
}


	
function init_search() {
	$('.search-form select').bind('change', function(event) {
		if ("Search.." == $('#search_text').attr('value')) $('#search_text').attr('value','');
		post('#extsearch', '#search-data'); return false; 
	});
}

function init_master() {
	$('#online_stream_check_time').html(online_stream_check_time/1000 + ' seconds');
	$('#user_check_time').html(user_check_time/1000 + ' seconds');
	$('#model_check_time').html(model_check_time/1000 + ' seconds');
	$('#chat_update_time').html(chat_update_time/1000 + ' seconds');
}

function check_access( url ) {

	switch( url )
	{
		case '/performer/finances': 
			if (undefined !== onlinestatus && 0 != onlinestatus)  
			{
				notice('Available when you are not in chat');
				return false;
			}
			else return true;
			break;
		default: break;
	}

	return true;
}

/* callbacks*/

function photo_callback ( ) {
	if('selected' == $('#tab2').parent().attr('class')) 
	{
		$('#upload').hide();
		$('#webcam-btns').show(); 
	} else if (avatar = $('#avatar')) 
	{
		$('#upload-container').hide();
		$('#avatar-edit').toggleClass('refresh-avatar');
	}
}

function webcam_callback ( ) {
	$('#webcam').hide();
	$('#webcam-btns').show(); 
}

/* document ready */
$(document).ready(function() {
	// notice
	$('#notice').click(function(){
		$(this).css('display', 'none');
	});
	
	// init favorite
	init_favorite();
		
	// 
	init_tabs();
	
	// TODO move from here
	init_lists();
	
	init_notice();
	
	// initlightbox
	$("a[rel|=show]").lightbox({loopImages: true, fitToScreen: true, borderSize:50, vertBorderSize:10});

	init_search();

});
