/**
 * @author PhuongND <phuongnd@cyworld.vn>
 * Not change if you don't know what you're doing
 */
$(function(){	
	/*$('.chk_btn').click(function(){
		var index = $('.chk_btn').index(this);
		var element = $('.chk_btn').get(index);
		if(element.checked == true) {
			receive(element);
		}
		else {
			stop_receive(element);
		}
	});*/
	
	initFollowEvent();
	initRequestEvent();
	initUnfollowEvent();
	initMobileEvent();
	initUnmobileEvent();
			
	$('.tbl_notice tr').mouseover(function(){
		$(this).attr('class','mouse_over');
//		console.log($('.mouse_over').attr('id'));
	}).mouseout(function(){
		$(this).removeAttr('class');
	});
	$('.tbl_notice_compact tr').mouseover(function(){
		$(this).addClass('mouse_over');
//		console.log($('.mouse_over').attr('id'));
	}).mouseout(function(){
		$(this).removeClass('mouse_over');
	});
	try{
		var options = {};
		options.content = '';
		options.show = {};
		options.show.when = {};
		options.show.when.event = 'mouseover';
		options.hide = {};
		options.hide.delay = 0;
		options.hide.fixed = false;
		options.hide.when = {}
		options.hide.when.event = 'mouseout';
		options.position = {};
		options.position.corner = {};
		options.position.corner.target = 'leftBottom';
		options.position.adjust = {};
		options.position.adjust.x = -139;
		options.style = {};
		options.style.border= 0;
		options.style.width = 176;
		options.style.background = 'transparent';
		options.style.padding = 0;
		options.style.classes = {};
		options.style.classes.content = '';
		
		$('.actions_ico').qtip(options);
		
		$('.actions_ico').click(function(){
			var oSelf= $(this);
			var profileid = oSelf.attr('id');
			var url = $('#selfURL').val();
			var mydata = [{name:'profileid',value:profileid},{name:'grouptype',value:0}];
			var method = 'GET';
		
			if($(this).attr("name")==''){
				oSelf.attr("name","1");				
				oSelf.qtip('api').loadContent(url,mydata,method);
				oSelf.qtip('show');
				oSelf.unbind('mouseover');
				oSelf.unbind('mouseout');
				setTimeout(function(){
					$(document).click(function(){	
						$(document).unbind('click');
						oSelf.qtip('hide');	
						oSelf.attr("name","");					
					});
				},0);
			}else{	
				oSelf.attr("name","");
				oSelf.qtip('api').loadContent(url,mydata,method);
				oSelf.qtip('show');
			}
		});
	}
	catch(e) {
		alert(e);
	}
});


function follow(profileid) {
	var url = $("#subscribe_url").val();
	var token = $("#token").val();
	var ajax = 1;
	var fromaction = $("#fromaction").val();
	var subscribeto = profileid;
	var currentid = $("#currentid").val();
	var ownerid = $("#ownerid").val();
	var mydata = [
	              {name:'token',value:token},
	              {name:'ajax',value:ajax},
	              {name:'fromaction',value:fromaction},
	              {name:'subscribeto',value:subscribeto}
	              ];
	var options = {
					url:url,
					dataType:'xml',
					type:'POST',
					async: false,
					data:mydata,
					success: function(xml){
						var nickname = $('nickname', xml).text();
						var profileid = $('profileid', xml).text();
						var total = $('total',xml).text();
						var follower_count = $('followers',xml).text();
						var message = $('message', xml).text();
						var auto_receive = $('auto_receive',xml).text();
						var mobile_status = $('mobile_status',xml).text();
						var span = document._importNode($('following span',xml).get(0),true);
						var li = $('.profile_function .status_follow');
						var blocked_span = li.find('.block_ico_active');
						var unblock_link = li.find('.unblock_ico');
						var element = $('#follow-'+profileid); 
						
						var display_span = ['subscriptions','subscribers','resultsearch'];
						
//						alert(mobile);
						
						$('#update_via_mobile-' + profileid).html(message);
						if( (fromaction == 'subscriptions' || fromaction == 'subscribers') && currentid == ownerid){
							$('#title').text(total);
							$("#following_number").text(total);
						}
						else if(fromaction == 'showstream'){
							$("#follower_number").text(follower_count);
						}
						
						element.unbind('click');
						if( ( display_span.inArray(fromaction,false) ) ) {
							if(auto_receive == 1) {
								var mobile_span = document._importNode($('mobile span',xml).get(0),true);
								element.replaceWith(mobile_span);
							}
							else {
								var mobile_icon = document._importNode($('mobile mobile_ico a',xml).get(0),true);
								element.replaceWith(mobile_icon);
							}
							
						}
						else {
							if(auto_receive==1) {
								var	mobile = document._importNode($('mobile unmobile_message a',xml).get(0),true);
							}
							else {
								var	mobile = document._importNode($('mobile mobile_message a',xml).get(0),true);
							}
								
							
						}
						initUnfollowEvent();
//						$('.entity_subscribe').remove();
						$('.follow_message').remove();
						blocked_span.remove();
						unblock_link.remove();
						li.append(span);
						li.append(mobile);
						initMobileEvent();
						initUnmobileEvent();
				
					},
					error: function(e){
						console.log(e);
					}
				};
	$.ajax(options);
	
	$('.actions_ico').qtip('hide');
}


function unfollow(profileid) {
	var url = $("#unsubscribe_url").val();
	var token = $("#token").val();
	var ajax = 1;
	var currentid = $("#currentid").val();
	var ownerid = $("#ownerid").val();
	var fromaction = $("#fromaction").val();
	var unsubscribeto = profileid;
	var mydata = [
	              {name:'token',value:token},
	              {name:'ajax',value:ajax},
	              {name:'fromaction',value:fromaction},
	              {name:'unsubscribeto',value:unsubscribeto}
	              ];
	
	var options = {
					url:url,
					dataType:'xml',
					type:'POST',
					async:false,
					data:mydata,
					success: function(xml){
						var protect = $('protect', xml).text();
						var nickname = $('nickname', xml).text();
						var profileid = $('profileid', xml).text();
						var total = $('total',xml).text();
						var follower_count = $('followers',xml).text();
						var message = $('message', xml).text();
						var tr = $('tr#'+profileid);
						var elementOnProfile = $('ul.profile_function li.status_follow .check_following');
						var elementOnFollow = $('tr#'+profileid+' td.col3 span.check_following');
						var mobileOnFollow = $('tr#'+profileid+' td.col3 a#mobi-'+profileid);
						var span_mobileOnFollow = $('tr#'+profileid+' td.col3 span#mobi-'+profileid);
						var mobileOnProfile = $('ul.profile_function li.status_follow #mobi-'+profileid);
						if((fromaction=='subscriptions' || fromaction == 'subscribers') && currentid == ownerid){
							$('#title').text(total);
							$('#following_number').text(total);
							if(fromaction == 'subscriptions'){ 
								setTimeout(function(){
									tr.remove();
								},1);
								return;
							}
						}
						else if(fromaction == 'showstream'){
							$("#follower_number").text(follower_count);
						}
						$('#update_via_mobile-' + profileid).html(message);
						$('#follow-'+profileid).unbind('click');
						mobileOnProfile.remove();					
						if(protect == 0){
//							var followOnProfile = document._importNode($('follow span',xml).get(0),true);
							var followOnProfile = document._importNode($('follow follow_message a',xml).get(0),true);
							var followOnFollow = document._importNode($('follow follow_ico a',xml).get(0),true);
							var li = $('ul.profile_function li.status_follow');
							var blocked_span = li.find('span.block_ico_active');
							var unblock_link = li.find('a.unblock_ico');
																							
							mobileOnFollow.replaceWith(followOnFollow);
							span_mobileOnFollow.replaceWith(followOnFollow);
							elementOnFollow.replaceWith(followOnFollow);
							elementOnProfile.replaceWith(followOnProfile);
							
							blocked_span.remove();
							unblock_link.remove();
							li.append(followOnProfile);
							
							initFollowEvent();
						}
						else{
							if(fromaction=='showstream')
							{
								window.history.go(0);
								return;
							}
							var requestOnFollow = document._importNode($('follow request_ico a',xml).get(0),true);
							mobileOnFollow.replaceWith(requestOnFollow);
							span_mobileOnFollow.replaceWith(requestOnFollow);
							initRequestEvent();
						}
						
					},
					error: function(e){
						console.log(e);
					}
				};
	$.ajax(options);
	
	$('.actions_ico').qtip('hide');
}

function receive(object) {
	var oSelf= $(object);

	var profileid = oSelf.attr('id');
	if(profileid == '' || profileid == null || typeof(profileid) == 'undefined' || profileid.substr(0,5) == 'mobi-'){
		var tr = oSelf.parents('tr');
		profileid = tr.attr('id');
		if(typeof(tr)=='undefined' || profileid == null || profileid == '' || typeof(profileid) =='undefined')
		{
			var ul = oSelf.parents('ul');
			profileid = ul.attr('id');
		}
	}
	

	var token = $('#token').val();
	var url = $('#action_url').val();
	var fromaction = $("#fromaction").val();
	
	var _mydata = [{name: 'profile',value: profileid},
	               {name: 'receive', value: 1},
	               {name: 'token', value: token},
	               {name: 'fromaction',value: fromaction}
	              ];
	$('#update_via_mobile-'+profileid).html('Requesting...');
	$.ajax({
		type: 'POST',
		dataType: 'xml',
		url: url,
		data: _mydata,
		success: function(xml){
//			console.info(xml);
			var result = $('result',xml).text();
			var nickname = $('nickname',xml).text();
			var message = $('message',xml).text();
			var message1 = $('message1',xml).text();
			var classreturn = $('stopreceiveclass', xml).text();
			var title = $('unfollow', xml).text();
			var span = document._importNode($('mobile span',xml).get(0),true);
			var mobileOnFollow = $('tr#'+profileid+' td.col3 #mobi-'+profileid);
			var mobileOnProfile = $('ul.profile_function li.status_follow #mobi-'+profileid);
			var li = $('ul.profile_function li.status_follow');
			var blocked_span = li.find('span.block_ico_active');
			var unblock_link = li.find('a.unblock_ico');
			var following_span = document._importNode($('following span',xml).get(0),true);
//			var a = document._importNode($('a',xml).get(0),true);
			var a = document._importNode($('mobile a',xml).get(0),true);
			if(result != 1){
				$('#update_via_mobile-'+profileid).html(message);
				$('#update_via_mobile').html(message);
			}
			else{
				
				if(fromaction=='showstream'){
					if (message !='') {
						$("#noticealert").text(message.replace(/<\S[^><]*>/g,""));
				  		$("#noticealertshow").attr("style", "display:block;");
				  		setTimeout("$('.err_login').slideUp();",3000);
					}
					
				} else {
					$('#update_via_mobile-'+profileid).html(message);
					
				}
				
				if(fromaction=='resultsearch'){
					$("#list_icons-"+profileid+" span.check_following").remove();
				}
				
				mobileOnFollow.replaceWith(span);
				mobileOnProfile.replaceWith(a);
				blocked_span.replaceWith(following_span);
				unblock_link.replaceWith(a);
				initUnmobileEvent();
				initMobileEvent();
				
			}
				
		},
		error: function(){
			
		}
	});
	
	$('.actions_ico').qtip('hide');
	
	return false;
}
function stop_receive(object){
	var oSelf= $(object);

	var profileid = oSelf.attr('id');
	if(profileid == '' || profileid == null || typeof(profileid) == 'undefined' || profileid.substr(0,5) == 'mobi-'){
		var tr = oSelf.parents('tr');
		profileid = tr.attr('id');
		if(typeof(tr)=='undefined' || profileid == null || profileid == '' || typeof(profileid) =='undefined')
		{
			var ul = oSelf.parents('ul');
			profileid = ul.attr('id');
		}
	}
	
	var fromaction = $("#fromaction").val();
	var token = $('#token').val();
	var url = $('#action_url').val();
	
	var _mydata = [{name: 'profile',value: profileid},
	               {name: 'receive', value: 0},
	               {name: 'token', value: token},
	               {name: 'fromaction',value: fromaction}
	              ];
	$('#update_via_mobile-'+profileid).html('Requesting...');
	
	$.ajax({
		type: 'POST',
		dataType: 'xml',
		url: url,
		data: _mydata,
		success: function(xml){
//			console.info(xml);
			var result = $('result',xml).text();
			var nickname = $('nickname',xml).text();
			var message = $('message',xml).text();
			var message1 = $('message1',xml).text();
			var classreturn = $('receiveclass', xml).text();
			var title = $('follow', xml).text();
			var following_span = document._importNode($('following span',xml).get(0),true);
			var a = document._importNode($('mobile a',xml).get(0),true);
			
			var li = $('ul.profile_function li.status_follow');
			var blocked_span = li.find('span.block_ico_active');
			var unblock_link = li.find('a.unblock_ico');
			
			if(result != 1){
				$('#update_via_mobile-'+profileid).html(message);
				$('#update_via_mobile').html(message);
			}
			else{
				
				if(fromaction=='showstream'){
					if (message !='') {
						$("#noticealert").text(message.replace(/<\S[^><]*>/g,""));
				  		$("#noticealertshow").attr("style", "display:block;");
				  		setTimeout("$('.err_login').slideUp();",3000);
					}
					
				} else {
					$('#update_via_mobile-'+profileid).html(message);
					
				}
				
																		
				$('#mobi-'+profileid).replaceWith(a);
				
				$('#mobi-'+profileid).unbind('click');
				blocked_span.replaceWith(following_span);
				unblock_link.replaceWith(a);
				initMobileEvent();

				$('#update_via_mobile').html('<a href = "javascript:void(0);" id ="'+profileid+'" onclick="receive(this);" class="'+classreturn+'" title="'+title+'"> </a>');
			}
				
		},
		error: function(){
			
		}
	});
	
	$('.actions_ico').qtip('hide');
}

function sendRequest(profileid) {	
	var url = $("#sendrequest_url-"+profileid).val();
	var mydata = [
	              {name:'ajax',value:1},
	              {name:'profileid',value:profileid}
	              ];
	$('#update_via_mobile-'+profileid).html('Requesting...');
	try{
		$.ajax({
			url:url,
			type: "POST",
			dataType:'text',
			data: mydata,
			success: function(res) {
				$('#update_via_mobile-'+profileid).html(res);
				var html = '<a id="follow-'+profileid+'" title="'+$('#pending_request').val()+'" class="pending_ico"/>';
				$("a#follow-"+profileid).replaceWith(html);
				return false;
			},
			error: function(e){
				throw e;
			}
		});
	}
	catch(e) {
		alert(e);
	}
	
	$('.actions_ico').qtip('hide');
}

function initFollowEvent(){
	$('tr .col3 .follow_ico').click(function(){
		var oSelf = $(this);
		if(oSelf.attr('class') == 'follow_ico send_request')
		{
			return false;
		}
		var tr = oSelf.parents('tr');
		var profileid = tr.attr('id');
		follow(profileid);
		return false;
	});
//	$('.entity_subscribe input[type="button"]').click(function(){
	$('a.follow_message').click(function(){
		var notlogin = $("#notlogin").val();
		if(notlogin==1) {
			return true;
		}
		var oSelf = $(this);
		var ul = oSelf.parents('ul.profile_function');
		var profileid = ul.attr('id');
		follow(profileid);
		return false;
	});
}

function block(profileid) {
	if(!confirm($("#delete_confirm_block").val()))
		return false;
	var url = $("#block_url").val();
	var profileid = profileid;
	
	var mydata = [{name:'id',value:profileid},
	              {name:'ajax',value:1}
	              ];
	var currentid = $("#currentid").val();
	var ownerid = $("#ownerid").val();
	var fromaction = $("#fromaction").val();
	var follower_count = $("#title_subcribers").text();
	
	$.ajax({
		url: url,
		dataType: 'xml',
		type: 'POST',
		data: mydata,
		success: function(res){
			var message = $('message',res).text();
			var result = $('result',res).text();
			if(result == 0) {
				alert(message);
				return false;
			}
			if(fromaction == 'showstream' || fromaction == 'postprotected'){
				window.history.go(0);
				return false;
			}
			
			if(fromaction == 'subscribers' && currentid == ownerid) {
				var tr = $('tr#'+profileid);
				follower_count = follower_count-1;
				$("#title_subcribers").text(follower_count);
				$("#follower_number").text(follower_count);
				tr.remove();
				
				return false;
			}
			$('#update_via_mobile-'+profileid).html(message);	
			
		},
		error: function(e){
			alert(e);
		}
	});
	
	$('.actions_ico').qtip('hide');
}

function unblock(profileid) {
	var url = $("#unblock_url").val();
	var profileid = profileid;
	var token = $("#token").val();
	var action = $("#fromaction").val();
	
	var mydata = [
	              {name:'unblockto',value:profileid},
	              {name:'ajax',value:1},
	              {name:'token',value:token}
	              ];
	
	$.ajax({
		url: url,
		dataType:'xml',
		type: 'POST',
		data: mydata,
		success: function(xml){
			var message = $('message',xml).text();
			var result = $('result',xml).text();
			if(result == 1){
				$('#update_via_mobile-'+profileid).html(message);
				if(action == 'showstream' || action == 'postprotected'){
					window.history.go(0);
				}
			}
		},
		error: function(e){
//			console.info(e);
		}
	});
	
	$('.actions_ico').qtip('hide');
}

function initUnfollowEvent(){
	$('tr .col3 .unfollow_ico').click(function(){
		var oSelf = $(this);
		var tr = oSelf.parents('tr');
		var profileid = tr.attr('id');
		unfollow(profileid);
		return false;
	});
}

function initMobileEvent(){
	$('tr .col3 .mobi_ico').click(function(){
		receive(this);
		return false;
	});
	$('ul.profile_function li.status_follow a.mobi_message').click(function(){
		receive(this);
		return false;
	});
}

function initUnmobileEvent(){
	$('tr .col3 .unmobi_ico').click(function(){
		stop_receive(this);
		return false;
	});
	$('ul.profile_function li.status_follow a.unmobi_message').click(function(){
		stop_receive(this);
		return false;
	});
}

function initRequestEvent() {
	$('tr .col3 .send_request').click(function(){
		var oSelf = $(this);
		var tr = oSelf.parents('tr');
		var profileid = tr.attr('id');
		sendRequest(profileid);
		return false;
	});
}

function stripHTML(){
	var re= /<\S[^><]*>/g
	for (i=0; i<arguments.length; i++)
	arguments[i].value=arguments[i].value.replace(re, "")
	}