var timeout;
var freeTimeout;
var timeoutTime = 2*60*1000;
 
$(document).ready(function(){
	timeout = setTimeout('refreshCams()', timeoutTime);
	freeTimeout = setTimeout('refreshFreeCams()', timeoutTime + 2000);
	getFavorites('Y');
	$('.Navigation').click(function(){
		$('.Navigation').each(function(index){
			$(this).removeClass('active');
		});
		$(this).addClass('active');
	});
	
	$('.mouse_over').live('mouseover', function(){
		var parent = $(this);
		var type = '';
		$('#mouse_overs div').each(function(index){
			type = $(this).attr('id').substring(4);
			if($(parent).hasClass(type))
				return false;				
		});
		
		$("#tip_"+type).css({'display': 'block',
					'position': 'absolute'});
		$('.mouse_over').mousemove(function(e){
			$("#tip_"+type).css({'left': (e.pageX + 20),
								'top': (e.pageY + 10)});
		})
	});
	$('.mouse_over').live('mouseout click', function(){
		$('.tip').css('display', 'none');
	});	
	
	$('#Language_Change').change(function()
			{  window.location = '/index.php?lang='+$(this).attr('value');	});
});

function refreshCams(){
	$.post('/ajax/gateway.php', 
			{task: 'refreshCams'}, 
			function(data){
				$('#PreviewsWrap').replaceWith(data);
				timeout = setTimeout('refreshCams()', timeoutTime);
			}
	);
}

function refreshFreeCams(){
	$.post('/ajax/gateway.php', 
			{task: 'refreshFreeCams'}, 
			function(data){
				$('#FreePreviewsWrap').replaceWith(data);
				freeTimeout = setTimeout('refreshFreeCams()', timeoutTime);
			}
	);
}

function changePage(page, type){
	$.post('/ajax/gateway.php', 
			{page: page,
			type: type,
			task: 'setPage'}, 
			function(data){
				if(data != 'inactive'){
					if(type == 'cams'){
						clearTimeout(timeout);
						timeout = setTimeout('refreshCams()', timeoutTime);
						$('#PreviewsWrap').replaceWith(data);
					}
					else if(type == 'favorites'){
						getFavorites('P');
					}
					else if(type == 'free'){
						clearTimeout(freeTimeout);
						freeTimeout = setTimeout('refreshFreeCams()', timeoutTime);
						$('#FreePreviewsWrap').replaceWith(data);
					}
				}
			}
	);
}

function setOption(type, option){
	option = option.replace('*','\\*'); 
	
	if($('#'+option).hasClass('active'))
		$('#'+option).removeClass('active');
	else
		$('#'+option).addClass('active');
	
	$('input[name=search]').val('');
	var options = new Array();
	options[0] = new Array('nickname', '');
	var counter = 1;
	$('.category').each(function(index){
		options[counter] = new Array();
		options[counter][0] = $(this).children('div').attr('id');
		$(this).children('ul').children('li').each(function(index){
			if($(this).hasClass('active')){
				if(typeof options[counter][1] != 'undefined')
					options[counter][1] += '-' + $(this).attr('id');
				else
					options[counter][1] = $(this).attr('id');
			}
		})
		counter++;
	});
	
	saveOptions(options);
}

function setSex(option){
	$('input[name=search]').val('');	
	var options = new Array();
	options[1] = new Array('nickname', '');
	options[0] = new Array('sex', option);
	saveOptions(options);
}

function searchNickname(){
	var nickname = $('input[name=search]').val();
	var options = new Array();
	options[0] = new Array('nickname', nickname);
	saveOptions(options);
}

function resetOptions(){
	$('input[name=search]').val('');
	var options = new Array();
	options[0] = new Array('nickname', '');
	saveOptions(options);
}

function saveOptions(options){
	$.post('/ajax/gateway.php', 
			{'gw_options[]':options,
			task: 'setOptions'}, 
			function(data){
				clearTimeout(timeout);
				timeout = setTimeout('refreshCams()', timeoutTime);
				$('#PreviewsWrap').replaceWith(data);				
			}
	);	
}

function openProfile(account){
	if(account != ''){
		$.post('/ajax/gateway.php', 
				{account:account,
				task: 'getProfile'}, 
				function(data){
					if($('#SearchWrap').next().attr('id') != 'ProfileWrap')
						$(data).insertAfter('#SearchWrap');
					else
						$('#ProfileWrap').replaceWith(data);
					
					targetOffset = $('#ProfileWrap').offset().top;
					$('html,body').animate({scrollTop: targetOffset-15}, 1000);
					$("a[rel=model_gallery]").fancybox({
						'transitionIn'		: 'none',
						'transitionOut'		: 'none',
						'titlePosition' 	: 'over',
						'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
							return '<span id="fancybox-title-over">Afbeelding ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
						}
					});
				}
		);
	}
}

function showScoreStars(score) {
	var flashvars = {};
	var params = { wmode: "transparent", quality: "high", lang: "EN", score: score };
	var attributes = { score : score };
	swfobject.embedSWF("/swf/evaluations.swf?score="+score, "score_flash", "62", "16", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
}

function startChat(url, pay_type, account){
	/*if(pay_type == 'free'){
		if(checkAccessToken() == 'ntok'){
			openLoginPopup(account);
			return false;
		}
	}*/
	width = screen.width;
	params  = 'width=' + width;
	params += ', height='+screen.height;
	params += ', top=0, left=0'
	params += ', fullscreen=yes';
	params += ', resizable=yes';
	params += ', scrollbars=yes';
	
	newwin=window.open(url,'Freecams', params);
	if (window.focus) {newwin.focus()}	
	return false;
}

function checkAccessToken(){
	var message = 'ntok';
	$.ajax({type: 'POST',
			url: '/ajax/gateway.php', 
			data: 'task=checkAccessToken',
			async: false,
			success: function(data){
				message = data;
			}
	});
	return message;
}

function openLoginPopup(account){
	$.post('/ajax/gateway.php', 
			{service: account,
			task: 'openLoginPopup'}, 
			function(data){
				if($('#mouse_overs').next().attr('id') != 'loginPopupWrapper')
					$(data).insertAfter('#mouse_overs');
				else
					$('#loginPopupWrapper').replaceWith(data);
				$('#loginPopupWrapper').show();
				//$(data).insertAfter('#mouse_overs');		
				/*$('#loginLink').fancybox({
						'titlePosition'		: 'inside',
						'transitionIn'		: 'none',
						'transitionOut'		: 'none'})
						.trigger('click');*/
			}
	);	
}

function doLoginLogic(){
	$.ajax({async: false,
			type: 'POST',
			data: {username: $('input[name=username]').val(),
					password: $('input[name=password]').val(),
					username_new: $('input[name=username_new]').val(),
					email: $('input[name=email]').val(),
					task: 'doLoginLogic'},
			url: '/ajax/gateway.php', 
			success: function(data){
				alert(data);
				$.fancybox.close();
				startChat('http://www.google.be', 'free');
		}
	});
	return false;
}

function getFavorites(init){
	$.getJSON("http://cams.dnxlive.com/webservices/gateway.php?task=getAllPreferences&scope=favorites&jsoncallback=?",
			function(data) {
				if($.isArray(data.favorites)) {
			      var fav_txt = "";
			      jQuery.each(data.favorites, function(i, cammer) {
			        if(fav_txt == "") fav_txt += cammer;
			        else fav_txt += "-" + cammer;
			      });
			      $.post("/ajax/gateway.php", 
			    		  {accounts: fav_txt, 
			    	  		init: init, 
			    	  		task: 'getFavorites'}, 
			    	  		function(data) {
			    	  			if(init != 'Y'){			    	  				
			    	  				$('#PreviewsWrap').replaceWith(data);
			    	  				clearTimeout(timeout);
			    	  			}
			    	  		}
			      );
			    }
			}
	);
}

function addToFavorites(account, profile) {
	if(profile == 'N')
		$("#" + account + ' .Btn_Favorite').replaceWith('<div class="Btn_Favorite mouse_over del_favorite" onclick="removeFromFavorites(\''+ account + '\', \'changeButton\');"><img src="/images/Profile_Fav_Black.png" width="16" height="16" /></div>')
	else
		$("#profileFavorite").replaceWith('<div id="profileFavorite" onclick="removeFromFavorites(\''+ account + '\', \'changeProfileButton\');" class="BtnWrap" style=" float:right; margin:10px 0 0 0;"><div class="BtnLeft BlackLeft" style=" width:30px;"></div> <div class="BtnContent BlackContent" style="width:142px">Favoriet verwijderen</div><div class="BtnRight BlackRemove"></div> </div>')

	//We gaan ook de dnxlive favorieten updaten
	jQuery.getJSON("http://cams.dnxlive.com/webservices/gateway.php?task=addToFavorites&account=" + account + "&jsoncallback=?",
			function(data){
				getFavorites('Y');
			}
	);
	return false;
}

function removeFromFavorites(account, action) {
  //We gaan de snapshot al verwijderen voor we de call doen
  if(action == 'removeSnap') 
	  $("#" + account).remove();
  else if(action == 'changeButton')
	  $("#" + account + ' .Btn_Favorite').replaceWith('<div class="Btn_Favorite mouse_over add_favorite" onclick="addToFavorites(\''+ account + '\', \'N\');"><img src="/images/Profile_Fav.png" width="16" height="16" /></div>')
  else if(action == 'changeProfileButton')
	  $("#profileFavorite").replaceWith('<div id="profileFavorite" onclick="addToFavorites(\''+ account +'\',\'Y\');" class="BtnWrap" style=" float:right; margin:10px 0 0 0;"><div class="BtnLeft BlackLeft" style=" width:30px;"></div> <div class="BtnContent BlackContent" style="width:142px">Favoriet toevoegen</div><div class="BtnRight" style="background:url(/images/Submit/SubmitBtn_03_Favorite_03.png);"></div> </div>')

  //We gaan ook de dnxlive favorieten updaten
  jQuery.getJSON("http://cams.dnxlive.com/webservices/gateway.php?task=removeFromFavorites&account=" + account + "&jsoncallback=?",
	  	function(data){
	  		//na remove gaan we updaten
	  		if(action == 'removeSnap') 
	  			getFavorites('P');
	  		else if(action == 'changeButton')
	  			getFavorites('Y');
		}
  );
  return false;
}

function changeSnapSize(size,type){
	$.post('/ajax/gateway.php', 
			{size:size,
			type: type,
			task: 'changeSnapSize'}, 
			function(data){
				if(type == 'cams'){
					clearTimeout(timeout);
					timeout = setTimeout('refreshCams()', timeoutTime);
					$('#PreviewsWrap').replaceWith(data);
				}
				else if(type == 'favorites'){
					getFavorites('P');
				}
			}
	);
}

function bookmark() {
	title = document.title;
	url = document.location.href;
	if(document.all) window.external.AddFavorite(url, title);
	else if(window.sidebar) window.sidebar.addPanel(title, url, "");
}

/* COUNTDOWN FUNCTIONS */
function getServerTime(){
	var time;
	$.post('/ajax/gateway.php', 
			{task: 'getServerTime'}, 
			function(data){
				time = new Date(data);
			}
	);
	return time;
}

function onCountdownExpiry(){
	$('#freecamsCounter').replaceWith('<div id="FreePreviewsWrap"></div>');
	refreshFreeCams();
}
