    function trimByWord(sentence) { //function to trim the description to 15 words
    var result = sentence; //assign the passed value to a variable
    var resultArray = result.split(" "); //spilt it up by spaces
        if(resultArray.length > 15){ //get the first 15 elements in the array
        resultArray = resultArray.slice(0, 15); //slice her up
        result = resultArray.join(" ") + "…"; //add elipses at the end
        }//end if
    return result; //return it
    }

    //initiate GLOBAL vars
    var shareURL; 
    var shareTitle = encodeURIComponent(document.title); //encode the title for passing in a url string to the web services
    var serviceURL; //initialize the service URL
    var windowTitle; //initialize the windowTitle
    var shareWinOpts = 'toolbar=1,status=0,scrollbars=yes,width=635,height=520'; //popupwindow options
    

    
    function getAlteredUrl(shareApp){ // this function is adapted from the send2friend.js file this 
        var locationurl = top.location.href; //get the url of the top window
        var splitUrlArray = ""; //initalize variable 
        var splitUrlArray1 = ""; //initalize variable
        var splitUrlArray2 = ""; //initalize variable
        var mvVar=""; //initalize variable
        var shareAppPrefix = 'mv='; //set this prefix
        
        var shareAppTrack = shareAppPrefix + shareApp; //put the url variables together
        
        if (locationurl.indexOf("mv") != null & locationurl.indexOf("mv") > 0) { //if statement taken from the send2friend.js file
                splitUrlArray = locationurl.split("mv");
            if(splitUrlArray !=null && splitUrlArray.length > 0 ){
                splitUrlArray1 = splitUrlArray[0];
                splitUrlArray2 = splitUrlArray[1];
                if (splitUrlArray2.indexOf("&") != null & splitUrlArray2.indexOf("&") > 0) {
                     if(splitUrlArray2.indexOf('&')> 0 ){ 
                        var startindex = splitUrlArray2.indexOf("&") ; 
                        var endindex = splitUrlArray2.length; 
                        var remUrl = splitUrlArray2.substring(startindex , endindex);
                        locationurl = splitUrlArray1+shareAppTrack+remUrl;
                     }
                }else {
                    locationurl = splitUrlArray1+shareAppTrack;
                }
            }
        }else
        {
          if (locationurl.indexOf("?") != null & locationurl.indexOf("?") > 0) {    
            locationurl = locationurl+"&"+shareAppTrack;
          }else{
            locationurl = locationurl+"?"+shareAppTrack;
          }
        }
        return locationurl; 
    }
    
//  function showMoreSharing(){
//      if ( $(this).parents('dl').next().is('dl') ){
//          $(this).parents('dl').hide();
//          $(this).parents('dl').next().show();
//      }
//  }
//  function showLessSharing(){
//      if ( $(this).parents('dl').prev().is('dl') ){
//          $(this).parents('dl').hide();
//          $(this).parents('dl').prev().show();
//      }
//  } legacy functionality for scrolling through the web services
    
    function showShareModal(){
        //s.pageName.Value = 'Product Summary > sendToFriend';
            omnitureTracking('sendToFriend');
        $("#shareModalAbsoluteWrap").remove(); //remove any previous instances of this window.
        $("#shareBorder").remove(); //remove the border
        $('body').append('<div id="shareModalAbsoluteWrap"></div>'); //add the div onto the bottom of the page
        $('body').append('<div id="shareBorder"></div>'); //add the div onto the bottom of the page
        //$("#shareModalAbsoluteWrap").load(imagePath+"shared/html/share_widget.html"); //load the html of the into the div
        $("#shareModalAbsoluteWrap").html(shareWidget());
        shareWidgetjs();
        var offset = $(this).offset(); //get the offset of the element that was clicked in this case the "share this item" link
        var outWidthThis = $(this).outerWidth(); //get the actual width of the clicked element
        var outHeightThis = $(this).outerHeight(); //get the actual height of the clicked element
        var outWidth = $('#shareModalAbsoluteWrap').outerWidth(); //get the width of the modal
        var setMenuTop = (offset.top + outHeightThis) + 'px'; //set the correct value for the top offset in pixels
        var setMenuLeft = (offset.left - outWidth + outWidthThis)  + 'px'; //set the correct value for the left offset in pixels
        $("#shareModalAbsoluteWrap").css({'top' : setMenuTop, 'left' : setMenuLeft} ); //position the modal from the top and left
        var setRoundBorderTop = (offset.top + outHeightThis - 9) + 'px';  //position the border from the top
        var setRoundBorderLeft = (offset.left - outWidth + outWidthThis - 1)  + 'px'; //position the border from the left
        var setRoundBorderHeight = $('#shareModalAbsoluteWrap').outerHeight() + 8  + 'px'; //set the border to the correct height
        $("#shareBorder").css({'top' : setRoundBorderTop, 'left' : setRoundBorderLeft, 'height' : '229px'} ); //position the modal from the top and left
        omnShare(1);
        return false; //return false
    }
    function closeShareModal(){
            $("#shareModalAbsoluteWrap").remove(); //remove the instance of the modal
            $("#shareBorder").remove(); //remove the border
    }
    function shareAction(){
        var desc = $('#desc p:first').text(); //Get the text in the first paragraph in the description 
        if(desc){
            var descFirstSentence = trimByWord(desc); //Split that string at the first sentence.
            var shareDesc = encodeURIComponent( descFirstSentence ); //encode the sentence to pass in the URI
        }
        else{
            var shareDesc = '';
        }
        var shareImageSrc = $('.slider img:first').attr('src'); //get the src of the productImage
        if(shareImageSrc){
            var shareImageArray = shareImageSrc.split('?'); //remove the extra variables at the end of the image src, if we don't do this, it'll error
            var shareImage = encodeURIComponent('<img src="'+shareImageArray[0]+'" width="200" style="float:left; margin:0px 10px 10px 0px;" >'); //encode the img html into something a url can accept
        }
        else{
            var shareImage = '';
        }
        var testClick = $(this).attr('id'); //get the id of what was clicked
        switch(testClick) //switch cases are faster and easier to maintain than ifs, so WE USE THEM!!!!!    
        {  
        case 'shareDigg':
          windowTitle = 'Digg';
          shareURL = encodeURIComponent( getAlteredUrl('digg') ); //encode the url for passing 
          serviceURL = 'http://digg.com/submit?url='+shareURL+'&amp;title='+shareTitle+'&amp;bodytext='+shareDesc; //construct the appropriate service call
          window.open(serviceURL,windowTitle,shareWinOpts); //open the popup
          omnShare(2,windowTitle);
          break;
        case 'shareFacebook':
          windowTitle = "Facebook";
          shareURL = encodeURIComponent( getAlteredUrl('facebook') );
          serviceURL = 'http://www.facebook.com/sharer.php?u='+shareURL+'&amp;t='+shareTitle;
          window.open(serviceURL,windowTitle,shareWinOpts);
          omnShare(2,windowTitle);
          break;
        case 'shareMyspace':
          windowTitle = 'MySpace';
          shareURL = encodeURIComponent( getAlteredUrl('myspace') );
          serviceURL = 'http://www.myspace.com/Modules/PostTo/Pages?t='+shareTitle+'&u='+shareURL+'&c='+shareImage+shareDesc; //myspace lets us add extra fancy stuff to 'c' variable which is essentially the description
          window.open(serviceURL,windowTitle,shareWinOpts);
          omnShare(2,windowTitle);
          break;
        case 'shareIM':
          windowTitle = 'AOLIM';
          shareURL = getAlteredUrl('aolim');
          serviceURL = 'aim:goim?message='+shareURL; //for aim we don't encode the url because it is not passing through the browser
          omnShare(2,windowTitle);
          window.open(serviceURL,windowTitle,shareWinOpts);
          break;
        case 'shareDelicious':
          windowTitle = 'Delicious';
          shareURL = encodeURIComponent( getAlteredUrl('delicious') );
          serviceURL = 'http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url='+shareURL+'&amp;title='+shareTitle;
          omnShare(2,windowTitle);
          window.open(serviceURL,windowTitle,shareWinOpts);
          break;
        case 'shareTwitter':
          windowTitle = 'Twitter';
          shareURL = getAlteredUrl('twitter'); //for twitter we don't encode the url because it is not passing through the browser
          serviceURL = 'http://twitter.com/home?status='+shareTitle+' '+shareURL;
          omnShare(2,windowTitle);
          window.open(serviceURL,windowTitle,shareWinOpts);
          break;
        case 'shareStumbleUpon':
          windowTitle = 'StumbleUpon';
          shareURL = encodeURIComponent( getAlteredUrl('stumbleupon') );
          serviceURL = 'http://www.stumbleupon.com/submit?url='+shareURL+'&amp;title='+shareTitle;
          omnShare(2,windowTitle);
          window.open(serviceURL,windowTitle,shareWinOpts);
          break;
        default: //the default is set to email
          $('#sendEmailWrapper').toggle(); //open and close the email wrapper div
          newheight = $('#modalWrapper').height() + 35 +'px'; //sent the wrapper to a certain height 
          if($('#shareBorder').height() < 450){ //check the height of the border 
            $('#shareBorder').css({"height": newheight}); //expand it if its short
          }
          else{
              $('#shareBorder').css({"height": '229px'});//contract if its tall
          }
          $(this).toggleClass('current'); //add a class of current to the div if you've clicked email
          omnShare(2,'Email');
        }//end switch
    }//end shareAction func
    
    function charCount(){
        maxLen = 200; // max number of characters allowed
        if ( $(this).val().length >= maxLen) {
            $(this).val( $(this).val().substring(0, maxLen) );
            $('#charLeft').text( maxLen - $(this).val().length + ' Characters Left');
        }
        else{ 
            $('#charLeft').text( maxLen - $(this).val().length + ' Characters Left');
        }
    }//end char count function
    
$(document).ready(function(){
    $('.sendToFriend').bind("click",showShareModal);
});




function sendEmailValidateAndSend() //most of this is legacy, improvements were made in regards to how the variables are collected etc
 {
        $('#emailToFriend input').removeClass('fail'); //remove all the failed classes from the inputs to restart validation
        $('.sendEmailError').text(''); //remove the text from the error divs
        newBorderheight = $('#modalWrapper').height() + 30 +'px'; //set the wrapper's height
        $('#shareBorder').css({"height": newBorderheight}); //expand it if its short
        
        var name = $('#emailToFriend #yourName').val(); // get the values from the forms
        var vEmail = $('#emailToFriend #yourEmail').val();
        var fEmail = $('#emailToFriend #friendsEmail').val();
        var locationurl = top.location.href;

        if(!nameValidation(name)){ //check and validate the name field
            $('#yourName').addClass('fail'); 
            return false;
        }

       function nameValidation(name){ //function that validate the name it only returns false if there is something really wierd going on in there
            var  regexpression = /^\s*[a-zA-Z\s][a-zA-Z0-9\s\.\-\\]*$/ ;
            var yourName = name.replace( /^\s*/, "" );
            if(yourName.match(regexpression) || yourName.length == 0){
                return true;
            }   
            $('#yourName').addClass('fail');
            $('#nameError').text('The name you entered appears incorrect.');
            return false;
       }//end nameValidataion func


    if (!validateEmailAddress(vEmail.toLowerCase(),vEmail)){ //Run the users email address through the validator
                $('#yourEmail').addClass('fail');
                $('#yourEmailError').text('Please enter your E-mail Address.');
                newBorderHeight = $('#shareBorder').height() + 20 +'px'; //reset thr border wrapper height
                $('#shareBorder').css({"height": newBorderHeight}); //expand it if its short
                return false;
        }


      var vArray = fEmail.split(";"); //Take the address in the friends email field and slipt them by a semi-colom and put them into an array
     
      for ( count=0; count < vArray.length; count++){ //loop through that array and attempt to valiadate each email address
            var vElem = vArray[count];
            if (!validateEmailAddress(vElem.toLowerCase(),vElem))
                    {
                    $('#friendsEmail').addClass('fail');
                    $('#friendsEmailError').text('The E-mail address(es) you entered appear incorrect.');
                    newBorderHeight = $('#shareBorder').height() + 36 +'px'; //reset thr border wrapper height
                    $('#shareBorder').css({"height": newBorderHeight}); //expand it if its short
                    return false;
                    }
      }//end for loop


        
        var locationurl = getAlteredUrl('s2f'); //run through new enhanced tracking functionality
        
        var stringUrl = locationurl.replace(/&/g,"*"); //legacy feature
        var visitorName  = $('#yourName').val();
        var visitorEmail = $('#yourEmail').val();
        var friendsEmail = $('#friendsEmail').val();
        document.cookie = "userEmail="+visitorEmail+";" //legacy, don't know exactly what this does
        
        $('#shareModalAbsoluteWrap').html(''); //clear the html in the modal
        //$("#shareModalAbsoluteWrap").load(imagePath+"shared/html/email_confirmed.html"); //load the confirmation message
        $("#shareModalAbsoluteWrap").html(emailConf());
        emailConfjs();
        $('#shareBorder').css({"height": "268px"}); //close the border
        
        var ajaxurl = "SendToAFriendCmd?storeId="+storeId+"&visitorName="+visitorName+"&visitorEmail="+visitorEmail+"&friendsEmail="+friendsEmail+"&url="+stringUrl;
        ajaxCall(ajaxurl,'dummytwo');
        
        
        
    return false;
}

function dummytwo(){ 
    return;
}


function validateEmailAddress(tempemail,displayEmail){
var email = $.trim(tempemail); //jquery to trim whitespace, replacing the rtrim and ltrim function, 2-13-09

if(email == '' ){
        //alert("Email address is required");
        //$('#yourEmailError').text('Please Enter Your Email');
        return false;
}

var regex1 = /^[^\s@]+@([A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]\.|[A-Za-z0-9]\.)+([A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]|[A-Za-z0-9])$/; //legacy regex variables
var regex2 = /^(root@|abuse@|spam@)/; //legacy regex variables
var failedAlert = "The e-mail address you entered appears incorrect. (Example of a correct address: sears@sears.com.) Please check your information and try again.";
    
    if(!email.match(regex1)){
        //alert(failedAlert);
        return false;
    } else if(email.match(regex2)){
        alert(displayEmail + " is not allowed");
        return false;
    }else if(!checkEmailChar(email)){
        //alert(failedAlert);
        return false;
    }
return true;
}


function omnShare(typeOmn,nameClick) {   
  if (typeof s == 'undefined') {
    return false;
  }
  if(typeof nameClick !='undefined'){
    s.prop29=nameClick
    s.linkTrackEvents = 'None';
    s.tl(this,'o',nameClick);
  }else if(typeOmn==1){
    omPrefix='Product Summary > Share This Item';
     s.t();
  }
  
  return false;
  }
function shareWidgetjs(){
    $('dl.shareIt dd').bind('click',shareAction);
$('#modalWrapper #closeButton').bind('click',closeShareModal);
$("#shareModalAbsoluteWrap").bgiframe(); // apply the ie6 iframe plugin so that the modal appears above select elements
$('body').click(function() {
$("#shareModalAbsoluteWrap").remove(); //apply the lightbox eefect to the modal, so if the user clicks off it the modal disappears
$("#shareBorder").remove();
});//end body click func
$('#shareModalAbsoluteWrap').click(function(event){
event.stopPropagation(); //make sure if the user clicks within the modal, it doesn't disappear
});//end shareModalAbsoluteWrap click func
$("#message").bind('keydown',charCount); //bind a function for the character count
$("#message").bind('keyup',charCount); //bind a function for the character count
    $("#message").bind('change',charCount);  //bind a function for the character count    

}  
  
function shareWidget(){ 
var widgetHtml = '<div class="allMiddle">'+
    '<div id="modalWrapper">'+
'            <h2>'+
'                <a id="closeButton" title="Close">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>'+
'                Share This Item'+
'            </h2>'+
'                <dl id="shareThis" title="Share This" class="shareIt">'+
'                    <dt title="Select A Service">'+
'                       <!--<div class="forwardBack">'+
'                           <div class="showLessShare arrowleftinactive"></div>'+
'                            <div class="showMoreShare arrowright"></div>'+
'                        </div>-->'+
'                        Select a Service'+
'                    </dt>'+
'                    <dd title="Email This" id="shareEmail" class="left">E-mail</dd>'+
'                    <dd title="Digg This" id="shareDigg">Digg</dd>'+
'                    <dd title="Add to MySpace" id="shareMyspace" class="left">MySpace</dd>'+
'                    <dd title="Add to Facebook" id="shareFacebook">Facebook</dd>'+
'                    <dd title="Send An AOL IM" id="shareIM" class="left">AOL IM</dd>'+
'                    <dd title="Add to Delicious" id="shareDelicious">Delicious</dd>'+
'                    <dd title="Twitter" id="shareTwitter" class="left">Twitter</dd>'+
'                    <dd title="Stumble Upon" id="shareStumbleUpon">StumbleUpon</dd>'+
'                </dl><!--end share this-->'+
'            <div id="sendEmailWrapper">'+
'                <h3 title="E-mail This Item">E-mail This Item</h3>'+
'                <p>'+
'                    We’ll send your friend(s) a link to this page and a personalized message. '+
'                    <span class="requiredFields">* Required Fields</span>'+
'                </p>'+
'                <form id="emailToFriend" action="javascript:;">'+
'                        <fieldset>'+
'                            <label for="yourName" title="Your Name:">Your Name:</label><input type="text" name="yourName" Title="Your Name" id="yourName" />'+
'                            <div id="nameError" class="sendEmailError"></div>'+
'                            <label for="yourEmail" title="Your E-mail">Your E-mail:*</label><input type="text" name="yourEmail" title="Your Email" id="yourEmail" />'+
'                            <div id="yourEmailError" class="sendEmailError"></div>'+
'                            <label for="friendsEmail" title="Friend\'s Email">Friend\'s E-mail:*</label><input type="text" name="friendsEmail" title="Friend\'s Email" id="friendsEmail" />'+
'                            <div id="friendsEmailError" class="sendEmailError"></div>'+
'                            <div class="instructs">Separate multiple emails by a semi-colon(;)</div> '+
'                            <div class="clear"></div>'+
'                            <div id="sendEmailButtonWrapper">'+
'                               <div id="messageError"></div>'+
'                                <button type="submit" onclick="if(sendEmailValidateAndSend()); return false" class="sendEmail" name="sendEmail" title="Send E-Mail"></button>'+
'                            </div><!--end sendEmailButtonWrapper-->                     </fieldset>                 </form>            </div><!--end sendemail wrapper--></div><!--end modal wrapper--></div>';
    return widgetHtml;
}






function emailConfjs(){

        $('dl.shareIt dd').bind('click',shareAction);
        $('#modalWrapper #closeButton').bind('click',closeShareModal);
        $("#shareModalAbsoluteWrap").bgiframe();

        $('body').click(function() {
         $("#shareModalAbsoluteWrap").remove();
         });
         $('#shareModalAbsoluteWrap').click(function(event){
             event.stopPropagation();
         });

}

function emailConf(){
var temp ='<div class="allMiddle">'+
'    <div id="modalWrapper">'+
'        <div class="emailModalTop"></div>'+
'            <h2>'+
'                <a id="closeButton" title="Close">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</a>'+
'                E-mail sent'+
'            </h2>'+
'            <p class="emailConfirmedMessage">'+
'               Thank you for sharing this link with your friend(s).'+
'            </p>'+
'             <dl class="shareIt" title="Share This" id="shareThis">'+
'                    <dt title="Select A Service">'+
'                        More ways to share this link:'+
'                    </dt>'+
'                     <dd title="Email This" id="shareEmail" class="left">E-mail</dd>'+
'                    <dd title="Digg This" id="shareDigg">Digg</dd>'+
'                    <dd title="Add to MySpace" id="shareMyspace" class="left">MySpace</dd>'+
'                    <dd title="Add to Facebook" id="shareFacebook">Facebook</dd>'+
'                    <dd title="Send An AOL IM" id="shareIM" class="left">AOL IM</dd>'+
'                    <dd title="Add to Delicious" id="shareDelicious">Delicious</dd>'+
'                    <dd title="Twitter" id="shareTwitter" class="left">Twitter</dd>'+
'                    <dd title="Stumble Upon" id="shareStumbleUpon">StumbleUpon</dd>'+
'                       </dl>'+
'            <div id="sendEmailWrapper">'+
'                <h3 title="E-mail This Item">E-mail This Item</h3>'+
'                <p>'+
'                    We’ll send your friend(s) a link to this page and a personalized message. '+
'                    <span class="requiredFields">* Required Fields</span>'+
'                </p>'+
'                <form id="emailToFriend" action="javascript:;">'+
'                        <fieldset>'+
'                            <label for="yourName" title="Your Name:">Your Name:</label><input type="text" name="yourName" Title="Your Name" id="yourName" />'+
'                            <label for="yourEmail" title="Your E-mail">Your E-mail:*</label><input type="text" name="yourEmail" title="Your Email" id="yourEmail" />'+
'                            <div id="yourEmailError" class="sendEmailError"></div>'+
'                            <label for="friendsEmail" title="Friend\'s Email">Friend\'s E-mail:*</label><input type="text" name="friendsEmail" title="Friend\'s Email" id="friendsEmail" />'+
'                            <div id="friendsEmailError" class="sendEmailError"></div>'+
'                            <div class="instructs">Separate multiple emails by a semi-colon(;)</div> '+
'                            <div class="clear"></div>'+
'                            <div id="sendEmailButtonWrapper">'+
'                               <div id="messageError"></div>'+
'                                <button type="submit" onclick="if(sendEmailValidateAndSend()); return false" class="sendEmail" name="sendEmail" title="Send E-Mail"></button>'+
'                            </div><!--end sendEmailButtonWrapper-->'+
'                     </fieldset>'+
'                 </form>'+
'            </div><!--end sendemail wrapper-->'+
'        <div class="emailModalBottom"></div>'+
'    </div><!--end modal wrapper-->'+
'</div>';
return temp;
}
