// $Id$

function ShowDiv(divId)
{
    el = document.getElementById(divId);
    el.style.display = 'block';
}

function HideDiv(divId)
{
    el = document.getElementById(divId);
    el.style.display = 'none';        
}

function ShowCommentInput(ucId)
{
    divElementArray = document.getElementsByTagName('div');
    ShowNewReplyInput(ucId);
    for (i=0;i<divElementArray.length;i++)
    {
        divElement = divElementArray[i];
        if (divElement.id.substr(0, 9) == 'newReply_' && divElement.id.substr(9) != ucId)
        {
            otherUcId = divElement.id.substr(9);
            divElement.style.display = 'none';
        }

        if (divElement.id.substr(0, 13) == 'commentInput_')
        {
            divElement.style.display = 'block';
        }

        if (divElement.id.substr(0, 20) == 'newCommentSubmitted_')
        {
            divElement.style.display = 'none';
        }
    }
}

var commentsDisplayingArray = new Array();
var newReplyInputDisplaying;
var displayChildrenArray = new Array();
var displayChildrenIntervalId;
function ToggleCommentDisplay(ucId)
{   
    if (commentsDisplayingArray[ucId])
        HideComment(ucId);
    else
    {
        ShowComment(ucId);
        // Show child comments
        if (childCommentArray[ucId])
        {
            for (i=childCommentArray[ucId].length-1; i>=0; i--)
            {
                displayChildrenArray.push(childCommentArray[ucId][i]);
            }
            // Show children in intervals or else the formatting gets messed up.
            displayChildrenIntervalId = setInterval(DisplayChildComments, 10);
        }
        
    }
}

function DisplayChildComments()
{
    if (0 == displayChildrenArray.length)
    {
        clearInterval(displayChildrenIntervalId);
        return;
    }
       
    childUcId = displayChildrenArray.pop();
    if (childUcId)
        ShowComment(childUcId);
}

function HideComment(ucId)
{
    HideDiv("commentHeader_" + ucId);
    ShowDiv("commentSummary_" + ucId);
    commentsDisplayingArray[ucId] = false;
}

function ShowComment(ucId)
{
    HideDiv("commentSummary_" + ucId);    
    ShowDiv("commentHeader_" + ucId);


    commentsDisplayingArray[ucId] = true;
}

function ShowNewReplyInput(ucId)
{
    ShowDiv("newReply_" + ucId);    
    newReplyInputDisplaying = ucId;
}

document.write('<script src=/js/ajaxfunctions.js></script>');
function PostUserComment(ucId, prId, prName, pgId)
{
    for (i=0;i<document.forms.length;i++)
    {
        if (document.forms[i].name == ucId + "_Form")
            f = document.forms[i];
    }

    invalidFieldArray = ValidUserCommentEntry(f);
    if (invalidFieldArray.length != 0)
    {
        if (invalidFieldArray.length > 2)
        {
            $lastField = invalidFieldArray.pop();
            fieldDisplay = invalidFieldArray.join(", ") + ", and " + $lastField;            
        }
        else
        {
            fieldDisplay = invalidFieldArray.join(" and ");
        }
        
        alert("Please correct the follwing fields: " + fieldDisplay);
        return;
    }
    
    // Create the XMLHttpRequest object.
    c = CreateHTMLRequestor();

    // if the XMLHttpRequest object is in any state other than 0 (unitialized), then stop the current request.
    if (c && c.readyState!=0)
    {
        c.abort();
    }

    // Set the function that handles changes in state.
    c.onreadystatechange = processReqChange;
    if (f.notify && f.notify.checked)
        notifyUser = "Y";
    else
        notifyUser = "N";

    // Send the request.
    c.open("GET", "/usercomments/addusercomment.php?ucId="+f.ucId.value+"&prId="+f.prId.value+"&name="+encodeURIComponent(f.userName.value)+"&email="+encodeURIComponent(f.email.value)+"&title="+encodeURIComponent(f.commentTitle.value)+"&comment="+encodeURIComponent(f.comment.value)+"&notify="+notifyUser+"&sequenceId="+f.sequenceId.value, true);
    c.send(null);
    
    return false;
}

function processReqChange()
{
    var status;
    if (c)
    {
        // only if req shows "complete"
        if (c.readyState == 4)
        {
            try
            {
                status = c.status;
            }
            catch (err)
            {
                //alert(err);
                status = '';
            }            

            if (status == 200) // Numeric code returned from server. 200 means "OK".
            {
                if (c.responseText)
                {
                    responseArray = c.responseText.split("|");
                    ucId = responseArray[0];
                    prId = responseArray[1];
                    prName = responseArray[2];
                    pgId = responseArray[3];
                    errorMessage = responseArray[4];
                    if (errorMessage)
                    {
                        errorDiv = document.getElementById("commentInputError_" + ucId);
                        errorDiv.innerHTML = errorMessage;
                    }
                    else
                    {
                        ShowDiv('newCommentSubmitted_' + ucId);
                        HideDiv('commentInput_' + ucId);
                        
                        errorDiv = document.getElementById("commentInputError_" + ucId);
                        errorDiv.innerHTML = "";
                        
                        for (i=0;i<document.forms.length;i++)
                        {
                            if (document.forms[i].name == ucId + "_Form")
                                f = document.forms[i];
                        }
                        
                        f.email.value = "";
                        f.userName.value = "";
                        f.commentTitle.value = "";
                        f.comment.value = "";
                        if (f.notify)
                            f.notify.checked = false;

                        
                        if (100 == pgId)
                            dirName = "cell-phones";
                        else if (101 == pgId)
                            dirName = "plans";
                        else
                            dirName = "accessories";
                            
                        var template_data = {
                    			"prName": prName,
                                "pageURL": "http://shark.letstalk.com/" + dirName + "/productdetail.htm?prId=" + prId
                            };
                        var regularBody = "";
                        
                        delete Object.prototype.clone;
                        
                        if (FB.Facebook.apiClient.get_session())
                        {
                            FB.Connect.showFeedDialog(59571901913,
                                                      template_data,
                                                      null, // template_ids
                                                      regularBody,
                                                      null, // story_size
                                                      FB.RequireConnect.promptConnect, // require_connect
                                                      function() {
                        
                                                        Object.prototype.clone = function()
                                                        {
                                                        	var copy = {};
                                                        	for (var i in this)
                                                        	{
                                                        		var value = this[i];
                                                        		try
                                                        		{
                                                        			if (value != null && typeof(value) == 'object' && value != window && !value.nodeType)
                                                        			{
                                                        				// for IE5 which doesn't inherit prototype
                                                        				value.clone = Object.clone;
                                                        				copy[i] = value.clone();
                                                        			}
                                                        			else
                                                        			{
                                                        				copy[i] = value;
                                                        			}
                                                        		}
                                                        		catch(e)
                                                        		{
                                                        			copy[i] = value;
                                                        		}
                                                        	}
                                                        
                                                        	return copy;
                                                        };
                                                        	                                
                                                      });
                        }

                        
                    }
                }
            } 
            else {
                //alert("There was a problem retrieving the HTML data:\n" + c.statusText);
            }
        }
    }
}

function ValidUserCommentEntry(formObj)
{
    var invalidFieldArray = new Array();
    if (formObj.email.value == '' || !IsValidEmail(formObj.email.value))
        invalidFieldArray.push("Email");   

    if (formObj.commentTitle.value == '')
        invalidFieldArray.push("Title");

    if (formObj.comment.value == '')
        invalidFieldArray.push("Comment");
    
    return invalidFieldArray
}

function IsValidEmail(email)
{
    return true;
}

var fbUserInfo;

function UpdateCommentInputForm(result)
{
    for (i=0;i<document.forms.length;i++)
    {
        if (document.forms[i].name.substr(document.forms[i].name.search("_")) == "_Form")
        {
            f = document.forms[i];
            f.userName.value = result[0].name;
        }
    }
    
}

function FBLogout()
{
    FB.Connect.logout();

    divElementArray = document.getElementsByTagName('div');
    for (i=0;i<divElementArray.length;i++)
    {
        divElement = divElementArray[i];
        if (divElement.id.substr(0, 10) == "fbConnect_")
        {
            divElement.innerHTML = "<p>Enter your personal information to the left, or sign in with your Facebook account by clicking the button below. <fb:login-button onlogin=\"UpdateDivWithFBUserInfo();\"></fb:login-button>";
        }
    }
    
    for (i=0;i<document.forms.length;i++)
    {
        if (document.forms[i].name.substr(document.forms[i].name.search("_")) == "_Form")
        {
            f = document.forms[i];
            f.userName.value = "";
        }
    }    
    
    delete Object.prototype.clone;
    FB.XFBML.Host.parseDomTree();     
}

function UpdateDivWithFBUserInfo()
{
    divElementArray = document.getElementsByTagName('div');
    for (i=0;i<divElementArray.length;i++)
    {
        divElement = divElementArray[i];
        if (divElement.id.substr(0, 10) == "fbConnect_")
        {
            divElement.innerHTML = 
                "<span>" + 
                "<fb:profile-pic uid=loggedinuser facebook-logo=true></fb:profile-pic>" + 
                "Welcome, <fb:name uid=loggedinuser useyou=false></fb:name>. You are signed in with your Facebook account." + 
                "<p><a href='javascript: void(0);' onclick='FBLogout();'>Click here to Sign Out</a></p></span>"; 
        }
    }
    
    FB.Facebook.apiClient.users_getInfo(FB.Facebook.apiClient.get_session().uid, ['name', 'email_hashes'], function(result, exception){UpdateCommentInputForm(result)});
    
        
    // because this is XFBML, we need to tell Facebook to re-process the document 
    delete Object.prototype.clone;
    FB.XFBML.Host.parseDomTree(); 

/*
    Object.prototype.clone = function()
    {
    	var copy = {};
    	for (var i in this)
    	{
    		var value = this[i];
    		try
    		{
    			if (value != null && typeof(value) == 'object' && value != window && !value.nodeType)
    			{
    				// for IE5 which doesn't inherit prototype
    				value.clone = Object.clone;
    				copy[i] = value.clone();
    			}
    			else
    			{
    				copy[i] = value;
    			}
    		}
    		catch(e)
    		{
    			copy[i] = value;
    		}
    	}
    
    	return copy;
    }; 
*/
} 

function CommentMouseOver(divId)
{
    el = document.getElementById(divId);
    el.className = el.className + " hover";
}

function CommentMouseOut(divId)
{
    el = document.getElementById(divId);
    el.className = el.className.replace(" hover", "");
}