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");
		 }, 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);
	 });

	 $("#contrast-clear-all").click(function(){
	     for(j=0;j<4;j++)
	     {
	         $("#contrast_hidden_"+(j+1)).attr("value",'');
		 $("#beauty-product-contrast-box .contrast_ul_list li").remove(".li_contrast"+j);
	     }
	     $("#beauty-product-contrast-box .contrast_number").html(0);
	     $("#brand-product-others-recommend .v-align").each(function(i){
                 $(this).removeAttr("checked"); 
	     });
	 });

	 showPopupLayerLogin($("#btn-header-login"));
	 showPopupLayerLogin($("#btnReSignIn"));
	 showPopupLayerLogin($("#login-link"));
	 showPopupLayerRecovery($("#login-box .forgetpassword"));

	 showPopupLayerRecovery($(".forgetpassword-link"));

	 showPopupLayerNewsletter($("#btn-Subscribe"));

	 showPopupLayerRealityShowPreview($("#realityshow-preview-btn"));

	 showPopupLayerQaAdvancedSearch($("div.expert-search-content .select-text"));

         showPopupBeautyProductSearch($("#beauty_product_search_inner .arr,.arr222"));

	 showPopupBeautyContrastBox($("#brand-product-others-recommend .v-align"));

	 ContrastBeautyButtonBox($("#contrast-floatConBut-begin"));

	 ContrastBeautyButtonAllBox($("#contrast-floatConBut-lot"));

	 //user login
	 userLogin();

	 //pwd recovery
	 pwdRecovery(); 

	 //show friend
	 showFriendBox($("#final-to-f"));

	 $(".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();

	 $("#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 showPopupBeautyProductSearch(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:$("#beauty-product-search-box"),css:{cursor:"default",top:'50%',left:(w-800)/2+'px',width:'454px',border:"0","z-index":"10000"}});
		}
                else
		{
		$.blockUI({message:$("#beauty-product-search-box"),css:{cursor:"default",top:'30%', left:(w-800)/2+'px',width:'454px',border:"0","z-index":"10000"}});
		}
		showPopupBg("#PopupBg");
             });

	     $("#beauty-product-search-box .search_floatSetTit a").click(function(){
		closePopup();
	     });
	 }

	 function showPopupBeautyContrastBox(o)
	 {
             o.click(function(){
		var flag=false;
		var val_array = new Array();
		var name_array = new Array();
		var num = 0;
		$("#brand-product-others-recommend :checkbox").each(function(i){
                   if($(this).attr("checked")==true){
		       flag=true;
		       val_array[i] = $(this).val();
		       name_array[i] = $("#contrast_"+$(this).val()).val();
		       num ++;
		   }
		   else
		   {
                       val_array[i] = '';
                       name_array[i] = '';
		   }
		});

                $("#beauty-product-contrast-box .contrast_number").html(num);
		for(j=0;j<val_array.length;j++)
		{
                    $("#contrast_hidden_"+(j+1)).attr("value",val_array[j]);
                    $("#beauty-product-contrast-box .contrast_ul_list li").remove(".li_contrast"+j); 
		    if(val_array[j] != '')
		    {
                        $("#beauty-product-contrast-box .contrast_ul_list").append("<li class='li_contrast"+j+"'><span><a class='contrast-current-remove' style='color:#CD4A7E' href='javascript:void(0)'>删除</a></span>·"+name_array[j]+"</li>"); 
                        removeContrastCurrent($("#beauty-product-contrast-box .contrast-current-remove"),(j+1),val_array[j]);
		    }
		}

		if(flag){
		   $("#beauty-product-contrast-box").css("display","block");
		}
		else{
                    $("#beauty-product-contrast-box").css("display","none");
		}
             });

	     $("#beauty-product-contrast-box .contrast_floatSetTit a").click(function(){
                 $("#beauty-product-contrast-box").css("display","none");
	     });

	 }

         function removeContrastCurrent(o,num,value)
	 {
             o.click(function(){
                 var count=$("#beauty-product-contrast-box .contrast_number").html()-1;
                 $(this).parent().parent().remove();
		 $("#contrast_hidden_"+num).attr("value",'');
                 $("#brand-product-others-recommend #contrast_"+value).next().removeAttr("checked");
                 $("#beauty-product-contrast-box .contrast_number").html(count);
             });
	 }

	 function ContrastBeautyButtonAllBox(o)
	 {
              o.click(function(){
		     //var all_report_url = '/beauty/beauty_products/product_contrast_list/(product)/'+$("#contrast_hidden_current").val();
		     var all_report_url = '/beauty/(line)/美容/(price_range)/'+$("#contrast_hidden_current_range").val()+'/(sub_category)/'+$("#contrast_hidden_current_sub_category").val()+'/(contrast)/'+$("#contrast_hidden_current").val();
		     $(this).attr("href",all_report_url);
		 });
	 }

	 function ContrastBeautyButtonBox(o)
	 {
              o.click(function(){
                 var val_array = new Array();
		 var num=0;
		 for(i=1; i<5; i++)
		 {
                     if($("#contrast_hidden_"+i).val() != '')
		     {
		         num++;
			 val_array[i]=$("#contrast_hidden_"+i).val();
		     }
		 }
		 if(num > 3)
		 {
                     $(this).attr("href","javascript:void(0)");
		     alert("最多只能同时选择三个产品进行对比！");
		     return false;

		 }
		 else
		 {
		     var report_url = '/beauty/beauty_products/product_contrast_report/(product)/'+$("#contrast_hidden_current").val();
		     var temp_num = 0;
		     for(k=0; k<val_array.length; k++)
		     {
		         if(val_array[k] != undefined)
			 {
                            if(temp_num == 0)
                                report_url += '/(pli)/'+val_array[k]; 
                            if(temp_num == 1)
                                report_url += '/(plii)/'+val_array[k]; 
			    if(temp_num == 2)
                                report_url += '/(pliii)/'+val_array[k]; 
			    temp_num ++;
			 }
		     }
                     $(this).attr("href",report_url);
		 }
             });
	 }

	 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 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);

