var focused = new Array();
var highlighted = new Array();

var titles = new Array();
var descriptions = new Array();

var tooManyChars=false;

var req;
var which;

var tokenName;
var token;
var timeCreated;

 function highlight(theTextField) {
 	if(theTextField.name == "titleTextarea") {
 		titles[theTextField.name] = theTextField.value;
 	} else if(theTextField.name == "descriptionTextarea") {
 		descriptions[theTextField.name] = theTextField.value;
 	}

 	theTextField.style.backgroundColor = "#D8E9F9";
 	highlighted[theTextField.name] = true;
 }


 function unhighlight(theTextField) {
 	if(!focused[theTextField.name]) {

 		if(theTextField.name == "titleTextarea") {
 			theTextField.value = titles[theTextField.name];
 			//setTimeout ( "cancelTitle()", 1000 );
             cancelTitle();
 			highlighted[theTextField.name] = false;
 		} else if(theTextField.name == "descriptionTextarea") {
 			theTextField.value = descriptions[theTextField.name];
 			//setTimeout ( "cancelDescription()", 1000 );
            cancelDescription();
 			highlighted[theTextField.name] = false;
 		}
 	}
 }

 function focusOn(theTextField) {
  	focused[theTextField.name] = true;
  	highlighted[theTextField.name] = true;

  	theTextField.style.backgroundColor = "#D8E9F9";
  	//theTextField.style.border = "1px inset gray";
  	theTextField.style.paddingLeft = "2px";

  	theTextField.select();

  	if(theTextField.name == "titleTextarea") {
  		titles[theTextField.name] = theTextField.value;
  		// theTextField.style.fontSize = 18 + "px";
  		// theTextField.style.fontWeight = "bold";

  		var hiddenButtonsDiv = document.getElementById("hiddenTitleButtonsDiv");
  		hiddenButtonsDiv.style.display = "block";

  	} else if(theTextField.name == "descriptionTextarea") {
  		descriptions[theTextField.name] = theTextField.value;
  		// theTextField.style.fontSize = 12 + "px";
  		theTextField.style.fontStyle = "normal";

  		var hiddenButtonsDiv = document.getElementById("hiddenDescriptionButtonsDiv");
  		hiddenButtonsDiv.style.display = "block";
  	}
  }

  function cancelTitle() {
  	cancel(document.getElementById("titleTextarea"));
  }

  function cancelDescription() {
  	cancel(document.getElementById("descriptionTextarea"));
  }

  function cancel(theTextField) {
  	if(theTextField.name == "titleTextarea") {
  		//theTextField.style.fontSize = "14px";
  		//theTextField.style.fontWeight = "bold";
  		theTextField.style.backgroundColor = "#ffffff";
  		// theTextField.style.border = "none";

  		theTextField.value = titles[theTextField.name];

  		highlighted[theTextField.name] = false;
  		focused[theTextField.name] = false;

  		var hiddenButtonsDiv = document.getElementById("hiddenTitleButtonsDiv");
  		hiddenButtonsDiv.style.display = "none";

  	} else if(theTextField.name == "descriptionTextarea") {
  		//theTextField.style.fontSize = "12px";
  		//theTextField.style.fontWeight = "normal";
  		theTextField.style.backgroundColor = "#ffffff";
  		//theTextField.style.border = "none";

  		theTextField.value = descriptions[theTextField.name];

  		highlighted[theTextField.name] = false;
  		focused[theTextField.name] = false;

  		var hiddenButtonsDiv = document.getElementById("hiddenDescriptionButtonsDiv");
  		hiddenButtonsDiv.style.display = "none";
  	}
  }
function deleteContentAsAdmin(contentId, contentTypeId)
{
//    alert("content id = " + contentId);
//    alert("content type id = " + contentTypeId);
    window.location.replace('/community/admin/adminFlaggedContent!deleteContent.action?contentId=' + contentId + '&contentTypeId=' + contentTypeId);
}
function deleteTopicAndPostAsAdmin(itemId)
{
//    alert("content id = " + contentId);
//    alert("content type id = " + contentTypeId);
    window.location.replace('/community/admin/adminFlaggedContent!deleteTopicsAndPosts.action?contentId=' + itemId);
}

function deleteMemberCommentAsAdmin(commentId, commentTypeId)
{
//    alert("CommentId = " + commentId);
//    alert("commentType = " + commentTypeId);
    if(commentTypeId == 1)   //content comment
    {
       window.location.replace('/community/admin/adminFlaggedContentComments!deleteContentComment.action?contentId=' + commentId);
    }else if(commentTypeId==2)//member comment
     {
       window.location.replace('/community/admin/adminFlaggedMemberComments!deleteMemberComment.action?contentId= '+commentId);
    }

 }
////////////////////SETS///////////////////////////////////
function addContentToSet(setSelect,contentId,args) {

        newSetId = setSelect.options[setSelect.selectedIndex].value;

        if(newSetId != -1 && newSetId != 'new'){
          BXmlHttp.quickRequest('/community/sets/addContentToSet.bt?contentId='+contentId+'&setId='+newSetId+args,processSetListUpdate,processSetListUpdate);
        }

        if(newSetId == 'new'){
          document.getElementById('addSet').style.display='block';
        }else{
          document.getElementById('addSet').style.display='none';
        }
}
function showAlbumCreatePage(){
    document.getElementById('addNewSet').style.display='block';
}

function removeContentFromSet(contentId,setId,args) {
      BXmlHttp.quickRequest('/community/sets/removeContentFromSet.bt?contentId='+contentId+'&setId='+setId+args,processSetListUpdate,processSetListUpdate);
}

function cancelNewSet(){
   document.getElementById('addSet').style.display='none';
   document.getElementById('addSetError').style.display='none';
   setSelect = document.getElementById('setSelect');
   setSelect.selectedIndex=0;
}

function cancelAlbum(){
   document.getElementById('addNewSet').style.display='none';
   document.getElementById('addSetError').style.display='none';
}

function addNewSet(contentId,args){
    newTitle = document.getElementById("setTitle").value;
   // newDesc = document.getElementById("setDescription").value;

    if(newTitle != ""){
        BXmlHttp.quickRequest('/community/sets/addNewSet.bt?contentId='+contentId+'&setTitle='+newTitle+'&setDescription='+args,processSetListUpdate,processSetListUpdate);

    }else{
        document.getElementById('addSetError').style.display='block';
    }

}

function processSetListUpdate(responseText){
	    document.getElementById("setList").innerHTML = responseText;
}


function checkIfEmptyAndPostURL(url,commentForm,divId)
{
    var commentValue = commentForm.comment.value;
    if(commentValue == '')
    {
        return false;
    }else
    {
       postUrl(url,commentForm,divId);
    }

}
function postUrl(url, theForm, divId) {
	which = divId;
	var queryString = "";
	for( var i = 0; i < theForm.length; i++) {
		if(i != 0) {
			queryString = queryString + "&";
		}


		var element = theForm.elements[i];
		queryString = queryString + element.name + "=" + escape(element.value);
		// need to do this for windows users
		queryString = queryString.replace(/%u2019/,"%27");
       // alert("length = " + element.value.length);
	}

    //alert(queryString);

	if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
		req.onreadystatechange = processStateChange;
		try {
			req.open("POST",url,true);
			req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		} catch (e) {
			alert(e);
		}
		req.send(queryString);

	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processStateChange;
			req.open("POST",url,true);
			req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			req.send(queryString);
		}
	}

    focused = new Array();


}

function processStateChange() {
	if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response

			document.getElementById(which).innerHTML = req.responseText;
		} else {
			alert("Problem: " + req.statusText);
		}
	}

}

function processFavoriteStateChange(responseText) {
	document.getElementById('contentFavoriteSpan').innerHTML = responseText;
}

function countText(textField){
   if(textField.name == "titleTextarea"){
      if(textField.value.length > 255){
        textField.value = textField.value.substring(0,255);
        tooManyChars = true;
      }else{
        tooManyChars = false;
      }
   }else if(textField.name == "descriptionTextarea"){
      if(textField.value.length > 10000){
        textField.value = textField.value.substring(0,10000);
        tooManyChars = true;
      }else{
        tooManyChars = false;
      }
   }
}

function addCategoryToContent(catSelect,contentId) {
    newCatId = catSelect.options[catSelect.selectedIndex].value;
    if(newCatId != -1){
      BXmlHttp.quickRequest("/community/content/addCategoryToContent.bt?contentId="+contentId+"&catId="+newCatId,addCategoryCallback,addCategoryCallback);
    }
}

function addCategoryCallback(responseText){
    var categoryTextNode = document.createTextNode(responseText);
    var categoryDisplayDiv = document.getElementById("categoryDisplay");
    var oldTextNode = categoryDisplayDiv.firstChild;
    if (oldTextNode != undefined) {
        categoryDisplayDiv.replaceChild(categoryTextNode,oldTextNode);
    } else {
        categoryDisplayDiv.appendChild(categoryTextNode);
    }
    // make sure delete is not hidden
    var hideButtonSpan = document.getElementById("categoryDelete");
    hideButtonSpan.style.display = '';
}

function removeCategoryFromContent(contentId) {
    BXmlHttp.quickRequest("/community/content/removeCategoryFromContent.bt?contentId="+contentId,removeCategoryCallback,removeCategoryCallback);
}

function removeCategoryCallback(responseText){
    if (responseText == "removed") {
        var categoryDisplayDiv = document.getElementById("categoryDisplay");
        var oldTextNode = categoryDisplayDiv.firstChild;
        categoryDisplayDiv.removeChild(oldTextNode);
        // and hide delete button
        var hideButtonSpan = document.getElementById("categoryDelete");
        hideButtonSpan.style.display = 'none';
    }
}

function createContentMarquee(contentArray) {

}

// makes a-synch request for comments page
function loadCommentsForContent(contentId, url, sortOrder) {
    var requestURL = url + '&contentId=' + contentId + '&sOr=' + sortOrder;
    BXmlHttp.quickRequest(requestURL,updateCommentsCallback,updateCommentsCallback);
}

// makes a-synch request for reverse favorites
function loadFavoritersForContent(contentId, url, sortOrder) {
    var requestURL = url + '&contentId=' + contentId;
    BXmlHttp.quickRequest(requestURL,updateCommentsCallback,updateCommentsCallback);
}


// callback for updating comments div
function updateCommentsCallback(responseText) {
    var commentsDiv = document.getElementById("commentDiv");
    commentsDiv.innerHTML = responseText;
}

// validate the upload video file form - simple validation
// to prevent user from having to wait for upload and then
// server-side validation to fail. also changes host for url
// to remote server
function validateUploadVideoFileRemoteForm(theForm) {

    // error message to be returned
    //var errorMessage = "";
    var errorMessages = new Array();

    // video must be present and correct file extension
    var videoFileField = theForm.videoFile;
   
if (videoFileField.value == "") {

        //errorMessage = errorMessage + "\nVideo is required.";
        errorMessages.push("Please select a video to upload.");
    }

if ((videoFileField.value != "") && (!validateVideoType(videoFileField.value))) {
        //errorMessage = errorMessage + "\nVideo type invalid. Valid types listed below.";
        errorMessages.push("Video filetype not currently supported. Supported filetypes listed below.");
    }

    // title must be present
    var titleField = theForm.title;
    if (titleField.value == "") {
        //errorMessage = errorMessage + "\nVideo is required.";
        errorMessages.push("Please provide a title for your video.");
    }

    // tags must be present and valid
    var tagsField = theForm.tags;
    if ((tagsField.value != "") && (!validateTags(tagsField.value))) {
        //errorMessage = errorMessage + "\nOnly letters and numbers in tags, please. Group multi-word tags in quotes.";
        errorMessages.push("Only letters and numbers in tags, please. Group multi-word tags in quotes.");
    }

	// terms must be agreed to
	// because terms are considered agreed to if someone clicks to submit, we don't need to check this... which is also breaking the form. 
	//var agreeToTerms = theForm.agreeToTerms;
	//alert("got the terms... " + agreeToTerms);
	//if (!agreeToTerms.checked){
//		errorMessages.push("You must agree to the terms and conditions.");
//		alert("there's an error here");
//	}
	// if no errors, change host name and submit
    if (errorMessages.length == 0) {
        theForm.action="/community/video/uploadVideoFileRemote.bt";
		return true;
    }
    // else write errors to page and return false
    else {
	    addErrorMessagesToDiv(errorMessages,"videoUploadErrorMessages");
        return false;
    }
}

// validate the upload audio file form - simple validation
// to prevent user from having to wait for upload and then
// server-side validation to fail.
function validateUploadAudioFileForm(theForm) {
    //var errorMessage = "";
    var errorMessages = new Array();

    // video must be present and correct file extension
    var audioFileField = theForm.audioFile;
    if (audioFileField.value == "") {
        errorMessages.push("Oops. You didn't pick a music file.");
    }
    if ((audioFileField.value != "") && (!validateAudioType(audioFileField.value))) {
        errorMessages.push("Audio filetype not currently supported. Supported filetypes listed below.");
    }

    // title must be present
    var titleField = theForm.title;
    if (titleField.value == "") {
        errorMessages.push("Oops. You didn't enter a title.");
    }

    // category must be present
    var categoryField = theForm.category;
    if (categoryField.value == "") {
        errorMessages.push("Oops. You didn't choose a category.");
    }

    // tags must be present and valid
    var tagsField = theForm.tags;
    if (tagsField.value == "") {
        errorMessages.push("Oops. You didn't tag your music file.");
    }
    if ((tagsField.value != "") && (!validateTags(tagsField.value))) {
        errorMessages.push("Only letters and numbers in tags, please. Group multi-word tags in quotes.");
    }

    // if no errors,submit
    if (errorMessages.length == 0) {
        return true;
    }
    // else write errors to page and return false
    else {
        addErrorMessagesToDiv(errorMessages,"audioUploadErrorMessages");
        return false;
    }
}

// adds a new errors node to a specified div
function addErrorMessagesToDiv(errorMessages, errorDivName) {
    var errorDiv = document.getElementById(errorDivName);

    // create unordered list - add class style
    var ulElement = document.createElement('ul');
    ulElement.className = 'systemErrors';

    // add each list item
    for (var i = 0; i < errorMessages.length; i++) {
        var liElement = document.createElement('li');
        var liTextNode = document.createTextNode(errorMessages[i]);
        liElement.appendChild(liTextNode);
        ulElement.appendChild(liElement);
    }

    // add list to div/replace - there could only be one there so grab first child
    if (errorDiv.hasChildNodes()) {
        var oldElement = errorDiv.firstChild;
        errorDiv.replaceChild(ulElement,oldElement);
    }
    else {
        errorDiv.appendChild(ulElement);
    }

}

// valid videos
var VALID_VIDEO_TYPE_REGEX = new RegExp(".flv|.mov|.wmv|.avi|.mpg|.mpeg|.mp4|.3gp|.3g2|.asf","i");

// validates video extension - simple validation, only validates if name contains
// above strings at the END, which should be most cases. server side is more thorough
function validateVideoType(filename) {
    // check on regex
    if (filename.match(VALID_VIDEO_TYPE_REGEX) != null)
        return true;
    else
        return false;
}

// valid audio
var VALID_AUDIO_TYPE_REGEX = new RegExp(".mp3","i");

// validates audio extension - simple validation, only validates if name contains
// above strings at the END, which should be most cases. server side is more thorough
function validateAudioType(filename) {
    // check on regex
    if (filename.match(VALID_AUDIO_TYPE_REGEX) != null)
        return true;
    else
        return false;
}

// count occurances of a string in another
function strCountOccurances(str,occStr) {
    count = 0;
    pos = str.indexOf(occStr);
    while ( pos != -1 ) {
       count++;
       pos = str.indexOf(occStr,pos+1);
    }

    return count;
}

var VALID_TAG_REGEX = new RegExp("^[a-zA-Z0-9\'\" ]+$");

// simple validation of tags, just checks for balanced quotes and
// only alphanums
function validateTags(tagsString) {
    // only can have an even number of quotes
    var totalQuotes = strCountOccurances(tagsString,"\'") + strCountOccurances(tagsString,'\"');
    if (totalQuotes % 2 != 0)
        return false;

    // only alphanumerics or quotes
    if (VALID_TAG_REGEX.exec(tagsString) == null)
        return false;

    // good
    return true;
}

// used to store anchor tags that are removed so they can be replaced later
var anchorTagArray = new Array();

// creates a form in the comments section to add a threaded comment
function showThreadedCommentForm(commentId,contentId,contentTypeId) {
    // create form
    var formElement = document.createElement('form');
    formElement.setAttribute('id','addComentForm'+commentId);

    // text area div
    var textAreaPElement = document.createElement('p');

    // text area creation - #(@(* you IE - I got this function off of http://www.easy-reader.net/archives/2005/09/02/death-to-bad-dom-implementations/
    var textAreaElement = document.createNamedElement('textarea','commentText');
    textAreaElement.setAttribute('cols','35');
    textAreaElement.setAttribute('rows','5');

    // submit button
    var submitButtonElement = document.createElement('input');
    submitButtonElement.setAttribute('type','button');
    submitButtonElement.setAttribute('value','Post Reply');
    // IE nonsense, doesn't support set attribute
    if (!submitButtonElement.attachEvent)
        submitButtonElement.setAttribute('onclick','submitThreadedComment(' + commentId + ',' + contentId + ',' + contentTypeId + ')');
    else
        submitButtonElement.onclick = function() {submitThreadedComment(commentId,contentId,contentTypeId)};

    // cancel button
    var cancelButtonElement = document.createElement('input');
    cancelButtonElement.setAttribute('type','button');
    cancelButtonElement.setAttribute('value','Cancel');
    cancelButtonElement.onclick = function() {destroyThreadedCommentForm(commentId)};

    // append all to form element
    textAreaPElement.appendChild(textAreaElement);
    formElement.appendChild(textAreaPElement);
    formElement.appendChild(submitButtonElement);
    formElement.appendChild(cancelButtonElement);

    // create div and put form inside of it
    var formDiv = document.createElement('div');
    formDiv.id = 'threadedReplyTo' + commentId;
    formDiv.className= 'commentReplyToLink';
    formDiv.appendChild(formElement);

    // put div in table cell
    var tableCell = document.getElementById('commentInfoTD' + commentId);
    tableCell.appendChild(formDiv);

    // update link div - need to remove a and store it in an array so we can pull it out again later.
    // the array is a 2-d array that looks like - [(commentId#1,anchorTag#1),(commentId#2),(anchorTag#2)...]
    var linkDiv = document.getElementById('replyLinkTo' + commentId);
    linkDiv.className = 'commentReplyLinkClicked';
    var anchorTag = document.getElementById('replyAnchorTag' + commentId);
    var idToAnchorTagArray = new Array(commentId,anchorTag);
    anchorTagArray.push(idToAnchorTagArray);

    // create static text to replace the anchor
    var staticTextSpan = document.createElement('span');
    staticTextSpan.id = 'commentReplyStaticTextSpan' + commentId;
    var staticTextTextNode = document.createTextNode(anchorTag.firstChild.nodeValue);
    staticTextSpan.appendChild(staticTextTextNode);

    // update the link Div
    linkDiv.replaceChild(staticTextSpan,anchorTag);

    return false;
}

// creates a form in the comments section to add a threaded comment
function showMediaThreadedCommentForm(commentId,contentId,contentTypeId) {
    // create form
    var formElement = document.createElement('form');
    formElement.setAttribute('id','addComentForm'+commentId);

    // text area div
    var textAreaPElement = document.createElement('p');

    // text area creation - #(@(* you IE - I got this function off of http://www.easy-reader.net/archives/2005/09/02/death-to-bad-dom-implementations/
    var textAreaElement = document.createNamedElement('textarea','commentText');
    textAreaElement.setAttribute('cols','35');
    textAreaElement.setAttribute('rows','5');

    // submit button
    var submitButtonElement = document.createElement('input');
    submitButtonElement.setAttribute('type','button');
    submitButtonElement.setAttribute('value','Post Reply');
    // IE nonsense, doesn't support set attribute
    if (!submitButtonElement.attachEvent)
        submitButtonElement.setAttribute('onclick','submitThreadedComment(' + commentId + ',' + contentId + ',' + contentTypeId + ')');
    else
        submitButtonElement.onclick = function() {submitThreadedComment(commentId,contentId,contentTypeId)};

    // cancel button
    var cancelButtonElement = document.createElement('input');
    cancelButtonElement.setAttribute('type','button');
    cancelButtonElement.setAttribute('value','Cancel');
    cancelButtonElement.onclick = function() {destroyMediaThreadedCommentForm(commentId)};

    // append all to form element
    textAreaPElement.appendChild(textAreaElement);
    formElement.appendChild(textAreaPElement);
    formElement.appendChild(submitButtonElement);
    formElement.appendChild(cancelButtonElement);

    // create div and put form inside of it
    var formDiv = document.createElement('div');
    formDiv.id = 'threadedReplyTo' + commentId;
    formDiv.appendChild(formElement);

    // put div in table cell
    var tableCell = document.getElementById('commentInfoFont' + commentId);
    tableCell.appendChild(formDiv);

    // update link div - need to remove a and store it in an array so we can pull it out again later.
    // the array is a 2-d array that looks like - [(commentId#1,anchorTag#1),(commentId#2),(anchorTag#2)...]
    var anchorTag = document.getElementById('replyAnchorTag' + commentId);
    var idToAnchorTagArray = new Array(commentId,anchorTag);
    anchorTagArray.push(idToAnchorTagArray);

    // create static text to replace the anchor
    var staticTextSpan = document.createElement('span');
    staticTextSpan.id = 'commentReplyStaticTextSpan' + commentId;
    var staticTextTextNode = document.createTextNode(anchorTag.firstChild.nodeValue);
    staticTextSpan.appendChild(staticTextTextNode);

    // update the link Div
    tableCell.replaceChild(staticTextSpan,anchorTag);

    return false;
}

// gets rid of a threaded comment form
function destroyThreadedCommentForm(commentId) {

    // remove the form
    var tableCell = document.getElementById('commentInfoTD' + commentId);
    var replyDiv = document.getElementById('threadedReplyTo' + commentId);
    tableCell.removeChild(replyDiv);

    // update link div - get the anchor tag out of the array to replace the span
    var linkDiv = document.getElementById('replyLinkTo' + commentId);
    linkDiv.className = 'commentReplyLinkNotClicked';

    for (var i = 0; i < anchorTagArray.length; i++) {
        var commentIdToAnchorArray = anchorTagArray[i];
        if ((commentIdToAnchorArray != null) && (commentIdToAnchorArray[0] == commentId)) {
            var staticTextSpan = document.getElementById('commentReplyStaticTextSpan'+commentId);
            linkDiv.replaceChild(commentIdToAnchorArray[1],staticTextSpan);
            anchorTagArray[i] = null;
        }
    }
}

// gets rid of a threaded comment form
function destroyMediaThreadedCommentForm(commentId) {

    // remove the form
    var tableCell = document.getElementById('commentInfoFont' + commentId);
    var replyDiv = document.getElementById('threadedReplyTo' + commentId);
    tableCell.removeChild(replyDiv);

    // update link div - get the anchor tag out of the array to replace the span
    var linkFont = document.getElementById('commentInfoFont' + commentId);
    linkFont.className = 'commentReplyLinkNotClicked';

    for (var i = 0; i < anchorTagArray.length; i++) {
        var commentIdToAnchorArray = anchorTagArray[i];
        if ((commentIdToAnchorArray != null) && (commentIdToAnchorArray[0] == commentId)) {
            var staticTextSpan = document.getElementById('commentReplyStaticTextSpan'+commentId);
            linkFont.replaceChild(commentIdToAnchorArray[1],staticTextSpan);
            anchorTagArray[i] = null;
        }
    }
}

// submits a threaded comment
function submitThreadedComment(commentId, contentId, contentTypeId) {

    // get the form and append the value to url
    var threadedCommentForm = document.getElementById('addComentForm'+commentId);

    var textAreaEl;
    var formElements = threadedCommentForm.elements;
    for (var i = 0; i < formElements.length; i++) {
        if (formElements[i].name == 'commentText') {
            textAreaEl = formElements[i];
        }
    }

    var commentText = escape(textAreaEl.value);

    var commentSubmitURL = '/community/content/comment/submit.bt?comment=' + commentText
            + '&contentId=' + contentId + '&parentId=' + commentId + "&contentTypeId="
            + contentTypeId;

    BXmlHttp.quickRequest(commentSubmitURL,threadedCommentCallback,threadedCommentCallback);
}

// callback for updating threaded comments div
function threadedCommentCallback(responseText) {
    var commentsDiv = document.getElementById("commentDiv");
    commentsDiv.innerHTML = responseText;
}

document.createNamedElement = function(type, name) {
  var element;
  try {
    element = document.createElement('<'+type+' name="'+name+'">');
  } catch (e) { }
  if (!element || !element.name) { // Not in IE, then
    element = document.createElement(type)
    element.name = name;
  }
  return element;
}

// checks to see if add to set is needed after a change to set dropdown on permalink
// page
function handleAddToSet() {
    // look for elements first
    if (document.getElementById("setSelect") &&
            document.getElementById("addSet")) {
        var setSelectEl = document.getElementById("setSelect");
        // -2 == add new set
        if (setSelectEl.value == -2) {
            //var addSetDivEl = document.getElementById("addSet");
            //addSetDivEl.style.display="block";
            photoPage.openBox();
        }
    } else {
        alert("you need to enable javascript to add content to a set!");
    }
}

// checks to see if add to set is needed after a change to set dropdown on permalink
// page
function handlePhotoAddToSet() {
    // look for elements first
    if (document.getElementById("albumChooser")) {

        var setSelectEl = document.getElementById("albumChooser");
        // -2 == add new set
        if (setSelectEl.value == -2) {
            //var addSetDivEl = document.getElementById("addSet");
            //addSetDivEl.style.display="block";
            photoPage.openBox();
        }
    } else {
        alert("you need to enable javascript to add content to a set!");
    }
}

function addNewSetForNewContent(contentId) {
    newTitle = document.getElementById("setTitle").value;
    // newDesc = document.getElementById("setDescription").value;

    if (newTitle != "") {
        BXmlHttp.quickRequest('/community/sets/addNewSetForNewContent.bt?contentId=' + contentId + '&setTitle=' + newTitle + '&setDescription=', addNewSetToList, addNewSetToList);
    } else {
        document.getElementById('addSetError').style.display = 'block';
    }

}



//add new sets (works on both photo and video upload pages)
function addNewSetWithNoContentAjax(contentTypeId) {
	//$('addSetForm').setDescription.value="test";
    //var newTitle = document.getElementById("setTitle").value;
    var newTitle = $('addSetForm').setTitle.value;
    //var newDesc = document.getElementById("setDescription").value;
    var newDesc = $('addSetForm').setDescription.value;
	if (newTitle != "") {
        var urlToSubmit = '/community/sets/addNewEmptySet.bt';
        var formValues = $('addSetForm').serialize(true);
        var response = new Ajax.Request(urlToSubmit, {method: 'post', parameters: formValues, onSuccess:updateAlbumLists});
        $('addSetForm').setTitle.value = "";
        $('addSetForm').setDescription.value = "";
        
    } else {
        document.getElementById('addSetError').style.display = 'block';
    }
}

function openAddSetOverlayDialog(contentID) {
	overlayUI();
	
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','addSetOverlayDialog');
	objOverlay.style.display = 'none';

	var objOverlayForm = document.createElement('form');
	objOverlayForm.setAttribute('id', 'addSetForm');
	objOverlayForm.setAttribute('method', 'post');
	objOverlayForm.setAttribute('action', '#');

	$$('body')[0].appendChild(objOverlay);
	$('addSetOverlayDialog').appendChild(objOverlayForm);
	$('addSetForm').onsubmit = function() { addNewSetWithNoContentAjax(contentID); return false; };
	$('addSetForm').update($('addSetOverlayDialogContents').innerHTML);

	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var dialogBoxTop = arrayPageScroll[1] + ( Math.abs(arrayPageSize[3] -  $('addSetOverlayDialog').getHeight()) / 2 );
	var dialogBoxWidth = 400;
	var dialogBoxLeft = ((arrayPageSize[2] / 2) - (dialogBoxWidth / 2)) + arrayPageScroll[0];
	$('addSetOverlayDialog').style.top = dialogBoxTop +"px";
	$('addSetOverlayDialog').style.left = dialogBoxLeft +"px";
	$('addSetOverlayDialog').setStyle({position: 'absolute', zIndex: 100});

	$('addSetOverlayDialog').show();
}

function closeAddSetOverlayDialog() {
	$('addSetOverlayDialog').hide();
	$('addSetOverlayDialog').remove();
	closeOverlayUI();
}



//email overlay for permalinks
function openEmailContentOverlayDialog() {
	overlayUI();

	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','emailContentOverlayDialog');
	objOverlay.style.display = 'none';

	var objOverlayForm = document.createElement('form');
	objOverlayForm.setAttribute('id', 'emailContentForm');
	objOverlayForm.setAttribute('method', 'post');
	objOverlayForm.setAttribute('action', '#');

	$$('body')[0].appendChild(objOverlay);
	$('emailContentOverlayDialog').appendChild(objOverlayForm);
	$('emailContentForm').onsubmit = function() { sendEmailContent(); return false; };
	$('emailContentForm').update($('emailContentOverlayDialogContents').innerHTML);

	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var dialogBoxTop = arrayPageScroll[1] + ( Math.abs(arrayPageSize[3] -  $('emailContentOverlayDialog').getHeight()) / 2 );
	var dialogBoxWidth = 400;
	var dialogBoxLeft = ((arrayPageSize[2] / 2) - (dialogBoxWidth / 2)) + arrayPageScroll[0];
	$('emailContentOverlayDialog').style.top = dialogBoxTop +"px";
	$('emailContentOverlayDialog').style.left = dialogBoxLeft +"px";
	$('emailContentOverlayDialog').setStyle({position: 'absolute', zIndex: 100});

	$("emailContentOverlayDialog").show();
}

function closeEmailContentOverlayDialog() {
    $('emailContentOverlayDialog').hide();
    $('emailContentOverlayDialog').remove();
    closeOverlayUI();
}

function sendEmailContent() {
    var email = $('emailContentForm').emailContentTo.value;
    var errorFlag = '';
    var valid = '';
    var emailList = email.split(",");

    if (email == '') {
        errorFlag = 'empty';
    } else {
        for (var i = 0; i < emailList.length; i++) {
            valid = validateEmailAddress(emailList[i].strip());
            if (!valid) {
                errorFlag = 'invalid';
            }
        }
    }

    if (errorFlag == 'empty') {
        $('emailContentError').update('<div class=\"systemError\" style=\"margin-bottom: 0; margin-top: 20px;\">You must enter at least one e-mail address.</div>');
    } else if (errorFlag == 'invalid') {
        $('emailContentError').update('<div class=\"systemError\" style=\"margin-bottom: 0; margin-top: 20px;\">All e-mail addresses must be valid. Multiple e-mail addresses must be separated by commas.</div>');
    } else {
        var formValues = $('emailContentForm').serialize();
        var sendEmailRequest = new Ajax.Request('/community/emailToAFriend/sendEmail.bt', {method: 'post', parameters: formValues});
        $('emailContentError').hide();
        $('emailContentNotify').update('<div class=\"systemError\" style=\"margin-bottom: 0; margin-top: 20px;\">Your e-mail has been sent.</div>');
    }

}



function updateAlbumLists(originalRequest) {
    //alert("In updateAlbumLists");
    var response = originalRequest.responseText;
    //alert(response);
    results = response.split("||");
    //alert(document.getElementById("setToken").value);
    document.getElementById("setToken").value = results[0];
    //alert(document.getElementById("setToken").value);
    //alert("setTokenTime :" +document.getElementById("setTokenTime").value);
    document.getElementById("setTokenTime").value = results[1];
    //alert("setTokenTime :" +document.getElementById("setTokenTime").value);
    document.getElementById("select_album").innerHTML = results[2];
    //alert(document.getElementById("select_album").innerHTML);
   //    var album = document.getElementById("select_album");
    //    new Insertion.Top("select_album",response);
}

// takes set id, adds it to list of choices with title
function addNewSetToList(newId){
    // get set name from form
    var setTitleEl = document.getElementById("setTitle");
    var newTitle = setTitleEl.value;

    // get select
    var setSelectEl = document.getElementById("setSelect");

    // create new option
    var setOptionEl = document.createElement("option");
    setOptionEl.setAttribute("value",newId);
    setOptionEl.setAttribute("selected","selected");
    var setOptionTxt = document.createTextNode(newTitle);
    setOptionEl.appendChild(setOptionTxt);

    // before adding, need to unset "selected" in desired
    var selectOptions = setSelectEl.options;
    for (var i = 0; i < selectOptions.length; i++) {
        var currentOption = selectOptions[i];
        if (currentOption.getAttribute("selected"))
            currentOption.removeAttribute("selected");
    }

    // now, add the new option to the list
    setSelectEl.appendChild(setOptionEl);

    // hide form to add and reset title
    var addSetDivEl = document.getElementById("addSet");
    addSetDivEl.style.display="none";
    setTitleEl.value="";
}

// displays upload progress bar
function showPhotoUploadProgressBar(form) {
    // disable the submit button

    submitButton = document.getElementById('uploadButton');
    submitButton.className="inactiveButton";
    submitButton.disabled=true;

    // create progress bar - two divs, one border and one
    // inside. the inside has width 0% to start and will grow
    // in the AJAX function
    var progressBarAndFooterDiv = document.createElement("div");
    progressBarAndFooterDiv.id = "progressBarAndFooterDiv";

    var progressBarBorderDiv = document.createElement("div");
    progressBarBorderDiv.id = "progressBarBorderDiv";
    var progressBarDiv = document.createElement("div");
    progressBarDiv.id = "progressBarDiv";
    progressBarBorderDiv.appendChild(progressBarDiv);
    progressBarDiv.style.width="0%";

    // footer text for progress bar
    var progressBarFooterNode = document.createElement("p");
    progressBarFooterNode.id = "progressBarFooterNode";
    progressBarFooterNode.className = "uploadingNotInProgressText";
    var progressBarFooterTextNode = document.createTextNode("Upload starting...");
    progressBarFooterNode.appendChild(progressBarFooterTextNode)

    // add to div
    progressBarAndFooterDiv.appendChild(progressBarBorderDiv);
    progressBarAndFooterDiv.appendChild(progressBarFooterNode);

    // add to form
    //var parent = document.getElementById("uploadPhotoFormSubmissionCell");
    var parent = document.getElementById("uploadProgressBar");
    parent.appendChild(progressBarAndFooterDiv);

    // the updater will handle the ajax call to update progress
    window.setInterval("updateUploadBarManager()",5000);
    form.submit();
    return true;
}

// validate, then create progress bar
function handleVideoUploadSubmission(theForm) {
 
var pass = validateUploadVideoFileRemoteForm(theForm);
    
    if (pass == false)
        return false;

    showMediaUploadProgressBar('video');

    theForm.submit();
    return true;
}

// validate, then create progress bar
function handleAudioUploadSubmission(theForm) {
    var pass = validateUploadAudioFileForm(theForm);

    if (pass == false)
        return false;

    showMediaUploadProgressBar('audio');
    return true;
}

function showMediaUploadProgressBar(type) {
    // disable the submit button
    submitButton = document.getElementById('uploadButton');
    submitButton.className="inactiveButton";
    submitButton.disabled=true;

    // create progress bar - two divs, one border and one
    // inside. the inside has width 0% to start and will grow
    // in the AJAX function
    var progressBarAndFooterDiv = document.createElement("div");
    progressBarAndFooterDiv.id = "mediaUploadProgressBarAndFooterDiv";

    var progressBarBorderDiv = document.createElement("div");
    progressBarBorderDiv.id = "progressBarBorderDiv";
    var progressBarDiv = document.createElement("div");
    progressBarDiv.id = "progressBarDiv";
    progressBarBorderDiv.appendChild(progressBarDiv);
    progressBarDiv.style.width="0%";

    // footer text for progress bar
    var progressBarFooterNode = document.createElement("p");
    progressBarFooterNode.id = "progressBarFooterNode";
    progressBarFooterNode.className = "uploadingNotInProgressText";
    var progressBarFooterTextNode = document.createTextNode("Upload starting...");
    progressBarFooterNode.appendChild(progressBarFooterTextNode)

    // add to div
    progressBarAndFooterDiv.appendChild(progressBarBorderDiv);
    progressBarAndFooterDiv.appendChild(progressBarFooterNode);

    // add to form
//    var parent = document.getElementById("uploadMediaFileForm");

    var parent = document.getElementById("uploadProgressBar");

    parent.appendChild(progressBarAndFooterDiv);

    // the updater will handle the ajax call to update progress
    window.setInterval("updateUploadBarManager()",5000);

    return true;
}

// this initiates AJAX call to update the upload bar
function updateUploadBarManager() {
    // I apologize but this is super ghetto. IE will always cache the AJAX result, so for IE we will
    // make a dummy param and tack it onto the url, so that it doesn't hit the cache
    var url = '/community/content/uploadStatus.bt?dummy=' + new Date().getTime();

    makeAJAXRequestForXML(url,handleUploadStatusUpdate);
}

// AJAX callback- will update the progress bar based upload status from the sever
function handleUploadStatusUpdate(responseXML) {
    // get the percent and extend the progress bar div
    var percent = getTextValueForElementFromXML("percent",responseXML);
    var progressBarDiv = document.getElementById("progressBarDiv");
    var widthValue = percent + "%";
    progressBarDiv.style.width=widthValue;

    // text rep of progress for footer
    var statusText = getTextValueForElementFromXML("display",responseXML);

    // is it done or not?
    var doneText = getTextValueForElementFromXML("done",responseXML);

    // add text
    var progressBarFooterNode = document.getElementById("progressBarFooterNode");
    var oldTextNode = progressBarFooterNode.firstChild;
    var newTextNode = document.createTextNode(statusText);
    progressBarFooterNode.replaceChild(newTextNode,oldTextNode);

    // if it's not done, change the class of the paragraph
    if (doneText != 'done') {
        progressBarFooterNode.className = "uploadingInProgressText";
    } else {
        progressBarFooterNode.className = "uploadingNotInProgressText";
    }
}

function flagContent(contentId,flagType){
	if(flagType == 'flag'){
		BXmlHttp.quickRequest('/community/flagItems/flagContent.bt?method=flagContent&contentId='+contentId,flagCallback,flagCallback);
	} else {
		BXmlHttp.quickRequest('/community/content/approveFlagged.bt?contentId='+contentId,flagCallback,flagCallback);
	}
}

function flagCallback(responseText){
    //do nothing
    //document.getElementById("inappropriateDiv").innerHTML = responseText;
}

var flaggedGroupId;

function flagForumPost(forumEntryId,groupId){
    flaggedGroupId = forumEntryId;
    var action = '/community/flagItems/flagContent.bt?method=flagGroupForumEntryAndPost&forumEntryId='+forumEntryId+'&groupId='+groupId+'&'+tokenName+'='+token+'&timeTokenGenerated='+timeCreated;
	var regRequest = new Ajax.Request(action, {onComplete:refreshForumPosts});
}

function flagForumTopic(forumEntryId,groupId){
    flaggedGroupId = forumEntryId;
    var action = '/community/flagItems/flagContent.bt?method=flagGroupForumEntryAndPost&forumEntryId='+forumEntryId+'&groupId='+groupId+'&'+tokenName+'='+token+'&timeTokenGenerated='+timeCreated;
	var regRequest = new Ajax.Request(action, {onComplete:refreshTopics});
}

function refreshForumPosts(originalRequest){
	if(originalRequest.status==403){
		var response = originalRequest.responseText;
		results = response.split("||");
		token = results[0];
		timeCreated = results[1];
		$('flagForumPostNotify' + flaggedGroupId).update(results[2]);
		closeOverlayConfirmation();
		return false;  
	}
	else{
		$('flagForumPostNotify' + flaggedGroupId).update('<div class=\"systemError\" style=\"margin-bottom: 0;\">Thank you for reporting this post.</div>');
		closeOverlayConfirmation(); 
	    overlayConfirmation('flagPostConfirmation${entry.id}');
		return false; 
	}
}

function refreshTopics(originalRequest){
	if(originalRequest.status==403){
		var response = originalRequest.responseText;
		results = response.split("||");
		token = results[0];
		timeCreated = results[1];
		$('flagForumPostNotify' + flaggedGroupId).update(results[2]);
	}
	else{
		$('flagForumPostNotify' + flaggedGroupId).update('<div class=\"systemError\" style=\"margin-bottom: 0;\">Thank you for reporting this post.</div>');
	}
}
function flagPostCallback(responseText){
	var linkId = 'flagLink' + flaggedGroupId;
	document.getElementById(linkId).innerHTML = responseText;
}

function changeContentPermissionFromSelect(contentId,theSelect) {
	for (var i =0; i < theSelect.options.length; i++) {
		if (theSelect.options[i].selected) {
			BXmlHttp.quickRequest(
        	'/community/content/updatePermission.bt?contentId='+contentId+'&permission='+theSelect.options[i].value,
	        permissionCallback,
    	    permissionCallback
		    );
		}
	}
}

function changePermission(newPermission,contentId){
    BXmlHttp.quickRequest(
        '/community/content/updatePermission.bt?contentId='+contentId+'&permission='+newPermission,
        permissionCallback,
        permissionCallback
    );
}

function permissionCallback(responseText){
    // do nothing
}

function deleteComment(commentId,contentId){
    which = 'commentDiv';
    BXmlHttp.quickRequest(
        '/community/content/comment/delete.bt?commentId='+commentId + '&contentId=' + contentId,
        function(responseXML) {
            document.getElementById(which).innerHTML = responseXML;
        }
    );
}

function newFocusTab(index) {
    if(index==1) {
        document.getElementById('commentTab').className = 'tabActive';
        document.getElementById('favoritedTab').className = 'tabInactive';
    }
    else {
        document.getElementById('commentTab').className = 'tabInactive';
        document.getElementById('favoritedTab').className = 'tabActive';
    }
}

function contentNewFocusTab(index) {
    if(index==1) {
        document.getElementById('similarContentTab').className = 'activeContentTab';
        document.getElementById('memberContenttTab').className = 'inactiveContentTab';
    }
    else {
        document.getElementById('similarContentTab').className = 'inactiveContentTab';
        document.getElementById('memberContenttTab').className = 'activeContentTab';
    }
}

function showMoreEmbeds() {
    var htmlRow = document.getElementById('htmlCode');
    var bbRow = document.getElementById('bbCode');
    var howTosRow = document.getElementById('howTos');
    var lessSpan = document.getElementById('lessEmbeds');
    var moreSpan = document.getElementById('moreEmbeds');

    htmlRow.className='shownRow';
    bbRow.className='shownRow';
    howTosRow.className='shownRow';
    lessSpan.className='showSpan';
    moreSpan.className='hideSpan';
}

function showLessEmbeds() {
    var htmlRow = document.getElementById('htmlCode');
    var bbRow = document.getElementById('bbCode');
    var howTosRow = document.getElementById('howTos');
    var lessSpan = document.getElementById('lessEmbeds');
    var moreSpan = document.getElementById('moreEmbeds');

    htmlRow.className='hiddenRow';
    bbRow.className='hiddenRow';
    howTosRow.className='hiddenRow';
    lessSpan.className='hideSpan';
    moreSpan.className='showSpan';
}

function doRating(contestId, contentId, contestContentId, rating){
    //var urlStr = '/contest/rateIt.bt?contestContentId='+contestContentId+'&rating='+rating+'&contestId='+contestId+'&contentId='+contentId;
    var urlStr = '/community/contest/rateIt.bt?contestId='+contestId+'&contentId='+contentId+'&contestContentId='+contestContentId+'&rating='+rating;
    BXmlHttp.quickRequest(urlStr, ratingCallback, ratingCallback);
}

function ratingCallback(responseText){
    document.getElementById("ratingsDiv").innerHTML = responseText;
}

function hideContentFromSearch(contentId, code) {
    var url = '/community/content/hideContentFromSearch.bt?contentId=' + contentId + '&hide=' + code;

    makeAJAXRequestForXML(url,handleHideContentFromSearch);

    // display msg while waiting
    var parElement = document.getElementById('hideFromSearchP' + contentId);
    var anchorElement = document.getElementById('hideFromSearchLink' + contentId);
    var msgNode = document.createTextNode('Hiding...');
    parElement.replaceChild(msgNode,anchorElement);

    return false;
}

function handleHideContentFromSearch(responseXML) {
    // text rep of progress for footer
    var statusText = getTextValueForElementFromXML("success",responseXML);

    // display confirm msg
    var message = '';
    if (statusText == 'true') {
        var contentId = getTextValueForElementFromXML("contentId",responseXML);
        var hide = getTextValueForElementFromXML("hide",responseXML);

        if (hide == '0') {
            message = 'Content no longer hidden from search. If you made a mistake, refresh the page to hide.';
        } else {
            message = 'Content hidden from search. If you made a mistake, visit the permalink page to unhide. If you hid this from the permalink page, refresh the page to unhide it.';
        }
    } else {
        message = 'There was a problem hiding the content. Please refresh the page and try again. If the problem persists see a developer.';
    }

    var parElement = document.getElementById('hideFromSearchP' + contentId);
    var msgNode = document.createTextNode(message);
    clearAllChildren(parElement);
    parElement.appendChild(msgNode);
}

function openDeleteContent() {
	Effect.Appear('deleteContentOverlay');
}

function closeDeleteContent() {
	Effect.Squish('deleteContentOverlay');
}

function openLinkContent() {
	Effect.Appear('linkContentOverlay');
}

function closeLinkContent() {
	Effect.Squish('linkContentOverlay');
}

function openEmailContent() {
	Effect.Appear('emailContentOverlay');
}

function closeEmailContent() {
	Effect.Squish('emailContentOverlay');
}

function openEmbedContent() {
	Effect.Appear('embedContentOverlay');
}

function closeEmbedContent() {
	Effect.Squish('embedContentOverlay');
}

function openFlagContent() {
	Effect.Appear('flagContentOverlay');
}

function closeFlagContent() {
	Effect.Squish('flagContentOverlay');
}
function openFavoriteContent() {
	Effect.Appear('favoriteContentOverlay');
}

function closeFavoriteContent() {
	Effect.Squish('favoriteContentOverlay');
}

function submitEditContentTitleForm(formUrl,theForm) {
	var titleTextArea = document.getElementById('newTitleTextarea');
	if (titleTextArea.value == '') {
		var editTitleCopy = document.getElementById('editTitleCopy');
		var editTitleText = editTitleCopy.firstChild;
		editTitleText.textContent = 'Title must not be empty';
	} else {
		postUrl(formUrl, theForm, 'titleTextareaDiv');
	}
}

function deleteContentFromGroup(contentId,groupId,contentTypeId,pageNum) {
	url = '/community/groups/admin/deleteContentFromGroup.bt?contentId=' + contentId + '&groupId=' + groupId + '&contentTypeId=' 
	+ contentTypeId +'&pageNum='+pageNum+'&'+tokenName+'='+token+'&timeTokenGenerated='+timeCreated;
	goToUrl(url);
}

function resetEmailForm() {
    //alert("successfully sent!");
    closeEmailContent();
    $('emailContentForm').reset();
    $('emailContentToError').hide();
    $('invalidEmailContentToError').hide();
    $('emailContentTo').setStyle({borderColor: ''});

}

function validateEmailAddress(email)  {
   var regExp = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

   if(regExp.test(email) == false) {
      return false;
   }
   else {
       return true;
   }
}

///////////////////////////tags/////////////////////////////////
/*
 * This function diables onClick event
 * it is useful if you want to make sure
 * that onClick is rune once only.
*/
function disableOnClick(obj) {
    if (typeof obj != 'undefined')
    {
        obj.onclick = new Function("return false;");
    };
}

function removeTagFromContent(contentId,tagId) {
      sendTagRequest("/community/tags/removeTagFromContent.bt?contentId="+contentId+"&tagId="+tagId);
}

function removeGroupFromContent(contentId,groupId) {
      sendGroupRequest("/community/groups/removeGroupFromContent.bt?contentId="+contentId+"&groupId="+groupId);
}

function sendGroupRequest(url) {
	if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
		req.onreadystatechange = processGroupListUpdate;
		try {
			req.open("GET", url, true);
		} catch (e) {
			alert(e);
		}
		req.send(null);

	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processGroupListUpdate;
			req.open("GET", url, true);
			req.send();
		}
	}
}

function processGroupListUpdate(){
   if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
            document.getElementById("groupsList").innerHTML = req.responseText;
		} else {
			alert("Problem: " + req.statusText);
		}
	}
}

function showhideNewGroups() {
	// hides & shows the newGroups section
    if(document.getElementById('groupBank').style.display=='block') {
        document.getElementById('groupBank').style.display='none';
    }
    else {
        document.getElementById('groupBank').style.display='block';
    }
}

function addGroupToContent(newGroupId,contentId) {
    if(newGroupId != -1 && newGroupId != 'new') {
        newItemURL = "/community/groups/addGroupToContent.bt?contentId="+contentId+"&groupId="+newGroupId;
        var ajaxResponse = new Ajax.Request(newItemURL, {onSuccess: updateGroupBox});

        //sendTagRequest(newItemURL);
    }
}

function updateGroupBox(originalRequest) {
    var gotBack = originalRequest.responseText;
    if (gotBack.match(/[a-zA-Z0-9]/)) {
        $('groupsList').update(gotBack);
    }
    else {
        alert ('Error');
    }
}

function sendTagRequest(url) {
	if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
		req.onreadystatechange = processTagListUpdate;
		try {
			req.open("GET", url, true);
		} catch (e) {
			alert(e);
		}
		req.send(null);

	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processTagListUpdate;
			req.open("GET", url, true);
			req.send();
		}
	}
}





///////////////////////////TAGS//////////////////////////
function showhideNewTags() {
    // hides & shows the newTag section
    if(document.getElementById('tagBank').style.display=='block') {
        document.getElementById('tagBank').style.display='none';
        }
    else {
        document.getElementById('tagBank').style.display='block';
        }
    }

function addTagToContent(newTagId,contentId) {
    if(newTagId != -1 && newTagId != 'new') {
        newItemURL = "/community/tags/addTagToContent.bt?contentId="+contentId+"&tagId="+newTagId;
        var ajaxResponse = new Ajax.Request(newItemURL, {onSuccess: updateTagBox});

        //sendTagRequest(newItemURL);
    }
}

function updateTagBox(originalRequest) {
    var gotBack = originalRequest.responseText;
    if (gotBack.match(/[a-zA-Z0-9]/)) {
        $('tagList').update(gotBack);
        }
    else {
        alert ('Error');
        }
    }

function addNewTag(contentId){
    newTag = document.getElementById("tagTitle").value;
    var tagPattern = /[a-zA-Z0-9]/;
    var iChars = "!@#$%^&*()+=-[]\\;,./{}|:<>?";
    var bSpecialChar = 0;

    for (var i = 0; i < document.getElementById("tagTitle").value.length; i++) {
        if (iChars.indexOf(document.getElementById("tagTitle").value.charAt(i)) != -1) {
            document.getElementById('tagError').style.display='block';
            bSpecialChar = 1;
            }
        }

    if (validTags(newTag)) {
        if (document.getElementById("tagTitle").value.length == 0 || bSpecialChar == 1) {
            document.getElementById('tagError').style.display='block';
            }
        else {
            newTagURL = "/community/tags/addNewTag.bt?contentId="+contentId+"&tagName="+newTag;
            var ajaxResponse = new Ajax.Request(newTagURL, {onSuccess: updateTagBox});
            }
        }
    else {
        document.getElementById('tagError').style.display='block';
        //showTagError(true);
        }
    }

function showTagError(show) {
    tagErrorDiv = document.getElementById("tagErrors");
    if (show) {
        tagErrorDiv.innerHTML = "Only letters and numbers in tags, please.";
    } else {
        tagErrorDiv.innerHTML = "";
    }
}

function validTags(tags) {
    index = tags.indexOf(",");
    return (index == -1);
}

function cancelNewTag(){
   document.getElementById('addTag').style.display='none';
   tagSelect = document.getElementById('tagSelect');
   tagSelect.selectedIndex=0;
}

function processTagListUpdate(){
   if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
            if ( (req.responseText != 'ERROR') && (req.responseText != 'TAG_IN_MULTIPLE_CONTESTS') ) {
			    document.getElementById("tagList").innerHTML = req.responseText;
            } else if (req.responseText == 'TAG_IN_MULTIPLE_CONTESTS') {
                tagErrorDiv = document.getElementById("tagErrors");
                tagErrorDiv.innerHTML = "<span class='error'>You can only enter 1 contest at a time!</span>";
            } else {
                tagErrorDiv = document.getElementById("tagErrors");
                tagErrorDiv.innerHTML = "<span class='error'>Only letters, numbers, spaces and quotes are allowed!</span>";
            }

		} else {
			alert("Problem: " + req.statusText);
		}
	}
}

function sendTagRequest(url) {
	if (window.XMLHttpRequest) { // Non-IE browsers
		req = new XMLHttpRequest();
		req.onreadystatechange = processTagListUpdate;
		try {
			req.open("GET", url, true);
		} catch (e) {
			alert(e);
		}
		req.send(null);

	} else if (window.ActiveXObject) { // IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange = processTagListUpdate;
			req.open("GET", url, true);
			req.send();
		}
	}
}

function hideContestVote(tabName) {
	if (typeof contestTag != 'undefined')
	{
		if(tabName == contestTag) {
			hideDiv("ratingsDiv");
		}
	}
}

function showContestVote(tabName) {
	if (typeof contestTag != 'undefined')
	{
		if(tabName == contestTag) {
			showDiv("ratingsDiv");
		}
	}
}



// Albums
function showhideNewAlbums() {
    // hides & shows the newAlbum section
    if(document.getElementById('albumBank').style.display=='block') {
        document.getElementById('albumBank').style.display='none';
        }
    else {
        document.getElementById('albumBank').style.display='block';
        }
    }

function addSetToContent(newSetId,contentId,args) {
    if(newSetId != -1 && newSetId != 'new') {
        newItemURL = "/community/sets/addContentToSet.bt?contentId="+contentId+"&setId="+newSetId+args,processSetListUpdate,processSetListUpdate;
        var ajaxResponse = new Ajax.Request(newItemURL, {onSuccess: updateSetBox});

        //sendTagRequest(newItemURL);
    }
}

function updateSetBox(originalRequest) {
    var gotBack = originalRequest.responseText;
    if (gotBack.match(/[a-zA-Z0-9]/)) {
        $('setList').update(gotBack);
        }
    else {
        alert ('Error');
        }
    }

function addToFavorites(contentTypeId, contentId) {
    newFavoriteURL = "/community/content/favorite/add.bt?contentTypeId="+contentTypeId+"&contentId="+contentId
    +"&"+tokenName+"="+token+"&timeTokenGenerated="+timeCreated;
    var ajaxResponse = new Ajax.Request(newFavoriteURL,{onComplete: postAddToFavorites});
    newContent = "Bookmarked | ";
    $('favoriteBox').update(newContent);
}

function postAddToFavorites(originalRequest){
	var returnText = originalRequest.responseText;
	results = returnText.split("||");
	token=results[0];
	timeCreated=results[1];
	if(originalRequest.status==403){
		document.getElementById('mediaPermLinkError').innerHTML = results[2];
		document.getElementById('mediaPermLinkError').style.display='block';
	}
	else{
		document.getElementById('mediaPermLinkError').style.display='none';
		newContent = "Bookmarked | ";
    	$('favoriteBox').update(newContent);
    }
}
//Tags
    function hideExtraTags(min, len)
    {
            for (i=min;i<len;i++) {
                var element = document.getElementById("tag" + i).style.display = "none";
            }
            var element = document.getElementById("showExtraTags").style.display = 'inline';
            var element = document.getElementById("hideExtraTags").style.display = 'none';
    }
    function showExtraTags(min, len)
    {
            for (i=min;i<len;i++) {
                var element = document.getElementById("tag" + i).style.display = "inline";
            }
            var element = document.getElementById("showExtraTags").style.display = 'none';
            var element = document.getElementById("hideExtraTags").style.display = 'inline';
    }

        function searchTags() {
            form = document.getElementById('tagSearchForm');
    //            if(form.tag.value=='Search Tags') {
    //                alert ("Please enter a tag to search");
    //                return false;
    //            }
                form.action = "<%=request.getContextPath()%>/tags/displayContentByTag.bt";
                form.submit();
        }

function submitSort() {
	form = document.getElementById('tagSearchForm');
    form.action = "<%=request.getContextPath()%>/tags/displayContentByTag.bt";
    form.submit();
}





/* Photo area scripts for dealing for the various pop ups and what not.  May need to be integrated elsewhere as needed */


// cribbing somewhat liberally from icant.co.uk/articles/from-dhtml-to-dom/domscripting.js to start

var photoPage = {
    //CSS Classes
    dynamicClass: 'popBox', showClass: 'show', hideClass:'hide',
    //Page Ids
    chooserBox: 'chooserBox',
init:function() {
     if(!document.getElementById) {return;}
     photoPage.initBox();
    },
initBox: function(){
        var container=document.getElementById('uploadPhotoChanges');
        if (!container){return;}
        //photoPage.cssjs('add', container, photoPage.dynamicClass);
        photoPage.chooserBox = document.createElement('div');
        photoPage.chooserBox.id='chooserBox';
        photoPage.cssjs('add', photoPage.chooserBox, photoPage.hideClass);
        container.appendChild(photoPage.chooserBox);
        var closeLink = document.createElement('a');
        closeLink.setAttribute('href', '#');
        closeLink.innerHTML=('close');
        photoPage.addEvent(closeLink, 'click', photoPage.closeBox, false, false);
        photoPage.chooserBox.appendChild(closeLink);
	//closeLink = photoPage.chooserBox.getElementByID('closebox');
        ///photoPage.addEvent(closeLink, 'click', photoPage.closeBox, false);
        //photoPage.fixSafari(closebox);
        // for now just use the javascript in the uploadForm.jsp to shoot off OpenWin if needed
},

    openBox: function(e){
   // for now just show it.
       // lets make sure it is being put in the right spot;
       var albumContainer = $('albumChooser');
       //alert(parseInt(albumContainer.style.top, 10));
       //alert(albumContainer.offsetTop);
        new Ajax.Updater(photoPage.chooserBox.id, '/portfolio/photo/new_album.html', {method:'get'});
        photoPage.cssjs('remove',photoPage.chooserBox, photoPage.hideClass);
        //photoPage.cancelClick(e);
        },

    closeBox: function(e){
      // close it
      photoPage.cssjs('add', photoPage.chooserBox, photoPage.hideClass);
      return false;
},


addEvent: function(elm, evType, fn, useCapture){
		if (elm.addEventListener)
		{
			elm.addEventListener(evType, fn, useCapture);
			return true;
		} else if (elm.attachEvent) {
			var r = elm.attachEvent('on' + evType, fn);
			return r;
		} else {
			elm['on' + evType] = fn
		}
	}

  ,
// cssjs tests
	cssjs:function(a,o,c1){
		switch (a){

			case 'add':
				if(!photoPage.cssjs('check',o,c1)){o.className+=o.className?' '+c1:c1;}
			break;
			case 'remove':
				var rep=o.className.match(' '+c1)?' '+c1:c1;
				o.className=o.className.replace(rep,'');
			break;
			case 'check':
				return new RegExp("(^|\\s)" + c1 + "(\\s|$)").test(o.className)
			break;
		}
	}







}
photoPage.addEvent(window, 'load',photoPage.init, false);

//Upload forms
function setTextFieldValue() {
    var l = location.href;
    //alert(l.indexOf('tagId'));
    if (l.indexOf('tagId') !== -1) {
        var sUrl = location.href;
        var aUrl = new Array();
        aUrl = sUrl.split('?');
        var tagValPair = aUrl[1];
        var tagVal = new Array();
        tagVal = tagValPair.split('tagId=');
        //alert(tagVal[1]);
        //alert(document.uploadPhotoForm.tagsToAdd.value)
        document.uploadPhotoForm.tagsToAdd.defaultValue = tagVal[1];
        document.uploadPhotoForm.tagsToAdd.value = tagVal[1];
    } else {
        return false;
    }
}

function init() {
    document.getElementById('tagsToAdd').focus();
}

function validateEntry() {

}

function addAnotherPhotoFileLine() {
    allPhotoFileLines = document.getElementById("photoFiles");
    numCurrentPhotoLines = allPhotoFileLines.rows.length;

    if (numCurrentPhotoLines < 20) {
        insertText = '<tr><td>' + (numCurrentPhotoLines + 1) + '.</td><td>';
        insertText = insertText + '<input id="photoFiles'+ numCurrentPhotoLines + '" type="file" size="40" name="photoFiles[' + numCurrentPhotoLines + ']" /></td></tr>';

        new Insertion.Bottom('photoFiles', insertText);
    }
    else {
        alert("You can only upload up to 20 photos at a time.");
    }
}

function setMethod(target) {
    document.forms[0].method.value = target;
}


function setTextFieldValue() {
   	var l = location.href;
   	//alert(l.indexOf('tagId'));
   	if (l.indexOf('tagId') !== -1) {
		var sUrl = location.href;
		var aUrl = new Array();
		aUrl = sUrl.split('?');
		var tagValPair = aUrl[1];
		var tagVal = new Array();
		tagVal = tagValPair.split('tagId=');
		//alert(tagVal[1]);
		//alert(document.uploadPhotoForm.tagsToAdd.value)
		document.uploadPhotoForm.tagsToAdd.defaultValue = tagVal[1];
		document.uploadPhotoForm.tagsToAdd.value = tagVal[1];
	} else {
		return false;
	}
}

// Start JS function for Admin Edit
// Current comment being editted
var activeEdit = null;
// Original text  being edited
var originalText = null;

/**
 * Prepare the text area for edit
 */
function prepareEditContentComment(comment) {
	var editComment = 'contentCommentText'+comment;
	if (editComment != activeEdit) {
		closeEditContentComment();
		activeEdit = editComment;
	} else {
		return false;
	}
	originalText = $(activeEdit).innerHTML;
	// stripTags()
	var commentText = originalText.replace(/<br>/gi, '\n').trim();

	var edit_area = "<div id='editCommentTextDiv'>" +
					"<form id='editCommentTextForm' action='#' method='post' onSubmit='return false;'>" +
					"<input type='hidden' name='editComment' value='" + comment +"' />" +
					"<textarea name='comment' id='editComment' class='contentCommentFormInput' rows='4' onkeyup='checkNumberOfCharacters(this, \"editRemainChars\"); return false;'>" + commentText+ "</textarea>" +
					"<div class='commentChars'>You can enter <span id='editRemainChars'>2000</span> more characters.</div>" +
					"<a href='#' onclick='submitEditContentComment(); return false;' class='btn24Blue'>" +
					"<div class='editCommentFailed'></div>" +
					"<span class='left'>&nbsp;</span>" +
					"<span class='middle'>Save</span>" +
					"<span class='right'>&nbsp;</span>" +
					"</a>" +
					"<a href='#' onclick='closeEditContentComment(); return false;' class='btn24Blue'>" +
					"<span class='left'>&nbsp;</span>" +
					"<span class='middle'>Cancel</span>" +
					"<span class='right'>&nbsp;</span>" +
					"</a>" +
					"<div class='clearer'></div>" +
					"</form>" +
					"</div>";
	$(activeEdit).update(edit_area);
	checkNumberOfCharacters('editComment', "editRemainChars");
}

/**
 * Close the comment area after edit
 */
function closeEditContentComment() {
	if (activeEdit != null){
		if (originalText != null) {
			$(activeEdit).innerHTML = originalText;
		}
		activeEdit = null;
		originalText = null;
	}
}

/**
 * Save the edit content comment
 */
function submitEditContentComment() {
	var text = $('editCommentTextForm').comment.value;
	text = text.replace(/^\s+|\s+$/g, '');
	if (text.length > 0) {
		var params = Form.serialize('editCommentTextForm', false);
		url = '/community/content/comment/edit.bt';
		var loginRequest = new Ajax.Request(url, {method: 'post', parameters: params,
			onSuccess: function() {
				var commentText = $('editCommentTextForm').comment.value
				originalText = commentText.replace(/\n/gi, '<br>');
				closeEditContentComment();
			}, onException : function() {
			$('editCommentFailed').innerHTML = 'Sorry, the edit failed.';
		}});
	} else {
		alert("Comment cannot be blank!");
	}
}
// End JS function for Admin Edit
