 AppInit.addEvent(function() {
    
    
    //-- LIST 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);
			});
			
		});
	}

});

	
//-- AJAX THUMBS --//

// Create an Ajax call for the /home and /profile horizontal gallery
// to refresh the thumbnails

function updateGallery(options){

	// Create the variables
	
	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;
	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 container =  $(node);
	
	/*
	var node = node;
	var container =  $(node);
	var page = page;
	var sort = sort;
	var display = display;
	var channel = channel;
	var collection = collection;
	*/
	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 += '&nowrapper';
	
	// If the .loading div was already created, show it.
	//if (container.down('div.loading')) {
		//container.down('div.loading').show();
	//}
	
	// Create the Ajax
	new Ajax.Request(theurl, {
   		method: 'get',
   		onSuccess: function(transport) {
     		setTimeout(function(){
     			// Replace the container's content with the new content
         		container.innerHTML = transport.responseText;
         		
         		// Add the loading div then hide it.
         		//container.innerHTML += '<div class="loading"><img src="http://assets.dev.filemobile.com/96/loading.gif" alt="Loading"/></div>';
         		//container.down('div.loading').hide();
			}, 0);
		}
	});
}

//-- AJAX RATING --//

function rateMedia(node, rating, id, updateThis) {
	
	// node = the id name of the button
	// rating = 10 for rating up, 0 for rating down
	// id = the media id number being rated
	// updateThis = the id of the box that holds the rating count
	
	// Create the variables
	var element = $(node);
	var rating = rating;
	var id = id;
	var updateThis = updateThis;
	
	//
	element.setStyle({
	   	cursor: 'auto',
    	opacity: '0.5'
	});

	// Make the rateFile request. using 'returnData' allows for all the media.getInfo to be returned in the next function
	jsonRequest ( 'media.rateFile', { 'id': id, 'rating': rating, 'returnData': true }, function (result) { 
		
		// If using thumb up / thumb down rating, you have to do a little math
		//var rResult = Math.round(((result.rating * result.votecount) - (result.votecount * 5)) / 5);
		// Or if just using 'likes'...
		var rResult = result.votecount;

		// Fade out the number, change it, then fade it back in
		new Effect.Fade ( $(updateThis).down(0), { duration: 0.5, from: 1, to: 0.01,
 			'afterFinish': function () {
 				if (rResult > 0) {
 					//rResult = "+"+rResult;
 				}
 				$(updateThis).down(0).innerHTML = rResult;
 				$(updateThis).down(0).fade({ duration: 0.5, from: 0.01, to: 1 });
 			}
 		});
	
	}, function () { 
	
		// If there was an error
		console.log ('There was an error rating this media'); 
		
	}, true );
	
}



//--AJAX Favourites --/

function favMedia(id) {
	
	var id = id;

	jsonRequest ( 'media.addToFavorites', { 'mid': id, 'returnData': true }, function (result) { 

		//console.log(results);

		$('addedtofav').show();
		$('addedtofav').fade({ duration: 0.5, from: 0, to: 1});
		setTimeout("$('addedtofav').fade ({ duration: 0.5, from: 1, to: 0 })",4000);
	
	}, function () { 
	
		// If there was an error
		alert ( 'oops' ); 
		
	}, 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'; */
	$(element).previousSiblings()[0].scrollTo();
	document.location = '#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) {

	/* -- 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);
	/* -- end validation using title field -- */
		
	// 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'; */
	$(element).previousSiblings()[0].scrollTo();
	document.location = '#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);
		var n = $(element).previousSiblings()[0];
		//and if not this is for list forms
		if(!n){
			var n = $(element).previousSiblings()[0];
		}
	}
	
	$(element.id).addClassName('errorField');
	
	if(!n){n = 'captcha';}
	var title = String(n.innerHTML);
	var o = n.innerHTML;

	console.log(n);
	
	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);
	});
}

/* 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'; */
	$(element).previousSiblings()[0].scrollTo();
	document.location = '#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 showNewComments(mid, submit, page){
	var page = page;
	if(submit == 0){
		if (!url){
			var url  = '/ajaxcomment?media_id=' + mid;
		} else {
			var url = url;    
		}
	}else{
		var url  = '/ajaxcomment?media_id=' + mid + "&page=" + page;
	}
    
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(transport) {
	setTimeout(function(){	
            $('commentHolder').innerHTML = transport.responseText;
	    
	        // Add the loading div then hide it.
         	 $('commentHolder').innerHTML += '<div class="loading"><img src="http://assets.dev.filemobile.com/96/loading_large.gif" alt="Loading"/></div>';
         	 $('commentHolder').down('div.loading').hide();
		}, 0);
        }
    });    
}
