//<![CDATA[

/*
IE doesn't seem to like setting .type on newly created input elements, so here's a hack from:

http://cf-bill.blogspot.com/2006/03/another-ie-gotcha-dynamiclly-created.html
*/
function createInput(type)
{
	try
	{
		var input_element = document.createElement('<input type="'+ type + '" />');
	}
	catch(err)
	{
		var input_element = document.createElement('input');
		input_element.setAttribute('type',type);
	}
	
	return input_element;
}

// Source: http://www.aspandjavascript.co.uk/javascript/javascript_api/get_element_top_left.asp
// Slight modification made to styling.  Used to get the top of an element for scrolling.
function getElementTop(Elem)
{
	if(document.getElementById)
	{	
		if(typeof Elem == 'string')
		{
			var elem = document.getElementById(Elem);
		}
		else
		{
			var elem = Elem;
		}
	}
	else if (document.all)
	{
		if(typeof Elem == 'string')
		{
			var elem = document.all[Elem];
		}
		else
		{
			var elem = Elem;
		}
	}
	yPos = elem.offsetTop;
	tempEl = elem.offsetParent;
	while (tempEl != null)
	{
		yPos += tempEl.offsetTop;
  		tempEl = tempEl.offsetParent;
	}
	return yPos;
}

/*
function that focuses on an error div since focus() only pertains to field elements
*/
function errorFocus(id)
{
	window.scrollTo(0,getElementTop(id));
}

/*
This is a function to update the list of avaliable dates based on month and year
it simply makes an ajax call to a PHP page that uses checkdate till it hits
the end of the month, sending that value back to us for the callback function
*/
function dayUpdate(month_id,year_id,day_holder,day_value)
{
	var month = ge(month_id);
	var month_val = month[month.selectedIndex].value;

	var year = ge(year_id);
	var year_val = year[year.selectedIndex].value;
	var day_val = 1;
	try
	{
		if (day_value)
		{
			day_val = gv(day_value);
		}
		else
		{
			day_val = gv(day_holder);
		}
	}
	catch (e) {}
	
	ajax(ajaxObject(),'GET','/private/option_day.php?year=' + year_val + '&month=' + month_val + '&day=' + day_val + '&holder=' + day_holder, dayUpdateCallback);
}

/*
This is for IE since it doesn't understand the placement of innerHTML with <options> in a <select>
field (firefox does).  Instead we use dom functionality in a loop to create our option list.
*/
function dayUpdateCallback(responseText)
{
	// var date
	eval(responseText);
	
	var holder = ge(date.holder);
	var day_val = holder.value;
	if (date.selected > 0 && date.selected < 32)
	{
		if (date.selected > (date.max - 1))
		{
			day_val = date.max - 1;
		}
		else
		{
			day_val = date.selected;
		}
	}
	holder.innerHTML = '';
	
	var selectthis = 0;
	for ( var i = 1 ; i < date.max; i++)
	{
		var element = document.createElement('option');
		element.value = i;
		if (day_val==i)
		{
			element.selected = true;
		}
		element.appendChild(document.createTextNode(i));
		
		holder.appendChild(element);
	}
}

function postKeyValues(id_array,post_string)
{
	if(!post_string)
	{
		post_string = '';
	}

	for(var i = 0; i < id_array.length ; i++)
	{
		try
		{
			var post_string = post_string + '&' + id_array[i] + '=' + escape(document.getElementById(id_array[i]).value);
		}
		catch (err)
		{
			alert('getElementById on ' + id_array[i] + ' failed!');
		}
	}

	return post_string;
}

function removeElement(element)
{
	if(typeof element == 'string')
	{
		var target = document.getElementById(element);
	}
	else
	{
		var target = element;
	}
	
	var parent = target.parentNode;
	parent.removeChild(target);
}

function textGet(id)
{
	if (typeof id == "string")
	{
		var element = document.getElementById(id);
	}
	else
	{
		var element = id;
	}
	
	if(document.getElementsByTagName('body')[0].innerText)
	{
		return element.innerText;
	}
	else
	{
		return element.textContent;
	}
}

// Need documentation here!!
function setAddressValue1(form, value)
{
	document.forms[form].int_address1_format.value = value;
}

// Need documentation here!!
function setAddressValue2(form, value)
{
	document.forms[form].int_address2_format.value = value;
}

// Need documentation here!!
function showBlock(block, display)
{
	var element = document.getElementById(block);
	if (element)
	{
		if(display == 'block' || display == 'inline')
		{
			element.style.display = display;
		}
		else if(display == 'other')
		{
			element.style.display = 'block';
		}
		else
		{
			element.style.display = 'none';
		}//end if
	}
}//end function

// Need documentation here!!
function clearFormatting(id)
{
	try
	{
		var target = document.getElementById(id); 
		target.style.background = '#ffffff';
		target.style.color = '#000000';
	}
	catch (e) {}
}//end function

// Set value of a <td id='id'></td>
function textSet(id,text)
{
	if (typeof id == "string")
	{
		var element = document.getElementById(id);
	}
	else
	{
		var element = id;
	}

	try
	{
		element.innerHTML = text;
	}
	catch (e)
	{
		console.log('textSet() error, el not found: ' + id);
	}

	if (id=='debug')
	{
		element.style.color = '#ffffff';
	}
}

// Need documentation here!!
function fieldWatcher(field)
{
	updated_fields	= document.getElementById('updated_fields').value;
	check_for_match	= updated_fields.indexOf(field);
	
	if(check_for_match == -1)
	{
		document.getElementById('updated_fields').value = field + ':' + updated_fields;
	}
}//end function

// Need documentation here!!
function updateUsername()
{
	var updated_username	= gv('primary_email');
	var username_container	= ge('username_display');
	
	document.getElementById('updated_username').value = 'true';
	document.getElementById('username_display').className = 'row_warning';
	
	username_container.innerHTML = updated_username;
	window.id = setTimeout(updateUsername,100);		
}//end function

function release_updateUsername()
{
	window.clearTimeout(window.id);
}//end function

//function removeSelectedContact("reservation_contact_browser","reservation_");
function removeSelectedContact(location,prefix,cancel_callback)
{
	textSet(location,'');
	showBlock(location, 'none');
	document.getElementById(prefix + 'contact_id').value = '';
	if (cancel_callback)
	{
		eval(cancel_callback+'();');
	}
}

/*
This functions require the AJAX methods
*/
function contactsBrowser(contact_type, location, sort_by, dir, page_id, prefix, action, cancel_callback, search_string)
{	
	if(action == 'close')
	{
		showBlock(location,'none');
		if (cancel_callback)
		{
			eval(cancel_callback+'();');
		}
	}
	else
	{
		if(!contact_type)
		{
			contact_type = '';
		}
		if(!search_string)
		{
			search_string = '';
		}
		if (search_string.indexOf('&')!=-1)
		{
			search_string = escape(search_string);
		}
		
		var page_get = '/private/contacts_selector.php?list_chosen=' + contact_type + '&location=' + location + '&prefix=' + prefix + '&pageid=' + page_id + '&sortby=' + sort_by + '&dir=' + dir + '&cancel_callback=' + cancel_callback + '&search_string='+search_string;
	
		ajaxpage(page_get, location);

		showBlock(location,'block');
	}
}

function contactSelected(location, prefix, first_name, last_name, id, cancel_callback)
{
	if (location == 'temp_applicant')
	{
		$('permit_contact').value = first_name + ' ' + last_name;
		clearFormatting('permit_contact');
	}
	if(location == 'broker_browser')
	{
		ajax(ajaxObject(),'GET','/private/insurance_detail.php?mode=get_contact&contact_id=' + id, insurancePopulate);
		return;
	}

	if(location == 'permit_contact' || location == 'reservation_contact_browser')
	{
		document.getElementById(location).innerHTML = first_name + ' ' + last_name + ' <a href=' + "'" + 'javascript:removeSelectedContact("' + location + '","' + prefix + '", "");' + "'" + '>remove</a>';
	}
	else if (location == 'location_contact_browser')
	{
		showBlock('new_contact','none');
		document.getElementById(location).innerHTML = first_name + ' ' + last_name + " <a href='' onclick=\"showBlock('new_contact','block');;document.getElementById('"+location+"').innerHTML='';document.getElementById('"+prefix + "contact_id').value='';return false;\">cancel</a>";
	}
	else
	{
		showBlock(location,'none');
	}

	if(prefix == 'applicant_' || prefix == 'lc_')
	{ }
	else
	{
		document.getElementById(prefix + 'first_name').value = first_name;
		document.getElementById(prefix + 'last_name').value	= last_name;
	}

	if(prefix == 'broker_')
	{
		document.getElementById('broker_id').value	= id;
		showBlock('broker_form','none');
		showBlock('broker_form_instructions','none');
		showBlock('broker_cancel','block');
		showBlock('broker_chosen','block');
		document.getElementById('broker_chosen').innerHTML = 'You have chosen the existing contact: ' + first_name + ' ' + last_name + ' from our contact directory.';
	}
	else
	{
		document.getElementById(prefix + 'contact_id').value = id;
	}

	if (cancel_callback)
	{
		eval(cancel_callback+'();');
	}
}

/*
This functions require the AJAX methods
*/
function companyBrowser(contact_type, display_target, location, field, sort_by, dir, page_id, action, action2, callback, show_only, search_string, newcofunction)
{
	if(action == 'close')
	{
		showBlock(location,'none');
		if (typeof(callback)!="undefined")
		{
			if (callback != 'undefined')
			{
				eval(callback + '("' + action + '");');
			}
		}
	}
	else
	{
		if(!contact_type)
		{
			contact_type = '';
		}
		if(!show_only)
		{
			show_only = '';
		}
		if(!search_string)
		{
			search_string = '';
		}
		if (search_string.indexOf('&')!=-1)
		{
			search_string = escape(search_string);
		}
		
		var page_get = '/private/company_selector.php?list_chosen=' + contact_type + '&display_target=' + display_target + '&location=' + location + '&field=' + field + '&pageid=' + page_id + '&sortby=' + sort_by + '&dir=' + dir + '&callback=' + callback + '&show_only=' + show_only + '&search_string='+search_string + '&newcofunction='+newcofunction;
		ajaxpage(page_get, location);

		if (typeof(callback)!='undefined')
		{
			if (callback != 'undefined')
			{
				if (callback.indexOf('(')!=-1)
				{
					eval(callback);
				}
				else
				{
					eval(callback + '("' + action + '");');
				}
			}
		}
		showBlock(location,'block');
	}
}

function companySelected(location, display_target, field, company_id, company_name, callback)
{
	if (location == 'temp_bill_to_company' || location == 'temp_production_company' || location == 'insured_company' || location == 'permit_company')
	{
		clearFormatting(display_target);
		showBlock(location,'none');

		$(display_target).value 	= company_name
		$(field).value				= company_id + '~|~' + company_name;
		
		if (location == 'temp_production_company')
		{
			closeTempProduction();
			$('temp_prod_company_name').value = '';
			$('temp_prod_company_contact_name').value = '';
			$('temp_prod_company_phone').value = '';
			$('temp_prod_company_phone_ext').value = '';
		}
		
		if (location == 'insured_company')
		{
			closeTempInsurance();
			$('temp_company_name').value = '';
			$('temp_company_contact_name').value = '';
			$('temp_company_phone').value = '';
			$('temp_company_phone_ext').value = '';
		}

		if (typeof(callback)!="undefined" && callback!='undefined')
		{
			try
			{
				eval(callback + '("close");');
			}
			catch (e) {}
		}    
	}
	else if(display_target == 'ic_holder')
	{
		ajax(ajaxObject(),'GET','/private/insurance_detail.php?mode=get_company&company_id=' + company_id, insurancePopulate);
	}
	else if(display_target == 'associated')
	{
		ajax(ajaxObject(),'POST','/private/insurance_associated.php','associated_holder_edit','&mode=associated_add&view=edit&company_name=' + company_name + '&company_id=' + company_id);
	}
	else if(display_target == 'contacts_associated')
	{
		ajax(ajaxObject(),'POST','/private/contacts_associated_companies.php','associated_holder_edit','&mode=associated_add&view=edit&company_name=' + company_name.replace('&','%26') + '&company_id=' + company_id);
	}
	else
	{
		showBlock(location,'none');

		document.getElementById(display_target).innerHTML	= company_name + ' - <a href="javascript: removeCompanySelected(\'' + display_target + '\',\'' + field + '\')">remove</a>';
		document.getElementById(field).value				= company_id + '~|~' + company_name;

		var location_link = ge(location+'_link');
		
		if (location_link)
		{
			location_link.innerHTML = 'change';
		}

		if (typeof(callback)!="undefined" && callback!='undefined')
		{
			try
			{
				eval(callback + '("close");');
			}
			catch (e) {}
		}
	}
}

function removeCompanySelected(display_target, field)
{
	document.getElementById(display_target).innerHTML	= '';
	document.getElementById(field).value				= '';
}

function highlightRequired(post_result, prefix)
{
	if (typeof prefix == "undefined")
	{
		prefix = "";
	}
	for( var i = 0; i < post_result.fields.length; i++ )
	{
		var current_field = ge(prefix + post_result.fields[i]);
		if ( current_field.nodeName == 'INPUT' && current_field.type == 'text' || current_field.nodeName == 'TEXTAREA' || current_field.nodeName == 'SELECT')
		{
			if (typeof current_field.onfocus != 'function')
			{
				current_field.onfocus = 'clearFormatting(this.id);';
			}
			current_field.style.backgroundColor = '#FFCCCC';
		}
	}
}

function ge(element_id)
{
	return document.getElementById(element_id);
}

function gv(element_id)
{
	return document.getElementById(element_id).value;
}

function gxv(element_id)
{
	return escape(document.getElementById(element_id).value);
}

function numOnly(e, input, allow_zero)
{
	if (typeof allow_zero == "undefined")
	{
		allow_zero = false;
	}
	else
	{
		allow_zero = true;
	}
	
	var keynum;
	var keychar;
	var numcheck;
	
	if(window.event)
	{
		keynum = e.keyCode;
	}
	else if(e.which)
	{
		keynum = e.which;
	}
	switch (keynum)
	{
		case 8:
		case 9:
		case 18:
		case 27:
		case 37:
		case 38:
		case 39:
		case 40:
		case 46:
			return true;
	}
	if (allow_zero==false)
	{
		if ((keynum==96 || keynum == 48) && input.value=='')
		{
			return false;
		}
	}
	if (keynum <= 48 && keynum >= 57)
	{
		return true;
	}
	if (keynum >= 96 && keynum <= 105)
	{
		return true;
	}
	keychar = String.fromCharCode(keynum);
	numcheck = /\d/;
	return numcheck.test(keychar);
}

/*
Send in a JSON array as the haystack that looks like this: haystack.fields[i] and look for the node name that matches needle.

This is useful for searching a JSON array for specific fields, i.e select fields so you can handle them outside of the 
default error handling.
*/
function FindNeedle(haystack, needle)
{
	for( var i = 0; i < haystack.fields.length; i++ )
	{
		if(haystack.fields[i] == needle)
		{
			return true;
		}
	}
	return false;
};

function checkRequired(list)
{
	var required = new Array();
	for( var i = 0; i < list.length; i++ )
	{
		var item = list[i];
		if (gv(item)=='')
		{
			required.push(item);
		}
	}
	if (required.length > 0)
	{
		highlightRequired({ "fields": required });
		return false;
	}
	return true;
}

function toggle(obj, when_none) {
	var el = ge(obj);
	if ( el.style.display != when_none ) {
		el.style.display = when_none;
	}
	else {
		el.style.display = 'block';
	}
}

function formatProdTitle(id)
{
	ge(id).value = ge(id).value.toUpperCase().replace(/"/g,'');
}
//]]>
