/* - - - - - - - - - - - - - - - - - - - - -

Title : Headspace Javascript Functions
Author : Motionlab
URL : http://www.motionlab.co.uk

Last Updated : 09th May 2008

- - - - - - - - - - - - - - - - - - - - - */

/* Global vars */
var ut = true;
var et = true;
var na = true;
var pe = true;
var alertMode = false;
var pulse = 10;
  

/* Used for searching for friends =) */
function searchFriends(search, search2, search3) {

	// Tell flash what we are lookign for!
    var obj = swfobject.getObjectById("myCom");
    
    if(search == ''){
		search ='%';	
	}
	
	if (obj && typeof obj.searchFriends != "undefined") {
        obj.searchFriends(search, search2, search3);
    }   else {
     alert("no such function");
    }

}


/* Used for the sitewide live searching */
function autocomplete() {
	// Used with the auto complete searching
	new Ajax.Autocompleter("autocomplete", "livesearch", "/search/livesearch/", { frequency: '1.5', tokens: ','});

}

/* Used for find towns in the db */
function autocomplete_city() {
	// Used with the auto complete searching
	new Ajax.Autocompleter("qyr1", "citysearch", "/friends/citys/", { tokens: ','});
}

/* Used for find towns in the db */
function autocomplete_job() {
	// Used with the auto complete searching
	new Ajax.Autocompleter("qyr2", "jobsearch", "/friends/jobs/", { tokens: ','});
}


/* Gets the next page of friends */
function nextFriends(page) {
    
    // Update the currentFriends with the next page
    new Ajax.Updater('currentFriends', '/friends/currentfriends/' + page);

}


/* Gets the next page of friends */
function friendsRequests() {
    
    // Update the currentFriends with the next page
    new Ajax.Updater('pendingFriends', '/friends/requestfriends/');

}


/* Gets the next page of friends */
function acceptFriend(friend) {

   new Effect.Fade('message-'+friend, {duration:0.8 , afterFinish:function(){ nextFriends(1); } });  
   new Effect.Fade('divider-'+friend, {duration:0.8 }); 
   new Ajax.Request("/user/accept/?user=" + encodeURIComponent(friend), {  method: 'get' });    
}


/* Gets the next page of friends */
function denyFriend(friend) {

   new Effect.Fade('message-'+friend, {duration:0.8 , afterFinish:function(){ nextFriends(1); } });  
   new Effect.Fade('divider-'+friend, {duration:0.8 }); 
   new Ajax.Request("/user/deny/?user=" + encodeURIComponent(friend), {  method: 'get' });    
}


/* Used for obtaining the users recent requests/messages.
 * Displayed at the top of each page (once logged in) */
function startPollingUser(user) {
	
	// Periodically send out a pulse.
	new Ajax.PeriodicalUpdater('userData', '/user/userdata/?username=' + user, {asynchronous:true, frequency:pulse, decay: 2, onFailure:function(){alertBox('neterror')}, on404:function(){alertBox('neterror');}});
}



/* Show alert box */
function alertBox(type) {
	
	if (alertMode == false) {
		
		alertMode = true;
		window.scrollTo(0, 0); 
		$('overlay').className = "overlay-show";
		$('alert').className = "overlay-show";
		
		var bod = document.getElementsByTagName('body')[0];
		var htm = document.getElementsByTagName('html')[0];
		bod.style.height = '100%';
		bod.style.overflow = 'hidden';
		htm.style.height = '100%';
		htm.style.overflow = 'hidden'; 

		new Effect.Opacity('overlay', {duration:0.4, from:0.0, to:0.75});
		new Effect.Opacity('alert', {duration:0.3, from:0.0, to:0.99999});
		
		// What type of error?
		if (type == "neterror") {
			$('alert-bar').className = "alert-neterror";
			$('alert-title').className = "alert-icon-neterror";
			$('alert-title').innerHTML = "A Network Disruption was Detected!";
			$('alert-main').innerHTML = "To ensure the quality of service, Headspace will attempt to temporarily disable the more interactive features of the site.";
		
		}
	}
}


//alertbox("neterror");



/* The world according to Flash */
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    }
    else {
      if(document[movieName].length != undefined){
          return document[movieName][1];
      }
        return document[movieName];
    }
}
 
 

/* Function to delete message */
function deleteMessage(thread) {
	
    // Del msg
	new Ajax.Request("/inbox/delete/?thread=" + encodeURIComponent(thread), {  method: 'get', onSuccess: function(transport) { updateMessage(transport.responseText); } });	
}



/* Function to add friend */
function addFriend(user) {
    
    // Add friend
    new Ajax.Request("/user/add/?req=" + encodeURIComponent(user), {  method: 'get', onSuccess: function(transport) { } });    
    
    // Clean up styles
    //$('addfriend-icon').hide();
    new Effect.Fade('addfriend-icon', {duration:0.8 });  
}



/* Function to report user */
function reportUser(user) {
    
    // TODO
    
    // Clean up styles
    new Effect.Fade('flagprofile-icon', {duration:0.8 });  
}



/* Function to update message */
function updateMessage(resp) {

	new Effect.Fade('message'+resp, {duration:0.8, afterFinish:function(){$('message'+resp).className = "message-deleted";} });
}



/* Kills the alert box */
function killAlertBox() {
	
	alertMode = false;
	new Effect.Opacity('alert', {duration:0.2, from:0.99999, to:0.0});
	new Effect.Opacity('overlay', {duration:0.4, from:0.75, to:0.0, afterFinish:function(){$('overlay').className = "overlay-hide";  $('alert').className = "overlay-hide";} });
	var bod = document.getElementsByTagName('body')[0];
	var htm = document.getElementsByTagName('html')[0];
	bod.style.height = 'auto';
	bod.style.overflow = 'auto';
	htm.style.height = 'auto';
	htm.style.overflow = 'auto'; 
}



/* Used for validating the username, to make sure it does
 * not exists in the database!  */
function validateUser() { 

	// Grab target
	var target = document.getElementById("username"); 

	// Value has valid length?
	if(target.value.length > 2) {
		
		// Send ajax request
		new Ajax.Request("/user/checkuser/?username=" + encodeURIComponent(target.value), {  method: 'get', onSuccess: function(transport) {validateUserCallback(transport.responseText); } });
		
	} else {
		
		// Swop styles
		$('usernameField').className = "field-invalid";
		$('regBtn').disabled = true;
	}
}



/* Call back for user validation */
function validateUserCallback(responseText) {

	// Have callback text from transport?
	if (responseText == "true") {
	  
	  	// Taken =(
		$('usernameField').className = "field-taken";
		ut = true;

	} else {

       // Available =)
	   $('usernameField').className = "field-available";
	   ut = false;
      
	}  
	validateLocalRegistrationData();
}



/* Used for validating the username, to make sure it does
 * not exists in the database! */
function validateEmail() { 

	// Grab target
	var target = document.getElementById("email"); 
	
	// Is locally validated email?
	if(isValidEmail(target.value)) {

		// Send ajax request / remote validation
		new Ajax.Request("/user/checkemail/?email=" + encodeURIComponent(target.value), {  method: 'get', onSuccess: function(transport) {validateEmailCallback(transport.responseText); } });
		
	} else {

		// Swop styles
		$('emailField').className = "field-invalid";
		$('regBtn').disabled = true;
		
	}

}



/* Call back for user validation */
function validateEmailCallback(responseText) {

   // Have callback text from transport?
   if (responseText == "true") {
	   
	  	// Taken =(
		$('emailField').className = "field-taken";
		et = true;

    } else {

	  	// Available =)
		$('emailField').className = "field-available";
		et = false;
      
    }  
	validateLocalRegistrationData();
}



/* Validate a name */
function validateName() {

    var mdiv = document.getElementById("fullnameField");
    var target = document.getElementById("fullname"); 
	
	if((target.value.length < 6) || (target.value.length > 29) ) {
	   
       // set the style on the div to invalid
       mdiv.className = "field-invalid";
	   na = true;

    } else {

       // set the style on the div valid
       mdiv.className = "field-available";
	   na = false;
      
    }  
	validateLocalRegistrationData();
}



/* Validate a password */    
function validatePassword() {
	
	if((document.getElementById("pass1").value.length < 4) || (document.getElementById("pass1").value.length > 20) ) {
	   
       // set the style on the div to invalid
       document.getElementById("pass1Field").className = "field-invalid";
	   pe = true;

    } else {
		
		document.getElementById("pass1Field").className = "field";
		
		if(document.getElementById("pass1").value == document.getElementById("pass2").value ) {
			
			document.getElementById("pass2Field").className = "field";
			 pe = false;
		} else {
			document.getElementById("pass2Field").className = "field-invalid";
			 pe = true;
		}
    
      
    }  
	validateLocalRegistrationData();
}



function isValidEmail(e) {
	
	ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";

	for(i=0; i < e.length ;i++){
		if(ok.indexOf(e.charAt(i))<0){ 
			return (false);
		}	
	} 

	if (document.images) {
		re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
		re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
		if (!e.match(re) && e.match(re_two)) {
			return (-1);		
		} 

	}
}



/* Validate registration form */
function validateLocalRegistrationData() {

  if ((ut == false) &&  (et == false) && (na == false) && (pe == false) && ($('agreeTOS').checked) )  {
	   
	   $('regBtn').disabled = false;
	   
  } else {
	  
	  $('regBtn').disabled = true;
  }
}



/* Validate standard password */ 
function validateStandardPassword() {
	
	if( ($('password').value.length < 7) || ($('password').value.length > 20) ) {
	   
		// Bad password
		$('passwordField').className = "field-invalid";
		$('subBtn').disabled = true;
	  
    } else {
		
		// Good password
		$('passwordField').className = "field";
		$('subBtn').disabled = false;
    }  
	
}



/* Validate a password */    
function comparePassword() {
    
    if((document.getElementById("pass1").value.length < 7) || (document.getElementById("pass1").value.length > 20) ) {
       
       // set the style on the div to invalid
       document.getElementById("pass1Field").className = "field-invalid";
       $('subBtn').disabled = false;  

    } else {
        
        document.getElementById("pass1Field").className = "field";
        
        if(document.getElementById("pass1").value == document.getElementById("pass2").value ) {
            
            document.getElementById("pass2Field").className = "field";
            $('subBtn').disabled = false;  
        } else {
            document.getElementById("pass2Field").className = "field-invalid";
             $('subBtn').disabled = true;  
        }
    
      
    }  

}

/* clear the search box */
function clearSearch(event) {
	  var element = event.element();
	  element.value = "";
}

//function used for pass values between the discipline select boxes
function passValue(selectionSize) {

	//create an array of all the disciplines they are trying to add
	var newDisciplines;
	newDisciplines = $('discipline').getValue();
	
	//create an array of the existing disciplines that they have selected
	var selectedDisciplines;
	selectedDisciplines = $('selected_discipline').getValue(); 
	
	//calculated the size of the teo arrays
	selectionSize = selectionSize + newDisciplines.size();
	
	//check that there are going to be no more than 5 disciples			
	if(selectionSize<7){
	
	//loop through each discipline that you are going to add
	newDisciplines.each(function(item) {
		
		//check that they new discipline doesnt already exist
		for (key in selectedDisciplines) {
			if ((selectedDisciplines[key] == item)) {
				alert('You have already added '+item+' as a discipline.');
				return false;
			}
		}
		
		//the new discipline
		var optn = document.createElement("OPTION");
		optn.text = item;
		optn.value = item;
		optn.selected = true;
		optn.id = item;
		$('regForm')['selected_discipline[]'].options.add(optn,0);
		
	});
	
} else {
	//alert the user that they have tried to add to many disciplines
	alert ("You can only select a maximum of 5 disciplines.");
}
	return false;
}

//function used to highlight the disciplines that you have selected
function highlightDisciplines() {
		for(i=0;i<=document.regForm.selected_discipline.length-1;i++) { 
			document.regForm.selected_discipline.options[i].selected = true;
		}
}

//function used to remove items from the selected disciplines box
function removeValue() {
		//create an array of the existing disciplines that they have selected
		var selectedDisciplines;
		selectedDisciplines = $('selected_discipline').getValue();
		
		//loop through the selected disciplines that are to be removed 
		selectedDisciplines.each(function(item) {
		if(item != 'default_option') {
			$(item).remove();
		}
		});

	return false;	
}

function deletePortfolio() {
 	  var check = confirm('Are you sure you want to delete this Portfolio?\nPLEASE NOTE: You cannot undo this action.');
      if (check == true) {
       	return true;
      } else {
		return false;  
	  }
	
}

function deleteResource() {
 	  var check = confirm('Are you sure you want to delete this Resource?\nPLEASE NOTE: You cannot undo this action.');
      if (check == true) {
       	return true;
      } else {
		return false;  
	  }
	
}

function checkarea() {
	
	
	var optionElements = $('file_type').childElements();
	var disabled = false;
	
	var grabArchiveIndex = null;
	
	if($F('area') == 'climate') {		
		disabled = true;
	}
	optionElements.each(function(node) {
		if(node.readAttribute('value') == 'archive') {
			node.writeAttribute('disabled', disabled);
			grabArchiveIndex = node.selectedIndex;
		}
	});
	
	$('file_type').selectedIndex = (grabArchiveIndex - 1);
	
}

function checktype() {
	if($F('file_type') == "lead") {
		Effect.BlindUp('youtubeEmbed');
		Effect.BlindUp('resourceFile');
		Effect.BlindUp('happeningInfo');
		Effect.BlindDown('leadInfo');
		if($('interview')){Effect.BlindUp('interview');}
	}
	/*else if($F('file_type') == "audio") {
		Effect.BlindUp('youtubeEmbed');
		Effect.BlindDown('resourceFile');
		Effect.BlindUp('leadInfo');
		Effect.BlindUp('happeningInfo');
		if($('interview')){Effect.BlindUp('interview');}
	}
	else if($F('file_type') == "archive") {
		Effect.BlindUp('youtubeEmbed');
		Effect.BlindDown('resourceFile');
		Effect.BlindUp('leadInfo');
		Effect.BlindUp('happeningInfo');
		if($('interview')){Effect.BlindUp('interview');}
	}*/
	else if($F('file_type') == "happening") {
		Effect.BlindUp('youtubeEmbed');
		Effect.BlindUp('resourceFile');
		Effect.BlindUp('leadInfo');
		Effect.BlindDown('happeningInfo');
		if($('interview')){Effect.BlindUp('interview');}
	}
	else if($F('file_type') == "video") {
		Effect.BlindDown('youtubeEmbed');
		Effect.BlindUp('resourceFile');
		Effect.BlindUp('leadInfo');
		Effect.BlindUp('happeningInfo');
		if($('interview')){Effect.BlindUp('interview');}
	} 
	
	else if($F('file_type') == 'interview') {
		
		Effect.BlindUp('youtubeEmbed');
		Effect.BlindUp('leadInfo');
		Effect.BlindUp('resourceFile');
		Effect.BlindUp('happeningInfo');
		Effect.BlindDown('interview');
	}
		else 
		{
		Effect.BlindUp('youtubeEmbed');
		Effect.BlindUp('leadInfo');
		Effect.BlindDown('resourceFile');
		Effect.BlindUp('happeningInfo');
		if($('interview')){Effect.BlindUp('interview');}
		}

}