/*the baseURL*/
var uri = new Object();
getURL(uri);
var baseUrl='http://'+uri.dom+'/';

var calledPage = '';

/*to switch based on navigator*/
var nav=(navigator.appName).toLowerCase();

/**path of ticked and unticked boxes */
var untickedURL='css/defaultPlantyContentPics/boxUnticked.png';
var tickedURL='css/defaultPlantyContentPics/boxTicked.png';

/**
* Array of selected photos
**/
var arraySelectedPhotos=new Array();

var arrayHeaderMenuID=new Array('menu1','menu2','menu3','menu4','menu5','menu6','menu7');
function changeHeaderMenuclass(elementID) {
	var NAME;
	for (i=0;i<arrayHeaderMenuID.length;i++){
		NAME=document.getElementById(arrayHeaderMenuID[i]);
		NAME.className='headerMenu'+arrayHeaderMenuID[i].charAt(arrayHeaderMenuID[i].length-1);
	}
	var NAME = document.getElementById(elementID);
	if(NAME.className=='headerMenu1'){
		NAME.className='headerMenu1Active';
		return;
	}
	if(NAME.className=='headerMenu2'){
		NAME.className='headerMenu2Active';
		return;
	}
	if(NAME.className=='headerMenu3'){
		NAME.className='headerMenu3Active';
		return;
	}
	if(NAME.className=='headerMenu4'){
		NAME.className='headerMenu4Active';
		return;
	}
	if(NAME.className=='headerMenu5'){
		NAME.className='headerMenu5Active';
		return;
	}
	if(NAME.className=='headerMenu6'){
		NAME.className='headerMenu6Active';
		return;
	}
	if(NAME.className=='headerMenu7'){
		NAME.className='headerMenu7Active';
		return;
	}
} 

/**
* Tick the checkbox for a photo
**/
function tickUntickCheckbox(imageID, tdID, photoID){
	var imgTag=document.getElementById(imageID);
	if(imgTag.src==baseUrl+untickedURL){//tick
		imgTag.src=baseUrl+tickedURL;
		imgTag.alt='Déselectionner la photo';
		arraySelectedPhotos[photoID]=true;
	}
	else{//untick
		imgTag.src=baseUrl+untickedURL;
		imgTag.alt='Sélectionner la photo';
		arraySelectedPhotos[photoID]=false;
	}
	
	var tdTag=document.getElementById(tdID);
	if(tdTag.className=='tdSelected'){
		tdTag.className='tdNotSelected';
	}
	else{
		tdTag.className='tdSelected';
	}
}

/**
* This function is called to tick checkboxes when displaying user albun content on page reload.
**/
function retickCheckBox(){
	for (photoID in arraySelectedPhotos){
		if(arraySelectedPhotos[photoID]==true){
			var imgTag=document.getElementById('checkBox'+photoID);
			imgTag.src=baseUrl+tickedURL;
			imgTag.alt='Déselectionner la photo';
			var tdTag=document.getElementById('tdImg'+photoID);
			tdTag.className='tdSelected';
		}
	}
}

function untickAllCheckBoxes(){
	for (photoID in arraySelectedPhotos){
		if(arraySelectedPhotos[photoID]==true){
			var imgTag=document.getElementById('checkBox'+photoID);
			imgTag.src=baseUrl+untickedURL;
			imgTag.alt='Sélectionner la photo';
			var tdTag=document.getElementById('tdImg'+photoID);
			tdTag.className='tdNotSelected';
		}
	}
	clearSelectedPhotosArray();
}

function infoMessage(divName,message){
  var div=document.getElementById(divName);
  div.innerHTML=message;
}

function checkValidUrl(strUrl){
    var RegexUrl = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return RegexUrl.test(strUrl);
}


/*
increment a number inside a string
example : var str = "fluff (3) stringy 9 and 14 other things";

// fluff (6) stringy 9 and 14 other things :: 3 is added to the first number
alert( stringIncrement(str, 3, 0) );
// fluff (3) stringy 6 and 14 other things :: -3 is added to the second number
alert( stringIncrement(str, -3, 1) );

// fluff (3) stringy 9 and 24 other things :: 10 is added to the third number
alert( stringIncrement(str, 10, 2) );
*/
function stringIncrement( str, inc, start ) {
    start = start || 0;
    var count = 0;
    return str.replace( /(\-?d+)/g, function() {
        if( count++ == start ) {
            return(
                arguments[0]
                .substr( RegExp.lastIndex )
                .replace( /\d+/, parseInt(arguments[1])+inc )
            );
        } else {
            return arguments[0];
        }
    })
}

// http://javascript.about.com/library/blurl2.htm
// copyright Stephen Chapman, 1st Jan 2005
// you may copy this function but please keep the copyright notice with it
function getURL(uri) {
	uri.dir = location.href.substring(0, location.href.lastIndexOf('\/'));
	uri.dom = uri.dir; 
	if (uri.dom.substr(0,7) == 'http:\/\/')
		uri.dom = uri.dom.substr(7);
	uri.path = ''; 
	var pos = uri.dom.indexOf('\/'); 
	if (pos > -1) {
		uri.path = uri.dom.substr(pos+1); 
		uri.dom = uri.dom.substr(0,pos);
	}
	uri.page = location.href.substring(uri.dir.length+1, location.href.length+1);
	pos = uri.page.indexOf('?');
	if (pos > -1) {
		uri.page = uri.page.substring(0, pos);
	}
	pos = uri.page.indexOf('#');
	if (pos > -1) {
		uri.page = uri.page.substring(0, pos);
	}
	uri.ext = '';
	pos = uri.page.indexOf('.');
	if (pos > -1) {
		uri.ext =uri.page.substring(pos+1);
		uri.page = uri.page.substr(0,pos);
	}
	uri.file = uri.page;
	if (uri.ext != '') 
		uri.file += '.' + uri.ext;
	if (uri.file == '') 
		uri.page = 'index';
	uri.args = location.search.substr(1).split("?");
	return uri;
}


                  

/**
* Clear the array of selected photo
**/
function clearSelectedPhotosArray(){
	arraySelectedPhotos.length=0
}


/**
* List of images to preload
**/
    if (document.images)
    {
      preload_image_object = new Image();
      // set image url
      image_url = new Array();
      image_url[0] = baseUrl+untickedURL;
      image_url[1] = baseUrl+tickedURL;
      //image_url[2] = "http://mydomain.com/image2.gif";
      //image_url[3] = "http://mydomain.com/image3.gif";

       var i = 0;
       for(i=0; i<=1; i++) 
         preload_image_object.src = image_url[i];
    }
/** end of images preloading**/


/*Function to enable accesskey in forms*/
function formAccessKey(){
	document.f.firstname.focus();
}

/** true if the value of a form field is empty*/
function isEmpty(elem){
	if(elem.value == null || elem.value.length == 0){
		return true;
	}
	return false;
}

// If the element's string matches the regular expression it is all numbers
function isNumeric(elem){
	var numericExpression = /^[0-9]+$/;
	if(elem.value.match(numericExpression))
		return true;
	return false;
}

/**
* Displays a photo coming from an album or uploaded directly in the user controller
**/
function selectProfilePhotoFromAlbum(photo_id){
	//update current selected photo
	new Ajax.Updater('current_selected_photo','users/displaySelectedPhoto/'+photo_id, {
			asynchronous:true, 
			evalScripts:true,
			requestHeaders:['X-Update', 'current_selected_photos']
			});
	//update form used to accept the selected photo
	new Ajax.Updater('validateChosenPhotoForm','users/validateChosenPhotoForm/'+photo_id, {
			asynchronous:true, 
			evalScripts:true,
			onComplete:function(transport){
				Event.observe('validateChosenPhoto', 'submit', function(event) {
					new Ajax.Updater('leftContentBox','/Users/validateChosenPhoto', {
								parameters:Form.serialize('validateChosenPhoto'),
								asynchronous:true,
								evalScripts:true,
								requestHeaders:['X-Update', 'leftContentBox']});	
						}
					, false);
			},
			requestHeaders:['X-Update', 'current_selected_photos']
			});
}


/**
* Displays a photo uploaded directly associated to a website (linksControler)
**/
function selectWebsitePhoto(photo_id){
	//update current selected photo
	new Ajax.Updater('photoWebsite','/links/displayPhoto/'+photo_id, {
			asynchronous:true, 
			evalScripts:true,
			requestHeaders:['X-Update', 'current_selected_photos']
			});
}
/**
* Fill in a form field
* fieldID is the id of the input field
* value is the value to use to fill the input field
*/
function fillField(fieldID, value){
	theInput = document.getElementById(fieldID);
	theInput.value = value;	
}


/**
* Checks if the content has the general syntax of an email.
* This means that the input data must contain at least an @ sign and a dot (.). Also, the @ must not be the first character of the email address, and the last dot must at least be one character 
**/
function validateEmail(field){	
	with (field){
		apos=value.indexOf("@");
		dotpos=value.lastIndexOf(".");
  		if (apos<1||dotpos-apos<2)
			return false;
		return true;
	}
}

/**
* checks if a required field has been left empty. If the required field is blank, the function returns false. If a value is entered, the function returns true
**/
function validateRequired(field){
	with (field){
		if (value==null||value=="")
			return false;
		else
			return true;
	}
}



var loginCharOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
/*
* Checks that string characters contained in fiels are onlu the one in loginCharOK
*
*/
function checkLoginChar(field){
	var allValid=true;
	with (field){
		var checkStr=value;
		for (i = 0; i < checkStr.length; i++){
			ch = checkStr.charAt(i);
			for (j = 0; j < loginCharOK.length; j++){
				if (ch == loginCharOK.charAt(j))
					break;
			}
 			if (j == loginCharOK.length){
				allValid = false;
				break;
			}
		 }
	}
	return allValid;
}

// returns the array number of the selected radio button or -1 if no button is selected
function getSelectedRadio(buttonGroup) {
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} 
	
 // returns the value of the selected radio button or "" if no button is selected
function getSelectedRadioValue(buttonGroup) {
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
}

/**
* get the maximum height of two div and applies it to both of them
*/
function equalizeDivHeight(div1,div2){
	maxHeight=0;
	var div1Elem=document.getElementById(div1);
	var div2Elem=document.getElementById(div2);
	if(div1Elem!=null && div2Elem!=null){
		if(div1Elem.offsetHeight>maxHeight)
			maxHeight=div1Elem.offsetHeight;
		if(div2Elem.offsetHeight>maxHeight)
			maxHeight=div2Elem.offsetHeight;
		div1Elem.style.height=maxHeight+'px';
		div2Elem.style.height=maxHeight+'px';
	}
}

// Usefull for photos page
function displayAlbumScrollBox(albumId) {
    var controllerToCall = '/albums/displayAlbumScrollBox/'+albumId;
    new Ajax.Updater('lastAlbumScrollBox',controllerToCall, {
        asynchronous:true,
        evalScripts:true,
        requestHeaders:['X-Update', 'leftContentBox']});
   
}

function deleteComment(CommentId, currentPage) {
    var controllerToCall = '/comments/deleteComment/'+CommentId+'/page:'+currentPage;
    new Ajax.Updater('Comments', controllerToCall, {
        asynchronous:true,
        evalScripts:true,
        requestHeaders:['X-Update', 'leftContentBox']});
}


function postComment() {
    var controllerToCall = '/comments/postComment/'
    new Ajax.Updater('Comments', controllerToCall, {
        asynchronous:true,
        evalScripts:true,
        parameters: $('postCommentForm').serialize(true),
        requestHeaders:['X-Update', 'Comments']
    });
    return false;
}


function sendPrivateMessage() {
	var controllerToCall = '/privateConversations/postMessage/'
    new Ajax.Updater('conversationsInbox', controllerToCall, {
        asynchronous:true,
        evalScripts:true,
        parameters: $('postMessageForm').serialize(true),
        requestHeaders:['X-Update', 'conversationsInbox']
    });
    return false;
}


/* Automagic forms */
function activateForm(objectId, divId, fieldName, methodToCall, controller, enterTag, closeTag) {
	var linkId = fieldName+'Link'+objectId;
	var textLink = $(linkId).innerHTML;
	
	if (enterTag == '<h2>')
		inputSize = 40;
	else
		inputSize = 30;
	
	if (textLink == 'Cliquez pour renseigner ce champ') {
		textLink = '';
	}
	if (enterTag && closeTag) {
		$(divId).innerHTML = "<input class=\"automagic\" name=\""+fieldName+""+objectId+"\" id=\""+fieldName+""+objectId+"\" size="+inputSize+" value=\""+textLink+"\" />&nbsp;&nbsp;&nbsp;";
	}
	else {
		$(divId).innerHTML = "<textarea class=\"automagic\" rows=\"1\" cols=35 name=\""+fieldName+""+objectId+"\" id=\""+fieldName+""+objectId+"\">"+textLink+"</textarea>";
	}
	$(fieldName+''+objectId+'SubmitSpan').innerHTML = "<input type=\"button\" value=\"Enregistrer\" id=\""+fieldName+""+objectId+"Submit\" onClick=\"submitV('"+controller+"', '"+methodToCall+"', '"+fieldName+"', "+objectId+", '"+divId+"', '"+enterTag+"', '"+closeTag+"');\"/>";
	return false;
}


function submitV(controller, methodToCall, fieldName, objectId, divId, enterTag, closeTag) {
	var inputId = fieldName+objectId;
	var formValue = $F(inputId);
	
	new Ajax.Request ( controller+"/"+methodToCall+"/"+objectId+"/"+fieldName, {
		parameters : { newValue : formValue },
		asynchronous:true, 
		evalScripts:true, 
		requestHeaders:["X-Update", "leftContentBox"]}
	);
	
	if (!formValue) {
		formValue = 'Cliquez pour renseigner ce champ';
	}
	
	$(divId).innerHTML = enterTag+"<a id=\""+fieldName+"Link"+objectId+"\" onclick=\"activateForm("+objectId+",'"+divId+"','"+fieldName+"','"+methodToCall+"','"+controller+"','"+enterTag+"','"+closeTag+"');\">"+ formValue +"</a>"+closeTag;
	$(fieldName+''+objectId+'SubmitSpan').innerHTML = "";
	return false;
}


/**
* Apply the className to make an album cover selected, deselects the other covers
**/
function selectCover(idToSelect,divContainingAllCover){
	//deselect the selected cover
	var divContainingAllCover = document.getElementById('divContainingAllCover');
	//To get all div elements within the element divContainingAllCover, with a “miniCoverSelected” class.
    var selectedCovers=getElementsByClassName("miniCoverSelected", "div", divContainingAllCover); 
	//var selectedCovers=divContainingAllCover.getElementsByClassName('miniCoverSelected');
	for (var i=0; i<selectedCovers.length; i++) {
         selectedCovers[i].className='miniCover';
     }
	  
	//select the cover to select
	var element=document.getElementById(idToSelect);
	element.className='miniCoverSelected';
}

/**
* Resets category Menus
* Arguments must be the number of menu to reset, separeted with commas or * for all
**/
function resetCategoryMenus(MenusToReset){
	if(MenusToReset=='*')
		MenusToReset='1,2';
	
	var reg=new RegExp("[,]+","g");
	var arr=MenusToReset.split(reg);
	for (var i=0; i<arr.length; i++) {
	 	new Ajax.Updater('categoryMenu'+arr[i],'/homePage/displayHomePageMenu/', {
					asynchronous:true, 
					evalScripts:true,
					requestHeaders:['X-Update', 'categoryMenu']}) ;	
	}
}

/* To display the cover image edition link block */
var displayEditAlbumCoverBlock = function() {
	$('albumCoverEditionBlock').style.visibility = "visible";
}
		
var hideEditAlbumCoverBlock = function() {
	$('albumCoverEditionBlock').style.visibility = "hidden";
}

function selectCoverPhoto(albumId, photoId) {
	new Ajax.Updater('formAlbumEditionRight','/albums/selectAlbumCoverPhoto/0', {
		asynchronous:true, 
		evalScripts:true, 
		onComplete:function(transport) {
			$('coverPhotoId').value = photoId;
		}, 
		parameters: {'album_id' : albumId, 'cover_photo_id' : photoId}, 
		requestHeaders:['X-Update', 'formAlbumEditionRight']
	});
}


function deleteReceiver(userId) {
	userElementDiv = $('messageSelectedReceiver_'+userId);
	userElementDiv.className = 'deletedMessageSelectedReceiver';
	userElementDiv.innerHTML = '';
	userElementDiv.style.visibility = 'hidden';
}


function sendConversation() {
	
	var errorMessage = "";
	if (!$F('title')) {
		errorMessage+= "Cette conversation n'a pas de titre.<br />";
	}
	if (!$F('messageContent')) {
		errorMessage+= "Le contenu de la conversation est vide.<br />";
	}
	/*if (!$F('receivers')) {
		errorMessage+= "Cette conversation n'a pas de destinataires.<br />";
	}*/
	
	if (errorMessage) {
		errorMessage.replace(/<br \/>/, '');
		$('errorDiv').innerHTML = "<p>"+errorMessage+"</p>";
		return false;
	}
	else {
		
		$('errorDiv').innerHTML = "";
		
		new Ajax.Updater('leftContentBox','/privateConversations/composeConversation', {
			asynchronous:true, 
			evalScripts:true, 
			parameters : $('postMessageForm').serialize(true),
			requestHeaders:['X-Update', 'conversationsInbox']
		});
	}
}

function sendPrivateMessage() {
	new Ajax.Updater('conversationsInbox','/privateConversations/postMessage', {
		asynchronous:true, 
		evalScripts:true, 
		parameters : $('postMessageForm').serialize(true),
		requestHeaders:['X-Update', 'conversationsInbox']
	});
}

function initializeAjaxUploadPhotoButton(creationDate, objectTypeId, objectId) {
	new AjaxUpload('upload_button', {
            action: '/attachments/uploadPhoto',
            onComplete: function(file, response) {
                addUploadedPhotoToSelection(creationDate, objectTypeId, response.match(/^\d+/), objectId);
            }
    });
}

/**
* Creates an ajax link to a category of Links.
*/
function linkCategory(categoryId) { 
		new Ajax.Updater('leftContentBox','/links/displayCategory/'+categoryId, {
			asynchronous:true, 
			evalScripts:true, 
			requestHeaders:['X-Update', 'leftContentBox']
		});
		
		resetCategoryMenus('*');
		window.dhtmlHistory.add('/links/displayCategory/'+categoryId+':::/homePage/displayHomePageMenu/:::/homePage/displayHomePageMenu/','leftContentBox:::categoryMenu1:::categoryMenu2');
};


/*
*function called in the plant creation form on click on the perennial or grass checkboxes
*@param elementId id of the checkbox
*@param friendElementId1 id of the perrenial checkbox
*@param friendElementId2 id of the grass checkbox
*@param plantId
**/
function perennialChecked(elementId,friendElementId1,friendElementId2,bambooElemId,plantId){
	var elem=document.getElementById(elementId);
	var friendElem1=document.getElementById(friendElementId1);
	var friendElem2=document.getElementById(friendElementId2);
	var bambooElem=document.getElementById(bambooElemId);
	if(elem.checked==true){
		if((friendElem1.checked==false || friendElem2.checked==false) && bambooElem.checked==false){//neither perennial or grass was checked
			new Ajax.Updater('leafTypeElem','/plants/displayLeafTypeElement/perennial/'+plantId, {
				asynchronous:true, 
				evalScripts:true,
				requestHeaders:['X-Update', 'current_selected_photos']
			});
		}
	}
	if(elem.checked==false){
		if(friendElem1.checked==false && friendElem2.checked==false && bambooElem.checked==false){//perennial and grass are unchecked
			new Ajax.Updater('leafTypeElem','/plants/displayLeafTypeElement/normal/'+plantId, {
				asynchronous:true, 
				evalScripts:true,
				requestHeaders:['X-Update', 'current_selected_photos']
			});
		}
	}
	
}

/**
* function called in the plant creation form on click on the bamboo checkbox
*@param elementId id of the checkbox
*@param perennialId id of the perrenial checkbox
*@param grassId id of the grass checkbox
*@param plantId
**/
function bambooChecked(elementId,perennialId,grassId,plantId){
	var elem=document.getElementById(elementId);
	var perennialElem=document.getElementById(perennialId);
	var grassElem=document.getElementById(grassId);
	if(elem.checked==true){
		new Ajax.Updater('leafTypeElem','/plants/displayLeafTypeElement/bamboo/'+plantId, {
			asynchronous:true, 
			evalScripts:true,
			requestHeaders:['X-Update', 'current_selected_photos']
		});
	}
	if(elem.checked==false){
		if(grassElem.checked || perennialElem.checked){
				new Ajax.Updater('leafTypeElem','/plants/displayLeafTypeElement/perennial/'+plantId, {
				asynchronous:true, 
				evalScripts:true,
				requestHeaders:['X-Update', 'current_selected_photos']
			});
		}
		else{
			new Ajax.Updater('leafTypeElem','/plants/displayLeafTypeElement/normal/'+plantId, {
				asynchronous:true, 
				evalScripts:true,
				requestHeaders:['X-Update', 'current_selected_photos']
			});
		}
	}
}


/* Notifications */
function hideNotificationHLBlock(iNotification) {
	divId = 'notificationBlock'+iNotification;
	
	new Ajax.Request('/notifications/markNotificationAsRead/'+iNotification, {
		asynchronous:true, 
		evalScripts:true,
		onComplete : function () {
			new Ajax.Updater('menuNotificationsBox', '/notifications/displayNotificationsLinks/', {
				asynchronous:true, 
				evalScripts:true,
				requestHeaders:['X-Update', 'menuNotificationsBox']
			});
		}	
	});
	
	Effect.Fade(divId, { duration: 1.0 });
	setTimeout("$(divId).innerHTML = ''",1000);
	setTimeout("$(divId).style.display = 'none'",1000);
}

