// Search form

function searchFormClick(e,x) {
	// check to see if the text input value is equal to the default value
	if (e.value == x) {
		// if they are the same, remove the default value and the grey text colour
		e.value = '';
		e.removeClassName('searchgrey');
	}
}

function searchFormBlur(e,x) {
	// check if the text input doesn't have a value
	if (e.value == '' || !e.value || e.value == null) {
		// if theres no value, add the default value and the grey text colour
		e.value = x;
		e.addClassName('searchgrey');
	}
}


// Tabbed gallery class

var Gallery = Class.create();

Gallery.prototype = {
	initialize: function(e) {
		this.element = $(e);
		this.createTabs();
	},
	createTabs: function() {
		this.element.childElements().each(function(e,i) {
			if (i > 1) {
				e.hide();
			}
		});
		this.tabs = this.element.down(1).childElements();
		this.tabs.each(function(e,i) {
			e.observe('click', function(event) {
				this.siblings().each(function(f,j) {
					f.removeClassName('active');
				});
				this.addClassName('active');
				this.up(2).childElements().each(function(f,j) {
					if (j > 0) {
						f.hide();
					}
				});
				this.up(2).childElements()[i+1].show();
			});
		});
	}
}


AppInit.addEvent(function() {
    
    
    // Media details sidebar boxes
        
    // Find all the sidebar media lists.
    var boxes = $$('div.sidebarlist h2');
    boxes = boxes.concat($$('div.openclose h2'));
    
    // When the user clicks on the media lists' header, toggle the visibilty 
    // of the list and change the header's class name so the icon will change. 
    boxes.each ( function(item){
       item.onclick = function () {
            var the_div = item.next();    
			var the_icon = item.select('span');
            item.toggleClassName('active');
            the_div.toggle();                  
        }                
    });  
        
        
    // Tool tips
  
  	// Using the elements title attribute and the content, display a fancy
  	// tool tip above the icons in the user info panel.
  	
  	// Find all the elements with the class name 'tool'
    var tooltip = $$('a.tool');
    var tooltip = tooltip.concat($$('span.tool'));
		
	tooltip.each ( function(i) {
	
		Event.observe(i, 'mouseover', function(e) {
		       				       		
       		// Get the current position of the item and it's title.
       		// The title is used as the text of the tooltip
            var p = i.positionedOffset();
            var t = i.readAttribute('title');
            
            // Remove the title attribute so it won't appear on the mouseover.
            i.writeAttribute('title',"");
            
            // check if its in the comments
            if (i.hasClassName('mini')) {
            	//console.log("yes");
            }
            
            // If there is already a tooltip, remove it
            if ($$('div.tooltip').length >= 1) {
            	$$('div.tooltip').each( function(i2) {
            		i2.remove();
            	});
            }
            
            // Add a new tooltip and it's required attributes.
			tt = $(document.createElement("div")); 
			i.up(1).appendChild(tt);
			tt.addClassName("tooltip");
			
			// Place the text from the title attribute into the tooltip.
			tt.innerHTML = t;
			
			// Find the placement of the link and positon the tooltip accordingly.
			//var xPos = -p[0] + i.getWidth();
  			var xPos = (p[0] + i.getWidth()/2) - (tt.getWidth()/2);
  			
  			//console.log("x:"+xPos+" y:"+yPos);
  			
  			// Add the required CSS and fade in the tooltip.
  			if (i.hasClassName('mini')) {
  				var yPos = -(i.up(1).getHeight()-50);
  				var css = "left: "+xPos+"px; top: "+yPos+"px; position:relative;";
  			} else {
  				var yPos = 0;
  				var css = "left: "+xPos+"px; top: "+yPos+"px;";
  			}
  			tt.writeAttribute("style", css);
			tt.show();
		});
		
		Event.observe(i, 'mouseout', function(e) {
		
			// If there is a tooltip Replace the title attribute with
			// the text inside the tooltip and remove the tooltip.
            if ($$('div.tooltip').length >= 1) {
            	$$('div.tooltip').each( function(i2) {
            		i.writeAttribute('title',i2.innerHTML);
            		i2.remove();
            	});
            }
		});
		
	});


	// Tags
	
	// Replace the list of tags in the element with the id of "tags" with
	// links to the search page using the tag as the query.
	
	// Only do this if there is a element with the id of "tags".
	if ($("tags")) {
	
		// Get the tags
		var tagsT = $("tags").innerHTML;
		
		// Split them and create other variables.
		var tagsV = tagsT.split(" ");
		var tagsU = "";
		var tagsA = "";
		
		for (tagsI=0;tagsI<tagsV.length;tagsI++) {
		
			// If we're at the last tag, dont add a comma after the link.
			if (tagsV.length-tagsI<=1) {
				tagsA = "";
			} else {
				tagsA = ", ";
			}
			
			// 
			tagsU += '<a href="/mediasearch?q='+tagsV[tagsI]+'">'+tagsV[tagsI]+'<\/a>'+tagsA;
		}
		
		$("tags").innerHTML = tagsU;
	
	}
	
	
	if ($("mapheader")) {
	    $('mapheader').observe('click', function(event){
	       
			var medialat = $('lat').value;
			var medialong = $('long').value;
			
			medialat = parseFloat(medialat);
			medialong = parseFloat(medialong);
				
			AppInit.addEvent(function() {
				initMap(medialat,medialong,11,false,false,true);
			});
			
		});
	}

});

	
// Homepage Horizontal Ajax Gallery

function updateGallery(options){

	// Create the variables
	
	// Required
	var page = typeof options.page == 'undefined' ? console.log("'page' is required") : options.page;
	var node = typeof options.node == 'undefined' ? console.log("'node' is required") : options.node;
	var sort = typeof options.sort == 'undefined' ? console.log("'sort' is required") : options.sort;
	
	// Optional
	var channel = typeof options.channel == 'undefined' ? false : options.channel;
	var collection = typeof options.collection == 'undefined' ? false : options.collection; 
	var filetype = typeof options.fileTypes == 'undefined' ? '1,2,3,4' : options.fileTypes;
	var moderation = typeof options.moderationStatus == 'undefined' ? 'notdenied' : options.moderationStatus;
	var child = typeof options.includeChildren == 'undefined' ? '0' : options.includeChildren;
	var tag = typeof options.tag == 'undefined' ? '' : options.tag;
	var search = typeof options.searchQuery == 'undefined' ? '' : options.searchQuery;
	var startTime = typeof options.startTime == 'undefined' ? '' : options.startTime;
	
	var container =  $(node);
	
	var c = "";
        
	if (channel && channel != false) {
		c += "&channel="+channel;
	} else {
		c += "&channel=";
	}
	
	if (collection && collection != false) {
		c += "&collection="+collection;
	} else {
		c += "&collection=";
	}
	
	// combine the variables into a URL
	var theurl  = '/ajaxgallery?id=' + node;
	theurl += '&sort=' + sort;
	theurl += '&page=' + page;
	theurl += c;
	theurl += '&fileTypes='+ filetype;
	theurl += '&moderation='+ moderation;
	theurl += '&child='+ child;
	theurl += '&tag='+ tag;
	theurl += '&search='+ search;
	theurl += '&startTime='+ startTime;
	theurl += '&nowrapper';
	
	// remove all the thumbs and replace it with a loading icon
	container.innerHTML = '<div class="loading"></div><div class="loadingafter"></div>';
	
	// create the Ajax
	new Ajax.Request(theurl, {
   		method: 'get',
   		onSuccess: function(transport) {
     		setTimeout(function(){
     			// replace the container's content with the new thumbs
         		container.innerHTML = transport.responseText;
			}, 0);
		}
	});
}


// Ajax Rating

function fmLike(mid, uid) {
	// if the user isn't logged in display the error message asking them to log in
	if (uid <= 1) {
		alert($('loginLike').value);
	} else {	
		if (!$('vote'+mid).next().hasClassName("disabled")) {
			// disable the button
			$('vote'+mid).next().addClassName("disabled");
			// assume the js request will work and auto increment the total count
			$('vote'+mid).innerHTML = (parseInt($('vote'+mid).innerHTML)+1);
			jsonRequest('media.rateFile', {"id":mid,"rating":10,"returnData":true},
	    		function(result) {},
	    		function(exception) { console.log(exception); }
	  		);
  		}
	}
}


// Ajax Favourites

function favMedia(mid) {
	var id = mid;
	jsonRequest ( 'media.addToFavorites', { 'mid': id, 'returnData': true },
		function (result) { 
			$('addedtofav').show();
			$('addedtofav').fade({ duration: 0.5, from: 0, to: 1});
			setTimeout("$('addedtofav').fade ({ duration: 0.5, from: 1, to: 0 })",4000);
		}, function(exception) { console.log(exception); },
	true );
	
}

var FavRemoveCounter = 4;

function removeFav(div, id, node) {
	
	var container = $(div);
	var id = id;
	var node = node;
	
	jsonRequest ( 'media.removeFromFavorites', { 'mid': id }, function (result) { 
		
	var theurl = '/newfav?count='+FavRemoveCounter+'&nowrapper';
	
		new Effect.Fade ( $(node).up(1), { duration: 0.5, from: 1, to: 0.000001,
			'afterFinish': function () {
				$(node).up(1).hide();
				new Ajax.Request(theurl, {
					method: 'get',
					onSuccess: function(transport) {							
						container.innerHTML += transport.responseText;
							setTimeout(function(){
								var newDiv = "new"+(FavRemoveCounter-1);
								//$(newDiv).fade({ duration: 1, from: 0.00001, to: 1 })
							console.log($(newDiv));
						}, 300);
					}
				});				
			}
		});
	
	FavRemoveCounter++;
	
	});
	
}

AppInit.addEvent (
    function() {
        $$( 'label' ).each ( function ( label ) {
            label.defaultColor = label.getStyle ( 'color' );
        } );
    }

);


/* this funciton is for validation on register, all else is being handeled in the below function */
function handleValidationRegister(element,message) {

	var eName = message.substr(0,message.indexOf(' '));
	
	// If the message's first word is the element's name and the element has a title attribute, remove the name from the message and add the title
	// This way we don't depend on the element's name when displaying the error message.
	if (eName = element.name && element.title) {
		message = element.title+" "+message.substr(message.indexOf(' '));
	}

   $('validationmessage').innerHTML = message;

   $( element ).addClassName ( 'errorField' );

   if ( $( element ).hasClassName ( 'fmCheckBox' ) ) {
     $( element ).up ().addClassName ( 'errorLabel' );
   }

	var mylocation = document.location.toString();
	var newloc = mylocation.split('#');
	document.location = newloc[0] + '#validationmessage'; 

   var labels = element.form.getElementsByTagName('label');
   for(var i=0;i<labels.length;i++) {
    
     if (labels[i].htmlFor==element.id) {
        labels[i].style.color = '#CC0000';
     } else {
        labels[i].style.color = labels [ i ].defaultColor;
     }
   }

}

/* This is for all validation except EXCEPT register, see above function handleValidationRegister for that
function handleValidation(element,message, lang) {

	// For more discriptive validation errors
	// Make sure the error message's first word is the element's name attribute
	
	if(lang == 'en'){
		console.log('english');
		console.log('english message -> '+message);

	}else if(lang == 'fr'){
		console.log('french');
		
		//This is for the validation depending on if french of english urls used
		message = message.replace("is a required field","est un champ obligatoire.");
	    message = message.replace("does not contain a valid Canadian postal code","ne contient pas de code postal canadien valide.");
	    message = message.replace("does not contain a valid phone number","ne contient pas de numéro de téléphone valide.");
	    message = message.replace("does not contain a valid email address","ne contient pas une adresse email valide.");
	    message = message.replace("captcha you entered was invalid, please try again","Le captcha que vous avez entré est incorrect. Veuillez SVP essayer de nouveau.");
	    message = message.replace("The email address supplied is already registered. Did you forget your login information?","Le courriel que vous avez inscrit a déjà été utilisé. Veuillez SVP utiliser la section Me connecter pour participer à nouveau.");
	    message = message.replace("does not have a valid date","n'a pas une date valide.");
	    message = message.replace("Your password needs to be at least 6 characters long","Votre mot de passe doit contenir au minimum 6 caractères.");
	    message = message.replace("The passwords did not match","Les mots de passe ne correspondent pas.");
	    message = message.replace("The email fields do not match","Les emails ne correspondent pas");
	    message = message.replace("A username has to be a minimum of 6 characters, can only contain A-Z 0-9 and _ (underscore) and has to start with a letter","Le nom d'utilisateur doit contenir au minimum 6 caractères du type A-Z 0-9 and _ (underscore) et doit commencer par une lettre");
	    message = message.replace("The username you picked was already taken. Please try something else","Le nom d'utilisateur que vous avez saisi est déjô utilisé. Veuillez recommencer.");
		message = message.replace("The email or password you specified were incorrect","L'email ou le mot de passe indiqués sont incorrects.");
	    
	    // Translate the field names
	    message = message.replace("firstname","Prenom");
	    message = message.replace("lastname","Nom");
	    message = message.replace("email","Courriel");
	    message = message.replace("phonenumber", "T&eacute;l&eacute;phone");
	    message = message.replace("meta[birthyear]", "Ann&eacute;e de naissance");
	    message = message.replace("gender", "Sexe");
	    message = message.replace("meta[CodePostal]", "Code postal");
	    message = message.replace("password", "Mot de passe");
	    message = message.replace("confirm", "Confirmer le mot de passe");
	    // Add more here translations here.

		console.log('the message has ben translated into french, the following-> ' + message);
	}
		
	// If the message's first word is the element's name and the element has a title attribute, remove the name from the message and add the title
	// This way we don't depend on the element's name when displaying the error message.
	
	var mylocation = document.location.toString();
	var newloc = mylocation.split('#');
	document.location = newloc[0] + '#validationmessage'; 
	
	// the output
	var out = '';
	var m = message.substr(0,message.indexOf(' '));
	
	if (element.type == "checkbox") {
		var n = $(element).next();
	} else {		
		// this is for table forms
		var n = $(element).up(0).previousSiblings()[0].down(0);
		
		//and if not this is for list forms
		if(!n){
			var n = $(element).previousSiblings()[0];
		}
	}
			
	if(!n){n = 'captcha';}
	var title = String(n.innerHTML);
	var o = n.innerHTML;
	
	if (message != "The email address supplied is already registered. Did you forget your login information?" && message.substr(0,10) != "A username" && message.substr(0,11) != "The captcha") {
		
		//message = o.substr(0,o.indexOf('*'))+" "+message.substr(message.indexOf(' '));
		if (title.indexOf('*') > -1){
			out = title.substr(0,title.indexOf('*'))+" "+message.substr(message.indexOf(' '));
		} else{
			out = element.title+""+" "+message.substr(message.indexOf(' '));
		}

	} else if (message.substr(0,10) == "A username") {
		out = o+message.substr(10);	
	}else if (message.substr(0,4) == "user") {
		out = o+message.substr(4);	
	} else if (message.substr(0,11) == "The captcha") {
		out = message;
	} else if (message == "The email address supplied is already registered. Did you forget your login information?") {
		out = "The email address supplied is already registered.";
	}
	
 	var labels = element.form.getElementsByTagName('label');
	for(var i=0;i<labels.length;i++) {
		if (labels[i].htmlFor==element.id) {
			// put the message inside the label
			if (element.type != "checkbox") {
				labels[i].innerHTML = out;
			}
			// make the label stand out
			labels[i].addClassName('error');
			// remove the old border-color
			// this fixes an issue when fading out the border
			element.setStyle({'borderColor':''});
			// make the input stand out
			element.addClassName('errorField');
			// scroll to that element
			//console.log(cumulativeOffset(element));
			//window.scrollTo(cumulativeOffset(element)[0],cumulativeOffset(element)[1]);
		}
	}

	function removeStyles(e,n) {
		var labels = element.form.getElementsByTagName('label');
		for(var i=0;i<labels.length;i++) {
			if (labels[i].htmlFor==element.id) {
				labels[i].innerHTML = n;
				labels[i].removeClassName('error');
				element.removeClassName('errorField');
			}
		}
	}

	element.observe('focus', function(event) {
		removeStyles(event, o);
	});
}
*/





function handleValidation(element,message) {
	// we check if it already has the error class to prevent multiple messages appearing on the same element
	if (!element.hasClassName('errorField')) {
	
		// the name of the element
		var name = message.substr(0,message.indexOf(' '));
		
		// the actually error message
		var originalMessage = message;
		var message = message.substr(message.indexOf(' '));
		
		// if its a checkbox, don't highlight the element but highlight the text beside it
		if (element.type == "checkbox") {
			var label = $(element).next();
		} else {
			var label = $(element).up(0).previousSiblings()[0].down(0);
		}
		
		// the title we're going to use
		var title = element.title;
		
		// without *
		var titlesub = title.substr(0,title.indexOf('*'))
		
		// the output
		var out = '';
		
		// check the message and output the right title and message combo
		if (name == element.name && title) {
			if (message != "The email address supplied is already registered. Did you forget your login information?" && message.substr(1,8) != "username" && message.substr(0,11) != "The captcha") {
				if (title.indexOf('*') > -1) {
					out = titlesub+" "+message;
				} else {
					out = title+message;
				}
			} else if (message == "The email address supplied is already registered. Did you forget your login information?") {
				out = "The email address supplied is already registered.";
			} else {
				out = titlesub+" "+message;
			}
		} else {
		
			if (message.substr(1,8) === "username" && message.substr(14,6) !== "picked") {
				out = titlesub+" "+message.substr(10);
			} else	if (message.substr(1) === "passwords did not match") {
				out = "P"+message.substr(2);
			} else if (element.type == "checkbox") {
				out = titlesub+message;
			} else {
				out = originalMessage;
			}
		}
		
		// get all the labels in this from
		var labels = element.form.getElementsByTagName('label');
		for(var i=0;i<labels.length;i++) {
			// check all the labels for the one that matches the failed form element
			if (labels[i].htmlFor==element.id) {
				// put the message inside the label
				//if (element.type != "checkbox") {
					labels[i].innerHTML = out;
				//}
				// make the label stand out
				labels[i].addClassName('error');
				// remove the old border-color
				// this fixes an issue when fading out the border
				element.setStyle({'borderColor':''});
				// make the input stand out
				element.addClassName('errorField');
				// scroll the browser to that element.
				labels[i].scrollTo();

			}
		}
	
		// remove the styles from the failed form element and the label
		function removeStyles(t) {
			// search though all the labels again
			for(var i=0;i<labels.length;i++) {
				// find the label that matches the failed form element
				if (labels[i].htmlFor==element.id) {
					// return everything to normal
					labels[i].innerHTML = t;
					labels[i].removeClassName('error');
					element.removeClassName('errorField');
				}
			}
		}

	}

	// we want the element and label to retrun to normal when the user relizes the error.
	element.observe('focus', function(event) {
		removeStyles(title);
	});
}










/* This is for the login lightbox in the header; validation, */
function lightboxValidate(element,message){
	
	/* -- validation using title field -- */
	// For more discriptive validation errors
	// Make sure the error message's first word is the element's name attribute
	console.log(message);
	
	if (message == "A username has to be a minimum of 6 characters, can only contain A-Z 0-9 and _ (underscore) and has to start with a letter") {
		message = "has to be a minimum of 6 characters, can only contain A-Z 0-9 and _ (underscore) and has to start with a letter"
	}
	
	var eName = message.substr(0,message.indexOf(' '));
	
	// If the message's first word is the element's name and the element has a title attribute, remove the name from the message and add the title
	// This way we don't depend on the element's name when displaying the error message.
	if (eName = element.name && element.title) {
		message = element.title+" "+message.substr(message.indexOf(' '));
	}
	/* -- end validation using title field -- */
	$('validationmessage').show();
	$('validationmessage').innerHTML = message;

	$( element ).addClassName ( 'errorField' );

   if ( $( element ).hasClassName ( 'fmCheckBox' ) ) {
     $( element ).up ().addClassName ( 'errorLabel' );
   }

	var mylocation = document.location.toString();
	var newloc = mylocation.split('#');
	document.location = newloc[0] + '#validationmessage'; 

   var labels = element.form.getElementsByTagName('label');
   for(var i=0;i<labels.length;i++) {
    
     if (labels[i].htmlFor==element.id) {
        labels[i].style.color = '#cc0000';
     } else {
        labels[i].style.color = labels [ i ].defaultColor;
     }
   }
	
	var et = $$(".errorText");
	for(var j = 0; j < et.length; j++){
		et[j].innerHTML = message;
		$(et[j]).show();
	}
	
	return false;

}


// FOR Media Detail Page commenting when not logged in

/* For Commenting on a mediadetail page; ajax submition. */
/* Because of the MMC when logged in the comment is only ajax when
   a user is not logged in or the user is public. */
function submitComments(mid,login){
	var mid = mid;
	var login = login;
	
	var validator = new FMFormValidate();
	validator.addValidationErrorListener(function(element,message) {
				
		$('errorCaptcha').innerHTML = 'Sorry! Your comment was not submitted. ' + message + '.';
		$('commentsError').show();
		$('commentsError').fade({ duration: 8.0, from: 1, to: 0 });
	});
	
	//creates the url for the post
	if(login == 0){
		var message=document.getElementById("message").value;
		var url  = "/action/v2/addtextcomment?"+$('submitComment').serialize();
	}else{
		var message=document.getElementById("message").value;
		var name=document.getElementById("name").value;
		var email=document.getElementById("email").value;
		var captcha=document.getElementById("captcha").value;
		var url  = "/action/v2/addanonymouscomment?"+$('submitComment').serialize();
		
	}
	if(message == "" || name=="" || email =="" || captcha==false ){
		$('commentsError').show();
		return validator.submit($('submitComment'));	
	}else{
		if(login==1){
			return validator.submit($('submitComment'));
		}
			new Ajax.Request(url, {
				method: 'post',
				onSuccess: function(transport) {
					console.log(transport);
					
				$('comments').show();
				showNewComments(mid, 0);
				Form.reset('submitComment');
				$('comments').delay(10, $('comments').fade({ duration: 4.0, from: 1, to: 0 }));	
			},
			onFailure: function(){
				$('confirm').innerHTML = 'Something went wrong...';
			}
		});
	}
}

function ajaxComments(element, obj) {
	url = "/ajax_comments";
	vars = obj;
	new Ajax.Request(url, {
		method: 'get',
		parameters: vars,
		onSuccess: function(transport) {
			$(element).innerHTML = transport.responseText;
		}
	});

}

//stripes white space for the next function
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
}

//translates the uploadage returned by the {%media.uploadage} variable of the medialist component
// currently it only returns english text
	function uploadageTranslate(da, lang){

		da.each(function(elem, i){
        
        var uploadage = da[i].innerHTML;
        
        if(lang == 'en'){
			da[i].innerHTML = uploadage;
		}else{
			var num = uploadage.indexOf(' ');
			var time = uploadage.substr(0, num);
			var term = uploadage.substr(num);
			
			term = term.trim();
			
			switch (term)
			{
			case 'seconds':
			  var termTranslate = 'seconde';
			  break;
			case 'minutes':
			  var termTranslate = 'minutes';
			  break;
			 case 'hours':
			  var termTranslate = 'heures';
			  break;
			case 'days':
			  var termTranslate = 'jour';
			  break;
			case 'weeks':
			  var termTranslate = 'semaine';
			  break;
			case 'months':
			  var termTranslate = 'mois';
			  break;
			case 'years':
			  var termTranslate = 'annŽe';
			  break;
			default:
			  var termTranslate = term;
			}
			
			da[i].innerHTML = time + ' ' + termTranslate;
		}
        
     });

}
