var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var is_gecko = ((clientPC.indexOf('gecko')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0')==-1));
var is_safari = ((clientPC.indexOf('applewebkit')!=-1) && (clientPC.indexOf('spoofer')==-1));
var is_khtml = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ));

var is_ff2_win = (clientPC.indexOf('firefox/2')!=-1 || clientPC.indexOf('minefield/3')!=-1) && clientPC.indexOf('windows')!=-1;
var is_ff2_x11 = (clientPC.indexOf('firefox/2')!=-1 || clientPC.indexOf('minefield/3')!=-1) && clientPC.indexOf('x11')!=-1;
if (clientPC.indexOf('opera') != -1) {
	var is_opera = true;
	var is_opera_preseven = (window.opera && !document.childNodes);
	var is_opera_seven = (window.opera && document.childNodes);
}

function setTextareaValue(editorid, textareaid) {
	var textarea = document.getElementById(textareaid);
	if(document.all) {
		var val = document.getElementById(editorid).innerHTML;
	}else{
		var val = document.getElementById(editorid).contentWindow.document.body.innerHTML;
	}
	//alert(textareaid);
	//alert(editorid);
	//alert('textareaid: '+textarea.value);
	textarea.value = val;
	//alert(textareaid +': '+textarea.value);
	return true;
}

function getTextareaValue(textareaid) {
	var textarea = document.getElementById(textareaid);
	return textarea.value;
}

function insertImage(editorid, imagePath) {
	if ((imagePath != null) && (imagePath != "")) {
		if (document.all) {
			document.getElementById(editorid).innerHTML += '<img src=\"' + imagePath + '\">';
		}
		else{
			document.getElementById(editorid).contentWindow.document.execCommand('insertimage',false,imagePath);
		}
	}
}

function insertImage2(editorid, imagePath, position, caption) {
	if ((imagePath != null) && (imagePath != "")) {
		if (document.all) {
			document.getElementById(editorid).focus();//without this image can't be inserted, but position is top left
			document.execCommand('insertimage',false,imagePath);
		}
		else{
			document.getElementById(editorid).contentWindow.document.execCommand('insertimage',false,imagePath);
		}
	}
}

function insertImageWithStyle(editorid, imagePath, position, caption) {
	if (imagePath != null && imagePath != "") {
		var captionpart = caption ? caption : '';
		var imgTag;

		if (document.all) {
			var text = document.getElementById(editorid).innerHTML;

			if(position=='float') {
				imgTag = '<img src="'+imagePath+'" class="floatimage" title="'+ captionpart + '"/>';
			}
			else{
				imgTag = '<img src="'+imagePath+'" class="image" title="'+ captionpart + '"/>';
			}
			if (text.match(/~~/)) {
				document.getElementById(editorid).innerHTML = text.replace(/~~/,imgTag);
			}
		}
		else{
			/*
			var text = document.getElementById(editorid).contentWindow.document.body.innerHTML;
			if(position=='float') {
				imgTag = imagePath + "\"" + " class=\"floatimage\" title=\"" + captionpart;//alert(imgTag);
			}
			else{
				imgTag = imagePath + "\"" + " class=\"image\" title=\"" + captionpart;
			}
			document.getElementById(editorid).contentWindow.document.execCommand('insertimage',false,imgTag);
			document.getElementById(editorid).contentWindow.document.body.innerHTML = unescape(document.getElementById(editorid).contentWindow.document.body.innerHTML);
			*/
			///*
			document.getElementById(editorid).contentWindow.document.execCommand('insertimage',false,imagePath);
			var text = document.getElementById(editorid).contentWindow.document.body.innerHTML;

			var re = new RegExp(imagePath);
			//alert(text + "\n" + re);
			//if(text.match(re))	alert(re);
			if(position=='float') {
				var regex = new RegExp(imagePath,"g");
				imgTag = imagePath + "\"" + " class=\"floatimage\" title=\"" + captionpart;
				document.getElementById(editorid).contentWindow.document.body.innerHTML = text.replace(regex,imgTag);
				//alert(document.getElementById(editorid).contentWindow.document.body.innerHTML);
			}
			else{
				var regex = new RegExp(imagePath,"g");
				imgTag = imagePath + "\"" + " class=\"image\" title=\"" + captionpart;
				document.getElementById(editorid).contentWindow.document.body.innerHTML = text.replace(regex,imgTag);
				//alert(document.getElementById(editorid).contentWindow.document.body.innerHTML);
			}
			//*/
		}
	}
}

function insertImageAndThumb(editorid, imagePath, thumbPath, position, caption) {
	if (imagePath != null && imagePath != "" && thumbPath != null && thumbPath != "") {
		if (document.all) {
			if(position=='float') {
				document.getElementById(editorid).innerHTML += '<div class="answerImageFloat" style="padding:0 5px 5px 0;margin:0 5px 0 0;float:left;border:1px solid #333;"><img src="'+imagePath+'" /><p>'+caption+'</p></div><br />';
			}else{
				document.getElementById(editorid).innerHTML += '<div class="answerImage" style="padding:0 5px 5px 0;margin:0 5px 0 0;border:1px solid #333;"><img src="'+imagePath+'" /><p>'+caption+'</p></div><br />';
			}
		}
		else{
			if(position=='float') {
				//document.getElementById(editorid).contentWindow.document.execCommand('insertimage',false,imagePath);
				document.getElementById(editorid).contentWindow.document.body.innerHTML += '<div class="answerImageFloat" style="padding:0 5px 5px 0;margin:0 5px 0 0;float:left;border:1px solid #333;"><img src="'+imagePath+'" /><p>'+caption+'</p></div><br />';
			}else{
				//document.getElementById(editorid).contentWindow.document.execCommand('insertimage',false,imagePath);
				document.getElementById(editorid).contentWindow.document.body.innerHTML += '<div class="answerImage" style="padding:0 5px 5px 0;margin:0 5px 0 0;border:1px solid #333;"><img src="'+imagePath+'" /><p>'+caption+'</p></div><br />';
			}
		}
	}
}

function insertImageUpload (editorid, imagePath, thumbPath, position) {
	if (imagePath != null && imagePath != "" && thumbPath != null && thumbPath != "") {
		if (document.all) {
			if(position=='float') {
				document.getElementById(editorid).innerHTML += '<div class="answerImageFloat" style="padding:0 5px 5px 0;margin:0 5px 0 0;float:left;border:1px solid #333;"><img src="'+thumbPath+'" /></div><br />';
			}else{
				document.getElementById(editorid).innerHTML += '<div class="answerImage" style="padding:0 5px 5px 0;margin:0 5px 0 0;border:1px solid #333;"><img src="'+thumbPath+'" /></div><br />';
			}
		}
		else{
			if(position=='float') {
				//document.getElementById(editorid).contentWindow.document.execCommand('insertimage',false,imagePath);
				document.getElementById(editorid).contentWindow.document.body.innerHTML += '<div class="answerImageFloat" style="padding:0 5px 5px 0;margin:0 5px 0 0;float:left;border:1px solid #333;"><img src="'+thumbPath+'" /></div><br />';
			}else{
				//document.getElementById(editorid).contentWindow.document.execCommand('insertimage',false,imagePath);
				document.getElementById(editorid).contentWindow.document.body.innerHTML += '<div class="answerImage" style="padding:0 5px 5px 0;margin:0 5px 0 0;border:1px solid #333;"><img src="'+thumbPath+'" /></div><br />';
			}
		}
	}
}

function insertHyperLink(editorid) {
	var httpURL = prompt("Enter a Hyper Link URL:", "http://");
	if ((httpURL != null) && (httpURL != "")) {
		document.getElementById(editorid).contentWindow.document.execCommand("CreateLink",false,httpURL);
	}
}

function insertVideo(editorid,videoURL) {
	if(!is_gecko)
		var videoURL = iePrompt("Enter a Video Link:");
	else
		var videoURL = prompt("Enter a Video Link:", "");
	if ((videoURL != null) && (videoURL != "")) {
		videoURL = videoURL.replace(/^.*\bsrc=\"(.+)\"\b.*/g,"$1");
		videoURL = videoURL.replace(/\b\".+/g,"");
		//alert(videoURL);
		
		if (document.all) {
			document.getElementById(editorid).innerHTML += '<div style=\"padding:10px 10px 10px 0;\"><iframe src=\"'+videoURL +'\" frameborder=\"0\" style=\"width:425px;height:344px;\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"></iframe></div><br />';
		}
		else{
			document.getElementById(editorid).contentWindow.document.body.innerHTML += '<div style=\"padding:10px 10px 10px 0;\"><iframe src=\"'+videoURL +'\" frameborder=\"0\" style=\"width:425px;height:344px\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"></iframe></div><br />';
		}
	}
}

function embedVideo(editorid,videoURL) {
	if ((videoURL != null) && (videoURL != "")) {
		//alert(videoURL);
		videoURL = videoURL.replace(/^.*\bsrc=\"(.+)\"\b.*/g,"$1");
		videoURL = videoURL.replace(/\b\".+/g,"");
		//alert(videoURL);
		
		if (document.all) {
			document.getElementById(editorid).innerHTML += '<iframe src=\"'+videoURL +'\" name=\"video\" frameborder=\"0\" style=\"width:425px;height:344px;\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"></iframe>';
		}
		else{
			document.getElementById(editorid).contentWindow.document.body.innerHTML += '<iframe src=\"'+videoURL +'\" name=\"video\" frameborder=\"0\" style=\"width:425px;height:344px\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"></iframe>';
		}
	}
}

/*
function embedVideo(editorid, videoURL) {
	if (videoURL != null && videoURL != "") {		
		if (document.all) {
			document.getElementById(editorid).innerHTML += '<div style="padding:10px 10px 10px 0;border:1px solid #000;width:240px;height:200px;" id="video">'+videoURL+'</div>';
		}
		else{
			document.getElementById(editorid).contentWindow.document.body.innerHTML += '<div style="padding:10px 10px 10px 0;border:1px solid #000;width:240px;height:200px;" id="video">'+videoURL+'</div>';
		}
	}	
}
*/
function insertAudio(editorid) {
	if(!is_gecko)
		var audioURL = iePrompt("Enter a Audio Link:");
	else
		var audioURL = prompt("Enter a Audio Link:", "");

	if ((audioURL != null) && (audioURL != "")) {
		audioURL = audioURL.replace(/^.*\bsrc=\"(.+)\"\b.*/g,"$1");
		audioURL = audioURL.replace(/\b\".+/g,"");
		//alert(audioURL);
		if (document.all) {
			document.getElementById(editorid).innerHTML += '<div style=\"padding:10px 10px 10px 0;\"><embed src=\"/res/dewplayer-multi.swf\" quality=\"high\" width=\"250\" height=\"20\" allowScriptAccess=\"always\" wmode=\"transparent\" type=\"application/x-shockwave-flash\" flashvars=\"mp3=' + audioURL + '\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\"></embed></div>';
		}
		else{
			document.getElementById(editorid).contentWindow.document.body.innerHTML += '<div style=\"padding:10px 10px 10px 0;\"><iframe src=\"/res/dewplayer-multi.swf?mp3=' + audioURL + '\" frameborder=\"0\" style=\"width:250px;height:20px;\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"></iframe></div>';
		}
	}
}

function setHTML(editorid, html) {
	var frameHtml = "<html id=\"" + editorid + "\">";
	frameHtml += "<head>";
	frameHtml += "<style>";
	frameHtml += "body{font-family:Arial,sans-serif;color:#595959;font-size:14px;line-height:1.5em;}";
	frameHtml += "h1{font-size:22px;margin-bottom:5px;color:#595959;} h2{font-size:18px;margin-bottom:5px;color:#595959;} h3{border-bottom:1px solid #b4b4b4;font-size:18px;margin-bottom:5px;color:#595959;}";
	frameHtml += "h4{font-size:16px;background:#FFFFA0 none repeat scroll 0 0;border:1px solid #E5E597;margin:0.9em 0;padding:0.571em 0.786em;color:#595959;}";
	frameHtml += "h5{font-size:13px;background:#F5F5F5 none repeat scroll 0 0;border:1px solid #DDDDDD;margin:0.9em 0;padding:0.571em 0.786em;color:#595959;}";
	frameHtml += "blockquote{color:#696969;font-size:18px;margin:10px;padding-left:20px;padding-right:20px;text-indent:-20px;background:url('/css/common/closequote.gif') no-repeat right bottom;} blockquote:first-letter {background:url('/css/common/openquote.gif') no-repeat left top; padding-left: 20px;}";
	frameHtml += ".image{margin:5px 5px 5px 0;display:block;} .floatimage{float:left;margin:5px 5px 5px 0;}";
	frameHtml += "</style>";
	frameHtml += "</head>";
	frameHtml += "<body>";
	frameHtml += html;
	frameHtml += "</body>";
	frameHtml += "</html>";
	var div = document.getElementById(editorid).contentWindow.document;	
	div.open();
	div.write(frameHtml);
	div.close();
}

function iePrompt(str){
   var settings = "dialogWidth: 400px; dialogHeight: 150px; center: yes; edge: raised; scroll: no; status: no; resizable: no;";
   return window.showModalDialog('/res/InsertVideo.html', str, settings);
}

function enableDesignMode(editorid,editdiv){
	var iframe = document.getElementById(editorid);
	var div = document.getElementById(editdiv);
	if (iframe.contentDocument && div)	{
		div.onmouseover = function() { 
			setTimeout( function() { iframe.contentDocument.designMode = "on"; }, 10 );
		}
	}
	else{
		iframe.contentDocument.designMode = "on"; 
	}
}

function initIFrame(editorid){  
	var ffiFrame = document.createElement("IFRAME");  
	ffiFrame.id = editorid;  
	ffiFrame.src = "blank.html";  
	document.body.appendChild(ffiFrame);
}

function toggleHighLight(div) {
	if (div) {
		curclass = div.className;
		curclass = curclass == 'highlightvisible' ? 'highlighthidden' : 'highlightvisible';
		div.className = curclass;
	}
}

function showImage(imagediv, imagePath) {
	document.getElementById(imagediv).innerHTML = '';
	document.getElementById(imagediv).innerHTML = '<img src=\"' + imagePath + '\" width=\"100\" height=\"75\" style=\"border:1px solid #007EB3;\" title=\"Preview\"><br>Preview';
}
function showImage_small(imagediv, imagePath) {
	document.getElementById(imagediv).innerHTML = '';
	document.getElementById(imagediv).innerHTML = '<img src=\"' + imagePath + '\" width=\"55\" height=\"41.25\" style=\"border:1px solid #007EB3;margin-right:10px;\" title=\"Preview\">';
}
function showImagePreviewSmall(imagediv, imagePath) {
	document.getElementById(imagediv).innerHTML = '';
	document.getElementById(imagediv).innerHTML = '<img src=\"' + imagePath + '\" width=\"24\" height=\"18\" style=\"border:1px solid #007EB3;margin-right:10px;vertical-align:middle;\" title=\"Preview\">Preview';
}

function setFormat(editorid, style) {
	switch (style){
		case "heading1":
			if(document.all) {
				document.execCommand('formatblock',false,'<h1>');
			}
			else{
				document.getElementById(editorid).contentWindow.document.execCommand('formatblock',false,'<h1>');
			}
			break;
		case "heading2":
			if(document.all) {
				document.execCommand('formatblock',false,'<h2>');
			}
			else{
				document.getElementById(editorid).contentWindow.document.execCommand('formatblock',false,'<h2>');
			}
			break;
		case "heading3":
			if(document.all) {
				document.execCommand('formatblock',false,'<h3>');
			}
			else{
				document.getElementById(editorid).contentWindow.document.execCommand('formatblock',false,'<h3>');
			}
			break;
		case "bodytext":
			unBlockQuotes(editorid);
			break;
		case "alert":
			if(document.all) {
				document.execCommand('formatblock',false,'<h4>');
			}
			else{
				document.getElementById(editorid).contentWindow.document.execCommand('formatblock',false,'<h4>');
			}
			break;
		case "note":
			if(document.all) {
				document.execCommand('formatblock',false,'<h5>');
			}
			else{
				document.getElementById(editorid).contentWindow.document.execCommand('formatblock',false,'<h5>');
			}
			break;
		case "blockquote":
			if(document.all) {
				doBlockQuotes(editorid);
			}
			else{
				document.getElementById(editorid).contentWindow.document.execCommand('formatblock',false,'<blockquote>');
			}
			break;
	}
}

function doBlockQuotes(editorid) {
// ideally we want to use .execCommand('FormatBlock',false,'<BLOCKQUOTE>') but it does not work in ie
// So since we are NEVER (famous last words) going to use the <ADDRESS> block functionality, but want our blockquote button to work like that
// we first change the block into <ADDRESS> tags, using the FormatBlock functionality of the execCommand
	document.execCommand('formatblock',false,'<ADDRESS>');

	document.getElementById(editorid).innerHTML = document.getElementById(editorid).innerHTML.replace(/<(\/?)ADDRESS>/gi, "<$1BLOCKQUOTE>");

	// then we tidy any extra <BLOCKQUOTES> that have been unhelpfully added.
	document.getElementById(editorid).innerHTML = document.getElementById(editorid).innerHTML.replace(/<BLOCKQUOTE>\s*?<BLOCKQUOTE>/gi, "<BLOCKQUOTE>");
	document.getElementById(editorid).innerHTML = document.getElementById(editorid).innerHTML.replace(/<\/BLOCKQUOTE>\s*?<\/BLOCKQUOTE>/gi, "<\/BLOCKQUOTE>");
	document.getElementById(editorid).innerHTML = document.getElementById(editorid).innerHTML.replace(/<BLOCKQUOTE>\s*?<\/BLOCKQUOTE>/gi, "");
	//alert(document.getElementById(editorid).innerHTML);
}

function unBlockQuotes(editorid) {
// well you'd think that selecting normal from the paragraph menu would revert the <blockquotes> back into <p>'s
// it does if you try it twice (once to insert <p>'s inside the <blockquotes>, the 2nd time, removing the <blockquotes>)
// that may be liveable with if not

	if(document.all) {
		// only highlighted text
		// change the formatBlock to be normal paragraphs
		document.execCommand('formatblock',false,'<p>');

		// use regexs to tidy up nested <P> tags inside <blockquotes>
		document.getElementById(editorid).innerHTML = document.getElementById(editorid).innerHTML.replace(/<BLOCKQUOTE>\s*?<P>/gi,"<p>");
		document.getElementById(editorid).innerHTML = document.getElementById(editorid).innerHTML.replace(/<\/P>s*?<\/BLOCKQUOTE>/gi,"<\/p>");
		document.getElementById(editorid).innerHTML = document.getElementById(editorid).innerHTML.replace(/<BLOCKQUOTE>\s*?<\/BLOCKQUOTE>/gi, "");
	}
	else{
		document.getElementById(editorid).contentWindow.document.execCommand('formatblock',false,'<p>');

		document.getElementById(editorid).contentWindow.document.body.innerHTML = document.getElementById(editorid).contentWindow.document.body.innerHTML.replace(/<BLOCKQUOTE>\s*?<P>/gi,"<p>");
		document.getElementById(editorid).contentWindow.document.body.innerHTML = document.getElementById(editorid).contentWindow.document.body.innerHTML.replace(/<\/P>s*?<\/BLOCKQUOTE>/gi,"<\/p>");
		document.getElementById(editorid).contentWindow.document.body.innerHTML = document.getElementById(editorid).contentWindow.document.body.innerHTML.replace(/<BLOCKQUOTE>\s*?<\/BLOCKQUOTE>/gi, "");
	}
}

function insertCharAtCaretPos(editorid) {
	// only for IE
	if (document.selection  && !is_gecko) {
		var theSelection = document.selection.createRange().text;
		document.getElementById(editorid).focus();
		if (theSelection.charAt(theSelection.length - 1) == " ") { // exclude ending space char, if any
			theSelection = theSelection.substring(0, theSelection.length - 1);
			document.selection.createRange().text = theSelection + " " + "~~";
		} 
		else {
			document.selection.createRange().text = theSelection + "~~";
		}
	} 
	// reposition cursor if possible
	if (document.getElementById(editorid).createTextRange) {
		document.getElementById(editorid).caretPos = document.selection.createRange().duplicate();
	}
}

function removeCharAtCaretPos(editorid) {
	if(document.all) {
		var text = document.getElementById(editorid).innerHTML;

		if (text.match(/~~/)) {
			document.getElementById(editorid).innerHTML = text.replace(/~~/,"");
		}
	}
}

function strip_tags(str, allowed_tags) {
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
 
	//remove script/style block
	str = str.replace(/\//gi,"\/");
	str = str.replace(/<script\b[^>]*>[\w|\t|\r|\W]*?<\/script>/gi,"");
	str = str.replace(/<style\b[^>]*>[\w|\t|\r|\W]*?<\/style>/gi,"");

    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
 
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
 
    str += '';
 
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
 
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
 
        // Save HTML tag
        html = matches[key].toString();
 
        // Is tag not in allowed list? Remove from str!
        allowed = false;
 
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i == 0) {
                allowed = true;
                break;
            }
        }
 
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
    return str;
}
