/**
 * Tripi Javascript helpers License
 * ---------------------------------------------------------------
 * the use of this code for commercial uses requires the written
 * authorization of the author.
 * non-commercial use of part or all of the code requires the inclusion
 * of this notice in the used source.
 *
 * enjoy. :-)
 * 
 * admin@tripi.co.il
 */

// convert all characters to lowercase to simplify testing
function flashActive() {
	theObjects = document.getElementsByTagName("object"); 
	for (var i = 0; i < theObjects.length; i++)
	theObjects[i].outerHTML = theObjects[i].outerHTML; 
}

function addError(context, message) {
	document.getElementById(context+"Errors").innerHTML += message + "<br>";
	document.location.hash = "#"+context+"ErrorsAnchor";
}

function setError(context, message) {
	$(context+"Errors").innerHTML = message + "<br/>";
//	document.location.hash = "#"+context+"ErrorsAnchor";
}

function clearErrors(context) {
	document.getElementById(context+"Errors").innerHTML = "";
}

/*
 * Enables/disables a document element
 * @param id the id of the element
 * @param endisable when this parameter is ommited the element visibility is negated
 */
function endisableElement(id, endisable, imageId) {
	var element = document.getElementById(id);
	if (element) {
		var visibility;
		if (endisable == true) 
			visibility = "block";
		else if (endisable == false)
			visibility = "none";
		else 
			visibility = (element.style.display == "block" ? "none" : "block");
			
		if (imageId)
			document.getElementById(imageId).src=(visibility=="block" ? "images/arrow_open.gif" : "images/arrow_close.gif");
		
		element.style.display = visibility;
	} else
		alert("Error: element with id '" + id + "' doesn't exist");
}

/*
 * Enables/disables a document element
 * @param id the id of the element
 * @param endisable when this parameter is ommited the element visibility is negated
 */
function endisableButton(id, buttonId) {
	var element = document.getElementById(id);
	if (element) {
		var visibility = (element.style.display == "block" ? "none" : "block");
			
		if (buttonId) {
			if (visibility=="block")
				$(buttonId).addClassName("activated");
			else
				$(buttonId).removeClassName("activated");
		}
		element.style.display = visibility;
	} else
		alert("Error: element with id '" + id + "' doesn't exist");
}

function setDescription(description) {
	document.getElementById("helpDescription").style.display = "block";
	document.getElementById("helpDescription").innerHTML = description;
}

function clearDescription() {
	document.getElementById("helpDescription").style.display = "none";
	document.getElementById("helpDescription").innerHTML = "";
}

var urlregexp;
function isUrlValid(fieldId) {
	if (urlregexp == null)
		urlregexp = new RegExp("^http://([\\w-]+\\.)+[\\w-]{2,5}(/[\\w- +./?#~%&=]*)?$", "");
	var	url = document.getElementById(fieldId).value;
	if (url.indexOf("http://") != 0)
		url = "http://"+url;	
	
	return urlregexp.test(url);
}

function renderLinkHtml(outputFieldId, descriptionFieldId, urlFieldId, mandatory) {
	// TODO: validate/escape the fields
	// TODO: trim both fields
	var description = document.getElementById(descriptionFieldId).value;
	var url = document.getElementById(urlFieldId).value;
	
	if (url=="") {
		// if url is not mandatory simply continue
		if (!mandatory)
			return true;

		setError("link", "חובה לציין כתובת אינטרנט");
		return false;
	}
	
	if (description == "")
	// TODO: shorten the url for view
		description = url;

	var view = "<a target=\"_blank\" href=\""+url+"\">"+description+"</a>";
	document.getElementById(outputFieldId).value = view;
	return true;
}
function renderPictureHtml(outputFieldId, url, id) {
	// TODO: validate/escape the fields
	// TODO: trim both fields
	
	var view = "<img src=\"" + url + "\"" + (id?" id=\"" + id +"\"":"") + ">";
	document.getElementById(outputFieldId).value = view;
	return true;
}


// renderContactHtml('contactView','phoneCountryCode','phoneAreaCode','phoneNumberCode','contactName','email')
function renderContactHtml(outputFieldId, countryCodeFieldId, areaCodeFieldId, numberFieldId, descriptionFieldId, emailFieldId) {
	// TODO: validate/escape the fields
	// TODO: trim all fields
	var countryCode = document.getElementById(countryCodeFieldId).value;
	var areaCode = document.getElementById(areaCodeFieldId).value;
	var number = document.getElementById(numberFieldId).value;
	var description = document.getElementById(descriptionFieldId).value;
	var email = document.getElementById(emailFieldId).value;

	var encodedPhone = countryCode+"-"+areaCode+"-"+number;

	var view = "";
	
	if (email != "")
		view += "<a href=\"mailto:"+email+"\">";

	if (description != "") {
		view += description
		if (number != "") {
			view += " ("+encodedPhone+")";
		} else {
			if (email == "") {
				setError("contact", "חובה לציין מספר טלפון או אימייל");
				return false;
			}
		}
	} else {
		if (email != "") {
			view += email;
			if (number != "") {
				view += " ("+encodedPhone+")";
			}
		} else {
			if (number != "") {
				view += encodedPhone;
			} else {
				setError("contact", "חובה לציין מספר טלפון או אימייל");
				return false;
			}
		}
	}

	if (email != "")
		view += "</a>";
	
	document.getElementById(outputFieldId).value = view;
	return true;
}

// renderRangeHtml('rangeView','startDate','endDate','repetition')
function renderRangeHtml(outputFieldId, startDateFieldId, endDateFieldId, repetitionFieldId) {
	var startDate = document.getElementById(startDateFieldId).value;
	var endDate = document.getElementById(endDateFieldId).value;
	var repetition = document.getElementById(repetitionFieldId).value;

	var view = "";
	view += startDate + "-" + endDate;
	if (repetition > 0) {
		view += " כל ";
		if (repetition == 10) {
			view += "שנה";
		} else if (repetition == 20) {
			view += "חודש";
		}
	}

	document.getElementById(outputFieldId).value = view;
	return true;
}

// find the absolute position of the element
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

// find the absolute position of the element
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/*
 * @param value
 * @param valuesArray a sorted array with the values
 * @param roundUp if true the index will be 1 in front, otherwise it will be 1 ahead
 * @return index of the nearest value in the array
 */
function findNearestValueIndex(value, valuesArray, roundUp) {
	if (value <= valuesArray[0])
		return 0;
	for (var i = 1; i<valuesArray.length-1; i++) {
		if (value==valuesArray[i])
			return i;
		if (value>valuesArray[i] && value<valuesArray[i+1]) {
			if (roundUp)
				return i+1;
			else
				return i-1;
		}
	}
	return valuesArray.length-1;
}

// disable enter key submittal in forms
var enterKeyPressed = false;
function filterEnterKey(e) {
	if (enterKeyPressed) {
		enterKeyPressed = false;
		return false;
	}
	var nav = window.event ? true : false;
	if (nav) {
		// Mozilla supports this elegent solution
		if (e && e.which == 13) {
			return false;
		}
	} else {
		// However internet explorer requires this two phase process because a
		// new event is genrated for the submit process instead of bubbling the original
		// event
		if (e && e.keyCode == 13) {
			enterKeyPressed = true;
			return false;
		}
	}
	return true;
}

//Goto add comment link
function addCommentLink() {
	document.getElementById("addComment").style.display="block";
	var nameField = document.getElementById("name");
	if (nameField)
		nameField.focus();
	else
		document.getElementById("subject").focus();		
	
	document.getElementById("addCommentLink").style.display="none";
	return false;
}

/* Maps */
function placeLabelOnElement(mapId, itemId) {
	var labelId = "locationLabel"+mapId+"_"+itemId;
	var label = document.getElementById(labelId);

	var alignLeftField = document.getElementById("alignLeft"+mapId);
	var alignLeft = (alignLeftField.value == "true");

	var xField = document.getElementById("mapX"+mapId);
	var yField = document.getElementById("mapY"+mapId);

	label.style.visibility = "visible";

	label.className = (alignLeft ? "leftAligned" : "");
	label.style.left = (xField.value-(alignLeft ? 100 :0)) + "px";
	label.style.top = (yField.value) + "px";
}

function highlightMapLocation(item,uid,show) {
	var mapLabelElement = document.getElementById("locationLabel"+item+"_"+uid);
	if (mapLabelElement)
		mapLabelElement.className = (show ? "highlight" : "")+(mapLabelElement.className.indexOf("leftAligned")>-1? " leftAligned" : "");
}

function pointSelect(mapId, itemId, event) {
	document.getElementById("showOnMap"+mapId).checked=true;

	var imageElement = document.getElementById("itemImage"+mapId);
	var xField = document.getElementById("mapX"+mapId);
	var yField = document.getElementById("mapY"+mapId);

	var absoluteX = findPosX(imageElement);
	var absoluteY = findPosY(imageElement);
	
	var relativeX, relativeY;

	if (window.event) {
		// ie
		// todo: compensate for ie's tendancy to include the border as part of the element
		relativeX = event.offsetX;
		relativeY = event.offsetY;
	} else {
		// mozilla
		relativeX = event.clientX - (absoluteX - document.documentElement.scrollLeft);
		relativeY = event.clientY - (absoluteY - document.documentElement.scrollTop);
	}
	
	xField.value = relativeX;
	yField.value = relativeY;
	
	var labelId = "locationLabel"+mapId+"_"+itemId;
	var label = document.getElementById(labelId);
	if (!label)
		label = document.getElementById(labelId+"_new");

	placeLabelOnElement(mapId,itemId);
}

function changeLabelAlignment(mapId, itemId) {
	var alignLeftField = document.getElementById("alignLeft"+mapId);
	var alignLeft = !(alignLeftField.value == "true");

	alignLeftField.value = (alignLeft ? "true" : "false");
	
	placeLabelOnElement(mapId,itemId);
}

function miniformOpen(formNameToOpen) {
	document.getElementById("miniformAdd"+formNameToOpen).style.display = 'block';
	document.getElementById(formNameToOpen + "_Link").style.display = 'none';
	return true;
}

function miniformClose(formNameToClose) {
	document.getElementById(formNameToClose + "_Link").style.display = 'block';
	document.getElementById("miniformAdd" + formNameToClose).style.display = 'none';
	return true;
}

function inputClear(input, defaultText, activate) {
	var searchField=$(input);
	if (activate) {
		if (searchField.getValue()==defaultText)
			searchField.value="";
		searchField.addClassName("active");
	} else {
		if (searchField.getValue()=="") {
			searchField.removeClassName("active");
			searchField.value=defaultText;
		}
	}
}

function searchButtonClick() {
	var searchField=$("searchField");
	if (searchField.getValue()=="חיפוש באתר" || searchField.value=="") {
		setError("search", "אנא הכנס מילות חיפוש");
		return false;
	}
	return true;
}

// Query String Parameters Cache (To Save CPU)
// Note: this function is case sensitive
var qsParams = new Array();
function getParameter(paramName) {
	var queryregexp = new RegExp("(\\\?|&)"+paramName+"=(.*?)(&|$)", "");
	var paramValue;
	if (paramValue = qsParams[paramName])
		return paramValue;
	// else get the value of the parameter from the query string and cache it
	
	var qs;
	qs = window.location.search;
	// if we are in a frame the parameters are taken from the top frame
	if (!qs)
		qs = top.window.location.search;
	// if no query string return null
	if (!qs)
		return null;
	var regexpResult = queryregexp.exec(qs);
	if (regexpResult)
		return qsParams[paramName] = regexpResult[2];
	else
		return null;
}

// This is a function for the hierarchy table drawing trigerred by onmouseover/out
// it hides all the tables and shows the onmouseover one if so.
function toggleMenu(currElem,nextPos) {
	stdBrowser=(document.getElementById)?true:false
	menuObj=(stdBrowser)?document.getElementById(currElem).style : eval("document." + currElem)
	if (toggleMenu.arguments.length == 1) {
 		nextPos = (parseInt(menuObj.visiblity)=='visible')?'hidden' : 'visible'
 	}
 	menuObj.visibility = nextPos;
 	menus = document.getElementsByTagName('span');
 	for (i=0;i<menus.length;i++) {
 		menu = menus[i];
 		if ((menu.id.indexOf('s_')==0) && (menu.id!=currElem)) {
 			menu.style.visibility = 'hidden';
		 }
	}
}

/* Multiple Pictures */

// Slideshows container
var slideshowArray = new Array();

/**
 * a Image Slideshow object
 */
function SlideShow(num, pictures, options) {
	this.num = num;
	this.pictures = pictures;
	this.pictureCount = this.pictures.length;
	this.currentPictureIndex = -1;
	this.currentlyPlaying = false;

	this.currentEntityId = options["objectName"];

	this.delay = options["delay"]; // Time in milliseconds 
	this.imagePrefix = options["imagePrefix"];
	this.startImage = options["selectedImage"];

	this.slideshowContainer = $("slideshowContainer"+num);
	this.imgTag = $("slideshowImage" + num);
	this.gotoNextPictureController = $("slideshowNextPicture"+num);
	this.gotoPreviousPictureController = $("slideshowPreviousPicture"+num);
	this.titleBlock = $("slideshowTitle"+num);
	this.pictureDateBlock = $("slideshowDate"+num);
	this.descriptionBlock = $("slideshowDescription"+num);
	this.counterBlock = $("slideshowCounter"+num);
	this.userLink = $("slideshowUser"+num);
	this.previousThumb = $("slideshowPreviousThumb"+num);
	this.currentThumb = $("slideshowCurrentThumb"+num);
	this.nextThumb = $("slideshowNextThumb"+num);
	
	this.zoom = function() {
		showLightbox(this.num);
	}.bindAsEventListener(this);
	
	this.zoomIndex = function(index) {
		this.currentPictureIndex = index;
		this.zoom();
	};
	
	this.gotoFirstPicture = function() {
		return this.gotoIndex(0);
	}

	this.gotoLastPicture = function() {
		this.gotoIndex(this.pictureCount - 1);
	}

	this.gotoNextPicture = function() {
		this.gotoIndex(this.currentPictureIndex + 1);
	}

	this.gotoPreviousPicture = function() {
		this.gotoIndex(this.currentPictureIndex-1);
	}
	
	this.approve = function(event) {
		window.open('ApproveImage.action?id='+ this.pictures[this.currentPictureIndex]["uid"],'imageUpload','left=20,top=20,width=580,height=150,toolbar=0,location=0,status=0,directories=0,menubar=0,scrollbars=0,resizable=0');
		Event.stop(event);
	}
	
	this.undelete = function(event) {
		window.location='UnDeleteImage.action?id='+ this.pictures[this.currentPictureIndex]["uid"];
		Event.stop(event);
	}
	
	this.remove = function(event) {
		window.location='DeleteImage.action?id='+ this.pictures[this.currentPictureIndex]["uid"];
		Event.stop(event);
	}

	this.play = function() {
		this.currentlyPlaying = true;
	}
	
	this.pause = function() {
		this.currentlyPlaying = false;
	}
	
	this.playPause = function() {
		if (this.currentlyPlaying)
			this.pause();
		else
			this.play();
	}
	
	this.gotoIndex = function(index) {
		if (this.pictureCount == 0 || this.currentlyPlayingIndex == index)
			return;
		else if (index > (this.pictureCount - 1))
			return this.gotoFirstPicture();
		else if (index < 0)
			return this.gotoLastPicture();
		
		this.currentPictureIndex = index;
		
		if (this.imgTag == undefined)
			return;
		
		var picture = this.pictures[index];

		// Image Container
		var zoomAvailable = picture["zoomAvailable"];
		
		this.imgTag.src = this.imagePrefix + picture["uid"] + (!this.fullSize || !zoomAvailable ? "_resized.jpg" : ".jpg");

		this.imgTag.parentNode.style.cursor = (zoomAvailable?"pointer":"auto");
		
		if (this.pictureDateBlock)
			if (picture["pictureDate"]) {
				this.pictureDateBlock.style.visibility="visible";
				var pictureDate = picture["pictureDate"];
				this.pictureDateBlock.innerHTML = pictureDate.getDate() + "/" + (pictureDate.getMonth()+1) + "/" + pictureDate.getFullYear();
			} else
				this.pictureDateBlock.style.display="hidden";

		if (this.titleBlock) 
			this.titleBlock.update(picture["title"]);
		

		if (picture["status"]==600)
			this.slideshowContainer.addClassName("deleted");
		else
			this.slideshowContainer.removeClassName("deleted");
		
		if (picture["status"]==0)
			this.slideshowContainer.addClassName("notapproved");
		else
			this.slideshowContainer.removeClassName("notapproved");
			
		if (zoomAvailable) {
			this.slideshowContainer.addClassName("zoomAvailable");
			Event.observe(this.imgTag.parentNode, "click", this.zoom);
		}
		else {
			this.slideshowContainer.removeClassName("zoomAvailable");
			Event.stopObserving(this.imgTag.parentNode, "click", this.zoom);
		}

		if (this.descriptionBlock)
			this.descriptionBlock.update(picture["description"]);

		if (this.counterBlock)
			this.counterBlock.update("" + (index-0+1) + "/" + this.pictureCount);
			
		if (this.userLink) {
			this.userLink.update(picture["user"]["displayName"]);
			this.userLink.href = "Show.action?user="+picture["user"]["uid"];
		}
		
		if (this.previousThumb) {
			var prevpicture;
			if (index > 0)
				prevpicture = this.pictures[index-1];
			if (prevpicture) {
				this.previousThumb.src = this.imagePrefix + prevpicture["uid"] + "_thumb.jpg";
				this.previousThumb.parentNode.style.visibility = "visible";
			} else
				this.previousThumb.parentNode.style.visibility = "hidden";
		}

		if (this.currentThumb) {
			if (picture) {
				this.currentThumb.src = this.imagePrefix + picture["uid"] + "_thumb.jpg";
				this.currentThumb.parentNode.style.visibility = "visible";
			} else
				this.currentThumb.parentNode.style.visibility = "hidden";
		}

		if (this.nextThumb) {
			var nextpicture;
			if (index < this.pictureCount)
				nextpicture = this.pictures[index+1];
			if (nextpicture) {
				this.nextThumb.src = this.imagePrefix + nextpicture["uid"] + "_thumb.jpg";
				this.nextThumb.parentNode.style.visibility = "visible";
			} else
				this.nextThumb.parentNode.style.visibility = "hidden";
		}
		
		if (this.currentEntityId != null) {
			var indexCookie = readCookie("lastImageIndex");
			if (!indexCookie)
				indexCookie = "";
			var indexArray = decodeArray(indexCookie);
			indexArray[this.currentEntityId]=index;
			writeCookie("lastImageIndex", encodeArray(indexArray), 1);
		}
	}
	// Init
	if (this.previousThumb)
		Event.observe(this.previousThumb.parentNode, "click", this.gotoPreviousPicture.bindAsEventListener(this));

	if (this.nextThumb)
		Event.observe(this.nextThumb.parentNode, "click", this.gotoNextPicture.bindAsEventListener(this));
	
	if (this.pictureCount > 0) {
		if (this.startImage) {
			this.gotoIndex(this.startImage - 0);
		} else {
			var indexCookie = readCookie("lastImageIndex");
			if (indexCookie) {
				var indexArray = decodeArray(indexCookie);
				if (indexArray[this.currentEntityId])  
					this.gotoIndex(indexArray[this.currentEntityId] - 0);
				else
					this.gotoFirstPicture();
			} else
				this.gotoFirstPicture();
		}
	} else
		this.gotoFirstPicture();
}

function writeCookie(name, value, days){
     if (days) {
     	(time = new Date()).setTime((new Date()).getTime()+days*24*60*60*1000);
     	var exp = '; expires='+time.toGMTString();
     } else {
     	var exp='';
     }
     document.cookie=name+"="+value+exp+"; path=/";
}

function readCookie(name) {
	var cookies = document.cookie.split(';');
	for(var i=0; i<cookies.length; i++) {
		var cookie=cookies[i].replace(/^\s+/, '');
		if (cookie.indexOf(name+'=')==0)
		return cookie.substring(name.length+1);
	}
	return null;
}
     
function eraseCookie(name) {
	writeCookie(name, "", -1);
}

// A more compact array.join function, saves both key and value in the encoded string
function encodeArray(array) {
	var tempArray = new Array();
	for (var key in array)
		if (typeof array[key] == "string" || typeof array[key] == "number")
			tempArray[tempArray.length] = key + ":" + array[key];
	return tempArray.join(",");
}

function decodeArray(string) {
	var tempArray = string.split(",");
	var decodedArray = $H();
	tempArray.each(function(value, index) {
		var t = value.split(":");
		decodedArray[t[0]]=t[1];
	});
	return decodedArray;
}