 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');
            var t = i.readAttribute('name');
            
            // 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(page, node, sort, display, channel, collection, pagesize){

	// Create the variables
	var node = node;
	var container =  $(node);
	var page = page;
	var sort = sort;
	var display = display;
	var channel = channel;
	var collection = collection;
        var pagesize = pagesize;
	
	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 + '&sort=' + sort + '&page=' + page + '&pagesize=' + pagesize  + c +'&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;
         		
                //alert(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' );
        } );
    }
    );


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);
	
	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;
     }
   }

}

if ($('validationmessage')) {
	$('validationmessage').hide();
}




