var boxOptions = {
    'overlayShow': false,
    'transitionIn': 'elastic',
    'transitionOut':'elastic',  
    'speedIn': 200, 
    'speedOut': 200,
    'easingIn' : 'swing',
    'easingOut': 'swing',
    'centerOnScroll': true,
    'modal': true,
    'width': 332,
    //'height': 403,
    'height': 450,
    'padding': 0,
    'showCloseButton': false
};


var Site = {
		
	fullBaseUrl: null,
	isStarted: false,
	isLoading: false,		//	true when loading content
	enableAjaxLinks: (document.location.host.indexOf('.local') >= 0) ? false : false,	//	enable ajaxification of links
	hasLoaded: false,		//	true after window.onload 
	formData: null,			//	stores form data
        messages: null,			//	stores current message list (empty by default)
	
	onReady: function() {

		this.setTimezoneCookie();

		// Set base path
		this.fullBaseUrl = document.location.protocol + '//' + document.location.host;

		//	Disable ajaxification, if old version of safari
		if ($.browser.safari && (parseFloat($.browser.version) < 3.0)) {
			Site.enableAjaxLinks = false;
		}

		//	Disable animations in IE <= 7, they are too slow and behave badly with PNGs
		if ($.browser.msie && ($.browser.version < 8)) {
			$.fx.off = true;
		}

		//	Apply element behaviors
		for (var selector in this.elements) {
			var $elms = $(selector);

			if ($elms.size() > 0) {
				this.elements[selector]($elms);
			}
		}

		//	Apply module behaviors
		for (var selector in this.modules) {
			var $elms = $(selector);	
			
			if ($elms.size() > 0) {
				this.modules[selector]($elms);
			}
		}
		
		//	Prevents $.history.init() from calling loadPage on init
		Site.hasLoaded = false;
		$(window).bind('load', function() {
			Site.hasLoaded = true;
		});

		//	Configure history plugin to use Site.loadPage()
		if (Site.enableAjaxLinks) {
			$.history.init(
				function(hash) {
					//	Prevent history plugin from trying to load home page on init
					//	but still allow hashed URLs to travel to true destination page
					if ((hash == '' || hash == null || hash == '!') && !Site.hasLoaded) {
						return;
					}

					// #!/foo/bar URLs are given to us (via hash) as '!/foo/bar'.
					// Strip this character off before constructing the path.
					// (This should already be done, but is here just in case.)
					if (hash.charAt(0) == '!') {
						hash = hash.substr(1);
					}
					
					//	Allow us to return to the originating page
					if (!hash) {
						hash = document.location.pathname;
					}
					
					hash = Site.fullBaseUrl + hash;
					
					Site.loadPage(hash, Site.formData);
					Site.formData = null;
				}
			);
		}
	},

	loadPage: function(url, data) {
		//	Fix Home on the nav menu
		if ((url == null) || (url == "") || url == '/') url = '/';
		
		//	This seems to fix IE borking out on visiting, e.g:,
		//	http://localhost/artists/ffd#/artists/ffd
		//	(Gives a broken page on the hash page load)
		if ($.browser.msie) {
			url = url + '/?cachebust=' + Math.random();
		}
		
		//	Fix data
		var postData = '';
		if (data != null) {
			postData = {};
			for (var index in data) {
				postData[data[index]['name']] = data[index]['value'];
			}
		}
		
		Site.setLoading(true);
		
		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		params = data;
		if ( params ) {
			// If it's a function
			if ( $.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;

			// Otherwise, build a param string
			} else if ( typeof params === "object" ) {
				params = $.param( params, $.ajaxSettings.traditional );
				type = "POST";
			}
		}


		// Request the page
		var $site = $('#site .page');
		$.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			complete: function( res, status ) {

				// If successful, inject the HTML into all the matched elements
				if (status === "success" || status === "notmodified") {

					Site.setLoading(false);

					//	Remove scripts to avoid "Permission Denied" errors in IE
					//	Remove comments to avoid buggy behavior with jQuery.append() in IE8
					var content = res.responseText.replace(/<script(.|\s)*?\/script>/gi, "").replace(/<!--(.|\s)*?-->/gi, "");

					// Create a dummy div to hold the results, and inject the contents of the document in
					var $content = $("<div />").append(content);

					//	Cleanup
					content = null;
					res = null;
					
					//	Find selector in content
					var newSite = $content.find('#site:first');
					var $newSite = $content.find('#site:first .page');
					var newSiteHeader = $content.find('#site:first .page > .header');
					var newSiteContent = $content.find('#site:first .page > .content');
					var newSiteFooter = $content.find('#site:first .page > .footer');
					
					if ($newSite.length) {
						//	Replace site contents
//						$site.replaceWith($newSite);
						jQuery("#site").attr("class", newSite.attr("class"));
						$site.find(">.header").replaceWith(newSiteHeader);
						$site.find(">.content").replaceWith(newSiteContent);
						$site.find(">.content").attr("class", newSiteContent.attr("class"));
						$site.find(">.footer").replaceWith(newSiteFooter);
						
						
						//	Apply module behaviors
						for (var selector in Site.modules) {
							var $elms = $(selector);
							
							if ($elms.size() > 0) {
								Site.modules[selector]($elms);
							}
						}
						
						$("body").delegate("a", "click", function(event) {
							return Site.handleLinkClick(event);
						});
						
						
						
						//	Set window scrollbar to top
						$('html,body').attr('scrollTop', 0);
					}
					else {
						//	Find error messages in the content or find redirects?
						var $redirect = $content.find('#ajax-redirect');
						if ($redirect.length) {
							var url = $redirect.attr('href');
							// Trim base url
							if (url.indexOf(Site.fullBaseUrl) == 0) {
								url = url.substring(Site.fullBaseUrl.length);
							}
							$.history.load(url);

						} else {
							// It's all gone wrong; cancel loading with an error
							Site.setLoading(false, "There was an error loading that page.");
						}
					}
				}
			},
			error: function(res, status, errorThrown) {
				// Interrupted requests
				Site.setLoading(false, "There was an error loading that page.");
			},
            success: function (res, status, httpRequest) {

                if (httpRequest.readyState == 4) {
                    if (httpRequest.status == 200) {
                        var url = document.location.hash.substr(1);
                        pageTracker._trackPageview(url);
						
                        //Reinitialize the facebook button
                        window.addFacebookButtonScript();

                        Site.setLoading(false);
                    }
                }
            }
		});
		
	},
	
	setLoading: function(isLoading, error) {
		Site.isLoading = isLoading;
		var $content = $('.content:first');

		var $overlay = $content.find('.page-overlay');
		var createOverlay = function(){
			return $('<div class="page-overlay" />').prependTo($content);
		};

		if (isLoading) {
			$('#site').addClass('preloader');
			if (!$overlay.length) {
				//	Overlay doesn't exist; create it.
				$overlay = createOverlay();
			}
		}
		else {
			var removeOverlay = function(){
				$('#site').removeClass('preloader');
				$('.content:first .page-overlay:first').remove();
			};

			if (error != undefined) {
				if (!$overlay.length) {
					$overlay = createOverlay();
				}

				// Add an error message that is displayed, then fades away after a brief pause.
				var $error = $('<div class="page-overlay-error"><span></span></div>').appendTo('body');
				$error.find('span').html(error);

				setTimeout(function(){
					$overlay.animate({
						"opacity": 0,
					}, 'slow', 'linear', function(){
						removeOverlay();
						$error.remove();
					});
				}, 1000);
				
			} else {
				// Get rid of it right away.
				removeOverlay();
			}
		}
	},

	displayMessages: function() {
		/* TODO: ?
        if (Site.messages.size() > 0) {
        	
        	var $message = $('#radio-bar-container .messages li:first');
        	
        	if (!$message.length) {
        		return;
        	}
        	
        	var showError = function($message) {
        		
        		if (!$message.length) {
        			return false;
        		}
        		
        		$message.show()
        			.parents('.messages-container')
        			.animate({opacity:"show"}, "slow")
        			.delay(3000)
        			.animate({opacity:"hide"}, "slow")
        			.end()
        			.delay(3500)
        			.animate({opacity:"hide"}, "slow", function() {
        					showError($message.next('li'));
        			});
        	};
        	
        	showError($message);
        }
		*/
	},

	setTimezoneCookie: function() {
		var offset = ((new Date()).getTimezoneOffset()/60)*(-1);
		var expires = new Date();
		expires.setTime(expires.getTime() + (6 * 30 * 24 * 60 * 60 * 1000)); // 6 months
		$.cookie('tz', offset, {expires: expires, path: '/'});
	},

	truncate: function(text, length) {
		text = String(text);
		if (text.length > length) {
			text = text.substr(0, length-2) + '...';
		}
		return text;
	},
	
	elements: {
		/**
		 * Applies site-wide Ajaxification of links
		 */
		'#site': function($elms) {
			
			if (!Site.enableAjaxLinks) {
				return;
			}
			
			//	Bind to links
			$("body").delegate("a", "click", function(event) {
				return Site.handleLinkClick(event);
			});
			
			/**
			$('a').live(
				'click',
				function(event) {
					return Site.handleLinkClick(event);
				}
			);
			*/
		},
		
		/*** NOT WORKING
                // Autocomplete
                '.multiselect': function($elms) {
                            // Uncomment to enable
                        $elms.fcbkcomplete({
                                cache: false,
                                filter_case: false,
                                filter_hide: true,
                                filter_selected: false,	
                                firstselected: true
                        });

                },
        */
        
        
		/* MP3 player */
		'#radio-player': function($elms) {
			
			//	Initialise player
			// TODO: 
			// old$elms.player();
			
			// moved to layout.ctp
			//var radioPlayerControl = new RadioPlayerControl();
		}
	},

	isInternalSiteLink: function(obj) {
		if (typeof(obj) == 'string') {

			switch (true) {
				case obj.charAt(0) == '#':	// Anchor links
					return false;

				case obj.substr(-4) == '.xml': // XML links
					return false;

				case $.browser.msie && (obj.indexOf('#') !== -1):
					return false;

				case obj.charAt(0) == '/':	// Relative links
					return true;

				case obj.indexOf(Site.fullBaseUrl) == 0:
					return true;			// Same domain links

				default:
					return false;			// All other links
			}
		}
		if ('undefined' == typeof(obj)) {
			obj = $(obj);
		}
		if (obj['jquery']) {
			//	Ignore when target or rel attribute set
			if (obj.attr('target') || obj.attr('rel')) {
				return false
			}

			if (obj.is('a')) {
				return arguments.callee(obj.attr('href'));
			}
			else if (obj.is('form[enctype=multipart/form-data]')) {
				return false;
			}
			else if (obj.is('form')) {
				return arguments.callee(obj.attr('action'));
			}
		}
		return false;
	},

	handleLinkClick: function(event) {

		if (Site.isLoading) return false;
		var $target = $(event.currentTarget);
		if (Site.isInternalSiteLink($target)) {
			var url = $target.attr('href');
			//	Hack to force root page link to work
			if (url == '/') {
				url = '//';
			}
			//	Trim base url
			if (url.indexOf(Site.fullBaseUrl) == 0) {
				url = url.substring(Site.fullBaseUrl.length);
			}
			$.history.load(url);

			event.stopPropagation();
			event.preventDefault();
			return false;
		}

		return true;
	},

	handleFormSubmit: function(event) {

		if (Site.isLoading) return false;
		var $target = $(event.currentTarget);
		if (Site.isInternalSiteLink($target)) {
			var url = $target.attr('action') + '/?cachebust=' + Math.random();
			//	Trim base url
			if (url.indexOf(Site.fullBaseUrl) == 0) {
				url = url.substring(Site.fullBaseUrl.length);
			}
			Site.formData = $target.formToArray();
			$.history.load(url);

			event.stopPropagation();
			event.preventDefault();
			return false;
		}
		return true;
	},
        /**
         *  Return the TRUE path of the page
         *  --if a hash value exists it takes precedence
         **/
        getUriPath : function(){
            var path = document.location.hash.substr(1);
            if(path != ''){
                return path;
            }
            return document.location.pathname;
        },
	
	/**	
	 *  Modules behaviors
	 *  - reinitialised on each Ajax page load 
	 */
	modules: {
			'form': function($elms) {
				if (!Site.enableAjaxLinks) {
					return;
				}

				$elms.bind(
					'submit',
					function(event) {
						return Site.handleFormSubmit(event);
					}
				);
			},
                        '#channel-take': function($elms) {
                            
                          $elms.fancybox(boxOptions);
                          
                          var value = $.cookie('CakeCookie[CLAIM_TOKEN]');
                          var currentPath = window.location.pathname;
                          
                          if(value == currentPath) {
                              if(1 == $('#user-login li.loggedin').length) {
                                  $('#channel-take-logged-in').show();
                              } else {
                                  $elms.show();
                              }
                              
                          }
                          
                        },
                        '.track-podcast-download': function($elms){
                            var path = Site.getUriPath();
                            _gaq.push(['_trackEvent', 'Podcasts', 'Download', path ]);
                            return true;
                        },
                        '.js-hover': function($elms){
                            $elms.hover(
                              function () {
                                $(this).css('opacity', 0.5)
                              }, 
                              function () {
                                $(this).css('opacity', 1);
                              }
                            );
                        },
                        '.scroll-content': function($elms){
                                
                                $('.profile-description .text').jScrollPane();
                                $('.profile-event-list').jScrollPane();
                                $('.profile-mixtape-list').jScrollPane();
                                // Enforce the height of the scroller...
                                //$('.jScrollPaneDrag').css({height: 20+'px'});
                        },
                        '.track-podcast-subscribe': function($elms){
                            var path = Site.getUriPath();
                            _gaq.push(['_trackEvent', 'Podcasts', 'Subscribe', path ]);
                            return true;
                        },
                        // http://thomasbillenstein.com/jTweetsAnywhere
                        '#pulse-home-twitter': function($elms){
                            $('#pulse-home-twitter').jTweetsAnywhere({
                                username: 'pulseradiodjs',
								list: 'djs',
                                count: 10,
                                showTweetFeed: {
                                    showProfileImages: true,
                                    showTimestamp: {
                                        refreshInterval: 3000
                                    },
                                    autorefresh: {
                                        mode: 'trigger-insert',
                                        interval: 30
                                    },
                                    paging: {mode: 'more'}
                                },
                                onDataRequestHandler: function(stats, options) {
                                    if (stats.dataRequestCount < 11) {
                                        return true;
                                    }
                                    else {
                                        stopAutorefresh(options);
                                        //alert("To avoid struggling with Twitter's rate limit, we stop loading data after 10 API calls.");
                                    }
                                }
                            });
                        },
                        // http://thomasbillenstein.com/jTweetsAnywhere
                        '#profile-twitter-box': function($elms){
                            $('#profile-twitter-box').jTweetsAnywhere({
                                username: $('#profile-twitter-box').attr('rel'),
                                count: 10,
                                showTweetFeed: {
                                    showProfileImages: true,
                                    showTimestamp: {
                                        refreshInterval: 3000
                                    },
                                    autorefresh: {
                                        mode: 'trigger-insert',
                                        interval: 30
                                    },
                                    paging: {mode: 'more'}
                                },
                                onDataRequestHandler: function(stats, options) {
                                    if (stats.dataRequestCount < 11) {
                                        return true;
                                    }
                                    else {
                                        stopAutorefresh(options);
                                        //alert("To avoid struggling with Twitter's rate limit, we stop loading data after 10 API calls.");
                                    }
                                }
                            });
                        },
                        '#global_leaderboard_top_right_728x90': function($elms){
                            // fix google dfp
                            $elms.show();
                            $elms.css({
                                'position': 'absolute',
                                'right' : '16px',
                                'top' : '42px'
                            });
                         },
                        '#fb-comments': function($elms){
                        	if (window.FB)
                            	FB.XFBML.parse(document.getElementById('fb-comments'));
                         },
                        '#fb-like': function($elms){
                        	if (window.FB)
                            	FB.XFBML.parse(document.getElementById('fb-like'));
                         },
                        /*'.toggle': function($elms){
                        	$elms.bind('click', function(){
                                    var $base = $(this).parent().attr('rel');
                                    var $type = $(this).attr('rel');
                                    
                                    $("."+$base+"-form").toggle();
                                    console.log($base);
                                    console.log($type);
                                    return false;
                                })
                         },*/
			'.news-snippet':function($elms){

				var $active = $('#twitter ul li.active');
				if ( $active.length == 0 ) $('#twitter ul li:first').slideDown('slow');

                                var refresh_id = setInterval(function() {
				var $active = $('#twitter ul li.active', $elms);
                                if ( $active.length == 0 ) $active = $('#twitter ul li:last', $elms);
                                                $active.slideUp('slow', function() {
                                                        var $next =  $(this).next().length ? $(this).next() : $('#twitter ul li:first', $elms);
                                                        $next.slideDown('slow');
                                                        $(this).removeClass('active');
                                                        $next.addClass('active');
                                                });
                                }, 5000);
				$('#twitter a').attr('target', '_blank');
			},
                        /*
						JOE Edited
						'.header-login':function($elms){
                            
                            $('#sign-up', $elms).fancybox(boxOptions);
                            $('#sign-in', $elms).fancybox(boxOptions);
                            
                            
                        },
                        '.header-welcome': function($elms){
                            $('#view-account', $elms).fancybox(boxOptions);
                        },
						*/
						
						'#user-login': function($elms){
                            $('#view-account', $elms).fancybox(boxOptions);
                            $('#sign-up', $elms).fancybox(boxOptions);
                            $('#sign-in', $elms).fancybox(boxOptions);
                            
                            if($('#upload-trigger', $elms).hasClass('iframe')) {
                               $('#upload-trigger', $elms).fancybox(boxOptions);
                            }
                            
                            
                            //$('#show-about', $elms).fancybox(boxOptions_about);
							
							//Following Followers have modal turned off
							boxOptions_no_modal = boxOptions;
							boxOptions_no_modal['modal']=false;
                            $('.follow-channel-message-login', $elms).fancybox(boxOptions_no_modal);//Used when a user tries to favorite an article/channel/mixtape when not logged in
                        },
                        
						
			
			/*'.header-login':function($elms){
			
				$("input:text, input:password", $elms).example(function(){return $(this).attr('title');});
			
				var updateFormAction = function(e) {
					var value = $(this).val();
					if ((value == '') || (value == $(this).attr('title'))) {
						// DISABLE MEMBER LOGIN
						// $('input:submit', $elms).attr('value', 'SIGNUP');
						$('.submit a', $elms).html('SIGN UP');
					}
					else {
						// DISABLE MEMBER LOGIN
						//$('input:submit', $elms).attr('value', 'LOGIN');
						$('.submit a', $elms).html('LOGIN');
					}
				};
			
				$("input:text", $elms).bind('keypress', updateFormAction).bind('blur', updateFormAction);

			},*/
			
			
			'#UserMeForm .profile-header-update': function($elms) {

                                if ($('.form-profile-inset div.error').length == 0) {
                                    $elms.siblings('.input').slideUp(0);
                                    $elms.siblings('.form-profile-inset').slideUp(0);
                                }
				
				$elms.toggle(
					function() {
						$(this).siblings('.input').slideDown();
						$(this).siblings('.form-profile-inset').slideDown();
					},
					function() {
						$(this).siblings('.input').slideUp();
						$(this).siblings('.form-profile-inset').slideUp();
					}
				);
			},


            '.nav-container': function($elms) {

				$('.nav a', $elms).addClass('highlight').hover(function(){
					$('.nav a', $elms).addClass('unhighlight');
				}, function() {
					$('.nav a', $elms).removeClass('unhighlight');
				});


                $('.nav li', $elms).hover(
                    function (){
                        // Hide any open submenus
                        $('.sub-nav .submenu:visible').hide();

                        // Show my submenu
                        var $parts = $(this).attr('class').split('-');
                        $("#submenu-"+$parts[1]).show();

                    },
                    function () {
                        // Do nothing - allows user to click items in submenu
                    }
                );
            },
			
			
			/*
			 * Mixtape page
			 * 
			 */
			
			'.mixtapes-layout.music-mixtapes':function($elms){
			
					var type_selector = $('#type-selector',$elms).val();
					
					$('#type-selector',$elms).sexyCombo({
						textChangeCallback: function () {
							if (this.getHiddenValue() != type_selector){
                                                            if(true == Site.enableAjaxLinks) {
                                                                $.history.load(this.getHiddenValue());
                                                            } else {
                                                                window.location = this.getHiddenValue();    
                                                            }
							}
							return true;
						}
					});
					
					var genre_selector = $('#genre-selector',$elms).val();
					
					$('#genre-selector',$elms).sexyCombo({
						textChangeCallback: function () {
							if (this.getHiddenValue() != genre_selector){
                                                            if(true == Site.enableAjaxLinks) {
                                                                $.history.load(this.getHiddenValue());
                                                            } else {
                                                                window.location = this.getHiddenValue();    
                                                            }
                                                                
							}
							return true;
						}
					});
					
					
					var sort_selector = $('#sort-selector',$elms).val();
					
					$('#sort-selector',$elms).sexyCombo({
						textChangeCallback: function () {
							if (this.getHiddenValue() != sort_selector){
                                                            if(true == Site.enableAjaxLinks) {
                                                                $.history.load(this.getHiddenValue());
                                                            } else {
                                                                window.location = this.getHiddenValue();    
                                                            }
							}
							return true;
						}
					});
					
					var naturalHeight = 26;
					var padding = 6;
					$('.highlights > ul > li').hover(
						function() {
							var height = padding + $('.secondary-information', this).height();
							$('.title', this).stop(true).animate({
									height: naturalHeight + height,
									marginTop: -height
								}, 300
							);
						},
						function() {
							$('.title', this).stop(true).animate({
									height: naturalHeight,
									marginTop: 0
								}, 300
							);
						}
					);
			},
			
			
			/*
			 * Music: profile page
			 * 
			 */
			
			'.profile-gallery.music-profiles':function($elms){
			
					var type_selector = $('#type-selector',$elms).val();
                                        
					$('#type-selector',$elms).sexyCombo({
						textChangeCallback: function () {
							if (this.getHiddenValue() != type_selector) {
                                                            if(true == Site.enableAjaxLinks) {
                                                                $.history.load(this.getHiddenValue());
                                                            } else {
                                                                window.location = this.getHiddenValue();    
                                                            }
							}
							return true;
						}
					});
					
					var genre_selector = $('#genre-selector',$elms).val();
					
					$('#genre-selector',$elms).sexyCombo({
						textChangeCallback: function () {
							if (this.getHiddenValue() != genre_selector){
                                                            if(true == Site.enableAjaxLinks) {
                                                                $.history.load(this.getHiddenValue());
                                                            } else {
                                                                window.location = this.getHiddenValue();    
                                                            }
							}
							return true;
						}
					});
					
					
					var sort_selector = $('#sort-selector',$elms).val();
					
					$('#sort-selector',$elms).sexyCombo({
						textChangeCallback: function () {
							if (this.getHiddenValue() != sort_selector){
                                                            if(true == Site.enableAjaxLinks) {
                                                                $.history.load(this.getHiddenValue());
                                                            } else {
                                                                window.location = this.getHiddenValue();    
                                                            }
							}
							return true;
						}
					});
			},

			/*
			 * Social event page:
			 * 
			 */
			
			'.social-events':function($elms){
				
						/*------------------------------------------------------
						  Start: Event filtering 
						--------------------------------------------------------*/
							var country_value = $('#country-selector',$elms).val();
							
							$('#country-selector',$elms).sexyCombo({
								emptyText: "Filter by country",
								
								textChangeCallback: function () {
									if (this.getHiddenValue() != country_value){
										$.history.load(this.getHiddenValue());
									}
									return true;
								}
							});
							

							var region_value = $('#region-selector',$elms).val();
							$("#region-selector",$elms).sexyCombo({
								
								emptyText: "Filter by region",
								textChangeCallback: function () {
									if (this.getHiddenValue() != region_value){
										$.history.load(this.getHiddenValue());
									}
									return true;
								}
							});
						
						/*------------------------------------------------------
						  End: Event filtering 
						--------------------------------------------------------*/
	
			},
	

			/*------------------------------------------------------
			  Start: Radio Schedule - Current playing artists
			--------------------------------------------------------*/
			'.radio-home .highlights .artist': function($elms) {
				var naturalHeight = 20;
				var padding = 7;
				$elms.hover(
					function() {
						var height = padding + $('.secondary-information', this).height();
						$('.title', this).stop(true).animate({
								height: naturalHeight + height,
								marginTop: -height
							}, 300
						);
					},
					function() {
						$('.title', this).stop(true).animate({
								height: naturalHeight,
								marginTop: 0
							}, 300
						);
					}
				);
				
			},
			/*------------------------------------------------------
			  End: Radio Schedule - Current playing artists
			--------------------------------------------------------*/
			
			/*------------------------------------------------------
			  Start: Radio Schedule - Nav
			--------------------------------------------------------*/
			'.radio-schedule-container':function($elms) {
				 $('.radio-schedule-nav', $elms).hover(
						function() {
							$('.radio-schedule-days').css('display', 'block');
						},function(){
							$('.radio-schedule-days').css('display', 'none');
		                }
					);
			},
			/*------------------------------------------------------
			  End: Radio Schedule - Nav
			--------------------------------------------------------*/
			
			/*
			 * Homepage:
			 * 
			 */
			
			
			/*------------------------------------------------------
			  Start: Image Slide show on home page
			--------------------------------------------------------*/
			'.slideshow-highlights':function($elms){
					var typo = true;
					var typoMarginTop = 15;
					var imagePaddingBottom = 26;
					var isHomePage = false;
					
					if ($elms.parents('.layout-home').length) {
						typoMarginTop = 0;
						isHomePage = true;
					}
                    else {
						typo = false;
						imagePaddingBottom = 7;
					}

					if (typo && !isHomePage) {
						$('a', $elms).each(
							function() {
								var title = $('img', this).attr('alt');
								$(this).attr('title', Site.truncate(title, 30));
								$('img', this).attr('alt', Site.truncate(title, 30));
							}
						);
					}

					$(".slideshow-highlights").slideViewerPro({ 
						thumbs: 7,  
						autoslide: true,  
						easeTime: 750,
                                                asTimer: 8000,
						typo: typo,
						typoMarginTop: typoMarginTop,
						imagePaddingBottom: imagePaddingBottom,
						galBorderWidth: 0, 
						thumbsBorderOpacity: 0,
						thumbsBorderWidth: 0,
						buttonsTextColor: "#707070", 
						buttonsWidth: 0, 
						thumbsBorderOpacity: 1.0,
						thumbsPercentReduction: 6,
						thumbsActiveBorderOpacity: 1.0, 
						thumbsActiveBorderColor: "", 
						shuffle: false,
						custom_leftThumbnail:true,		//Display thumbnail on left hand side  
						//custom_leftThumbImg:"/img/home-slide-thumbnail-button.jpg",		//Img button
						custom_individualThumbWidth:15,
						custom_totalThumbHeight:120,
						custom_showThumbnailImg: false
						
					}); 
			},
			/*------------------------------------------------------
			  End: Image Slideshow 
			--------------------------------------------------------*/
			
			/*------------------------------------------------------
			  Start: Radio schedule currently playing artists
			--------------------------------------------------------*/
			'.mod-schedule .artist-gallery li a.pic': function($elms) {


				$elms.hover(
					function() {
						var height = 25 + $('.secondary-info', this).height();
						$('.caption', this).stop(true).animate({
								height: height,
								marginTop: -height
							}, 300
						);
					},
					function() {
						$('.caption', this).stop(true).animate({
								height: 0,
								marginTop: 0
							}, 300
						);
					}
				);
			},
			/*------------------------------------------------------
			  End: Radio schedule currently playing artists
			--------------------------------------------------------*/

			/*------------------------------------------------------
			  Start: Radio page schedule currently playing artists
			--------------------------------------------------------*/
			'.radio-home .highlights .artist-gallery li a.pic': function($elms) {

				$elms.hover(
					function() {
						var height = 25 + $('.secondary-info', this).height();
						$('.caption', this).stop(true).animate({
								height: height,
								marginTop: -height
							}, 300
						);
					},
					function() {
						$('.caption', this).stop(true).animate({
								height: 0,
								marginTop: 0
							}, 300
						);
					}
				);
			},
			/*------------------------------------------------------
			  End: Radio page schedule currently playing artists
			--------------------------------------------------------*/


			/*------------------------------------------------------
			  Start: Mixtapes page featured mixtapes
			--------------------------------------------------------*/
			'.mixtapes-layout .highlights li a.pic': function($elms) {

				$elms.hover(
					function() {
						var height = 25 + $('.secondary-info', this).height();
						$('.caption', this).stop(true).animate({
								height: height,
								marginTop: -height
							}, 300
						);
					},
					function() {
						$('.caption', this).stop(true).animate({
								height: 0,
								marginTop: 0
							}, 300
						);
					}
				);
			},
			/*------------------------------------------------------
			  End: Mixtapes page featured mixtapes
			--------------------------------------------------------*/


			/*------------------------------------------------------
			  Start: Radio schedule page, now-playing
			--------------------------------------------------------*/
			'.radio-schedule .now-playing li a.pic': function($elms) {

				$elms.hover(
					function() {
						var height = 25 + $('.secondary-info', this).height();
						$('.caption', this).stop(true).animate({
								height: height,
								marginTop: -height
							}, 300
						);
					},
					function() {
						$('.caption', this).stop(true).animate({
								height: 0,
								marginTop: 0
							}, 300
						);
					}
				);
			},
			/*------------------------------------------------------
			  End: Radio schedule page, now-playing
			--------------------------------------------------------*/

			/*------------------------------------------------------
			  Start: Radio schedule navigation
			--------------------------------------------------------*/			
			'.mod-schedule .tracklist': function($elms){
				
				
					var currentDateTime = new Date();
					var currentTimestamp = currentDateTime.getTime();
					var currentDate = currentDateTime.toDateString();
					
					var currentPageIndex = null;
					var records_to_show = 4;
					var init_page = 0;	// Page for current time
					var $list = $('ul li.track', $elms); 	//Collect all track lists
					//console.log($elms);
					$list.eq( records_to_show - 1).nextAll().hide();		//Show the first record group, hide the rest
					
					//Populate nav buttons
					$first_nav_button = $('div.nav ul li:first', $elms); 	//Collect the first button
					$first_nav_button.nextAll().remove();									//remove other buttons
					number_of_buttons = Math.round($list.length / records_to_show);			//count number of buttons to be shown
					for(i=1; i < number_of_buttons; i++){									//Iterate to display button
						$new_button = $first_nav_button.clone(true);
						$new_button.removeClass('selected');			
						$new_button.insertAfter($first_nav_button);

						var pageTimestamp = new Date(currentDate + ' ' + $list.eq(records_to_show*i).find('.time').text()).getTime();
						if ((currentPageIndex == null) && pageTimestamp > currentTimestamp) {
							currentPageIndex = i-1;
						}
					}
					
					//Bind button's click events
					var $nav_buttons = $('div.nav ul li', $elms); 		//Collect all existing buttons
					var start=0;
					$.each($nav_buttons, function(index, $value){
						$(this).bind('click',{start_record: start, records:records_to_show}, function(e){
							
							//Set active state on this button
							$nav_buttons = $('.mod-schedule .tracklist div.nav ul li');
							$nav_buttons.removeClass('selected');
							$(this).addClass('selected');
							
							//Hide all existing tracks
							var $list = $('.mod-schedule .tracklist ul li.track');		//Collect all track lists
							$list.hide();
							
							//iterate to show the records
							last_record_to_show = e.data.start_record +  records_to_show;
							for(i=e.data.start_record; i < last_record_to_show; i++ ){
								$list.eq(i).show();
							}
						
							//stop event
							e.stopPropagation();
							e.preventDefault();
							return false;
						});
						start += records_to_show;
					});
					
					$nav_buttons.eq(currentPageIndex).trigger('click');
			},
			/*------------------------------------------------------
			  End: Radio schedule navigation
			--------------------------------------------------------*/
			
			/*------------------------------------------------------
			  Start: Home Profile Featured Artists
			--------------------------------------------------------*/
			'.mod-profile-featured .artist-gallery li a': function($elms) {
				
				$elms.hover(
					function() {
						var height = 8 + $('.secondary-info', this).height();
						$('.caption', this).stop(true).animate({
								height: 25 + height,
								marginTop: -height
							}, 300
						);
					},
					function() {
						$('.caption', this).stop(true).animate({
								height: 25,
								marginTop: 0
							}, 300
						);
					}
				);
			},
			/*------------------------------------------------------
			  End: Home Profile Featured Artists
			--------------------------------------------------------*/

			/*------------------------------------------------------
			  Start: Home Boxes
			--------------------------------------------------------*/
			'.layout-home': function($elms) {

				// Slide-up hover effect on labels
				var $hotspots = $('.mod-news .primary a, .mod-interviews .primary a, .mod-reviews .primary a, .mod-events .bd a, .mod-gallery .bd a, .mod-comp .bd a');
				$hotspots.each(function() {
					var $label = $('.label', this);
					var fullHeight = $label.height();
					var collapsedHeight = $label.children('h5').height();
					var maxHeight = jQuery(this).parent().height();
					$label.css('height', collapsedHeight+'px').css('visibility','visible');
					$label.find('.link-read-more').css('opacity', 0);
					$label.hover(function() {
						var $label = $(this);
						if (fullHeight > maxHeight) fullHeight = maxHeight - 20;
						$label.stop(true).animate({height: fullHeight}, 300);
						$label.find('.link-read-more').stop(true).animate({opacity: 1.0});
					}, function() {
						var $label = $(this);
						$label.stop(true).animate({height: collapsedHeight}, 300);
						$label.find('.link-read-more').stop(true).animate({opacity: 0.0});
					});
				});

				// Feature switching for interviews, news and reviews
				var $features = $('.mod-news, .mod-interviews, .mod-reviews');
				$features.each(function(){
					var $feature = $(this);
					$('li > a', $feature).click(function(e){
						$feature.find('.bd > .primary:not(:animated)').fadeOut(300, function() {$(this).remove();});

						var $content = $(this).siblings('.primary').clone(true);
						$content.prependTo($feature.find('.bd')).fadeIn(300);

						e.preventDefault();
						e.stopPropagation();
						return false;
					});
				});

			},
			/*------------------------------------------------------
			  End: Home Boxes
			--------------------------------------------------------*/

			/*------------------------------------------------------
			  Start: Home Mixtape Tracklist Module
			--------------------------------------------------------*/
			'.layout-home .mod-mixtapes.featured .tracklist .track, .layout-home .mod-mixtapes.latest .tracklist .track':function($elms){
				$elms.mouseenter(
					function(event) {
						var thumbUrl = $(this).find('.play > a').attr('thumbUrl');
						$(this).parents('.mod-mixtapes').find('.showcase:first img').attr('src', thumbUrl);
					}
				);
			},
			/*------------------------------------------------------
			  End: Home Mixtape Tracklist Module
			--------------------------------------------------------*/
			
			/*------------------------------------------------------
			  Start: Radio Featured Artist
			--------------------------------------------------------*/
			'.radio-featured-artist .highlights': function($elms) {
				var padding = 14;
				$('.artist', $elms).hover(
					function() {
						var height = $('.details > div', this).height();
						$('.details', this).stop(true).css('display', 'list-item').animate({
								height: height + padding
							}, 300
						);
					},
					function() {
						$('.details', this).stop(true).animate({
								height: 0
							}, 300
						);
					}
				);
				
			},
			/*------------------------------------------------------
			  End: Radio Featured Artist
			--------------------------------------------------------*/
			
			/*------------------------------------------------------
			  Start: Radio Toolbar
			--------------------------------------------------------*/
			'#ie6 #radio-bar-container':function($elms){
				
				$( '#radio-bar-container' ).scrollFollow({
					relativeTo: 'bottom',
					offset: 0,
					speed: 1,
					delay: 1
				});
			},
			/*------------------------------------------------------
			  End: Radio Toolbar
			--------------------------------------------------------*/

			/*------------------------------------------------------
			  Start: Resetting message count
			--------------------------------------------------------*/
			'#radio-bar-container a.notifications':function($elms){
                $elms.html('<span>0</span>'); /* html doesn't like being passed 0 or '0' */
                $elms.unbind('click');
			},
			/*------------------------------------------------------
			  End: Resetting message count
			--------------------------------------------------------*/

			/*------------------------------------------------------
			  Start: Rerouting Messages From Main Page to Radio Toolbar
			--------------------------------------------------------*/
			'#site .message':function($elms){
                Site.messages = $elms;
                var messages_container = $('#radio-bar-container .messages-container');
                var messages = $('.messages', messages_container);
                var notifications = $('a.notifications');
                var notifications_count = 0;
                messages.html('');
                if (Site.messages.size() > 0) {
                    Site.messages.each(function(){
                        $('p, li', this).each(function() {
                            $('<li></li>').html($(this).html()).appendTo(messages).hide();
                            notifications_count++;
                        });
                    });
                    notifications.html('<span>' + notifications_count + '</span>');
                    Site.displayMessages();
                    notifications.bind('click', Site.displayMessages);
                } else {
                    notifications.bind('click', function() {/* do something here if you like */});
                }
			},
			/*------------------------------------------------------
			  End: Rerouting Messages From Main Page to Radio Toolbar
			--------------------------------------------------------*/
                
			/*------------------------------------------------------
			  Start: AddThis functionality
			--------------------------------------------------------*/
			'.addthis_button': function($elms) {
                var url = document.location.protocol + '//' + document.location.host + document.location.hash.substr(1);
                $elms.each(function(){
                    $(this)
                    .mouseover(function(){return addthis_open(this, '', url, '[TITLE]')})
                    .mouseout(function(){addthis_close()})
                    .click(function(){return addthis_open(this, '', url, '[TITLE]')});
                });

			},
			/*------------------------------------------------------
			  End: AddThis functionality
			--------------------------------------------------------*/

			/*------------------------------------------------------
			  Start: Signout
			--------------------------------------------------------*/
			'div.header-welcome div.submit': function($elms) {
                $('input', $elms).click(function() {
                    window.location = '/users/logout';
                });

			},
			/*------------------------------------------------------
			  End: signout
			--------------------------------------------------------*/

			/*------------------------------------------------------
			  Start: Home page feature switch
			--------------------------------------------------------*/
			'.feature-switch': function($elms) {
                $('.switch li a', $elms).click(
					function(e) {
                        
                        e.preventDefault();
                        e.stopPropagation();

                        var the_switch = $(this).parentsUntil('.feature-switch').filter('.switch');

                        the_switch.siblings('div.active').fadeOut('slow').removeClass('active');
                        the_switch.siblings('div#'+$(this).attr('rel')).fadeIn('slow').addClass('active');

                        $(this).parent().siblings().removeClass('first');
                        var current_hidden = $(this).parent().siblings('.hidden');
                        $(this).parent().after(current_hidden).hide().removeClass('active').addClass('hidden');
                        current_hidden.show().removeClass('hidden').addClass('active');
                        $(this).parent().siblings('.active').first().addClass('first');

					}
				);

			},
			/*------------------------------------------------------
			  End: Home page feature switch
			--------------------------------------------------------*/

			/*------------------------------------------------------
			  Start: Artist Profile Mixtape Share Buttons
			--------------------------------------------------------*/
			'.music-profile .profile-mixtapes .profile-mixtape-list,#manage-mixtapes .profile-mixtapes .profile-mixtape-list': function($elms) {

				/* Panel Animation */
				var animation = 'swing';
				var openClass = 'open';
				var openRightPx = 54;
				var closeRightPx = -432;

				var closePanel = function($target) {
					$target.animate({'right': closeRightPx}, 'fast', animation, function(e){
						$target.css('display', 'none');
						$target.removeClass(openClass);
					});
				};
				var togglePanel = function($target) {
					if ($target.hasClass(openClass)) {
						closePanel($target);
					} else {
						$target.css('display', 'block');
						$target.animate({'right': openRightPx}, 'fast', animation, function(e){
							$target.addClass(openClass);
						});
					}
				};

				$pmix = $elms.find('.p-mix');
				$pmix.find('a.button.share-trigger').click(function(e){
					e.preventDefault();

					// Close all the existing panels
					closePanel($pmix.find('.share-platforms.open'));

					// Open 
					togglePanel($(this).closest('.p-mix').find('.share-platforms'));
				});

				/* Bit.ly / "Make it Shorter" buttons */
				$pmix.find('.share-code-shorten').click(function(e){
					var targetInput = $(this).closest('div.link').find('input.share-link');
					var urlToShorten = targetInput.val();
					targetInput.addClass('loading');
					targetInput.val(''); // clear the box

					var apiHandler = new APIHandler({
						Url: '/web_services/bitly_shorten',
						Method: APIMETHODS.GET,
						Data: {url_to_shorten: urlToShorten},
						Async: true,
						Callback: function(response){
							targetInput.removeClass('loading');
							if (response.result && response.value.url != undefined) {
								targetInput.val(response.value.url);
							} else {
								targetInput.val(urlToShorten); // Restore the original.
							}
						}
					});
				});
			}
			/*------------------------------------------------------
			  End: Artist Profile Mixtape Share Buttons
			--------------------------------------------------------*/

			
			/*------------------------------------------------------
			  Start: Gradient Rollover states - now depdendent on ccs psuedo
			--------------------------------------------------------*/
			/*'.rollover-gradient-list': function($elms) {
              $('.item', $elms).hover(
					function() {
						$(this).addClass ('active');	
					},function(){
		                $(this).removeClass ('active');	
	                }
				);
			}*/
			/*------------------------------------------------------
			  End: Gradient Rollover states
			--------------------------------------------------------*/

	}
};	

$(document).ready(
	function() {
			Site.onReady();

		}
);


function closeAndGoTo(url) {
    parent.$.fancybox.close();
    if(window.location.pathname != url){
		window.location = url;
    }
}

// Returns the dialogue DOM
function getPopup() {
    var frameName = $('#fancybox-frame').attr('name')
    return window.frames[frameName].document;
}


/*------------------------------------------------------
  j.gilmore: Added JavaScript START
--------------------------------------------------------*/

var formSubmitted	= false;
var formErrors		= false;

$(document).ready(function(){
	//--------------------------------------------------- User Login Menu ---------------------------------------------------
	//Let's move the sub2 menu to the left of the main menu by calculating it's width
	submenu2width = $('#user-login >ul > li > ul > li > ul').css('width');
	$('#user-login ul.sub2').css({'left': '-'+submenu2width, 'width':submenu2width}).addClass('sub2-jquery');
	//Hide the menu with jQuery	
    $('#user-login ul.sub,#user-login ul.sub2').css({'visibility':'visible','display':'none'});;
	
	//Mouse over functions 
	$('#user-login ul > li').hover(function(){
		$(this).find('ul.sub').stop(true,true).slideDown('fast');
	})

	$('#user-login ul > li.expand').hover(function(){
		$(this).find('ul.sub2').stop(true,true).slideDown('fast');
	})
	
	//Mouse out functions
	$('#user-login ul > li').mouseleave(function(){
		$(this).find('ul.sub').slideUp('slow');
		$(this).find('ul.sub2').slideUp('slow');
	})
	$('#user-login ul.sub2').mouseleave(function(){
		$(this).hide();
	})
	
	//Switching user profiles
	$('#user-login > ul > li > ul > li.expand > ul > li > a').click(function(e) {
		thisHTML = $(this).html();
		thisA = $(this)
		$('#user-login > ul > li.loggedin > a').css({'background-position':'95% 8px'}).html('Switching...');
        e.preventDefault();
		var page = '/web_services/'+thisA.attr('rel');
		$.getJSON(page, function(data) {
			if (data.result==true)
			{
				$('#user-login > ul > li.loggedin > a').css({'background-position':'95% -26px'}).html(thisHTML);
				$('#user-login ul.sub2').slideUp('slow');
				$('#user-login ul.sub').slideUp('slow');
				
				// Refresh the page if the user is on the Manage Channel or Account Settings page
				var urlPath = window.location.pathname;
				switch(urlPath) {
					case "/channel/edit":
					case "/account/edit":
						window.location.reload();
				}
			}
		});
    });
	
	/* --------------------------------------------------- New code to display the submenu pop up -------------------------------------------------- */
    $("ul.topnav > li").hover(function() {
  
        //Following events are applied to the subnav itself (moving subnav up and down)  
        $(this).find("ul.subnav").stop(true,true).slideDown('fast').show(); //Drop down the subnav on click  
		$(this).find('a').addClass('hover');
  
        $(this).hover(function() {  
        }, function(){  
            $(this).find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
			$(this).find('a').removeClass('hover');
        });  
  
        //Following events are applied to the trigger (Hover events for the trigger)  
        }).hover(function() {  
            $(this).addClass("subhover"); //On hover over, add class "subhover"  
        }, function(){  //On Hover Out  
            $(this).removeClass("subhover"); //On hover out, remove class "subhover"  
    });  
	
	//--------------------------------------------------- Channel Edit - Accordian ---------------------------------------------------
	//$("#channel-edit .toggle-display").hide();//Hide elements first
	$("#channel-edit .toggle").click(function() {//If toggle button clicked then open up the content
		thisForm = $(this).next('div');
		$(this).hide();
		//thisForm.css('outline','1px solid red');
		thisForm.slideDown(500);
			//Detect if the form has been changed if so set our variable to acknowledge this
			thisForm.find(":input").change(function() {
				//alert('dirty form');
				form_is_dirty = true;
			});
			
			//Close up the accordian menu once done or saved
			$("#channel-edit .button-done, #channel-edit .account-options .submit input:not(#save-links-form)").click(function() {

				 $(this).parents('div.toggle-display').slideUp(500,function(){
						$(this).parents('div.account-options').find('.toggle').fadeTo(100,1);
					 });
			});
	});

	function displayLessThanGreaterThanCheck(value){
		var regex=/^[^<>]+$/; //^[a-zA-z]+$/
		if(regex.test(value)){
			return true;
		} else {
			return false;
		}
	}

	//Ajax saving of profile data
	function process_save_data(id,data,update_message,error_message){
		if (data.result===true){
			$('.updated-details').html(update_message).slideDown(300).delay(1000).fadeTo(600,0,function(){$('.updated-details').hide().css('opacity','1')});	
			$('#'+id+'-error').slideUp(300);	 
		}else if (data.result===false){
			$('#'+id+'-error').html(error_message + data.msg).slideDown(300);
		}
		else {
			$('#'+id+'-error').html('JSON Error!').slideDown(300);
		}
	}
	
	//Update display title
	$('#channel-edit:not(.channel-apply) #ProfileTitle').keyup(function(e) {
		if (displayLessThanGreaterThanCheck($('#ProfileTitle').val()))
		{
			$('#user-login > ul > li.loggedin > a').html($('#ProfileTitle').val());
			$('#channel-edit > .title > .display-name').html($('#ProfileTitle').val());
			$('#ProfileTitle-error').slideUp(300);
		}
		else
		{
			$('#ProfileTitle-error').html('Sorry - You may not use < or > symbols in user name').slideDown(300);
		}
    });
	$('#channel-edit:not(.channel-apply) #ProfileTitle').change(function(e) {
		if (displayLessThanGreaterThanCheck($('#ProfileTitle').val()))
		{
			$.post("/web_services/save_profile/", {title: $('#ProfileTitle').val()},
			 function(data) {
				 process_save_data('ProfileTitle',data,'\'Display Name\' has been updated','Error Saving \'Display Name\' - ');
			 }, 
			 "json"
			);
		}
    });
	//Update year of birth
	$('#ProfileDateOfBirthMonth,#ProfileDateOfBirthDay,#ProfileDateOfBirthYear').change(function(e) {
		dob = $('#ProfileDateOfBirthYear').val() + "-" + $('#ProfileDateOfBirthMonth').val() + "-" + $('#ProfileDateOfBirthDay').val();
		if ($('#ProfileDateOfBirthYear').val()=="" || $('#ProfileDateOfBirthMonth').val()=="" || $('#ProfileDateOfBirthDay').val()=="")
		{
			//alert('Not a number! '+ dob);
		}
		else
		{
			$.post("/web_services/save_profile/", {date_of_birth: dob},
			 function(data) {
				 process_save_data('ProfileDOBGender',data,'\'Date of Birth\' has been updated','Error Saving Date of \'Date of Birth\' - ');
			 }, 
			 "json"
			);
		}
    });
	//Update gender
	$('#channel-edit:not(.channel-apply) #ProfileSex').change(function(e) {
		$.post("/web_services/save_profile/", {sex: $('#ProfileSex').val()},
		 function(data) {
			 process_save_data('ProfileDOBGender',data,'\'Gender\' has been updated','Error Saving \'Gender\' - ');
		 }, 
		 "json"
		);
    });
	//Update location
	$('#channel-edit:not(.channel-apply) #ProfileLocation').change(function(e) {
		$.post("/web_services/save_profile/", {country_location_id: $('#ProfileLocation').val()},
		 function(data) {
			 process_save_data('ProfileLocation',data,'\'Location\' has been updated','Error Saving \'Location\' - ');
		 }, 
		 "json"
		);
    });
	//Update About Me
	$('#channel-edit:not(.channel-apply) #ProfileContent').change(function(e) {
		$.post("/web_services/save_profile/", {content: $('#ProfileContent').val()},
		 function(data) {
			 process_save_data('ProfileContent',data,'\'About me\' section has been updated','Error Saving \'About me\' section - ');
		 }, 
		 "json"
		);
    });
	
	//Edit links - hides the end two lines, and adds a 'Add More' button to the one above
	var moreButton = jQuery("<span class='add-more'>Add More</span>");
	$(".col-2-layout").find('.linkentry:nth-child(3)').append(moreButton);
	$(".col-2-layout").find('.linkentry:nth-child(4)').append(moreButton).hide();
	$(".col-2-layout").find('.linkentry:nth-child(5)').append(moreButton).hide();
	$(".col-2-layout").find('.linkentry:nth-child(6)').append(moreButton).hide();
	$(".col-2-layout").find('.linkentry:nth-child(7)').hide();
	
	$('.col-2-layout .add-more').click(function() {
		$(this).fadeTo(200,0,function() {$(this).hide()});
		$(this).parents('fieldset').find('.linkentry:hidden').first().slideDown(200);
	});
	
	//--------------------------------------------------- List of followers - append HTML for name, and show on hover over --------------------------------------------------- 
	$('.follow-grid li').hover(
	function (){
		$(this).find('a,img').removeAttr('title').append("<div class='follow-name'><div class='triangle-up'>&#9650;</div>"+$(this).find('img').attr('alt')+"</div></div>");
		$(this).find('.follow-name').delay(400).fadeTo(400,1);
	},
	function () {
		$(this).find('.follow-name').hide().remove();
	});
	
	//Text replace
	//$('label[for="ProfileContent"]').html("ABOUT ME");
	//$('label[for="ProfileImage0File"]').html("UPLOAD IMAGE");
	
	//If the Textarea for ProfileContent is empty let's display a message in the textarea box, and remove it if user clicks on the textarea to edit
	if ($('#ProfileContent').val()==""){
		$('#ProfileContent').parent('.input').css('position','relative').append("<div class='ProfileContentAppended' style='position:absolute;top:20px;left:5px'>Tell us a bit about yourself...</div>");
	}
	$('#ProfileContent').click(function(e) {
       $(this).parent('.input').find('.ProfileContentAppended').remove();
    });

	
	//Launch the fancy box for a new channel application
	//$('#channel-apply .apply').fancybox(boxOptions);
	
	//If user clicks on View Followers/View Following then launch in Fancy box
	$('a.view-followers-following').fancybox(boxOptions);
	
	
	//Follow Channel/Article or Mixtape
	$('body').delegate('.follow-channel,.follow-channel-med,.follow-channel-small', 'click',function(e) {
        e.preventDefault();
		thisElement = $(this);
		$('.follow-channel-message').hide();
		thisElement.fadeTo(200,0.3);
		var page = '/web_services/'+thisElement.attr('rel');
		$.getJSON(page, function(data) {
			if (data.result==true)
			{
				if (thisElement.attr('class') == ('follow-channel')){
					thisElement.css('background-position','0px -47px');
				}
				else if (thisElement.attr('class') == ('follow-channel-med')){
					thisElement.css('background-position','-69px 0');
				}
				else if (thisElement.attr('class') == ('follow-channel-small')){
					thisElement.css('background-position','0px -18px');
				}
				thisElement.fadeTo(100,0).fadeTo(100,1)
			}
			else
			{
				thisElement.fadeTo(100,1);
				if("No user logged in"==data.msg){
					message = 'Sorry you must be logged in before you can do that!';
					thisElement.find('.follow-channel-message').html(message).fadeTo(300,1);
				}
				else{
					thisElement.find('.follow-channel-message').html(data.msg).fadeTo(300,1).delay(2000).fadeTo(300,0,function() {$(this).hide()});
				}
			}
		});
    }); 
	
	/*------------------------------------------------------ Account Settings Form Validation START --------------------------------------*/
	//Function to check if item has been entered	
	function check_account_settings(id_of_element,message,ErrorArray){
		if ($(id_of_element).val()==""){
			$(id_of_element).closest('div.input').find('.error-box').html(message).slideDown(200);
			ErrorArray[id_of_element] = true;
		}else{
			$(id_of_element).closest('div.input').find('.error-box').slideUp(200);
		}
	}

	//Append error elements	to inside of surrounding div
	$('.account-settings input').closest('div.input').append('<div class="error-box"></div>');
	$('.account-settings div.input .error-box').css({'margin':'2px 0 10px 179px','width':'286px'});
	
	$('#submit_change_email').click(function(e) {
		var ErrorArray = new Array();
		//Check fields have been filled out
		check_account_settings('#UserEmailCurrent','Please enter your current email address',ErrorArray);
		check_account_settings('#UserEmailNew','Please enter a new email address',ErrorArray);
		check_account_settings('#UserConfirmEmail','Please confirm the new email address you wish to use',ErrorArray);
		//Check emails match
		if ($('#UserEmailNew').val() != $('#UserConfirmEmail').val()){
			ErrorArray['#UserConfirmEmail'] = true;
			$('#UserConfirmEmail').closest('div.input').find('.error-box').html('Confirmation Email must match - Please check the details').slideDown(200);
		}
		
		var stopFormProcess = false;
		for (x in ErrorArray)
		{
			if (ErrorArray[x]==true){stopFormProcess=true;}
		}
		if (stopFormProcess==true){
			return false;}
		else{
			return true;}
    });
	
	$('#submit_change_password').click(function(e) {
		var ErrorArray = new Array();
		//Check fields have been filled out
		check_account_settings('#UserCurrentPassword','Your existing password',ErrorArray);
		check_account_settings('#UserPassword','Please enter a new password',ErrorArray);
		check_account_settings('#UserConfirmPassword','Please confirm your new password',ErrorArray);
		//Check emails match
		if ($('#UserPassword').val() != $('#UserConfirmPassword').val()){
			ErrorArray['#UserConfirmPassword'] = true;
			$('#UserConfirmPassword').closest('div.input').find('.error-box').html('Confirmation Password must match!').slideDown(200);
		}		
		
		var stopFormProcess = false;
		for (x in ErrorArray)
		{
			if (ErrorArray[x]==true){stopFormProcess=true;}
		}
		if (stopFormProcess==true){
			return false;}
		else{
			return true;}
    }); 
	
	
	//Restyle any cake php errors
	$('.account-settings .error-message').addClass('error-box').css({'margin':'2px 0 10px 179px','width':'286px'}).slideDown(200);
	/*------------------------------------------------------ Account Settings Form Validation END --------------------------------------*/
	
	/* ----------------------------------------------------- Channel Edit - Manage Channels/Mixtapes/Articles --------------------------------------------------------------- */
		//Display close on hover over
	$('.manage-followers-mixtapes li, .manage-my-mixtapes ul > li').hover(
	function() {
		$(this).find('.close').show();
	},
	function () {
		$(this).find('.close').hide();
	});
	//When the close button is clicked bring up the confirm box, then close the li if the confirm yes is clicked
	$('.manage-followers-mixtapes ul li .close,.manage-my-mixtapes ul > li .close').click(function() {
		$('.confirm').hide();//Hide any other open ones
		var ThisLi = $(this).parent('li')
			ThisLi.delegate('.no','click',function() {
				ThisLi.find('.confirm').hide();
			});
			ThisLi.find('.confirm').fadeTo(200,1);
			ThisLi.find('.yes').click(function() {						
				var page = '/web_services/'+ThisLi.attr('rel');
				$.getJSON(page, function(data) {
					if (data.result==true)
					{
						ThisLi.fadeTo(200,0,function(){
							ThisLi.hide();
						})
					}
					else
					{
						ThisLi.find('.confirm').html('<span class="triangle-up">&#9650;</span><div style="background:#8e2828;margin:0px -5px;padding:0px 5px">ERROR! '+data.msg+' - <span class="no">Ok</span></div>')
					}
				});
			});
	});

	
	//User changes the title of their uploaded mixtape
	$('.manage-my-mixtapes ul > li input.title').change(function() {
		var mixtapeTitle = jQuery(this).val();
		var postData = {
			'data[Mixtape][title]': mixtapeTitle
		};
		var page = '/web_services/'+$(this).attr('rel');
		var apiHandler = new APIHandler({
			Url: page,
			Method: 'POST',
			Data: postData,
			Callback: function(response) {
				console.log(response);
			}
		});
		
		/*
		$.getJSON(page, function(data) {
			if (data.result==true)
			{
			}
		});*/
	});
	
	
	//Inititalize Tabs Status
	$('#manage-mixtapes').show();$('#tab-mixtapes').addClass('tab-selected');
	$('#manage-articles').hide();
	

	$('#tab-mixtapes').click(function(){
		$('#tab-mixtapes').addClass('tab-selected')
		$('#tab-articles').removeClass('tab-selected')
		$('#manage-mixtapes').fadeTo(200,1);
        $('#manage-articles').hide();
    });
	$('#tab-articles').click(function(){
		$('#tab-mixtapes').removeClass('tab-selected')
		$('#tab-articles').addClass('tab-selected')
		$('#manage-mixtapes').hide();
        $('#manage-articles').fadeTo(200,1);
    });
	/* ----------------------------------------------------- Channel Edit - Manage Channels/Mixtapes/Articles END --------------------------------------------------------------- */

	//Function to check if display URL contains only a-z,0-9 and - or _
	function displayURLCheck(value){
		var regex=/^[0-9A-Za-z-_]+$/; //^[a-zA-z]+$/
		if(regex.test(value)){
			return true;
		} else {
			return false;
		}
	}

		//1 - click on change slug so show the text input box
		$('#change-slug').click(function(e) {
		   $('#profile-slug').hide();
		   $('#new-slug').fadeTo(300,1);
		   $('#change-slug').hide();
		});
		//2 - User types new values let's change the button to check
		$('#new-slug').keyup(function(e) {
		   $('#change-slug').hide();
		   if ($('#check-slug').css('display')=="none"){$('#check-slug').fadeTo(300,1);};
		   if (displayURLCheck($('#new-slug').val())==false){
			   $('.display-url-message').fadeTo(300,1);
		   }else{
			   $('.display-url-message').fadeTo(300,0,function(){$('.display-url-message').hide()});
		   }
		});
		//3 - User clicks check availability
		$('#check-slug').click(function(e) {
			var page = '/web_services/check_permalink_available/'+$('#new-slug').val()+'/?rnd='+Math.floor(Math.random()*99999999999);
			$.getJSON(page, function(data){
				if (data.result==true){
					$("#slug-msg").fadeTo(300,1).html('<span class="notice-box" style="display:inline;position:relative">'+data.msg+'</span>');
					$("#save-slug").fadeTo(300,1);
					$("#warning-box").fadeTo(300,1);
				}
				else if(data.result==false)
				{	
					$("#slug-msg").show().html('<span class="error-box" style="display:inline">'+data.msg+'</span>');
					$("#save-slug").hide();$("#warning-box").hide();
				}
				//else{/*alert('JSON Request invalid for '+page);*/}//Catch all error
			});
		});
		//4 - User clicks save permanantly
		$('#save-slug').click(function(e) {
			var page = '/web_services/save_permalink/'+$('#new-slug').val()+'/?rnd='+Math.floor(Math.random()*99999999999);
			$.getJSON(page, function(data){
				if (data.result==true){//Succesful save
					$("#slug-msg").show().html('<span class="notice-box" style="display:inline;position:relative">'+data.msg+'</span>');
					$("#save-slug").hide();$("#warning-box").slideUp(300);$('#check-slug').fadeTo(300,0,function(){$('#check-slug').hide()});
					$('#new-slug').fadeTo(300,0,function(){
						$('#profile-slug').fadeTo(300,1).html($('#new-slug').val());
					});
				}
				else if(data.result==false)
				{	
					$("#slug-msg").show().html('<span class="error-box" style="display:inline">'+data.msg+'</span>');
					$("#save-slug").hide();$("#warning-box").hide();
				}
				//else{/*alert('JSON Request invalid for '+page);*/}//Catch all error
			});
		});

	//Function to fix youtube video overlay that goes over the top of the radiobar
    $("iframe").each(function(){
		thisIframe = $(this);
		if (thisIframe.attr('src')) {
			var ifr_source = thisIframe.attr('src');
			var wmode = "wmode=transparent";
			if(ifr_source.indexOf('?') != -1) {
				var getQString = ifr_source.split('?');
				var oldString = getQString[1];
				var newString = getQString[0];
				thisIframe.attr('src',newString+'?'+wmode+'&'+oldString);
			}
			else thisIframe.attr('src',ifr_source+'?'+wmode);
		}
    }); 

	/* About Page */
	$('.tab1,#arrow-left').click(function(e) {
		$('.tab1').addClass('selected');
		$('.tab2').removeClass('selected');
		$('#section1').animate({
			"left": '0px'
			}, 1000);
		$('#section2').animate({
			"left": '-900px'
			}, 1000);
    });
	$('.tab2,#arrow-right').click(function(e) {
		$('.tab2').addClass('selected');
		$('.tab1').removeClass('selected');
		$('#section1').animate({
			"left": '900px'
			}, 1000);
		$('#section2').animate({
			"left": '0px'
			}, 1000);
    });
	
	
	//Channel Application page	
	var steps = 2;
	var activeStep = 1;
	
	//jQuery(".channel-apply-button.back").hide();
	//jQuery(".channel-apply .submit input").hide();
	
	function show_stage1(){
		$('#channel-apply-wrapper .stage2').slideUp(800);$('#channel-apply-wrapper .stage1').slideDown(800);
	}
	function show_stage2(){
		$('#channel-apply-wrapper .stage1').slideUp(800);$('#channel-apply-wrapper .stage2').slideDown(800);
	}
	
	$(".channel-apply-button.next, h2.stagetwo").click(function(event) {
		show_stage2()
		$(".channel-apply-button.next").hide();
		$(".channel-apply-button.back").show();
		$(".channel-apply .submit input").show();
	});
	
	$(".channel-apply-button.back, h2.stageone").click(function(event) {
		show_stage1()
		$(".channel-apply-button.next").show();
		$(".channel-apply-button.back").hide();
		$(".channel-apply .submit input").hide();
	});

	// What is this 
	function check_channel_apply(id_of_element,message,e){
		if ($(id_of_element).val()==''){
			show_stage1()
			$(id_of_element+'-error').html(message).slideDown(300);
			e.preventDefault();
			formErrors = true;
			return false;
		}
		else{
			$(id_of_element+'-error').slideUp(300);
			return true;
		}
	}


	//Channle Apply form validation
	$(".channel-apply .submit input").click(function(e) {
	
		var channelApplicationNode = $(".channel-apply");
		
		//Check the Sectinos have been entered
		check_channel_apply('#ProfileTitle','Please enter a name for the channel you are applying for',e);
		
		// TODO: Determine whether to enforce gender (N/A for club/label)
		// REMOVED Mandatory field for gender - Some artists are groups! 
		check_channel_apply('#ProfileLocation','Please choose your location',e);
		check_channel_apply('#ProfileContent','Please write some information about the channel you are applying for',e);
		
		// If the form has errors return false 
		if(true == formErrors) {
			return false;
		}
		
		// Dont submit the form twice
		if(true == formSubmitted) {
			return false;
		}
		
		// if it passes add a flag so that form is not submitted twice
		formSubmitted = true;
	});

	//Upload Mixtape Validation
	function isDate(dateStr,error_id) {
		var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
		var matchArray = dateStr.match(datePat); // is the format ok?

		if (matchArray == null) {
		$(error_id).html("Please enter date as either dd/mm/yyyy or dd-mm-yyyy.").slideDown(300);
		return false;
		}
		
		day = matchArray[1];
		month = matchArray[3];
		year = matchArray[5];
		
		
		if (day < 1 || day > 31) {
		$(error_id).html("Day must be between 1 and 31.").slideDown(300);
		return false;
		}
		
		if (month < 1 || month > 12) { // check month range
		$(error_id).html("Month must be between 1 and 12.").slideDown(300);
		return false;
		}
		
		if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		$(error_id).html("Month "+month+" doesn`t have 31 days!").slideDown(300)
		return false;
		}
		
		if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
		$(error_id).html("February " + year + " doesn`t have " + day + " days!").slideDown(300);
		return false;
		}
		}
		return true; // date is valid
	}

	$('#MixtapeMixtapeName, #MixtapeDateOfRecording').focus(function(e) {
        $(this).select();
    });
    

	
	$('.select-file').mouseover(function(e) {
		if ($('#MixtapeMixtapeName').val()==='') {
			$('#MixtapeMixtapeName-error').html('You must enter a name').slideDown(300);
		}
		else{
			$('#MixtapeMixtapeName-error').slideUp(300);
		}
		
		if (isDate($('#MixtapeDateOfRecording').val(),'#MixtapeDateOfRecording-error')){
			$('#MixtapeDateOfRecording-error').slideUp(300);
		}
    });

	//Only allow uploads after checking terms and conditions
	$('#agree-upload').attr('checked',false)//Set to false on page reload
	$('#agree-upload').click(function(e) {
		if ($('#agree-upload').attr('checked')===true){
			$('#upload .select-file').show();
		}else{
			$('#upload .select-file').hide();
		}        
    });
	
	//Show upload terms and condition
	$('#upload .terms-agree .show-terms').click(function(e) {
        $('#upload .terms').slideDown(300);
    });
	
	//Delete channel JSON request
	$('table.channel-status td.delete-channel a').click(function(e) {
		$('table.channel-status td.delete-channel .confirm').hide();
        e.preventDefault();
		var page = $(this).attr('href');
		var thisRow = $(this).closest('tr');
		var thisConfirm = $(this).find('.confirm')
		
		thisConfirm.fadeTo(300,1,function(){
			thisConfirm.find('.no').click(function(){thisConfirm.fadeOut(300);});
			thisConfirm.find('.yes').click(function(){
				$.getJSON(page, function(data) {
					if (data.result===true){
						thisRow.fadeOut(300);
						if (data.redirect!=null)
						{
							window.location.href = data.redirect;
						}
					} else {
						thisConfirm.html(data.msg)
					}
				});
			});
		});
    });
	
	//About page
	$('.about .q > a').click(function(e) {
        thisA = $(this);
        thisP = $(this).next('p');
		if (thisP.css('display')=='none'){
			thisP.slideDown(300);
			thisA.css('text-decoration','none');
		}
		else{
			thisP.slideUp(300);
			thisA.css('text-decoration','underline');
		}
    });
	
});

function OpenSignUp() {
	$("#sign-up").click();
}
/*------------------------------------------------------
  j.gilmore: Added JavaScript END
--------------------------------------------------------*/



