

var NicheSite = {
	
	basePath:	null,
	isLoading: false,
	hasInit: true,
	ajaxLinks: true, // enable ajax-ification of all links
	
	onReady:	function()
	{
		
		//	Set base path
		NicheSite.basePath = $('script[@src*=/js/]:first').attr('src').split('/js/')[0];
		NicheSite.basePath = document.location.protocol + '//' + document.location.host;
		
		//	Disable ajaxification, if old version of safari
		if ($.browser.safari && (parseFloat($.browser.version) < 3.0)) {
			NicheSite.ajaxLinks = false;
		}
		
		Lightbox.autohideElements = 'select, embed[id!=soundtrax], object[id!=soundtrax]';
		Lightbox.onHideElements = function()
		{
			$('embed, object').css('visibility','hidden');
		}
		Lightbox.onShowElements = function()
		{
			$('embed, object').css('visibility','visible');
		}
		
		for (var selector in this.elements)
		{
			var $elms = $(selector);

			if ($elms.size() > 0)
			{
				this.elements[selector]($elms);
			}
		}
		
		
		for (var selector in this.repeatables) {
			var $elms = $(selector);

			if ($elms.size() > 0) {
				this.repeatables[selector]($elms);
			}
		}
		
		/*
		if ( document.location.hash.match(/#\/.+/))
		{
			NicheSite.loadPage( document.location.hash.replace('#', '') );
		}
		*/
				
		if (NicheSite.ajaxLinks) {
			$.historyInit(
				function(hash) {
					if ( (NicheSite.hasClicked) || (hash.length > 1) ) {
						if (hash == null) hash = '';
						hash = NicheSite.basePath + hash; 
					
						NicheSite.loadPage(hash);
						NicheSite.hasClicked = false;
					}
				}
			);
		}

		NicheSite.hasClicked = true;
		
		
	},
	
	loadPage: function(url)
	{
		baseUrl = url.match(/http:\/\/.*?\//);
		
		//	Fix Home on the nav menu
		if ((url == null) || (url == "") || url == '/') url = '/news';
		
		//	This seems to fix IE borking out on visiting, e.g:,
		//	http://niche/artists/ffd#/artists/ffd
		//	(Gives a broken page on the hash page load)
		if ($.browser.msie)
		{
			request_url = url + '/?cachebust=' + Math.random();
		}
		else
		{
			request_url = url;;
		}
		
		this.isLoading = true;

		$('#site_container').append('<h2 id="tmp" style="display:none;">Content goes here</h2>').children('#tmp').load(
			request_url,
			'',
			function(response)
			{
				// alert('we loaded page: ' + request_url);
				
				if ($('#tmp > #page_container').size() == 0)
				{
					$('#tmp').html(response);
				}
				
				// $('#site_container > #page_container').empty().html($('#tmp > #page_container').html());
				// $('#site_container > #nav').empty().html($('#tmp > #nav').html());
				
				//$('#site_container > #page_container').empty().append($('#tmp > #page_container'));
				//$('#site_container > #nav').empty().append($('#tmp > #nav'));
				
				$('#site_container > #page_container').replaceWith($('#tmp > #page_container'));
				$('#site_container > #nav').replaceWith($('#tmp > #nav'));
			
				
				$('#tmp').empty().remove();
				
				NicheSite.isLoading = false;
				NicheSite.setLinksToAjax();
				
				//	Re-apply Lightbox
				Lightbox.updateImageList();

		
				//	Re-apply repeatables
				for (var selector in NicheSite.repeatables)
				{
					var $elms = $(selector);
		
					if ($elms.size() > 0)
					{
						NicheSite.repeatables[selector]($elms);
					}
				}
				
				//	Add hash to URL
//				var hash_url =  '#' + url.replace(NicheSite.basePath,'');
//				document.location.hash = hash_url;
				
				//	Set window scrollbar to top
				$('html,body').attr('scrollTop', 0);
			}
		
		 );
	},
	
	setLinksToAjax: function()
	{
		$('#nav a, #page_container a').not('[href$=".mp3"]').not('[href$=".flv"]').unbind().click(function(event)
		{
			var internalRegex = new RegExp("^(/|" + NicheSite.basePath + ")");
			
			if (this.href.match(internalRegex) )
			{
				// internal url
				
				if (NicheSite.isLoading) return false;
			
				//	Check target is not set
				if (!(this.target.length > 0) && ($(this).attr('rel') == null))
				{
					var hostRegex = new RegExp("^" + NicheSite.basePath);
					NicheSite.hasClicked = true;
					var url = this.href.replace(hostRegex, '');
					
					$.historyLoad(url);
					//NicheSite.loadPage( this.href);
					
					return false;
				}
			}
			else
			{
				// external url
				return true;
			}
			
		});
	},
	
	elements:	
	{
		//	Files functionality
		'.admin_template input.file': function($elms)
		{
			var duplicateInput;
			duplicateInput = function()
			{
				$(this).clone().insertAfter($(this)).val('').attr('name', $(this).attr('name').replace(/Attachment]\[[a-z0-9]*?]/, 'Attachment][' + Math.floor(Math.random()*1000000 + 100) +']' )).one('change', duplicateInput);
				
			};
			
			$elms.one('change',
				duplicateInput
			);
		},
		
		//	Editor functionality
		'.admin_template textarea.editor': function($elms)
		{
			var fckeditor_base_path = NicheSite.basePath + '/js/fckeditor/';
			var styles_path = $('link[@href$=.css]:first').attr('href');
			
					$elms.each(
						function()
						{
							
							var editor = new FCKeditor( this.id ) ;
							editor.BasePath	= fckeditor_base_path ;
							editor.Config['EditorAreaCSS'] = styles_path;
							editor.ToolbarSet = 'Basic';
							editor.Height = 250;
							editor.ReplaceTextarea() ;
						}
					);
				
			
		},
		'#soundtrax': function(elm)
		{
			if (SWFObject)
			{
				var width = 175;
				var height = 25;
	
				var so = new SWFObject(NicheSite.basePath + "/app/webroot/files/soundtrax.swf", "soundtrax_movie", width, height, "8", "#cccccc");
				
				so.addParam('scale','noScale');	
				
				so.addVariable('template', 'none');
				
				so.write("soundtrax");
				so = null;
				
				//	Since soundtrax is playing, dynamically load any links to prevent a full page load
				if (NicheSite.ajaxLinks) {
					NicheSite.setLinksToAjax();
				}
			}			
		}
	},
		
	repeatables:	
	{
		'.feature_page_image':	function($elms)
		{
			//$('ul', $elms).innerfade({ speed: 'slow', timeout: 5000});
			$('ul', $elms).cycle({ 
			    fx:    'fade', 
			    pause:  5 
			});
		},
		
		'#page a[@href^="http://youtube.com"], #page a[@href^="http://www.youtube.com"]': function($elms)
		{
//			$(document).ready(function(){
			    $elms.flash(
			        { height: 260, width: 350, bgcolor: '#000000' },
			        { version: 8 },
			        function(htmlOptions) {
			            $this = $(this);
			            htmlOptions.src = $this.attr('href');
			            $this.before($.fn.flash.transform(htmlOptions)).empty();						
			        }
			    );
//			});

		},
		
		'#page a[@href$=".mp3"]': function($elms)
		{
			$elms.click(
				function(e)
				{
					$s = $('#soundtrax_movie');
					if ($s.length > 0)
					{
						$s[0].insertMp3($(this).attr('href'), $(this).attr('title'));
					}
					e.preventDefault();
					e.stopPropagation();
					return false;
				}
			);
			
		}
	}
	
};


$(document).ready( 
	function()
	{
		NicheSite.onReady();
	}
);

