
jQuery(document).ready(function(){


	jQuery(".comments-link a").live("click",function(e){
		         e.preventDefault();
		         jQuery('#comments-loader')[0].innerHTML = "";
		         
		          var art = jQuery(this).parents("article").find(".entry-title a");
		          var ct = jQuery(this).parents("article").find(".entry-content").text();
		          var pict = jQuery(this).parents("article").find("img");
		          
		         	WPCSwitcher.GraphStreamPublish.Body = WPCSwitcher.GraphStreamPublishApp.Body = {message: 'comentó en ' + window.title,
													 			link: art[0].href,
													 			name: art.text(),
													 			caption: window.title,
													 			picture: pict.length>0 ? pict[0].src : '',
													 			description: ct};
													
													
				
		         jQuery('#comments-loader').load(this.href+" #comments",function() {
		           jQuery.nmManual("#comments-loader",{
		           				callbacks: {
		              			initFilters: function(nm) {
		              				nm.filters.push('Dom');
		              		  }
		                  }
		              	});
		       });   
		});
		
		
		jQuery("a.page-numbers").live("click",function(e){
		         e.preventDefault();
		         jQuery('#comments').fadeOut(300);
		         jQuery('#comments').innerHTML = "";
		         if(this.href.indexOf("#comments")>0){
				         jQuery('#comments').load(this.href+" #comments > *",function(){
				     			  jQuery('#comments').fadeIn(300);
				         });
				     }else if(this.href.indexOf("#respond")>0){
								jQuery('#comments').load(this.href+" #respond",function(){
				     			  jQuery('#comments').fadeIn(300);
				         });
				     }
		});
		
		
		
		jQuery('li.jaw_years a.jaw_years').live('click', function(){
			jquery_archive_list_animate(this);
	                return false;
		});
		
		
		jQuery('#submit').live('click',function(e){ e.preventDefault();sendAjaxComment(this,'guest'); return false;}); 
	  jQuery('#fb_submit').live('click',function(e){ e.preventDefault();
	  	jQuery('#fbcommentform #comment_parent').val(jQuery('#guestcommentform #comment_parent').val());
			sendAjaxComment(this,'fb'); return false;}); 
	  jQuery('#'+WPCSwitcher.Settings.loginBtn).live('click',WPCSwitcher.LoginAction);	
	  jQuery('#guest_login').live('click',function(e){ e.preventDefault(); WPCSwitcher.ShowTab('guest');WPCSwitcher.HideTab('fb'); return false;});
		jQuery('#'+WPCSwitcher.Settings.fb_logout).live('click',WPCSwitcher.LogoutAction);
		
		jQuery('#guestcommentform #comment_parent').live('change',function(){
				jQuery('#fbcommentform #comment_parent').val(jQuery(this).val());
			});
		
	
		callbacksInit();
});		  
  
function callbacksInit(){
  
  try{
  	
	
  	
 // TB_init();
  if(wpa2a){
  	var tgts = [];
  	jQuery("article").each(function(){
  		var link = jQuery(this).find(".entry-title a");
  		tgts.push({title: link.text(),url: link.attr("href"),el:jQuery(this).find(".a2a_target")[0]});
  	});
  	wpa2a.targets = tgts;
  	wpa2a.init();
  	if(window.a2a != undefined ){ 
  		
  	for(var i=0,target,targets=wpa2a.targets,length=targets.length;i<length;i++){
  			target=targets[i];
  			window.a2a_config.linkname=target.title;
  			window.a2a_config.linkurl=target.url;
  			window.a2a.init('page',{target:target.el});
  		
  	}
  }
 
  }
  
   }catch(err){}

}


var PTM_AJAX_Comments =
{   
	init: function(d) {
		PTM_AJAX_Comments.assignVars(d);
	},
   
   data:{},
     
   assignVars: function(data) {
    	
		this.data.submitId = data.submitId,	
		this.data.btSubmit = jQuery('#'+data.submitId).attr('value');
		this.data.activityImage = data.activityImage;
		this.data.showForm = data.showForm
		this.data.disableForm = data.disableForm;
		this.data.activityImage = data.activityImagePath;		
		this.data.activeColor = data.activeColor;
    this.data.inactiveColor = data.inactiveColor;
    this.data.css_comment = data.css_comment;
    this.data.css_commentform = data.css_commentform;
		this.data.css_commentlist = data.css_commentlist;
		this.data.css_respond = data.css_respond;
		this.data.textNoComment = data.textNoComment;
		this.data.textAddingComment = data.textAddingComment;
		this.data.textCommentAdded = data.textCommentAdded;
		this.data.compatContentPress = data.compatContentPress;
		this.data.compatAntispamBee = data.compatAntispamBee;
		this.data.commentPosition = data.commentPosition;
		this.data.fieldPrefix = data.fieldPrefix;
		this.data.ptmAcResponseId = 'ptm-ac-response'+data.fieldPrefix;
		this.data.ptmAcLoaderId =  'ptm-ac-loader'+data.fieldPrefix;
		this.data.comment_parent = 0;
		
		PTM_AJAX_Comments.setColors();
		PTM_AJAX_Comments.sendForm();
		
	},
					
	setColors: function() {
		jQuery('#'+this.data.fieldPrefix+'author').focus(function(){jQuery(this).css('background', '#'+this.data.activeColor);}).blur(function(){jQuery(this).css('background', '#'+this.data.inactiveColor);});
		jQuery('#'+this.data.fieldPrefix+'email').focus(function(){jQuery(this).css('background', '#'+this.data.activeColor);}).blur(function(){jQuery(this).css('background', '#'+this.data.inactiveColor);});
		jQuery('#'+this.data.fieldPrefix+'url').focus(function(){jQuery(this).css('background', '#'+this.data.activeColor);}).blur(function(){jQuery(this).css('background', '#'+this.data.inactiveColor);});
		jQuery('#'+this.data.fieldPrefix+'url').focus(function(){jQuery(this).css('background', '#'+this.data.activeColor);}).blur(function(){jQuery(this).css('background', '#'+this.data.inactiveColor);});
	},
	
	sendForm: function(submitButton) {
		
		  this.data.comment_parent = jQuery('#comment_parent')[0].value;
		  if(jQuery(this.data.ptmAcResponseId).length<=0){
			jQuery('#'+this.data.css_commentform).before('<div id="'+this.data.ptmAcResponseId+'" style="display:none;"></div>');
			jQuery('#'+this.data.css_commentform).before('<div id="'+this.data.ptmAcLoaderId+'" style="display:none;"><img src="'+this.data.activityImage+'" alt="'+this.data.textAddingComment+'" /></div>');
		}
	//			try {
				// reset message
				jQuery("#"+this.data.ptmAcResponseId).removeClass('ptm-ac-error ptm-ac-success').html('').hide();
				
				/*
					if(this.comment.value === '' || this.comment.value == this.comment.title) {
						jQuery(this.data.ptmAcResponseId).addClass('ptm-ac-error').html('<span>'+this.data.textNoComment+'</span>').show();
						this.comment.focus();
						return false;
					}
			*/
                
				// all good, make comment
				var ptm_ajax_options = { 
					beforeSubmit: PTM_AJAX_Comments.preSubmit,
					success: PTM_AJAX_Comments.postSubmit,
					error : PTM_AJAX_Comments.ajaxError,
					type: 'post'
				};
				
				jQuery('#'+this.data.css_commentform).ajaxSubmit(ptm_ajax_options); 
				return false;
			
			//catch(e) {
				// do a normal postback in case of an unexpected error
		//		console.log(e);
		//		return true;	
		//	}
	},
	
	ajaxError: function(XMLHttpRequest, textStatus, errorThrown) {
		PTM_AJAX_Comments.removeActivity();
		var _wpResponse,  _wpBody, _error;
		// check for wp_die
		if(XMLHttpRequest.status == 500 || XMLHttpRequest.status == 403) {
			_wpResponse = XMLHttpRequest.responseText;
			_wpBody = jQuery(_wpResponse).contents().filter(function(){return this.nodeType != 1;});
			_error = _wpBody[2].wholeText;
		} else {
			_error = 'Ha ocurrido un error inesperado. Inténtelo de nuevo.';
		}
		PTM_AJAX_Comments.throwError(_error);
		return;
	},
	
	preSubmit: function(formData, jqForm, ptm_ajax_options) {
		PTM_AJAX_Comments.addActivity();
	},
	
	postSubmit: function(responseText, statusText, xhr, $form) {
		/*
		console.log(responseText);
		console.log(statusText);
		console.log(xhr);
		console.log($form);
		*/
		PTM_AJAX_Comments.removeActivity();
		// check for errors
		var errordata = responseText.split(":");
		is_error = errordata[0]; // If WP returned an error, the value of is_error is now 'error'
		
		if(is_error == 'error') {
			PTM_AJAX_Comments.throwError(errordata[1].trim());
			return;
		} else if(responseText == -1) { // likely not all fields filled
			PTM_AJAX_Comments.throwError('Por favor, rellene los campos obligatorios');
		} else {
			PTM_AJAX_Comments.processComment(responseText,$form);
			PTM_AJAX_Comments.clearInputs();
		}
	},
	
	processComment: function(data) {
		
		if( data.indexOf('<ol class="commentlist">')>0){
			
			data= '<ol class="commentlist">' + data.split('<ol class="commentlist">')[1];
			data= data.split("</ol>")[0] +"</ol>";
		
	  }else{
	  	data="";
	  }
	  
	  
		if (this.data.comment_parent!=0){
			
			var parentId = "#li-comment-"+this.data.comment_parent;
			
			var elementInBody = jQuery(parentId);
			var elementInResponse = jQuery("#comments-loader").html(data).find(parentId);
			elementInResponse.hide();
			var elementRContent = elementInResponse.html();
			jQuery("#comments-loader").html("");
			
			jQuery('#'+this.data.css_respond).fadeOut();
			jQuery('.'+this.data.css_commentlist).append(jQuery('#'+this.data.css_respond));
			jQuery('#'+this.data.css_respond).fadeIn();
			elementInBody.fadeOut();
			elementInBody.html(elementRContent);
			elementInBody.fadeIn();
			
			
		}else{ 
			
			
			var elementInResponse = jQuery("#comments-loader").html(data).find("li.depth-1:last-child");
			elementInResponse.hide();
			var elementRContent = elementInResponse.clone();
			jQuery("#comments-loader").html("");
			
			var commentlist = jQuery("ol.commentlist");
			
			if(commentlist.length==0){
				commentlist = jQuery('#'+this.data.css_respond).before('<ol class="commentlist"></ol>');
			}
			
			elementInResponse = jQuery("ol.commentlist").append(elementRContent);
			
			jQuery(elementRContent).fadeIn();
			jQuery('#'+this.data.css_respond).fadeOut();
			jQuery('.'+this.data.css_commentlist).append(jQuery('#'+this.data.css_respond));
			jQuery('#'+this.data.css_respond).fadeIn();
			
			
		}
		
		/*
		
		
		// remove the reply form
		jQuery('#cancel-comment-reply-link').click();
		*/
		jQuery("#"+this.data.ptmAcResponseId).addClass('ptm-ac-success').html('<span>'+this.data.textCommentAdded+'</span>').show();
	
	},
		
	addActivity: function() {
		jQuery("#"+this.data.ptmAcResponseId).removeClass('ptm-ac-error').html('<span>'+this.data.textAddingComment+'</span>').show();
		if (this.data.disableForm == 'checked') {	
			jQuery('#'+this.data.css_commentform+' *').attr("disabled","disabled");
		} else {
			jQuery('#'+this.data.css_respond).fadeOut();
		}
	},
	
	removeActivity: function() {
		jQuery("#"+this.data.ptmAcResponseId).removeClass('ptm-ac-error').html('').hide();
		if(this.data.showForm == 'checked') {
			jQuery('#'+this.data.css_respond).fadeIn();
		}
		jQuery('#'+this.data.css_commentform+' *').removeAttr("disabled");
	},
	
	clearInputs: function() {
		jQuery('#comment').val('');
		jQuery('#comment_parent').val('');
	},
	
	throwError: function(message) {
		PTM_AJAX_Comments.removeActivity();
		jQuery('#'+this.data.css_commentform).fadeIn();
		jQuery("#"+this.data.ptmAcResponseId).addClass('ptm-ac-error').html('<span>'+message+'</span>').show();
	}
};

function sendAjaxComment(button,formId){

	var data;
	var valid = true;
	
	if(formId == "guest"){
		
	  data = {submitId: 'submit',
	
			'showForm' : '',
			'disableForm' : 'checked',
			'compatContentPress' : '',
			'compatAntispamBee' : '',
			'activityImagePath' : '../images/activity1.gif',
			'activeColor' : 'EEEEEE',
			'inactiveColor' : 'FFFFFF',
			'css_style' : '#ptm-ac-response{}'+"\n"+'.ptm-ac-success > span{color:green;}'+"\n"+'.ptm-ac-error > span{font-weight:bold;color:red;}'+"\n"+'#ptm-ac-loader{display:inline-block;}'+"\n"+'#ptm-ac-loader > img{margin-left:15px;}',
			'css_commentform' : 'guestcommentform',
			'css_comment' : 'comment',
			'css_commentlist' : 'commentlist',
			'css_respond' : 'respond',
			'textNoComment' : 'Por favor, escriba su comentario.',
			'textAddingComment' : 'Añadiendo comentario, por favor espere...',
			'textCommentAdded' : 'Su comentario ha sido añadido, ¡gracias!',
			'callback_name' : '',
			'commentPosition' : 'bottom',
		'fieldPrefix' : ''};
		
			
	}else{
		
		data = {submitId: 'fb_submit',
	
			'showForm' : '',
			'disableForm' : 'checked',
			'compatContentPress' : '',
			'compatAntispamBee' : '',
			'activityImagePath' : '../images/activity1.gif',
			'activeColor' : 'EEEEEE',
			'inactiveColor' : 'FFFFFF',
			'css_style' : '#ptm-ac-responsefb_{}'+"\n"+'.ptm-ac-success > span{color:green;}'+"\n"+'.ptm-ac-error > span{font-weight:bold;color:red;}'+"\n"+'#ptm-ac-loaderfb_{display:inline-block;}'+"\n"+'#ptm-ac-loader > img{margin-left:15px;}',
			'css_commentform' : 'fbcommentform',
			'css_comment' : 'comment',
			'css_commentlist' : 'commentlist',
			'css_respond' : 'respond',
			'textNoComment' : 'Por favor, escriba su comentario.',
			'textAddingComment' : 'Añadiendo comentario, por favor espere...',
			'textCommentAdded' : 'Su comentario ha sido añadido, ¡gracias!',
			'callback_name' : '',
			'commentPosition' : 'bottom',
			'fieldPrefix' : 'fb_'};
		
		
			
	}
	

	PTM_AJAX_Comments.init(data);

}


