/**
 * @class EmailFriendBubble_Class
 * This class Sends Email Messages to from the site
 * @constructor 
 */
Core.EmailFriendBubble_Class=function() {
    /**
    * The DHTML ID of the main layer of the EmailFriend bubble
    */
    this.ProductEmailTemplate="TellAFriendProduct.xml";
    this.TopicEmailTemplate="Topic_TellAFriend.xml";
    this.IsStaticTemplate=false;
    this.TellAFriendPageURL="";
    /**
    * The DHTML ID of the main layer of the EmailFriend bubble
    */
    this.Bubble_DivID="EmailFriend_div";
    /**
    * The DHTML ID of the confirm layer of the EmailFriend bubble
    */
    this.BubbleConfirm_DivID="EmailFriendConfirm_div";
    /**
    * The error message to designate incorrect fields
    */   
    this.FieldError = "<span style='color:#FF0000'><strong>!&nbsp;</strong></span>";
    /**
    * The DHTML ID of the General Error Message
    */   
    this.GeneralErrorID = "EmailFriend_GeneralError";
    /**
    * The DHTML ID of the General Error Message
    */   
    this.GeneralError = "<div style='color:#FF0000'><strong>Please fill all the requred fields.</strong></div>";
    /**
    * The email error message
    */   
    this.EmailError = "<div style='color:#FF0000'><strong>Please enter a valid email address.</strong></div>";
    /**
    * The fatel error message
    */   
    this.FatalError = "<div style='color:#FF0000'><strong>Sorry this email cannot be sent.</strong></div>";
    /**    
    * The DHTML ID of the Sender's first name
    */
    this.Sender_FnameID="Sender_Fname";
    /**    
    * The DHTML ID of the Sender's first name error
    */
    this.Sender_FnameErrorID="Sender_FnameError";
    /**
    * The DHTML ID of the Sender's last name
    */
    this.Sender_LnameID="Sender_Lname";
    /**    
    * The DHTML ID of the Sender's last name error
    */
    this.Sender_LnameErrorID="Sender_LnameError";
    /**
    * The DHTML ID of the Sender's Email
    */
    this.Sender_EmailID="Sender_Email";
    /**    
    * The DHTML ID of the Sender's email name error
    */
    this.Sender_EmailErrorID="Sender_EmailError";
    /**    
    * The DHTML ID of the Friend's email addresses
    */
    this.Friend_EmailID="Friend_Email";    
    /**    
    * The DHTML ID of the Friend's message
    */
    this.Friend_EmailErrorID="Friend_EmailError";
    /**    
    * The DHTML ID of the Friend's email addresses error
    */
    this.Friend_MessageID="Friend_Message"; 
    /**    
    * The DHTML ID of the checkbox asking to copy the sender to the email
    */
    this.Sender_CopyEmailID="Sender_CopyEmail"; 
    /**    
    * The DHTML ID of the Friend's email addresses
    */    
    this.Friend_EmailListID="Friend_EmailList";  
    /**    
    * to track if there is missing information
    */
    this.hasErrors=false;
    /**    
    * to track if there is a bad email address entered
    */
    this.EmailhasErrors=false;
    /**    
    * Product Code
    */
    this.ProductCode=""; 
    /**    
    * Topic Code
    */
    this.TopicCode=""; 
    /**    
    * Topic Type
    */
    this.TopicType="";    
    this.LeftPosition = "";
    this.TopPosition = "";
    /**
     * When the Email a friend bubble is shown, 
     */
    this.ShowBubble=function(which) {
        _CoreModalPopUp._PopupControlID=this.Bubble_DivID;
        _CoreModalPopUp.ShowModal();
    }
    /**
     * When the Email a friend confirmation bubble is shown, 
     */
    this.ShowConfirmBubble=function() {
    
        // Get email addresses to show on the confirm page
        var senderEmailListobj=$get(this.Friend_EmailListID);
        var friendEmailobj=$get(this.Friend_EmailID);
        if ((friendEmailobj != null) && (senderEmailListobj != null))
            senderEmailListobj.innerHTML = this.GetEmailList(friendEmailobj.value);
        _CoreModalPopUp._PopupControlID=this.BubbleConfirm_DivID;
        _CoreModalPopUp.ShowModal();
    }
    
    /**
     * Validates the email fields and sends the email 
     */
    this.SendEmail=function() {
        this.hasErrors=false;
        this.EmailhasErrors=false;
        var copyEmail=false;
        var validTemplate="";
        var code="";
        var isProduct=false;
        // Get all the fields needed for the email
        
        // check the validity of the input fields
        // Sender First Name
        var fromFname = this.ValidateField($get(this.Sender_FnameID), this.Sender_FnameErrorID, this.FieldError);
        // Sender Last Name
        var fromLname = this.ValidateField($get(this.Sender_LnameID), this.Sender_LnameErrorID, this.FieldError);      


        // Sender Email
        var fromEmail = "";
        if ($get(this.Sender_EmailID) != null)
            fromEmail = $get(this.Sender_EmailID).value;
           
        this.ValidateEmailField(fromEmail, this.Sender_EmailErrorID, this.FieldError);
        
        // Friends Email        
        var toEmail = "";
        if ($get(this.Friend_EmailID) != null)
            toEmail = $get(this.Friend_EmailID).value;
        
        this.ValidateEmailField(toEmail, this.Friend_EmailErrorID, this.FieldError);
       
        // Friends Message
        var fromMsg = "";
        // check if the messsage box control exits
        if($get(this.Friend_MessageID) != null)
            fromMsg = $get(this.Friend_MessageID).value;
            
        //check and set the Copy to control
        if ($get(this.Sender_CopyEmailID) != null)
             copyEmail = $get(this.Sender_CopyEmailID).checked;

        // check for general errors & check for email errors
        if (this.hasErrors || this.EmailhasErrors){
            var errorsb = new StringBuilder(); 
            if (this.hasErrors)
                errorsb.append(this.GeneralError);
            
            if(this.EmailhasErrors)
                errorsb.append(this.EmailError);
                
            $get(this.GeneralErrorID).innerHTML = errorsb.toString();
            
            return;    
        }
   
        // determine if Product or Topic
        if (this.ProductCode != ""){
            // send the appropraiate template
            validTemplate = this.ProductEmailTemplate; 
            isProduct = true;
            // send productcode passed in
            code = this.ProductCode; 
        }else if (this.TopicCode != ""){
            // send the appropraiate template
            validTemplate = this.TopicEmailTemplate; 
            isProduct = false;
            // send topicCode:topicType passed in
            code = this.TopicType + ":" + this.TopicCode;
        
        }else if (this.IsStaticTemplate == true){
            validTemplate = this.TopicEmailTemplate; 
            isProduct = false;
        }
         if (this.TellAFriendPageURL=="") {
           this.TellAFriendPageURL=document.location.href;
         }
       // goes into the WS Call
       // MicrosoftFrance.MCS.Commerce.WS.AJAXProject.CustomerWebService.SendMailTellAFriend(fromFname, fromLname, fromEmail, fromMsg, toEmail, copyEmail, code, isProduct, validTemplate, 'html', this.OnCompleteRequest,onError,onTimeout);
           MicrosoftFrance.MCS.Commerce.WS.AJAXProject.CustomerWebService.SendMailTellAFriend(fromFname, fromLname, fromEmail, fromMsg, toEmail, copyEmail, code, isProduct, validTemplate, 'html',this.TellAFriendPageURL, this.OnCompleteRequest,onError,onTimeout);
    }
    
    /**
     * Validates the field used on Mandatory fields 
     * @param {object} field - control to validate
     * @param {string} errorID - the control ID of the error container
     * @param {string} errorVal - value to add into the error container on error
     */
    this.ValidateField=function(field, errorID, errorVal) {
        var fieldVal = "";
        if(field != null){
            fieldVal = field.value;
            if (fieldVal.length <= 0){
                $get(errorID).innerHTML = errorVal;
                this.hasErrors = true;
            }else{
                $get(errorID).innerHTML = '';
            }
        }
        return fieldVal;
    }
    
    /**
     * Validates the Email field
     * @param {string} email - value from the email textbox (could be a comma separated list)
     * @param {string} errorID - the control ID of the error container
     * @param {string} errorVal - value to add into the error container on error     
     */
    this.ValidateEmailField=function(email, errorID, errorVal) {
        // validation support for multiple addresses
        if (email.indexOf(',') == -1){
            var emailhasError=false;
            var at="@";
            var dot=".";
            var lat=email.indexOf(at);
            var lstr=email.length;
            var ldot=email.indexOf(dot);
            
            // has an @
            if (email.indexOf(at)==-1 || email.indexOf(at)==0 || email.indexOf(at)==lstr)
               emailhasError = true;
            // has at least one .
            if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 || email.indexOf(dot)==lstr)
                emailhasError = true;
            // has only 1 @
            if (email.indexOf(at,(lat+1))!=-1)
                emailhasError = true;
            // has a . after the @
            if (email.substring(lat-1,lat)==dot || email.substring(lat+1,lat+2)==dot)
                emailhasError = true;
            // doesn't have a . right before @
            if (email.indexOf(dot,(lat+2))==-1)
                emailhasError = true;
            // no spaces
            if (email.indexOf(" ")!=-1)
                emailhasError = true;
                
            if(emailhasError){
                $get(errorID).innerHTML = errorVal;
                this.EmailhasErrors = emailhasError;
                return;
            }else{
                $get(errorID).innerHTML = '';
            }
		}else{
		    var elist = email.split(",");
            for ( i =0;i<=elist.length-1;i++) {
                this.ValidateEmailField(elist[i],errorID,errorVal);
            }
		}
	}
	
    /**
     * This method is called after a web Service Call is Completed
     * @param {string} result The result object returned from the web service
     */
    this.OnCompleteRequest=function(result){
        DoDefault();
         if (result!=null) {
        
            if(result == "true"){
                var eDiv = $get(_EmailFriendBubble_Class.Bubble_DivID)
                if(eDiv != null){   
                    eDiv.style.display="none";
                }
                _EmailFriendBubble_Class.ShowConfirmBubble();
            }else{
                //$get(_EmailFriendBubble_Class.GeneralErrorID).innerHTML = result;
                $get(_EmailFriendBubble_Class.GeneralErrorID).innerHTML = _EmailFriendBubble_Class.FatalError;
            } 
         }else { 
            alert ("Sorry this email cannot be sent.");
         }
    
    }

    /**
     * This method helps the confirm page display the "friend's" emails
     * @param {string} emailList value from the email textbox (could be a comma separated list)
     */    
    this.GetEmailList=function(emailList) {
        var sb = new StringBuilder();
        
        if (emailList.indexOf(',') == -1){
            sb.append(emailList);
        }else{
            var elist = emailList.split(",");
            for ( i =0;i<=elist.length-1;i++ ) {
               sb.append(elist[i]);
               sb.append("<br/>");
            }
        }
        return sb.toString();
    }
}

/*
 * It registers the EmailFriendBubble_Class using registerClass method of MS AJAX Library
 */
if (IsTypeDefined) { Core.EmailFriendBubble_Class.registerClass('Core.EmailFriendBubble_Class'); }

/**
 * It instantiates an object of type _EmailFriendBubble_Class
 */
var _EmailFriendBubble_Class = new Core.EmailFriendBubble_Class();



//Handle the cookie for add to bag click event:
var _SkinCeuticals_User_Used_Add_To_Bag="SkinCeuticals_User_Clicked_ADD_ToBag"
function HasSkinCeuticalUserUsedAddToBagYet() {
  try {
                    var _cookieValue=_CoreAjaxCookieManager.ReadCookie( _SkinCeuticals_User_Used_Add_To_Bag);
                     if (_cookieValue!='') {
                             return true;
                     }
                     else {
                         //save it
                         _CoreAjaxCookieManager.CreateCookie(_SkinCeuticals_User_Used_Add_To_Bag,"USED",9999);
                         //but return false so the caller shows the continue bubble
                         return false;
                     }
                    
    }
       catch (e)  {
       alert(e);
       return false;
      
   }

}

/* Continue Add To Bag Bubble */

/* This function is used from att to bag From Continue Bubble */
function AddToBagFrom_ContinueAddToBagBubble() {
  _VariantBubble_Class.AddToCartFromProductDetails( _LastShoppingCartItem.ItemCode,_LastShoppingCartItem.ItemQuantity); 
}

/* Shows the Continue add to bag bubble */
function ContinueAddToBagBubble() {
 _CoreModalPopUp._PopupControlID='SKINCEUTICALS_CONTINUE_ADD_TO_BAG_BUBBLE';
 _CoreModalPopUp.ShowModal();

}
   
   
   
   function ScrollWindowToShoppingCart(){
       window.scrollTo(0, 0); 
   
   }
   
//complim,entary power system area on bubble shopping cart
var AJAX_DEFAULT_RTLCODE="LOREAL";
var POWER_SYSTEM_ASSOCIATION_NAME='ComplimentaryProducts';
var AJAX_SHOPPINGCART_POWER_SYSTEM="AJAX_SHOPPINGCART_POWER_SYSTEM";
var AJAX_SHOPPINGCART_POWER_SYSTEM_PRODUCTS="AJAX_SHOPPINGCART_POWER_SYSTEM_PRODUCTS";   
   
_ShoppingCartBubble_Class.beforeOpen="ShoppingCartBeforeOpen"; 
_ShoppingCartBubble_Class.beforeClose="ShoppingCartBeforeClose";

function ShoppingCartBeforeOpen() {
   var obj=$get('ShoppingCartBubble_ItemQuantity');
   var obj2=$get('ShoppingCartBubble_ItemQuantity_footer');
   if (obj!=null) {
      if (obj2!=null) {
        obj2.innerHTML=obj.innerHTML;
      }
   }
   ScrollWindowToShoppingCart();
   GetPowerSystem();

}

function ShoppingCartBeforeClose() {
  //do nothing, do not delete it.  
}

function GetPowerSystem(){
     var obj=$get(AJAX_SHOPPINGCART_POWER_SYSTEM);
      if ( obj!=null) {
        obj.style.display="none";
      }
      var obj2=$get('AJAX_COMPLETE_MESSAGE');
      if ( obj2!=null) {
        obj2.style.display="none";
      }
       _WebServiceAPI.GetProductAssociations(AJAX_DEFAULT_RTLCODE,_LastShoppingCartItem.ItemParentCode,POWER_SYSTEM_ASSOCIATION_NAME,false,'DisplayPowerSystemOnComplete');

}

function DisplayPowerSystemOnComplete(result){


        DoDefaultWithoutEvent();
        var obj=$get(AJAX_SHOPPINGCART_POWER_SYSTEM);
        var obj2=$get('AJAX_COMPLETE_MESSAGE');
        if (result!=null) {
                    if ( obj!=null) {
                        obj.style.display="block";
                    }
                    if ( obj2!=null) {
                        obj2.style.display="block";
                    }
                    var sb = new StringBuilder();
                    sb.append("");
                    for (var i=0; i < result.length; i++)  {
                        var _rewriter=GetCrossSellURLRewriterPage(result[i].CategoryHomePage,result[i].URLRewrittenHomePage);
                        sb.append("<div class=\"float_L padding03_A\">");
                        sb.append("<div class=\"float_L margin02_L\"><a href=\"" + _rewriter + "\"><img src=\"/img/product/packshot/XS_" + result[i].SKU + ".jpg\"  width=\"32px\" height=\"65px\" border=\"0\"/></a></div>");
                        sb.append("<div style=\"width:74px\" class=\"float_L\">");
                        sb.append("<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"2\">");
                        sb.append("<tr valign=\"center\">");
                        sb.append("<td height=\"70\" class=\"ADrkBlue_10RTT\" valign=\"top\" style=\"margin-left:15px;\"><a href=\"" + _rewriter + "\">" + result[i].Name + "</a></td>");
                        sb.append("</tr>");
                        sb.append("</table>");
                        sb.append("</div>");
                        sb.append("</div>");
                        if (i==1) { break;}
                        
                        
                        
                    }
                    
                     var objpowersystem=$get(AJAX_SHOPPINGCART_POWER_SYSTEM_PRODUCTS);
                     if (objpowersystem!=null) {
                        
                         objpowersystem.innerHTML= sb.toString();
                    }
        }

}

function GetCrossSellURLRewriterPage(ctgHomePage,prdHomePage) {
   var rewriter="/_us/_en/catalog/";
   rewriter=rewriter + ctgHomePage.replace(".aspx","/");
   rewriter=rewriter + prdHomePage + ".htm";
   return rewriter;
}

