/*
* Title: interlopers.net main site JS
* Author: Simon Smith - http://www.blink-design.net
* Site: http://www.interlopers.net
* Requires jQuery 1.4+
* Note: Written and tested on jQuery 1.4.2
*/


(function( window, $, undefined ) {
	
	var LOPERS = window.LOPERS || {};
	
	var site = LOPERS.mainSite = {
		
		init : function() {
		
			// Small jQuery tasks
			
			$('#content').find('a[rel=highslide]').addClass('highslide');
			
			$('#top').delegate('a', 'click', function(e) {
				
				$('html, body').animate({scrollTop:0}, 'slow'); 
				e.preventDefault();
				
			});
			
			// Seperate method calls
							
			this.clearInput('#tutorial-search');
			this.tutorialImage();
			this.mapBattleBox();
			this.advancedSearch.init();
			this.applyHighslideClass( '#news img.news_image', 'a[href^="http://www.interlopers.net"]' );
			this.applyHighslideClass( '#portfolio-display img.gen_img' );
			this.contactForm.init();
			this.ratePortfolio();
			
			// Tutorial Search page
			this.ajaxSearch.init({
				form : $('#search-results'),
				results : '#results',
				spinnerID : 'search-loading'
			});
			
			// Portfolio Search page
			this.ajaxSearch.init({
				form : $('#portfolio-search'),
				results : '#portfolio-wrap',
				spinnerID : 'portfolio-loading'
			});
			
		},
		
		clearInput : (function() {

			var replaceText = function( elem, text ) {

				elem.focus(function() {

					if ( this.value === text ) {

						this.value = '';

					}

				}).blur(function() {

					if ( this.value === '' ) {

						this.value = text;

					}

				});

			}

			return function( elem, text ) {

				if ( elem === undefined ) { // Make sure we have an element to deal with

					throw 'Target element not supplied. Pass string or jQuery object';

				}

				elem = (elem.constructor === 'Object') ? elem : $(elem); // Is the element a string or object?

				if ( text === undefined ) { // If no text string passed, use whatever the value attribute is set to...

					replaceText( elem, elem.val() );

				} else { // ...otherwise set it to text argument

					elem.val(text);

					replaceText( elem, text );

				}

			}

		})(),
		
		tutorialImage : function() {
				
			var images = $('#content').find('img.tutorial-image');
			
			var imgElem = $('<div/>', {
				'class' : 'tutorial-image-wrap'
			});
			
			images.wrap(imgElem);
			
		},
		
		mapBattleBox : function() {
				
			var battleBox = $('#latest-battle');
			
			$('body').delegate('', 'click', function(e) {
				
				var current = $(e.target), speed = 450;
				
				if ( current.parents('#current-battles').length > 0 ) { // We have clicked the battle link or elements inside it
					
					( battleBox.is(':visible') ) ? battleBox.hide(speed) : battleBox.show(speed);
					
					e.preventDefault();
					
				} else if ( battleBox.is(':visible') ) { // User has clicked elsewhere but only act if box is open
					
					battleBox.hide(speed);
					
				}
				
			});
			
		},
		
		advancedSearch : (function() {
			
			var setupContainer = function( id, target ) {
				
				var container = $('<div/>', {
					'id' : id
				});
				
				target.before(container);
				
			}
			
			var closeForm = function(form) {
				
				form.slideUp(function() {
					$(this).empty();
					site.advancedSearch.searchLink.text('Open Advanced Search');
				});				
				
			}
			
			var cleanUp = function() {
				
				$('#loading').remove();
				site.advancedSearch.searchLink.text('Close Advanced Search');
				
			} 
			
			var insertSearchForm = function(data) {
					
				var formContainer = $('#ajax-search-container');
				var form = $(data).find('#content div.advanced-search').html();
				
				formContainer.html(form).slideDown();
					
			}
						
			return {
			
				init : function() {
					
					var that = this;
					this.infoBar = $('#info-bar');
					this.searchLink = this.infoBar.find('form p a');
					
					this.searchLink.text('Open Advanced Search');
					setupContainer('ajax-search-container', this.infoBar);
					
					this.searchLink.live('click', function(e) {
						
						var self = $(this),
							url = self.attr('href'),
							formContainer = $('#ajax-search-container');
						
						if ( formContainer.is(':visible') ) { // If the form is already open..
							closeForm(formContainer);
							return false;
						}
						
						$.ajax({
							type : 'POST',
							dataType : 'html',
							url : url,
							beforeSend : that.addSpinnerToPage( that.searchLink.parent(), 'loading', 'images/site/ajax-loader.gif', '<p/>' ),
							success : insertSearchForm,
							complete : cleanUp
						});
						
						e.preventDefault();
						
					});
					
				},
				
				addSpinnerToPage : function( target, id, imgPath, type ) {
					
					//util.strict( [Object, String, String, String], arguments );
					
					var spinnerImg = $('<img/>', {
						'src' : imgPath
					});
					
					var container = $(type, {
						'id' : id
					});
					
					container.html(spinnerImg);
					target.after(container);
					
				}
				
			}
			
		})(),
		
		contactForm : {
			
			init : function() {
				
				this.form = $('#contact');
				this.message = $('#message');
				
				this.createElements();

				if (!this.message.length > 0) {
					this.form.before(this.errorWrap);
				}
				
				this.sendForm();
				
			}, 
			
			sendForm : function() {
				
				var that = this;
				
				this.form.submit(function(e) {
					
					var self = $(this),
						str = self.serialize(),
						path = self.attr('action'),
						message = $('#message');
						
					$.ajax({
						type : 'POST',
						url : path,
						data : str + '&submit=Send',
						dataType : 'html',
						beforeSend : function() {
							message.slideUp('fast');
							that.form.after(that.loadingText);
							$('#loading-text').fadeIn();
						},
						success : function(data) {
							
							var response = $(data).find('#message').html();
							
							message.html(response).hide().slideDown('fast');
							
							$('#loading-text').fadeOut('fast', function() { 
								$(this).remove(); 
							});
							
							if (message.find('p.success').text() === 'Your email has been sent!') {
								that.form.slideUp('fast', function() { 
									that.form.remove();
								});
							}
							
						}
					});
				
					e.preventDefault();
						
				});
					
			},
			
			createElements : function() {
				
				this.errorWrap = $('<div/>', {
					id : 'message'
				});
				
				this.loadingText = $('<p/>', {
					id : 'loading-text',
					text : 'Sending...'
				});
				
			}
			
		},
		
		ratePortfolio : (function() {
			
			return function() {
				
				var rateBox = $('#rate-box'),
					form = $('#rate-portfolio'),
					ratingText = rateBox.find('h3 + p'),
					statBoxRating = $('#portfolio-stats').find('td').eq(2);
				
				form.submit(function(e) {
					
					var self = $(this),
						str = self.serialize(),
						path = self.attr('action');
						
					$.ajax({
						type : 'POST',
						url : path,
						data : str,
						dataType : 'html',
						beforeSend : function() {
							
							ratingText.append('<img src="images/site/spinner.gif" class="rating-spinner" alt="" />');
							
						},
						success : function(data) {
				
							var topRating = $(data).find('#portfolio-stats td:eq(2)').html(),
								bottomRating = $(data).find('#rate-box h3 + p').html();
								
							ratingText.html(bottomRating);
							statBoxRating.html(topRating);
															
						}
					});							
					
					e.preventDefault();
					
				});
				
			}
			
		})(),
		
		applyHighslideClass : (function() {
			
				var applyClass = function(link) {

					if ( link.length > 0 ) {

						link.attr({
							'class' : 'highslide',
							rel : 'highslide'
						});

					}

				}
				
				return function( image, url ) {
				
					image = ( image.constructor === 'Object' ) ? image : $(image);
					var that = this;
				
					image.each(function() {
					
						var link = (url === undefined) ? $(this).parent('a') : $(this).parent(url);
						applyClass(link);
					
					});
				
				}
				
			})()
							
	}	
		
	
	site.ajaxSearch = $.extend({}, site.advancedSearch); // Inherit public spinner methods from advancedSearch
	
	site.ajaxSearch.init = function(opts) {
		
		var that = this;
		
		opts.form.submit(function(e) {
			
			var self = $(this),
				str = self.serialize(),
				path = self.attr('action');
				
			$.ajax({
				type : 'POST',
				url : path,
				data : str,
				dataType : 'html',
				beforeSend : that.addSpinnerToPage( self.find('input[type=submit]'), opts.spinnerID, 'images/site/spinner.gif', '<div/>' ),
				success : function(data) {
					
					var response = $(data).find(opts.results).html();
					$(opts.results).empty().hide().html(response).fadeIn();
					
				},
				complete : function() {
					$('#' + opts.spinnerID).remove();
				}
			});
			
			e.preventDefault();	
			
		});
		
	}

	// Utility methods
	
	/*util = LOPERS.utils = { 
		
		strict : function( types, args ) { // Used to ensure methods recieve correct argument types and amounts
			
			if (types.length != args.length) {
				throw 'Invalid number of arguments. Expected ' + types.length + ' but received ' + args.length + ' instead!';
			}
			
			for (var i = 0; i < args.length; i++) {
				if (args[i].constructor != types[i]) {
					throw "Invalid argument type. Expected " + types[i].name + ' but received ' + args.constructor.name + ' instead.';
				}
			}
	
		}
	
	}*/
	
	window.LOPERS = LOPERS;
	
})( window, jQuery );

LOPERS.mainSite.init();

// Highslide settings
hs.graphicsDir = 'images/site/hs/';
hs.showCredits = false;
