/*
 * Custom Functions
 * placeholder for all custom jQuery
 * some functions might be better placed in separate js files and called when needed
 */

$(document).ready(function(){
	
	// add a space on each side of / so that the text can be broken onto multiple lines
	if ($('table.suites th.unitsuite-number').length) {
		$('table.suites th.unitsuite-number').html($('table.suites th.unitsuite-number').html().replace('/', ' / '));
	}
 
	$('table.suites tr th:last-child').addClass('last');
 
	/*
	 * building (detail)
	 */
	$('.building .left table:last-child').addClass('last');
	
	/*
	 * Footer Links
	 * loop through the lists to get the tallest one and set them all to the
	 * same height (for styling)
	 */
	var col_height = 0;
	$('#footer-links ul').each(function() {
		if ($(this).outerHeight() > col_height) {
			col_height = $(this).outerHeight();
		}
	});
	$('#footer-links ul').height(col_height);
	//$('#footer-links ul:last').addClass('last');

	/*
	 * Buildings (search results & detail pages)
	 * remove the brackets (sq. ft.) in the table lists
	 */
	$('.building table.list td').each(function() {
		$(this).text($(this).text().replace('(', ''));
		$(this).text($(this).text().replace(')', ''));
	});
	
	// these inputs are too long for the page width making it spill outside
	// the page boundaries
	$('#lay-admin form table input#en_add_value').attr('size', 35);
	$('#lay-admin form table input#fr_add_value').attr('size', 35);
	
	/*
	 * Page Padding
	 *
	 * we added a background colour to the main body so we needed to add padding
	 * to the main content area. problem being that some elements that appear
	 * within #content (which is padded) need to behave more like header elements
	 * that are outside the padded area.
	 *
	 * #midbar ('back to search results')
	 * #menu-report (print | update | file library [jumpto])
	 * #refine-search
	 *
	 * TODO: can this be accomplished via the templates?
	 */
	$('#header').after($('#midbar'));
	
	/*
	 * Homepage
	 * bottom half of page make left & right side same heights so that the CSS
	 * can align the images to the bottom
	 *
	 * add an extra 7px for the shading on the graphics
	 */
	if ($('#lay-home .panels .left').length && $('#lay-home .panels .right').length) {
		$('#lay-home .panels .left').height($('#lay-home .panels .right').height() + 7);
	}
	
	/*
	 * Rounded Corners
	 * http://www.malsup.com/jquery/corner
	 * older version: http://www.methvin.com/jquery/jq-corner-demo.html
	 */
	$('#pagenav a').corner('3px'); /* buttons on property search summary */
  
	/* filter tabs using css3 for rounding, IE8- need this method
	 * note: rounding does not work on form input elements
	 */
	//$('ul.actions input.form-submit').corner('3px');
	if ($.browser.msie) {
		$('#select-all').corner('3px');
		//$('ul.actions li input.form-submit').corner('3px');
	}
  
	/*
	 * Get URL Params
	 * helper: to be used by other functions
	 * can pass a url, if no url passed will use the current url of the page
	 */
	function get_url_vars(url)
	{
		// if we're not passed the url, use the page url
		if (!url || url.length == 0)
		{
			var url = window.location.href;
		}		 
	    var vars = [], hash;
	    var hashes = url.slice(url.indexOf('?') + 1).split('&');
	    for(var i = 0; i < hashes.length; i++)
		{
	        hash = hashes[i].split('=');
	        vars.push(hash[0]);
	        vars[hash[0]] = hash[1];
	    }
	    return vars;
	}
	
	/*
	 * Links
	 * open external links in a new window
	 * append url to title attribute for external links
	 * open docs in a new window
	 */
	$('a[href^="http:"]').not('[href*="altusinsite.com"]').attr('target', '_blank').addClass('external');
	$('a[class^="doc"]').attr('target', '_blank');
	
	$('a.external').each(function() {
		var title = $(this).attr('title') + ' (' + $(this).attr('href') + ')';
		$(this).attr('title', title);
	});
		
	/*
	 * Tabs
	 * currently only appear on the homepage
	 * TODO: refactor
	 */
	// tabs: loop through the tabs to get the tallest one and set all the tabs
	// to that height
	var tab_height = 0;
	$('#tabs-content .tab').each(function() {
		if ($(this).height() > tab_height) {
			tab_height = $(this).height();
		}
	});
	$('#tabs-content .tab').css('height', tab_height);
	
	// tabs: rounded corners (http://www.malsup.com/jquery/corner)
	$('ul#tabs li.first a').corner('round tl 10px cc:#81b3f0');
	$('ul#tabs li.first a').corner('round tr 10px cc:#e4efff');
	$('ul#tabs li.middle a').corner('round tl 10px cc:#e4efff');
	$('ul#tabs li.middle a').corner('round tr 10px cc:#e4efff');
	$('ul#tabs li.last a').corner('round tl 10px cc:#e4efff');
	$('ul#tabs li.last a').corner('round tr 10px cc:#8dcaf9');
	
	/* .jquery-corner margin-top is initially set by the roundedcorners js to -9px
	   seen if you 'inpect element'. firefox/safari/chrome need -10px */
	if (!$.browser.msie) {
		$('.jquery-corner').css('margin-top', '-10px');
	}
	
	/* chrome & safari: the width #tabs is 1px too short */
	/*if ($.browser.safari) {
		$('#tabs li.last a').width($('#tabs li.last a').width() + 1);
	}*/
	
	// set the active tab
	// if 'tab' parameter is passed via the url & exists, use that
	// else set the first tab in the list to active
	if ($('ul#tabs').length) {
		var tab = get_url_vars()['tab'];
		if ($(tab) && $('#tab-' + tab).length) {
			var tab = '#tab-' + tab;
		} else {
			var tab = $('ul#tabs li a').attr('href');
		}
		
		// set tab & content
		// TODO: what if a tab was already set via code?
		$('ul#tabs a[href="' + tab + '"]').parent().addClass('selected');
		
		// problem: when the inactive tab gets hidden the autocomplete is appending
		// width:0pt to .suggestions which makes the autocomplete styling wonky
		$('#tabs-content').find('.tab').not(tab).hide();
	}
	
	// add click functionality
	$('ul#tabs li a').bind('click', function() {
		var active = $(this).attr('href');
		
		// update tabs
		$(this).parent().parent().find('.selected').removeClass('selected');
		$(this).parent().addClass('selected');
		
		// update content
		$('#tabs-content').find('.tab').not(active).hide();
		$('#tabs-content').find(active).show();
		
		// return false to prevent the browser going to the href
		return false;
	});
	
	/*
	 * Building Detail
	 * expand / collapse suite detail
	 * TODO: this is just called from module/buildinglist, probably should be
	 * moved to a js file there
	 *
	 * NOTE: functionality has changed, i don't think this is being used anymore
	 * TODO: comment this out?
	 */
	$('table[id^="suite"] a.suite').click(function() {
		var table = $(this).parent().parent().parent().parent().attr('id');
		var href = $(this).attr('href');
		var sid = get_url_vars(href)['spaceid'];
		var suite = '#suite-' + sid;
		
		// if this suite detail already exists, remove it (toggle)
		// we could rewrite this so that if exists hide/show toggle
		if ($(suite).length > 0) {
			$(suite).remove();
			return false;
		}
		
		// only show one suite detail at a time, remove others
		//$('table#suites tr.suite').remove();
		$('table[id="' + table + '"] tr.suite').remove();
		
		// load the suite
		$(this).parent().parent().after('<tr id="suite-' + sid + '" class="suite"><td>&nbsp;</td><td colspan="6" class="detail"></td></tr>');
		$(suite + ' td.detail').load(href);
		
		// return false to prevent the browser going to the href
		return false;
		
	});

 	/*
	 * Refine Search
	 * move fielset to top of page
	 *
	 * TODO: this is currently only used by module/buildinglist. probably should
	 * be moved to a js file there
	 */
	var menu = $('#menu-report');
	var refine = $('form fieldset#form_search');
	if (refine.length && menu.length) {
		// move refine search below pagenav
		refine.parents('form#form_search_building').find('#pagenav').after(refine.addClass('bar').parent());
		
		// add last class to geozone list columns
		//refine.find('ul.list-column li:last').addClass('last');
		refine.find('ul.list-column').each(function() {
				$(this).find('li:last').addClass('last');
		});
		
		// insert the search results message into the fieldset
		var msg = $('.message.plain');
		if (msg.length) {
				//refine.prepend(msg);
				//refine.find('legend').append(msg);
				refine.find('legend').after(msg);
		}
		
		// allow message text/link to expand collapse fieldset
		$('form fieldset.collapsible a.toggle').click(function() {
			var fieldset = $(this).parents('fieldset');
		  fieldset.find('.fieldset-wrapper').toggle();
			
			if (fieldset.hasClass('collapsed')) {
				fieldset.removeClass('collapsed').addClass('expanded');
				fieldset.find('span.toggle').html('&lsaquo;');
			} else if (fieldset.hasClass('expanded')) {
				fieldset.removeClass('expanded').addClass('collapsed');
				fieldset.find('span.toggle').html('&rsaquo;');
			}
			
			return false;
		});
	}

	/*
	 * refine search: if a geozone checkbox is checked, uncheck 'current location'
	 *
	 * BUG (IE): change event not registering (see notes in other js files)
	 */
	var current_location = $('#current-location input[type=checkbox]');
	var geozones = $('ul.list-column');
	if (current_location.length && geozones.length) {
  	//geozones.find('input[type=checkbox]').change(function(){
		geozones.find('input[type=checkbox]').bind(($.browser.msie ? 'click' : 'change'), function () {
			if ($(this).attr('checked')) {
	      current_location.attr('checked', false);
	    }
			// if all geozones are unchecked, re-check current location
			if (geozones.find('input[type=checkbox]:checked').length == 0) {
	      current_location.attr('checked', true);
	    }
  	});
  }

	/* clone the saved report message to the top of the page */
	/*if (refine.length) {
		refine.parent().after($('#mod-searchengine-5 .message').clone());
	}*/
	
	/* clone the saved report message to the top of the page
	 * do duplicate on: search results & arriving through perspective reports
	 * don't duplicate when: viewing a saved report
	 */
	if (get_url_vars()['page'] == 'searchengine') {
		var msg = $('#mod-searchengine-5 .message');
		if (msg) {
			$('#pagenav').next().after(msg.clone());
		}
	}
	
	/*
	 * Back Button
	 * back button on property detail page
	 *
	 * the back button appears with the content, but we want it to appear in a
	 * bar separate from the content. Same treatment as *Refine Search* may
	 * want to consider merging these
	 *
	 * TODO: What other instances will we be using this bar?
	 */
	var bar = $('#content #midbar');
	if (bar.length) {
		$('#content').before(bar);
	}
	
});
