
var Mwr = {
	Controller: null,
	Home: null,
	Supplemental: null,
	Clients: null,
	Brokers: null,
	Companies: null,
	Dashboard: null,
	Login: null
};

/**
 * Run every page through here and feed it only the JS it needs.
 */
Mwr.Controller = {
	init: function() {
		// Always run this (located in script.js)
		Ctm.System.init();
		
		//Show body after everything is loaded to prevent "flash" of slider content
		$('body').css('display', 'block');

		// Fire off JS based on URI segment
		var uri = document.location.pathname.split('/');

		// Dashboard
		if (uri[1] == 'dashboard') { Mwr.Dashboard.init(); }

		// All Favorite Companies
		if (uri[1] == 'dashboard' && uri[2] == 'favorites') { Mwr.Dashboard.getAllFavoriteCompanies(); }

		// All Favorite Research
		if (uri[1] == 'dashboard' && uri[2] == 'research') { Mwr.Dashboard.allResearch(); }

		// Research
		if (uri[1] == 'dashboard') {
			if (uri[2] == 'research-detail' || uri[2] == 'browse-research' || uri[2] == 'research') {				
				Mwr.Research.init();
			}
		}
		// If doing a search from detail page, redirects back to browse		
		if (uri[1] == 'dashboard' && uri[2] == 'research-detail')
		{
			Mwr.Research.searchRedirect();
			Mwr.Companies.init();	
		}
		
		// Research
		if (uri[1] == 'research') {
			Mwr.AllResearch.init();
		}
		// Recent Research
		if (uri[1] == 'research' && uri[2] == 'recent-research') {				
			Mwr.AllResearch.initRecent();
		}
		
		// MWR Week in Reviews Research
		if (uri[1] == 'research' && uri[2] == 'past-reviews') {				
			Mwr.MwrResearch.initRecent();
		}
		
		// Companies page (part of the dashboard)
		if (uri[1] == 'dashboard' && uri[2] == 'companies') {			
			Mwr.Companies.init();
		}
		
		//Location pages
		if (uri[1] == 'our-company' && uri[2] == 'locations') { Mwr.Locations.init(); }
		
		//Account Forms
		if (uri[1] == 'account' || uri[2] == 'edit-account') { Mwr.Account.init(); }
		
		// Our Company > Directory Page
		if (uri[1] == 'our-company' && uri[2] == 'directory') { Mwr.Accordion.init(); }

		// Our Company > Management
		if (uri[1] == 'our-company' && uri[2] == 'management') { Mwr.Accordion.init(); }

		// News
		if (uri[1] == 'news') { Mwr.News.init(); }
				
		// Research > Team Page
		if (uri[1] == 'research' && uri[2] == 'team') { Mwr.Accordion.init(); }
		
		if (uri[1] == 'team' && uri[2] == 'page') 
		{
			$(".brokertitle").each(function(){
							var titleHtml = $(this).html();
							$(this).html(titleHtml.replace(/,/g , ',<br/>'));
						});
		}
		
		
		// Homepage or SupplementalPage
		if (uri[1] == '') {
			Mwr.Home.init();
		} else {
			Mwr.Supplemental.init();
		}
	}
};

/**
 * Homepage JS
 */
Mwr.Home = {
	init: function() {
		objElements.$body.addClass('homepage');
		Mwr.Home.stickyFooter();
		Mwr.Home.rotatingBackgroundImage();
		
	},

	// Add content to the sticky footer
	stickyFooter: function() {
		$('footer').before($('#extra-footer'));
	},
	
	rotatingBackgroundImage: function() {
		$('#slider').slides({
			effect: 'fade',
			generatePrevNext: false,
			generatePagination: false,
			play: 5000,
			animationStart: function() {
				$('#slider-links a').removeClass('active');
			},
			animationComplete: function(slideNum) {
				$('#link-'+slideNum).addClass('active');
			}
		});
		
		objElements.$window.bind('resize load', function() {
			// Adjust background images to stay centered in the window
			if (objElements.$body.width() < 1500 && objElements.$body.width() > 960) {
				var updatedLeft = Math.round((objElements.$body.width() - 1500) / 2);
				updatedLeft = updatedLeft + 'px';
				$('.homepage > #slider .slides_container').css('left', updatedLeft);
				$(this).css('overflow', 'hidden');
			} else if (objElements.$body.width() == 960) {
				console.log('awesome');
				$('.homepage > #slider .slides_container').css('left', '-270px');
			} else {
				$('.homepage > #slider .slides_container').css('left', 0);
			}
		});
	}
};

/**
* Locations Page
*/
Mwr.Locations = {
	init: function() {
		Mwr.Locations.contactFormModal();
		Mwr.Locations.buildHeader();
	},
	
	contactFormModal: function() {
		$('#contact-wrapper').hide();
		$('#contact-link').click(function() {
			$('#contact-wrapper').dialog({
				modal: true,
				resizable : false,
				title: 'Contact This Office',
				width: 500,
				open: function() {
					$('#contact-wrapper').show();
				}
			});
		});
	},
	
	buildHeader: function() {
		//Add class to content section
		$('#main > section').attr('id', 'location-content');
		
		var $heading = $('#main h1');
		var headingText = $heading.text().split(', ');
		
		//Check if a State is defined and put a comma after the city
		if (headingText[1] == undefined) {
			headingText[1] = '';
		} else {
			headingText[0] += ',';
		}
		
		//Create wrapper for header text
		$heading.wrap('<div id="location-header" />');
		$heading.replaceWith(
			'<h1>' + headingText[0] + '</h1>' +
			'<h3>' + headingText[1] + '</h1>'
		);
	}
};

/**
* Accordian settings
*/
Mwr.Accordion = {
	init: function() {
		Mwr.Accordion.addAccordionClass();
		Mwr.Accordion.createColumns();
	},
	
	addAccordionClass: function () {
		$('#accordion h2, #accordion h4').addClass('acc_trigger');
		$('#accordion > div').addClass('acc_container clearfix');
		
		Mwr.Accordion.accordionAction();
	},
	
	accordionAction: function () {
		$('.acc_trigger').prepend('<span class="header-icon"></span>');
		
		$('.acc_container').hide(); //Hide/close all containers
		
		//On Click
		$('.acc_trigger').click(function(){
			
			if( $(this).next().is(':hidden') ) { //If immediate next container is closed...
				$('.acc_trigger').next().slideUp('500', function() {
					$(this).prev().removeClass('active').children('.header-icon').removeClass('active'); //Make all arrows point to the right
					$('.no-info').removeClass('active');
				}); //Remove all "active" state and slide up the immediate next container
				$(this).toggleClass('active').next().slideDown(); //Add "active" state to clicked trigger and slide down the immediate next container
				$(this).children('.header-icon').toggleClass('active');
				if ($(this).next().is(':last-child') && $(this).parent().next().attr('class') == 'no-info') {
					$('.no-info').addClass('active');
				}
			} else {
				$('.acc_trigger').next().slideUp('500', function() {
					$(this).prev().removeClass('active').children('.header-icon').removeClass('active'); //Make all arrows point to the right
					$('.no-info').removeClass('active');
				}); //Remove all "active" state and slide up the immediate next container
			}
			return false; //Prevent the browser jump to the link anchor
		});
	},
	
	createColumns: function() {
		$('.acc_container').each(function() {
			var listCount = $(this).find('li').length;
			var maxColCount = Math.ceil(listCount / 2);
			
			if (listCount > maxColCount) {
				var $listItems = $(this).find('li:gt(' + (maxColCount - 1) + ')');
				$listItems.detach();
				$(this).append('<ul></ul>');
				$(this).find('ul:last-child').append($listItems);
			}
		});
	}
}

/**
 * CTM.Supplemental
 *
 * JS that runs on supplemental pages.
 */
Mwr.Supplemental = {
	init: function() {
		// Add a class that indicates it's a supplemental page
		objElements.$body.addClass('sup');

		if (!objElements.$body.hasClass('companies')) {
			Mwr.Supplemental.matchElementHeight();
		}
		
		//Mwr.Supplemental.changeLocationsLink();
	},
	
	/*
	changeLocationsLink: function() {
		$('a[href="/our-company/locations"]').each(function() {
			var originalLink = $(this).attr('href');
			$(this).attr('href', originalLink + '/seattle');
		});
	},
	*/

	// Fuction to set the matching heights
	matchElementHeight: function() {
		objElements.$window.load(function() {
			// Reset the heights
			$('#main > section, #main > aside').css('height', 'auto');

			// Get the height of all the sections
			var sectionHeight = parseInt($('#main > section').css('height'), 10);
			var asideHeight = parseInt($('#main > aside').css('height'), 10);
			var matchingHeight;

			// Check which height is larger and set it as the 'matchingHeight'
			if (sectionHeight > asideHeight) {
				matchingHeight = sectionHeight;
			} else {
				matchingHeight = asideHeight;
			}

			// Set the 'matchingHeight' on all the elements
			$('.team #main > section, .team #main > aside, .cms #main > section, .cms #main > aside, .news #main > section, .news #main > aside, .recent-research #main > section, .recent-research #main > aside, .research.index #main > section, .research.index #main > aside, .recent.team #main > section, .recent.team #main > aside').css('minHeight', matchingHeight);
		});
	}
};

/**
 * Mwr.Clients
 */
Mwr.Clients = {
	init: function() {}
};

/**
 * jqGrid Defaults
 */
Mwr.Grid = {
	// Defaults for bottom nav bar
	navDefaults: {
		edit: false,
		add: false,
		del: false,
		search: false,
		refresh: false
	},

	// Defaults for adding search to column headers
	filterDefaults: {
		stringResult: true,
		searchOnEnter: false,
		defaultSearch: 'cn'
	},

	// Callback after jqGrid is rendered
	afterComplete: function() {
		$('#gs_actions').remove();
		$('.ui-search-toolbar input').attr('autocomplete', 'off').addClass('search');
	},

	init: function() {
		// Defaults for main jqGrid functionality
		$.extend($.jgrid.defaults, {
			datatype: 		'json',
			loadonce: 		true,
			// autowidth: 	true,
			rowNum: 		20,
			viewrecords: 	true,
			shrinkToFit: 	true,
			width:			535,
			sortorder: 		'asc',
			pginput: 		false,
			ignoreCase: 	true,
			height: 		'100%'
		});
	}
};

Mwr.Dashboard = {
	limits: {
		dashboardCompanies: 5,
		dashboardResearch: 8,
		allResearch: 20
	},
	offsets: {
		allResearch: 0
	},

	init: function() {
		objElements.$body.addClass('dashboard');

		Mwr.Dashboard.undoMatchingHeight();
		Mwr.Dashboard.getRecentResearch();
		Mwr.Dashboard.getFavoritesCompanies();
		Mwr.Dashboard.sidebarResearchList();
		Mwr.Dashboard.adjustBackground();
		Mwr.Dashboard.stockQuote();

	},

	// Removes column heights
	undoMatchingHeight: function() {
		$('#main > section, #main > aside').css('height', 'auto');
	},

	// Get recent research by favorite companies
	getRecentResearch: function() {
		$.ajax({
			url: '/api/research/favorite',
			type: 'POST',
			data: {limit: Mwr.Dashboard.limits.dashboardResearch + 1},
			success: function(data) {
				// If there are more records, show more link and remove last element
				if (data.data.research.length > Mwr.Dashboard.limits.dashboardResearch) {
					data.data.research.splice(Mwr.Dashboard.limits.dashboardResearch);
				}

				$.each(data.data.research, function(i, research) {
					$('table#recent-research').append(
						'<tr>' +
							'<td><time>' + research.tsPublished + '</time></td>' +
							'<td><a href="/dashboard/research-detail/' + research.researchID + '">(' + research.symbol + ') ' + research.title + '</a></td>' +
						'</tr>'
					);
				});
		  	}
		});
	},

	// Get recent research by favorite companies and display in a list
	sidebarResearchList: function() {
		$.ajax({
			url: '/api/research/favorite',
			type: 'POST',
			data: {limit: 6},
			success: function(data) {
				// If there are more records, show more link and remove last element
				if (data.data.research.length > 5) {
					$('#recent-research-list').parent().prepend('<ul class="section-options"><li><a href="/dashboard/research/">View All</a></li></ul>');
					data.data.research.splice(5);
				}

				$.each(data.data.research, function(i, research) {
					$('#recent-research-list').append(
						'<li>' +
							'<a href="/dashboard/research-detail/' + research.researchID + '">' +
								'<time>' + research.tsPublished + '</time> ' +
								'(' + research.symbol + ') ' + research.title +
							'</a>' +
						'</li>'
					);
				});
		  	}
		});
	},

	// Favorites list for Dashboard
	getFavoritesCompanies: function() {
		$.ajax({
			url: '/api/companies/getfavorites',
			type: 'POST',
			data: {limit: Mwr.Dashboard.limits.dashboardCompanies + 1},
			success: function(data) {
				// If there are more records, show more link and remove last element
				if (data.data.companies.length > Mwr.Dashboard.limits.dashboardCompanies) {
					$('#client-favorites').prev().prepend('<li><a href="/dashboard/favorites/">View All</a></li>');
					data.data.companies.splice(Mwr.Dashboard.limits.dashboardCompanies);
				}

				$.each(data.data.companies, function(i, company) {
					$('#client-favorites').append(
						'<tr>' +
							'<td class="symbol">' + company.symbol + '</td>' +
							'<td class="name"><a href="/dashboard/browse-research/' + company.companyID + '" data-company-id="' + company.companyID + '">' + company.name + '</a></td>' +
							'<td><a href="#" class="remove-favorite-action" data-company-id="' + company.companyID + '" data-toggle="remove" title="Remove">Remove</a></td>' +
						'</tr>'
					);
				});
			}
		});

		Mwr.Companies.removeFavorite();
	},

	// Get jqGrid of all your favorited companies
	getAllFavoriteCompanies: function() {
		// Call Grid.init() to set default values for jqGrid
		Mwr.Grid.init();

		$('#companies-grid').jqGrid({
			url: '/api/companies/getallfavorites',
			colNames: ['Symbol', 'Company', ''],
			colModel: [
				{name: 'symbol', index: 'symbol', width: 60},
				{name: 'name', index: 'name', width: 420},
				{name: 'actions', index: 'actions', width: 40}
			],
			pager: '#companies-pager',
			sortname: 'name',
			loadComplete: Mwr.Grid.afterComplete,

			// Callback after jqGrid is rendered
			afterComplete: function() {
				Mwr.Grid.afterComplete();
			}
		}).navGrid('#companies-pager', Mwr.Grid.navDefaults);

		Mwr.Companies.removeFavorite();
	},

	// initialize the favorite research paginated page
	allResearch: function() {
		window.location.hash = '#1';
		Mwr.Dashboard.getAllResearch(1);

		$('.research-pagination a').live('click', function() {
			var offset = $(this).attr('href').substring(1);
			Mwr.Dashboard.getAllResearch(offset);
		});

	},

	// Get all research by favorite companies, with pagination
	getAllResearch: function(offset) {
		var $pagination = $('.research-pagination')
		var $table = $('#favorite-research')

		$pagination.html('');
		$table.html('');

		if (offset !== undefined) {
			Mwr.Dashboard.offsets.allResearch = (parseInt(offset) - 1) * parseInt(Mwr.Dashboard.limits.allResearch);
		}

		$.ajax({
			url: '/api/research/favorite',
			data: {
				limit: Mwr.Dashboard.limits.allResearch + 1,
				offset: Mwr.Dashboard.offsets.allResearch
			},
			success: function(data) {
				// If this isnt the first page of results, show previous link
				var previous = parseInt(Mwr.Dashboard.offsets.allResearch) / parseInt(Mwr.Dashboard.limits.allResearch);
				if (previous > 0) {
					$pagination.append('<li><a href="#' + previous + '">Previous</a></li>');					
				}
				// If there are more records, show more link and remove last element
				if (data.data.research.length > parseInt(Mwr.Dashboard.limits.allResearch)) {
					var next = previous + 2;
					$pagination.append('<li><a href="#' + next + '">Next</a></li>');
					data.data.research.pop();
				}

				$.each(data.data.research, function(i, research) {
					$table.append(
						'<tr>' +
							'<td>' + research.tsPublished + '</td>' +
							'<td><a href="/dashboard/research-detail/' + research.researchID + '">(' + research.symbol + ') ' + research.title + '</a></td>' +
						'</tr>'
					);
				});
			}
		});
	},

	// Add a gradient to the top of the page
	adjustBackground: function() {
		// background-size fallback
		if(!Modernizr.backgroundsize) {
			$('body').append(
				'<style>' +
				'body { background-image:none !important; position: relative; border: none !important; } ' +
				'body > * { position:relative; z-index:9999; }' +
				'img#bg { border: none; left: 0; width: 100%; position:fixed; z-index:1; }' +
				'</style>'
			);
			objElements.$body.prepend('<img src="/assets/images/dashboard-body-bg-ie.jpg" id="bg" />');
		} else {
			objElements.$html.css('backgroundImage', objElements.$body.css('backgroundImage')).addClass('account-dashboard');
		}

		// add gradient
		objElements.$body.prepend('<div id="extra-bg" />');
	},

	// get the stock quote info from Google
	stockQuote: function() {
		var names = [
			'DOW',
			'EURO',
			'GOLD',
			'YEN',
			'NASDAQ',
			'OIL',
			'S&P'
		]
		var symbols = 'INDEXDJX:.DJI,EUR,GOLD,LON:JPYP,INDEXNASDAQ:.IXIC,OIL,INDEXSP:.INX';
		$.getJSON('http://finance.google.com/finance/info?client=ig&q=' + symbols + '&callback=?', function(data){
			 $ticker = $('#stock-ticker');
			$.each(data, function(i, item) {
				var style = (item.c > 0) ? 'up' : 'down';
				$ticker.append('<li class="' + style + '">' + names[i] + ': <span>' + item.c.substr(1) + '</span> (' + item.cp + '%)</li>');
			});

			 width = 0;
			 speed = 20 * 1000;
			$.each($ticker.children(), function(i, child) {
				width += $(this).width() + 10;
			});

			// duplicate items for smooth transition
			$ticker.append($ticker.clone().children());
			
			// animate the ticker
			var tickerAnimation = function(cont) {
				if(cont == 'undefined' || !cont) {
					$ticker.css('marginLeft', 0);
				}
				var percent = width/2 / (width/2 - parseInt($ticker.css('marginLeft')));
				$ticker.animate({'marginLeft': -width}, speed * percent, 'linear', tickerAnimation);
			};
			tickerAnimation();

			/*$ticker.hover(function() {
				$ticker.stop();
			}, function() {
				tickerAnimation(true)
			});*/
		});
	}
};

/**
 * Company Management (Front End)
 */
Mwr.Companies = {
	init: function() {
		Mwr.Companies.getAll();
	},

	// jqGrid of all companies, with a favorite toggle
	getAll: function() {

		// Call Grid.init() to set default values for jqGrid
		Mwr.Grid.init();

		$('#companies-grid').jqGrid({
			url: '/api/companies/all',
			rowNum: 10,
			colNames: ['Symbol', 'Company', ''],
			colModel: [
				{name: 'symbol', index: 'symbol', width: 60},
				{name: 'name', index: 'name', width: 400},
				{name: 'actions', index: 'actions', width: 60}
			],
			pager: '#companies-pager',
			sortname: 'name',		
			loadComplete: Mwr.Grid.afterComplete,

			// Callback after jqGrid is rendered
			afterComplete: function() {
				Mwr.Grid.afterComplete();
				$('#gs_actions').remove();
				$('.ui-search-toolbar input').attr('autocomplete', 'off').addClass('search');
			}
		}).navGrid('#companies-pager', Mwr.Grid.navDefaults);

		$('#companies-grid').jqGrid('filterToolbar', Mwr.Grid.filterDefaults);

		Mwr.Companies.setFavorite();
	},

	// Hijack remove favorite links
	removeFavorite: function() {
		$('.remove-favorite-action').live('click', function(e) {
			e.preventDefault();
			$this = $(this);

			var companyID = $this.attr('data-company-id');
			var toggle = $this.attr('data-toggle');

			$.ajax({
				url: '/api/companies/setfavorite',
				type: 'POST',
				data: {
					companyID: companyID,
					toggle: toggle
				},

				success: function(data) {
					$this.parent().parent().remove();
				}
			});
		});
	},

	// Hijack toggle favorite links
	setFavorite: function() {
		$('.favorite-action').live('click', function(e) {
			e.preventDefault();
			$this = $(this);

			var companyID = $this.attr('data-company-id');
			var toggle = $this.attr('data-toggle');

			// TODO : add dialog box asking are you sure...
			$.ajax({
				  url: '/api/companies/setfavorite',
				  type: 'POST',
				  data: {
						companyID: companyID,
						toggle: toggle
					},
				  success: function(data) {
				  	if(data.response == 'add') {
						$this.removeClass('like').addClass('unlike').attr('data-toggle', 'remove').text('Remove');
				  	} else if(data.response == 'remove') {
						$this.removeClass('unlike').addClass('like').attr('data-toggle', 'add').text('Add');
				  	}
				  }
			});
		});
	}
};

Mwr.Research = {
	init: function() {
		Mwr.Research.browse();
		Mwr.Research.filter();
	},

	// Get all research, filtered by company and/or sector, with pagination
	browse: function(company, sector) {
				
		var uri = document.location.pathname.split('/');
		
		var companyID = (uri[3] !== undefined) ? uri[3] : 0;
		var sectorID = (uri[4] !== undefined) ? uri[4] : 0;
		
		// if values came through url, preset the values in the form
		$('#companyID').val(companyID);
		$('#sectorID').val(sectorID);
		
		$table = $('#browse-research');

		$.ajax({
			url: '/api/research/filtered',
			data: {limit: 10, companyID: companyID, sectorID: sectorID},
	  		success: function(data) {
				$table.empty();
				if (data.data.research.length == 0) {
					$table.append(
						'<tr><td rowspan="2">There are no results for these search parameters.</td></tr>'
					);
				} else {
					$.each(data.data.research, function(i, research) {
						$table.append(
							'<tr>' +
								'<td>' + research.tsPublished + '</td>' +
								'<td><a href="/dashboard/research-detail/' + research.researchID + '">(' + research.symbol + ') ' + research.title + '</a></td>' +
							'</tr>'
						);
					});
				}
		  	}
		});
	},
	filter: function() {		
		$('#companyID, #sectorID').change(function() {
			var companyID = $('#companyID').val();
			var sectorID = $('#sectorID').val();
			document.location.href = '/dashboard/browse-research/' + companyID + '/' + sectorID;	
			/**
			* Removed so value would be kept in url. 
			* Downside: page reloads each time you change your search.
			* Upside: your search values will be kept when using back on detail page			
			*/
			//Mwr.Research.browse(companyID, sectorID);
		});
	},
	searchRedirect: function() {
		// Gets called only from the research view page
		Mwr.Research.filter();
		// Reset values in search form (so it doesn't preset the articleID from url as the companyID		
		$('#companyID').val(0);
		$('#sectorID').val(0);
	}
};



Mwr.AllResearch = {
	limits: {
		allResearch: 20
	},
	offsets: {
		allResearch: 0
	},
	
	init: function() {
		Mwr.AllResearch.checkLogin();
	},
	
	initRecent: function() {
		var uri = document.location.pathname.split('/');
		if (uri[3] == undefined || (uri[3] == 0 && uri[4] == 0)) {
			Mwr.AllResearch.getAllResearch();
		} else {
			Mwr.AllResearch.browse();
		}
		
		Mwr.AllResearch.filter();
		Mwr.AllResearch.allResearch();
		
		Mwr.AllResearch.redirectToLogin();
	},
	
	// initialize the favorite research paginated page
	allResearch: function() {
		window.location.hash = '#1';

		$('.research-pagination a').live('click', function() {
			var offset = $(this).attr('href');
			offset = offset.substring(offset.length - 1);
			var uri = document.location.pathname.split('/');
			
			if (uri[3] == undefined || (uri[3] == 0 && uri[4] == 0)) {
				Mwr.AllResearch.getAllResearch(offset);
			} else {
				Mwr.AllResearch.browse(uri[3], uri[4], offset);
			}
			
		});

	},

	getAllResearch: function(offset) {
		var $pagination = $('.research-pagination');
		var $table = $('#all-research');

		$pagination.html('');
		$table.html('');

		if (offset !== undefined) {
			Mwr.AllResearch.offsets.allResearch = (offset - 1) * Mwr.AllResearch.limits.allResearch;
		}

		$.ajax({
			url: '/api/research/all',
			data: {
				limit: Mwr.AllResearch.limits.allResearch + 1,
				offset: Mwr.AllResearch.offsets.allResearch
			},
			success: function(data) {
				// If this isnt the first page of results, show previous link
				var previous = Mwr.AllResearch.offsets.allResearch / Mwr.AllResearch.limits.allResearch;
				if (previous > 0) {
					$pagination.append('<li><a href="#' + previous + '">Previous</a></li>');					
				}
				
				// If there are more records, show more link and remove last element
				if (data.data.research.length > Mwr.AllResearch.limits.allResearch) {
					var next = previous + 2;
					$pagination.append('<li><a href="#' + next + '">Next</a></li>');
					data.data.research.pop();
				}

				$.each(data.data.research, function(i, research) {
					var stockSymbol = '';
					if (research.symbol != null) {
						stockSymbol = '(' + research.symbol + ') ';
					}
					
					$table.append(
						'<tr>' +
							'<td class="research-date">' + research.tsPublished + '</td>' +
							'<td><a href="/dashboard/research-detail/' + research.researchID + '">' + stockSymbol + research.title + '</a></td>' +
						'</tr>'
					);
				});
			}
		});
	},

	// Get all research, filtered by company and/or sector, with pagination
	browse: function(company, sector, offset) {
		var $pagination = $('.research-pagination');
		var uri = document.location.pathname.split('/');
		$pagination.html('');
		
		var companyID = (uri[3] !== undefined) ? uri[3] : 0;
		var sectorID = (uri[4] !== undefined) ? uri[4] : 0;
		
		if (offset !== undefined) {
			Mwr.AllResearch.offsets.allResearch = (parseInt(offset) - 1) * parseInt(Mwr.AllResearch.limits.allResearch);
		}

		// if values came through url, preset the values in the form
		$('#companyID').val(companyID);
		$('#sectorID').val(sectorID);
		
		$table = $('#all-research');

		$.ajax({
			url: '/api/research/filtered',
			data: {limit: Mwr.AllResearch.limits.allResearch, companyID: companyID, sectorID: sectorID, offset: Mwr.AllResearch.offsets.allResearch},
	  		success: function(data) {
				$table.empty();
				if (data.data.research.length == 0) {
					$table.append(
						'<tr><td rowspan="2">There are no results for these search parameters.</td></tr>'
					);
				} else {
					
					var previous = parseInt(Mwr.AllResearch.offsets.allResearch) / parseInt(Mwr.AllResearch.limits.allResearch);
					if (previous > 0) {
						$pagination.append('<li><a href="#' + previous + '">Previous</a></li>');					
					}
					
					// If there are more records, show more link and remove last element
					if (data.data.research.length >= Mwr.AllResearch.limits.allResearch) {
						var next = previous + 2;
						$pagination.append('<li><a href="#' + next + '">Next</a></li>');
						data.data.research.pop();
					}
				
					$.each(data.data.research, function(i, research) {
						$table.append(
							'<tr>' +
								'<td class="research-date">' + research.tsPublished + '</td>' +
								'<td><a href="/dashboard/research-detail/' + research.researchID + '">(' + research.symbol + ') ' + research.title + '</a></td>' +
							'</tr>'
						);
					});
				}
		  	}
		});
	},
	
	filter: function() {		
		$('#companyID, #sectorID').change(function() {
			var companyID = $('#companyID').val();
			var sectorID = $('#sectorID').val();
			document.location.href = '/research/recent-research/' + companyID + '/' + sectorID;	
			/**
			* Removed so value would be kept in url. 
			* Downside: page reloads each time you change your search.
			* Upside: your search values will be kept when using back on detail page			
			*/
			//Mwr.Research.browse(companyID, sectorID);
		});
	},
	
	searchRedirect: function() {
		// Gets called only from the research view page
		Mwr.Research.filter();
		// Reset values in search form (so it doesn't preset the articleID from url as the companyID		
		$('#companyID').val(0);
		$('#sectorID').val(0);
	},
	
	checkLogin: function() {
		$.ajax({
			url: '/api/account/authenticated',
			
			success: function(data) {
				if (data.authenticated == 'false') {
					$('.research-doc a, .sso .button a, .recent-research-link a').attr('href', '/account/login').removeAttr('target');
					$('#archives').remove();
				} else {
					$('#preview').remove();
				}
			}
		});
	}
};

Mwr.MwrResearch = {
	limits: {
		allResearch: 20
	},
	offsets: {
		allResearch: 0
	},
	
	init: function() {
		Mwr.MwrResearch.checkLogin();
	},
	
	initRecent: function() {
		var uri = document.location.pathname.split('/');
		if (uri[3] == undefined || (uri[3] == 0 && uri[4] == 0)) {
			Mwr.MwrResearch.getMwrResearch();
		} else {
			Mwr.MwrResearch.browse();
		}
		Mwr.MwrResearch.allResearch();	
		Mwr.MwrResearch.redirectToLogin();
	},
	
	// initialize the favorite research paginated page
	allResearch: function() {
		window.location.hash = '#1';

		$('.research-pagination a').live('click', function() {
			var offset = $(this).attr('href');
			offset = offset.substring(offset.length - 1);
			var uri = document.location.pathname.split('/');
			
			if (uri[3] == undefined || (uri[3] == 0 && uri[4] == 0)) {
				Mwr.MwrResearch.getMwrResearch(offset);
			} else {
				Mwr.MwrResearch.browse(uri[3], uri[4], offset);
			}
			
		});

	},

	getMwrResearch: function(offset) {
		var $pagination = $('.research-pagination');
		var $table = $('#all-research');

		$pagination.html('');
		$table.html('');

		if (offset !== undefined) {
			Mwr.MwrResearch.offsets.allResearch = (offset - 1) * Mwr.MwrResearch.limits.allResearch;
		}

		$.ajax({
			url: '/api/research/reviews',
			data: {
				limit: Mwr.MwrResearch.limits.allResearch + 1,
				offset: Mwr.MwrResearch.offsets.allResearch
			},
			success: function(data) {
				// If this isnt the first page of results, show previous link
				var previous = Mwr.MwrResearch.offsets.allResearch / Mwr.MwrResearch.limits.allResearch;
				if (previous > 0) {
					$pagination.append('<li><a href="#' + previous + '">Previous</a></li>');					
				}
				
				// If there are more records, show more link and remove last element
				if (data.data.research.length > Mwr.MwrResearch.limits.allResearch) {
					var next = previous + 2;
					$pagination.append('<li><a href="#' + next + '">Next</a></li>');
					data.data.research.pop();
				}

				$.each(data.data.research, function(i, research) {
					var stockSymbol = '';
					if (research.symbol != null) {
						stockSymbol = '(' + research.symbol + ') ';
					}
					
					$table.append(
						'<tr>' +
							'<td class="research-date">' + research.tsPublish + '</td>' +
							'<td><a href="/dashboard/research-detail/' + research.researchID + '">' + stockSymbol + research.title + '</a></td>' +
						'</tr>'
					);
				});
			}
		});
	},

	// Get all research, with pagination
	browse: function(company, sector, offset) {
		var $pagination = $('.research-pagination');
		var uri = document.location.pathname.split('/');
		$pagination.html('');
		
		if (offset !== undefined) {
			Mwr.MwrResearch.offsets.allResearch = (parseInt(offset) - 1) * parseInt(Mwr.MwrResearch.limits.allResearch);
		}
		
		$table = $('#all-research');

	},

	checkLogin: function() {
		$.ajax({
			url: '/api/account/authenticated',
			
			success: function(data) {
				if (data.authenticated == 'false') {
					$('.research-doc a, .sso .button a, .recent-research-link a').attr('href', '/account/login').removeAttr('target');
				}
			}
		});
	}
};

Mwr.News = {
	init: function() {
		Mwr.News.pagination();
	},
	
	pagination: function() {
		var currentPage = 0;
			
		//Get total number of pages
		var totalPages = Math.ceil($('.news #main article').length / 4) - 1;
		
		//If hash page number is available, show articles based on page number
		if (location.hash.length > 0) {
			var visiblePage = location.hash;
			currentPage = visiblePage.split('#')[1];
			var firstArticle = currentPage * 4;
			var lastArticle = (currentPage * 4) + 4;
			
			$('.news #main article').hide().slice(firstArticle, lastArticle).show();
		} else {
			$('.news #main article:gt(3)').hide();
		}
		
		//Hides prev/next buttons if browser is at start or end of news pages respectively
		if (currentPage == 0) {
			$('#newer').hide();
		} else if (currentPage == totalPages) {
			$('#older').hide();
		} else {
			
		}
		
		$('#prevNext a').click(function(e) {
			e.preventDefault();
			var target = $(this).attr('id');
			
			$('.news #main article:visible').hide();
			
			//Checks whether to go forward or back
			if (target == 'newer') {
				if (currentPage > 0) {
					currentPage--;
				}
			} else {
				if (currentPage < totalPages) {
					currentPage++;
				}
			}
			
			firstArticle = currentPage * 4;
			lastArticle = (currentPage * 4) + 4;
			$('.news #main article').slice(firstArticle, lastArticle).show();
			window.location.hash = currentPage;
			
			if (currentPage == 0) {
				$('#newer').hide();
			} else if (currentPage == totalPages) {
				$('#older').hide();
			} else {
				$('#prevNext a').show();
			}
		});
	}
}

Mwr.Login = {
	init: function() {
		Mwr.Login.login();
	},
	login: function() {

		$('#account-login').click(function(e) {
			e.preventDefault();
            var url = this.href;
            var dialog = $('<div style="display:none"></div>').appendTo('body');
			
            // load remote content
            dialog.load(
                url, 
                {},
                function (responseText, textStatus, XMLHttpRequest) {
                    dialog.dialog({ 
						modal: true, 
						resizable : false,
						title: 'Account Login / Register',
						width: 700
					});
                }
            );
			
        });
	}
};

Mwr.Account = {
	init: function() {
		Mwr.Account.formValidation()
	},
	
	formValidation: function() {
		$('input[type="tel"]').mask('999.999.9999');
	}
};

$(function() {
	Mwr.Controller.init();
	Mwr.Login.init();
});

