var HOVER_CONTAINTER_ID = 'divProfileHover';
var HOVER_CONTAINTER_HTML = '<div id="divProfileHover"></div>';
var DOMAIN = '/';
var isRemote = 0;
var timerID;

document.onmousemove = MouseMoveHandler;
var curElement;

//--------------------------------------------------------------
// ProfileId class
//--------------------------------------------------------------
function ProfileId(sId) {
    
    //call base constructor
    Serializable.call(this);
    //initialize properties
    this.m_sId = sId;
}

ProfileId.prototype.GetId = function()
{
    return this.m_sId;
}

ProfileId.prototype.Serialize = function()
{
    var xmlFormat = "<sId>" + this.GetId() + "</sId>"
    return xmlFormat;
}
//-------------- End of ProfileId Class -------------------------

//--------------------------------------------------------------
// Profile class
//--------------------------------------------------------------
function Profile(sid, userName, location, mood, moodKey, signature, imageUrl, milestones, firstName, lastName, friendshipStatus) {
    
    //call base constructor
    Serializable.call(this);
    //initialize properties
    this.m_sid = sid;
    this.m_userName = userName;
    this.m_location = location;
    this.m_mood = mood;
    this.m_moodKey = moodKey;
    this.m_signature = signature;
    this.m_imageURL = imageUrl;
    this.m_milestones = milestones;
    this.m_firstName = firstName;
    this.m_lastName = lastName;
    this.m_friendshipStatus = friendshipStatus;
}

Profile.prototype.GetSID = function()
{
    return this.m_sid;
}

Profile.prototype.Serialize = function()
{
    var xmlFormat = "<xml />"
    return xmlFormat;
}

Profile.prototype.GetHtml = function()
{
    var html = GetLocalizedContents();
    
    html = html.replace(/\[DOMAIN\]/g,DOMAIN);
    html = html.replace(/\[SID\]/g,this.m_sid);
    
    html = html.replace("[USERIMAGE]",this.m_imageURL);
    html = html.replace(/\[USERNAME\]/g,this.m_userName);
        
    html = ReplaceName(html, this.m_firstName, this.m_lastName);
    html = ReplaceLocation(html, this.m_location);
    html = ReplaceSignature(html, this.m_signature);
    html = ReplaceAddFriend(html, this.m_friendshipStatus);
    html = ReplaceFriendRequest(html, this.m_friendshipStatus);
    html = ReplaceFriend(html, this.m_friendshipStatus);
    html = ReplaceConfirmFriend(html, this.m_friendshipStatus);
    html = ReplaceToken(html, this.m_friendshipStatus);
    
   // console.log(html);
    return html;
}
//-------------- End of Profile Class -------------------------

function ReplaceName(html, firstName, lastName)
{
    if(firstName != "" || lastName != "")
    {
        html = html.replace("[DISPLAY_NAME]", "inline;");
        html = html.replace("[FIRSTNAME]", firstName);
        html = html.replace("[LASTNAME]", lastName);
    }
    else
    {
        html = html.replace("[DISPLAY_NAME]", "none;");        
    }
    
    return html;
}

function ReplaceLocation(html, location)
{
    if(location != "")
    {
        html = html.replace("[DISPLAY_LOCATION]", "inline;");
        html = html.replace("[LOCATION]", location);
    }
    else
    {
        html = html.replace("[DISPLAY_LOCATION]", "none;");        
    }
    
    return html;
}

function ReplaceSignature(html, signature)
{
    if(signature != "")
    {
        html = html.replace("[DISPLAY_SIGNATURE]", "inline;");
        html = html.replace("[SIGNATURE]", signature);
    }
    else
    {
        html = html.replace("[DISPLAY_SIGNATURE]", "none;");        
    }
    
    return html;
}

function ReplaceAddFriend(html, friendshipStatus)
{
    if(friendshipStatus == 2)
    {
        html = html.replace("[DISPLAY_ADD_FRIEND]", "inline;");
    }
    else
    {
        html = html.replace("[DISPLAY_ADD_FRIEND]", "none;");        
    }
    
    return html;
}

function ReplaceFriendRequest(html, friendshipStatus)
{
    if(friendshipStatus == 3)
    {
        html = html.replace("[DISPLAY_FRIEND_REQUEST]", "inline;");
    }
    else
    {
        html = html.replace("[DISPLAY_FRIEND_REQUEST]", "none;");        
    }
    
    return html;
}

function ReplaceFriend(html, friendshipStatus)
{
    if(friendshipStatus == 1)
    {
        html = html.replace("[DISPLAY_FRIEND]", "inline;");
    }
    else
    {
        html = html.replace("[DISPLAY_FRIEND]", "none;");     
    }
    
    return html;
}

//if friendship request is pending for this user
function ReplaceConfirmFriend(html, friendshipStatus)
{
    if(friendshipStatus == 4)
    {
        html = html.replace("[DISPLAY_CONFIRM_FRIEND]", "inline;");
    }
    else
    {
        html = html.replace("[DISPLAY_CONFIRM_FRIEND]", "none;");     
    }
    
    return html;
}

function ReplaceToken(html, friendshipStatus)
{
    //is a friend
    if(friendshipStatus == 1)
    {
        html = html.replace("[DISPLAY_TOKEN]", "inline;");
        html = html.replace("[DISPLAY_FRIEND]", "inline;");
    }
    else
    {
        html = html.replace("[DISPLAY_TOKEN]", "none;");   
        html = html.replace("[DISPLAY_FRIEND]", "none;");     
    }
    
    return html;
}

function AddAsFriend(sid)
{
    var xmlInput = "<input><ClientID>" + sid + "</ClientID></input>";
    
    if(isRemote == 1)
    {
        AddAsFriendRemote(xmlInput);
    }
    else
    {
        $.ajax({
            type: "POST",
            url: "/Services/UserServicePage.aspx",
            data: "method=AddFriend&xmlInput=" + xmlInput,
            error: function(XMLHttpRequest, textStatus, errorThrown) {        
            },
            success: function(xml) {
                $(JId('profilePopUpAddFriend')).hide();
                $(JId('profilePopUpRequested')).show()
            } //end of success handler
        });
    }
}


function AddAsFriendRemote(xmlInput)
{  
    var remoteInput = "<remoteInput>xmlInput=" + xmlInput + "</remoteInput>";
    
    var xmlData = "<remoteUrl>" + DOMAIN + "Services/UserServicePage.aspx" + "</remoteUrl><postData><remoteMethod>method=AddFriend</remoteMethod>" + remoteInput + "</postData>";
    
    var xmlInput = PrepareXmlInput(xmlData);

    $.ajax({
        type: "POST",
        url: "/httpservices/proxyservice.aspx",
        data: "method=RemotePost&xmlInput=" + xmlInput,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        },
        success: function(xml) {
             $(JId('profilePopUpAddFriend')).hide();
             $(JId('profilePopUpRequested')).show()
        } 
    });
}


function ConfirmAsFriend(sid)
{
    var xmlInput = "<input><ClientID>" + sid + "</ClientID></input>";
    
    if(isRemote == 1)
    {
        ConfirmAsFriendRemote(xmlInput);
    }
    else
    {
        $.ajax({
            type: "POST",
            url: "/Services/UserServicePage.aspx",
            data: "method=ConfirmFriend&xmlInput=" + xmlInput,
            error: function(XMLHttpRequest, textStatus, errorThrown) {        
            },
            success: function(xml) {
                $(JId('profilePopUpConfirmFriend')).hide();
                $(JId('profilePopUpFriend')).show(); 
                $(JId('profilePopUpSendToken')).show();
            } //end of success handler
        });
    }
}

function ConfirmAsFriendRemote(xmlInput)
{  
    var remoteInput = "<remoteInput>xmlInput=" + xmlInput + "</remoteInput>";
    
    var xmlData = "<remoteUrl>" + DOMAIN + "Services/UserServicePage.aspx" + "</remoteUrl><postData><remoteMethod>method=ConfirmFriend</remoteMethod>" + remoteInput + "</postData>";
    
    var xmlInput = PrepareXmlInput(xmlData);

    $.ajax({
        type: "POST",
        url: "/httpservices/proxyservice.aspx",
        data: "method=RemotePost&xmlInput=" + xmlInput,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        },
        success: function(xml) {
             $(JId('profilePopUpConfirmFriend')).hide();
             $(JId('profilePopUpFriend')).show();
             $(JId('profilePopUpSendToken')).show();
        } //end of success handler
    });
}

function DisplayProfile(event, ctrl, sId, hideTokenLink)
{
    var point = GetCoordinates(event);
     
    var evt = (!event) ? window.event : event;
    
    //display initial hover that indicates that an action is going on
    //ShowHover(evt, ctrl, WAIT_HTML, point);
    
    //now get profile via AJAX
    var profileId = new ProfileId(sId);
    
    var xmlData = profileId.Serialize();
    
    var xmlInput = PrepareXmlInput(xmlData);
    
    //console.log(xmlInput);
    
    var profile = null;
    
    $.ajax({
         type: "POST",
         url: "/Services/UserServicePage.aspx",
         data: "method=GetProfile&xmlInput=" + xmlInput,
         error: function(XMLHttpRequest, textStatus, errorThrown) { 
         
                  //remove waiting html
                  $(document).ready(function() {
                    HideProfile();
                    }
                  );
                    
                  //alert(textStatus + " " + errorThrown);
                  
                  }, //error
         success: function(xml) {
                     
                  profile = ProfileSuccessHandler(xml); 
                  
                  var profileHtml = profile.GetHtml();
    
                  //console.log(profileHtml);
                  
                   $(document).ready(function() {
                    ShowHover(evt, ctrl, profileHtml, point);
                    }
                  );
                                    
                  if(hideTokenLink){$(JId('profilePopUpSendToken')).hide();}
                 
                  }//success
       }); //ajax
       
} //getprofile

function DisplayProfileRemote(event, ctrl, sId, memberNumber, proxyUrl, remoteUrl, domain, country)
{
    if (sId == "" && memberNumber == "")
        return;
    
    DOMAIN = domain;
    FOOTPRINT = domain;
    COUNTRY = country;
    isRemote = 1;
    
    var point = GetCoordinates(event);
     
    var evt = (!event) ? window.event : event;
    
    var remoteInput = "<remoteInput>xmlInput=<xml><sId>" + sId + "</sId><memNum>" + memberNumber + "</memNum></xml></remoteInput>";
    
    var xmlData = "<remoteUrl>" + remoteUrl + "</remoteUrl><postData><remoteMethod>method=GetProfile</remoteMethod>" + remoteInput + "</postData>";
    
    var xmlInput = PrepareXmlInput(xmlData);
    
    $.ajax({
         type: "POST",
         url: proxyUrl,
         data: "method=RemotePost&xmlInput=" + xmlInput,
         error: function(XMLHttpRequest, textStatus, errorThrown) { 
                  //remove waiting html
                  $(document).ready(function() {
                    HideProfile();
                    }
                  );
                    
                  }, //error
         success: function(xml) {
                     
                  profile = ProfileSuccessHandler(xml); 
                  
                  if (profile != null && profile.GetSID() > 0)
                  {
                        //Show hover only if the SocNet profile exists
                        var profileHtml = profile.GetHtml();   
                         
                         $(document).ready(function() {
                            ShowHover(evt, ctrl, profileHtml, point);
                            }
                          );
                  }
                 
                  }//success
       }); //ajax
}

function ShowHover(e, ctrl, html, point)
{    
    if ($(JId(HOVER_CONTAINTER_ID)).length == 0)
    {
        //one-time operation; add a dummy container for hover
        $('body').append(HOVER_CONTAINTER_HTML);
    }
    
    if (IsMouseOverElement(ctrl))
    {    
        //Show the hover box only if the mouse is still over the same element (there could be delay in fetching service data)        
        clearTimeout(timerID);
        $(JId(HOVER_CONTAINTER_ID)).replaceWith(html);
        $(JId(HOVER_CONTAINTER_ID)).css('position','absolute').css('top', point.Y).css('left', point.X);
    }
    
}

//This is called when the mouse is over the profile hover box
function DisplayHover()
{    
    clearTimeout(timerID);
    $(JId(HOVER_CONTAINTER_ID)).css('display', 'inline');    
}

function HideProfile()
{
     timerID = setTimeout(HideProfileHandler, 200); 
}

function HideProfileHandler()
{
     $(JId(HOVER_CONTAINTER_ID)).css('display', 'none');
}

function MouseMoveHandler(event)
{
    var evt = (!event) ? window.event : event;
    var target = evt.target? evt.target : evt.srcElement;
    
    if (target != null && target.href != null)
    {
        curElement = target;
    }
    else
    {
        curElement = null;
    }
}

//Determine if the mouse is currently over the given element
function IsMouseOverElement(ctrl)
{
    if (curElement != null)
    {
        if (curElement.href == ctrl.href)
            return true;
    }
    
    return false;
}

function ProfileSuccessHandler(xml)
{
    var profile = null;
    //Get the thread Id from response
     $(xml).find('output').each(function(i){
     
       var sid = $(this).find("sid").text();
       var userName = $(this).find("userName").text();
       var location = $(this).find("location").text();
       var signature = $(this).find("signature").text();
       var mood = $(this).find("mood").text();
       var moodKey = $(this).find("moodKey").text();
       var imageUrl = $(this).find("image").text();
       var milestones = $(this).find("milestones").text();
       var firstName = $(this).find("firstName").text();
       var lastName = $(this).find("lastName").text();
       var friendshipStatus = $(this).find("friendshipStatus").text();
       
       if (imageUrl.length == 0)
       {
            imageUrl = GetDefaultProfileImage();
       }
       
       profile = new Profile(sid, userName, location, mood, moodKey, signature, imageUrl, milestones, firstName, lastName, friendshipStatus);
       
     });
     
       return profile;
   }

function GetLocalizedContents() {
    var rawContent = hoverTemplate;
    for (var parameter in ProfileHover_LocResources) {
        var replacementParameter = "[{" + parameter + "}]";
        rawContent = rawContent.replace(replacementParameter, ProfileHover_LocResources[parameter]);
    }
    return rawContent;
}

var hoverTemplate = ' ' +
'<div id="divProfileHover" onmouseover="DisplayHover()" onmouseout="HideProfile()">' +
'   <div class="profile-bubble">' + 
'        <div class="profile-bubble-top">' + 
'            <div class="profile-bubble-bot">' + 
'                <table cellspacing="0" cellpadding="0" border="0" width="348">' + 
'                    <tbody>' + 
'                        <tr>' + 
'                            <td valign="top" rowspan="6">' + 
'                                <div class="pict">' + 
'                                    <img style="border-width: 0px;" src="[USERIMAGE]" class="medium" />' + 
'                               </div>' + 
'                            </td>' + 
'                            <td>' + 
'                                <div class="info">' + 
'                                    <div class="top">' + 
'                                        <h2>' + 
'                                            <a href="[DOMAIN]People/UserProfile.aspx?sid=[SID]">[USERNAME]</a>' + 
'                                        </h2>' + 
'                                    </div>' + 
'                                   <div>' + 
'                                        <table border="0">' + 
'                                            <tbody>' + 
'                                                <tr style="display: [DISPLAY_NAME]">' + 
'                                                    <td style="font-weight: bold; width: 60px;">' +
'                                                        <span>[{Name_Label}]</span>' + 
'                                                    </td>' + 
'                                                    <td>' + 
'                                                        [FIRSTNAME] [LASTNAME]</td>' + 
'                                                </tr>' + 
'                                                <tr style="display: [DISPLAY_LOCATION]">' + 
'                                                    <td style="font-weight: bold; width: 60px;">' +
'                                                        <span>[{Location_Label}]</span>' + 
'                                                   </td>' + 
'                                                    <td>' + 
'                                                        [LOCATION]</td>' + 
'                                                </tr>' + 
'                                                <tr style="display: [DISPLAY_SIGNATURE]">' + 
'                                                    <td style="width: 200px;" colspan="2">' +
'                                                        <span><strong>[{Signature_Label}]</strong> </span>' + 
'                                                        <br />' + 
'                                                        <span>[SIGNATURE]</span>' + 
'                                                    </td>' + 
'                                                </tr>' + 
'                                           </tbody>' + 
'                                        </table>' + 
'                                    </div>' + 
'                                </div>' + 
'                            </td>' + 
'                        </tr>' + 
'                   </tbody>' + 
'                </table>' + 
'                <div class="profile-info-bot-popup">' + 
'                    <span id="profilePopUpAddFriend" style="float: right; display: [DISPLAY_ADD_FRIEND]"><a href="javascript:void(0)" onclick="AddAsFriend([SID]);"' +
'                        class="show-more">[{Add_As_Friend_Text}]</a></span>' +
'                           <span id="profilePopUpConfirmFriend" style="float: right; display: [DISPLAY_CONFIRM_FRIEND]">' +
'                            <a href="javascript:void(0)" onclick="ConfirmAsFriend([SID]);"class="show-more">[{Confirm_As_Friend_Text}]</a></span>' + 
'                           <span id="profilePopUpRequested" style="float: left; display: [DISPLAY_FRIEND_REQUEST]">' +
'                            <i>[{Friend_Request_Sent_Text}]</i> </span><span id="profilePopUpSendToken" style="float: right; display: [DISPLAY_TOKEN]">' +
'                                <a href="[DOMAIN]people/sendtoken.aspx?sid=[SID]" class="show-more">[{Send_A_Token_Text}]' +
'                                </a></span><span id="profilePopUpFriend" style="float: left; display: [DISPLAY_FRIEND]"><i>[{Currently_A_Friend_Text}]</i>' + 
'                               </span>' + 
'                </div>' + 
'            </div>' + 
'       </div>' + 
'   </div>' +
'</div>'

