gloader.load(
	['glow', '1'],
	{
		async: true,
		onLoad: function(glow) {
		
            bbc.fmtj.utils.createObject('bbc.fmtj.apps.democracyLive');
    		
    		bbc.fmtj.apps.democracyLive = (function(){
    			var _ajaxBaseUrl = '';	
    			
    			function _getAjaxBaseUrl() {
    				return _ajaxBaseUrl;
    			}
    			
    			function _setAjaxBaseUrl(url) {
    				_ajaxBaseUrl = url;
    			}
                
                return {
                    getAjaxBaseUrl: _getAjaxBaseUrl,
                    setAjaxBaseUrl: _setAjaxBaseUrl
                };
    		 })();
		}
	});gloader.load(
	['glow', '1', 'glow.dom', 'glow.events'],
	{
		async: true,
		onLoad: function(glow) {
		bbc.fmtj.utils.createObject('bbc.fmtj.apps.externalBlogs');
		var $ = glow.dom.get;
		var _addListener = glow.events.addListener;
		
		 bbc.fmtj.apps.externalBlogs = (function(){
			function openUrl(ev){
				ev.preventDefault();
				window.location.href = $(this).prev().val();
			}
			
			return{
				init: function(formNodeList){
					formNodeList.each(function(){
						if ($(this).get('fieldset > select').next().is('div')) {
							_addListener($(this).get('fieldset > select').next(), 'click', openUrl);
						}
					});
				}
			};
		 })();
		 
		glow.ready(function(){
				bbc.fmtj.apps.externalBlogs.init($('.content-object-19 > form'));
		});
		}//end of glow onload
	});gloader.load(['glow', '1', 'glow.dom', 'glow.widgets.Overlay'], {

    onLoad: function(glow){
	
		bbc.fmtj.utils.createObject('bbc.fmtj.apps.FollowCookieIo');
		var cookieName = 'dlive';
		var cookiePath = "path=/democracylive/";
		
		bbc.fmtj.utils.createObject('bbc.fmtj.apps.FollowAction');
		
		bbc.fmtj.utils.createObject('bbc.fmtj.apps.FollowPanel');
		
        bbc.fmtj.apps.FollowCookieIo = (function(){
			function readCookie(){
				var allcookies = document.cookie;
				var start, end, cookieData;
				if ( allcookies === "" ) {
					return -1;
				}
				start = allcookies.indexOf( cookieName + '=' );
				if ( start === -1 ) {
					return -1;
				}
				start += cookieName.length + 1;
				end = allcookies.indexOf( ';' , start );
				if ( end == -1 ) {
					end = allcookies.length;
				}
				cookieData = allcookies.substring( start , end );
				return cookieData;
			}
			
			function setCookie(value){
				var myCookieValue = readCookie();
				if(myCookieValue !== -1){
					myCookieValue += '_'+value;
				}else{
					myCookieValue = '_'+value;
				}
				writeCookie(myCookieValue);
			}
			
			function writeCookie(val){
				var myCookieValue = val;
				var today;
				today = new Date();
				var expiryDate;
				if(myCookieValue){
					// one year, the maximum allowed under S&G -  
					expiryDate = new Date(today.setTime(today.getTime()+ (365 * 24 * 60 * 60 * 1000)));
				}else{
					// We have no information to store in the cookie so set the expiry date to the past. This will delete the cookie.
					expiryDate = new Date();
				}
				var expires = "expires=" + expiryDate.toUTCString();
				document.cookie = cookieName + "=" + myCookieValue + "; " + expires + "; " + cookiePath;
				return true;
			}
            
			return {
                name: cookieName,
                path: cookiePath,
                content: '',
                readCookie: readCookie,
                setCookie: setCookie,
                writeCookie: writeCookie
            };	
        })();
        
        bbc.fmtj.apps.FollowAction = (function(){

			function followRep(repId){
				var myCookie = bbc.fmtj.apps.FollowCookieIo.readCookie();
				var isRep;
				// check there is already a cookie value
				if(typeof myCookie === 'string'){
					isRep = isRepFollowed(repId, myCookie);
	            	if(!isRep){
						var tempList = myCookie.split('_');
						var tempListArr = [];
						for(var i = 0; i < tempList.length; i++){
		        			if(/\d{5,6}/.test(tempList[i])){
		        				//add to new array
		        				tempListArr.push(tempList[i]);
		        			}
		        		}
						if(tempListArr.length < 5){
							bbc.fmtj.apps.FollowCookieIo.setCookie(repId);
							glow.dom.get('#follow-representative > div.follow').hide();
			            	glow.dom.get('#follow-representative > div.following').show();
						}else{
							maxErrorMsg();
						}
					}
				}else{
							bbc.fmtj.apps.FollowCookieIo.setCookie(repId);
							glow.dom.get('#follow-representative > div.follow').hide();
			            	glow.dom.get('#follow-representative > div.following').show();
				}
            }
            
            function unFollowRep(repId){
            	var myCookie = bbc.fmtj.apps.FollowCookieIo.readCookie();
            	var rep = '_'+repId;
            	var newCookieData = myCookie.replace(rep,'');
            	bbc.fmtj.apps.FollowCookieIo.writeCookie(newCookieData);
            	glow.dom.get('#follow-representative > div.follow').show();
            	glow.dom.get('#follow-representative > div.following').hide();
            }
            
            function maxErrorMsg(){
            	var errorOverlay = new glow.widgets.Overlay(glow.dom.create('<span title="Close">'
            			+ '</span>'),{
            		width: 226,
            		modal: true,
            		mask: new glow.widgets.Mask({color: '#fff', opacity:0, onClick: function(){this.remove();}}),
            		autoPosition: false
            	});
            	glow.dom.get('#follow-representative > div.follow > h4.max').show();
            	errorOverlay.show();
            	glow.events.addListener(glow.dom.get(), 'click', maxErrorMsgHide);
            	glow.events.addListener(errorOverlay, 'afterHide', maxErrorMsgHide);
            }
            
            function maxErrorMsgHide(){
            	glow.dom.get('#follow-representative > div.follow > h4.max').hide();
            }
            
            function isRepFollowed(repId, cookieData){
            	var _isRepFollowed;
							var tempArr = cookieData.split('_');
							for(var i = 0; i < tempArr.length; i++){
								if(/repId/.test(tempArr[i])){
									_isRepFollowed = true;
								}else{
								_isRepFollowed = false;
								}
							}
            	return _isRepFollowed;
            }
			
            function assignEventListeners(){
	        	glow.events.addListener(glow.dom.get('#follow-representative > div.following > h4.stop > a'), 'click', function(ev){
	        		ev.preventDefault();
	        		if(/\d{5,6}/.test(glow.dom.get(ev.source).attr('class'))){
	        		  unFollowRep(glow.dom.get(ev.source).attr('class'));
	            	  bbc.fmtj.apps.FollowPanel.validateCookieValue();
	        		}
	        	});
	        	
	        	//assign listener to follow link
	        	glow.events.addListener(glow.dom.get('#follow-representative > div.follow > h3 > a'), 'click', function(ev){
	        		ev.preventDefault();
	        		if(/\d{5,6}/.test(glow.dom.get(ev.source).attr('class'))){
	        		  followRep(glow.dom.get(ev.source).attr('class'));
	            	  bbc.fmtj.apps.FollowPanel.validateCookieValue();
	        		}
	        	});
        	}
        	return{
                followRep: followRep,
                unFollowRep: unFollowRep,
                isRepFollowed: isRepFollowed,
                assignEventListeners: assignEventListeners
        	};
        })();
        
bbc.fmtj.utils.createObject('bbc.fmtj.apps.FollowPanel');
		
        bbc.fmtj.apps.FollowPanel = (function(){
			var queryParameters = {cy:'', gb:''};
			
			function validateCookieValue(){
				if(/\d{5,6}/.test(bbc.fmtj.apps.FollowCookieIo.readCookie())){
					updateLeftPanel();
				}else{
					glow.dom.get('#followed-reps-none').show();
					glow.dom.get('#followed-reps').hide();
					glow.dom.get('#followed-reps').attr('class', 'panel-collapse');
				}
			}
			
        	function actOnCookieGb(){
        		var tempList = bbc.fmtj.apps.FollowCookieIo.readCookie().split('_');
        		for(var i = 0; i < tempList.length; i++){
        			if(/^\d{5}$/.test(tempList[i])){
        				queryParameters.gb += '&mpids[]='+tempList[i];
        			}
        		}
			}
			
        	function actOnCookieCy(){
        		var queryParametersCy = '';
        		var tempList = bbc.fmtj.apps.FollowCookieIo.readCookie().split('_');
        		for(var i = 0; i < tempList.length; i++){
        			if(/^9\d{5}$/.test(tempList[i])){
        				queryParameters.cy += '&mpids[]='+tempList[i];
        			}
        		}
			}
            
        	function updateLeftPanel(){
					var isEnId = false;
        		glow.dom.get('#followed-reps-none').hide(); 
						glow.dom.get('#followed-reps').show();
						glow.dom.get('#followed-reps').attr('class', 'panel-expand');
        		//updating english content
						actOnCookieGb();
						if(queryParameters.gb != ''){
							var urlEn = bbc.fmtj.apps.democracyLive.getAjaxBaseUrl() + '/democracylive/service/search?type=following' + queryParameters.gb + '&locale=en_GB';
							var request = glow.net.get(urlEn, {
								async: false,
								onLoad: function(response) {
								isEnId = true;
									glow.dom.get('#followed-reps').replaceWith(glow.dom.create(response.json().dl_follow_panel).get('#followed-reps'));
									glow.dom.get('#followed-reps').show();
									glow.dom.get('#followed-reps').attr('class', 'panel-expand');
								 },
								 onError: function(response) {
									 glow.dom.get('#followed-reps').html(glow.dom.create('<p>error processing!!</p>'));
								 }
							});
						}
        		//updating welsh reps
        		actOnCookieCy();
						if(queryParameters.cy != ''){
							var urlCy = bbc.fmtj.apps.democracyLive.getAjaxBaseUrl() + '/democracylive/service/search?type=following' + queryParameters.cy + '&locale=cy_GB';
							var requestCy = glow.net.get(urlCy, {
								async: false,
								onLoad: function(response) {
								if(isEnId){
								var tempNode = glow.dom.create(response.json().dl_follow_panel).get('#followed-reps > ul').html();
									glow.dom.get('#followed-reps > ul').append(tempNode);
								 }else{
									glow.dom.get('#followed-reps').replaceWith(glow.dom.create(response.json().dl_follow_panel).get('#followed-reps'));
									glow.dom.get('#followed-reps').show();
										glow.dom.get('#followed-reps').attr('class', 'panel-expand');
								 }},
								 onError: function(response) {
									 glow.dom.get('#followed-reps').html(glow.dom.create('<p>error processing!!</p>'));
								 }
							});
						}
						queryParameters.gb = '';
						queryParameters.cy = '';
        	}
        	
			return {
				validateCookieValue: validateCookieValue
            };	
        })();

        glow.ready(function(){
        	//left panel
        	bbc.fmtj.apps.FollowPanel.validateCookieValue();
        	glow.dom.get('#panel-following-left').show();

        	//assign listener to follow link - right panel
        	bbc.fmtj.apps.FollowAction.assignEventListeners();
        	var currentMp = glow.dom.get('#follow-representative > div.follow > h3 > a').attr('class');
        	var cookiePresent = bbc.fmtj.apps.FollowCookieIo.readCookie();
        	if(cookiePresent !== -1){
        		listAllFollowed();
        	}
        	
        	if(glow.dom.get('#follow-representative').length > 0){
            	glow.dom.get('#follow-representative').show();
        	}
        	
        	function listAllFollowed(){
        		var tempList = cookiePresent.split('_');
            	glow.dom.get('#follow-representative > div.follow').show();
        		for(var i = 0; i < tempList.length; i++){
        			if(/\d{5,7}/.test(tempList[i])){
        				if(currentMp == tempList[i]){
        					glow.dom.get('#follow-representative > div.follow').hide();
    		            	glow.dom.get('#follow-representative > div.following').show();
        				}
        			}
        		}
        	}
        });
    }
});gloader.load(
	['glow', '1', 'glow.dom', 'glow.events'],
	{
		async: true,
		onLoad: function(glow) {
		bbc.fmtj.utils.createObject('bbc.fmtj.apps.genericToggle');
		
		function alterTitle(node){
			if(node.attr('title').indexOf('Show') != -1){
				node.attr('title', glow.lang.replace(node.attr('title'), /Show/, 'Hide'));
			}else{
				node.attr('title', glow.lang.replace(node.attr('title'), /Hide/, 'Show'));
			}
		}
		
		 bbc.fmtj.apps.genericToggle = (function(){
			return{
				init: function(node, nodeToToggle, toggleClass, titleNode){
				glow.events.addListener(node, 'click', function(ev){
						ev.preventDefault();
						nodeToToggle.toggleClass(toggleClass);
						alterTitle(titleNode);
					});
				}
			};
		 })();
		 
		glow.ready(function(){
			var targetElement = glow.dom.get('.content-object-23 > h2');
			var nodeToToggle = glow.dom.get('.content-object-23');
			var togglingClass = 'hidden';
			var titleNode = glow.dom.get('.content-object-23 > h2');
			bbc.fmtj.apps.genericToggle.init(targetElement, nodeToToggle, togglingClass, titleNode);
		});
		}//end of glow onload
	});gloader.load(
    ['glow', '1', 'glow.dom', 'glow.events', 'glow.data'],
    {
        onLoad: function(glow){

	    bbc.fmtj.utils.createObject('bbc.fmtj.av.utils.startOffsetTime')
            bbc.fmtj.av.utils.startOffsetTime = (function(){
		
		    
                function cueMedia(){
		    
		    var clipStartTime,
			empClipId,
			clip;
			
		    empClipId = bbc.fmtj.page.storyId == '(none)' ? getStoryIdFromUri(bbc.fmtj.page.uri) : bbc.fmtj.page.storyId;	
    
                    if(empClipId){
			
			clipStartTime = getStartTime();
		        
			bbc.fmtj.av.emp.load( function() {
			    
			
			    clip = bbc.fmtj.av.emp.playerInstances['emp_'+empClipId];
                            clip.onMediaPlayerInitialised = function() {
	                            clip.call('cueItem',[empClipId,clipStartTime]);
                            }
	                
			});
                    }
		    
                }
		
		function getStoryIdFromUri(uri){
		    
			var regex = /\/democracylive\/hi\/.*(\d{7,10}).stm/,
			
			storyId = uri.match(regex)[1];
			
			return storyId.toString();
			
		}

                function getStartTime(){
		    
                    // grab whatever's appended to the page URL, if anything
                    // match h for hours, m for minutes, s for seconds
                    // convert hours and minutes into seconds
                    // add up all the seconds and return the value
		    
                    var h,
			m,
			s,
			totalSecs,
			queryStr = bbc.fmtj.page.queryString,
			timecode = getTimeCode(queryStr, 't');
		    
			h = m = s = totalSecs = 0;
                    
                    if(timecode){
                        h = getUnitsFromTimeCode('h',timecode);
                        m = getUnitsFromTimeCode('m',timecode);
                        s = getUnitsFromTimeCode('s',timecode);
                        totalSecs = (h*3600)+(m*60)+s;
                    }
		    
                    return totalSecs;
		
                }// end getStartTime()

                function getTimeCode(qStr, key){
                    // Extracts and returns the value of key from a query string using glow.data.decodeUrl().
                    // Uses try, catch because glow.data.decodeUrl() throws an error if the query string is not valid/well-formed
                    var tValue;
		               
		    try{
			tValue = glow.data.decodeUrl(qStr)[key];
		    }
		    catch(err){
			return false;
		    }
		    return tValue;
                    
                }// end getTimeCode()

                function getUnitsFromTimeCode(unit, tcode){
		    
                    // Fetch the numbers immediately followed by the unit type specified(h, m or s).
                    // If found, parse as a decimal integer and return.
                    // If not, we'll return 0
                    
		    var exp 		= new RegExp( '\\d+'+unit ),
			unitsValue 	= 0,
			matchResults	= tcode.match( exp );
			
                    if(matchResults){
                        // Specify '10' to make sure we parse as decimal
                        unitsValue = parseInt( matchResults[0], 10 );
                    } 		    
		    else if(unit === 's'){
                        
			// check for time code without 's' for seconds specified
                        matchResults = tcode.match( /^\d+$/ );
                        
			if(matchResults){
                            // Specify '10' to make sure we parse as decimal
                            unitsValue = parseInt( matchResults[0], 10 );
                        }
                    }
                    return unitsValue;
		
                }// end getUnitsFromTimeCode()
		
		function fetchEmpClipId(){
		    
                    // get the one cip we want and return it, or nothing
                    var embedObjParams = glow.dom.get( "object > param" ),
			temp,
			paramNode,
			i;
			
                    for(i = 0; i < embedObjParams.length; i++){
			    paramNode = glow.dom.get(embedObjParams[i]);
                        if( paramNode.hasAttr('name') && paramNode.attr('name') === 'id'){
                            temp = paramNode.attr('value').split('embeddedPlayer_');
                            return temp[1];
                        }
                    }
                    return false;
		
                }// end fetchEmpClipId()


                return {
                    init: function(){
			
                        cueMedia();
			
                    },
		    checkTimeCodeIsset:function( qs ){
			
			var ret = getTimeCode( qs,'t' );
			// if ret is undefined, there isnt a 't' value
			if( ret ){
			    return true;
			}
			return false;
		    
		    }
                };

            }) ();// end democracy_media_asset_page()

            glow.ready(function(){
		if( bbc.fmtj.page.queryString && bbc.fmtj.av.utils.startOffsetTime.checkTimeCodeIsset(bbc.fmtj.page.queryString) == true ){
		    
			bbc.fmtj.av.utils.startOffsetTime.init()
			
		}
            });

        }//end of glow onload
    });gloader.load(
	["glow", "1", "glow.dom", "glow.events", 'glow.net'],
	{
		onLoad: function(glow){

			processingRequest = (function() {
			    
				function showAnimation(node){
					node.show();
				}
				
				function hideAnimation(node){
					node.hide();
				}
				return {
					showAnimation: function(animationWrapper){	
						showAnimation(animationWrapper);
					},
					hideAnimation: function(animationWrapper){
						hideAnimation(animationWrapper);
					}
				};
				
			}) ();
		}
	}
);gloader.load(
	["glow", "1", "glow.dom", "glow.events"],
	{
		onLoad: function(glow){
			bbc.fmtj.utils.createObject("bbc.fmtj.apps.democracy_list_displayer");

			bbc.fmtj.apps.democracy_list_displayer = (function() {
			
			    /* Define class vars  */
				var repIds = [
				    "#uk",
				    "#northern-ireland",
				    "#scotland",
				    "#wales",
				    "#europe"
				];

				function toggleListsCss( event ) {
					var mySelectionId = event.attachedTo.id;
					for( var i = 0; i < repIds.length; i++ ){
					    var myRepsListsNode = new glow.dom.NodeList();
					    myRepsListsNode = glow.dom.get( "#representatives-lists" );
						
					    var myLinkBlock = new glow.dom.NodeList();
					    myLinkBlock = myRepsListsNode.get( "#lists-nav " + repIds[i] );
						
					    var myListBlock = new glow.dom.NodeList();
					    myListBlock = myRepsListsNode.get( repIds[i] + "-list" );
						if( myListBlock.attr( "id" ) == mySelectionId + '-list'  ){
						    myListBlock.show();			
							myLinkBlock.attr( "class", "selected" )
							if ( !myLinkBlock.hasClass( "selected" ) ){
							    myLinkBlock.addClass( "selected" );
							}
						}else{
						    myListBlock.hide();
							if ( myLinkBlock.hasClass( "selected" ) ){
							    myLinkBlock.removeClass( "selected" );
							}
						
						}
					}
					location.href = "#" + mySelectionId;
                    event.preventDefault();					
				}
				
				function addLinksListeners( ids ) {
					glow.events.addListener(
					    glow.dom.get( "#representatives, #lists-nav" ).get( ids ),
					    "click",
                        toggleListsCss						
					);
				}
				
				return {
					initLinksListeners: function(){		
						addLinksListeners( repIds );
					}
				};
				
			}) ();
			
			glow.ready(function() {
				// addListeners here 
				bbc.fmtj.apps.democracy_list_displayer.initLinksListeners();
            });
		}
	}
);gloader.load(
	["glow", "1", "glow.dom", "glow.events", 'glow.net'],
	{
		onLoad: function(glow){

			democracy_deep_links_toggler = (function() {
			    /* initialise vars */
				
				function toggleDeepLinks(event){
				    event.preventDefault();
					// Get the element which contains both the element which triggered this event and the one we want to toggle
					var theDaddy = glow.dom.get(event.attachedTo).parent().parent();
					// Get the header link element
				    var myHeaderLink = theDaddy.get('h4 a');					
					
					// Get the subheader element (containing text stating how many results are showing, and a link to toggle this option)
					var myHowManyStrap = theDaddy.get('h5');
					
					// If there's nothing in our subheader node yet then we need to make a search request,
					// retrieve the links data, append the new HTML to theDaddy, then add a listener to any 
					// link in the new HTML.
					if(myHowManyStrap.html() === ''){
					    // disable the header link to avoid multiple requests triggered by rapid mouse-clicks
					    glow.events.removeAllListeners(myHeaderLink);
					    glow.events.addListener(
					        myHeaderLink,
					        "click",
                            preventDefault						
					    );
                        var baseUrl = bbc.fmtj.apps.democracyLive.getAjaxBaseUrl();
						glow.net.get(baseUrl + myHeaderLink.attr('href'), {
						    useCache: true,
						    onLoad: function(response){
							    var responseNode = glow.dom.create(response.text());
					            responseNode.hide();

                                var myDeepLinksItems = responseNode.get('li');
                                if(myDeepLinksItems.length > 5){
					                for(var i = 5; i < myDeepLinksItems.length; i++){
						                glow.dom.get(myDeepLinksItems[i]).hide();						    
						            }					    
						        }

							    theDaddy.append(responseNode);
								//toggleHowMany(event);
							    glow.events.addListener(
					                theDaddy.get( ".deep-links-header a" ),
					                "click",
                                    toggleHowMany					
					            );
					            responseNode.show();
						        // change the direction of the link arrow (dictated by whether or not the CSS class hidden is applied)
					            myHeaderLink.removeClass('hidden');
								// enable the header link again
                                glow.events.removeAllListeners(myHeaderLink);
                                glow.events.addListener(
                                    myHeaderLink,
                                    "click",
                                    toggleDeepLinks						
                                );
						    },
						    onError: function(response){
							     // alert('error loading file: ' + response.statusText());
						    }
					    });
					}else{
					    // Get the list element we want to toggle
					    var myLinksListNode = theDaddy.get('ol');
						
						if(myHeaderLink.hasClass('hidden')){
					        myLinksListNode.show();
					        myHowManyStrap.show();
						    // change the direction of the link arrow (dictated by whether or not the CSS class hidden is applied)
					        myHeaderLink.removeClass('hidden');
						}else{
					        myLinksListNode.hide();
					        myHowManyStrap.hide();
						    // change the direction of the link arrow (dictated by whether or not the CSS class hidden is applied)
					        myHeaderLink.addClass('hidden');
						}
					}
				}//end toggleDeepLinks()
				
				function toggleHowMany(event){
				    event.preventDefault();
					var limit = 5;
					// Get the element which contains both the element which triggered this event and the one we want to toggle
					var theDaddy = glow.dom.get(event.attachedTo).parent().parent();					
					// Get the list element we want to toggle
				    var myDeepLinksItems = theDaddy.get('ol li');
					// toNum as in 'showing 1-toNum' - a number greater than 0 and less than or equal to limit
					var toNum = myDeepLinksItems.length > limit ? limit : myDeepLinksItems.length;
				    var mySubHeaderNode = theDaddy.get('h5');
					var myLinkNode = mySubHeaderNode.get('a');
					if(myLinkNode.text() === 'Show all'){
					    myDeepLinksItems.each(function(i){
						    if(glow.dom.get(myDeepLinksItems[i]).css('display') == 'none'){
						        glow.dom.get(myDeepLinksItems[i]).show();
							}
						});
						myLinkNode.text('Show 1-'+toNum);
						var myNewText = 'Showing 1-'+myDeepLinksItems.length+' of '+myDeepLinksItems.length+' results found ';
					}else if(myDeepLinksItems.length > 5){
					    for(var i = 5; i < myDeepLinksItems.length; i++){
						    glow.dom.get(myDeepLinksItems[i]).hide();						    
						}
						myLinkNode.text('Show all');
						var myNewText = 'Showing 1-'+toNum+' of '+myDeepLinksItems.length+' results found ';
					}else{
						myLinkNode.text('Show all');
						var myNewText = 'Showing 1-'+toNum+' of '+myDeepLinksItems.length+' results found ';
					}
					// remove the listener node to preserve it in IE
					var preservedLinkNode = mySubHeaderNode.get(myLinkNode).remove();
					//overwrite HTML content with new text and restore link with listener still preserved
					mySubHeaderNode.html(myNewText).append(preservedLinkNode);
				}//end toggleHowMany()
				
				function preventDefault(event){
                    event.preventDefault();
                }
				
				function addDeepLinksListeners() {
					glow.events.addListener(
					    glow.dom.get( "ul > li > .instances a" ),
					    "click",
                        toggleDeepLinks						
					);
					/*
					glow.events.addListener(
					    glow.dom.get( ".deep-links-header a" ),
					    "click",
                        toggleHowMany					
					);
					*/
				}//end addDeepLinksListeners()
				
				function showInstancesLinks() {
				    // deep links header links will be hidden by default so that non-Javascript users don't get them
                    // this function switches them on
					// @to do - find a less risky way to get the header links than just the class name alone
                    glow.dom.get( ".instances" ).show();				
				}//end showInstancesLinks()
				
				return {
					initDeepLinksListeners: function(){	
                        showInstancesLinks();
                        addDeepLinksListeners();
					}
				};
				
			}) ();
			
			glow.ready(function() {
				// addListeners here 
				democracy_deep_links_toggler.initDeepLinksListeners();
            });
		}
	}
);gloader.load(
	['glow', '1', 'glow.dom', 'glow.events', 'glow.data', 'glow.net', 'glow.forms', 'glow.widgets.Overlay'],
	{
		async: true,
		onLoad: function(glow) {
			var $ = glow.dom.get;
			var _addListener = glow.events.addListener;
			var submitButtonStatus = {};
			var checkgroups = [];
			var focusOn;
			var currentDate = {};
            var integerRadix = 10;
			var dateRefine = false; // - boolean used in check_box_action.js
			var myOverlay;
			var queryString = {
				sortBy: '&sort-by=Relevance',refineByDateOpt: '&refine-by-date=day_range',
				pagination: parseInt(1, integerRadix),
				refineByDate: '&in-the-last=all'
				};
			
			glow.ready(function(){
				var fieldsetNodes = $("#content-object-18-form > fieldset");
				submitButtonStatus.hide = function(){
					$('#content-object-18-form > div.submit').hide();
					$('.content-object-18').attr('id', 'no-submit-button');
				};
				submitButtonStatus.show = function(){
					$('#content-object-18-form > div.submit').show();
					$('.content-object-18').removeAttr('id');
				};
				checkgroups = 
				[
					$('div#form-wrapper-b > ol > li > input.checkbox')
				];
				initialiseSearchRefine(fieldsetNodes);
				addTopLevelListeners();
				
				glow.lang.map(checkgroups, function(node){
					$(this).each(function(){
						$(this).attr('checked', 'checked');
						$(this).parent().attr('class', 'selected');
					});
					_addListener(node, 'click', function(){
							returnChecked();
							sendQueryString();
						});
				});
				returnChecked();
				if($('input#search-locale').length > 0){
					queryString.locale = '&locale=' + $('input#search-locale').val();
				}else{
					queryString.locale = '';
				}
				
			});
			
		function addTopLevelListeners(){
			_addListener($(['div#form-wrapper-b > ol > li > a.select-all', 'div#form-wrapper-b2 > ol > li > a.select-all']), 'click', function(event){
				selectAll($(this).parent().parent().parent().get('ol > li > input.checkbox'));
				event.preventDefault();
				updateResults();
			});
			
			_addListener($(['div#form-wrapper-b > ol > li > a.clear-all', 'div#form-wrapper-b2 > ol > li > a.clear-all']), 'click', function(event){
				clearAll($(this).parent().parent().parent().get('ol > li > input.checkbox'));
				event.preventDefault();
				updateResults();
			});
			
			_addListener($(['input#date', 'input#relevance']), 'click', function(i){
				queryString.sortBy = '&sort-by='+this.value;
				refineByDateClass($('#'+this.id).parent());
				returnChecked();
				sendQueryString();
			});
			
			_addListener($('input#submit'), 'click', function(i){
				i.preventDefault();
				refineByDateValue();
				processingRequest.showAnimation($('#submit-animation'));
			});
			addPaginationListeners();
		}
		
		function selectAll(nodeList){
			nodeList.each(function(){
				this.checked = true;
			});
			returnChecked();
		}
		
		function clearAll(nodeList){
			nodeList.each(function(){
				this.checked = false;
			});
			returnChecked();
		}
		
		function returnChecked(){
			var insts = '';
			var tot = 0;
			var checkNodeLength = 0;
			glow.lang.map(checkgroups, function(node){
				checkNodeLength = node.length;
				$(node).each(function(i){
					if (this.checked) {
						if($('#panel-representatives-content-wrapper').length > 0){
							insts += '&roles[]=' + $(this).val();
							$(this).parent().attr('class', 'selected');
							tot++;
						}else{
							if($('#panel-video-content-wrapper').length > 0){
								insts += '&institutions[]=' + $(this).val();
								$(this).parent().attr('class', 'selected');
								tot++;
							}
						}
						
					}
					else {
							$(this).parent().attr('class', 'unselected');
						}
				});
				
			});;
			if(tot === checkNodeLength){
				queryString.institutions = '';
			}else{
				queryString.institutions = insts;
			}
		}
		
		function initialiseSearchRefine(fieldsetNodes){
			hideRefineOptParams(fieldsetNodes);
			submitButtonStatus.hide();
			addRefineOptionsTitles();
			addAttrToElement([[$('#form-wrapper-b > ol.hidden'), 'class', 'showing ol-a'], [$('#form-wrapper-b > h3.hidden'), 'class', 'showing']]);
			_addListener(fieldsetNodes.get('legend > a'), 'click', function(event){
				event.preventDefault();
				showHideClicked($(this));
			});
			
			if ($('div#form-wrapper-c').isWithin($('form#content-object-18-form'))) {
				getCalendarMarkup(function (response){
					createOverlay(glow.dom.create(response.text()));
				});
				refineByDateClass($('#number-of-days').parent());
				refineByDateClass($('#relevance').parent());
				_addListener($(['#between-dates' ,'#number-of-days']), 'click', refineByDate);
				disableDateInput();
			}
			if($('#panel-representatives-content-wrapper').length > 0){
				$('fieldset.fieldset-b').css('border-bottom', 'none');
			}
		}
		
		
		function createOverlay(nodelist){
				myOverlay = new glow.widgets.Overlay(nodelist, {
					width: 226,
					modal: true,
					mask: new glow.widgets.Mask({color: '#fff',opacity: 0, onClick: function(){this.remove();}}),
					autoPosition: false
				});
				
				addCalendarContentListeners();
				
				_addListener($(['input#from', 'input#to']), 'focus', displayCalendar);
				
				_addListener(myOverlay, 'afterHide', isSubmitEnabled);
                var selectorDate = myOverlay.content.get('h3')[0].className.split('-'); // - @done->defensive coding-check for existance of node
                currentDate = {
                    month: parseInt(selectorDate[1], integerRadix),
                    year: parseInt(selectorDate[0], integerRadix)
                };
		}
		
		function addCalendarContentListeners() {	
			_addListener(myOverlay.content.get('div.next > a'), 'click', getNextMonth);
			_addListener(myOverlay.content.get('div.prev > a'), 'click', getPreviousMonth);
			addListenerForMonthDays();
		}
			
		function displayCalendar(event) {
			focusOn = this.id;
			event.source.value = '';
			var offset = $(this).offset();
			myOverlay.container.css('top', (offset.top + 20)).css('left', (offset.left - 60));
			myOverlay.show();
		}
					
		function getPreviousMonth(event) {	
			event.preventDefault();
			currentDate.month--;
			if(0 === currentDate.month) {
				currentDate.month = 12;
				currentDate.year--;
			}
			getCalendarMarkup(updatePanel);
		}
			
		function getNextMonth(event) {	
			event.preventDefault();
			currentDate.month = currentDate.month % 12;
			if (!currentDate.month) { currentDate.year++; }
			currentDate.month++;
			getCalendarMarkup(updatePanel);
		}
		
		function getCalendarMarkup(onLoad) {
			var url = bbc.fmtj.apps.democracyLive.getAjaxBaseUrl() + '/democracylive/service/calendar';
			url = (! currentDate.month ?
				url :
				glow.lang.interpolate(url + '?month={year}-{month}', currentDate)
			);
			glow.net.get(url, {
					useCache: true,
					onLoad: onLoad,
					onError: function(response){
						// console.log('error loading file: ' + response.status+ " " +response.statusText());
					}
				});
		}
			
		function updatePanel(response) {
            var contentReplacement = glow.dom.create(response.text());
            // - @todo Check if response.text() is not html - does glow throw an error
            myOverlay.content.html(contentReplacement.html());
            // @todo Cache each calendar view's nodelists or strings in memory.
            // Cache nodelists or strings depending on whether detached nodes retain their listeneres.
            addCalendarContentListeners();	
        }
	
		function addListenerForMonthDays() {
			var myLinks = myOverlay.content.get('table > tbody > tr > td > a');
			_addListener(myLinks, 'click', function(e){
				e.preventDefault();
				insertSelectedDate($(this).html());
			});
		}
			
		function insertSelectedDate(selectedDay) {
			var clickedDay = selectedDay;
			var selectedDateString = clickedDay+'/'+currentDate.month+'/'+currentDate.year;
			$('#'+focusOn).val(selectedDateString);
			myOverlay.hide();
		}
			
			
		function hideRefineOptParams(fieldsetNodes){
			for(var i=1;i<fieldsetNodes.length; i++){
				$(fieldsetNodes.get('legend > a').slice(i, i+1)).attr('class', 'hidden');
				$(fieldsetNodes.get('legend > a').slice(i, i+1)).parent().next().hide();
			}
		}
		
	
		function addRefineOptionsTitles(){
			addAttrToElement([
				[$('#sort-by > a'), 'title', 'Hide sort by'],
				[$('#refine-by-institution > a'), 'title', 'Show refine by institution'],
				[$('#refine-by-date > a'), 'title', 'Show refine by date'],
				[$('#by-event > a'), 'title', 'Show refine by event']
				]);
		}


		function addAttrToElement(obj){
			for(var i=0; i<obj.length; i++){
				obj[i][0].attr(obj[i][1], obj[i][2]);
			}
		}
		
		function showHideClicked(node){
			if(node.hasClass('hidden')){
				node.removeAttr('class');
				node.parent().next().show();
				addAttrToElement([[node, 'title', glow.lang.replace(node.attr('title'), /Show/, 'Hide')]]);
				if(node.attr('title').indexOf('date') != -1){
					submitButtonStatus.show();
				}
			}else{
				node.parent().next().hide();
				addAttrToElement([[node, 'class', 'hidden'],[node, 'title', glow.lang.replace(node.attr('title'), /Hide/, 'Show')]]);
				if(node.attr('title').indexOf('date') != -1){
					submitButtonStatus.hide();
				}
			}
		}
		
		function refineByDate(){
			queryString.refineByDateOpt = '&refine-by-date=' + $(this).val();
			if('number-of-days' === this.id){
				if ($('#date-from > label').hasAttr('class')) {	$('#date-from > label').removeAttr('class'); }
				if ($('#date-to > label').hasAttr('class')) { $('#date-to > label').removeAttr('class'); }
				if($('#submit').hasAttr('disabled')){$('#submit').removeAttr('disabled');}
				$('#select-number-of-days').removeAttr('disabled');
				$('#error-message').hide(); 
				$('#to').attr('class', 'input');
				disableDateInput();
				dateRefine = false;
			}else{
				addAttrToElement([[$('#select-number-of-days'), 'disabled', 'disabled'], [$('#submit'), 'disabled', 'disabled']]);
				$('input#to').removeAttr('disabled');
				$('input#from').removeAttr('disabled');
				dateRefine = true;
				if(/\d{1,2}\/\d{1,2}\/\d{4}/.test($('#from').val()) && /\d{1,2}\/\d{1,2}\/\d{4}/.test($('#to').val())){
					$('#submit').removeAttr('disabled');
					validateDates();
				}
			}
			refineByDateClass($('#'+this.id).parent());
		}
			
		function refineByDateClass(selectedParent){
			if(selectedParent.attr('class').indexOf('a')===-1){
				addAttrToElement([[selectedParent, 'class', 'b selected'], [selectedParent.prev(), 'class', 'a unselected']]);
			}else{
				addAttrToElement([[selectedParent, 'class', 'a selected'], [selectedParent.next(), 'class', 'b unselected']]);
			}
		}
		
		function isSubmitEnabled(){
			var node = $('#'+focusOn);
			var regex = /\d{1,2}\/\d{1,2}\/\d{4}/;
			if (regex.test(node.val())) {
				node.prev().removeAttr('class');
				if(regex.test($('#from').val()) && regex.test($('#to').val())){
					validateDates();
				}
			}else {
				addAttrToElement([[node.prev(), 'class', 'highlight'], [$('#submit'), 'disabled', 'disabled']]);
			}
		}
		
		function disableDateInput(){
			if($(['input#from', 'input#to'])){
				addAttrToElement([[$('input#from'), 'disabled', 'disabled'], [$('input#to'), 'disabled', 'disabled']]);
			}
		}
		
		function refineByDateValue()
		{
			if ($('div#form-wrapper-c').length > 0) {
				if (!dateRefine) {
					queryString.refineByDate = '&in-the-last=' + $('select#select-number-of-days').val();
				}
				else {
					//validateDates();
				}
			}else{
				queryString.refineByDate = '';
			}
			updateResults();
		}
		
		function validateDates(){
				var rawDateFrom = glow.dom.get('#from').val().split('/');
		  		var rawDateTo = glow.dom.get('#to').val().split('/');
				var dateFrom = rawDateFrom[1] + '/' + rawDateFrom[0] + '/' + rawDateFrom[2];
				var dateTo = rawDateTo[1] + '/' + rawDateTo[0] + '/' + rawDateTo[2];
				
	  			if (Date.parse(dateFrom) > Date.parse(dateTo)) {
	  				$('#error-message').show();
					addAttrToElement([[$('#submit'), 'disabled', 'disabled'],[$('#to'), 'class', 'input error']]);
					return;
	  			}else{
					 
					queryString.refineByDate = '&mindate=' + $('input#from').val() + "&maxdate=" + $('input#to').val();
					if($('#error-message').length > 0){
						$('#error-message').hide(); 
						$('#to').attr('class', 'input');
						$('#submit').removeAttr('disabled');
					}
				}
	  	}
		
		function sendQueryString(){
			refineByDateValue();
		}
		
		function updateResults(event) {
			queryString.query = 'q='+$('#search-term').val();
			queryString.refineByInstitution = '';
			queryString.refineByLocation = '';
			if($('#panel-historic-moments-content-wrapper').length>0){
				queryString.section = 'historic-moments';
				queryString.institutions = '';
			}else{
				if($('#panel-representatives-content-wrapper').length > 0){
					queryString.section = 'representatives';
					queryString.refineByDateOpt = '';
					queryString.refineByDate = '';
					if($('#institution-search-term').val().length > 0){
						queryString.refineByInstitution = '&institution=' + $('#institution-search-term').val();
					}
					if($('#location-search-term').val().length > 0){
						queryString.refineByLocation = $('#location-search-term').val();
					}
				}else{
					queryString.section = 'media';
				}
			}
			if($('div#form-wrapper-a').length<1){queryString.sortBy = '';}
            var url = bbc.fmtj.apps.democracyLive.getAjaxBaseUrl();
			url = glow.lang.interpolate(url + '/democracylive/service/search?{query}{sortBy}{institutions}{refineByDateOpt}{refineByDate}&type={section}{refineByInstitution}{refineByLocation}&start={pagination}{locale}', queryString);
			glow.net.get(url, 
				{
					useCache: true,
					onLoad: function(response){
						var myData = response.json();
						var pageCount = parseInt(glow.dom.create(myData.meta).val(), integerRadix);
						if(pageCount < queryString.pagination){
							queryString.pagination = pageCount; //pageCount;
							saveCorrectMaxPage();
						}else{
							processingRequest.hideAnimation($('#submit-animation'));
							updateSearchResults(myData);
						}
					},
					onError: function(response){
						// console.log('error loading file: ' + response.status+ " " +response.statusText());
					}
				}
			);
		}
		
		function updatePageContent(property){
			for(var i=0; i<property.length; i++){
				$(property[i][1]).replaceWith(glow.dom.create(property[i][0]));
			}
		}
		
		function updateSearchResults(data)
		{
			if ($('#panel-video-content-wrapper').length > 0) {
				updatePageContent([
				[data.dl_media_relatedsearches, '#panel-related-searches'], 
				[data.dl_media, $('#panel-video-content-wrapper')], 
				[data.dl_representatives_panel, '#panel-representative-search'],
				[data.head, '#pagination-top'],
				[data.foot, '#bottom']]);
				addPaginationListeners();
				runSearchDeepLinks();
				return;
			}
			if($('#panel-representatives-content-wrapper').length > 0){
				updatePageContent([
				[data.dl_representatives, $('#panel-representatives-content-wrapper')],
				[data.head, '#pagination-top'],
				[data.foot, '#bottom']
				]);
				addPaginationListeners();
				return;
			}
			if($('#panel-historic-moments-content-wrapper').length > 0){
				updatePageContent([
				[data.dl_historic_moments, $('#panel-historic-moments-content-wrapper')],
				[data.head, '#pagination-top'],
				[data.foot, '#bottom']
				]);
				addPaginationListeners();
				runSearchDeepLinks();
				return;
			}
		}
		
		function addPaginationListeners(){
			if($('div#pagination-links-top').length > 0){
				var pageNavLinks = $('div#pagination-links-top > ul > li').push($('div#pagination-links-bottom > ul > li'));
				if($('h3.previous').isWithin($('div'))){
					pageNavLinks.push($('div#pagination-links-top > h3.previous')).push($('div#pagination-links-bottom > h3.previous'));
				}
				if($('h3.next').isWithin($('div'))){
					pageNavLinks.push($('div#pagination-links-top > h3.next')).push($('div#pagination-links-bottom > h3.next'));
				}
				
				pageNavLinks.each(function(){
					if(!$(this).hasClass('selected')){
						_addListener($(this), 'click', function(ev){
							ev.preventDefault();
							var clickedId = $(this).children().attr('class');
							queryString.pagination = parseInt(clickedId.split('-')[1], integerRadix);
							updateResults();
						});
					}
				});
			}
		};
		
		function saveCorrectMaxPage(){
			updateResults();
		}
		
		function runSearchDeepLinks(){
			democracy_deep_links_toggler.initDeepLinksListeners();
		}
		}//end of glow onload
	});
gloader.load(
	["glow", "1", "glow.dom", "glow.events"],
	{
		onLoad: function(glow){
			bbc.fmtj.utils.createObject("bbc.fmtj.apps.democracy_search_results_filter");

			bbc.fmtj.apps.democracy_search_results_filter = (function() {
			    /* initialise vars */
				/* Text links will have an onclick behaviour applied to them */
			    var institutionsIds = [
				    "#house-of-commons",
				    "#house-of-lords",
				    "#scotland",
				    "#wales",
				    "#northern-ireland",
				    "#europe"
				];

				function filterResults( event ) {
					var myTargetId = event.attachedTo.id;
					var myTargetNode = glow.dom.get( "#" + myTargetId );
					
					for ( var id in institutionsIds ){
					    var myLiNode = glow.dom.get( "#institutions-filters" ).get( institutionsIds[ id ] );
					    if ( myTargetNode.isWithin( myLiNode ) ){
							// Get the checkbox as a Glow node
							var myCheckBox = myLiNode.get( institutionsIds[ id ] + "-checkbox" );
							alert( myCheckBox.attr( "id" ) );
							var myChecked = myCheckBox[0].checked;                         //core DOM
							//var myChecked = myCheckBox.attr( "checked" );     // Glow
							alert( myChecked );
							if( myChecked ){
								//myCheckBox.attr( "checked", false );    Glow
								myCheckBox[0].checked = false;    // Core DOM
								alert( myCheckBox.attr( "id" ) + " should be unchecked now" );
							}else{
							    //myCheckBox.attr( "checked", true );  Glow
								myCheckBox[0].checked = true;     // core DOM
								alert( myCheckBox.attr( "id" ) + " should be checked now" );
							}
						}
					}
                    event.preventDefault();					
				}
				
				function addLinksListeners( ids, eventType, scope ) {
				    if ( scope ){
					    glow.events.addListener(
					        ids,
					        eventType,
                            filterResults,
                        	scope					
					    );
					}else{
					    glow.events.addListener(
					        ids,
					        eventType,
                            filterResults			
					    );
					}
				}
				
				return {
					initLinksListeners: function(){	
                        for	( var id in institutionsIds ){
							var listItemId = institutionsIds[ id ];
							/* Add a listener to this list item's link */
							glow.events.addListener( listItemId + "-link", "click", filterResults )
							/* Add a listener to this list item's checkbox */
							glow.events.addListener( listItemId + "-checkbox", "click", filterResults )
                        }
					}
				};
				
			}) ();
			
			glow.ready(function() {
				// addListeners here 
				bbc.fmtj.apps.democracy_search_results_filter.initLinksListeners();
            });
		}
	}
);/*gloader.load(
	["glow", "1", "glow.dom", "glow.anim"],
	{
		onLoad: function(glow){
		
			bbc.fmtj.net.json.model.registerRenderer(function(){
		
				var democracyLiveScheduleRenderer = bbc.fmtj.net.json.renderer.createRendererBase("democracyLiveScheduleRenderer");
				democracyLiveScheduleRenderer.render = function(schedulesObj, json){									
					// create empty arrays to hold animations
					var fadeInAnims = [], fadeOutAnims = [];

					//create an array of content divs
					var schedules = [];
					for(var item in schedulesObj){
					    schedules.push(schedulesObj[item]);
					}
					var animatingDivs = glow.dom.get(schedules).each(function(i){
                        var mycontentId = this.contentId;			
						var myNode = glow.dom.get(mycontentId);
						var feedData = json[this.scheduleDataName];
						//var regex = new RegExp( ' xmlns=\\"http:\\/\\/www.w3.org\\/1999\\/xhtml\\"', 'g' );
						//var strippedStr = glow.lang.replace(feedData, regex, '');
						var feedDataNode = glow.dom.create('<div>'+feedData+'</div>');
						//glow.lang.replace(feedData, regex, '');
						
					    // Check whether the new node data is different from the existing  content node data
						// If not, there's nothing to do
						if(myNode.html() == feedDataNode.html())return false;
						//alert(unescape(myNode.html()));
						//alert(feedData);
					
					    // Store the original CSS settings so we can return to them later
						var origColor = glow.dom.get(mycontentId).css('color');
						var origBackGroundColor = glow.dom.get(mycontentId).css('background-color');
						
						// Add animations for this content element to our animations array
					    fadeInAnims[i] = glow.anim.css(mycontentId, 0.5, {
							"opacity": {
							"from": 0,
							"to": 1
							}
						});
					    fadeOutAnims[i] = glow.anim.css(mycontentId, 0.5, {
							"opacity": {
							"from": 1,
							"to": 0
							}
						});
						
						// Use the CSS opacity property to hide the content, then change the CSS colours 
						// and secretly overwite the content with a loading image
						myNode.css('opacity', 0);
						myNode.css('color', '#efefef');
						myNode.css('background-color', '#efefef');
						myNode.html('<img id="loader" class="loader-anim" src="http://newsimg.bbc.co.uk/sol/shared/img/v4/icons/loading.gif" />');
						
						// A listener which waits for the loading fade-out animation to complete, then
						// fires a function which resets the CSS to the original settings, overwrites
						// the existing  content with new content, and starts the fade-in animaton
						glow.events.addListener(fadeOutAnims[i], 'complete', function(){
						    myNode.css('color', origColor);
						    myNode.css('background-color', origBackGroundColor);
						    //glow.dom.get(mycontentId).html(json[scheduleData]);
						    myNode.html(feedDataNode.html());
						    myNode.css('opacity', 1);
							fadeInAnims[i].start();
						});
					});					
					var channels = [];
					for (i = 0, len = fadeInAnims.length; i < len; i++) {
					  //channels[i] = [ fadeInAnims[i], 3, fadeOutAnims[i], displayContentAnims[i] ];
					  channels[i] = [ fadeInAnims[i], 3, fadeOutAnims[i] ];
					}

					//put it all together and play
					new glow.anim.Timeline(channels, {loop:false}).start();					
				}
				return democracyLiveScheduleRenderer;
				
			});
		}
	}
)*/