/**
 *	 Copyright(c) 2009: Mantecao / Grupo Alion C.A.
 *	 url: www.mantecao.com.ve/licensing
 *	 email: licensing@mantecao.com.ve
 *	 author: Nilda Ching
 *	 description: Funciones en comun variadas utilizadas en los blogs, post, productos
 *	 usage:
 */

 var can_comment = false;
 var start_search = false; // variable que indica si se debe iniciar una busqueda rapida
 var is_looking = false; // variable que indica si se esta ejecutando una busqueda 
 var event_values = {}; //objeto donde se almacenan los valores requeridos en el metodo core.events.new_comment
/**
 * autoLogin: metodo ejecuta una autenticacion, es utilizado despues del registro de un usuario
 * @param {Object} resp: objeto que contiene los datos necesarios para la autenticacion
 */
function autoLogin(resp){
	var extra_params = {service:'account',url:"/authenticate.json",verb:'PUT'};
	var params = {};
	var r;
	params['login'] = resp["email"];
	params['password'] = resp["password"];
	params['opt']= "by-credentials";
	
	core.feedback({action:'wait'});
	$.post( config.api(), config.default_params(params,extra_params) , function(data){
		r = data.response;
		if( r.success ){
			sessvars.site.userinfo = r.entry;
			core.feedback({action:'welcome'});
			showUser(r);
			core.account.showLogout();
		}else {
			var msg = core.account.getError(r,core.account.dom.SignIn);
			core.feedback({action:'error',msg:msg});
		}
		
	}, "json" );
}

function bindCommentsScroller(type) {
	// 88px es la altura minima de un comentario.
	$('#ScrollUp_comments').click(function() {
		$('.comments').animate({scrollTop: '-=' + 176 + 'px'}, 400);
	});
	
	$('#ScrollDown_comments').click(function() {
		if ($(".comments .comment").length > 0) {
			if ($(".comments .comment:last").offset().top - $(".comments").offset().top < 440) {
				$('div.boton_down_mas_comentarios').attr("style", "display:none;");
				if($('div.commentlist .center').length > 0 )$('div.commentlist .center').append('<div class="load_comments"><div><img src="/media/images/loadinfo.net.24x24.gif" width="19" height="19"></div></div>');
				else $('div.commentlist').append('<div class="load_comments"><div><img src="/media/images/loadinfo.net.24x24.gif" width="19" height="19"></div></div>');
				if(type == 'post')loadComments();
				else loadProductComments();
			}
			else {
				$('.comments').animate({
					scrollTop: '+=' + 176 + 'px'
				}, 400);
			}
		}
	});
}

/**
 * verifyUSerToCommentForm: metodo que verifica si existe una sesion de usuario para mostrar o no las preguntas en 
 * formulario de comentario
 */
function verifyUSerToCommentForm(){
	if(sessvars.site.userinfo){
		can_comment = true;
		$("tr#question_comment").attr("style","display:none;");
	}
}


 function addCommentComplete(data){
	var r = data.response; 
	if ( r.success ){
		$("#commentform").find(":input[id='submit']").removeAttr("disabled");
		core.feedback({action:'update',icon:'clean-icon', msg:'Gracias por su Comentario!', timeout:5});
		
		// incrementar el numero de comentarios
		var text_comment = $('h4.comment_count').html();
		var s = text_comment.indexOf("(") + 1;
		var e =  text_comment.indexOf(")");
		var cant = parseInt(text_comment.substr(s,e-s)) + 1;
		$('h4.comment_count').empty();
		$('h4.comment_count').append("COMENTARIOS (" + cant + ")"); 
		
		// incluir el comentario que se acaba de crear
		var comment_div = $('<div class="comment"></div>');
		
		if($('div.usuario .avatar img').is(':visible')){
			comment_div.append('<div class="imagen_avatar fl"><img height="50" width="50" alt="" src="' + $('div.usuario .avatar img').attr('src') + '"></div>');			
		}else comment_div.append('<div class="imagen_avatar fl"><img height="50" width="50" alt="" src="' + config.env[env]['site'] + '/media/images/avatars/anonymous_avatar.png"></div>');
		
		if (sessvars.site.userinfo) {
			comment_div.append('<div class="data fl"><h4>' + sessvars.site.userinfo.user.firstname + '&nbsp;' + sessvars.site.userinfo.user.lastname + ' dice:</h4><h5></h5>');
		}
		else {
			comment_div.append('<div class="data fl"><h4>' + $("#commentform").find(":input[id='email']")[0].value + ' dice:</h4><h5></h5>');
		}
	
		comment_div.append('<div class="clearing"></div>');
		comment_div.append('<p>' + $("#commentform").find(":input[id='comment']")[0].value + '</p>');
		
		//$('div.commentlist .comments').append(comment_div);
		//comment_div.prependTo('div.commentlist .comments');
		cursor_pcomments = 0;	
		var temp_comments = '';
		$.each($('.commentlist .comment'),function(index, value){
			if(index < 4){
				temp_comments += '<div class="comment">' + $(this)[0].innerHTML + '</div>';
				cursor_pcomments += 1;
			}
		});
		$('.commentlist .comments').empty();
		$('.commentlist .comments').append(comment_div);
		$('.commentlist .comments').append(temp_comments);
		cursor_pcomments += 1;
		
		$("#commentform").resetForm();
		
		//invocamos el evento "new_comment" del core
		core.events.call('new_comment',event_values);
		
	}else{	
		var msg = core.account.getError(r,core.contact.dom);	
		core.feedback({action:'error',msg:msg});
	}
	//core.feedback({action: 'info', msg: 'Comentario agregado.'}), 
}

function addCommentForm(formId, relation) {
	// verificar si existe sesion de usuario
	var params = {};
	var email_re = new RegExp(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/); 
	$('#' + formId).ajaxForm({
		beforeSubmit: function (formData, jqForm, options) {
			var invalid = false;
			var errors = {};
			var params = {};
			var vars = {};

			if (can_comment) {
				if (location.search.indexOf('post_id') != -1)
				params['relation[id]'] = location.search.split('=')[1]; // post_id=N
				else params['relation[id]'] = $("#product_id").html();
				params['relation[type]']= relation;
				
				switch (relation){
					case 'post':
						event_values['object_type'] = "post";
						break;
					case 'product':
						event_values['object_type'] = "producto";
						break;
				}
				// para obtener el nombre tanto del post como del producto, se toma en cuenta que estos se encuentran
				// en un div dentro de la diagramacion, con un id en comun llamado "object_name"
				event_values['object_name'] = $('#object_name').html();
				
				if (sessvars.site.userinfo) {
					params['token'] = sessvars.site.userinfo.token;
					event_values['contact_name'] = sessvars.site.userinfo.user.firstname + '&nbsp;' + sessvars.site.userinfo.user.lastname;
				}else event_values['contact_name'] = $("#commentform").find(":input[id='email']")[0].value;
				
				for (var i = 0; i < formData.length; i++) {
					switch (formData[i].name) {
						case 'comment':{
							if (!formData[i].value) {
								errors[formData[i].name] = {
									field: 'Mensaje',
									msg: app.messages.CANNOTBEEMPTY
								};
								invalid = true;
							}
							else {
								params['comment'] = formData[i].value;
								event_values['comment'] = formData[i].value;
							}
							break;
						}
						case 'email':{
							if ($("#commentform").find(":input[id='email']").is(":visible")) {
								if (!formData[i].value) {
									errors[formData[i].name] = {
										field: 'Email',
										msg: app.messages.CANNOTBEEMPTY
									};
									invalid = true;
								}
								else {
									if (!email_re.test(formData[i].value)) {
										errors[formData[i].name] = {
											field: 'Email',
											msg: app.messages.INVALIDFORMAT
										};
										invalid = true;
									}
									else 
										params['email'] = formData[i].value;
								}
							}
							break;
						}
						case 'url':{
							if ($("#commentform").find(":input[id='url']").is(":visible")) {
								if (formData[i].value) {
									params['website_url'] = formData[i].value;
								}
							}
							break;
						}
					} // eo switch
				} // eo for
				// verificacion si hay error, muestra feedback de errores
				if (!invalid) {
					// desactivar el boton de enviar
					$("#submit").attr('disabled', 'disabled');
					$('#error_contactos').css('display', 'none');
					
					core.feedback({action: 'wait'});
					var extra_params = {
						service: 'create_comment',
						url: ".json",
						verb: 'POST'
					};
					$.post(config.api(), config.default_params(params, extra_params), addCommentComplete, "json");
				}
				else showErrorsFormContacts(errors);
			} else{
				var html_question = $("div#question")[0].innerHTML;
				if (html_question == app.messages.COMMENTS_QUESTION_WANT_REGISTER) {
					if (!$("input[id='user_reg']")[0].checked && !$("input[id='user_reg']")[1].checked){
						errors['question'] = {	field: app.messages.COMMENTS_QUESTION_WANT_REGISTER,msg: app.messages.SELECTQUESTION}
						showErrorsFormContacts(errors);
					}else core.account.SignUp.localize();
				}
				else {
					if (html_question == app.messages.COMMENTS_QUESTION_LEAVE_ANONYMOUSCOMMENTS) {
						if (!$("input[id='user_reg']")[0].checked && !$("input[id='user_reg']")[1].checked) {
							errors['question'] = {field: app.messages.COMMENTS_QUESTION_LEAVE_ANONYMOUSCOMMENTS,msg: app.messages.SELECTQUESTION}
							showErrorsFormContacts(errors);
						}else core.account.SignIn.localize();
					}
					else {
						errors['question'] = {
							field: app.messages.COMMENTS_QUESTION_USER_REGISTERED,
							msg: app.messages.SELECTQUESTION
						}
						showErrorsFormContacts(errors);
					}
				}
				//core.ui.localize('questioncomment',{msg: 'Seleccione su opci&oacute;n', tooltip: 'leftMiddle',target: 'rightMiddle',style_name : 'dark'})
				//core.account.SignIn.localize();
			}
		} // eo function
		
	});
	return false;
}

/**
 * changeQuestion: metodo que cambia la pregunta en secuencias de preguntas para enviar un comentario de un post
 */
function changeQuestion(accion){
	var html_q;
	
	html_q = $("div#question")[0].innerHTML;
	$('#validation_msg').empty();
	switch (html_q){
		case app.messages.COMMENTS_QUESTION_USER_REGISTERED:{
			$("form[id='commentform']").find(":input[id='user_reg']")[0].checked = false;
			$("form[id='commentform']").find(":input[id='user_reg']")[1].checked = false;
			if(accion){
				$("div#question").empty();
				$("div#question").append(app.messages.COMMENTS_QUESTION_LEAVE_ANONYMOUSCOMMENTS);
			}else{
				$("div#question").empty();
				$("div#question").append(app.messages.COMMENTS_QUESTION_WANT_REGISTER);
			}
			$("div#question").attr("style","display:none;float:left;");
			$("div#question").fadeIn('slow');		
			break;
		}
		case app.messages.COMMENTS_QUESTION_LEAVE_ANONYMOUSCOMMENTS:{
			if(accion){
				$("form[id='commentform']").find("tr#mail").removeAttr("style");
				$("form[id='commentform']").find("tr#web_site").removeAttr("style");
				$("form[id='commentform']").find("tr#mail").focus();
				can_comment = true;
			}else{
				core.account.SignIn.localize();
				$("form[id='commentform']").find("tr#mail").attr("style","display:none;");
				$("form[id='commentform']").find("tr#web_site").attr("style","display:none;");
				can_comment = false;
			}
			break;
		}
		case app.messages.COMMENTS_QUESTION_WANT_REGISTER:{
			if(accion){
				core.account.SignUp.localize();
				can_comment = false;
				$("form[id='commentform']").find("tr#mail").attr("style","display:none;");
				$("form[id='commentform']").find("tr#web_site").attr("style","display:none;");
			}else{
				$("form[id='commentform']").find("tr#mail").removeAttr("style");
				$("form[id='commentform']").find("tr#web_site").removeAttr("style");
				$("form[id='commentform']").find("tr#mail").focus();
				can_comment = true;
			}
			break;
		}
	}
	//return false;
}
 /**
  * activateSearch: método que configura el campo de busqueda, para que al admitir 6 caracteres consulte un parcial html
  * que contendra el resultado de la misma. A su vez activa el scroll del panel de resultados
  * @requires javascripts/jquery/jquery.tools.min.js
  * @requires javascripts/jquery/jquery.jScrollPane.js
  */
 function activateSearch(){
 	var url;
 	$('#search #q').keyup(function() {
	  if($(this).val().length >= 6){
	  		start_search = true;
			if (!is_looking) getSearch();
	  }else{
	  	fadeOut_searchpanel(true);
	  }
	});
 }
 
 function getSearch(){
 	var value = $('#search #q').val();
 	url = "/_quick_search_result.html?controller=blog&search=";
	
	start_search = false;
	is_looking = true;
	core.feedback({action: 'wait', timeout:0});
  	$.get(url + value, function(data){
		is_looking = false;
		fadeOut_searchpanel(false);
		var html = $("<div></div>").append($(data + ' body'));
		
		$(".scroll_panel #pane").append($(data + ' body'));
		if($(".scroll_panel #pane .seccion").length == 0){
			$(".scroll_panel #pane").html('<div class="noresults">' + app.messages.NORESULTSTOSHOW + '</div>');
		}
		// activar scroll
		$(".scroll_panel").fadeIn('fast');
		$('#pane').jScrollPane({scrollbarWidth:19, scrollbarMargin:0, showArrows:true, arrowSize:22});
		$('.jScrollPaneContainer').css('width','296px');
		$(".scroll_panel #pane").css("width","275px");
		$(".scroll_panel #pane").css("position","relative");
		if (jQuery.browser.msie) { //IE
			$('.jScrollArrowUp').css('margin','5 0 0 135px');
			$('.jScrollArrowDown').css('margin','0 0 5px 135px');
		}
		$('<div class="scroll_bar fr"></div><div class="clearing"></div>').insertAfter(".scroll_panel #pane");
		$('.jScrollPaneDrag').css("width","11px");
		$('.jScrollPaneDrag div').css("width","11px");
		
		core.feedback.close();
		if(start_search) getSearch();
	});
 }
 
 /**
  * fadeOut_searchpanel: método que oculta el panel de resultados de la búsqueda
  * @requires javascripts/jquery/jquery.tools.min.js
  */
 function fadeOut_searchpanel(hide){
 	if(hide)$(".scroll_panel").fadeOut('fast');
	
	/*$(".scroll_panel .posts .box").remove();
	$(".scroll_panel .products .box").remove();
	$(".scroll_panel .tags .box2").empty();*/
	$("#pane").empty();
 }
 
 function loadSDK_facebookPlugin(){
	window.fbAsyncInit = function() {
    FB.init({appId: '116491115074567', status: true, cookie: true,
             xfbml: true});
  	};
  	(function() {
        var e = document.createElement('script');
        e.type = 'text/javascript';
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
      }());
 }

 /**
  * fade_BannerTweets: método que inicializa un efecto fade para la cinta de tweets en el home
  * @requires javascripts/jquery/jquery.innerfade.js
  */
 function fade_BannerTweets(){
 	$('.twitter_bar ul#news').innerfade({
		speed: 'slow',
		timeout: 4000,
		type: 'sequence',
		containerheight: '26px'
	});
	
	$('ul#news li').css('position','');
 }

