$(document).ready(function(){
	$('#signup').submit(function(){ registerUser(); return false; });
	$('#signin').submit(function(){ loginUser(); return false; });
	$('#edit-profile').submit(function(){ editProfile(); return false; });
	$('#change-password').submit(function(){ changePassword(); return false; });
	$('#sendMessageForm').submit(function(){ sendMessage(); return false; });
	
	$('#sifreHatirlatmaFormu').live({submit:function(){ 
		var mail = $('#hatirlat').val().toString();
		if( mail.length > 5 && mail.indexOf('@') != -1 && mail.indexOf('.') != -1){
			sifreHatirlat(mail);
			return false;
		}else{
			alert('Geçerli bir e-posta adresi giriniz.');
			return false;
		}
			return false;
	}});

	$("#mycarousel").jcarousel({
		scroll: 3,
		wrap: 'circular',
		initCallback: mycarousel_initCallback,
		// This tells jCarousel NOT to autobuild prev/next buttons
		buttonNextHTML: null,
		buttonPrevHTML: null
	});


	$("#mycarousel2").jcarousel({
		scroll: 1,
		wrap: 'circular',
		initCallback: mycarousel_initCallback2,
		// This tells jCarousel NOT to autobuild prev/next buttons
		buttonNextHTML: null,
		buttonPrevHTML: null
	});

	$('#hediyeGondermeFormu .gift label').live({
		click : function(){
			$('#hediyeGondermeFormu .gift label').removeClass('active');
			$(this).addClass('active');
			$(this).children('input').attr('checked','checked');
		}
	});

	$('#bt-send-gift').live({
		click : function(){
			hediyeGonder();
			return false;
		}
	});
});



var alertFallback = true;
if (typeof console === "undefined" || typeof console.log === "undefined") {
 console = {};
 if (alertFallback) {
	 console.log = function(msg) {
		  alert(msg);
	 };
 } else {
	 console.log = function() {};
 }
}



function mycarousel_initCallback(carousel) {
	$('#mycarousel-next').bind('click', function() {
		carousel.next();
		return false;
	});

	$('#mycarousel-prev').bind('click', function() {
		carousel.prev();
		return false;
	});
};


function mycarousel_initCallback2(carousel) {
	$('#mycarousel-next2').bind('click', function() {
		carousel.next();
		return false;
	});

	$('#mycarousel-prev2').bind('click', function() {
		carousel.prev();
		return false;
	});
};



function registerUser(){
	var devam = true;
	if( $('input[name=agreeTerms]').is(':checked') ){
		$('#signup').children('.form-row').children('.required').each(function(i){
			var item = $(this);
			if( item.attr('type') == 'checkbox' ){
				if( !item.is(':checked') ){
					alert('Lütfen formu eksiksiz doldurun. 1');
					console.log( item.attr('id') + ' doldurulmadı. 1' );
					devam = false; 
					return false; 
				}
			}else{
				if( item.val() == '' || item.val() == '0' || item.val().length < 1 ){
					alert('Lütfen formu eksiksiz doldurun. 2');
					console.log( item.attr('id') + ' doldurulmadı. 2' );
					devam = false;
					return false;
				}
			}
		});
	} else {  alert('Üye sözleşmesini okumalı ve onaylamalısınız. 22'); devam = false; return false; }
	
	if( devam == true ){
		var data = $('#signup').serialize();
		$('#sbm-signup').hide();
		$.post( rootUrl+'/ajax.php?action=registerForm', data, function(resp){
			console.log( resp );
			if( resp.status == 'ok' ){
				$('#welcome-text').html( resp.message );
				$('#welcome-tabs a').removeClass('active');
				$('#bt-signin').addClass('active');
				$('.section').removeClass('active');
				$('.section:first').addClass('active');
				$('#bt-signup, #signup').remove();
				$('#lnk-signup').css('visibility','hidden');
			}else{
				alert( resp.error );
				$('#sbm-signup').show();

			}
		} );
	}
	return false;
}

function loginUser(){
	var devam = true;
	$('#signin').children('.required').each(function(i){
		var item = $(this);
		if( item.val() == '' || item.val() == '0' || item.val().length < 1 ){
			alert('Formu eksiksiz doldurun.');
			console.log( item.attr('id') + ' doldurulmadı.' );
			devam = false;
			return false;
		}

	});
	
	if( devam == true ){
		var data = $('#signin').serialize();
		console.log(data);
		$.post( rootUrl+'/ajax.php?action=loginForm', data, function(resp){
			console.log( 'response: ',resp );
			if( resp.status == 'ok' ){
				top.location.href = rootUrl;
			}else{
				alert( resp.error );
			}
		} );
	}
	return false;
}

function profileData(id){
	if( id ){ 
		$.post( rootUrl+'/ajax.php?action=profileData', { id : id }, function(resp){
			console.log(resp);
			if ( resp.error ){  $('#profileDiv').html('<div class="error">'+resp.error+'</div>'); }
			else if( resp.status == 'ok' ){
				document.title = resp.data.username+' profili | '+rootTitle;
				var data = '';
				var gender =  strType('gender', resp.data.gender);
				var bodyType =  strType('bodyType', resp.data.bodyType);
				var bodyHeight =  resp.data.bodyHeight + 'm';
				var bodyWeight =  resp.data.bodyWeight + 'kg';
				var hairType =  strType('hairType', resp.data.hairType);
				var hairColor =  strType('hairColor', resp.data.hairColor);
				var eyeColor =  strType('eyeColor', resp.data.eyeColor);
				data = 'Cinsiyet: '+gender+'<br />Vücut tipi: '+bodyType+'<br />Boy: '+bodyHeight+'<br />Kilo: '+bodyWeight+'<br />Saç tipi: '+hairType+'<br />Saç rengi: '+hairColor+'<br />Göz rengi: '+eyeColor+'<br />Resim: '+resp.data.pic;
				data += '<br />Son giriş: '+resp.data.lastLogin+'<br />Rank: '+resp.data.rank;



				$('#profileDiv').html('data geldi<br />'+data);
			}
		});
	}
}

function logout(){
	$.post( rootUrl+'/ajax.php?action=logout', function(resp){
		if (resp.status == 'ok'){
			top.location.href = rootUrl;
		}
	});
}

function strType(a,b){
	if( sysTypes[a][b] ){ return sysTypes[a][b]; }else{ return 'Belirtilmedi'; }
}

function myProfileData(){
	$.post( rootUrl+'/ajax.php?action=myProfileData', function(resp){
		if ( resp.error ){  $('#profileDiv').html('<div class="error">'+resp.error+'</div>'); }
		else if( resp.status == 'ok' ){ 
			currentUser = resp.data;
			console.log('currentUser',currentUser);
		}
	});
}


function objcount(obj) {
	var count = 0;
	for(var prop in obj) {
		if(obj.hasOwnProperty(prop)){ count = count+1; }
	}
	return count;
}

function myProfilePage(){
	if ( objcount(currentUser) > 1 ){
		$('#username').text( currentUser.username );
		$('#email').text( currentUser.mail );
		$('#birthday').text( currentUser.birthday );
		$('#location').text( currentUser.location );
		$('#bodyHeight').text( currentUser.bodyHeight+' m' );
		$('#bodyWeight').text( currentUser.bodyWeight+' kg' );
		$('#bodyType').text( strType('bodyType', currentUser.bodyType) );
		$('#hairType').text( strType('hairType', currentUser.hairType) );
		$('#hairColor').text( strType('hairColor', currentUser.hairColor) );
		$('#eyeColor').text( strType('eyeColor', currentUser.eyeColor) );
		$('#gender').text( strType('gender', currentUser.gender) );
		$('#avatar').html( '<img src="'+currentUser.pic+'" id="pic" style="width:125px; height:125px;">' );
	}else{
		setTimeout(function(){myProfilePage();},100);
	}
}


function myProfileEdit(){
	if ( objcount(currentUser) > 1 ){
		var form = $('#profileUpdateForm');
		form.children('#username').val( currentUser.username );
		form.children('#email').val( currentUser.mail );
		form.children('#birthday').val( currentUser.birthday );
		form.children('#location').val( currentUser.location );
		form.children('#bodyHeight').val( currentUser.bodyHeight );
		form.children('#bodyWeight').val( currentUser.bodyWeight );
		
		form.children('#gender').find('option').each( function(i,v){ 
			if( $(this).val() == currentUser.gender ){ $(this).attr('selected','selected'); return false; }
		});
		form.children('#bodyType').find('option').each( function(i,v){ 
			if( $(this).val() == currentUser.bodyType ){ $(this).attr('selected','selected'); return false; }
		});
		form.children('#hairType').find('option').each( function(i,v){ 
			if( $(this).val() == currentUser.hairType ){ $(this).attr('selected','selected'); return false; }
		});
		form.children('#hairColor').find('option').each( function(i,v){ 
			if( $(this).val() == currentUser.hairColor ){ $(this).attr('selected','selected'); return false; }
		});
		form.children('#eyeColor').find('option').each( function(i,v){ 
			if( $(this).val() == currentUser.eyeColor ){ $(this).attr('selected','selected'); return false; }
		});
		$('#avatar').html( '<img src="'+currentUser.pic+'" id="pic" style="width:125px; height:125px;">' );

	}else{
		setTimeout(function(){myProfileEdit();},100);
	}
}

function editProfile(){
	$('#bt-update').css('visibility','hidden');
	var data = $('#edit-profile').serialize();
	console.log(data);
	$.post( rootUrl+'/ajax.php?action=editProfile', data, function(resp){
		console.log( resp );
		if( resp.status == 'ok' ){
			currentUser = resp.data;
//			myProfileEdit();
			alert( resp.message );
		}else{
			alert( resp.error );
			$('#bt-update').css('visibility','visible');
		}
	} );
	return false;
}
function changePassword(){
	$('#bt-change-pw').css('visibility','hidden');
	var data = $('#change-password').serialize();
	console.log(data);
	$.post( rootUrl+'/ajax.php?action=changePassword', data, function(resp){
		console.log( resp );
		if( resp.status == 'ok' ){
			currentUser = resp.data;
			alert( resp.message );
		}else{
			alert( resp.error );
			$('#bt-change-pw').css('visibility','visible');
		}
	} );
	return false;
}

function newPic(url){
	currentUser.pic = url;
	$('#pic').attr('src', url);
	$('#uploadForm').hide();
};



function follow(id){
	if (id){
		$.post( rootUrl+'/ajax.php?action=follow', {id:id}, function(resp){
			if( resp.status == 'ok' ){
				alert( resp.message );
				$('#profile-actions ul li#subscribe a').attr('onclick', 'unfollow(\''+id+'\'); return false;').text('Takip Etme');
			}else{
				alert( resp.error );
			}
		} );
	}
	
	return false;
}


function unfollow(id){
	if (id){
		$.post( rootUrl+'/ajax.php?action=unfollow', {id:id}, function(resp){
			if( resp.status == 'ok' ){
				alert( resp.message );
				$('#profile-actions ul li#subscribe a').attr('onclick', 'follow(\''+id+'\'); return false;').text('Takip Et');
				$('#followListItem-'+id).remove();
			}else{
				alert( resp.error );
			}
		} );
	}
	
	return false;
}


function ban(id){
	if (id){
		$.post( rootUrl+'/ajax.php?action=ban', {id:id}, function(resp){
			if( resp.status == 'ok' ){
				alert( resp.message );
				$('#profile-actions ul li#block a').attr('onclick', 'unban(\''+id+'\'); return false;').text('Engeli Kaldır');
			}else{
				alert( resp.error );
			}
		} );
	}
	
	return false;
}


function unban(id){
	if (id){
		$.post( rootUrl+'/ajax.php?action=unban', {id:id}, function(resp){
			if( resp.status == 'ok' ){
				alert( resp.message );
				$('#profile-actions ul li#block a').attr('onclick', 'ban(\''+id+'\'); return false;').text('Engelle');
				$('#banLi-'+id).remove();
			}else{
				alert( resp.error );
			}
		} );
	}
	
	return false;
}

function newMessage(id, nick){
	var html = '';
	html += '<div id="overlay">';
	html += '<div class="window-wrap">';
	html += '<div id="send-message" class="window">';
	html += '<a href="#" id="close-window" onclick="(elem=document.getElementById(\'overlay\')).parentNode.removeChild(elem); return false;">İPTAL</a>';
	html += '<h3>YENİ MESAJ</h3>';
	html += '<form action="" method="post" id="sendMessageForm">';
	html += '<div class="entry">';
	html += '<label for="message-to">Alıcı :</label>';
	html += '<input type="text" id="message-to" name="toname" value="'+nick+'" disabled=disabled/>';
	html += '</div>';
	html += '<input type="hidden" name="to" value="'+id+'">';
	html += '<div class="entry">';
	html += '<label for="message">Mesaj :</label>';
	html += '<textarea id="message" name="message" cols="40" rows="4"></textarea>';
	html += '</div>';
	html += '<div class="action">';
	html += '<input type="submit" id="bt-send-message" name="send" value="Mesajı Gönder" onclick="sendMessage(); return false;" />';
	html += '</div>';
	html += '</form>';
	html += '</div>';
	html += '</div>';

	if( !$('div#overlay').length ){
		$('body').append(html);
	}else{
		$('div#overlay').css('display','block');
	}

	document.getElementById('overlay').style.height = document.body.scrollHeight + 'px';
}

function sendMessage(){
	$.post( rootUrl+'/ajax.php?action=sendMessage',  $('#sendMessageForm').serialize() , function(resp){
		if( resp.status == 'ok' ){
			alert( resp.message );
			$('#overlay').remove();
		}else{
			alert( resp.error );
		}
	} );
	
	return false;
}

function sendReply(id, to){
	if( id && to ){
		var msg = $('#post-message').val();

		$.post( rootUrl+'/ajax.php?action=sendMessage',  { message:msg, reply:id, to:to } , function(resp){
			if( resp.status == 'ok' ){
				alert( resp.message );
				top.location.href = rootUrl+"/message.php?id="+id;
			}else{
				alert( resp.error );
			}
		} );
	}
	
	return false;
}

function deleteMessage(id){
	if( id ){
		var ok = confirm("Mesajı silmek istediğinize emin misiniz?");
		if (ok){
			$.post( rootUrl+'/ajax.php?action=deleteMessage',  { id:id } , function(resp){
				if( resp.status == 'ok' ){
					$('#message-'+id).remove();
				}else{
					alert( resp.error );
				}
			} );
		}
		else{
			return false;
		}
	}
}

function deleteAllMessages(id){
	if( !id ){ var id = false; }

	var ok = confirm("Mesajları silmek istediğinize emin misiniz?");
	if (ok){
		$.post( rootUrl+'/ajax.php?action=deleteAllMessages',  { id:id } , function(resp){
			if( resp.status == 'ok' ){
				top.location.href = rootUrl+"/inbox.php";
			}else{
				alert( resp.error );
			}
		} );
	}
	else{
		return false;
	}
}


function giftList(id){
	var html = '';
	html += '<div id="overlay">';
	html += '<div class="window-wrap">';
	html += '<div id="send-gift" class="window">';
	html += '<a href="" id="close-window" onclick="(elem=document.getElementById(\'overlay\')).parentNode.removeChild(elem); return false;">İPTAL</a>';
	html += '<h3>HEDİYE GÖNDER</h3>';
	html += '<form method="post" id="hediyeGondermeFormu">';
	html += '<div class="gift">';

		$.post( rootUrl +"/ajax.php?action=giftList",{id:id},function(resp){
			$.each( resp.data, function(i,e){
				html += '<label><img src="'+rootUrl+'/media/gifts/'+e.picture+'" alt="'+e.name+'" /><strong>'+e.name+'</strong> '+e.price+'<input type="radio" name="gift" value="'+e.id+'" /></label>';
			});
		
			html += '</div>';
			html += '<div class="action">';
			html += '<input type="hidden" name="giftReciever" value="'+id+'" />';
			html += '<input type="submit" id="bt-send-gift" name="send" value="Hediye Gönder" />';
			html += '</div>';
			html += '</form>';
			html += '</div>';
			html += '</div>';
			html += '</div>';
			html += '<script>document.getElementById(\'overlay\').style.height = document.body.scrollHeight + \'px\';</script>';

			$('body').append(html);
		});
}

function hediyeGonder(){
	if( $('#hediyeGondermeFormu .gift label input:checked').length ){
		var alici = $('input[name=giftReciever]').val();
		var hediye = $('#hediyeGondermeFormu .gift label input:checked').val();
		if( alici != '' ){
			$.post(rootUrl+"/ajax.php?action=sendGift", { id:hediye, to:alici }, function(resp){
				if( resp.status == 'ok' ){
					alert( resp.message );
					$('#overlay').remove();
					$('.timer .time-left').text(resp.kalan);
				}else{
					alert( resp.error );
				}
			});
		}
	}
	return false;
}


function sifreHatirlat(mail){
	if( !mail ){
		var html = '<div id="overlay"><div class="window-wrap"><div id="recent-chats" class="window"><a href="" id="close-window" onclick="$(\'#overlay\').remove(); return false;">İPTAL</a>';
		html += '<h3>ŞİFREMİ UNUTTUM</h3><form action="" method="post" id="sifreHatirlatmaFormu"><div class="entry"><label for="hatirlat">E-posta Adresi :</label><input type="text" id="hatirlat" name="hatirlat" />';
		html += '</div><div class="action"><input type="submit" id="bt-send" name="send" value="Sorgula" /></div></form></div></div></div>';
		$('body').append(html);

		setTimeout(function(){
			document.getElementById('overlay').style.height = document.body.scrollHeight + 'px';
		},100);

	}else{
		$('#bt-search').attr('disabled','disabled');
		$.post(rootUrl+'/ajax.php?action=passwordRecovery', { mail:mail }, function(resp){
			if (resp.status == 'ok'){
				$('#sifreHatirlatmaFormu').html('<div style="text-align:center;">Şifreniz eposta adresinize gönderilmiştir.</div>');
				setTimeout(function(){ $('#overlay').remove(); }, 1500);
			}else{
				alert( resp.error );
				$('#bt-search').removeAttr('disabled');
			}
		});
		return false;
	}
}
