/**
 * js.js
 * @copyright Ayrmer Software 2006
 * 
 */

function createMarker2(posn, title, icon,html,link,type)
{
   var marker = new GMarker(posn, {
      title: title,
      icon: icon,
      draggable: false
   });
   
   if(type == "listing" || type == "info")
   {
      GEvent.addListener(marker, 'click', function(){ 
            window.open(link);               
         });
   }
   else if(type == "county")
   {
      GEvent.addListener(marker, 'click', function(){ 
            map.setCenter(posn);
            map.setZoom(9);               
         });
   }
   else
   {
      GEvent.addListener(marker, 'click', function(){ 
            map.setCenter(posn);
            map.setZoom(map.getZoom() + 1);               
         });
   }
   return marker;
}

function html_entity_decode( string, quote_style ) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
 
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    
    tmp_str = tmp_str.split('&#039;').join("'");
    
    
    return tmp_str;
}


function hideLoading()
{
  document.getElementById('loading').style.visibility = 'hidden';  
}

function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, 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;
    }
 
    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 for better compatibility
    entities['38'] = '&amp;';
 
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
 }

function changelink()
{
   if(document.getElementById("testlink").innerHTML != "something else")
   {
      document.getElementById("testlink").innerHTML = "something else";  
   }
   else
   {
      document.getElementById("testlink").innerHTML = "<img src='images/00CC00.gif' />";  
   }
}

function blankout(section)
{
   if(section == "acc")
   {
      document.getElementById("acc").checked = true;      
      document.getElementById("poi").checked = false;      
      document.getElementById("spec").checked = false;
      document.getElementById("gcn").checked = false;     
      
      //enabled / disable 
      for(i = 1; i < 8; i++)
      {
         document.getElementById("type" + i).disabled = false;     
      }
      for(i = 8; i < 20; i++)
      {
         document.getElementById("type" + i).disabled = true;     
         document.getElementById("type" + i).checked = false;
      }
   }
   else if(section == "spec")
   {
      document.getElementById("acc").checked = false;      
      document.getElementById("poi").checked = false;      
      document.getElementById("spec").checked = true;
      document.getElementById("gcn").checked = false;      
      
      //enabled / disable 
      for(i = 1; i < 8; i++)
      {
         document.getElementById("type" + i).disabled = true;
         document.getElementById("type" + i).checked = false;     
      }
      for(i = 8; i < 15; i++)
      {
         document.getElementById("type" + i).disabled = false;              
      }
      for(i = 15; i < 20; i++)
      {
         document.getElementById("type" + i).disabled = true;              
         document.getElementById("type" + i).checked = false;     
      }
   }
   else if(section == "poi")
   {
      document.getElementById("acc").checked = false;      
      document.getElementById("poi").checked = true;      
      document.getElementById("spec").checked = false;
      document.getElementById("gcn").checked = false;      
      for(i = 1; i < 15; i++)
      {
         document.getElementById("type" + i).disabled = true;
         document.getElementById("type" + i).checked = false;     
      }
      for(i = 15; i < 20; i++)
      {
         document.getElementById("type" + i).disabled = false;              
      }
      for(i = 19; i < 20; i++)
      {
         document.getElementById("type" + i).disabled = true;              
         document.getElementById("type" + i).checked = false;     
      }
   }
   else if(section == "gcn")
   {
      document.getElementById("acc").checked = false;      
      document.getElementById("poi").checked = false;      
      document.getElementById("spec").checked = false;
      document.getElementById("gcn").checked = true;      
      
      for(i = 1; i < 19; i++)
      {
         document.getElementById("type" + i).disabled = true;
         document.getElementById("type" + i).checked = false;     
      }
      for(i = 19; i < 20; i++)
      {
         document.getElementById("type" + i).disabled = false;              
      }
      
   }
}


function set_link(page){
	document.forms[0].insert.value = "index.php?"+((parseFloat(page)) ? "page=" : "alias=") + page
}

var requester;


/**
 * Sends an ajax request to get a list of organisations
 * @param string search_string 		= what to search for
 * @param integer id				= the contact id 
 */
function get_orgs(search_string, id) {
	
	if(!requester)
		requester = new Requester();
	
	if(document.getElementById('org_search').style.display = 'none')
		document.getElementById('org_search').style.display = '';
		
	requester.setAction(set_orgs);
	requester.loadURL('ajax.contact_to_org.php','search_string='+search_string+'&id='+id);
}

function get_comm_orgs(search_string) {
	
	if(!requester)
		requester = new Requester();
	
	if(document.getElementById('org_search').style.display = 'none')
		document.getElementById('org_search').style.display = '';
		
	requester.setAction(set_orgs);
	requester.loadURL('ajax.comm_to_org.php','search_string='+search_string);
}

function get_cats(search_string,newsletter) {
	
	if(!requester)
		requester = new Requester();
	
	if(document.getElementById('cat_search').style.display == 'none')
		document.getElementById('cat_search').style.display = '';		
	
	requester.setAction(set_cat);
	requester.loadURL('ajax.contact_types.php','search_string='+search_string+'&newsletter=' +newsletter);
}

function add_ab_to()
{
   if(document.forms[0].to.value != "")
   {
      document.forms[0].to.value = document.forms[0].to.value + ', ' + document.forms[0].address_book_to.value;
   }
   else
   {
      document.forms[0].to.value = document.forms[0].address_book_to.value;   
   }
}

function add_ab_cc()
{
   if(document.forms[0].cc.value != "")
   {
      document.forms[0].cc.value = document.forms[0].cc.value + ', ' + document.forms[0].address_book_to.value;
   }
   else
   {
      document.forms[0].cc.value = document.forms[0].address_book_to.value;   
   }
}

function add_ab_bcc()
{
   if(document.forms[0].bcc.value != "")
   {
      document.forms[0].bcc.value = document.forms[0].bcc.value + ', ' + document.forms[0].address_book_to.value;
   }
   else
   {
      document.forms[0].bcc.value = document.forms[0].address_book_to.value;   
   }
}

function set_orgs() {
	document.getElementById('org_search').innerHTML = requester.getText();
}

function set_cat() {
	document.getElementById('cat_search').innerHTML = requester.getText();
}


/**
 * Disables the enter button of a field so that the form doesn't submit when not wanted to
 * @param reference field 		= the html calling field
 * @param reference event		= the calling event
 */
function disable_enter(field, event) {
	
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	
	if (keyCode == 13) {
		field.focus();
		return false;	
	}
	
	return true;
}

/**
 * Clears an input field
 * @param reference element 	= the html input field
 * @param string string			= the string within the field
 */
function input_select_clear(element, string) {
	
	// if an element and string has been supplied
	if(element && string != '') {
		
		// if the value of the element is the same as the string clear the field
		if(element.value == string) {
			
			element.value = '';

			element.string = string;
			
			// add an on blur function to repopulate the string if the field is left empty
			element.onblur = function() {
				if(this.value == '') {
					this.value = this.string;	
				}
			};
		}
	}
}



function populate_auth_checks(element, num) {
	try {
		if(!num)
			return;
		
		// get the checks id
		caller_id = element.id;
		
		// split it into its parts
		caller_bits = caller_id.split('_');

		// get the caller number and remove it from the caller bits array
		caller_number = caller_bits.pop();
		
		// clone the caller_bits array
		var parent_elements = new Array;
		for(var i = 0; i < caller_bits.length; i++) {
			parent_elements[i] = caller_bits[i];
		}
		
		
		// remove the prefix string from the array
		parent_elements.shift();
		
		//alert(parent_elements);
		
		
		
			
		
		/*
		alert(typeof(parent_elements));
		parent_elements.shift();
		alert(parent_elements);*/
		
		
		
//		for(var a = 1; a < temp.length; a++) {
//			alert(temp[a]);
//		}
		

		// loop the number of elements
		for(var i=1; i <= num; i++) {
			
			// if the current itteration is the caller id ignore it
			if(caller_number == i) {
				continue;
			}
			
			// stick the id back together plus i to get the id
			id = caller_bits.join('_')+'_'+i;
				
			// get the element
			sub_element = document.getElementById(id) 
			
			// if its below the clicked element select it (unless its the first one)
			if(i <= caller_number) {
					sub_element.checked = true;
			}
			// otherwise unselect it
			else {
				sub_element.checked = false;
			}
		}
	}
	catch (error) {alert(error)}
}	


var marked_row = new Array;
function markRowsInit(odd_class_name, even_class_name, marked_class_name, hover_class_name) {
	
	if(!odd_class_name) {
		odd_class_name = 'odd';
	}
	if(!even_class_name) {
		even_class_name = 'even';
	}
	
	if(!marked_class_name) {
		marked_class_name = "marked";
	}
	
	if(!hover_class_name) {
		hover_class_name = "hover";
	}
	
	
	
    // for every table row ...
	var rows = document.getElementsByTagName('tr');
	
	
	for ( var i = 0; i < rows.length; i++ ) {
	    // ... with the class 'odd' or 'even' ...
		if ( odd_class_name != rows[i].className && even_class_name != rows[i].className ) {
			
		    continue;
		}
		
	    // ... add event listeners ...
        // ... to highlight the row on mouseover ...
	    if ( navigator.appName == 'Microsoft Internet Explorer' ) {
	        // but only for IE, other browsers are handled by :hover in css
			rows[i].onmouseover = function() {
			    this.className += ' '+hover_class_name;
			}
			rows[i].onmouseout = function() {
			    this.className = this.className.replace( ' '+hover_class_name, '' );
			}
	    }
        // ... and to mark the row on click ...
		rows[i].onmousedown = function() {
		    var unique_id;
            var checkbox;

 
            checkbox = this.getElementsByTagName( 'input' )[0];
            if ( checkbox && checkbox.type == 'checkbox' ) {
                unique_id = checkbox.name + checkbox.value;
            } else if ( this.id.length > 0 ) {
                unique_id = this.id;
            } else {
		        return;
		    }

            if ( typeof(marked_row[unique_id]) == 'undefined' || !marked_row[unique_id] ) {
                marked_row[unique_id] = true;
            } else {
                marked_row[unique_id] = false;
            }

            if ( marked_row[unique_id] == true) {
			    this.className += ' '+marked_class_name;
            } else {
				
			    this.className = this.className.replace(' '+marked_class_name, '');

            }

            if ( checkbox && checkbox.disabled == false ) {
                checkbox.checked = marked_row[unique_id];
            }
           
		}

		// ... and disable label ...
		var labeltag = rows[i].getElementsByTagName('label')[0];
		if ( labeltag ) {
		    labeltag.onclick = function() {
		        return false;
		    }
	    }
	    // .. and checkbox clicks
		var checkbox = rows[i].getElementsByTagName('input')[0];
		if ( checkbox ) {
		    checkbox.onclick = function() {
		        // opera does not recognize return false;
		        this.checked = ! this.checked;
		    }
	    }
	}
}


/**
 * Marks / Unmarks all depending on the callers state
 *
 * @param caller the check box that called
 * @param    container    DOM element
 */
function checkUncheckAll(caller, container) {
	if(caller.checked) {
		
		markAllRows(caller, container);

	}
	else {
		unMarkAllRows(caller, container);

	}
		
}
/**
 * Unmarks all rows and deselects the first checkbox inside the given element
 *
 * @param caller the check box that called
 * @param    container    DOM element
 */
function markAllRows( caller, container_id ) {

	var rows = document.getElementById(container_id).getElementsByTagName('tr');
    var unique_id;
    var checkbox;

	for ( var i = 0; i < rows.length; i++ ) {

        checkbox = rows[i].getElementsByTagName( 'input' )[0];

        if ( checkbox && checkbox.type == 'checkbox' && checkbox != caller) {
            unique_id = checkbox.name + checkbox.value;
            if ( checkbox.disabled == false ) {
                checkbox.checked = true;
                if ( typeof(marked_row[unique_id]) == 'undefined' || !marked_row[unique_id] ) {
                    rows[i].className += ' marked';
                    marked_row[unique_id] = true;
                }
            }
	    }
	}

//	return true;
}

/**
 * marks all rows and selects its first checkbox inside the given element
 * the given element is usaly a table or a div containing the table or tables
 *
 * @param	caller	the checkbox that called
 * @param    container    DOM element
 */
function unMarkAllRows( caller, container_id ) {

	var rows = document.getElementById(container_id).getElementsByTagName('tr');
    var unique_id;
    var checkbox;

	for ( var i = 0; i < rows.length; i++ ) {

        checkbox = rows[i].getElementsByTagName( 'input' )[0];

        if ( checkbox && checkbox.type == 'checkbox' && checkbox != caller) {
            unique_id = checkbox.name + checkbox.value;
            checkbox.checked = false;
            rows[i].className = rows[i].className.replace(' marked', '');
            marked_row[unique_id] = false;
        }
	}

//	return true;
}

function resize_email_iframe(element) {
	try {	
		iframe = document.getElementById('email_body');
		iframe.height = element.offsetHeight + 35;
	}
	catch (error) {}	
}

function my_contacts() {
	try {
		
	}
	catch(error) {}
	
}


function auto_upload() {
	try{
		document.getElementById('add_attachment_button').click();
	}
	catch(errors){}
}

function enable_followup(caller) {
	try {
		if(caller.checked == false) {
			document.getElementById('comm_followup_date_d').disabled = true;
			document.getElementById('comm_followup_date_m').disabled = true;
			document.getElementById('comm_followup_date_y').disabled = true;
			document.getElementById('comm_followup_date_hr').disabled = true;
			document.getElementById('comm_followup_date_mi').disabled = true;
			document.getElementById('followup_by').disabled = true;
		}
		else {
			document.getElementById('comm_followup_date_d').disabled = false;
			document.getElementById('comm_followup_date_m').disabled = false;
			document.getElementById('comm_followup_date_y').disabled = false;
			document.getElementById('comm_followup_date_hr').disabled = false;
			document.getElementById('comm_followup_date_mi').disabled = false;
			document.getElementById('followup_by').disabled = false;
		}
		
	}
	catch(errors){}
}

function enable_followup_onload() {
	enable_followup(document.getElementById('comm_requires_followup'));
	
}

function calculate_vat(vatRate) {
	var netTotal, vat, gross;
	if (document.getElementById('account_transaction_gross').value == '') {
		netTotal = document.getElementById('account_transaction_net').value
		if (netTotal != "NaN") {
			netTotal = parseFloat(netTotal);
			vat = netTotal * (vatRate);
			gross = netTotal + parseFloat(vat);
			netTotal = netTotal.toFixed(2);
			vat = vat.toFixed(2);
			gross = gross.toFixed(2);
			document.getElementById('account_transaction_net').value = netTotal;
			document.getElementById('account_transaction_vat').value = vat;
			document.getElementById('account_transaction_gross').value = gross;
		} else {
			total = '';
		}
	}
}
