/* ************************************************
 * Script: pagedComments.js
 * --------------------
 *
 * All JavaScript required for the pagedComments Tag.
 *
 **************************************************/
var emptyString = /^\s*$/ ;
var coID="";
function trim(str){
  return str.replace(/^\s+|\s+$/g, '');
}

function validateUrl(sInput) {
    var testString = sInput.value;
    if (emptyString.test(testString)){
        // alert("Empty String");
        return true;
    } else if (testString == "Website URL") {
        return true;
    } else if (testString == "http://") {
        return true;
    } else {
        var sUrl = trim(testString);

        var url = /^(http:\/\/|https:\/\/){1}[0-9A-Za-z\.\-]*\.[0-9A-Za-z\.\-]*$/ ;
        if (!url.test(sUrl)) {
            return false;
        }
    }
    return true;
}
function validateString (sInput) {
	var testString = sInput.value;
    if (emptyString.test(testString)){
		return false;
	}
    return true;
}

function validateEmail (sInput) {
	//trim off whitespacing
	var testString = sInput.value
    var sEmail = trim(testString);

	var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
	if (!email.test(sEmail)) {
		return false;
	}
	return true;
}
//Cookie Stuff
function Get_Cookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ){
		return null;
	}
	if ( start == -1 ) return null; 
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
}

	// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function SetCookie(cookieName,cookieValue,nDays, path, domain) {
 	var today = new Date();
 	var expire = new Date();
 	if (nDays==null || nDays==0) nDays=1;
 		expire.setTime(today.getTime() + 3600000*24*nDays);
 		document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString()+";path="+path+";domain="+domain;
}
//End Cookie Stuff
function submitPagedCommentForm(form) {
	var errs=0;
	var msg = "Your submission can not be completed, please review the following:\n\n";
	var msgName = "Name is required to post a comment, E! Online members must provide their email and password to post a comment.\n";
	var msgMemeberID = "Invalid member id\n";
	var msgUrl = "The URL entered is invalid - URLs must begin with either http:// or https:// followed by a valid web addresses.";
	var msgEmail = "A valid email address is required to post your comment.\n";
	var msgComments = "Sorry, you can't post a blank comment.\n";

    var memberEmailPresent = validateString(document.user_comments.usrEmail);

  

   	if (!validateString(document.user_comments.commentTextArea)){
   		errs += 1;
   		msg += msgComments;
   	}
    if (!validateUrl(document.user_comments.usrHomePage)) {
   		errs += 1;
   		msg += msgUrl;
    }

       if (errs>0)  alert(msg);

   return (errs==0);
 }

function showAbuselinks(){
    var showSpans=document.getElementById('blog_comments_list').getElementsByTagName('span');
    for(var i=0;i<showSpans.length;i++){
	    showSpans[i].className='abuseon';
    }
	document.getElementById('hideabuselink').style.display='inline';
	document.getElementById('showabuselink').style.display='none';
}
function hideAbuselinks(){
    var showSpans=document.getElementById('blog_comments_list').getElementsByTagName('span');
    for(var i=0;i<showSpans.length;i++){
	    showSpans[i].className='abuselink';
    }
	document.getElementById('showabuselink').style.display='inline';
	document.getElementById('hideabuselink').style.display='none';
}

 var xmlHttp;
 var divTagID;

  // Do Sighting Action
 function doPagedCommenting(url,queryString,divTagIDIn) {

  /*alert("URL = " + url + "\n" +
         "queryString = " + queryString + "\n" +
         "divTagIDIn = " + divTagIDIn);*/

   divTagID = divTagIDIn;
   if (window.ActiveXObject) {
     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
   } else {
     xmlHttp = new XMLHttpRequest();
   }
   xmlHttp.open("POST",url,true);
   xmlHttp.onreadystatechange = handleStateChange;
   xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
   xmlHttp.send(queryString);
 }


  // Handle State Change
function handleStateChange()
{
	//alert("IN HANDLE STATE CHANGE");
	if (xmlHttp.readyState == 4) // COMPLETE
	{
		if (xmlHttp.status == 200) // SUCCESS
		{
			var result = xmlHttp.responseText;
			//alert("result="+result);
			var response = document.getElementById(divTagID);
			if (response.hasChildNodes())
			{
				response.removeChild(response.childNodes[0]);
			}
			response.innerHTML = result;
		}
		else
		{
			//TODO comment this out at somepoint.
            // alert("FAILURE");
			// alert("xmlHTTP.status: "+xmlHttp.status);

            //Proper error handling?
            alert("There was a problem submitting your comment");
            response.innerHTML = result;
        }
	}
}

  // Show Comments Page
 function doCommentPaging(sortBy,pageNo,contentUUID,divTagIDIn,successurl) {
   doPagedCommenting("/mystyle/services/ajaxAddPagedComment.jsp","sort_by=" + sortBy + "&page="+pageNo + "&uuid="+contentUUID + "&containerDivId="+divTagIDIn+"&loginSuccess="+successurl,divTagIDIn);
 }

// Post Blog
function postComment(divTagIDIn,isMember, coID) {
    var button = document.getElementById("blog_button");
    var origButton = button.innerHTML;
    button.innerHTML = "<span class='button_link'>Posting Comment...</span>";

    Delete_Cookie("PostCookie","/",".mystyle.com");
	SetCookie("PostCookie",coID,5,"/",".mystyle.com");
    var error="";
	var errorPrefix = "Please correct the following problems:\n\n"
	var userEmail = "";
    var blogMessage = document.user_comments.commentTextArea.value;

	if (isMember == 'false')
	{
        if (!validateString(document.user_comments.name) || 
            document.user_comments.name.value == 'Your name') { // MS-340
			error+="- A name is required to post your comment\n";
		}
	    if (!validateEmail(document.user_comments.usrEmail)) {
			error+="- A valid email address is required to post your comment\n";
		}
		else
		{
			userEmail = document.user_comments.usrEmail.value;
		}
	}

    if (!validateString(document.user_comments.commentTextArea)) {
		error+="- Sorry, you can't post a blank comment";
	}
    if (!validateUrl(document.user_comments.usrHomePage)) {
		if (validateString(error)) {
            error+="\n";
        }
        error+="- The URL entered is invalid - URLs must begin with either http:// or https:// followed by a valid web addresses.";
	}
    
    blogMessage = encodeURIComponent(blogMessage);
    var uuid = document.user_comments.uuid.value;
	var actionSection = document.user_comments.action_section.value;
    var sort_by = document.user_comments.sort_by.value;
    var successurl = document.user_comments.successpath.value;
    var userUrl = document.user_comments.usrHomePage.value;
	if (userUrl == 'Website URL') {
		userUrl = "";
	}
    var userName = document.user_comments.name.value;
	if (userName == 'Your name') {
		userName = "Anonymous";
	}
	var captchaEntry = hex_md5(document.getElementById('uword').value);
	//var queryString = "action_section="+actionSection+"&sort_by="+sort_by+"&name="+userName+"&usrHomePage="+userUrl+"&usrEmail="+userEmail+"&commentTextArea="+blogMessage+"&uuid="+uuid+"&containerDivId="+divTagIDIn+"&page=last&loginSuccess="+successurl+"&captchaEntry="+captchaEntry;
	//
    // CMS-592, pass image ID to ajaxAddPagedComment directly instead of using cookie
	//
    var queryString = "simgID=" + coID + "&" + "action_section="+actionSection+"&sort_by="+sort_by+"&name="+userName+"&usrHomePage="+userUrl+"&usrEmail="+userEmail+"&commentTextArea="+blogMessage+"&uuid="+uuid+"&containerDivId="+divTagIDIn+"&page=last&loginSuccess="+successurl+"&captchaEntry="+captchaEntry;

	if (error != "") {
        alert(errorPrefix+error);
        button.innerHTML = origButton; 
    } else {
        alert("Thank you for your comment.");
        //alert("Calling do commenting: " + queryString);
        //location.hash = "commentstart";
        doPagedCommenting("/mystyle/services/ajaxAddPagedComment.jsp",queryString,divTagIDIn);
	}
}

function loginAndPostComment(divTagIDIn, coID) {
	isMember = 'false';
    postComment(divTagIDIn,isMember, coID);
}

function changeButtonStatus()
{
	var buttonText = document.getElementById("anonPostButton");

	if (document.user_comments.passwd.value.length > 0)
		buttonText.innerHTML = 'Sign In & Post Comment';
	else
		buttonText.innerHTML = 'Post Comment';

}

function confirmAbuse(commentID)
{
	var lb_confirmAbuse = confirm ("Report this comment as inappropriate\n\nIf you find the content of this comment inappropriate and feel it should be removed from the E! Online site, let us know by clicking 'OK' below.  This will notify us and we can take appropriate action.");
	if (lb_confirmAbuse)
	{
		abuse(commentID);
		alert ("Thank you for your input\n\nThis commment has been reported.  We will review this information and take appropriate action");
	}
}

function abuse(commentId)
{
	//Element.hide("commentBlock_" + commentId);
	var myAjax = new Ajax.Request(globalDir + "services/abusemsg.jsp",
			{
				method: 'get',
				parameters: "commentid="+commentId
			});
}


