/**
 * JavaScript useful functions
 */

var regExpBeginning = /^\s+/;
var regExpEnd = /\s+$/;

/**
 * Executes a command when the user presses enter
 * 
 * @param string type Type of action (form submission, function call, redirection)
 * @param string action Action to perform
 * @param ev Event
 * @deprecated
 */
function chkEnter(type, action, ev) {
	 if (window.event) {
		// IE
		e = window.event;
		var code = e.keyCode;
	} else {
		// Others
		var code = ev.keyCode;
	}

	if (code == 13) {
		if (type == 'form') {
			eval('document.' + action).submit();
		} else if (type == 'function') {
			eval(action);
		} else if (type == 'url') {
			document.location = action;
		}
	}
}

function disableEnterKey(e){
	var key;	 
	
	if (window.event) {
		key = window.event.keyCode; // IE
	} else {
		key = e.which; // firefox
	}	 
	
	return (key != 13);
}

/**
 * Delete spaces on the left and on the right of the string
 * 
 * @param string
 *            str String
 * @return string
 */
function trim(str) {
	return str.replace(regExpBeginning, "").replace(regExpEnd, "");
}

/**
 * Delete spaces on the leftt of the string
 * 
 * @param string
 *            str String
 * @return string
 */
function ltrim(str) {
	return str.replace(regExpBeginning, "");
}

/**
 * Delete spaces on the right of the string
 * 
 * @param string
 *            str String
 * @return string
 */
function rtrim(str) {
	return str.replace(regExpEnd, "");
}

function initRollover() {
	elements = document.getElementsByTagAndClassName('IMG', 'rollover');

	for (i = 0; i < elements.length; i++) {
		addEvent(elements[i], "mouseover", imageIdleToOver);
		addEvent(elements[i], "mouseout", imageOverToIdle);
		if (elements[i].parentNode && elements[i].parentNode.tagName == 'A') {
			addEvent(elements[i].parentNode, "focus", removeFocus);
		}
	}

	elements = document.getElementsByTagAndClassName('INPUT', 'rollover');

	for (i = 0; i < elements.length; i++) {
		addEvent(elements[i], "mouseover", imageIdleToOver);
		addEvent(elements[i], "mouseout", imageOverToIdle);
		if (elements[i].parentNode && elements[i].parentNode.tagName == 'A') {
			addEvent(elements[i].parentNode, "focus", removeFocus);
		}
	}
}

/**
 * Get all links with class 'rollout' and initialize the rollout on it
 * 
 * @return void
 */
// To deal with PDV's comments
var rolloutCase = 'regular';
 
function initRollout() {
	elements = document.getElementsByTagAndClassName('A', 'rollout');

	for (i = 0; i < elements.length; i++) {
		var tmp = elements[i].rel.split('_');
		
		if(rolloutCase == 'comment'){
			var filterComments = true;
		}else{
			var filterComments = false;
		}
		
		if(filterComments == false || (filterComments == true && tmp[1] == 'comment')){
			addEvent(elements[i], "click", captureRolloutLink);
		}
	}
}

/**
 * "ajaxify" a link: the URL will be loaded with AJAX
 * 
 * @return void
 */
function ajaxifyLinks() {
	elements = document.getElementsByTagAndClassName('A', 'ajaxify');

	for (i = 0; i < elements.length; i++) {
		
		elements[i].onclick = captureAjaxifiedLink;
	}
}


function makeDownloadLinksResetFlash ()
{
	elements = document.getElementsByTagAndClassName('A', 'download-link');

	for (i = 0; i < elements.length; i++) {
		
		elements[i].onclick = resetFlashPlayerIfSafari;
	}
}

function resetFlashPlayerIfSafari ()
{
	if (navigator.userAgent.toLowerCase().indexOf("safari") > -1)
	{
		var players = document.getElementsByName('flash_element');
		
		for (var player in players)
		{
			if (typeof(players[player].resetFlashPlayer) != 'undefined')
			{
				players[player].resetFlashPlayer();
			}
		}
	}
}

/**
 * "ajaxifyVideotheque" a link: the URL will be loaded with AJAX
 * 
 * @return void
 */
function ajaxifyVideothequeLinks() {
	elements = document.getElementsByTagAndClassName('A', 'ajaxifyVideotheque');

	for (i = 0; i < elements.length; i++) {
		
		elements[i].onclick = captureAjaxifiedVideothequeLink;
	}
}

/**
 * "ajaxifyLinksAbortOld" a link: the URL will be loaded with AJAX and abort old
 * connections
 * 
 * @return void
 */
function ajaxifyLinksAbortOld() {
	elements = document.getElementsByTagAndClassName('A', 'ajaxifyLibrary');

	for (i = 0; i < elements.length; i++) {
		
		elements[i].onclick = captureAjaxifiedLinkAbortOldLibrary;
	}
}

/**
 * Catches the browser's events
 * 
 * @return DOM Element
 */
function getSourceFromEvent(e) {
	if (e && e.target) {
		// Not IE
		return e.target;
	} else {
		// IE
		return window.event.srcElement;
	}
}

function removeFocus(e) {
	el = getSourceFromEvent(e);
	if (el.blur) {
		el.blur();
	}
}

function imageIdleToOver(e) {
	el = getSourceFromEvent(e);

	if (el && (el.tagName == "IMG" || el.tagName == "INPUT")
		&& el.src.indexOf('-idle') != -1) {
		el.src = el.src.replace('-idle', '-over');
	}

}

function imageOverToIdle(e) {
	el = getSourceFromEvent(e);

	if (el && (el.tagName == "IMG" || el.tagName == "INPUT")
		&& el.src.indexOf('-over') != -1) {
		el.src = el.src.replace('-over', '-idle');
	}
}

function captureAjaxifiedLink(e) {
	el = getSourceFromEvent(e);
	target = 'default_ajax_container';
	url = '';

	if (el && el.tagName == 'IMG') {
		el = el.parentNode;
	}

	if (el && el.tagName == "A") {
		url = el.href;
		if (el.rel) {
			target = el.rel;
		}
	}

	if (url.indexOf('?') != -1) {
		url += '&ajax=1';
	} else {
		url += '?ajax=1';
	}

	AjaxGetData(url, receive_ajax, $(target));

	return false;
}

/**
 * Special ajax to use in the videotheque, this will ensure that if a members
 * session expires while they are on the videotheque the code will not try to
 * load the disclaimer in place of the list of videos.
 */
function captureAjaxifiedVideothequeLink(e) {
	el = getSourceFromEvent(e);
	target = 'default_ajax_container';
	url = '';

	if (el && el.tagName == 'IMG') {
		el = el.parentNode;
	}

	if (el && el.tagName == "A") {
		url = el.href;
		if (el.rel) {
			target = el.rel;
		}
	}

	if (url.indexOf('?') != -1) {
		url += '&ajax=1';
	} else {
		url += '?ajax=1';
	}

	AjaxGetData(url, callbackLibrary, $(target));

	return false;
}

function captureAjaxifiedLinkAbortOldLibrary(e) {
	el = getSourceFromEvent(e);
	target = 'default_ajax_container';
	url = '';

	if (el && el.tagName == 'IMG') {
		el = el.parentNode;
	}

	if (el && el.tagName == "A") {
		url = el.href;
		if (el.rel) {
			target = el.rel;
		}
	}

	if (url.indexOf('?') != -1) {
		url += '&ajax=1';
	} else {
		url += '?ajax=1';
	}
	
	killAllInstancesOfFlashPlayer ();
	AjaxGetDataAbortOld(url, callbackLibrary, $(target));
	
	return false;
}

function killAllInstancesOfFlashPlayer ()
{
	var players = document.getElementsByName('flash_element');
	
	for (var player in players)
	{
		if (typeof(players[player].killFlashPlayer) != 'undefined')
		{
			players[player].killFlashPlayer();
		}
	}
}

function captureRolloutLink(e) {
	el = getSourceFromEvent(e);
	target = 'rollout_container';

	if (el && el.tagName == "A") {
		if (el.rel) {
			target = el.rel;
		}
	
		jQuery($(target)).slideToggle( "normal");
	}
	
	return false;
}

function submitFormAJAX(elt, target) {
	
	if (elt && elt.tagName == "FORM") {
		
		url = elt.action;

		if (url.indexOf('?') != -1) {
			url += '&ajax=1';
		} else {
			url += '?ajax=1';
		}
		
		parameters = getFormData();
		
		AjaxPostData(url, parameters, callbackLibrary, $(target));

		return false;
	} else {
		
		return true;
	}
}

/**
 * ajoute un événement sans écraser l'existant.
 */
function addEvent(obj, evType, fn, capt) {
	 
	 if (!obj) {
		return false;
	}

	if (obj.addEventListener) { // NS6+
		obj.addEventListener(evType, fn, capt);
	} else {
		if (obj.attachEvent) {
			obj.attachEvent("on" + evType, fn) // IE 5+
		} else {
			return false;
		}
	}
}

function cleanInput(element, defaultValue) {
	if (element.value == defaultValue){
		element.value = '';
	}
}

function restoreInput(element, defaultValue) {
	if (element.value == '')
	element.value = defaultValue;
}

function cleanTextarea(element, defaultValue) {
	if (element.innerHTML == defaultValue){
		element.innerHTML = '';
		element.value = '';
	}
}

function restoreTextarea(element, defaultValue) {
	if(element.value != ''){
		element.innerHTML = element.value;
	}

	if (element.value == '' || (element.innerHTML == '' && 0 > navigator.appVersion.indexOf("WebKit"))){
		element.innerHTML = defaultValue;
		element.value = defaultValue;
	}
}

/**
 * Restores the value of an element to defaultValue if the user didn't type
 * anything, and makes sure the type is text.
 * 
 * @param element An element on an HTML page
 * @param defaultValue the default value to maintain
 * @return none
 */
function restorePasswordInput(element, defaultValue, tplCase) {
	if (element.value == '') {
		if(tplCase == 'old'){
			document.getElementById('pEncryptedPassword').style.display = 'none';
			document.getElementById('pDecryptedPassword').style.display = 'block';
		}else if(tplCase == 'new'){
			document.getElementById('pEncryptedNewPassword').style.display = 'none';
			document.getElementById('pDecryptedNewPassword').style.display = 'block';
		}else if(tplCase == 'newConf'){
			document.getElementById('pEncryptedConfNewPassword').style.display = 'none';
			document.getElementById('pDecryptedConfNewPassword').style.display = 'block';
		}else if(tplCase == 'tempAccount'){
			document.getElementById('pEncryptedTempNewPassword').style.display = 'none';
			document.getElementById('pDecryptedTempNewPassword').style.display = 'block';
		}else if(TplCase == 'tempAccountConf'){
			document.getElementById('pEncryptedConfTempNewPassword').style.display = 'none';
			document.getElementById('pDecryptedConfTempNewPassword').style.display = 'block';
		}
	}
}
/**
 * When a user enters text into a password input, it will change the element
 * type to password and remove the default value from it.
 * 
 * @param element
 *            An element on an HTML page
 * @param defaultValue
 *            the default value to check for
 * @return none
 */
function cleanPasswordInput(element, defaultValue, tplCase) {
	
	if (element.value == defaultValue) {
		
		if (tplCase == 'old') {
			document.getElementById('pDecryptedPassword').style.display = 'none';
			document.getElementById('pEncryptedPassword').style.display = 'block';
			document.getElementById('encPass').focus();
			
		} else if(tplCase == 'new') {
			document.getElementById('pDecryptedNewPassword').style.display = 'none';
			document.getElementById('pEncryptedNewPassword').style.display = 'block';
			document.getElementById('encNewPass').focus();
			
		} else if(tplCase == 'newConf') {
			document.getElementById('pDecryptedConfNewPassword').style.display = 'none';
			document.getElementById('pEncryptedConfNewPassword').style.display = 'block';
			document.getElementById('encConfNewPass').focus();
			
		} else if(tplCase == 'tempAccount') {
			document.getElementById('pDecryptedTempNewPassword').style.display = 'none';
			document.getElementById('pEncryptedTempNewPassword').style.display = 'block';
			document.getElementById('encTempNewPass').focus();
			
		} else if(tplCase == 'tempAccountConf') {
			document.getElementById('pDecryptedConfTempNewPassword').style.display = 'none';
			document.getElementById('pEncryptedConfTempNewPassword').style.display = 'block';
			document.getElementById('encConfTempNewPass').focus();
		}
	}
}

/**
 * Open the selected item and close the previous one
 * 
 * @param id
 *            int FAQ item's ID
 */
function switchFAQQuestion(id){
	var selectedItem = document.getElementById('selectedItem').value;
	var oldClassName = document.getElementById('li_question_' + id).className;
	
	if(selectedItem != id){
		// Close the open one (if exists)
		if(selectedItem > 0){
				var elt = document.getElementById("rollout_container_" + selectedItem);
				
				// Triggers the jQuery behaviouh to fold the opened topic
				jQuery(elt).slideToggle( "normal");
				
			document.getElementById('li_question_' + selectedItem).className = '';
			var lis = document.getElementsByTagAndClassName('*', 'additional-faq');
		}
		
		// Switch style
		document.getElementById('li_question_' + id).className = 'selected';
		document.getElementById('selectedItem').value = id;
	}else{
		document.getElementById('li_question_' + id).className = '';
		document.getElementById('selectedItem').value = 0;
	}
}

function checkEmail(email){
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if (!filter.test(email)) {
		return false;
	}else{
		return(true);
	}
}

function getFormData() {
	data = "" ;
	
	// get data from inputs elements (text fields, hidden fields, checkboxes,
	// radio buttons, ...)
	inputs = document.getElementsByTagName("INPUT") ;
	for (i=0; i<inputs.length; i++) {
		child = inputs[i] ;
		
		if (child.type == "checkbox") {
			
			if (child.checked) {
				
				data += child.name + "=" + encodeURI(child.value) + "&";
			} else {
				
				data += child.name + "=&";
			}
		}
		else if (child.type == "radio") {
			
			if (child.checked) {
				
				data += child.name + "=" + encodeURI(child.value) + "&";
			} 
		} else { // text fields, hidden fields, ...

			data += child.name + "=" + encodeURI(child.value) + "&";
		}
	}
	
	// get data from textareas
	textareas = document.getElementsByTagName("TEXTAREA") ;
	for (i=0; i<textareas.length; i++) {
		
		child = textareas[i] ;
		data += child.name + "=" + encodeURI(child.value) + "&";
	}
	
	// get data from drop-down lists
	selects = document.getElementsByTagName("SELECT") ;
	for (i=0; i<selects.length; i++) {
		
		child = selects[i] ;
		data += child.name + "=" + encodeURI(child.options[child.selectedIndex].value) + "&";
	}
	
	return data ;
	
}

function verifyAge() {
	// if it's there is a date check if it's > 18 year
	var maxdate = new Date; 
	maxdate.setYear(maxdate.getYear() -18);
	
	// Set allowed to true by default and only modify this if we
	// are a yahoo disclaimer that fails.
	var isAllowed = true;
	var myDate = new Date;
	
	if(document.getElementById('is_yahoo').value == 'yahoo') {
		// Reset the link so we remain on the correct disclaimer page in case of
		// error.
		document.getElementById('enter_link').href='?from_yahoo=yahoo';
		
		// Verify we have the needed date components.
		var date_e = document.getElementById('day');
		var month_e = document.getElementById('month');
		var year_e = document.getElementById('year');
	
		if(date_e.selectedIndex != 0 && month_e.selectedIndex != 0 && year_e.selectedIndex != 0) {
			myDate.setDate(date_e.options[date_e.selectedIndex].value );
			myDate.setMonth(month_e.options[month_e.selectedIndex].value - 1); // January
																				// = 0
			myDate.setFullYear(year_e.options[year_e.selectedIndex].value);
			
			if (maxdate <= myDate)
				isAllowed = false;
		} else {
			isAllowed = false;
		}
	}
	
	return isAllowed;
}

function disclaimerAlert() {
	if(verifyAge() == false) {
		alert(_('disclaimer_verify_age'));
		
		return false;
	} else {
		// Reset the link to enter the site if all conditions are met.
		document.getElementById('enter_link').href = document.getElementById('enter_disclaimer').value;
	
		return true;
	}
}

function initOpenLinksNewWindows() {

	elements = document.getElementsByTagAndClassName('A', 'new_window');

	for (i = 0; i < elements.length; i++) {
		
		elements[i].onclick = captureOpenLinkNewWindow;
	}
}

function captureOpenLinkNewWindow (e) {
	el = getSourceFromEvent(e);
	
	// we need to check if the event came from an IMG tag. If so, we need to get
	// the parent A tag
	if (el && el.tagName == "IMG")
	{
		el = el.parentNode;
	}

	// since the links can come from text or an image, we need to check for
	// either tag name
	if (el && el.tagName == "A" && el.href) {
		
		url = el.href;
		
		// Hides everything except the URL
		window.open(url, '', 'directories=no,menubar=no,toolbar=no,scrollbars=yes,resizable=yes');

		return false;
	}
}

function openInParentAndCloseLighbox(link, parent) {
	
	url = link.href;
	
	if (url.indexOf('://') < 0) {
		
		url = siteBaseUrl + url;
	}

	parent.tb_remove();
	parent.location.href = url;
}

function closeLightboxAndReloadPage(parent) {
	
	parent.tb_remove();
	parent.location.reload(true);
}

/**
 * If the proper condition exist, function loops through all the video
 * templates, and compare the heights of the video on the left, to the video on
 * right for each row display. Resizes the smaller to match the bigger.
 */
function resizeVideoTemplates()
{ 
	if (typeof resetDescriptionHeight != 'undefined' && 1 == resetDescriptionHeight)
	{
		// loop through all the videos on the page
		for (var i = 1; i<= numTotalVideos; i++)
		{
			// declate a left index
			var left_ind = i;
			// increase the counter
			i++;
			// declare a right index
			var right_ind = i;
			
			
			// Perform the checks for descriptions
			var desc_left = document.getElementById("desc_p"+left_ind);	// the
																		// video
																		// template
																		// on
																		// the
																		// left
			var desc_right = document.getElementById("desc_p"+right_ind);  // the
																			// video
																			// template
																			// on
																			// the
																			// right

			// check if both exist - ie, not just one video on the last row
			if (desc_left && desc_right)
			{
				// compare their height, and set the lower height to the higher
				// one
				if (desc_left.offsetHeight > desc_right.offsetHeight)
				{
					desc_right.style.height = desc_left.offsetHeight+"px";
				}
				else
				{
					desc_left.style.height = desc_right.offsetHeight+"px";					
				}// end height check
			}// end element check
			
			// perform the checks for the casting section
			var cast_left = document.getElementById("casting_p"+left_ind);	// the
																			// video
																			// template
																			// on
																			// the
																			// left
			var cast_right = document.getElementById("casting_p"+right_ind);  // the
																				// video
																				// template
																				// on
																				// the
																				// right

			// check if both exist - ie, not just one video on the last row
			if (cast_left && cast_right)
			{
				// compare their height, and set the lower height to the higher
				// one
				if (cast_left.offsetHeight > cast_right.offsetHeight)
				{
					cast_right.style.height = cast_left.offsetHeight+"px";
				}
				else
				{
					cast_left.style.height = cast_right.offsetHeight+"px";
				}// end height check
			}// end element check
			
			// perform the checks for the titles using h2 (star videos)
			//the video template on the left
			var title_left = document.getElementById("title_h2"+left_ind);
			//the video template on the right
			var title_right = document.getElementById("title_h2"+right_ind);

			// check if both exist - ie, not just one video on the last row
			if (title_left && title_right)
			{
				// compare their height, and set the lower height to the higher
				// one
				if (title_left.offsetHeight > title_right.offsetHeight)
				{
					title_right.style.height = (title_left.offsetHeight - 10)+"px";
				}
				else
				{
					title_left.style.height = (title_right.offsetHeight - 10) +"px" ;
				}// end height check
			}// end element check
			
			// perform the checks for the titles using h3 (MB)
			//the video template on the left
			var title_mb_left = document.getElementById("title_h3"+left_ind);
			//the video template on the right
			var title_mb_right = document.getElementById("title_h3"+right_ind);

			// check if both exist - ie, not just one video on the last row
			if (title_mb_left && title_mb_right)
			{
				// compare their height, and set the lower height to the higher
				// one
				if (title_mb_left.offsetHeight > title_mb_right.offsetHeight)
				{
					title_mb_right.style.height = (title_mb_left.offsetHeight - 6)+"px";
				}
				else if (title_mb_left.offsetHeight < title_mb_right.offsetHeight)
				{
					title_mb_left.style.height = (title_mb_right.offsetHeight - 6)+"px";
				}// end height check
			}// end element check
		}// end for
	}
}

// change the category based on a select box change
// the value of the option should be the relative path
// to redirect to. Will not redirect to an absolute url.
function select_redirect(sel_el) {
	var stars_text = _('our_actrice_upper');
	
	// get the url
	var url = sel_el.options[sel_el.selectedIndex].value;
	
	// if the url doesn't start with http:// we need to add a / so that it
	// direct properly
	if ("http://" != url.substring(0,7))
	{
		url = "/" + url;
	}
	
	// determine if we open a new window or stay in the same one
	if(sel_el.options[sel_el.selectedIndex].text == stars_text) {
		window.open(url);
	} else if(sel_el.options[sel_el.selectedIndex].value != 0) {
		document.location = url;
	} else {
		return;
	}
}

function openLightboxOnLoad() {
	
	if (typeof lightbox_to_open != 'undefined' && '' != lightbox_to_open) {
		
		tb_show('Lightbox', lightbox_to_open);
	}
}

/**
 * this function will close a lightbox when clicking outside
 */
function closeLightboxWithoutReload(){
	parent.tb_remove();
}

/**
 * will show div to send a new message in support page
 */ 
function showAddMessage(){
	document.getElementById('ajoutMessage').style.display = 'inline';
}

function switchOnFocus(defValue)
{
	fakepswd = document.getElementById('fakepswd');
	pswd = document.getElementById('pass');
	
	fakepswd.style.display = 'none';
	pswd.style.display = '';
	pswd.focus();
}

function switchOnBlur(defValue)
{
	fakepswd = document.getElementById('fakepswd');
	pswd = document.getElementById('pass');
	
	if ('' == pswd.value)
	{
		fakepswd.style.display = '';
		pswd.style.display = 'none';
	}
}

function openSupportFromPopup(){
	window.opener.location = siteBaseUrl + 'messager/new_thread?case=support';
	window.close();
}

/**
 * This function will open a new full screen popup, for the url that was given
 * to it.
 */
function fullscreenNewWindow(url) {
	// Options to make it full screen
	 params  = 'width='+screen.width;
	 params += ', height='+screen.height;
	 params += ', top=0, left=0';
	 
	 // Other options to maintain look and feel.
	 params += ', location=yes';	// specifies the presence of the location bar
	 params += ', resizable=yes';	// specifies whether the window can be resized
	 params += ', menubar=yes';		// specifies the presence of the menu bar
	 params += ', toolbar=yes';		// specifies the presence of the toolbar
	 params += ', scrollbars=yes';	// specifies the presence of a scrollbar
	 params += ', status=yes';		// specifies the presence of the statusbar

	 newwin=window.open(url,'', params);
	 if (window.focus) {
		 newwin.focus()
	 }
	 return false;
}


/************************************************************
 * initialisation                                           *
 *                                                          *
 *   !!!! THIS HAS TO BE AT THE VERY END OF THE FILE !!!!   *
 *                                                          *
 * DO NOT CREATE FUNCTIONS AFTER THIS !!!!                  *
 ************************************************************/

if (typeof is_lightbox != 'undefined' && is_lightbox) {

	// add event to close the lightbox when we click outside the iFrame
	addEvent(self.parent.document.getElementById('TB_overlay'), "click", closeLightboxWithoutReload);
} else {
	
	addEvent(window, "load", initRollover);
	addEvent(window, "load", ajaxifyLinks);
	addEvent(window, "load", ajaxifyLinksAbortOld);
	addEvent(window, "load", initRollout);
	addEvent(window, "load", resizeVideoTemplates);
	addEvent(window, "load", initOpenLinksNewWindows);
	addEvent(window, "load", openLightboxOnLoad);
	addEvent(window, "load", makeDownloadLinksResetFlash);
	addEvent(window, "unload", killAllInstancesOfFlashPlayer);
}
// NO CODE SHOULD GO AFTER THIS LINE


