var BAD_EMAIL =					"Please enter a valid email address."
var REQUIREDFIELD =				"Required field"
var NAME_LABEL =				"Name"
var PHONE_LABEL =				"Phone"
var DETAILS_LABEL =				"Details"
var MUST_NOT_EXCEED =			"no debe exceder"
var CHARACTERS =				"characters"
var YOU_HAVE_ENTERED =			"You have entered"
var BAD_ZIPCODE_US =			"Please enter a 5-digit zip code."
var NO_LINKS =					"No links in fields please."
var THANK_YOU_FOR_CONTACTING =	"Thank you for contacting"
var PROBLEM =					"There was a problem submitting the form.\nPlease make sure there are no links in your content."
var THANK_YOU_FOR_SUBSCRIBING =	"Thank you for subscribing"

/*	MISC	*/

function secure_url () {
	return window.location.href.search(/^https/) != -1
}

function showFlash (width, height, URL) {
	var s = secure_url ? "s" : ""

	//DON'T KNOW IF ALIGN NECESSARY
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http' + s + '://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="' + width + '" height="' + height + '" align="middle">')
	document.write('<param name="movie" value="' + URL + '" />')
	document.write('<param name="quality" value="high" />')

	//THIS NEXT ONE SO THAT DROPDOWN MENUS HANGING OVER FLASH DON'T DISAPPEAR
	document.write('<param name="wmode" value="opaque">')

	//DON'T KNOW WHAT THIS DOES
	document.write('<param name="allowScriptAccess" value="sameDomain" />')

	//DON'T KNOW IF NECESSARY, BUT IT CAUSED THE FLASH IN ALIYAH JOB CENTER TO DISAPPEAR, SO DISABLING IT -- ALSO REMOVED bgcolor="#ffffff" FROM EMBED
	//document.write('<param name="bgcolor" value="#ffffff" />')

	//THE EMBED STATEMENT HAS PROPERTIES MATCHING ALL OF THE ABOVE PARAMS, PLUS TYPE AND PLUGINSPAGE
	document.write('<embed width="' + width + '" height="' + height + '" align="middle" src="' + URL + '" quality="high" wmode="opaque" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />')
	document.write('</object>')
}

function browserType () {
	if (found(navigator.appName, "Microsoft"))
		return "IE"
	if (navigator.userAgent.search(/Chrome/i) != -1)
		return "Google"
	if (navigator.userAgent.search(/Safari/i) != -1)
		return "Safari"
	if (navigator.userAgent.search(/Firefox/i) != -1)
		return "FF"
	return "FF"
}

function MM_preloadImages () { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function preload_specific_images() {
	var i
	for (i = 0; i < preloads.length; i++)
		preloads[i] = "'http://www.TheTopInjuryAttorneys.com/img/" + preloads[i] + "'"
	eval("MM_preloadImages(" + preloads.join(",") + ")")
}

if (typeof preloads != "undefined")
	loadAttacher(preload_specific_images)

function isObject (myID) {
	return (document.getElementById(myID) + "").search(/^\[object.*\]$/) != -1
}

function isVar (myVar) {
	return typeof myVar != "undefined"
}

function isnull (arg) {
	arg = arg + '';
	return (arg == '' || arg == 'null' || arg == 'undefined')
}

function loadAttacher (loadFunc) {
	if (window.addEventListener) {
		window.addEventListener("load", loadFunc, false)
	}
	else if (document.addEventListener) {
		document.addEventListener("load", loadFunc, false)
	}
	else if (window.attachEvent) {
		window.attachEvent("onload", loadFunc)
	}
}

//	OBJECT DISPLAYED IF PARENT CLICKED ON

function hide_and_seek (myID) {
	myStyle = document.getElementById(myID).style
	myStyle.display = myStyle.display == "" ? "none" : ""
}

/*	INPUT OBJECT RELATED FUNCTIONS	*/

function touchdown (myInput, defaultText) {
	if (myInput.value == defaultText) {
		myInput.style.textAlign = "left"
		myInput.value = ""
	}
}

function leaveField (myInput, defaultText) {
	if (myInput.value == "") {
		myInput.value = defaultText
	}
}

function numbersOnly (myField, e, decimal) {
	 var key, keyChar
	 if (window.event)
		 key = window.event.keyCode
	 else if (e)
		 key = e.which
	 else
		 return true
	 keyChar = String.fromCharCode(key)
	 // control keys
	 if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
		 return true
	 // numbers
	 else if (("0123456789").indexOf(keyChar) > -1)
		 return true
	// decimal point jump -- jump to the next field. code not working at this point.
	 else if (decimal && (keyChar == ".")) {
		myField.form.elements[decimal].focus()
		return false
	 }
	 else
		return false
}

function setInputs () {
	var myElements = document.getElementsByTagName("input")
	var i
	for (i = 0; i < myElements.length; i++) {
		if (myElements[i].getAttribute("type")) {
			if (myElements[i].getAttribute("type") == "text")
				myElements[i].className += " text"
			else if (myElements[i].getAttribute("type") == "password")
				myElements[i].className += " password"
			else if (myElements[i].getAttribute("type") == "button")
				myElements[i].className += " button"
			else if (myElements[i].getAttribute("type") == "submit")
				myElements[i].className += " button"
			else if (myElements[i].getAttribute("type") == "file")
				myElements[i].className += " file"
			myElements[i].className = myElements[i].className.replace(/^ /, "")
		}
	}
}

/*	STRING RELATED FUNCTIONS	*/

function empty (value) {
	return found(value, /^\s*$/)
}

//	THIS FUNCTION FOR CHECKING FOR EMPTY FIELDS WHEN THE LABEL IS INSIDE THE FIELD
//	TAKES INTO ACCOUNT SITUATIONS LIKE: 1. *NAME, 2. *[NAME], 3. NAME:

function reallyEmpty (id, actualLabel) {
	baseLabel = actualLabel.replace(/(^\*|:$)/g, "")
	baseLabel = baseLabel.replace(/(^[\[\(]|[\]\)]$)/g, "")
	inputText = getValue(id)
	return inputText == actualLabel || inputText == baseLabel || empty(inputText) ? (REQUIREDFIELD + ": " + baseLabel) : ""
}

function getValue (id) {
	return document.getElementById(id).value
}

function setValue (id, value) {
	document.getElementById(id).value = value
}

function found (haystack, needle) {
	return haystack.search(needle) != -1
}

function doEncrypt (myString) {
	var result = "";
	var i;
	for (i = 0; i < myString.length; i++)
		result += "&#" + myString.charCodeAt(i) + ";";
	return result;
}

function doMailto (to) {
	mailto = doEncrypt("mailto:");
	email = doEncrypt(to);
	anchorText = to
	extra = ""
	subject = ""
	if (doMailto.arguments.length >= 2 && doMailto.arguments[1] != "")
		subject = doEncrypt("?subject=" + doMailto.arguments[1]);
	else
		subject = ""
	if (doMailto.arguments.length >= 3 && doMailto.arguments[2] != "")
		anchorText = doMailto.arguments[2];
	else
		anchorText = to
	if (doMailto.arguments.length == 4 && doMailto.arguments[3] != "")
		extra = doMailto.arguments[3];
	else
		extra = ""
	return '<a extra href="' + mailto + email + subject + '">' + anchorText + "</a>"
}

//	FIELD VALIDATION

function addField (myID, myLabel, myRequired, myValidate, myMax) {
	fieldIDs.push(myID)
	fieldLabels.push(myLabel)
	fieldRequireds.push(myRequired)
	fieldValidations.push(myValidate)
	if (isnull(document.getElementById(myID).getAttribute("name")))
		document.getElementById(myID).setAttribute("name", myID)
	if (myMax)
		document.getElementById(myID).setAttribute("maxLength", myMax)
}

function removeWhiteSpace (myObject) {
	setValue(myObject.id, myObject.value.replace(/(^ *| *$)/g, "").replace(/ +/g, " "))
}

function simpleCheck (id, pattern, message) {
	myValue = getValue(id)
	if (empty(myValue))
		return ""
	return found(myValue, pattern) ? "" : message
}

function validate_email (id) {
	return simpleCheck(id, /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/, BAD_EMAIL)
}

function validate_emailList (id) {
	originalValue = document.getElementById(id).value
	document.getElementById(id).value = document.getElementById(id).value.
		replace(/;/g, ",").
		replace(/[, ]+/g, ",").
		replace(/(^[ ,]*|[ ,]*$)/g, "")
	emailList = document.getElementById(id).value.split(",")
	if (emailList.length > 10) {
		document.getElementById(id).value = originalValue
		return "You have entered more than 10 email addresses.\nPlease check this entry and try again."
	}
	for (i = 0; i < emailList.length; i++)
		if (emailList[i].search(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/) == -1) {
			document.getElementById(id).value = originalValue
			return "The e-mail address '" + emailList[i] + "' is not a valid e-mail address.\nPlease check your entry and try again."
	}
	return ""
}

function validate_empty_zipcode (id) {
	return found(getValue(id), /^\d{5}$/) ? "" : BAD_ZIPCODE_US
}

function validate_textarea_max (id, name, max_chars) {
	return getValue(id).length > max_chars ? (name + " must not exceed " + max_chars +
		" characters. (You have entered " + getValue(id).length + ".)") : ""
}

var debug = false

function checkFields () {
	var invalidField = ""
	var message = ""
	if (debug)
		alert("In checkfields")
	
	for (var i in fieldIDs) {
		if (debug)
			alert(i + ": " + fieldIDs[i])
		if (document.getElementById(fieldIDs[i])) {
			currentObject = document.getElementById(fieldIDs[i])
			if (currentObject.type == "text" || currentObject.type == "textArea")
				removeWhiteSpace(currentObject)
			if (!currentObject.disabled) {
				if (debug)
					alert("Req: " + fieldRequireds[i] + ". Valid: " + fieldValidations[i] + ". Value: " + currentObject.value)
				if ((fieldRequireds[i] && empty(currentObject.value)) ||
					(fieldValidations[i] &&
					(message = eval("validate_" + fieldValidations[i] + "('" + fieldIDs[i] + "')")) != "")) {
						invalidField = fieldIDs[i]
						break
				}
			}
		}
	}

	if (debug)
		alert("Out of loop")
	if (checkFields.arguments.length == 1)
		return invalidField == ""
	if (invalidField != "") {
		alert(message == "" ? REQUIREDFIELD + ": " + fieldLabels[i] : message)
		document.getElementById(invalidField).focus()
		return false
	}
	if (isObject("formSubmitButton"))
		document.getElementById("formSubmitButton").disabled = true
	else if (isObject("submitTD"))
		setTimeout("disableButton()", 10)
	return true
}

function checkForm (myFunc) {
	fieldIDs = Array();
	fieldLabels = Array();
	fieldRequireds = Array();
	fieldValidations = Array();

	myFunc()
	var i
	for (i = 0; i < fieldIDs.length; i++)
		if (getValue(fieldIDs[i]).search(/(https?:\/\/|href=)/) != -1) {
			alert(NO_LINKS)
			document.getElementById(fieldIDs[i]).focus()
			return false
		}
	if (!checkFields())
		return false
	return true
}

//	FOR AJAX

function GetXmlHttpObject () {
	var xmlHttp = null
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest()
	}
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")
		}
		catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
		}
	}
	return xmlHttp
}

function fix_url (url) {
	if (window.location.href.search(/^http:\/\/www\./) != -1 && url.search(/^http:\/\/www\./) == -1) {
		url = url.replace(/^http:\/\//, "http://www.")
	}
	if (window.location.href.search(/^http:\/\/www\./) == -1 && url.search(/^http:\/\/www\./) != -1) {
		url = url.replace(/^http:\/\/www\./, "http://")
	}
	return url
}

//	FOR SUBSCRIPTION TO PHP LIST

function subscribe (params) {
	if (
		isObject("subscribe_email")
		&&
		(empty(getValue("subscribe_email")) || validate_email("subscribe_email") != "")
	) {
		alert(BAD_EMAIL)
		document.getElementById("subscribe_email").focus()
		return
	}
	xmlHttp = GetXmlHttpObject()
	if (xmlHttp == null) {
		alert("Your browser does not support AJAX!")
		return
	}
	if (isObject("submitContainer") && isObject("wait")) {
		document.getElementById("submitContainer").style.display = "none"
		document.getElementById("wait").style.display = ""
	}
	var url = "http://www.TheTopInjuryAttorneys.com/process_subscribe.php"
	url = fix_url(url)
	xmlHttp.onreadystatechange = subscribe_stateChanged
	xmlHttp.open("POST" , url , true)
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8;")
	xmlHttp.send(params)
}

function subscribe_stateChanged () { 
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseText.search(/^(OK){1,2}$/) != -1) {
			alert(THANK_YOU_FOR_SUBSCRIBING)
			if (isObject("submitContainer") && isObject("wait")) {
				document.getElementById("wait").style.display = "none"
				document.getElementById("submitContainer").style.display = ""
			}
		}
		else
			document.getElementById("resultDiv").innerHTML = xmlHttp.responseText
	}
}

//	CONTACT	FORM

var contact_wait = -1

function process_contact (params) {
	xmlHttp = GetXmlHttpObject()
	if (xmlHttp == null) {
		alert("Your browser does not support AJAX!")
		return
	}
	if (contact_wait != -1) {
		document.getElementById(contact_wait + "submitContainer").style.display = "none"
		document.getElementById(contact_wait + "wait").style.display = ""
	}
	var url = "http://www.TheTopInjuryAttorneys.com/process_contact.php"
	url = fix_url(url)
	xmlHttp.onreadystatechange = contact_stateChanged
	xmlHttp.open("POST" , url , true)
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8;")
	xmlHttp.send(params)
}

function contact_stateChanged () { 
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseText.search(/CONTACTOK/) != -1) {
			blogName = "Top NY New York Personal Injury Lawyers (TOP-EN)".replace(/\(.*\)$/, "")
			alert(THANK_YOU_FOR_CONTACTING + " " + blogName + ", Experienced Personal Injury lawyers and Medical Malpractice attorneys..")
			pageTracker._trackPageview("/Contact Us Submission");
			if (contact_wait != -1) {
				document.getElementById(contact_wait + "submitContainer").style.display = ""
				document.getElementById(contact_wait + "wait").style.display = "none"
			}
		}
		else if (xmlHttp.responseText.search(/^NOGOOD$/) != -1) {
			alert(PROBLEM)
		}
		else
			document.getElementById("resultDiv").innerHTML = xmlHttp.responseText
	}
}

//	RESIZING VIDEOS

function resize_object (myObject, myProperty, newWidth) {
	currentWidth = parseInt(myProperty.width)
	currentHeight = parseInt(myProperty.height)
	newHeight = newWidth / currentWidth * currentHeight
	myProperty.width = newWidth
	myProperty.height = newHeight
}

function resize_video (myID, newWidth) {
	myParent = document.getElementById(myID)
	if (browserType() == "IE") {
		myInner = myParent.innerHTML.replace(/[\r\n]/g, " ")
		if (myInner.search(/<object.*>.*<embed.*>.*<\/object>/i) != -1) {
			myInner = myInner.replace(/<\/?object.*?>/ig, " ")
			myParent.innerHTML = myInner
		}
	}
	resize_object_type(myParent, newWidth, "object")
	resize_object_type(myParent, newWidth, "embed")
	document.getElementById(myID).style.display = ""
}

function resize_object_type (myParent, newWidth, objectType) {
	myObjects = myParent.getElementsByTagName(objectType)
	var i
	for (i = 0; i < myObjects.length; i++) {
		currentObject = myObjects[i]
		if (objectType == "embed")
			currentObject.wmode = "transparent"
		if (!isnull(currentObject.style.width)) {
			resize_object(currentObject, currentObject.style, newWidth)
		}
		else if (!isnull(currentObject.width)) {
			resize_object(currentObject, currentObject, newWidth)
		}
	}
}


var fieldIDs = Array()
var fieldLabels = Array()
var fieldRequireds = Array()
var fieldValidations = Array()

function setup_contact_fields () {
	addField("contact_name", NAME_LABEL, true, "", 50)
	addField("contact_phone", PHONE_LABEL, true, "", 25)
	addField("contact_email", "Email", true, "email", 50)
	addField("contact_zipcode", "Zip", true, "empty_zipcode", 5)
	addField("contact_details", DETAILS_LABEL, true, "details", "")
}

loadAttacher(setup_contact_fields)

function validate_details (id) {
	return validate_textarea_max(id, DETAILS_PROMPT, 500)
}

function process_TOP_contact () {
	process_contact(
		"Name=" + getValue("contact_name")
		+ "&Phone=" + getValue("contact_phone")
		+ "&Email=" + getValue("contact_email")
		+ "&Zipcode=" + getValue("contact_zipcode")
		+ "&Details=" + getValue("contact_details")
	)
}

contact_wait = "contact_"
