// Startup variables
var imageTag = false;
var theSelection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Helpline messages
var b_help = "Bold text: [b]text[/b]  (alt+b)";
var i_help = "Italic text: [i]text[/i]  (alt+i)";
var u_help = "Underline text: [u]text[/u]  (alt+u)";
var q_help = "Quote text: [quote]text[/quote]  (alt+q)";
var c_help = "Code display: [code]code[/code]  (alt+c)";
var l_help = "Unodered list: [list]text[/list] (alt+l)";
var oa_help = "Ordered list: [list=a]text[/list]  (alt+o)";
var o1_help = "Ordered list: [list=1]text[/list]  (alt+1)";
var p_help = "Insert normal image: [img]http://image_url[/img]  (alt+r)";
var pr_help = "Insert right aligned image text wrapped : [imgr]http://image_url[/imgr]  (alt+pr)";
var pl_help = "Insert left aligned image text wrapped : [imgl]http://image_url[/imgl]  (alt+pl)";
var w_help = "Insert URL: [url]http://url[/url] or [url=http://url]URL text[/url]  (alt+w)";
var a_help = "Close all open bbCode tags";
var s_help = "Font color: [color=red]text[/color]  Tip: you can also use color=#FF0000";
var f_help = "Font size: [size=x-small]small text[/size]";
var li_help = "list item: [*]text[/*] (alt+*)";

// Define the bbCode tags
var bbcode = new Array();
//                         2             4            6                  8                  10                 12                    14                 16                 18           20                   22               24
var bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=a]','[/list]' ,'[img]','[/img]', '[url]','[/url]','[*]','[/*]','[list=1]','[/list]','[imgr]','[/imgr]' ,'[imgl]','[/imgl]');

// funciones para cambiar el estilo de los elementos de los formularios
function gotfocus(anelement) {
	anelement.style.backgroundColor = "#FFFFE3";
}

function lostfocus(anelement) {
	anelement.style.backgroundColor = ''; //"#FFFFFF";
}

//funcion para cargar las imagenes ocultas.
function preloadimages() {
	document.IMGS = new Array();
	
	var i; 
	for (i = 0; i < arguments.length; i++) {
		document.IMGS[i] = new Image(); 
		document.IMGS[i].src = arguments[i];
	}
}

//funciones del forum.
// Shows the help messages in the helpline window
function helpline(help, aform) {
  aform.helpbox.value = eval(help + "_help");
}

// Replacement for arrayname.length property
function getarraysize(thearray) {
  for (i = 0; i < thearray.length; i++) {
    if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
      return i;
    }
  return thearray.length;
}

// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
  thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
  thearraysize = getarraysize(thearray);
  retval = thearray[thearraysize - 1];
  delete thearray[thearraysize - 1];
  return retval;
}

function bbstyle(bbnumber, atxtarea) {
	var txtarea = atxtarea;
	
	frmname = txtarea.form.name;
  txtarea.focus();
  donotinsert = false;
  theSelection = false;
  bblast = 0;

  if (bbnumber == -1) { // Close all open tags & default button names
    while (bbcode[0]) {
      butnumber = arraypop(bbcode) - 1;
      txtarea.value += bbtags[butnumber + 1];
      buttext = eval('document. ' + frmname + '.addbbcode' + butnumber + '.value');
      eval('document. ' + frmname + '.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
    }
    imageTag = false; // All tags are closed including image tags :D
    txtarea.focus();
    return;
  }

  if ((clientVer >= 4) && is_ie && is_win)
  {
    theSelection = document.selection.createRange().text; // Get text selection
    if (theSelection) {
      // Add tags around selection
      document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
      txtarea.focus();
      theSelection = '';
      return;
    }
  }
  else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
  {
    mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
    return;
  }

  // Find last occurance of an open tag the same as the one just clicked
  for (i = 0; i < bbcode.length; i++) {
    if (bbcode[i] == bbnumber+1) {
      bblast = i;
      donotinsert = true;
    }
  }

  if (donotinsert) {    // Close all open tags up to the one just clicked & default button names
    while (bbcode[bblast]) {
        butnumber = arraypop(bbcode) - 1;
        txtarea.value += bbtags[butnumber + 1];
        buttext = eval('document. '+ frmname + '.addbbcode' + butnumber + '.value');
        eval('document. ' + frmname + '.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
        imageTag = false;
      }
      txtarea.focus();
      return;
  } else { // Open tags

    if (imageTag && (bbnumber != 14)) {    // Close image tag before adding another
      txtarea.value += bbtags[15];
      lastValue = arraypop(bbcode) - 1;  // Remove the close image tag from the list
      eval('document. ' + frmname + '.addbbcode14.value = "Img"');  // Return button back to normal state
      imageTag = false;
    }

    // Open tag
    txtarea.value += bbtags[bbnumber];
    if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
    arraypush(bbcode,bbnumber+1);
    eval('document. ' + frmname + '.addbbcode'+bbnumber+'.value += "*"');
    txtarea.focus();
    return;
  }
  storeCaret(txtarea);
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close) {
  var selLength = txtarea.textLength;
  var selStart = txtarea.selectionStart;
  var selEnd = txtarea.selectionEnd;
  if (selEnd == 1 || selEnd == 2)
    selEnd = selLength;

  var s1 = (txtarea.value).substring(0,selStart);
  var s2 = (txtarea.value).substring(selStart, selEnd)
  var s3 = (txtarea.value).substring(selEnd, selLength);
  txtarea.value = s1 + open + s2 + close + s3;
  return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
  if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

function emoticon(text) {
  var txtarea = document.frm_msg.ta_msg;
	
  text = ' ' + text + ' ';
  if (txtarea.createTextRange && txtarea.caretPos) {
    var caretPos = txtarea.caretPos;
    caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
    txtarea.focus();
  } else {
    txtarea.value  += text;
    txtarea.focus();
  }
}

function isEqualorGraterThan(gstrdate, lstrdate) {
	var gdate = new Date(gstrdate.replace(/-/g, ' '));
	var ldate = new Date(lstrdate.replace(/-/g, ' '));
	return (gdate.getTime() >= ldate.getTime());
}

function _00_format(strMonth_or_Day) {
	if ((strMonth_or_Day > 0) && (strMonth_or_Day < 10)) {
		strMonth_or_Day = '0' + strMonth_or_Day  	
	}
	
	return strMonth_or_Day
}

function formatMySQLDate(aDate) {
  var aFormatedDate = '';
	
	aFormatedDate = aDate.getFullYear() + '-' + _00_format(aDate.getMonth()+1) + '-' + _00_format(aDate.getDate());
	
  return aFormatedDate;	
}

function formatMySQLDateTime(aDate) {
  var aFormatedDate = '';
	
	aFormatedDate = aDate.getFullYear() + '-' + _00_format(aDate.getMonth()+1) + '-' + _00_format(aDate.getDate()) + ' ' + aDate.getHours() + ':' + aDate.getMinutes() + ':' + aDate.getSeconds();
	
  return aFormatedDate;
}

function checkifnumber(evt) {
	evt = (evt) ? evt : window.event
	var charCode = (evt.which) ? evt.which : evt.keyCode
	
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		status = "This field accepts numbers only."
		return false
	}
	
	status = ""
	return true
}

function checkifpercentage(evt, atxt) {
	var accept = false;
	
	evt = (evt) ? evt : window.event
	//var key = (evt.which) ? evt.which : evt.keyCode
	var key = (evt.charCode) ? evt.charCode : evt.keyCode
	
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57	
	if (key < 32) {
		accept = true;	
	} else {
		
		switch (atxt.value) {
			case 'N': //si esta la N solo se puede agregar una A
				// a = 97; A = 65 -> 'NA' = accept
				if ((key == 97) || (key == 65)) {
					atxt.value = 'NA';
				}
				break;
			default:
				// '0' = 48; '9' = 57; N = 78; n = 110
				if ((key >= 48 && key <= 57) || (key == 78) || (key == 110)) {
					if ((key == 78) || (key == 110)) { //si es N o n poner NA
						if (atxt.value == '') atxt.value = 'NA';
					} else {
						accept = ((atxt.value + String.fromCharCode(key)) <= 100);
					}
				}
				break;
		}
		
	}
	return accept; //por defecto es false para evitar que el browser escriba la tecla generada en el evento keypress
}

function checkifalphaeffort(evt, atxt) {
	//Los posibles valores son A*, A, B, C, D, E, F, G y U con + o -
	var accept = false;
	
	evt = (evt) ? evt : window.event
	//var key = (evt.which) ? evt.which : evt.keyCode
	var key = (evt.charCode) ? evt.charCode : evt.keyCode
	
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57	
	if (key < 32) {
		accept = true;	
	} else {
		switch (atxt.value) {
			case 'A': //si ya esta la A, solo se puede agregar un *, + o -
				// * = 42 -> 'A*' = accept
				accept = ((key == 42) || (key == 43) || (key == 45));
				break;
			case 'B':  //se puede agregar + o - 
			case 'C':
			case 'D':
			case 'E':
			case 'F':
			case 'G':
			case 'U':
				// + = 43; - = 45
				if ((key == 43) || (key == 45)) {
					atxt.value += String.fromCharCode(key);
				}
				break;
			case 'N': //si esta la N solo se puede agregar una A
				// a = 97; A = 65 -> 'NA' = accept
				if ((key == 97) || (key == 65)) {
					atxt.value = 'NA';
				}
				break;
			case '':
				//toUpperCase a = 97 - 32 = A
				if (key >= 97) key -= 32;
				// A = 65; G = 71; U = 85; N = 78->se convierte en NA
				if ((key >= 65 && key <= 71) || (key == 85) || (key == 78)) {
					if (key == 78) { //si es N poner NA
						atxt.value = 'NA';
					} else {
						atxt.value = String.fromCharCode(key);
					}
				}
				break;
		}

	}
	return accept; //por defecto es false para evitar que el browser escriba la tecla generada en el evento keypress
}

//funcion para convertir caracteres ASCII del 128 al 159 a &#ascii;
//para hacer el texto compatible con Windows-1252 por IE
function charcode_windows1252(txt) {
	var txt1252 = txt;

	txt1252 = txt1252.replace(/€/g,'&#8364;');
	txt1252 = txt1252.replace(//g,'&#129;');
	txt1252 = txt1252.replace(/‚/g,'&#8218;');
	txt1252 = txt1252.replace(/ƒ/g,'&#402;');
	txt1252 = txt1252.replace(/„/g,'&#8222;');
	txt1252 = txt1252.replace(/…/g,'&#8230;');
	txt1252 = txt1252.replace(/†/g,'&#8224;');
	txt1252 = txt1252.replace(/‡/g,'&#8225;');
	txt1252 = txt1252.replace(/ˆ/g,'&#710;');
	txt1252 = txt1252.replace(/‰/g,'&#8240;');
	txt1252 = txt1252.replace(/Š/g,'&#352;');
	txt1252 = txt1252.replace(/‹/g,'&#8249;');
	txt1252 = txt1252.replace(/Œ/g,'&#338;');
	txt1252 = txt1252.replace(/ì/g,'&#236;');
	txt1252 = txt1252.replace(/Ž/g,'&#381;');
	txt1252 = txt1252.replace(//g,'&#143;');
	txt1252 = txt1252.replace(//g,'&#144;');
	txt1252 = txt1252.replace(/‘/g,'&#8216;');
	txt1252 = txt1252.replace(/’/g,'&#8217;');
	txt1252 = txt1252.replace(/“/g,'&#8220;');
	txt1252 = txt1252.replace(/”/g,'&#8221;');
	txt1252 = txt1252.replace(/•/g,'&#8226;');
	txt1252 = txt1252.replace(/–/g,'&#8211;');
	txt1252 = txt1252.replace(/—/g,'&#8212;');
	txt1252 = txt1252.replace(/˜/g,'&#732;');
	txt1252 = txt1252.replace(/™/g,'&#8482;');
	txt1252 = txt1252.replace(/š/g,'&#353;');
	txt1252 = txt1252.replace(/›/g,'&#8250;');
	txt1252 = txt1252.replace(/œ/g,'&#339;');
	txt1252 = txt1252.replace(//g,'&#157;');
	txt1252 = txt1252.replace(/ž/g,'&#382;');
	txt1252 = txt1252.replace(/Ÿ/g,'&#376;');
	
	return txt1252;
}

var _PENDINGREQUESTS = 0; //contador de pedidos XMLHTTP

//funcion para enviar un HTTPRequest al servidor
function submit_phpcall(callback, phpfunction) {
	_PENDINGREQUESTS++;
	
	var objXMLhttp = null; //inicializar objeto XMLHTTP
	try {
		objXMLhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			objXMLhttp= new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
				try {
					objXMLhttp = new XMLHttpRequest();
				} catch (e) {
					//Do nothing
				}	
		}
	}

	var ok = '';
	
	if (objXMLhttp != null) {
		// Usar true como ultimo parametro para conexion asincronica y false para sincronica
		objXMLhttp.open ('POST', '/scripts/sysHTTPresponse.php', (callback != null));
		objXMLhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	
		objXMLhttp.onreadystatechange = function() {
			if (objXMLhttp.readyState == 4) {
				// Retrieve txt data
				if (objXMLhttp.status == 200) {
					ok = objXMLhttp.responseText;
				} else {
					ok = 'XMLhttpRequest Error: ' + objXMLhttp.status;
				}

				if (callback != null) {
					callback(ok);
				}
			}
		};

		//formar los parametros
		var args = '&phpfunction=' + phpfunction;
		for (var i = 2; i < arguments.length; i++) {
			args += '&arg' + (i - 2) + '=' + arguments[i];
		}

		// Make the request
		objXMLhttp.send (args);
	}
	
	//solo en el caso de que la conexion sea sincronica, es util el valor devuelto
	return ok;
}

//funcion para llenar un <select></select> (acmb) con las opciones segun el contenido del control opts
//opts esta formado por expresiones javascript separadas por ~
//ej: opt.value='1';opt.text='primero';opt.selected=true~opt.value='0';opt.text='segundo';~
function	fillselect(acmb, opts) {
	var arropts = opts.split("~");
	var opt = null;
	
	//limpiar el <select /> por si tiene elementos
	while (acmb.length > 0) {
    acmb.remove(0);
	} 
	
	//agregar las opciones. Siempre arropts.length - 1 porque al final de cada option hay un ~ y el split agrega un elemento nulo al final
	for (var i = 0; i < arropts.length - 1; i++) {
		opt = document.createElement("option");
		eval(arropts[i]); //ejecutar las expresiones de opts
		
		try { 
			acmb.add(opt, null); //NN y FF way
		} catch (e) {
			try {
				acmb.add(opt); //IE way
			} catch (e) {}	
		}
		
	}
}

//funcion para mostrar la opcion "Loading..." seleccionada en un <select />
function setloading(acmb) {
	opt = document.createElement("option");
	opt.text = 'loading...';
	opt.selected = true;
	
	try { 
		acmb.add(opt, null); //NN y FF way
	} catch (e) {
		try {
			acmb.add(opt); //IE way
		} catch (e) {}	
	}

	acmb.disabled = false;	
}

//evento before unload para evitar que los usuarios cambien de pagina sin salvar los cambios
var glob_modified = false;
window.onbeforeunload = function (ev) {
	if (glob_modified) {
		var msg = "You have changed data, discard changes?";
		try {
			event.returnValue = msg;
		} catch (ex) {
			ev.returnValue = msg; //return msg;
		}
	}
}

function isPattern(avalue,pattern) {
	var regExp = new RegExp("^"+pattern+"$","");
	var correct = regExp.test(avalue);
	return correct;
}

function isTime24Hrs(avalue) {
	return isPattern(avalue, "(20|21|22|23|[01]\\d|\\d)(([:][0-5]\\d){1,2})");
}


