// general

/**
 * On focus of a text field, clears the field of it's original (default)
 * value. Also clears an optional second field.
 * @param  element     The element that got the focus
 * @param  origvalue   The original value of the focussed element
 * @param  sec_element The other element that should be cleared of its value
 */
function focusInputFieldText(element, origvalue, sec_element){
	if (element.value == origvalue ) {
		element.value = '';
		if(sec_element) {
			sec_element.value = '';
		}
	}
}

/**
 * On blur (leaving) of a text field, puts back its original (default)
 * value, when no new value was entered
 * @param  element     The element that got the focus
 * @param  origvalue   The original value of the focussed element
 */
function blurInputFieldText(element, origvalue){
	if (element.value == '' ) {
		element.value = origvalue;
	}
}

/** search/filter page results pages 
 * TODO: should be put in a RaboEvent specific js file. ***/
var curPage = 1;
var totPages = 1;

function searchPrevPage(url) {
	curPage--;
	searchUpdate(url);
}
function searchNextPage(url) {
	curPage++;
	searchUpdate(url);
}
function searchUpdate (url) {
	document.location.replace(url);
}
/*** End rabo specific funcs ***/

/**
 * Asks the user if (s)he is sure about submitting a (admin) form.
 * If so, a hidden field is set to true, else false.
 * Actually the name is chosen wrong, it is only called for confirmation
 * on deleting something....
 * @param  msg   The message to show the user.
 */
function confirmSubmit(msg) {
	var agree = confirm(msg);
	
	if (agree) {
		document.getElementById('agree_delete').value = 'true' ;
		return true;
	} else {
		document.getElementById('agree_delete').value = 'false' ;
		return false;
	}
}
// Code for admin pages with Video4all link

/**
 * Opens an url in a dialog with set width and hight.
 * Uploads can be skinned in different sizes, but this will not
 * be updated accordingly.
 */
function uploadDialog(url, type) {
	
	if(!type || type == 'video') {
		width = 632;
		height = 492;
	} else {
		width = 745;
		height = 585;
	}
		
	window.open(url, 'upload','width='+width+',height='+height+',scrollbars=yes,resizable=no');
}

/**
 * Opens a dialog with given url, width and height and is resizable according
 * to res parameter.
 */
function openDialog(url, width, height, res, windowname) {
	if(!windowname)
		windowname = 'dialog';
	window.open(url, windowname, 'width='+width+',height='+height+',scrollbars=yes,resizable='+(res?"yes":"no"));
}

/**
 * Another short hand window.open function.
 * Opens a dialog with the given url and of a defined width and height.
 */
function vidPlay (url) {
	window.open(url, 'view','width=433,height=562,scrollbars=no,resizable=yes');
}

/**
 * Puts the id of the just uploaded video/visual into the hidden field,
 * Otherwise:
 * gives message/warning to user via alert
 * shows/hides showspan/hidespan with appropriate texts
 * @param  id          The id of the uploaded video/visual (pid that is)
 * @param  fieldid     ID of the hidden field to put the id in
 * @param  hidespan    ID of the span that should be hidden
 * @param  showspan    ID of the span that should be shown
 * @param  reaction    Is the upload a reaction?
 */
function ackUpload (id, fieldid, hidespan, showspan, reaction) {
	//Give thanks for reaction and don't do anything else
	if(reaction == 1) {
		alert("Bedankt voor het plaatsen van uw reactie.\n\nUw reactie wordt ter controle door gestuurd naar de eigenaar van de video. Wanneer deze uw reactie goedkeurt verschijnt de reactie online.");
		return;
	}
	
	document.getElementById(fieldid).value = id;

	$("#"+hidespan).toggle();
	$("#"+showspan).toggle();
	alert ("Er is een video geupload, om deze te koppelen aan dit item moet u eerst nog op de 'opslaan' knop hieronder klikken.");
}

/**
 * Opens an invisible window that lets the user download an upload
 * @param  tc  Theme code
 * @param  pid Encoded public id of the upload
 * @param  cos CodecServer ID
 */
function uplDownload (tc, pid, cos) {
	if (cos > 0)
		//In FF this works, in IE7 you have to disable the download blocker first, but users will get a warning..
		document.location = "index.php?downloadvisual=1&tc=" + tc + "&uID=" + pid + "&cos=" + cos;
}

/**
 * Puts google map coordinates in corresponding hidden fields so they
 * can be saved to a database.
 */
function putMapCoords (lat, lon, latid, lonid) {
	document.getElementById(latid).value = lat;
	document.getElementById(lonid).value = lon;
}

/**
 * Gives feedback in the form of an alert to the user after
 * (s)he has 'entered'/changed/removed the coordinates of an
 * item or video.
 * Calls putMapCoords to put the coordinates into hidden fields for saving.
 */
function ackMap (lat, lon, latid, lonid, showspan, remove) {
	if(lat == '' || lon == '')
		return false;

	putMapCoords (lat, lon, latid, lonid);
	if(document.getElementById(latid).value != '' && remove !== true) {
		alert ("De coordinaten zijn binnengehaald, om deze te koppelen aan dit item moet u eerst nog op de 'opslaan' knop hieronder klikken.");
		document.getElementById(showspan).innerHTML = "De coordinaten zijn binnengehaald, om deze te koppelen aan dit item moet u eerst nog op de 'opslaan' knop hieronder klikken.";
		$('#'+showspan).css('display','block'); //show the hidden span
	}
	if(remove === true) {
		alert ("De coordinaten zijn gewist, om deze wijziging door te voeren moet u eerst nog op de 'opslaan' knop hieronder klikken.");
		document.getElementById(showspan).innerHTML = "De coordinaten zijn gewist, om deze wijziging door te voeren moet u eerst nog op de 'opslaan' knop hieronder klikken.";
		$('#'+showspan).css('display','block'); //show the hidden span
	}
	
	return true;
}

/**
 * Calender initiallize function
 * formid       = id of the form
 * elementname  = name of the element to write chosen date to (target)
 * time_comp    = should the time component be shown? - optional
 * time_setting = default time to display - optional
 * year_scroll  = is it possible to scroll through the years? - optional
 * submit       = should the form of the target be submitted after setting the value? - optional
 */
function initializeCalendar(formid, elementname, time_comp, time_setting, year_scroll, submit) {
	
	if(formid  === undefined || elementname === undefined)
		alert('missing information for initialisation of calendar');

	/* Handle default values */
	if(time_setting === undefined)
		time_setting = '';
	if(year_scroll === undefined)
		year_scroll = true;
	if(time_comp === undefined)
		time_comp = true;
	if(submit === undefined)
		submit = false;

	var calobj = new calendar3(document.getElementById(formid).elements[elementname]);
	calobj.time_setting = time_setting;
	calobj.year_scroll = year_scroll;
	calobj.time_comp = time_comp;
	calobj.submit = submit;
	
	return calobj;
}
/**
 * From http://radio.javaranch.com/pascarello/2005/01/09/1105293729000.html
 * @param    element     The element to scroll to. Not the id, the actual element.
 */
function scrollToElement(element){
	var selectedPosX = 0;
	var selectedPosY = 0;

	while(element != null){
		selectedPosX += element.offsetLeft;
		selectedPosY += element.offsetTop;
		element = element.offsetParent;
	  }

	 window.scrollTo(selectedPosX,selectedPosY);
}

/********************************* player functions ***********************************************/



/**
 * Speaks to the player to pass a new playlist url
 * @param  type      type of the object to make a playlist for
 * @param  id        id of the object to make a playlist for
 * @param  siteurl   full url with host to base of the current site
 * @param  playerid  id of the player. There could be more than 1 on a page
 */
function playItemInPlayer(type, id, siteurl, playerid){
	if(playerid === undefined)
		playerid = "FlashPlayer";
		
	/* Get the flashplayer object.*/
	lst = new Array();
	var flobj = document.getElementById(playerid);        

	if (flobj && typeof flobj.sendEvent !== undefined) {
		//send new playlist
		flobj.sendEvent('LOAD', lst[0] = {file:siteurl+'&playerxml=1&type='+type+'&id='+id});
		//set the player to play after 2 seconds. 2 secons to load the new playlist.
		setTimeout(function(){flobj.sendEvent("PLAY", 'true');}, 2000);
	}
	else
		alert('Er is iets mis gegaan bij het laden van de videospeler. Herlaad de pagina en probeer het opnieuw.');
	//scroll to the player
	scrollToElement(flobj);
}

/**
 * Sets the title of the currently playing video into the title div
 * @param  title  The new title to display
 */
function updateVisualTitle(title) {
	/* TODO: id van de flashplayer waarbij dit moet meegeven aan de functie, voor het geval
	   er meerdere players op 1 pagina zijn.*/
	$("#PlayerTitle").text(title);
}

/**
 * Sets the html from a hidden source div (source) to a hidden destination
 * div under the player and afterwards makes the destination visible.
 * @param   sourceid       ID attribute of the div that keeps the html
 * @param   destinationid  ID attribute of the div the html should
 *                         be put into.
 */
function transferHtmlContent(sourceid, destinationid) {
	//Get reactions html
	reactions = $('#'+sourceid).html();
	//Set into destination div
	$('#'+destinationid).html(reactions);
	//Make destination div visible
	$('#'+destinationid).show();
}

/**
 * Asks the player which playlist it is playing at the moment
 * @return  the url to the playlist
 */
function getPlaylistUrl() {
	/* Get the flashplayer object.
	 * TODO: flahsplayer id meegeven aan deze functie voor het geval er meer players op 1 pagina zijn */
	var player = document.getElementById("FlashPlayer");        
	var playlist = player.getConfig().file;
	alert(playlist);
}

/**
 * Calls phpMyVisites (statistics) pmv_click function that records a 'click' or view on calling.
 * @param  visualtitle      title of the visual that triggers this record, example the name of the viewed video
 * @param  visualtype       type of the visual that triggers this record, example 'video' or 'picture'
 * @param  visualmediumid   mediumid of the visual
 */
function visualViewed(visualtitle, visualtype, visualmediumid) {
	switch(visualtype)
	{
	case 'video':
		statsname = 'Video/' + visualtitle;
		statstype = 'VIDEO';
		break;    
	case 'image':
		if(visualtitle)
			statsname = 'Picture/' + visualtitle;
		else
			statsname = 'Picture/' + visualmediumid;
		statstype = 'PICTURE';
		break;
	case 'videomix':
		statsname = 'Videomix/' + visualtitle;
		statstype = 'VIDEOMIX';
		break;
	default:
		statsname = 'File/' + visualtitle;
		statstype = 'FILE';
		break;
	}

	if(typeof pmv_click == 'function') {
		pmv_click (phpmyvisitesURL, phpmyvisitesSite, document.location.href.substr(document.location.href.indexOf('//')), statsname, statstype);
	}
}
