var BAD_EMAIL =					"אנא הזינו כתובת מייל תקינה."
var REQUIREDFIELD =				"שדה חובה"
var NAME_LABEL =				"שם"
var PHONE_LABEL =				"טלפון"
var DETAILS_LABEL =				"פרטים"
var MUST_NOT_EXCEED =			"לא יכול לעלות על"
var CHARACTERS =				"תווים"
var YOU_HAVE_ENTERED =			"הזנת"
var BAD_ZIPCODE_US =			"אנא הזינו מיקוד של חמש ספרות"
var NO_LINKS =					"אנא לא להכניס לינקים"
var THANK_YOU_FOR_CONTACTING =	"תודה שיצרתם קשר עם"
var PROBLEM =					"הייתה תקלה בשליחת הטופס.\nאנא וודאו שאין לינקים בתוכן שהזנתם"
var 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.1jr.co.il/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.1jr.co.il/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.1jr.co.il/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 = "One Jerusalem Hebrew".replace(/\(.*\)$/, "")
			alert(THANK_YOU_FOR_CONTACTING + " " + blogName + ", One Jerusalem Hebrew.")
			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)
		}
	}
}


//	FOR TELL A FRIEND

function recommend () {
	xmlHttp = GetXmlHttpObject()
	if (xmlHttp == null) {
		alert("Your browser does not support AJAX!")
		return
	}
	var url = "http://www.1jr.co.il/mail.php"
	xmlHttp.onreadystatechange = friend_stateChanged
	xmlHttp.open("POST" , url , true)
	xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded;charset=UTF-8;')
	xmlHttp.send(
		"your_email=" + document.getElementById("your_email").value +
		"&friend_email=" + document.getElementById("friend_email").value +
		"&url=" + window.location.href +
		"&title=" + document.title
	)
}

function friend_stateChanged () { 
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseText == "OK")
			alert("תודה על עזרתך לפרסום המסר")
		else
			alert(xmlHttp.responseText)
		didSave = true
	}
}

function checkFriendFields () {
	if (validate_emailList("friend_email") != "") {
		alert('בכתובת הדוא"ל של חברך נפלה טעות. אנא תקן את הטעון תיקון.')
		document.getElementById("friend_email").focus()
		return false
	}
	if (validate_email("your_email") != "") {
		alert('בכתובת הדוא"ל שלך נפלה טעות. אנא תקן את הטעון תיקון.')
		document.getElementById("your_email").focus()
		return false
	}
	return true
}

//	FOR SIGN PETITION

function OJH_subscribe () {
	suffix = OJH_subscribe.arguments.length == 1 ? "_inner" : ""
	subscribe(
		"email=" + document.getElementById("petition_email" + suffix).value
		+ "&name=" + document.getElementById("petition_name" + suffix).value.replace(/ /g, "%20")
		+ "&country=" + document.getElementById("petition_country" + suffix).value
		+ "&sendUpdateValue=" + document.getElementById("sendUpdate" + suffix + "Value").value
		+ "&sendJerusalemValue=" + document.getElementById("sendJerusalem" + suffix + "Value").value
		+ "&sendTempleValue=" + document.getElementById("sendTemple" + suffix + "Value").value
		+ ((isObject("referrer") && !empty(getValue("referrer"))) ? ("&referrer=" + escape(document.getElementById("referrer").value)) : "")
	)
}

function checkPetitionFields () {
	suffix = checkPetitionFields.arguments.length == 1 ? "_inner" : ""
	if (getValue("petition_name" + suffix) == "שם" || getValue("petition_name" + suffix).search(/^\s*$/) != -1) {
		alert('אנא הקלד את שמך.')
		document.getElementById("petition_name" + suffix).focus()
		return false
	}
	if (validate_email("petition_email" + suffix) != "") {
		alert('בכתובת הדוא"ל שלך נפלה טעות. אנא תקן את הטעון תיקון.')
		document.getElementById("petition_email" + suffix).focus()
		return false
	}
	if (getValue("sendUpdate" +  suffix + "Value") == "no" && getValue("sendJerusalem" +  suffix + "Value") == "no" && getValue("sendTemple" +  suffix + "Value") == "no") {
		alert('אנא סמנו לפחות אחת מהאופציות.')
		return false
	}
	document.getElementById("submitContainer" + suffix).innerHTML = "אנא המתן..."
	return true
}

function updateCheckboxHidden (myObject, myID) {
	document.getElementById(myID + "Value").value = myObject.checked ? "yes" : "no"
}
