// 
// Global handling scripts
//
var loc_autocomplete_scr = 'http://sandbox.npr.org/exec/kickapps/autocomplete/findtags.php';
var loc_profanity_scr = 'http://sandbox.npr.org/exec/kickapps/profanity/profanity_secure.php';

// For testing
// var loc_autocomplete_scr = 'http://dev.kickapps.com/npr/autocomplete/findtags.php';
// var loc_profanity_scr = 'http://dev.kickapps.com/badwords/profanity_secure.php';

//
// Handle tag check boxes
//
var arraySize = 13;
var suggestedTags = new Array(arraySize);
suggestedTags[0] = "National Security";
suggestedTags[1] = "Iraq";
suggestedTags[2] = "Healthcare";
suggestedTags[3] = "Taxes";
suggestedTags[4] = "Immigration";
suggestedTags[5] = "Economy";
suggestedTags[6] = "Foreign Policy";
suggestedTags[7] = "Environment";
suggestedTags[8] = "Education";
suggestedTags[9] = "Government";
suggestedTags[10] = "Poverty";
suggestedTags[11] = "The Middle Class";
suggestedTags[12] = "Justice";

// 
// General Use Routines
//

// 
// Tag Counting and Handling Routines
//
function tagLengthCheck( strText, maxLength ) {
	
	var wordFailed = "";
	var delimText = "";
	var quoteStart = false;

	// Handle comman delimiting the text
	for (var i = 0; i < strText.length; i++) {
		if (strText.charAt(i) == '"') {
			if (quoteStart) {
				delimText = delimText + ",";
			}
			quoteStart = !quoteStart;
		}
		else {
			if (strText.charAt(i) == ' ') {
				if (!quoteStart) {
					delimText = delimText + ",";
				}
				else {
					delimText = delimText + strText.charAt(i);
				}
			}
			else {
				delimText = delimText + strText.charAt(i);
			}
		}
	}
	
	// Parse into a word array
	var tempArray = delimText.split(',');
	
	for (var i = 0; i < tempArray.length; i++) {
		if (tempArray[i].length > maxLength) {
			if (wordFailed =="") {
				wordFailed = tempArray[i];
			}
			else {
				wordFailed += ', ' + tempArray[i];
			}
		}
	}

	// Return the failed tags
	return wordFailed

}

//
// Handle inserting an element into the DOM
//
function insertAfter(newElement,targetElement) {
	var parent = targetElement.parentNode;
	if (parent.lastchild == targetElement) {
		parent.appendChild(newElement);
	} else {
		parent.insertBefore(newElement, targetElement.nextSibling);
	}
}

// 
// Tag functions
//
function tagCommaHandle(strText) {
	var tagList = "";
	
	if (strText.indexOf(",") > 0) {
		// Parse into a word array
		var tempArray = strText.split(',');
		for (var i = 0; i < tempArray.length; i++) {
			tagList += tagQuote(tempArray[i].trim()) + " ";
		}
		return tagList;
	}
	return strText;
}

function tagQuote(strText) {
	
	if (strText.indexOf(" ") > 0) {
		strText = '"' + strText + '"';
	}

	return strText;
}

function tagExists(strText, tagText) {
	
	if (tagText.indexOf(strText) > 0) {
		return true;
	}

	return false;
}

// 
// Recursively reverse all nodes beneath Node n, and reverse Text nodes
//
function replaceText(n) { 
    if (n.nodeType == 3 /*Node.TEXT_NODE*/) { // Reverse Text nodes
        var text = n.data;                    // Get content of node
        text = text.replace("blogs", "text commentaries");
        text = text.replace("Blogs", "Text commentaries");
        text = text.replace("blog posts", "text commentaries");
        text = text.replace("Blog posts", "Text commentaries");
        text = text.replace("Blog Posts", "Text Commentaries");
        text = text.replace("a blog post", "text commentary");
        text = text.replace("blog post", "text commentary");
        text = text.replace("Blog post", "Text commentary");
        text = text.replace("blog", "text commentary");        
        text = text.replace("My Blog", "My Text Commentary");   
        text = text.replace("My  Blog", "My Text Commentary");   
        text = text.replace("my blog", "my text commentary");        
        text = text.replace("Vegas Slots", "national security");        
        text = text.replace("Vegas slots", "national security");        
        text = text.replace("vegas slots", "national security");        
        if (window.location.href.indexOf("searchEverything") != -1) {
        	text = text.replace("Not yet rated", "");        
        }
        n.data = text;                        // Store reversed text
    }
    else { 
        var kids = n.childNodes;
        var numkids = kids.length;
        for(var i = numkids-1; i >= 0; i--) {       // Loop through kids
            replaceText(kids[i]);                   // Recurse to reverse kid
        }
    }
}

$j(document).ready(function() {
	replaceText(document);
});

// 
// Handle profile encoding
//
function urlEncode(strURL)
{
  var strURLEncode = escape(strURL);
  return strURLEncode;
}

// 
// Handle profile URL - urlencode
//
$j(document).ready(function() {
	if (Ka.Info.PAGE == 'pages/myPlace.jsp') {
		if ($j('#ka_myHomeURL')) {
			var profileTxt = $j('#ka_myHomeURL').text();
			var intIndexOfMatch = profileTxt.indexOf('http://');
			if (intIndexOfMatch != -1) {
				$j('#ka_myHomeURL').text( profileTxt.substr(0, intIndexOfMatch + 7) + urlEncode(profileTxt.substr(intIndexOfMatch + 7)) );
			}
		}
	}
});

// 
// Handle redirect back to original page
//
if (window.location.href.indexOf('displayUserLoginPage') != -1) {
	writeSessionCookie('registerRedirect', document.getElementById('redirectURL').value);
}

if (window.location.href.indexOf('displayUserRegisterPage') != -1) {
	writeSessionCookie('registering', 'true');
}

if (window.location.href.indexOf('displayMyPlace') != -1) {
	var referrer = getCookieValue('registerRedirect');
	if (referrer != null && referrer != '') {
		writeSessionCookie('registerRedirect', '');
		var reggin = getCookieValue('registering');
		if (reggin != null && reggin == 'true') {
			writeSessionCookie('registering', '');
			window.location.href='http://getmyvote.npr.org/kickapps' + referrer;	
		}	
	}
}

// 
// Handle setting the admin tags -->
//
function npr_getAdminTags(){  
	
	// Get the b parameter from the URL (AT tag is enclosed)
	var strTAG = getParam('b');
	if (strTAG != '') {

		var intIndexOfMatch = strTAG.indexOf('AT');
		if (intIndexOfMatch != -1) {
			strTAG = strTAG.substr(2);
		}
		else {
			strTAG = '';
		}
	}
	
	if (strTAG != '') {
		
		// Decode the value into text
		strTAG = decodeTags(strTAG);
		
		// Handle saving the admin tags
		writeSessionCookie("ka_uploadtags", strTAG);
		
	}
}

function npr_setAdminTags(){  

	strTAG = getCookieValue("ka_uploadtags");
	
	if (strTAG != '') {

		// Set the Admin field
		var adminFld = document.getElementById("mediaAdminTags");	
		if (adminFld) {
			adminFld.value = strTAG;
		}
	}
}

// Upload page checks
if (Ka.Info.PAGE == 'pages/newVideoUpload.jsp' || Ka.Info.PAGE == 'pages/newAudioUpload.jsp' || Ka.Info.PAGE == 'pages/newPhotoUpload.jsp' || Ka.Info.PAGE == 'pages/addBlog.jsp') {
	npr_getAdminTags();
	npr_setAdminTags();
} 
else {
	$j(document).ready(function() {
		npr_getAdminTags();
	});
}

// 
// Max tag word length validation
//
if (Ka.formValidation){
	Ka.formValidation.rules["max_tag_length"] = {
		message: '',
		test:function(val,propVal,element){
			var maxLength = 20;
			var longWords = tagLengthCheck(val, maxLength);
			if (longWords != "") {

				// Remove the words
				var tempArray = longWords.split(', ');
				var strValue = val;
				for (var i = 0; i < tempArray.length; i++) {
					strValue = strValue.replaceAll(tempArray[i], '')
				}
				
				this.message = 'The following tag(s) ' + longWords + ' are too long. Please limit your tag(s) to ' + maxLength + ' characters per tag.';

				// Put back in the tags field
				element.value = strValue.trim();
				return false;
			}
			return true;
		}
	}
}

var wc_haveTags = document.getElementsByName('tags');
if (wc_haveTags) {	
	$j('#tags').attr('max_tag_length','true');
};

var wc_haveMediaTags = document.getElementsByName('mediaTags');
if (wc_haveMediaTags) {	
	$j('#mediaTags').attr('max_tag_length','true');
};

var wc_havePlayerTags = document.getElementsByName('ka_playerAddTagsInput');
if (wc_havePlayerTags) {	
	$j('#ka_playerAddTagsInput').attr('max_tag_length','true');
};

// 
// Handle Allow for user names with spaces and periods
//
if (Ka.formValidation){
	//overwrite isAphaNum method
	Ka.formValidation.rules["is-alpha-numeric"] = {
		  message:"This field accepts only letters, numbers, spaces, underscores and periods",
		  test:function(val,propVal){
				 var nonAlphaRegX = /[^a-zA-Z0-9_\.\s]/;
				 if(nonAlphaRegX.test(val)){
					   return false;
				 }else{
					   return true;
				 }
		  }
	}

}

// 
// Handle Autocomplete tags
//
var haveTags = document.getElementsByName('tags');
if (haveTags) {	
	$j(document).ready(function() {
		$j("#tags").autocomplete(
			loc_autocomplete_scr,
			{
				selectFirst: false,
				multiple: true,
				multipleSeparator: " ",
				cacheLength: 1,
				delay: 10,
				matchSubset: false,
				mustMatch: false,
				proxy: location.protocol+'//'+location.hostname+'/kickapps/service/getHttpUrl.kickAction?urlLink='
			}
		);
	});
};

var haveMediaTags = document.getElementsByName('mediaTags');
if (haveMediaTags) {	
	$j(document).ready(function() {
		$j("#mediaTags").autocomplete(
			loc_autocomplete_scr,
			{
				selectFirst: false,
				multiple: true,
				multipleSeparator: " ",
				cacheLength: 1,
				delay: 10,
				matchSubset: false,
				mustMatch: false,
				proxy: location.protocol+'//'+location.hostname+'/kickapps/service/getHttpUrl.kickAction?urlLink='
			}
		);
	});
};

var havePlayerTags = document.getElementsByName('ka_playerAddTagsInput');
if (havePlayerTags) {	
	$j(document).ready(function() {
		$j("#ka_playerAddTagsInput").autocomplete(
			loc_autocomplete_scr,
			{
				selectFirst: false,
				multiple: true,
				multipleSeparator: " ",
				cacheLength: 1,
				delay: 10,
				matchSubset: false,
				mustMatch: false,
				proxy: location.protocol+'//'+location.hostname+'/kickapps/service/getHttpUrl.kickAction?urlLink='
			}
		);
	});
};

// 
// Handle Profanity Filter
//
function fixBadWordText(strText) {
	// Replace spaces with underscores
	return strText.replace(/\s/g, "_");
}

// Handle comments
if (typeof window.sendMessage != 'undefined') {
	var p_sendMessage = sendMessage;
	sendMessage = function(){
		var strComments = DWRUtil.getValue("text");
		var response = $j.ajax({
			type: "GET",
			url: location.protocol+'//'+location.hostname+'/kickapps/service/getHttpUrl.kickAction?urlLink='+loc_profanity_scr+'?texttocheck='+fixBadWordText(strComments),
			async: false
			}).responseText;
			
			if (response=='true'){
				p_sendMessage();
			}
			else {
				alert("The text you entered contains inappropriate content (word: " + response + ") and is not allowed on the site.");
			};
	}
}

// Handle the tag fields add button
if (typeof window.setTags != 'undefined') {
	var p_setTags = setTags;
	setTags = function(){
		var strTags = DWRUtil.getValue("ka_playerAddTagsInput");
		var response = $j.ajax({
			type: "GET",
			url: location.protocol+'//'+location.hostname+'/kickapps/service/getHttpUrl.kickAction?urlLink='+loc_profanity_scr+'?texttocheck='+fixBadWordText(strTags),
			async: false
			}).responseText;
			
			if (response=='true'){
				// Handle the commas in the tag
				DWRUtil.setValue("ka_playerAddTagsInput", tagCommaHandle(strTags));
				
				// handle the tag sets
				p_setTags();
			}
			else {
				alert("The text you entered contains inappropriate content (word: " + response + ") and is not allowed on the site.");
			};
	}
}

if (Ka.formValidation){
	Ka.formValidation.rules['badWordCheck'] = {
		 message: '',
		 test: function(input){
			 var response = $j.ajax({
				 type: "GET",
				 url: location.protocol+'//'+location.hostname+'/kickapps/service/getHttpUrl.kickAction?urlLink='+loc_profanity_scr+'?texttocheck='+fixBadWordText(input),
				 async: false
			 }).responseText;
			 if (response=='true'){return true};
			 this.message = 'The information you entered on this page contains inappropriate content (word: ' + response + ') and cannot be posted.';
			 return false;
		 }
	}

	// Registration checks
	if (Ka.Info.PAGE == 'login/registerUser.jsp'){
		//$j('#email').attr('badWordCheck','true');
		$j('#username').attr('badWordCheck','true');
	}
	
	// Edit Profile checks
	if (Ka.Info.PAGE == 'pages/manageProfileQuestions.jsp'){
		var profileTags = document.getElementsByName('tags');
	
		$j('#aboutMe').attr('badWordCheck','true');
		$j('#answer1').attr('badWordCheck','true');
		$j('#answer2').attr('badWordCheck','true');
		$j('#answer3').attr('badWordCheck','true');
		if (profileTags) {	
			$j('#tags').attr('badWordCheck','true'); 
		};
	}
	
	// Edit Account checks
	if (Ka.Info.PAGE == 'pages/manageAccountSettings.jsp'){
		$j('#email').attr('badWordCheck','true');
		$j('#firstName').attr('badWordCheck','true');
		$j('#lastName').attr('badWordCheck','true');
		$j('#postalCity').attr('badWordCheck','true');
		$j('#postalProvince').attr('badWordCheck','true');
		$j('#postalCode').attr('badWordCheck','true');
	}
	
	// Edit Blog checks
	if (Ka.Info.PAGE == 'pages/editBlog.jsp'){
		$j('#name').attr('badWordCheck','true');
		$j('#city').attr('badWordCheck','true');
		$j('#postalProvince').attr('badWordCheck','true');
		$j('#postalCode').attr('badWordCheck','true');
		$j('#description').attr('badWordCheck','true');
		$j('#tags').attr('badWordCheck','true');
	}
	
	// Add Blog checks
	if (Ka.Info.PAGE == 'pages/addBlog.jsp'){
		$j('#name').attr('badWordCheck','true');
		$j('#city').attr('badWordCheck','true');
		$j('#postalProvince').attr('badWordCheck','true');
		$j('#postalCode').attr('badWordCheck','true');
		$j('#mediaDescriptionRequired').attr('badWordCheck','true');
		$j('#tags').attr('badWordCheck','true');
	}
	
	// Media Upload checks
	if (Ka.Info.PAGE == 'pages/newVideoUpload.jsp' || Ka.Info.PAGE == 'pages/newAudioUpload.jsp' || Ka.Info.PAGE == 'pages/newPhotoUpload.jsp') {
		$j('#mediaName').attr('badWordCheck','true');
		$j('#mediaName1').attr('badWordCheck','true');
		$j('#mediaName2').attr('badWordCheck','true');
		$j('#mediaName3').attr('badWordCheck','true');
		$j('#mediaName4').attr('badWordCheck','true');
		$j('#mediaName5').attr('badWordCheck','true');
		$j('#mediaDescription').attr('badWordCheck','true');
		$j('#postalCity').attr('badWordCheck','true');
		$j('#postalProvince').attr('badWordCheck','true');
		$j('#postalCode').attr('badWordCheck','true');
		$j('#mediaTags').attr('badWordCheck','true');
	}
	
	// Media Edit checks
	if (Ka.Info.PAGE == 'pages/editVideo.jsp' || Ka.Info.PAGE == 'pages/editAudio.jsp' || Ka.Info.PAGE == 'pages/editPhoto.jsp') {
		$j('#mediaName').attr('badWordCheck','true');
		$j('#mediaDescription').attr('badWordCheck','true');
		$j('#postalCity').attr('badWordCheck','true');
		$j('#postalProvince').attr('badWordCheck','true');
		$j('#postalCode').attr('badWordCheck','true');
		$j('#mediaTags').attr('badWordCheck','true');
	}
	
	// Message Board checks
	if (Ka.Info.PAGE == 'pages/newDiscussion.jsp' || Ka.Info.PAGE == 'pages/newDiscussionThread.jsp'){
		$j('#ka_discussionSubject').attr('badWordCheck','true');
		$j('#ka_DiscussionName').attr('badWordCheck','true');
	}
}

// 
// Handle commas in tags
//
if (Ka.formValidation){
	Ka.formValidation.rules['tagCommaCheck'] = {
		message: '',
		test:function(val,propVal,element){
			element.value = tagCommaHandle(val);
			return true;
		}
	}

	// Edit Profile checks
	if (Ka.Info.PAGE == 'pages/manageProfileQuestions.jsp'){
		var profileTags = document.getElementsByName('tags');
		if (profileTags) {	
			$j('#tags').attr('tagCommaCheck','true'); 
		};
	}
	
	// Edit Blog checks
	if (Ka.Info.PAGE == 'pages/editBlog.jsp'){
		$j('#tags').attr('tagCommaCheck','true'); 
	}
	
	// Add Blog checks
	if (Ka.Info.PAGE == 'pages/addBlog.jsp'){
		$j('#tags').attr('tagCommaCheck','true'); 
	}
	
	// Media Upload checks
	if (Ka.Info.PAGE == 'pages/newVideoUpload.jsp' || Ka.Info.PAGE == 'pages/newAudioUpload.jsp' || Ka.Info.PAGE == 'pages/newPhotoUpload.jsp') {
		$j('#mediaTags').attr('tagCommaCheck','true'); 
	}
	
	// Media Edit checks
	if (Ka.Info.PAGE == 'pages/editVideo.jsp' || Ka.Info.PAGE == 'pages/editAudio.jsp' || Ka.Info.PAGE == 'pages/editPhoto.jsp') {
		$j('#mediaTags').attr('tagCommaCheck','true'); 
	}
}

// 
// Handle Recommended on Play Pages
//
if (Ka.Info.PAGE == 'pages/mediaPlayPage.jsp'){
	function setFavoriteCount(numAdjust){
		var strfavoriteCount = DWRUtil.getValue("favoriteCount");
		var favoriteCount = parseInt(strfavoriteCount);
		if (isNaN(favoriteCount)) {
			favoriteCount = 0;
		}
		else {
			favoriteCount = parseInt(strfavoriteCount);
		};
		favoriteCount = favoriteCount + numAdjust;
		DWRUtil.setValue("favoriteCount", String(favoriteCount));
		var recommendNumArea = document.getElementById('ka_recommendNumArea');
		if (recommendNumArea) {
			recommendNumArea.innerHTML = String(favoriteCount);
		}
	}
	
	function setupRecommended() {
		var lists = document.getElementsByTagName("div");
			for (var i=0; i<lists.length; i++) {
			if (lists[i].className.match("ka_stats")) {
				var innerHTML = lists[i].innerHTML;
				innerHTML = 'Recommended: <span id="ka_recommendNumArea"></span><br/>' + innerHTML;
				lists[i].innerHTML = innerHTML;
				setFavoriteCount(0);
				break;
			}
		}
	}

	Ka.addDOMLoadEvent(setupRecommended);

	function getAddText() {
	
		HTML = "";
		
		HTML += "<a href='javascript:addFavoriteMedia();'>";
		HTML += "Recommend</a>";
	
		return HTML;
	}
	
	function getRemoveText(){
		
		HTML = "";
		
		HTML += "<a href='javascript:removeFavoriteMedia();'>";
		HTML += "Don't Recommend</a>";
	
		return HTML;
	}

	if (typeof window.addFavoriteMedia != 'undefined') {
		var p_addFavoriteMedia = addFavoriteMedia;
		addFavoriteMedia = function(){
			p_addFavoriteMedia();
			setFavoriteCount(1);
		}
	}
	
	if (typeof window.removeFavoriteMedia != 'undefined') {
		var p_removeFavoriteMedia = removeFavoriteMedia;
		removeFavoriteMedia = function(){
			p_removeFavoriteMedia();
			setFavoriteCount(-1);
		}
	}

	// In tno then recomment
	function setRecommendedItem(flag){
		if (flag == false){
			addFavoriteMedia();
		}
	}
	
	// Check to see if recommended
	function setRecommended(){
		KickAppsBizComponent.isUsersFavoriteMedia(Ka.Info.USERID, Ka.Info.MEDIAID, Ka.Info.MEDIATYPE, Ka.Info.AFFILIATESITEID, setRecommendedItem);
	}

	function setLoginRedirect(){
		// Make sure to pass in the full URL with the recomment parameter
		oLoginForm = ka_findObj('ka_loginPopup');
		if (oLoginForm) {
			if (oLoginForm.redirectURL) {
				oLoginForm.redirectURL.value = oLoginForm.redirectURL.value + '?recommend=Y';
			}
		}
	}

	// Handle setting the recommend flag from widget
	function recommedMedia(){  
		
		// Get the recommed parameter from the URL
		var strTAG = getParam('recommend');
		if (strTAG != '') {
			if (Ka.Info.USERID == ''){
				Ka.popup('#ka_loginPopup',function(){
					setLoginRedirect();
				});
			}
			else {
				setRecommended();
			}
		}
	
	}
	
	$j(document).ready(function() {
		recommedMedia();
	});

}

// 
// Handle tag check boxes
//
function showSuggestedTags() {
	var cbDiv = document.createElement("div");
	cbDiv.className = "suggestedTags";
	
	// write the suggested tags into the page
	var theHTML = "Here's a partial list of subject ideas. Check the ones that apply to your commentary.<br /><div style=\"width:400px;\"><ul style=\"float:left;\">";
	var splitNum = Math.round(arraySize/2) - 1;
	for (var i = 0; i < arraySize; i++) {	
	    theHTML += '<li><input type="checkbox" name="' + suggestedTags[i] + '" id="' + suggestedTags[i] + '" style = "border:none;margin:0;"/> ' + suggestedTags[i] + '</li>';

		if ( i == splitNum ){
			theHTML += '</ul><ul style="float:right;">';
		}

	}
	cbDiv.innerHTML = "<br/>" + theHTML + "</ul></div><div class=\"spacer\">&nbsp;</div><br/>";

	var tagsElem = document.getElementById('mediaTags');
	if (tagsElem == null) {
		tagsElem = document.getElementById('tags');
	}
	
	insertAfter(cbDiv,tagsElem)
}

// call this on submit of the page
function addCheckedTagsToTagField(tagsElem) {
	var addingTags = "";
	var tagItem = "";

	for (var i = 0; i < arraySize; i++) {	
		if (document.getElementById(suggestedTags[i]).checked == true) {
			tagItem = suggestedTags[i].trim();
			if (!(tagExists(tagItem, tagsElem.value))) {
				addingTags += tagQuote(tagItem) + " ";
			}
		}
	}
	
	tagsElem.value = tagsElem.value + " " + addingTags.trim();
}

// 
// Handle the list to/watch value
//
// call this on submit of the page
var UploadSetup = false;
function showLookStation() {
	if (Ka.Info.PAGE == 'pages/newVideoUpload.jsp' || Ka.Info.PAGE == 'pages/newAudioUpload.jsp' || Ka.Info.PAGE == 'pages/newPhotoUpload.jsp' || Ka.Info.PAGE == 'pages/addBlog.jsp') {

		// Add the Profile question and text
		if (!(UploadSetup)) {
			if (document.getElementById('mediaTags') || document.getElementById('tags')){
				var tagsItem;
				
				// Write the question into the page
				var ka_listento = document.createElement("div");
				var theHTML = '<label>Station/Program I listen to or watch:</label><input id="ka_taglistento" type="text" value="" size="40" name="ka_taglistento"/>';
				ka_listento.innerHTML = theHTML;
				ka_listento.id = "ka_listento";

				var tagsElem = document.getElementById('mediaTags');
				if (tagsElem == null) {
					tagsElem = document.getElementById('tags');
				}
				insertAfter(ka_listento,tagsElem)
				
				// Set flag
				UploadSetup = true;	
			}
		}
	}
}

function addLookStationtoTagField(tagsElem) {
	var listen_to = document.getElementById('ka_taglistento');

	if (listen_to) {
		var tagItem = (listen_to.value).trim();

		if (!(tagExists(tagItem, tagsElem.value))) {
			tagsElem.value = tagsElem.value + " " + tagQuote(tagItem);
		}
	}
}

// Handle setting the user tags
function updatePageTags(frmObject) {

// Figure out the item to update
	var tagsElem = document.getElementById('mediaTags');
	if (tagsElem == null) {
		tagsElem = document.getElementById('tags');
	}

	// Handle the check boxes
	addCheckedTagsToTagField(tagsElem);
	
	// Handle the watched station
	addLookStationtoTagField(tagsElem);
	
	// Handle the commas in the tag
	tagsElem.value = tagCommaHandle(tagsElem.value);
}

// Handle popping these into the page
if (Ka.Info.PAGE == 'pages/newVideoUpload.jsp' || Ka.Info.PAGE == 'pages/newAudioUpload.jsp' || Ka.Info.PAGE == 'pages/newPhotoUpload.jsp' || Ka.Info.PAGE == 'pages/addBlog.jsp') {

	// NOTE: Make sure to keep this in order
	showLookStation();
	showSuggestedTags();
	
	// Handle the tags upono form submit
	if (typeof window.ka_checkUploadForm != 'undefined') {
		var p_ka_checkUploadForm = ka_checkUploadForm;
		ka_checkUploadForm = function(this_obj){
			updatePageTags(); 
			return p_ka_checkUploadForm(this_obj);
		}
	}

	if (typeof window.validateAddBlog != 'undefined') {
		var p_validateAddBlog = validateAddBlog;
		validateAddBlog = function(this_obj){
			updatePageTags(); 
			return p_validateAddBlog(this_obj);
		}
	}

} 

// 
// Handle the comment CR
//
function changeTextBox2TextArea( elementId ) {
	var itemToChange = document.getElementById( elementId );
	var ParentItem = itemToChange.parentNode;
	var innerHTML = ParentItem.innerHTML;
	 
	// property is read-only so we replace the element
	if ( itemToChange.type == 'text' ) {
		innerHTML = innerHTML.replace('<input', '<textarea COLS="60" ROWS="5"');
		innerHTML = innerHTML.replace('>', '></textarea>');
		ParentItem.innerHTML = innerHTML;
	} 
}

if (typeof window.handleRatingAndShoutBox != 'undefined') {
	var p_handleRatingAndShoutBox = handleRatingAndShoutBox;
	handleRatingAndShoutBox = function(loggedOn) {
		
		// Handle the rating and shout box
		p_handleRatingAndShoutBox(loggedOn);
		
		// Switch the text comment to a text area
		if ( document.getElementById('text') ) {
			document.getElementById('text').removeAttribute("onkeydown");
			document.getElementById('text').removeAttribute("size");
			changeTextBox2TextArea('text');
		}
	}
}
