function keypress_uppercase(event)
{
	if (!window.event)
		return;
	
	event = window.event;

	if (event.which)
		return;
	
	if (event.keyCode > 0x60 && event.keyCode < 0x7B)
		event.keyCode = event.keyCode - 0x20;	
}

function blur_uppercase(input)
{
	input.value = input.value.toUpperCase();
}

var combo_previous = {};

function check_edit(id,value)
{
	var combo = $(id + 'Id');
	var edit = $(id + 'Name');
	
	if(combo.options)
	{
		//if (combo.selectedIndex == 0)	 // commented by AG	version 1.7.5 phase I
		if (combo.options[combo.selectedIndex].value == 0)
		{
			combo.style.display = 'none';
			edit.style.display = 'inline';
	
			edit.value = value;
			edit.focus();  // commented by ajay giri
		}
		else
		{
			combo_previous[id] = combo.selectedIndex;
		}
	}
}

function check_combo(event, id)
{
	if (window.event)
		event = window.event;
	
	if (event.which)
		key = event.which;
	else
		key = event.keyCode;
	
	if (key == 27)
	{
		var combo = $(id + 'Id');
		var edit = $(id + 'Name'); 
		
		if(combo)
		{
			combo.selectedIndex = combo_previous[id];
			
			edit.style.display = 'none';
			edit.value = '';  //  added by ajaygiri
			combo.style.display = 'inline';
		}
	}
	
}

function show_message(msg,action,url,width,height)
{
	retVal = '';
	
	//popup_window('bericht.php?bericht=' + encodeURIComponent(msg), 400, 100, true);
	if(action == 'Error')
	{
       if(typeof(width) == 'undefined') 
	   {
	      width = 	 400;
	   }
	   if(typeof(height) == 'undefined')
	   {
	      height =  115;
	   }	   
	   retVal = popup_window(url+'showerrormessage.tpl.php?message=' + encodeURIComponent(msg), width, height, true); 
	}
	else if(action == 'Cancel')
	   retVal = popup_window(url+'showmessage.tpl.php?message=' + encodeURIComponent(msg), 400, 120, true);
	else if(action == 'Save')   
	   retVal = popup_window(url+'showsavemessage.tpl.php?message=' + encodeURIComponent(msg), 400, 130, true);
    else if(action == 'NoSave')   
	   retVal = popup_window(url+'shownosavemessage.tpl.php?message=' + encodeURIComponent(msg), 400, 130, true);
    else if(action == 'Remove')   
       retVal = popup_window(url+'showremovemessage.tpl.php?message=' + encodeURIComponent(msg), 400, 115, true);
	else if(action == 'Exit')   
       retVal = popup_window(url+'exitpagemessage.tpl.php?message=' + encodeURIComponent(msg), 400, 115, true);	 
	else if(action == 'ContactSearch')   
       retVal = popup_window(url+'showconfirmcontactsearch.tpl.php?message=' + encodeURIComponent(msg), 400, 120, true);    
	else if(action == 'AnimalSearch')   
       retVal = popup_window(url+'showconfirmanimalsearch.tpl.php?message=' + encodeURIComponent(msg), 400, 120, true); 
	else if(action == 'CreateAccounts')   
       retVal = popup_window(url+'showaccountsmessage.tpl.php?message=' + encodeURIComponent(msg), 400, 120, true); 
	else if(action == 'ConfirmConversion')   
       retVal = popup_window(url+'showconversionmessage.tpl.php?message=' + encodeURIComponent(msg), 400, 150, true);
	else if(action == 'Kennelclub')   
       retVal = popup_window(url+'showkennelclubmessage.tpl.php?message=' + encodeURIComponent(msg), 400, 115, true); 
	else if(action == 'ErrorImport')   
       retVal = popup_window(url+'showerrormessage.tpl.php?message=' + encodeURIComponent(msg), 400, 125, true);
	else if(action == 'ErrorImportAnimal')   
       retVal = popup_window(url+'showimportfilemessage.tpl.php?message=1', 400, 125, true);
	else if(action == 'importExtraBreedingPair')   
        retVal = popup_window(url+'showerrormessage.tpl.php?message=' + encodeURIComponent(msg), 400, 125, true);
	else if(action == 'Restore')
	   retVal = popup_window(url+'showconfirmrestore.tpl.php?message=' + encodeURIComponent(msg), 400, 120, true);
	else if(action == 'Waiting')
	   retVal = popup_window(url+'showwaitinginsertmessage.tpl.php?Id='+msg, 450, 220, true);
	else if(action == 'BackupRestoreMessage')   
       retVal = popup_window(url+'showerrormessage.tpl.php?message=' + encodeURIComponent(msg), 400, 130, true);
	else if(action == 'ExecuteStatement')   
       retVal = popup_window(url+'showexecutestatementmessage.tpl.php?message=' + encodeURIComponent(msg), 420, 120, true);
	else if(action == 'ContactChange') 
       retVal = popup_window(url+'showaccountsmessage2.tpl.php?message=' + encodeURIComponent(msg), 400, 140, true); 
	else if(action == 'ExitOutstanding')   
       retVal = popup_window(url+'exitpagemessage.tpl.php?message=' + encodeURIComponent(msg), 420, 125, true);	
	else if(action == 'IandR') 
	   retVal = popup_window(url+'showiandrmessage.tpl.php?message=' + encodeURIComponent(msg), 400, 130, true);
	else if(action == 'confirmation') 
	   retVal = popup_window(url+'showconfirmationmessage.tpl.php?message=' + encodeURIComponent(msg), 400, 125, true);
	else if(action == 'confirmationcode') 
	   retVal = popup_window(url+'showconfirmationcodemessage.tpl.php?message=' + encodeURIComponent(msg), 400, 130, true);
	else if(action == 'graph') 
	   retVal = popup_window(url+'showgraphmessage.tpl.php?message=' + encodeURIComponent(msg), 400, 130, true);
	  
	return retVal;
}

function show_message_country(msg)
{
	popup_window('bericht.php?bericht=' + encodeURIComponent(msg), 400, 100, true);
}


function popup_window(url, width, height, domodal)
{
	// Added by Ajay Giri 
	browser_name = detectBrowser_2();
	if(browser_name == 6)
	   height = ((45 * height)/100) + height; // In IE6, window height is 45% less as compared
	                                          // to IE7, so increase height by 45% in IE6
	// End of addition
	
	
	retVal = '';
	if (domodal && window.showModalDialog)
	{		
		var windowWidth = 400;
		var windowHeight = 400;
		var centerWidth = (window.screen.width - windowWidth) / 2;
	    var centerHeight = (window.screen.height - windowHeight) / 2 + 100 ;
		
		retVal = window.showModalDialog(url, window, "dialogWidth:" + (width ? width : '500') + "px;dialogHeight=" + (height ? height : '400') + "px;dialogLeft ="+centerWidth+";dialogTop ="+centerHeight+"; resizable: no");		
		return retVal;
	}
		
	else
	{		
		var windowWidth = 500;
		var windowHeight = 400;
		var centerWidth = (window.screen.width - windowWidth) / 2;
	    var centerHeight = (window.screen.height - windowHeight) / 2 + 100 ;
		
		window.open(url, "", "width="+(width ? width : '500')+"px,height="+(height ? height : '400')+"px,left ="+centerWidth+",top ="+centerHeight+",scrollbars=yes,location=no,toolbar=no,menubar=no,directories=no,status=yes,resizable=no");
		
		// dialog=YES,modal=YES .. removed by Ajay Giri
		//return retVal;		
	}
}

function popup_window_2(url, width, height, domodal)
{
	// Added by Ajay Giri 
	browser_name = detectBrowser_2();
	if(browser_name == 6)
	   height = ((45 * height)/100) + height; // In IE6, window height is 45% less as compared
	                                          // to IE7, so increase height by 45% in IE6
	// End of addition
	
	
	retVal = '';
	if (domodal && window.showModalDialog)
	{
		var windowWidth = 400;
		var windowHeight = 400;
		var centerWidth = (window.screen.width - windowWidth) / 2;
	    var centerHeight = (window.screen.height - windowHeight) / 2 + 100 ;
		
		retVal = window.showModalDialog(url, window, "dialogWidth:" + (width ? width : '500') + "px;dialogHeight=" + (height ? height : '400') + "px;dialogLeft ="+centerWidth+";dialogTop ="+centerHeight+"; resizable: yes");		
		return retVal;
	}
		
	else
	{		
		var windowWidth = 500;
		var windowHeight = 400;
		var centerWidth = (window.screen.width - windowWidth) / 2;
	    var centerHeight = (window.screen.height - windowHeight) / 2 + 100 ;
		
		window.open(url, "", "width="+(width ? width : '500')+"px,height="+(height ? height : '400')+"px,left ="+centerWidth+",top ="+centerHeight+",scrollbars=yes,location=no,toolbar=no,menubar=no,directories=no,status=yes,resizable=yes");
		
		// dialog=YES,modal=YES .. removed by Ajay Giri
		//return retVal;		
	}
}

function check_popup_box(e)
{
	if (!v_popupbox)
		return;
		
	Event.stopObserving(document, 'mousedown', check_popup_box);
	
	Element.hide(v_popupbox);
	v_popupbox = null;
}

function popup_box(from)
{
	// Show date picker at mouse position
	var item = $('popup_box_container');

	if (!item)
		return;
	
	v_popupbox = item;
	document.body.appendChild(v_popupbox);
	
	Element.setStyle(v_popupbox, {left: '0px', top: '0px'});
	
	var pos = Position.cumulativeOffset(from);

	Element.setStyle(v_popupbox, {left: pos[0] + 'px', top: pos[1] + 'px'});
	v_popupbox.style.display = 'inline';
	//Event.observe(document, 'mousedown', check_popup_box); // By Ajay Giri
}

function popup_box_2(from)
{
	// Show date picker at mouse position
	var item = $('popup_box_container');

	if (!item)
		return;
	
	v_popupbox = item;
	document.body.appendChild(v_popupbox);
	
	Element.setStyle(v_popupbox, {left: '0px', top: '0px'});
	
	var pos = Position.cumulativeOffset(from);
	
	pos[0] = pos[0] - 50;

	Element.setStyle(v_popupbox, {left: pos[0] + 'px', top: pos[1] + 'px'});
	v_popupbox.style.display = 'inline';
	//Event.observe(document, 'mousedown', check_popup_box); // By Ajay Giri
}


function init_online()
{
	var items = $$('div.pages, div.module');
	
	for (var i = 0; i < items.length; i++)
		$('thecontent').appendChild(items[i]);

}

function email_beheerder(onderwerp)
{
	popup_window("email.php?onderwerp=" + onderwerp, 500, 350);
}

var v_popupbox = null;

document.writeln('<a id="message_dummy" href="#" rel="lightbox"></a>');

if(Event.observe)
   Event.observe(window, 'load', init_online, false);

function email_admin( menuItem, idRecord, subjectData)
{
	subjectData = escape(subjectData);

	
	// Sending external email for 1.7.5 phase II .. AJG	
	flag = false;
	if(USE_EXTERNAL_EMAIL) // if to use external email client
	{	
		url = URL_HTTP + "direction.php?mId="+menuItem+"&rid_1="+idRecord+"&sData="+subjectData+'&action=SendAdminEmail';
		new Ajax.Request(url, {
			onSuccess: function(transport) {								
							flag = true;
							contentMsg = transport.responseText;							
							//var mailto_link = 'mailto:'+ADMIN_EMAIL+'?subject='+subjectData+'&body='+contentMsg;
							var mailto_link = 'mailto:'+ADMIN_EMAIL;
							win = window.open(mailto_link,'emailWindow');								
					   }
		});
		
		if(flag)
		{
		   return false;
		}
	}
	else
	{	
		window.open("contact_emailadministrator.php?menuItem="+menuItem+"&idRecord="+idRecord+"&subjectData="+subjectData, "ZooEasy", "scrollbars=yes,location=no,toolbar=no,menubar=no,directories=no,status=no,width=500px, height=350px");			
	}
	// End of sending external email
		
}


/**
 * Added by AJG
 */
function email_admin2( menuItem, idRecord, idRecord2, subjectData)
{	
	subjectData = escape(subjectData);
	
	// Sending external email for 1.7.5 phase II .. AJG	
	flag = false;
	if(USE_EXTERNAL_EMAIL) // if to use external email client
	{	
		url = URL_HTTP + "direction.php?mId="+menuItem+"&rid_1="+idRecord+"&rid_2="+idRecord2+"&sData="+subjectData+'&action=SendAdminEmail';
		new Ajax.Request(url, {
			onSuccess: function(transport) {							
							flag = true;
							contentMsg = transport.responseText;
							
							var mailto_link = 'mailto:'+ADMIN_EMAIL+'?subject='+subjectData+'&body='+contentMsg;	
							win = window.open(mailto_link,'emailWindow');								
					   }
		});
		
		if(flag)
		{
		   return false;
		}
	}
	else
	{	
		window.open("contact_emailadministrator.php?menuItem="+menuItem+"&idRecord="+idRecord+"&idRecord2="+idRecord2+"&subjectData="+subjectData, "ZooEasy", "scrollbars=yes,location=no,toolbar=no,menubar=no,directories=no,status=no,width=500px, height=350px");			
	}
}

/*
Added by Ajay Giri for checking whether form has been modified or not
before undo-ing any changes while clicking on the 'Cancel' button.
*/

var changed = 0;

function recordChange() {
 changed = 1; 
}

function recordChangeIfChangeKey(myevent) {
 if (myevent.which && !myevent.ctrlKey && !myevent.ctrlKey)
  recordChange(myevent);
}

function ignoreChange() {
 changed = 0;
}

function lookForChanges() {
 var origfunc;
 for (i = 0; i < document.forms.length; i++) {
  for (j = 0; j < document.forms[i].elements.length; j++) {
   var formField=document.forms[i].elements[j];
   var formFieldType=formField.type.toLowerCase();
   if (formFieldType == 'checkbox' || formFieldType == 'radio') {
    addHandler(formField, 'click', recordChange);
   } else if (formFieldType == 'text' || formFieldType == 'textarea') {
    if (formField.attachEvent) {
     addHandler(formField, 'keypress', recordChange);
	 addHandler(formField, 'change', recordChange);
    } else {
     addHandler(formField, 'keypress', recordChangeIfChangeKey);
	 addHandler(formField, 'change', recordChangeIfChangeKey);
    }
   } else if (formFieldType == 'select-multiple' || formFieldType == 'select-one') {
    addHandler(formField, 'change', recordChange);
   }
   else if (formFieldType == 'file') {
    addHandler(formField, 'change', recordChange);
   }
  }
  addHandler(document.forms[i], 'submit', ignoreChange);
 }
}

function addHandler(target, eventName, handler) {
 if (target.attachEvent) {
  target.attachEvent('on'+eventName, handler);
 } else {
  target.addEventListener(eventName, handler, false);
 }
}

/**  End of 'Cancel' link code .. by Ajay Giri  */

/**
 *  Added by Ajay Giri 
 */
 function validateChars(str,iChars)
 {
  if(iChars == '')
     iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";

  for (var i = 0; i < str.length; i++)
  {
  	if (iChars.indexOf(str.charAt(i)) != -1) 
	{  	
  	  return false;
  	}
  }
  return true;
 }
 
/**
 * Added by Ajay Giri
 * Functions related to File attachment/picture upload
 */
var allowedExt         = new Array('doc','docx','xls','xlsx','ppt','gif','jpg','jpeg','bmp','tif','txt','pdf');
var allowedImageExt    = new Array('jpg','jpeg','bmp','gif','tif');
var allowedImageExt2   = new Array('jpg','jpeg','bmp','gif','tif','png');
var allowedTemplateExt = new Array('docx');

Array.prototype.inArray = function (value)
{
	// Returns true if the passed value is found in the
	// array. Returns false if it is not.
	var i;
	for (i=0; i < this.length; i++) 
	{
		if (this[i] == value) 
		{
		return true;
		}
	}
    return false;
};

/* Checking attachment file for a valid file extension  */ 
function validFileType()
{	
	fileExt = getExtension(document.getElementById('UserFile').value);
		
	if(allowedExt.inArray(fileExt))
	{
	   return true;	
	}
	else
	{
	   return false;	
	}
}

/* Checking image file for a valid file extension  */ 
function validImageType()
{	
	fileExt = getExtension(document.getElementById('UserFile').value);
	if(allowedImageExt.inArray(fileExt))
	{
	   return true;	
	}
	else
	{
	   return false;	
	}
}
/* Checking image file for a valid file extension  */ 
function validImageType2(imagePath)
{	
	fileExt = getExtension(imagePath);
	if(allowedImageExt2.inArray(fileExt))
	{
	   return true;	
	}
	else
	{
	   return false;	
	}
}

/* Checking image file for a valid file extension  */ 
var allowedZipExt = new Array('zip');
function validZipFile()
{	
	fileExt = getExtension(document.getElementById('UserFile').value);	
	if(allowedZipExt.inArray(fileExt))
	{
	   return true;	
	}
	else
	{
	   return false;	
	}
}

/* Checking report template file for a valid file extension  */ 
function validTemplateFile(filePath)
{	
	fileExt = getExtension(filePath);
	if(allowedTemplateExt.inArray(fileExt))
	{
	   return true;	
	}
	else
	{
	   return false;	
	}
}

/* This function is used to get the file extension for a filename. */
function getExtension(value) {
  fileExt = value.substring(value.lastIndexOf('.') + 1,value.length);
  fileExt = fileExt.toLowerCase();
  return fileExt;
}

/* Checking for proper File path for uploading attachments. */
function PathValidation(path)
{
	//var path = document.getElementById("locPath").value;
	if(path == "") 
	{
		//alert("Enter location");
	    return false;
	}
	
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) 
	{		
		if((path.charAt(0) != "\\" && path.charAt(1) != "\\") && (path.charAt(0) != "/" && path.charAt(1) != "/"))
		{
			if(!path.charAt(0).match(/^[a-zA-z]/))  
			{
				//alert("Enter Valid location");
				return false;
			}
			if(path.charAt(1) == "" ||!path.charAt(1).match(/^[:]/) || !path.charAt(2).match(/^[\/\\]/))
			{
				//alert("Enter Valid location");
				return false;
			} else {
				//alert("Entered location " + path + " is correct");
				return true;
			}	
		}
	}
	else
	{
	    return true;	
	}
}

/**  End of File upload related functions  **/

function popupPadigree(animalId){
		//popup_window("pedigree.php?Id="+animalId, 850, 500);		 
		// window.showModalDialog("pedigree.php?Id="+animalId, window, "dialogWidth:850px;dialogHeight=500px; resizable: yes");
		
		var windowWidth = 500;
		var windowHeight = 400;
		var centerWidth = (window.screen.width - windowWidth) / 2;
	    var centerHeight = (window.screen.height - windowHeight) / 2 + 100 ;
		
		window.open("pedigree.php?Id="+animalId, "", "width=850px,height=500px,left ="+centerWidth+",top ="+centerHeight+",scrollbars=yes,location=no,toolbar=no,menubar=no,directories=no,status=yes,resizable=yes");
		 
}

function detectBrowser_2()
{
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) //test for MSIE x.x;
		var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
	return ieversion;
}


function mkunderline(cell){

	/*if( cell%2==0)
		trClass = "even";
	else
		trClass = "odd";

	document.getElementById(cell).className= 'underline '+  trClass;*/	
	
	document.getElementById(cell).className = document.getElementById(cell).className +  ' underline';
}

function removeunderline(cell){
	
	/*if( cell%2==0)
		trClass = "even";
	else
		trClass = "odd";
	document.getElementById(cell).className= trClass;*/	
	
	document.getElementById(cell).className = document.getElementById(cell).className.replace('underline','');
}


/* 
Code related to listing page navigation by pressing CTRL + <keys> combinations
@author Ajay Giri
*/
document.onkeydown = keydown; 
function keydown(evt)
{     
    if(document.getElementById('sheet_1'))
	{
	   if(document.getElementById('sheet_1').style.display == 'none')
	   {
		   return;
	   }	
	}	
	
	if(window.event)
	{
		evt = event;
	}	
	
	if (evt.ctrlKey && evt.keyCode==36) // CTRL + Home
	{
		if(document.getElementById('firstpage'))
	       document.getElementById('firstpage').onclick();
	} 
	else if (evt.ctrlKey && evt.keyCode==37) // CTRL + Left arrow
	{ 
	    if(document.getElementById('previouspage'))
	       document.getElementById('previouspage').onclick();
	}
	else if (evt.ctrlKey && evt.keyCode==39)
	{ 
	    if(document.getElementById('nextpage'))
	       document.getElementById('nextpage').onclick(); // CTRL + Right arrow
	}
	else if (evt.ctrlKey && evt.keyCode==35)
	{ 
	    if(document.getElementById('lastpage'))  
		   document.getElementById('lastpage').onclick(); // CTRL + End
	}
	else if (evt.ctrlKey && evt.keyCode==38)  // CTRL + Up -- for previouos record on details pages
	{ 
	    if(document.getElementById('previousRecord'))  
		   document.getElementById('previousRecord').click();
	}
	else if (evt.ctrlKey && evt.keyCode==40)  // CTRL + Down -- for next record on details pages
	{ 
	    if(document.getElementById('nextRecord'))  
		   document.getElementById('nextRecord').click();
	}
	
}
/* End of code */

/* PHP equivalent functions added by Ajay Giri  */

function htmlentities (string, quote_style) {
    // Convert all applicable characters to HTML entities  
    
    // *     example 1: htmlentities('Foo & Bar');    
	// *     returns 1: 'Foo &amp; Bar'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
        return tmp_str;
}

function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities     
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
     useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';    entities['62'] = '&gt;';
 
    // ascii decimals to real symbols
    for (decimal in entities) {        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}
/* End of PHP equivalent functions  */

//Set focus on the first text field of HTML form.
function setFirstElementFocus()
{
  var flag=false;
  for(z=0;z<document.forms.length;z++)
  {
    var form = document.forms[z];
    var elements = form.elements;
    for (var i=0;i<elements.length;i++)
    {
       var element = elements[i];
       /*
	   if((element.type == 'text' || 
		   element.type == 'textarea' || 
		   element.type == 'select-multiple' || 
		   element.type == 'select-one' || 
		   element.type == 'checkbox' || 
		   element.type == 'radio'
		   ) &&
           !element.readOnly &&
           !element.disabled)
	  */
	  if(( element.type == 'text' || element.type == 'textarea' ) && (element.disabled != true) && (element.readonly != 'readonly'))
	  {		  
		  show = true;
		  
		  if(document.getElementById('sheet_2'))  // Management -> Base tables
		  {			
			if(document.getElementById('sheet_2').style.display != 'block') 
			{
			   show = false;	
			}
		  }
		  
		  if(document.getElementById('sheet_1_detail'))  // Management -> Accounts
		  {			
			if(document.getElementById('sheet_1_detail').style.display != 'block') 
			{
			   show = false;	
			}
		  }
		  
		  if(document.getElementById('SettingsMatrix'))  // Management ->Settings -> Breeding Advisory matrix
		  {			
			if(document.getElementById('SettingsMatrix').style.display != 'block') 
			{
			   show = false;	
			}
		  }
		  
		  if(show)
		  {
		     element.focus();
		     flag=true;
		     break;
		  }
      }
    }
    if(flag)break;
  }
}

// Set focus on the first input element of each of the sub tabs of 'Extrafields' tab of animal, contact and breedingpair
function showOfDiv(div) 
{
   if(!div) 
   {
	  return;
   }
   
   div = typeof div === "string" ? document.getElementById(div) : div;
   var elements = div.getElementsByTagName("*"); // Fetch an array of all the elements inside a given <DIV>.
   var flag=false;
   
   totElements = elements.length;
   
   for(var i = 0; i < totElements; i++)
   {
		var element = elements[i];		
		switch(element.type)
		{
		  case "text":
		  case "textarea":	
		  /*case "select-one":
		  case "select-multiple":
		  case "checkbox":
		  case "radio":	*/  
		  
		  //alert("Type: " + element.type + "\nName: " + element.name + "\nId: " + element.id);	
		  if(element.disabled != true)
		  {		     
			 element.focus();
	         flag=true;
		  }
		}
	
	    if(flag)break;
   }
   
}

// Returns the same string as <string>, where the whitespace has been trimmed from the front and back.
String.prototype.trim = function() {
    return(this.replace(/^\s+/,'').replace(/\s+$/,''));
}

function isNumber(n) 
{   
   return !isNaN(parseFloat(n)) && isFinite(n); 
}

// Equivalent of PHP number_format() function in Javascript .. AJG .. googled
function number_format_php(number, decimals, dec_point, thousands_sep)
{
    number = (number+'').replace(',', '').replace(' ', '');
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    } 	
	return s.join(dec);	
}


// for print bar code
function hideFrameDiv()
{
   document.getElementById('frameDiv').style.display = "none";
}

// for print bar code
function printBarcode(animalId, administrationId,languageId)
{	
	 new Ajax.Request(siteUrl+'direction.php',
	 {
		  method: 'get',
		  parameters: { 
						action:'PrintBarcode',AnimalId: animalId, AdministrationId: administrationId, LanguageId: languageId  
					  },
		  onSuccess: function(response) 
					 {  					
						multiBytesStatus = response.responseText; 				
											
						if(multiBytesStatus == 0) // multibyte characters does not exists in the data
						{	
							 //frames['barcodeframe'].print();
						   if(document.getElementById('frameDiv'))
						   {	  
							  document.getElementById('frameDiv').style.display ="block";	  
							  if(document.getElementById('barcodeframe'))
							  {	
								 document.getElementById('frameDiv').focus();	
								 window['barcodeframe'].focus();	 
								 window['barcodeframe'].print();
								 setTimeout("hideFrameDiv()", 4000);
							  }  
						   }	
							
						}
						else
						{						
							var myarray = multiBytesStatus.split(">|<");
							errMsg = PRINT_BARCODE_MSG.replace('{0}',myarray[1]);
							
							//showError(errMsg,httpUrl);
							show_message(errMsg,'Error',httpUrl);
						}
						
					 }	  
		 
	  });	
}

function checkImport(method, callbackFunction)
{
    new Ajax.Request(siteUrl+'direction.php', 
	{
	  method: 'get',
	  parameters:{ 
					action:'CheckImportProcess', subaction: method, AdministrationId: adminId, UserId: userId 
				 },
	  onSuccess: function(response) 
				 { 					
					//alert(response.toSource());
					processStatus = response.responseText;					
					
					if(processStatus == 1)
					{						   
					   show_message(NO_IMPORT_PROCESS_DUE_TO_CRON,'Error',httpUrl);
					}
					else if(processStatus == 2 || processStatus == 3)
					{						  
					   show_message(NO_IMPORT_PROCESS_DUE_TO_IMPORT,'Error',httpUrl);
					}
					else if(processStatus == 4)
					{
					   show_message(NO_IMPORT_PROCESS_DUE_TO_CLEARANCE,'Error',httpUrl);	
					}
					else
					{				   
					   eval(callbackFunction + '()');				   
					}								
					
				 }	  
	  /*,onFailure: function() {  }*/
	});	
	
}

function sorting(formName, sortField, sortOrder)
{
  var formObj = document.forms[formName];
  
  oldSortField = document.getElementById('SortField').value;
  if(oldSortField != 0 && oldSortField != sortField)
  {
	 sortOrder = 0;  
  }
  
  if(sortOrder == 0)
  {
	 sortOrder = 1;
  }
  else if(sortOrder == 1)
  {
	 sortOrder = 2;  
  }
  else if(sortOrder == 2)
  {
	 sortOrder = 1;  
  }
  
  document.getElementById('SortField').value  = sortField;
  document.getElementById('SortOrder').value  = sortOrder;
  document.getElementById('LimitStart').value = 0; // redirect to first page when sort column is clicked
  formObj.submit();
}
