var szAjaxFile = "/php-include/wcp_ajax.php?";

// This is a global parameter used by the postComment() function to perform AJAX calls
var g_objCommentAjax = null;

// This posts a comment to a specific VideoID. The visitor must be logged in or it will return an error
function postComment(_videoID, _parentCommentID, _comment, _commentList, _statusMsg)
{
	// Parameters:
	//		_videoID = the unique identifier for the video to post the comment to
	//		_parentCommentID = the CommentID for the comment that this is a reply to (0 will be passed if there is no parent)
	//		_comment = the ID of the textbox for the comment text
	//		_commentList = the ID of the <ul> tag and parent that contains all the list of comments
	//		_statusMsg = the ID of the tag to display status messages as we process the posting of the comment
	
	// Make sure we have valid parameters
	if(!_comment || !_commentList || !_statusMsg || !_videoID) { return; }	
	if(_parentCommentID != null) { _parentCommentID = getValue(getElement(_parentCommentID)); }
	if(!_parentCommentID) { _parentCommentID = '0'; }
	
	// Get the objects based on the IDs
	var objComment = getElement(_comment);
	var objCommentList = getElement(_commentList);
	var objStatusMsg = getElement(_statusMsg);
	
	// Make sure the objects were found
	if(!objComment || !objCommentList || !objStatusMsg) { return; }
	
	// Make sure we have a valid comment
	var szComment = escape(trim(getValue(objComment)));
	if(szComment.length == 0)
	{
		setValue(objStatusMsg, "Please enter some text before posting a comment.");
		showElement(_statusMsg);
		fadeElement(_statusMsg, 3, "&nbsp;");
		return;
	}
	
	// Set the status message to show that we are posting a message
	setValue(objStatusMsg, '<img src="/images/loading.gif" alt="Posting comment" /> Posting comment ...');
	showElement(_statusMsg);
	
	// Generate the Ajax Request String
    var szAjaxRequest = szAjaxFile + "cmd=postComment&comment=" + szComment + "&videoID=" + escape(_videoID) + "&parentCommentID=" + escape(_parentCommentID);
	
	// Create an ajax object
	g_objCommentAjax = new BellwetherAjax(null, null);
	g_objCommentAjax.AjaxRequest(szAjaxRequest);
	
	// Create a call to check the status of the ajax request every 100 miliseconds
	setTimeout("postComment_Check('" + szComment + "', '" + _statusMsg + "', '" + _commentList + "', '" + _comment + "', '" + _parentCommentID + "')", 100);
}

// This posts a comment to a specific Article or Interview. The visitor must be logged in or it will return an error
function postArticleComment(_articleFilename, _parentCommentID, _comment, _commentList, _statusMsg)
{
	// Parameters:
	//		_articleFilename = the filename for the article to post a comment to
	//		_parentCommentID = the CommentID for the comment that this is a reply to (0 will be passed if there is no parent)
	//		_comment = the ID of the textbox for the comment text
	//		_commentList = the ID of the <ul> tag and parent that contains all the list of comments
	//		_statusMsg = the ID of the tag to display status messages as we process the posting of the comment
	
	// Make sure we have valid parameters
	if(!_comment || !_commentList || !_statusMsg || !_articleFilename) { return; }	
	if(_parentCommentID != null) { _parentCommentID = getValue(getElement(_parentCommentID)); }
	if(!_parentCommentID) { _parentCommentID = '0'; }
	
	// Get the objects based on the IDs
	var objComment = getElement(_comment);
	var objCommentList = getElement(_commentList);
	var objStatusMsg = getElement(_statusMsg);
	
	// Make sure the objects were found
	if(!objComment || !objCommentList || !objStatusMsg) { return; }
	
	// Make sure we have a valid comment
	var szComment = escape(trim(getValue(objComment)));
	if(szComment.length == 0)
	{
		setValue(objStatusMsg, "Please enter some text before posting a comment.");
		showElement(_statusMsg);
		fadeElement(_statusMsg, 3, "&nbsp;");
		return;
	}
	
	// Set the status message to show that we are posting a message
	setValue(objStatusMsg, '<img src="/images/loading.gif" alt="Posting comment" /> Posting comment ...');
	showElement(_statusMsg);
	
	// Generate the Ajax Request String
    var szAjaxRequest = szAjaxFile + "cmd=postArticleComment&comment=" + szComment + "&article=" + _articleFilename + "&parentCommentID=" + escape(_parentCommentID);
	
	// Create an ajax object
	g_objCommentAjax = new BellwetherAjax(null, null);
	g_objCommentAjax.AjaxRequest(szAjaxRequest);
	
	// Create a call to check the status of the ajax request every 100 miliseconds
	setTimeout("postComment_Check('" + szComment + "', '" + _statusMsg + "', '" + _commentList + "', '" + _comment + "', '" + _parentCommentID + "')", 100);
}

// This function checks if the ajax request has been completed and displays the result
function postComment_Check(_comment, _statusMsg, _commentList, _commentTextBox, _parentCommentID)
{
	// Parameters:
	//		_comment = the comment text so that if the post is successful, we can
	//			add the comment to the display list
	//		_statusMsg = the ID of the tag to display status messages as we process the posting of the comment
	//		_commentList = the ID of the <ul> tag and parent that contains all the list of comments
	//		_commentTextBox = the ID of the textbox containing the comment (this will have its value reset after the AJAX call)
	//		_parentCommentID = the unique CommentID of the parent comment
	
	// Make sure we have an ajax request in progress
	if(!g_objCommentAjax) { return; }
    
	// Check if the ajax call is complete
    if(g_objCommentAjax.HasResponse())
    {
        // Get the response 
        var szResponse = g_objCommentAjax.AjaxResult();
        if(!szResponse) { return; }
		
		// Hide the status message which says "Posting comment ..."
		hideElement(_statusMsg);
        
		// We expect the response to be SUCCESS or [an error message]
		var a_Response = szResponse.split("~|~");
		if(a_Response.length > 2 && a_Response[0] == "SUCCESS")
		{
			var szCommentID = "comment" + a_Response[1];
			var objCommentList = getElement(_commentList);
			setValue(objCommentList, a_Response[2]);
			
			// Move to the new comment
			if(_parentCommentID)
			{
				window.location = String(window.location).replace(/\#.*$/, "") + "#" + szCommentID;
			}
			
			// Fade the object
			fadeElement(szCommentID, 3, null, 0);
			
			// Reset the comment text
			var objComment = getElement(_commentTextBox);
			setValue(objComment, " ");
		}
		else
		{
			// There was an error, maybe the person is not logged in or another complication occurred
			
			// Update the status message with the failure
			var objStatusMsg = getElement(_statusMsg);
			setValue(objStatusMsg, "Error posting comment (comment not posted): " + szResponse);
			showElement(_statusMsg);
			fadeElement(_statusMsg, 3, "&nbsp;");
		}
        
		// Reset the comment ajax object
		g_objCommentAjax = null;
		
        return;
    }
    else
    {
        // If we don't have a response, we'll wait 200 miliseconds before trying again
        setTimeout("postComment_Check('" + _comment + "', '" + _statusMsg + "', '" + _commentList + "', '" + _commentTextBox + "')", 200);
    }
}

// This function sets the elements on the page to be setup for replying to a comment
function replyComment(_parentCommentID)
{
	// Parameters:
	//		_parentCommentID = the unique id of the parent comment to reply to
	
	// Make sure the supplied value is valid
	if(!_parentCommentID) { return; }
	
	// Get the element for this commentID
	var objParentComment = getElement("comment" + _parentCommentID);
	var objHiddenField = getElement("hfParentCommentID");
	var objStatusMsg = getElement("commentStatusMsg");
	var objCommentTextBox = getElement("tbComment");
	
	if(!objParentComment || !objHiddenField || !objStatusMsg || !objCommentTextBox) { return; }
	
	// Prepare the reply with bare minimum (so they can still reply if we fail below)
	setValue(objHiddenField, _parentCommentID);
	setValue(objStatusMsg, "Reply to comment below:");
	
	// Focus on the comment textbox
	objCommentTextBox.focus();
	
	// Get the value of the parent comment
	var szParentCommentValue = objParentComment.innerHTML;
	szParentCommentValue = String(szParentCommentValue).replace(new RegExp("\\s+", "g"), ' ');
	
	/*var testRegExp = new RegExp("u=([0-9]+)(.)>(.+)<(.)a(.+)strong", "im");
	var testMatch = testRegExp.exec(szParentCommentValue);
	if(testMatch != null)
	{
		var s = "Found match at: " + testMatch.index + "\n";
		for(var i = 0; i < testMatch.length; i++)
		{
			s = s + "testMatch[" + i + "]: " + testMatch[i] + "\n";
		}
		alert(s);
	} else { alert("Match not found"); }*/

	
	// Get the name of the person who posted the original comment
	var regExp = new RegExp("u=([0-9]+)(.)>(.+)<(.)a(.+)strong", "i");
	var m = regExp.exec(szParentCommentValue);
	var szOriginalPoster = "";
	if(m != null && m.length > 3)
	{
		szOriginalPoster = m[3];
	}
	
	// Get the text of the original comment
	regExp = new RegExp("span(.+)p>(.+)<(.)p", "i");
	m = regExp.exec(szParentCommentValue);
	var szOriginalComment = "";
	if(m != null && m.length > 2)
	{
		szOriginalComment = String(m[2]).replace(new RegExp("\\s+", "g"), ' ');
		szOriginalComment = String(m[2]).replace(new RegExp("<br>", "ig"), ' ');

		if(szOriginalComment.length > 18)
		{
			szOriginalComment = szOriginalComment.substring(0, 15) + "...";
		}
	}
	
	// Set the text of the status message to show the comment the person is replying to
	if(szOriginalPoster.length > 0 && szOriginalComment.length > 0)
	{
		setValue(objStatusMsg, "Reply to post by <b>" + szOriginalPoster + "</b>:<br />&emsp; &emsp; " + szOriginalComment);
	}
	
	// Show the status message
	showElement("commentStatusMsg");
	fadeElement("commentStatusMsg", 3, null, 0);
}

// This is a global parameter used by the postComment() function to perform AJAX calls
var g_objEditCommentAjax = null;

// This function sets the elements on the page to be setup for editing a comment
function editComment(_commentID, _securityCode)
{
	// Parameters:
	//		_commentID = the unique id of the comment to edit
	//		_securityCode = the unique security code necessary to perform the AJAX request for this _commentID
	
	// Make sure the supplied parameteres is valid
	if(!_commentID || !_securityCode) { return; }
	var objComment = getElement("comment" + _commentID);
	if(!objComment) { return; }
	
	// Set the status message to show that we are posting a message
	setValue(objComment, '<img src="/images/loading.gif" alt="Editing comment" /> Preparing to edit comment ...');
	
	// Generate the Ajax Request String
    var szAjaxRequest = szAjaxFile + "cmd=getEditCommentHTML&commentID=" + _commentID + "&securityCode=" + _securityCode;
	
	// Create an ajax object
	g_objEditCommentAjax = new BellwetherAjax(objComment, null);
	g_objEditCommentAjax.AjaxRequest(szAjaxRequest);

	return;
}

// This function reverts the elements on the page to the state they were before an edit was initiated
function cancelEditComment(_commentID, _securityCode)
{
	// Parameters:
	//		_commentID = the unique id of the comment to edit
	//		_securityCode = the unique security code necessary to perform the AJAX request for this _commentID
	
	// Make sure the supplied parameteres is valid
	if(!_commentID || !_securityCode) { return; }
	var objComment = getElement("comment" + _commentID);
	if(!objComment) { return; }
	
	// Set the status message to show that we are posting a message
	setValue(objComment, '<img src="/images/loading.gif" alt="Canceling comment edit" /> Canceling edit ...');
	
	// Generate the Ajax Request String
    var szAjaxRequest = szAjaxFile + "cmd=getCommentHTML&commentID=" + _commentID + "&securityCode=" + _securityCode;
	
	// Create an ajax object
	g_objEditCommentAjax = new BellwetherAjax(objComment, null);
	g_objEditCommentAjax.AjaxRequest(szAjaxRequest);

	return;
}

// This function saves the changes to an edit of a comment
function editCommentCmd(_commentID, _comment, _statusMsg, _commentList, _isArticle)
{
	// Parameters:
	//		_commentID = the unique ID of the comment to edit
	//		_comment = the ID for the textbox containing the new (edited) text for the comment
	//		_statusMsg = the ID for the div tag to place status messages inside
	//		_commentList = the ID of the <ul> tag and parent that contains all the list of comments
	//		_isArticle = (optional) defines if we need to edit an article instead of a video
	
	// Make sure we have valid parameters
	if(!_commentID || !_comment || !_statusMsg) { return; }	
	if(!_isArticle) { _isArticle = false; }
	
	// Get the objects based on the IDs
	var objComment = getElement(_comment);
	var objStatusMsg = getElement(_statusMsg);
	
	// Make sure the objects were found
	if(!objComment || !objStatusMsg) { return; }
	
	// Make sure we have a valid comment
	var szComment = escape(trim(getValue(objComment)));
	if(szComment.length == 0)
	{
		setValue(objStatusMsg, "Please enter some text before editing a comment.");
		showElement(_statusMsg);
		fadeElement(_statusMsg, 3, "&nbsp;");
		return;
	}
	
	// Set the status message to show that we are posting a message
	setValue(objStatusMsg, '<img src="/images/loading.gif" alt="Editing comment" /> Editing comment ...');
	showElement(_statusMsg);
	
	// Generate the Ajax Request String
	var szCommand = "editComment";
	if(_isArticle) { szCommand = "editArticleComment"; }
    var szAjaxRequest = szAjaxFile + "cmd=" + szCommand + "&commentID=" + _commentID + "&comment=" + szComment;
	
	// Create an ajax object
	g_objEditCommentAjax = new BellwetherAjax(null, null);
	g_objEditCommentAjax.AjaxRequest(szAjaxRequest);
	
	// Create a call to check the status of the ajax request every 100 miliseconds
	setTimeout("editCommentCmd_Check('" + _commentList + "', '" + _statusMsg + "')", 100);
}

// This function checks if the ajax request has been completed and displays the result
function editCommentCmd_Check(_commentList, _statusMsg)
{
	// Parameters:
	//		_commentList = the ID of the <ul> tag and parent that contains all the list of comments
	//		_statusMsg = the ID for the div tag to place status messages inside
	
	// Make sure we have an ajax request in progress
	if(!g_objEditCommentAjax) { return; }
    
	// Check if the ajax call is complete
    if(g_objEditCommentAjax.HasResponse())
    {
        // Get the response 
        var szResponse = g_objEditCommentAjax.AjaxResult();
        if(!szResponse) { return; }
		
		// Hide the status message which says "Posting comment ..."
		hideElement(_statusMsg);
        
		// We expect the response to be SUCCESS or [an error message]
		var a_Response = szResponse.split("~|~");
		if(a_Response.length > 2 && a_Response[0] == "SUCCESS")
		{
			var szCommentID = "comment" + a_Response[1];
			var objCommentList = getElement(_commentList);
			setValue(objCommentList, a_Response[2]);
			
			// Move to the new comment
			window.location = String(window.location).replace(/\#.*$/, "") + "#" + szCommentID;
			
			// Fade the object
			fadeElement(szCommentID, 3, null, 0);
		}
		else
		{
			// There was an error, maybe the person is not logged in or another complication occurred
			
			// Update the status message with the failure

			var objStatusMsg = getElement(_statusMsg);
			setValue(objStatusMsg, "Error editing comment (comment not edited): " + szResponse);
			showElement(_statusMsg);
			fadeElement(_statusMsg, 3, "&nbsp;");
		}
        
		// Reset the comment ajax object
		g_objEditCommentAjax = null;
		
        return;
    }
    else
    {
        // If we don't have a response, we'll wait 200 miliseconds before trying again
        setTimeout("editCommentCmd_Check('" + _commentList + "', '" + _statusMsg + "')", 200);
    }
}

// This function gets the value of the supplied element
function getValue(objElement)
{
	// Parameters:
	//		objElement = the element to get the value for
	
	
    // Make sure the object is valid
    if(!objElement) { return ""; }
    
    // Return the value of the object
    if(objElement.length)
    {
        // This is a drop down, so loop through and get the selected value
        for(var i = 0; i < objElement.length; i++)
        {
            if(objElement[i].selected)
            {
                return trim(objElement[i].value);
            }
        }
    }
    else
    {
		var szValue = "";
		
		if(objElement.innerHTML)
		{
			szValue = trim(objElement.innerHTML);
		}
		
		if(objElement.value)
		{
			szValue = trim(objElement.value);
		}
		
		return szValue;
    }

	// Unable to find a value, return an empty string
    return "";
}

// This function sets the value of an element
function setValue(objElement, _value)
{
	// Parameters:
	//		objElement = the element to set the value for
	//		_value = the value to set


	// Make sure we have valid parameters
	if(!objElement || !_value) { return; }
    _value = unescape(_value);
    
    // Step 2.  Set the value of the object
    if(objElement.value && !objElement.innerHTML)
    {
        objElement.value = _value;
    }
    else
    {
		objElement.innerHTML = _value;
    }
}

// This function hides an element on the page using its ID
function hideElement(_elementID)
{
	// Parameters:
	//		_elementID = the ID of the element to hide
	
	// Make sure we have valid parameters
	if(!_elementID) { return; }
	
	// Get the object
	var objElement = getElement(_elementID);
	
    // Make sure we have valid objects
    if(!objElement || !objElement.style) { return; }
    
    // Hide the object
    objElement.style.display = 'none';
}

// This function shows an element on the page
function showElement(_elementID)
{
   	// Parameters:
	//		_elementID = the ID of the element to show
	
	// Make sure we have valid parameters
	if(!_elementID) { return; }
	
	// Get the object
	var objElement = getElement(_elementID);
	
    // Make sure we have valid objects
    if(!objElement || !objElement.style) { return; }
    
    // Show the object
    objElement.style.display = 'block';
}

// This fades an element on the page before hiding it
var hideElementTimeout = null; // houses the id of the last hideElement timeout from the fadeElement function
var valueElementTimeout = null; // houses the id of the last setValue timeout from the fadeElement function
var idElementTimeout = null; // houses the id of the last elementID timeout from the fadeElement function
function fadeElement(_elementID, _fadeLevel, _resetText, _hideAfterCompletion)
{
    // Step 1.  Get the object
    if(!_elementID) { return; }
    var objElement = getElement(_elementID);
    if(!objElement || !objElement.style) { return; }
    if(!_fadeLevel) { _fadeLevel = 0; } // reset fade level to instant fade
	if(_hideAfterCompletion == null || typeof(_hideAfterCompletion) == "undefined") { _hideAfterCompletion = 1; } // reset the hide after completion to true
    else { _fadeLevel = parseInt(_fadeLevel); } // get the fade level as an integer
    // If we have timeouts going from a previous operation
    if(idElementTimeout && idElementTimeout == _elementID)
    {
        if(hideElementTimeout)
        {
            clearTimeout(hideElementTimeout);
        }
        if(valueElementTimeout)
        {
            clearTimeout(valueElementTimeout);
        }
    }
    
    // Step 2.  Determine the background color
    var szBackgroundColor = "#fffbcf";
    switch(_fadeLevel)
    {
        case 3:
            szBackgroundColor = "#fffbcf";
            break;
        case 2:
            szBackgroundColor = "#fffbe5";
            break;
        case 1:
            szBackgroundColor = "#fffbf3";
            break;
        case 0:
            // We're done fading, show a standard white background and set the element to hide
            szBackgroundColor = "#fff";
            idElementTimeout = _elementID;
			if(_hideAfterCompletion == 1)
			{
            	hideElementTimeout = setTimeout("hideElement('"+_elementID+"')", 3000);
			}
            if(_resetText)
            {
               valueElementTimeout = setTimeout("setValue('"+_elementID+"', '"+_resetText+"')", 3050);
            }
            break;
        default:
            // We don't understand this value, so we'll reset it and start at 3
            szBackgroundColor = "#fffbcf";
            _fadeLevel = 3;
            break;
    }
    // Update the _fadeLevel for the next pass
    _fadeLevel = _fadeLevel - 1;
    
    // Step 3.  Change the background color of the element
    objElement.style.backgroundColor = szBackgroundColor;
    
    // Step 4.  Call this same method again with the new fade level
    if(_fadeLevel >= 0)
    {
        if(_resetText)
        {
            setTimeout("fadeElement('"+_elementID+"','"+_fadeLevel+"','"+_resetText+"', '"+_hideAfterCompletion+"')", 1500);
        }
        else
        {
            setTimeout("fadeElement('"+_elementID+"','"+_fadeLevel+"',null,'"+_hideAfterCompletion+"')", 1500);
        }
    }
}

// Checks if a user submits a form by pressing enter
function checkSubmitForm(e)
{    
	var keyCode = 0;
	if(window.event) keyCode = e.keyCode;
	else if(e.which) keyCode = e.which;
	if(keyCode == 13) return true;
	return false;
}

// Clears a dropdown of all its entries
function clearDropDown(objDropDown)
{
    if(!objDropDown || !objDropDown.length || !objDropDown.options)
    {
        return;
    }
    
    for(var j = objDropDown.length; j >= 0; j--)
    {
        objDropDown.options[j] = null;
    }
}

// Populates a dropdown using a string with format Value~Name|Value2~Name2|Value3~Name3
function populateDropDown(objDropDown, _delimitedString)
{
    if(!_delimitedString || !objDropDown)
    {
        return;
    }
    // Split the response (Value~Name|Value~Name|Value~Name) up into the individual brands
    var a_AllItems = _delimitedString.split('|');
    if(!a_AllItems || !a_AllItems.length)
    {
        // Unable to parse the delimited string
        return;
    }
    
    for(var i = 0; i < a_AllItems.length; i++)
    {
        // Make sure this row has information
        if(!a_AllItems[i])
        {
            continue;
        }
        
        // Split up the Value~Name into individual elements
        var a_ItemInfo = a_AllItems[i].split('~');
        if(a_ItemInfo.length < 2)
        {
            continue;
        }
                
        // Create a new option element for the dropdown
        var objDropDownOption = document.createElement("option");
        
        // Add the value to the drop down option
        if(a_ItemInfo[0]) { objDropDownOption.setAttribute('value', a_ItemInfo[0]); }
        else { objDropDownOption.setAttribute('value', ''); }
        
        // Add the text to the drop down option
        objDropDownOption.appendChild(document.createTextNode(a_ItemInfo[1]));
        
        // Append the new option to the dropdown
        objDropDown.appendChild(objDropDownOption);
    }
}

// Removes leading whitespaces
function LTrim( value ) {
	if(!value || !value.replace) { return value; }
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	if(!value || !value.replace) { return value; }
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	if(!value || !value.replace) { return value; }
	return LTrim(RTrim(value));
	
}

// Gets an element by it's id on the page
function getElement(id)
{
    if (document.getElementById)
        var returnVar = document.getElementById(id);
    else if (document.all)
        var returnVar = document.all[id];
    else if (document.layers)
        var returnVar = document.layers[id];
    return returnVar;
}