var user = {};
var newsletter = {};

user.send_login = function()
{
    $("#boxlogin").hide();
    $(".loading").show();

    $.ajax({
	type: "POST",
	url: "/action/login",
	data: $("#ajaxlogin").serialize(),
	success: function( responseText ){
	    var res = eval('('+responseText+')');
	    if(res.res)
	    {
	        setTimeout(function(){
		    alert("登录成功！");
	            var url_redirect = $("#url_redirect");
		    if($("#url_redirect").val() != '')
	                location.href = $("#url_redirect").val();
		    else 
		        location.reload();
		}, 500);
	    }
	    else
	    {
		alert("用户名或密码错误");
		$("#boxlogin").show();
		$(".loading").hide();
		$("#login").focus();
	    }
	}
    });
};

user.send_password = function()
{
    $("#boxforget").hide();
    $(".loading").show();

    $.ajax({
	 type: "POST",
	 url: '/action/forgotpassword',
	 data: $("#ajaxforgetpassword").serialize(),
	 success: function( responseText ){
	     var res = eval('('+responseText+')');
	     if(res.res)
	     {
		 setTimeout(function(){
	             /*alert("若要重新设置密码，请转到可以接收该电子邮件的收件箱，打开标题为“重新设置密码”的邮件，然后按照其中的说明操作。");
		     $("#UserEmail").val("");
		     $(".loading").hide();
		     $("#boxforget").show();
		     $.unblockUI();
	             $("#PopupBg").css("display","none");*/
		     //location.href="/action/login";
		     var _email=$("#UserEmail").val();
		     var _str="<div class='login-title'>找回密码</div>";
		     _str += "<p>重置密码的邮件已发送至您的认证邮箱：";
		     _str += _email;
		     _str += "中，请及时查收！</p>"
		     _str += "<div class='btn'><a href='/'></a></div>";
		     _str += "<h3>小提示</h3>";
		     _str += "<div class='jmessage'>若要重新设置密码，请转到可以接收该电子</div>";
		     _str += "<div class='jmessage'>邮件的收件箱，打开标题为\"您的帐号及密码\"</div>";
		     _str += "<div class='jmessage'>的邮件，然后安照其中的说明操作。</div>";
		     $("div#pwd-recovery div.password-left").html(_str);
		 }, 500);
	     }
	     else
	     {
		 alert("邮件地址不存在。");
		 $("#UserEmail").val("");
		 $(".loading").hide();
		 $("#boxforget").show();
	     }
	 }
    });
};

newsletter.validNewsletter = function()
{
    $("#newsletter_box").html('<img src="/design/ellecn/images/ajax-loader-formulaire.gif" alt="Loading" title="Loading" />');
    var url = "/ajaxext/subscribe_newsletter/";
    $.ajax({
	type: 'POST',
	url: url,
	data: $("#inscription-newsletter-form").serialize(),
	success: function( responseText ){
	    newsletter.validNewsletterEnd( responseText ); 
	}
    });
};

newsletter.validNewsletterEnd =	function(responseText)
{
    var res = eval('('+responseText+')');
    if(res.res)
    {
	alert("订阅成功！");
	$.unblockUI();
	$("#PopupBg").css("display","none");
    }
    else
    {
	alert(res.content);
	$("#newsletter_box").html('<a href="javascript:void(0);" onclick="newsletter.validNewsletter()"><img src="/extension/action/design/ellecn/images/submits.png" alt="login-button" /></a>');
    }
};

(function($){

     $(function(){

	 $("#btnPollSubmit").click(function(){
	     var pollContentNodeID = $("#pollContentNodeID").val();
	     send_poll( pollContentNodeID );
	 });

	 $("#btnPollView").click(function(){
	     var pollMainNodeID = $("#pollMainNodeID").val();
	     poll_result(pollMainNodeID);
	 });

	 $("#btnPollRefresh").click(function(){
	     var pollNodeID = $("#pollNodeID").val();
	     poll_result(pollNodeID);
	 });

	 showPopupLayerLogin($("#btn-header-login"));
	 showPopupLayerLogin($("#btnReSignIn"));
	 showPopupLayerLogin($("#login-link"));
	 showPopupLayerRecovery($("#login-box .forgetpassword"));
	 showPopupLayerLogin($("#leave-comment"));

	 showPopupLayerRecovery($(".forgetpassword-link"));

	 showPopupLayerNewsletter($("#btn-Subscribe"));

	 showPopupLayerRealityShowPreview($("#realityshow-preview-btn"));

	 showPopupLayerQaAdvancedSearch($("div.expert-search-content .select-text"));
	 showPopupProductSearch($("div.product-search-content .select-text"));
	 showPopupBeautyProductSearch($("#beauty_product_search_inner .arr"));

	 //user login
	 userLogin();

	 //pwd recovery
	 pwdRecovery(); 

	 //show friend
	 showFriendBox($("#final-to-f"));

	 //show comment submit form login status
	 showCommentLoginStatus($("#check-logged"));

	 $(".commanage-block .print").click(function(){
	     window.print();
	 });

	 $("#article-tools .tool-hover").mouseover(function(){
	     $(this).css("background-color","#ffffff");
	 });

	 $("#article-tools .tool-hover").mouseout(function(){
	     $(this).css("background-color","#f4f4f4");
	 });

	 //show Comment
	 showCommentBox($("#final-a-post"));
	 showCommentBox($("#make-message"));
	 showPopupLayerLogin($("#light-box-login"));
         $(".btn-reply").each(function(i){showCommentBox($(this));});
	 doZoom();

         $("#comment-submit-form .fresh").click(function(){
	     $("#comment-submit-form #captcha_img").attr("src","/ajaxext/new_captcha/"+ Math.floor(Math.random()*100000));
	 });

	 $("#inscription-newsletter-box #newsletter_ellecn_daily").click(function(){
	      ChangeNewsletterStyle($(this));
	 });

         $("#inscription-newsletter-box #newsletter_ellecn_daily2").click(function(){
              ChangeNewsletterStyle($(this));
         });

	 $("#inscription-newsletter-box #newsletter_box .submit").click(function(){

	      var newsletterEmail = $("#inscription-newsletter-box #email").val();
	      if( newsletterEmail == "" )
	      {
	          alert("请输入邮件地址！");
 		  $("#inscription-newsletter-box #email").val("");
		  $("#inscription-newsletter-box #email").focus();
		  return false;
	      }

	      var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	      if (!filter.test(newsletterEmail))
	      {
                  alert("请输入有效的邮件地址！");
		  $("#inscription-newsletter-box #email").val("");
		  $("#inscription-newsletter-box #email").focus();
		  return false;
	      }
	      if( $("#inscription-newsletter-box #captcha").val() == "" )
	      {
		   alert("请输入验证码！");
		   return false;
	      }
	      newsletter.validNewsletter();
	 });

	 $("#inscription-newsletter-box #captcha").keypress(function(e){
	      if (e.keyCode == "13") {
	          newsletter.validNewsletter();
	          return false;
	      }
	 });

	 $("#inscription-newsletter-box #captcha_img").click(function(){
              $("#inscription-newsletter-box #captcha_img").attr("src","/ajaxext/captcha/"+ Math.floor(Math.random()*100000));
         });

         $("#inscription-newsletter-box .red-link").click(function(){
              $("#inscription-newsletter-box #captcha_img").attr("src","/ajaxext/captcha/"+ Math.floor(Math.random()*100000));
         });

	 function poll_result( node_id )
         {
	     $("#poll-loader").html('<img src="/design/ellecn/images/ajax-loader-formulaire.gif" alt="Loading" title="Loading" />');
	     var url='/layout/set/popup/content/collectedinfo/'+node_id;
	     $.ajax({
	          type: "GET",
		  async:false,
	          url: url,
		  success: function( responseText ){
		       after_poll( responseText ); 
		  }
	     });
         }

	 function send_poll( node_id )
     	 {
             var radio=$("#ajaxpoll").find(":radio");
	     var result=true;
	     for(var i=0;i<radio.length;i++){
	         if(!radio[i].checked){
		    result=false;
	         }
	         else
	         {
		    result=true;
		    break;
	         }			
	     }
	     if(!result){
	         alert("请选择任一选项后进行提交，谢谢支持！");
	         return false;
	     }

	     $("#poll-loader").html('<img src="/design/ellecn/images/ajax-loader-formulaire.gif" alt="Loading" title="Loading" />');
	     $.ajax({
		 type: "POST",
		 async:false,
	         url: '/layout/set/popup/content/action',
		 data: $("#ajaxpoll").serialize(),
		 success: function( responseText ){
		 	after_poll( responseText );	        
		  }
	     });
         }

	 function after_poll( responseText )
	 {
	    $("#poll-result-show").html( responseText );
	    $("#formPoll").hide();
	    $("#btnPollRefresh").html('<img src="/design/ellecn/images/home_poll_result.png" alt="Refresh" />');
	    $("#btnPollRefresh").css({
	       	    position: "absolute",
	 	    width: "147px",
	 	    height: "24px",
	 	    left: "10px",
	 	    bottom: 0,
	 	    cursor: "pointer",
	 	    display: "block"
	    });
	 }

	 function showPopupLayerLogin(o)
	 {
	     o.click(function(){
	         var w=document.documentElement.clientWidth;
	         var h=document.documentElement.clientHeight;
	         $.blockUI({message:$("#login-box"),css:{cursor:"default",top:(h-390)/2+'px',left:(w-660)/2+'px',width:'660px',border:"0","z-index":"10000"}});
	    	 showPopupBg("#PopupBg");
	         
	     });

	     $("#login-box .box-close").click(function(){
		 closePopup();
	     });
	 }

 	 function showPopupLayerRecovery(o)
	 {
	     o.click(function(){
	         var w=document.documentElement.clientWidth;
	         var h=document.documentElement.clientHeight;
	         $.blockUI({message:$("#pwd-recovery"),css:{cursor:"default",top:(h-390)/2+'px',left:(w-660)/2+'px',width:'660px',border:"0","z-index":"10000"}});
	    	 showPopupBg("#PopupBg");
	         
	     });

	     $("#pwd-recovery .box-close").click(function(){
		 closePopup();
	     });
	 }

	 function showPopupLayerNewsletter(o)
	 {
	     $("#inscription-newsletter-box #captcha_img").attr("src","/ajaxext/captcha/"+ Math.floor(Math.random()*100000));
	     o.click(function(){
	         var w=document.documentElement.clientWidth;
	         var h=document.documentElement.clientHeight;
	         $.blockUI({message:$("#inscription-newsletter-box"),css:{cursor:"default",top:(h-390)/2+'px',left:(w-660)/2+'px',width:'660px',border:"0","z-index":"10000"}});
	    	 showPopupBg("#PopupBg");
	         
	     });

	     $("#inscription-newsletter-box .box-close").click(function(){
		 closePopup();
	     });
	 }

	 function showPopupLayerRealityShowPreview(o)
	 {
	     o.click(function(){
	         var w=document.documentElement.clientWidth;
	         var h=document.documentElement.clientHeight;
	         $.blockUI({message:$("#realityshow-preview-box"),css:{cursor:"default",top:(h-390)/2+'px',left:(w-660)/2+'px',width:'660px',border:"0","z-index":"10000"}});
	    	 showPopupBg("#PopupBg");
	         
	     });

	     $("#realityshow-preview-box .box-close").click(function(){
		 closePopup();
	     });
	 }

	 function showPopupLayerQaAdvancedSearch(o)
	 {
	     o.click(function(){
	         var w=document.documentElement.clientWidth;
	         var h=document.documentElement.clientHeight;
	         $.blockUI({message:$("#qa-advanced-search-box"),css:{cursor:"default",top:(h-390)/2+'px',left:(w-454)/2+'px',width:'454px',border:"0","z-index":"10000"}});
	    	 showPopupBg("#PopupBg");
	         
	     });

	     $("#qa-advanced-search-box .box-close").click(function(){
		 closePopup();
	     });
	 }

	 function showPopupProductSearch(o)
	 {
	     o.click(function(){
	         var w=document.documentElement.clientWidth;
	         var h=document.documentElement.clientHeight;
		 if($.browser.msie&&($.browser.version == "6.0")&&!$.support.style)
		 {
	         $.blockUI({message:$("#product-search-box"),css:{cursor:"default",top:(h-990)/2+'px',left:(w-900)/2+'px',width:'454px',border:"0","z-index":"10000"}});
		 }
		 else
		 {
	         $.blockUI({message:$("#product-search-box"),css:{cursor:"default",top:(h-390)/2+'px',left:(w-454)/2+'px',width:'454px',border:"0","z-index":"10000"}});
		 }
	    	 showPopupBg("#PopupBg");
	     });

	     $("#product-search-box .search_floatSetTit a").click(function(){
		 closePopup();
	     });
	 }

         function showPopupBeautyProductSearch(o)
	 {
		o.click(function(){
		    var w=document.documentElement.clientWidth;
		    var h=document.documentElement.clientHeight;
		    $.blockUI({message:$("#beauty-product-search-box"),css:{cursor:"default",top:(h-390)/2+'px',left:(w-454)/2+'px',width:'454px',border:"0","z-index":"10000"}});
		    showPopupBg("#PopupBg");
		});

                $("#beauty-product-search-box .search_floatSetTit a").click(function(){
			closePopup();
		});
	 }

	 function closePopup()
	 {
	     $.unblockUI();
	     $("#PopupBg").css("display","none");
	 }

	 function showPopupBg(o)
	 {
	     var sizes=getPageSize();
	     var widthTotal=sizes[0];
	     var heightTotal=sizes[1];
	     $(o).css({
		 "display":"block",
	         "width":widthTotal,
	         "height":heightTotal
	     });
	
	 }

	 

	 function userLogin()
	 {
	     var form = $("#boxlogin");
	     var text = form.find(".text");

	     $(text[0]).focus();
	     $(".loading").hide();

	     $.each(text, function(i, n){
		//submit for key down the enter
		$(n).keydown(function(e){
		    if (e.keyCode == "13") {
			$("#boxlogin").click();
		    }
		});
	     });

	     $("#boxlogin").click(function(e){
		var result = true;
		if ($("#ajaxlogin #login").val() == "") {
		    alert("请输入用户名");
		    $("#ajaxlogin #login").focus();
		    result = false;
		}
		else if ($("#ajaxlogin #password").val() == "") {
		    alert("请输入密码");
		    $("#ajaxlogin #password").focus();
		    result = false;
		}
		if (!result)
		    return false;

		//user login
		user.send_login();

	     });

	 }

	 function pwdRecovery()
	 {
	     var form = $("#ajaxforgetpassword");
	     $(".loading").hide();

	     $("#pwd-recovery #UserEmail").keydown(function(e){
	         if(e.keyCode==13)
	         {
		     form.find(".submit").click();
	             return false;
	         }
	     });

	     form.find(".submit").click(function(){
		 var txtEmail = $("#pwd-recovery #UserEmail").val();
		 if( txtEmail == "" )
		 {
		     alert("邮件地址不能为空");
		     return false;
		 }
		 var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		 if (filter.test(txtEmail))
		 {
		     user.send_password();
		 }
		 else
		 {
		     alert("请输入正确格式的电子邮件");
		     $("#pwd-recovery #UserEmail").val("");
		     $("#pwd-recovery #UserEmail").focus();
		     return false;
		 }
	     });
	 }

	 function showFriendBox(o){
	     o.click(function(){
		  $(".loading").hide();
		  $("#box").show();
	          var w=document.documentElement.clientWidth;
	          var h=document.documentElement.clientHeight;
		  $.blockUI({
		      message:$("#light-box-friend"),css:{cursor:"default",top:(h-390)/2+'px',left:(w-660)/2+'px',width:'660px',border:"0","z-index":"10000"}
		  });
		  showPopupBg("#PopupBg");
	     });
	 } 

         function showCommentLoginStatus(o){
             var cookielogin = getCookie("user_logged");
	     if( $("#check-logged").length > 0 )
	     {
    	 	 if(cookielogin == "oui"){
                        $("#check-logged").empty();
	 		loginname = decodeURIComponent(escape(getCookie('login')));
	 		$("#check-logged").append(loginname+' 用户，您好！');
         	 }    	     
	     }
	 }

	 function showCommentBox(o){
	     var textarea=$("#light-box-comment textarea");
             var defaultVal="请在此发表评论，限1000字内。";
	     var cookielogin = getCookie("user_logged");
	     if( $("#checkLogged").length > 0 )
	     {
    	         $("#checkLogged").empty();
    	 	 if(cookielogin == "oui"){
	 		loginname = decodeURIComponent(escape(getCookie('login')));
	 		$("#checkLogged").append(loginname+' 用户，您好！');
         	 }else{
	 		$("#checkLogged").append('<a id="light-box-login" href="javascript:void(0)" title="会员登录">会员登录</a>');
		 }
    	     }
    	     o.click(function(){
		 var w=document.documentElement.clientWidth;
		 var h=document.documentElement.clientHeight;
		 textarea.val(defaultVal);
		 if(cookielogin == "oui"){
	    		$("#ckbAnonymity").attr("checked",false);
		 }
		 else{
	    		$("#ckbAnonymity").attr("checked",true);
		 }
		 //$("#commentID").attr("value",o.val());
		 $("#commentID").attr("value",o.attr("name"));
		 $.blockUI({
			message:$("#light-box-comment"),
				css:{border:"0",cursor:"default",top:(h-390)/2+'px',left:(w-600)/2+'px',width:'600px',"z-index":"10000"}
		 });
		 showPopupBg("#PopupBg");
    	     });
    	     textarea.click(function(){
		 if($(this).val()==defaultVal)textarea.val("");
    	     });
    	     $("#light-box-comment #box-close").click(function(){
		 closePopup();
	     });
         }

	 function getPageSize(){

	    var xScroll, yScroll;

	    if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	    }

	    var windowWidth, windowHeight;
	    if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	    } else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	    }

	    // for small pages with total height less then height of the viewport
	    if(yScroll < windowHeight){
		pageHeight = windowHeight;
	    } else {
		pageHeight = yScroll;
	    }

	    // for small pages with total width less then width of the viewport
	    if(xScroll < windowWidth){
		pageWidth = windowWidth;
	    } else {
		pageWidth = xScroll;
	    }


	    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	    return arrayPageSize;
         }

	function ChangeNewsletterStyle(daily)
	{
	    if ($(daily).val()==1)
	    {
		$('#newsLetters').css("display","none");
		$('#newsLetters-title').css("display","none");
	    }
	    else
	    {
		$('#newsLetters').css("display","block");
		$('#newsLetters-title').css("display","block");
	    }
        }

	function doZoom() {
	    $('.font-choose  a').each(function(i){
	        if(i<3)
	        {
		    var fontID = 'font_'+i;	
		    $('.font-choose a').each(function(i){
			if($('.final-p p').css('font-size') == '14px')
				$('#font_1').css('font-weight','bold');
		    });
		    $('#'+fontID).click(function(){
			$('.font-choose a').each(function(i){
				var fID = 'font_'+i;	
				$('#'+fID).css('font-weight','normal');
			});

			var fontSize = $(this).attr("title");
			$('.final-p').css('font-size',fontSize+'px');

			if($('.final-p').css('font-size') == fontSize+'px')
				$('#'+fontID).css('font-weight','bold');

			$('.final-p p').each(function(i){
				$(this).css('font-size',fontSize+'px');
			});

			$('.final-p p a').each(function(i){
				$(this).css('font-size',fontSize+'px');
			});

			$('.final-p p strong').each(function(i){
				$(this).css('font-size',fontSize+'px');
			});

			$('.final-p p b').each(function(i){
				$(this).css('font-size',fontSize+'px');
			});

			$('.final-p p a strong').each(function(i){
				$(this).css('font-size',fontSize+'px');
			});	

			$('.final-p p a b').each(function(i){
				$(this).css('font-size',fontSize+'px');
			});	
		    });
	        }
	    });
        }

     });

})(jQuery);
