//--------------------------------------------
// Set up our simple tag open values
//--------------------------------------------

var b_open = 0
var i_open = 0
var u_open = 0
var quote_open = 0
var code_open = 0
var sql_open = 0
var html_open = 0

var bbtags = new Array()
var text_enter_url = "Ââåäèòå ïîëíûé URL ññûëêè"
var text_enter_url_name = "Ââåäèòå íàçâàíèå ñàéòà"

var frmobj = document.forms.workform
var arrInput;
var arrText;

if( frmobj != "undefined" ){
	// frmobj.onsubmit = function() { return false; }
	arrInput = frmobj.getElementsByTagName('INPUT')
	for(var i = 0, n=arrInput.length; i<n; i++){
		switch( arrInput[i].getAttribute('type') ){
			case 'text':
				arrInput[i].onkeypress = processTextKeystokes
				break;
			case 'submit':
				// not ready yet
				// arrInput[i].onsubmit
				break;
			case 'hidden':
				// do nothing
				break;
			default:
				arrInput[i].onkeypress = processOtherKeystokes;
		}
	}
	arrText = frmobj.getElementsByTagName('TEXTAREA')
	for(var i = 0, n=arrText.length; i<n; i++){
		arrText[i].onkeypress = processTextareaKeystokes
	}
}

//==========================================
// Set up
//==========================================

// Sniffer based on http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html

var uagent    = navigator.userAgent.toLowerCase()
var is_safari = ( (uagent.indexOf('safari') != -1) || (navigator.vendor == "Apple Computer, Inc.") )
var is_opera  = (uagent.indexOf('opera') != -1)
var is_kon    = (uagent.indexOf('konqueror') != -1)
var is_webtv  = (uagent.indexOf('webtv') != -1)
var is_ie     = ( (uagent.indexOf('msie') != -1) && (!is_opera) && (!is_safari) && (!is_webtv) )
var is_ie4    = ( (is_ie) && (uagent.indexOf("msie 4.") != -1) )
var is_moz    = (navigator.product == 'Gecko')
var is_ns     = ( (uagent.indexOf('compatible') == -1) && (uagent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_safari) )
var is_ns4    = ( (is_ns) && (parseInt(navigator.appVersion) == 4) )

var is_win    =  ( (uagent.indexOf("win") != -1) || (uagent.indexOf("16bit") !=- 1) )
var is_mac    = ( (uagent.indexOf("mac") != -1) || (navigator.vendor == "Apple Computer, Inc.") )
var ua_vers   = parseInt(navigator.appVersion)


//==========================================
function processTextKeystokes(evt)
{
	if(window.event) evt = window.event

	if(evt.keyCode == 13){
		submitByKeypress()

		if(evt.preventDefault){
			evt.preventDefault()
		}
		if(evt.stopPropagation){
			evt.stopPropagation()
		}

		return false;
	}
}

//==========================================
function processTextareaKeystokes(e)
{
	if ( window.event ) e = window.event
	if( e.shiftKey && e.ctrlKey ){
		switch(e.keyCode)
		{
			case 66:
				// insert [b] if Ctrl+Shift+B pressed
				simpletag('b')
				break;
			case 67:
				// insert [code] if Ctrl+Shift+C pressed
				simpletag('code')
				break;
			case 73:
				// insert [i] if Ctrl+Shift+I pressed
				simpletag('I')
				break;
			case 81:
				// insert [quote] if Ctrl+Shift+Q pressed
				simpletag('quot')
				break;
			case 84:
				// insert TAB character if Ctrl+Shift+T pressed
				doInsert('\t','',1)
				break;
			case 85:
				// insert [url] if Ctrl+Shift+U pressed
				tag_url()
				if ( window.event ){
					e.returnValue = false
				} else {
					e.preventDefault()
				}
				break;
		}
	} else {
		if ( e.ctrlKey && !e.shiftKey && e.keyCode == 13 ){
			// Submit form if Ctrl+Enter pressed
			submitByKeypress()
		}
	}
}

//==========================================
function processOtherKeystokes(e){
	if ( window.event ) e = window.event
	if ( e.ctrlKey && !e.shiftKey && e.keyCode == 13 ){
		// Submit form if Ctrl+Enter pressed
		submitByKeypress()
	}
}


//==========================================
function submitByKeypress(){
	var s = '';
	for(var i=0, n=arrInput.length; i<n; i++){
		//alert(arrInput[i].name + ' ' + getStyle(arrInput[i], 'display'));
		if(
			arrInput[i].getAttribute('type') == "submit"
			&& getStyle(arrInput[i], 'display') == "block"
		){
			s = arrInput[i].getAttribute('name') + '=' + arrInput[i].getAttribute('value');
		}
	}
	if ( s != '' ){
		frmobj.action += ( frmobj.action.indexOf('?') == -1) ? '?' : '&';
		frmobj.action += s;
		//alert(frmobj.action);
		//return false;
		frmobj.submit();
	}
}


//==========================================
// Get a style property (name) of a specific element (elem)
function getStyle(elem, name) {
	// If the property exists in style[], then it's been set
	// recently (and is current)
	if (elem.style[name])
		return elem.style[name];
	
	// Otherwise, try to use IE's method
	else if (elem.currentStyle)
		return elem.currentStyle[name];
	
	// Or the W3C's method, if it exists
	else if (document.defaultView && document.defaultView.getComputedStyle) {
		// It uses the traditional 'text-align' style of rule writing,
		// instead of textAlign
		name = name.replace(/([A-Z])/g,"-$1");
		name = name.toLowerCase();
		// Get the style object and get the value of the property (if it exists)
		var s = document.defaultView.getComputedStyle(elem,"");
		return s && s.getPropertyValue(name);
	}
	// Otherwise, we're using some other browser
	else
		return null;
}


//==========================================
// Array: Get stack size
//==========================================

function stacksize(thearray)
{
	for (i = 0 ; i < thearray.length; i++ )
	{
		if ( (thearray[i] == "") || (thearray[i] == null) || (thearray == 'undefined') )
		{
			return i
		}
	}
	
	return thearray.length
}

//==========================================
// Array: Push stack
//==========================================

function pushstack(thearray, newval)
{
	arraysize = stacksize(thearray)
	thearray[arraysize] = newval
}

//==========================================
// Array: Pop stack
//==========================================

function popstack(thearray)
{
	arraysize = stacksize(thearray)
	theval = thearray[arraysize - 1]
	delete thearray[arraysize - 1]
	return theval
}

//==========================================
// Get cookie
//==========================================

function my_getcookie( name )
{
	cname = name + '='
	cpos  = document.cookie.indexOf( cname )
	
	if ( cpos != -1 )
	{
		cstart = cpos + cname.length
		cend   = document.cookie.indexOf(";", cstart)
		
		if (cend == -1)
		{
			cend = document.cookie.length
		}
		
		return unescape( document.cookie.substring(cstart, cend) )
	}
	
	return null
}

//==========================================
// Set cookie
//==========================================

function my_setcookie( name, value, sticky )
{
	expire = ""
	domain = ""
	path   = "/"
	
	if ( sticky )
	{
		expire = "; expires=Wed, 1 Jan 2020 00:00:00 GMT"
	}
	
	document.cookie = name + "=" + value + "; path=" + path + expire + domain + ';'
}

function get_easy_mode_state()
{
	return false
}

//==========================================
// Set the number of tags open box
//==========================================

function cstat()
{
	var c = stacksize(bbtags)
	
	if ( (c < 1) || (c == null) ) {
		c = 0
	}
	
	if ( ! bbtags[0] ) {
		c = 0
	}
}


//==========================================
// Close all tags
//==========================================

function closeall()
{
	if (bbtags[0])
	{
		while (bbtags[0])
		{
			tagRemove = popstack(bbtags)
			frmobj.body.value += "[/" + tagRemove + "]"
			
			eval(tagRemove + "_open = 0")
		}
	}
	bbtags = new Array()
	frmobj.body.focus()
}

//==========================================
// ADD CODE
//==========================================

function add_code(NewCode)
{
    frmobj.body.value += NewCode
    frmobj.body.focus()
}

//==========================================
// SIMPLE TAGS (such as B, I U, etc)
//==========================================

function simpletag(thetag,fieldname)
{
	var tagOpen = eval(thetag + "_open")
	
	if ( get_easy_mode_state() )
	{
		inserttext = prompt(prompt_start + "\n[" + thetag + "]xxx[/" + thetag + "]")
		if ( (inserttext != null) && (inserttext != "") )
		{
			doInsert("[" + thetag + "]" + inserttext + "[/" + thetag + "] ", "", false, fieldname)
		}
	}
	else
	{
		if (tagOpen == 0)
		{
			if(doInsert("[" + thetag + "]", "[/" + thetag + "]", true, fieldname))
			{
				eval(thetag + "_open = 1")
				
				//--------------------------------------------
				// Change the button status
				//--------------------------------------------
				
				pushstack(bbtags, thetag)
				cstat()
			}
		}
		else
		{
			//--------------------------------------------
			// Find the last occurance of the opened tag
			//--------------------------------------------
			lastindex = 0
			
			for (i = 0 ; i < bbtags.length; i++ )
			{
				if ( bbtags[i] == thetag )
				{
					lastindex = i
				}
			}
			
			//--------------------------------------------
			// Close all tags opened up to that tag was opened
			//--------------------------------------------
			
			while (bbtags[lastindex])
			{
				tagRemove = popstack(bbtags)
				doInsert("[/" + tagRemove + "]", "", false, fieldname)
				
				eval(tagRemove + "_open = 0")
			}
			
			cstat()
		}
	}
}

//==========================================
// URL tag
//==========================================

function tag_url(fieldname)
{
    var FoundErrors = ''
    var enterURL   = prompt(text_enter_url, "http://")
    var enterTITLE = prompt(text_enter_url_name, "My Webpage")

    if (!enterURL) {
        FoundErrors += " " + error_no_url
    }
    if (!enterTITLE) {
        FoundErrors += " " + error_no_title
    }

    if (FoundErrors) {
        alert("Error!"+FoundErrors)
        return
    }

	doInsert('[url="'+enterURL+'"]'+enterTITLE+'[/url]', '', false, fieldname)
}

//==========================================
// Insert attachment tag
//==========================================

function insert_attach_to_textarea(aid)
{
	doInsert( "[attachmentid="+aid+"]" )
}


//--------------------------------------------
// GENERAL INSERT FUNCTION
//--------------------------------------------
// ibTag: opening tag
// ibClsTag: closing tag, used if we have selected text
// isSingle: true if we do not close the tag right now
// return value: true if the tag needs to be closed later

//

function doInsert(ibTag, ibClsTag, isSingle, fieldname)
{
	var isClose = false
	if(fieldname){
		var obj_ta = frmobj.elements[fieldname]
	} else {
		var obj_ta = frmobj.body
	}
	
	//----------------------------------------
	// It's IE!
	//----------------------------------------
	if ( (ua_vers >= 4) && is_ie && is_win)
	{
		if (obj_ta.isTextEdit)
		{
			obj_ta.focus()
			var sel = document.selection
			var rng = sel.createRange()
			rng.colapse
			if((sel.type == "Text" || sel.type == "None") && rng != null)
			{
				if(ibClsTag != "" && rng.text.length > 0)
					ibTag += rng.text + ibClsTag
				else if(isSingle)
					isClose = true
	
				rng.text = ibTag
			}
		}
		else
		{
			if(isSingle)
			{
				isClose = true
			}
			
			obj_ta.value += ibTag
		}
	}
	//----------------------------------------
	// It's MOZZY!
	//----------------------------------------
	
	else if ( obj_ta.selectionEnd )
	{ 
		var ss = obj_ta.selectionStart
		var st = obj_ta.scrollTop
		var es = obj_ta.selectionEnd
		
		if (es <= 2)
		{
			es = obj_ta.textLength
		}
		
		var start  = (obj_ta.value).substring(0, ss)
		var middle = (obj_ta.value).substring(ss, es)
		var end    = (obj_ta.value).substring(es, obj_ta.textLength)
		
		//-----------------------------------
		// text range?
		//-----------------------------------
		
		if (obj_ta.selectionEnd - obj_ta.selectionStart > 0)
		{
			middle = ibTag + middle + ibClsTag
		}
		else
		{
			middle = ibTag + middle
			
			if (isSingle)
			{
				isClose = true
			}
		}
		
		obj_ta.value = start + middle + end
		
		var cpos = ss + (middle.length)
		
		obj_ta.selectionStart = cpos
		obj_ta.selectionEnd   = cpos
		obj_ta.scrollTop      = st


	}
	//----------------------------------------
	// It's CRAPPY!
	//----------------------------------------
	else
	{
		if (isSingle)
		{
			isClose = true
		}
		
		obj_ta.value += ibTag
	}
	
	obj_ta.focus()

	return isClose
}	

