var today = new Date()
var month = today.getMonth()
var year = today.getYear()

var browser = navigator.userAgent.toLowerCase()
var IE6 = (browser.indexOf('msie 6') != -1) ? true : false ;
var is_IE = (browser.indexOf('msie') != -1) ? true : false ;

var width = (IE6) ? "225px" : "220px" ;
var height = "247px"
var zIndex = "1000000000"

// email addresses
var JSONemail = {"addr": [
        {"name": "support", "domain": "checkmend", "tld": "com"},
        {"name": "info", "domain": "recipero", "tld": "com"}
    ]
};

function email(value)
{
	my_address = JSONemail.addr[value].name + "@" + JSONemail.addr[value].domain + "." + JSONemail.addr[value].tld
	document.write("<a href='mailto:" + my_address +"'>" + my_address +"<" + "/" + "a>")
}

loc_TO = null
function locations()
{
	if (loc_TO != null) { clearTimeout(loc_TO) }
	dimensions = my_dimensions(document.getElementById('locations_link'))
	dimensions_2 = my_dimensions(document.getElementById('wrapper'))
	dimensions_3 = my_dimensions(document.getElementById('container'))
	dimensions_4 = my_dimensions(document.body)
	document.getElementById('locations').style.top = "27px"
	if (IE6) {
		dimensions[1] += dimensions_2[1] + dimensions_3[1];
	} else if (is_IE) {
		dimensions[1] += dimensions_4[1] + dimensions_2[1] + dimensions_3[1];
	}
	document.getElementById('locations').style.left = dimensions[1].toString() + "px"
	document.getElementById('locations').style.visibility = 'visible'
}
function locations_hide()
{
	loc_TO = setTimeout("document.getElementById('locations').style.visibility = 'hidden'", 2000)
}

sections = Array('home_centre_col', 'home_stats', 'home_report_stolen', 'home_demo', 'home_report')
function highlight_me(obj)
{
	for (s in sections) {
		if (is_IE) {
			document.getElementById(sections[s]).style.filter = "alpha(opacity=50)";
		} else {
			document.getElementById(sections[s]).style.opacity = 0.5;
		}
	}
	if (is_IE) {
		obj.style.filter = "alpha(opacity=100)";
	} else {
		obj.style.opacity = 1;
	}
}
function unhighlight_me()
{
	for (s in sections) {
		if (is_IE) {
			document.getElementById(sections[s]).style.filter = "alpha(opacity=100)";
		} else {
			document.getElementById(sections[s]).style.opacity = 1;
		}
	}
}

function sort(item, order)
{
	my_order = (order.indexOf('asc') != -1) ? '&order_dir=desc' : '' ;
	item = item.replace(' ', '_')
	this_href = location.href.replace(/&order_by=([^&]*)/, '')
	this_href = this_href.replace(/&order_dir=([^&]*)/, '')
	this_href += "&order_by=" + item.toLowerCase() + my_order
	location.href= this_href
}

/**
* The Yahoo lightbox - needs the following in the script:

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.4.1/build/container/assets/container.css" /> 
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/container/container-min.js"></script>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.4.1/build/fonts/fonts-min.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.4.1/build/container/assets/skins/sam/container.css" />

*/	
function lightbox(title, id, my_width) {
	YAHOO.namespace("container");
	
	my_lightbox = document.createElement('div');
	my_lightbox.setAttribute ('id', 'lightbox_div')
	document.getElementsByTagName('body')[0].appendChild(my_lightbox)
	
	my_left = (document.documentElement.clientWidth)? document.documentElement.clientWidth/2 - 250 : false ;
	if (!my_left) { my_left = (window.innerWidth)? window.innerWidth/2 - 250 : document.body.clientWidth/2 - 250 ; }
	my_top = (document.documentElement.scrollTop)? document.documentElement.scrollTop + (document.documentElement.clientHeight/4) : false ;
	if (!my_top) { my_top = (window.pageYOffset)? window.pageYOffset + (window.innerHeight/4) : document.body.scrollTop + (document.body.clientHeight/4) ; }
	
	YAHOO.container.lightbox_div = 
	new YAHOO.widget.Panel('lightbox_div', { xy:[my_left,my_top], width:'500px', close:true, draggable:false, zindex:4, modal:true, visible:false, underlay:'matte', effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.3} } );
	YAHOO.container.lightbox_div.setHeader('<span>' + title + '</span>');
	YAHOO.container.lightbox_div.setBody("<p style='text-align:center;'><img src='thumbnail.php?stage=account&amp;photograph=" + id + "&amp;size=480' style='width:480px;'/></p>");
	YAHOO.container.lightbox_div.render(document.body);
	YAHOO.container.lightbox_div.show();
}

/**
* A useful function that returns an array (t -l - w - h) of the dimensions/position of an object
*/
function my_dimensions(the_obj) {
	if (the_obj) {
		my_values = new Array
		my_values[0] = (the_obj.offsetTop)? the_obj.offsetTop : the_obj.style.pixelTop ;
		my_values[1] = (the_obj.offsetLeft)? the_obj.offsetLeft : the_obj.style.pixelLeft ;
		my_values[2] = (the_obj.offsetWidth)? the_obj.offsetWidth : the_obj.style.pixelWidth ;
		my_values[3] = (the_obj.offsetHeight)? the_obj.offsetHeight : the_obj.style.pixelHeight ;
		return my_values
	}
}

function slide_all(dir) {
	// save the state of expanded rows
	var xmlHttpReq = false;
	var self = this;
	if (IE) {
		self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		self.xmlHttpReq = new XMLHttpRequest();
	}
	tds = document.getElementsByTagName('td')
	my_state = (dir == 'down') ? 'up' : 'down' ;
	my_ajax = (dir == 'down') ? 'on' : 'off' ;
	for (t in tds) {
		if (tds[t].id && tds[t].id.indexOf('slider_') != -1) {
			imgs = tds[t].getElementsByTagName('img')
			if (imgs[0].src.indexOf(my_state) == -1) {
				for (i in imgs) { imgs[i].src = 'images/' + my_state + '.png'; }
				obj = tds[t].id.replace('slider_', 'tr_')
				slide_from = my_dimensions(document.getElementById(obj))
				slide_to = my_dimensions(document.getElementById(obj).childNodes[0])
				if (my_state == 'down' && slide_from[3] > 25) {
					slide_up(obj)
				} else if (slide_from[3] < slide_to[3]) { 
					slide_down(obj)
				}
			}
			/* self.xmlHttpReq.open('GET', "ajax_save_state.php?store=inventory&object=" + obj + "&state=" + my_state, true);
			self.xmlHttpReq.send(null); */
		}
	}

	
}

function slide_row(obj) {
	slide_from = my_dimensions(document.getElementById(obj))
	slide_to = my_dimensions(document.getElementById(obj).childNodes[0])
	slider = obj.replace('tr_', 'slider_')
	imgs = document.getElementById(slider).getElementsByTagName('img')
	for (x in imgs) { imgs[x].src = (slide_from[3] < slide_to[3]) ? 'images/up.png' : 'images/down.png' ; }
	if (slide_from[3] < slide_to[3]) { slide_down(obj) } else { slide_up(obj) }
	
	// save the state of expanded rows
	var xmlHttpReq = false;
	var self = this;
	if (IE) {
		self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		self.xmlHttpReq = new XMLHttpRequest();
	}
	my_state = (slide_from[3] < slide_to[3]) ? 'on' : 'off' ;
	self.xmlHttpReq.open('GET', "ajax_save_state.php?store=inventory&object=" + obj + "&state=" + my_state, true);
	self.xmlHttpReq.send(null);
}
function slide_down(obj) {
	slide_from = my_dimensions(document.getElementById(obj))
	slide_to = my_dimensions(document.getElementById(obj).childNodes[0])
	if (slide_from[3] + 4 <= slide_to[3]) {
		my_height = slide_from[3] + 4
		document.getElementById(obj).style.height = my_height.toString() + "px"
		setTimeout("slide_down('" + obj + "')", 1)
	} else {
		document.getElementById(obj).style.height = slide_to[3].toString() + "px"
	}
}

function slide_up(obj) {
	slide_from = my_dimensions(document.getElementById(obj))
	if (slide_from[3] - 4 >= 25) {
		my_height = slide_from[3] - 4
		document.getElementById(obj).style.height = my_height.toString() + "px"
		setTimeout("slide_up('" + obj + "')", 1)
	} else {
		document.getElementById(obj).style.height = "25px"
	}
}

/**
* Used to display the calendar
*/
function calendar_show(field) {
	if (!document.getElementById('calendar')) {
		init_calendar()
	}
	editfield = field
	my_loc = my_dimensions(document.getElementById(editfield + '_year'))
	if (document.getElementById(editfield + '_year').value != '') {
		my_day = document.getElementById(editfield + '_day').value
		month = document.getElementById(editfield + '_month').value - 1
		year = document.getElementById(editfield + '_year').value
	} else {
		my_day = 1
		month = today.getMonth()
		year = today.getYear()
	}
	populate_titlebar()
	
	document.getElementById('calendar').style.top = my_loc[0].toString() + 'px'
	browser = navigator.userAgent.toLowerCase()
	if (browser.indexOf('msie') != -1 && browser.indexOf('opera') == -1) {
		my_loc_2 = my_dimensions(document.getElementById('container_2'))
		if (browser.indexOf('msie 6') == -1) {
			document.getElementById('calendar').style.left = (my_loc[1] + my_loc[2] + my_loc_2[1]).toString() + 'px'
		} else {
			document.getElementById('calendar').style.top = (my_loc[0] + 89).toString() + 'px'
			document.getElementById('calendar').style.left = (my_loc[1] + my_loc[2] + my_loc_2[1] + 288).toString() + 'px'
		}
	} else {
		document.getElementById('calendar').style.left = (my_loc[1] + my_loc[2]).toString() + 'px'
	}
	document.getElementById('calendar').style.visibility = 'visible'
}

/** 
* Add the Google Analytics onclick event to certain links
*/
function ga_links()
{
	IE = (navigator.appName == "Microsoft Internet Explorer") ? true : false ;
	anchors = document.getElementsByTagName('a')
	for (x in anchors) {
		if (!IE) {
			anchors[x].addEventListener('click', ga_click, true)
		} else {
			anchors[x].attachEvent('onclick', ga_click)
		}
	}
}
/**
* Track clicks on anchors using Google Analytics
* If you're only interested in certain document types then fill in the 'interest' array with file extensions and it will track just clicks directed to those file types
* Otherwise, leave the 'interest' array empty and fill in the 'no_interest' array with file extensions and it will track all clicks directed to file types that are not in that list
*/
function ga_click(e)
{
	interest = new Array()
	no_interest = new Array('php', 'html', 'htm', 'asp', 'shtml', 'ikml') // ignore these file types
	
	no_ga = false
	if (e.target) { targ = e.target }
	else if (window.event.srcElement) { targ = window.event.srcElement }
	if (targ.nodeType == 3) { targ = targ.parentNode }
	regExp = new RegExp(/\/\/([^\/]*)/)
	my_host = location.href.match(regExp)
	my_host = my_host[1].replace('www.', '')
	if (targ.href) {
		targ_host = targ.href.match(regExp)
		targ_host = targ_host[1].replace('www.', '')
		
		external_site = (targ_host != my_host) ? true : false ;
		if (external_site) {
			regExp2 = new RegExp(/\/\/(.*)/)
			my_link = targ.href.match(regExp2)
			ga_link = '/externalsite/' + my_link[1]
		} else {
			sections = targ.href.split('.')
			extension = sections[sections.length - 1]
			filter = (interest.length > 0) ? eval(interest) : eval(no_interest) ;
			no_ga = (interest.length > 0) ? true : false ;
			for (x = 0; x < filter.length; x++) {
				if (filter[x] == extension && interest.length == 0) { no_ga = true; break; }
				if (filter[x] == extension && interest.length > 0) { no_ga = false; break; }
			}
			if (!no_ga) {
				sections = targ.href.split('/')
				filename = sections[sections.length - 1]
				ga_link = '/clicks/' + extension + '/' + filename
			}
		}
		if (!no_ga) { pageTracker._trackPageview(ga_link); }
	}
}

/**
* The init function is called on page load to set variables and instantiate the calendar
* The onload method is appended to the window object by a command at the bottom of this script
*/
function init() {
	if (document.getElementById('get_towns')) {
		document.getElementById('get_towns').style.display = 'none'
		if (document.getElementById('town').value == '' && document.getElementById('town').options.length == 1) {
			document.getElementById('town').parentNode.style.visibility = 'hidden'
		}
	}
	// this is a little fix that enables IE to fix it's silly height and clearing issues without needing another stylesheet
	if	(document.getElementById('left_column')) {
		left_height = my_dimensions(document.getElementById('left_column'))[3]
		right_height = my_dimensions(document.getElementById('right_column'))[3]
		if (left_height > right_height) {
			document.getElementById('right_column').style.height = left_height.toString() + 'px'
		}
	}

	//ga_links()
	
	labels = document.getElementsByTagName('label')
	for (x = 0; x < labels.length; x++) {
		if (labels[x].className == 'date' || labels[x].className == 'date_floated') {
			field = labels[x].parentNode.getElementsByTagName('select')[0].id.replace('_day', '')
			labels[x].parentNode.innerHTML += "<a href='#' onclick='calendar_show(\"" + field + "\"); return false'><img src='/eu/images/calendar.png' alt='calendar' class='calendar_icon'/></a>"
		}
	}
	if (document.getElementById('form_buttons')) {
		anchors = document.getElementById('form_buttons').getElementsByTagName("a")
		my_innerHTML = document.getElementById('form_buttons').innerHTML
		for (a in anchors) {
			if (anchors[a] && typeof(anchors[a].href) != "undefined") {
				my_innerHTML = my_innerHTML.replace(anchors[a].parentNode.innerHTML, "<input type='button' onclick='location.href=\"" + anchors[a].href + "\"' value=\"" + anchors[a].innerHTML + "\" class='button_black'/>")
			}
		}
		document.getElementById('form_buttons').innerHTML = my_innerHTML
	}
	
	if (document.getElementById("last_added")) {
		setTimeout("fade_out('last_added', 0, true)", 5000)
	}
	
	// make any link with the class 'popup' a popup link onclick with the correct icon / or no icon where necessary
	anchors = document.getElementsByTagName("a")
	for (x in anchors) {
		if (anchors[x].className == "popup" || anchors[x].className == "popup_no_icon" || anchors[x].className == "close" || anchors[x].className == "popup_no_icon_full") {
			// set onclick command
			if (anchors[x].className == "close") {
				my_command = "window.close()"
			} else if (anchors[x].className == "popup" || anchors[x].className == "popup_no_icon" || anchors[x].className == "popup_no_icon_full") {
				my_command = "popup_win = window.open('" + anchors[x].href + "', 'popup', '"
				if (anchors[x].className == "popup_no_icon") {
					my_command += "height=660px, width=620px, "
				}
				my_command += "scrollbars, resizable, menubar, location, toolbar, status, directories'); popup_win.focus(); return false"
			}
			//assign command
			if(is_IE) {
				html = anchors[x].parentNode.innerHTML
				myregexp = new RegExp("<" + anchors[x].tagName + "[^>]+title=[\"]*" + anchors[x].title + "[\"]*[^>]+>", "gi")
				if (html.match(myregexp)) {
					this_anchor = html.match(myregexp)
					myregexp = new RegExp("href=\"([^\"])*\"")
					this_anchor_new = this_anchor[0].replace(myregexp, "href=\"\1\" onclick=\"" + my_command + "\"")
					anchors[x].parentNode.innerHTML = anchors[x].parentNode.innerHTML.replace(this_anchor[0], this_anchor_new)
				}
			} else {
				anchors[x].setAttribute("onclick", my_command)
				//anchors[x].setAttribute("href", "#")
			}
			if (anchors[x].className == 'popup') {
				anchors[x].innerHTML += "&#160;<img src='/eu/images/popup.gif' alt=''/>"
			}
		}
	}
	
	if (document.getElementById('date_of_birth_day')) {
		year = year - 30
		month = 0
	}
}
function init_calendar()
{
	calendar = document.createElement('div');
	calendar.setAttribute ('id' , 'calendar')
	calendar.setAttribute ('class' , 'calendar')
	titlebar = document.createElement('div')
	titlebar.setAttribute ('id' , 'titlebar')
 	calendar.appendChild(titlebar);
	datesbar = document.createElement('div')
	datesbar.setAttribute ('id' , 'datesbar')
 	calendar.appendChild(datesbar);
	document.getElementsByTagName('body')[0].appendChild(calendar)

	document.getElementById('calendar').style.position = "absolute"
	document.getElementById('calendar').style.width = width
	document.getElementById('calendar').style.height = height
	document.getElementById('calendar').style.left = "20px"
	document.getElementById('calendar').style.bottom = "20px"
	document.getElementById('calendar').style.zIndex = zIndex
	document.getElementById('calendar').style.border = "1px solid #acacac"
	document.getElementById('calendar').style.visibility = "hidden"
	document.getElementById('calendar').style.backgroundColor = "#dfdfdf"
	document.getElementById('calendar').style.fontFamily = "arial, verdana"
	populate_titlebar()
}
function populate_titlebar() {
	document.getElementById('titlebar').style.width = width
	document.getElementById('titlebar').style.height = '20px'
	document.getElementById('titlebar').style.textAlign = "center"
	document.getElementById('titlebar').style.fontWeight = "bold"
	document.getElementById('titlebar').style.fontFamily = "arial, verdana"
	browser = navigator.userAgent.toLowerCase()
	year = year%1900 + 1900
	var thisDate = new Date(year, month, 01)
	year = thisDate.getYear()
	year = year%1900 + 1900
	browser = navigator.userAgent.toLowerCase()
	month = thisDate.getMonth()

	months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	if (month == 12) {
		month = 0
		year++
	}
	if (month == -1) {
		month = 11
		year--
	}
	thisMonth = months[month]
	document.getElementById('titlebar').innerHTML = "<div style='font-weight:bold; text-align:center; margin:4px 4px 2px 4px;'>"
	document.getElementById('titlebar').innerHTML += "<div style='float:left; margin-left:4px;'><a href='javascript: year--;populate_titlebar()' title='Minus year' style='background-color:transparent;'><img src='/eu/images/icon_back.gif' style='border:none;' alt=''/></a><a href='javascript: month--;populate_titlebar()' title='Minus month' style='background-color:transparent;'><img src='/eu/images/icon_previous.gif' style='border:none;' alt=''/></a></div>"
	document.getElementById('titlebar').innerHTML += "<div style='float:right; margin-right:4px;'><a href='javascript: month++;populate_titlebar()' title='Add month' style='background-color:transparent;'><img src='/eu/images/icon_next.gif' style='border:none;' alt=''/></a><a href='javascript: year++;populate_titlebar()' title='Add year' style='background-color:transparent;'><img src='/eu/images/icon_forw.gif' style='border:none;' alt=''/></a></div>"	
	document.getElementById('titlebar').innerHTML += "" + thisMonth + " " + year + "</div>"

	populate_datesbar()
}
function populate_datesbar() {
	document.getElementById('datesbar').style.width = width
	document.getElementById('datesbar').style.top = '20px'
	document.getElementById('datesbar').style.textAlign = "center"
	todayyear = today.getYear()

	browser = navigator.userAgent.toLowerCase()
	todayyear = todayyear%1900 + 1900

	// column headings
	day_titles = new Array('Su','Mo','Tu','We','Th','Fr','Sa')
	day_titles_full = new Array('Sun','Mon','Tues','Wed','Thurs','Fri','Sat')
	page = "<div style='clear:both; width:"
	page += (IE6) ? "212" : "210" ;
	page += "px; margin:4px 4px 0px 4px; cursor:default; font-weight:bold;'>"
	for (x = 0; x < day_titles.length; x++) {
		page += "<div style='float:left; width:30px; text-align:center;'>" + day_titles[x] + "</div>"
	}
	page += "<div style='clear:both; height:0px; overflow:hidden;'></div></div>"

	day = today.getDate()
	startingday = new Date(year,month,1)
	startingday = startingday.getDay()

	days = new Array('31','28','31','30','31','30','31','31','30','31','30','31');
	totaldays = days[month]
	if (month == 1 && year % 4 == 0) { totaldays++ }
	month_previous = (month == 0) ? 11 : (month-1) ;
	totaldays_previous = days[month_previous]
	if (month_previous == 1 && year % 4 == 0) { totaldays_previous++ }
	totaldays_previous = totaldays_previous - (startingday-1)
	
	rows = 6
	
	page += "<div style='width:"
	page += (IE6) ? "212" : "210" ;
	page += "px; margin-left:4px; border:1px #acacac solid; border-bottom:none; background-color:white;'>"
	for (y = 0; y < 7; y++) {
		if (y == startingday) {
			break;
		} else {
			page += "<div style='float:left; width:30px; height:30px; cursor:default; background-color:#acacac; color:#6a6a6a'><div style='padding-top:7px;'>" + (totaldays_previous++) + "</div></div>"
		}
	} 
	has_break = false
	for (x = 1; x <= totaldays; x++) {
		if ((x + startingday) != 1 && (x + startingday) % 7 == 1) {
			has_break = true
			rows--
		}
		page += "<div style='float:left; cursor:pointer; text-align:center;"
		if ((x + startingday) % 7 != 0) {
			page += " border-right:1px #acacac solid; width:"
			page += (IE6) ? "30px;" : "29px;" ;
		} else {
			page += " width:30px;"
		}
		if (has_break) {
			page += " border-top:1px #acacac solid; height:29px;"
		} else {
			page += " height:30px;"
		}
		my_title = day_titles_full[(x + startingday - 1) % 7] + " " + thisMonth + " " + x + ", " + year
		page += "' onMouseOver='this.style.backgroundColor = \"#2960cf\"; this.style.color = \"white\"; document.getElementById(\"cal_current\").innerHTML=\"" + my_title + "\"' onMouseOut='this.style.backgroundColor = \"white\";this.style.color = \"black\"; document.getElementById(\"cal_current\").innerHTML=\"\"' onClick='selectDate(" + x + "," + (month + 1) + "," + year + ")'><div style='padding-top:6px;'>" + x + "</div></div>"
	}
	z = (x + startingday) % 7
	n = 1
	if (z != 1) {
		if (z == 0) { z = 7 }
		for (z = z - 1; z < 7; z++) {
			page += "<div style='float:left; width:30px; height:30px; cursor:default; background-color:#acacac; color:#6a6a6a'><div style='padding-top:7px;'>" + (n++) + "</div></div>"
		}
		rows--
	} else {
		rows--
	}
	if (rows > 0) {
		for (z = 1; z <= (rows*7); z++) {
			page += "<div style='float:left; width:30px; height:30px; cursor:default; background-color:#acacac; color:#6a6a6a'><div style='padding-top:7px;'>" + (n++) + "</div></div>"
		}
	}
	page += "<div style='clear:both; height:1px; overflow:hidden; background-color:#acacac;'></div></div><div style='float:right; height:15px; overflow:hidden; margin:4px;'><a href='javascript: hide()' style='background-color:transparent;'><img src='/eu/images/icon_close.gif' style='border:none;' alt=''/></a></div><div style='text-align:left; color:#6a6a6a; margin:4px; font-size:95%;' id='cal_current'>&#160;</div>"

	document.getElementById("datesbar").innerHTML = page
}

function selectDate(d,m,y) {
	d.toString().length < 2 ? d = "0" + d.toString() : d = d ;
	m.toString().length < 2 ? m = "0" + m.toString() : m = m ;
	eval ("document.getElementById('" + editfield + "_day').value = '" + d.toString() + "'")
	eval ("document.getElementById('" + editfield + "_month').value = '" + m.toString() + "'")
	eval ("document.getElementById('" + editfield + "_year').value = '" + y.toString() + "'")
	document.getElementById("calendar").style.visibility = "hidden"
}
function hide() {
	document.getElementById("calendar").style.visibility = "hidden"
}

var ajax_compat = true
var IE = (navigator.appName == "Microsoft Internet Explorer") ? true : false ;
try {
	// Firefox, Opera 8.0+, Safari
	xmlHttp = new XMLHttpRequest();
} catch (e) {
	// Internet Explorer
	try {
		xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			ajax_compat = false
		}
	}
}
/**
* Use AJAX to get a list of towns for the selected county
* This uses the same function as the PHP-generated towns list so that non-js enabled browsers don't get a different list
*/
function AJAX_load(file, value, return_function) {
	var xmlHttpReq = false;
	var self = this;
	if (IE) {
		self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		self.xmlHttpReq = new XMLHttpRequest();
	}
	self.xmlHttpReq.open('GET', file + "?" + value, true);
	self.xmlHttpReq.onreadystatechange = function() {
      	if (self.xmlHttpReq.readyState == 4 && return_function) {
            populate_counties(self.xmlHttpReq.responseText)
        }
	}
	self.xmlHttpReq.send(null);
}

/**
* These two functions are used to get the towns list and alter the towns select innerHTML
*/
function get_counties() {
	county = document.getElementById('county').value
	return AJAX_load('ajax_counties.php', 'county=' + county, populate_counties)

}
function populate_counties(value) {
	document.getElementById('town').options.length = 0;
	my_options = value.split('---')
	for (x = 0; x < my_options.length; x++) {
		this_options = my_options[x].split('::')
		if (this_options[0] != '') {
			document.getElementById('town').options[x] = new Option(this_options[1], this_options[0]);
		}
	}
	document.getElementById('town').parentNode.style.visibility = 'visible'
	document.getElementById('town').focus()
}

/**
* Validation - this just checks for empty fields that are mandatory and highlights the mandatory asterisk and gives a bold red error message at the top
* This uses JSON to do the error messages... which is added during deployment
*/
var JSONerrors = {"host_url":"dev.checkmend.com","no_data_true":"No form data was entered","field_match_true":"The submitted fields do not match what was expected","my_captcha_empty":"Please enter the security code ","my_captcha_invalid":"The captcha code that you have entered is not correct","identifier_empty":"Please enter an identifer (a unique serial number)","identifier_invalid":"Please enter an identifer of 5 or more characters","identifier_credits":"You do not have enough available credits to perform this search","email_empty":"Please enter an email address","email_invalid":"Please check the email address that you have entered","email_confirmation_empty":"Please re-enter your email address in the confirmation field. This helps avoid typing errors.","agree_to_terms_invalid":"You must agree to the terms and conditions before continuing","name_empty":"Please enter a name","name_api_fail":"Could not connect to checking service, please wait a few moments then try again","type_api_fail":"Could not connect to checking service, please wait a few moments then try again","card_type_empty":"Please enter a card type","card_number_empty":"Please enter a card number","card_number_invalid":"Please enter a valid card number","cv2_empty":"Please enter a security code","cv2_length":"Your security code should be 3 or 4 digits, you have entered:","expiry_month_empty":"Please enter an expiry month for your card","expiry_year_empty":"Please enter an expiry year for your card","house_number_empty":"Please enter your house name or number","address_1_empty":"Please provide the first line of your address","town_empty":"Please enter your postal town or city","post_code_empty":"Please enter your zip \/ postal code","issue_number_length":"Your issue number can only be a mximum of 4 numbers, you have entered:","password_empty":"Please enter a password","password_confirmation_empty":"Please re-enter your password in the confirmation field. This helps avoid typing errors.","password_confirmation_invalid":"Please enter a matching password in the confirmation field.","email_used":"An account already exists for the given email address","email_confirmation_invalid":"Please enter a matching email address in the confirmation field.","email_failed_login":"You could not be logged in. Please try again.","email_account_not_found":"No account matching that email address was found","new_password_invalid":"If you enter a new password you must enter a matching confirmation password","agree_invalid":"You must agree to the terms and conditions before continuing","file_upload_invalid":"Please upload a file","reference_used":"You already have a batch with that reference name","reference_empty":"Please enter a batch reference","id_invalid":"Please check your certificate ID and item identifier and try again","id_empty":"Please check your certificate ID and item identifier and try again","company_name_empty":"Please enter your company\/trading name","county_empty":"Please enter your state name","make_invalid":"Please enter a make","model_invalid":"Please enter a model","type_invalid":"Please enter an item type","make_empty":"Please enter a make","model_empty":"Please enter a model","type_empty":"Please enter an item type"}

function validate() {
	spans = document.getElementsByTagName('span')
	valid = true
	error_string = ''
	for (x in spans) {
		if (spans[x].className == 'mandatory') {
			has_error = false
			if (spans[x].parentNode.getElementsByTagName('input').length > 0 && spans[x].parentNode.getElementsByTagName('input')[0].className != 'button' && spans[x].parentNode.getElementsByTagName('input')[0].value == '') {
				has_error = true
				me = spans[x].parentNode.getElementsByTagName('input')[0]
			} else if (spans[x].parentNode.getElementsByTagName('textarea').length > 0 && spans[x].parentNode.getElementsByTagName('textarea')[0].value == '') {
				has_error = true
				me = spans[x].parentNode.getElementsByTagName('textarea')[0]
			} else if (spans[x].parentNode.getElementsByTagName('select').length > 0 && spans[x].parentNode.getElementsByTagName('select')[0].value == '') {
				has_error = true
				me = spans[x].parentNode.getElementsByTagName('select')[0]
			}
			if (has_error) {
				spans[x].style.color = '#ce0c0c'
				my_error = eval('JSONerrors.' + me.id + '_empty');
				error_string += "<li><a href='#' onclick='document.getElementById(\"" + me.id + "\").focus(); return false'>" + my_error + "</a></li>"
				valid = false
			} else {
				spans[x].style.color = 'black'
			}
		}
	}
	if (valid) {
		return true
	} else {
		if (!document.getElementById('error_output')) {
			var error = document.createElement('p')
			error.setAttribute('class', 'error')
			error.setAttribute('id', 'error_output')
			error_msg = document.createTextNode('There are some errors on your form. Please review and correct before continuing.')
			error.appendChild(error_msg)
			var form = document.getElementById('main_form')
			form.insertBefore(error, form.childNodes[0])
			document.getElementById('error_output').style.fontWeight = 'bold'
			document.getElementById('error_output').style.color = '#ce0c0c'
			document.getElementById('error_output').style.marginLeft = '15px'
			var error = document.createElement('div')
			error.setAttribute('id', 'error_list')
			form.insertBefore(error, form.childNodes[1])
			document.getElementById('error_list').innerHTML = "<ul class='error'>" + error_string + "</ul>"
			//location.href = '#top'
		}
		return false
	}
}
/* This can go when IE6 is defunct, yay! */
function thumbnail(obj, state)
{
	if (browser.indexOf('msie') != -1) {
		obj.style.filter = (state == 1) ? "alpha(opacity=100)" : "alpha(opacity=60)" ;
	} else {
		obj.style.opacity = (state == 1) ? 1 : 0.6 ;
	}
}
var fade_level = null
function fade_out(obj, level, shrink)
{
	if (fade_level == null) { fade_level = 100 }
	if (fade_level > level) {
		fade_level -= 5
		if (shrink) {
			dimensions = my_dimensions(document.getElementById(obj))
			new_height = dimensions[3] / 100 * fade_level
			document.getElementById(obj).style.height = new_height.toString() + 'px';
		}
		if (is_IE) {
			document.getElementById(obj).style.filter = "alpha(opacity=" + fade_level.toString()  + ")";
		} else {
			document.getElementById(obj).style.opacity = fade_level/100;
		}
		setTimeout("fade_out('" + obj + "', " + level.toString() + ", " + shrink.toString() + ")", 50)
	} else {
		fade_level = null
	}
}

var editfield = null
window.onload = init
