/* JS file for the Message Boards */

function onecontroller_post_reply(el, el_href, component, action, args, ajax) {
	
	if (typeof document.mb_post_reply_form == 'undefined') {
		return true;
	}
	
	if (typeof(tinyMCE.get('post_content')) != 'undefined') {
		var post_str = tinyMCE.get('post_content').save().replace(/&lt;/g,"<").replace(/&gt;/g,">");
	} else {
		var post_str = document.getElementsByName('post_content')[0].value;
	}
	
	ok_urls = ok_urls_str.split(',');
	
	if (!ok_urls[0]) {
		return true;
	}
	
	var expressions = {
		image: "(\\< *img .*?src *= *['\"]?)([^'\"\\s]+)(['\"]?.*?\\>)",
		param: "(\\< *param .*?(?=name *= *['\"]?movie['\"]?).*?value *= *['\"]?)([^'\"\\s]+)(['\"]?.*?\\>)",
		embed: "(\\< *embed .*?src *= *['\"]?)([^'\"\\s]+)(['\"]?.*?\\>)",
		bbimg: "(\\[img\\])([^'\"\\s]+)(\\[/img\\])"
	};
	
	for (x in expressions) {
		tagParts = post_str.match(
			new RegExp(expressions[x], "ig")
		);
		
		if (tagParts == null) {
			continue;
		}
		
		url = tagParts[0];
		
		urlPart = url.replace(/[\<\[].*?(https?:\/\/)([a-z-\.0-9]+)(:(\d+))?(.*)/i, "$2");
		
		if (!urlPart) {
			continue;
		}
		
		url_ok = false;
		
		for (var x = 0; x < ok_urls.length; x++) {
			ok_urls[x] = ok_urls[x].replace(/\\/g, "\\\\");
			urlExp = new RegExp('^(.*?\\.)?' + ok_urls[x] + '$', 'i');
			if (urlExp.test(urlPart)) {
				url_ok = true;
			}
		}
		
		if (!url_ok) {
			alert("Please remove the reference to \"" + urlPart + "\" and try again.");
			return false;
		}
	}
	
	return true;
	
};

function handle_onecontroller_post_reply(response) {
	document.getElementById('one_controller_container').innerHTML = response.responseText;
	oct_init_forum_tinymce_editor();
};

function onecontroller_post_delete(el, el_href, component, action, args, ajax) {
	// Parse out pid from args
	var args_array = args.split("?");
	var parsed_args = false;
	if (args_array[1] != null) {
		parsed_args = OneController.parseargs(args_array[1]);
	}
	
	// If couldn't retrieve valid args, return true to allow link to submit
	if (!parsed_args) {
		return true;
	}
	
	// Make sure we got back a pic
	if (parsed_args['pid'] == null) {
		return true;
	}
	
	// See if this is the confirmation click (if so, submit page)
	if (parsed_args['conf'] != null && parsed_args['conf'] == 'true') {
		return true;
	}
	
	// Get post_id
	var post_id = parsed_args['pid'];
	
	// Get conf box element
	var el_id = 'mp_submit_reply_delete_conf_box_' + post_id;
	
	// Toggle open/closed
	onecontroller_fm_toggle_display(el_id);
	
	return false;
};

function onecontroller_fm_toggle_display(el_id) {
	var el = document.getElementById(el_id);
	
	// Toggle open/closed
	if (el.style.display == 'block') {
		el.style.display = 'none';
	}
	else {
		el.style.display = 'block';
	}
};

function oct_init_forum_tinymce_editor(skinName) {
	var plugins = 'safari,media,inlinepopups,emotions,spellchecker';
	
	// Load paste plugin for IE
	if(YAHOO.env.ua.ie){
		plugins = plugins + ',paste';
	}
	
	if (skinName == undefined) {
		skinName = "onesite";
	}
	
	
	//This is for separate btns for each emoticon
	var EmotionButtons = {
		insert : function(file, title, ed) {
			var dom = ed.dom;
	
			tinyMCE.execCommand('mceInsertContent', false, dom.createHTML('img', {
				src : '/tools/tiny_mce/plugins/emotions/img/' + file,
				alt : title,
				title : title,
				border : 0
			}));
			
		}
	};

	
	// Init tinyMCE
	tinyMCE.init({
		setup : function(ed) {
		
			//do we want all the emoticons shown on row 1 or 2?
			if (row1_buttons.indexOf("cool") != -1) {
				var separate_emoticons = row1_buttons;
			}
			else if (row2_buttons.indexOf("cool") != -1) {
				var separate_emoticons = row2_buttons;
			}
			
			//build the individual emoticon btns?
			if (separate_emoticons) {
				var emoticons_array = separate_emoticons.split(",");
				var emoticons_imgsrc_array = {"cool":"smiley-cool",
											   "cry":"smiley-cry",
											   "embarrassed":"smiley-embarassed",
											   "foot in mouth":"smiley-foot-in-mouth",
											   "frown":"smiley-frown",
											   "innocent":"smiley-innocent",
											   "kiss":"smiley-kiss",
											   "laughing":"smiley-laughing",
											   "money mouth":"smiley-money-mouth",
											   "sealed":"smiley-sealed",
											   "smile":"smiley-smile",
											   "surprised":"smiley-surprised",
											   "tongue out":"smiley-tongue-out",
											   "undecided":"smiley-undecided",
											   "wink":"smiley-wink",
											   "yell":"smiley-yell"};
				
				function addbuttonfn(emoticon_imgsrc, emoticon) {
					ed.addButton(emoticon, {
						title : emoticon,
						image : "/tools/tiny_mce/plugins/emotions/img/" + emoticon_imgsrc,
						onclick : function() {
						      EmotionButtons.insert(emoticon_imgsrc, emoticon,ed);
						}
					});
				}                                             
	
				//loop through specified emoticons and create a btn for each
				for (i = 0; i < emoticons_array.length; i++) {
				      var emoticon = emoticons_array[i];
				      
				      if (emoticons_imgsrc_array[emoticon]) {
					      var emoticon_imgsrc = emoticons_imgsrc_array[emoticon] + ".gif";
					      
					      // Register individual emoticon btns
					      addbuttonfn(emoticon_imgsrc, emoticon);
				      }
				}
			}
			
		},
	    mode : "textareas",
	    //language: '',
	    theme : "advanced",
	    skin: skinName,
	    apply_source_formating: true,
	    theme_advanced_toolbar_location : "top",
	    theme_advanced_buttons1 : row1_buttons,
	    theme_advanced_buttons2 : row2_buttons,
	    theme_advanced_buttons3 : "",
	    valid_elements : "*[*]",
	    plugins : plugins,
	    relative_urls : false,
	    remove_script_host : false,
	    paste_auto_cleanup_on_paste: true,
	    force_br_newlines: force_br_newlines,
	    forced_root_block: forced_root_block
    });
    
    //tinyMCE.execCommand("mceAddControl", false, "post_content");
};

function oct_init_forum_yui_editor() {
	var myConfig = {
		//height: '300px',
		width: '100%',
		animate: true,
		dompath: true,
		focusAtStart: true,
		handleSubmit: true
	};
    myEditor = new YAHOO.widget.Editor('post_content', myConfig);
	
    myEditor.render();
};

/**
 *	This function is called when the user clicks on an image and then
 *	clicks on the "Select" button in the Photo Manager.
 *		*NOTE* Do NOT rename this function
 *
 *	@param	image_array		An array containing informatin about the
 *												image that was selected. Values returned
 *												include:
 *													[0] => photo_id
 *													[1] => filename
 *													[2] => full_path
 *													[3] => full_large_path
 *													[4] => full_thumb_path
 *	OR: if video
 *													[0] => video_id
 *													[1] => filename
 *													[2] => video_url
 *													[3] => preview_jpeg_url
 *													[4] => title
 *													[5] => media_type (should always be 'video')
 *													[6] => embed code (for external video service)
 *///http://www.onesite.com/resources/images/ratebg1.gif
function handle_selected(image_array) {
	var image_array = eval( '(' + image_array + ')' );
	
	if (image_array[5]) {
		if (image_array[5] == 'video') {
			var newimg = "<img src='" + image_array[3] + "' />";
			
			if (image_array[6]) {
				var newvid = image_array[6];
			}
			else {
				// Get width/height
				vwidth = 418;
				vheight = 314;
				if (image_array[7] && image_array[7] != 320 && image_array[7] > 0) {
					vwidth = parseInt(image_array[7]);
				}
				if (image_array[8] && image_array[8] != 240 && image_array[8] > 0) {
					vheight = parseInt(image_array[8]);
				}
				vpadwidth = vwidth;
				vpadheight = vheight + 85;
				var newvid = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="' + vpadwidth + '" height="' + vpadheight + '" id="player1" align="middle" style="">' +
						'<param name="movie" value="/resources/flash/tofPlayer.swf" />' +
						'<param name="FlashVars" value="autoPlay=0&hideRating=true&videoURL=' + image_array[2] + '&thumbURL=' + image_array[3] + '&videoID=' + image_array[0] + '&contentID=&videoWidth=' + vwidth + '&videoHeight=' + vheight + '&paddedWidth=' + vpadwidth + '&paddedHeight=' + vpadheight + '" />' +
						'<param name="wmode" value="transparent" />' +
						'<param name="quality" value="high" />' +
						'<param name="allowFullscreen" value="true" />' +
						'<embed src="/resources/flash/tofPlayer.swf" FlashVars="autoPlay=0&hideRating=true&videoURL=' + image_array[2] + '&thumbURL=' + image_array[3] + '&videoID=' + image_array[0] + '&contentID=&videoWidth=' + vwidth + '&videoHeight=' + vheight + '&paddedWidth=' + vpadwidth + '&paddedHeight=' + vpadheight + '" wmode="transparent" quality="high" width="' + vpadwidth + '" height="' + vpadheight + '" name="player1" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" allowFullscreen="true"/>' +
					'</object>';
			}
			inst = tinyMCE.get('post_content');
			
			if(YAHOO.env.ua.ie){
				var ieHatesMe = inst.getContent();
				inst.execCommand('mceInsertRawHTML', false, ieHatesMe + newvid);
				return;
			}
			
			inst.execCommand('mceInsertRawHTML', false, newvid);
			inst.execCommand('mceCleanup');
			
			return;
		}
	}
	
	// Else, must be photo
	// Make sure image width is <= 500px
	var imgurl = image_array[2];
	image_1 = new Image();
	image_1.src = imgurl;
	if (image_1.width <= 500) {
		var newimg = "<img src='" + imgurl + "' />";
	}
	else {
		var newimg = "<img src='" + imgurl + "' width='500' />";
	}
	
	newimg = ' ' + newimg;
	
	// Insert into tinyMCE if allowing html
	if (!forum_disable_html) {
		tinyMCE.execCommand('mceInsertContent',false,newimg);
	}
	else {
		var el = document.getElementById('post_content');
		el.value = el.value + "[img]" + imgurl + "[/img]";
	}
};

/**
 * Called when a user selects a photo from the new Photo Manager 
 * to be inserted into TinyMCE box.
 */
function handle_forum_photo_selection(photo) {
	// Get photo url
	var photo_url = photo.url;
	
	// Insert into tinyMCE if allowing html
	if (!forum_disable_html) {
		var insert_html = "<a href='" + photo.page_url + "'><img src='" + photo_url + "' /></a>";
		tinyMCE.execCommand('mceInsertContent', false, insert_html);
	}
	else {
		var el = document.getElementById('post_content');
		el.value = el.value + "[url=" + photo.page_url + "][img]" + photo_url + "[/img][/url]";
	}
};

/**
 * Called when a user selects a video from the new Video Manager 
 * to be inserted into TinyMCE box.
 */
function handle_forum_video_selection(video) {
	inst = tinyMCE.get('post_content');
	if(YAHOO.env.ua.ie){
		var ieHatesMe = inst.getContent();
		inst.execCommand('mceInsertRawHTML', false, ieHatesMe + video['embed_code']);
		return;
	}
	
	inst.execCommand('mceInsertRawHTML', false, video['embed_code']);
	inst.execCommand('mceCleanup');
}

/**
 * Populate the post content box with the syntax for quoting an existing post.
 */
function mb_viewcontent_quote(post_id) {
	// Get element
	var post_container = document.getElementById('mb_page_vc_posts_post_content_' + post_id);
	var post_content = post_container.innerHTML;
	
	// Show textarea
	document.getElementById('mb_page_vc_content_postwrapper1').style.display = 'block';
	
	// Add quote to textarea
	var textarea = document.getElementById('mb_page_vc_content_postcontent1');
	textarea.value = "[quote]" + post_content + "[/quote]";
};

function mb_init_post_calendar() {
	// Get el
	var el = document.getElementById('mb_thread_create_options_expires_value');
	
	// Return if not there
	if (typeof(el) == 'undefined' || !el || el == null) {
		return;
	}
	
	// Init calendar
	var calendar = new YAHOO.widget.Calendar("expiresCalendar", "calendarContainer", { title:"Choose a date:", close:true });
	calendar.render();
	
	YAHOO.util.Event.addListener("mb_thread_create_options_expires_edit", "click", calendar.show, calendar, true);
	calendar.selectEvent.subscribe(mb_select_post_calendar_date, calendar, true);
};

function mb_select_post_calendar_date(type,args,obj) {
	// Get selected date
	var date1 = this._toDate(args[0][0]);
	
	// Close popup
	obj.hide();
	
	// Extract data info
	var month = date1.getMonth() + 1;
	var day   = date1.getDate();
	var year  = date1.getFullYear();
	
	// Make sure date is older than today
	var cur_begin_date = new Date();
	if (cur_begin_date > date1) {
		month = cur_begin_date.getMonth() + 1;
		day = cur_begin_date.getDate();
		year = cur_begin_date.getFullYear();
	}
	
	// Print selected date to screen -- changed to fit datetime format
	document.getElementById('mb_thread_create_options_expires_value').value = year + '-' + month + '-' + day;
};

function mb_thread_change_perpage(url) {
	window.location = url + '&num=' + document.getElementById('mb_thread_per_page').value;
};

//for Forum Moderators select Forum dropdown menu
function ForumSelect(number)
{
	location.href = "?forum=" + number.value;
};

// Multi-Quote
var quote_ids = new Array();
function multiQuote(quote_id) {

	quote_ids_total = quote_ids.length;
	for (i = 0; i <= quote_ids_total; i++) {
		if (quote_ids[i] == quote_id) {
			quote_ids.splice(i, 1);
			document.getElementById('mq'+quote_id).className = "oneButtonGlobal mb_submit_reply_multiquote";
			var deleted = true;
			break;
		}
	}
	
	// If the quote_id didn't already exist (and was removed), add it
	if (!deleted) {
		quote_ids.push(quote_id);
		document.getElementById('mq'+quote_id).className = "oneButtonGlobal mb_submit_reply_multiquote_selected";
	}
	
	// Explode array
	quote_ids_csv = quote_ids.join(",");
	
	// Update both Reply links to include the selected quote_ids
	document.getElementById("threadReplyTop").href = thread_reply_link + "?quote=" + quote_ids_csv;
	document.getElementById("threadReplyBottom").href = thread_reply_link + "?quote=" + quote_ids_csv;
}

// Toggles selection of all threads (for Thread Tools)
function toggleThreadSelectAll(state) {
	var num_fields = document.getElementsByName('managethread[]').length;

	for(i = 0; i < num_fields; i++){
		document.getElementsByName('managethread[]')[i].checked = state.checked? true:false;
	}
};


/**
 * Thread Tools Menu
 */
var timeout = 500;
var hide_options_timer = 0;
var toolbar_options = 0;

// Show Thread Tools options
function show_options(id) {
	// stop hide timer
	stop_hide_timer();

	// hide old options
	if(toolbar_options) toolbar_options.style.visibility = 'hidden';

	// show new options
	toolbar_options = document.getElementById(id);
	toolbar_options.style.visibility = 'visible';
}

// Hide Thread Tools options
function hide_options() {
	if(toolbar_options) toolbar_options.style.visibility = 'hidden';
};

// Start timer to hide Thread Tools options (mouseout)
function start_hide_timer() {
	hide_options_timer = window.setTimeout(hide_options, timeout);
};

// Stop timer to hide Thread Tools options (mouseover)
function stop_hide_timer() {
	if(hide_options_timer) {
		window.clearTimeout(hide_options_timer);
		hide_options_timer = null;
	}
};
// hide thread tools options upon mouse-click
document.onclick = hide_options;

/**
 * Sets the signature limit and updates the remaining character count.
 */
function mb_signature_limit(limit) {
	// Get elements
	var signatureText = document.getElementById('signatureText').value;
	var signatureLength = signatureText.length;
	var signatureLeft = document.getElementById('signatureLeft');
	var signatureCharacters = document.getElementById('signatureCharacters');
	var signatureRemaining = limit - signatureLength;
	
	// Update the style if it is hidden
	if (signatureLeft.style.display == 'none') {
		signatureLeft.style.display = 'inline';
	}
	
	// Set the length of the input box
	if (signatureLength > limit) {
		var newSignature = signatureText.substring(0,limit);
		document.getElementById('signatureText').value = newSignature;
		signatureRemaining = 0;
	}
	
	// Change the remaining characters left
	signatureCharacters.innerHTML = signatureRemaining;
};