var sort_param = gup('sort');
if(sort_param == "")
	sort_param = 'freshness';
var other_params = document.location.search.substring(1, document.location.search.length).replace(/&?sort=\w+/, '').replace(/&?ns=\d/, '');
if(other_params.length > 0) {
	document.location.hash = ('#' + sort_param + '&' + other_params).replace(/&&/, '&');
	document.location.search = '';
}

var contact_name = '';
if(gup('company_name') != '')
	contact_name = decodeURIComponent(gup('company_name'));
else if(gup('contact_name') != '')
	contact_name = decodeURIComponent(gup('contact_name'));
	
$(function(){
	// Don't allow IE 6 or lower to hide sidebar (Doesn't want to show up again)
	if(!($.browser.msie && $.browser.version < 7)) {
		
		// Toggle Sidebar Selection Groups On Click
		$('.listings-accordion h3').click(function() {
			cookie_name = $(this).attr('id').replace('_header', '');
			if( $(this).is('.ui-state-active') ){ 
				$(this).removeClass('ui-state-active ui-corner-top');
				$(this).addClass('ui-corner-all');
				$(this).find('.ui-icon').addClass('ui-icon-triangle-1-e');
				$(this).find('.ui-icon').removeClass('ui-icon-triangle-1-s');
				$.cookie(cookie_name, 'collapsed'); }
			else { 
				$(this).addClass('ui-state-active ui-corner-top');
				$(this).removeClass('ui-corner-all');
				$(this).find('.ui-icon').addClass('ui-icon-triangle-1-s');
				$(this).find('.ui-icon').removeClass('ui-icon-triangle-1-e'); 
				$.cookie(cookie_name, 'open'); }
			$(this).next().slideToggle();
			return false;
		});
		
		// Give Closed Selection Groups Hover States
		$('.listings-accordion h3').hover(
			function() {
				$(this).addClass("ui-state-hover"); 
			},
			function() {
				$(this).removeClass("ui-state-hover"); 
			});
		if($.cookie('more_features') == null)
			collapseHeader('#more_features_header');
		collapseAccordion();
	}

	// Display Sort Dropdown If Javascript Is Enabled
	$('#listings-sort').css('display', 'block');
	
	// Give Sort Dropdown Hover States
	$("li.baseapp-button:not(.ui-state-disabled)")
		.hover(
			function(){ 
				$(this).addClass("ui-state-hover");
				$(this).find('a:not(.listings-sort-first)').css('display', 'block');
			},
			function(){ 
				$(this).removeClass("ui-state-hover");
				$(this).find('a:not(.listings-sort-first)').css('display', 'none'); 
			});
	
	if(contact_name != '') {
		$('#contact_name_header').html('Listings by ' + contact_name);
		$('#contact_name_header').show();
		
		if(gup('company_name') != '')
			$('#reset_link').attr('href', '#freshness&company_name=' + contact_name);
		else if(gup('contact_name') != '')
			$('#reset_link').attr('href', '#freshness&contact_name=' + contact_name);
	}
	
	// Check Address Bar For Changes Every 500ms
	setInterval("checkAnchor()", 500);

});

var monthNames = new Array("", "January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December");

var currentAnchor = null;
var sort = '';
var params = '';
var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
//Function which check if there are anchor changes, if there are, sends the ajax petition  

function checkAnchor(){
	//Check if it has changes
		
	var splits = null;
		
	var oldAnchorForLinks = removeRandomAmps(removeQueryValue(currentAnchor, ['page', 'per_page', 'all', 'origin']));
	var newAnchorForLinks = removeRandomAmps(removeQueryValue(document.location.hash, ['page', 'per_page', 'all', 'origin']));

	if(currentAnchor != document.location.hash){
		currentAnchor = document.location.hash;
		//if there is not anchor, sort by newest
		var query = '';
		if(!currentAnchor) {
			query = 'sort=freshness';
			sort = 'freshness';
			if($.cookie('origin') != null)
				query += '&origin=' + encodeURIComponent($.cookie('origin'));
		}
		else {
			splits = currentAnchor.substring(1).split('&');
			//Get the section
			sort = splits[0];
			delete splits[0];
			//Create the params string
			params = splits.join('&');
			if($.cookie('origin') != null)
				params += '&origin=' + encodeURIComponent($.cookie('origin'));
			query = 'sort=' + sort + params + '&callback=?';
		}

		//Send AJAX Request For Links
		if (oldAnchorForLinks != newAnchorForLinks) {
			$.getJSON('/listings/ajax_links', query, function(data) {
				$('#city').html(getGroupLinks('city', data.city));
				$('#rental_type').html(getGroupLinks('rental_type', data.rental_type));
				$('#bedrooms').html(getGroupLinks('bedrooms', data.bedrooms));
				$('#pets_allowed').html(getGroupLinks('pets_allowed', data.pets_allowed));
				$('#more_features').html(getGroupLinks('more_features', data.more_features));
				$('#month_available').html(getGroupLinks('month_available', data.month_available));
			
				if(data.item_count == 1)
					$('#listings-results-text').html(data.item_count + ' Result');
				else
					$('#listings-results-text').html(data.item_count + ' Results');
			
				if ( $("#my-listings").length > 0 )
					$('#my-listings').html(getGroupLinks('my_listings', data.my_listings)); 
				
				if ( $("#tag-list-search").length > 0 ) { 
					$('#tag-list-search').mouseup(); //tag search button gets stuck
					$('#tag-list-search').click(function(){
						var tags = $('#tag_list').attr('value').replace(',', ' ');
						if ( tags.length > 0 ) {
							document.location.hash = replaceQueryValue(currentAnchor, 'tags', tags);
							$('#tag-list-close').show();
						}
						else {
							document.location.hash = removeQueryValue(currentAnchor, 'tags');
							$('#tag-list-close').hide();
						}
						return false;
					});
					//capture the return key on text field
					$("#tag_list").bind("keydown", function(e) {
						if (e.keyCode == 13) $('#tag-list-search').click();
					});
					$('#tag-list-close')
						.hover(
							function(){ 
								$(this).addClass('ui-state-hover');
							}, 
							function(){ 
								$(this).removeClass('ui-state-hover');
							})
						.click(function() {
							$('#tag_list').attr('value', '');
							document.location.hash = removeQueryValue(currentAnchor, 'tags');
							$('#tag-list-close').hide();
							return false;
						});
				}
			
				if ( $("#embed_code").length > 0 ) { 
					embedCode = '<script type="text/javascript" src="' + siteUrl + '/embed?' + query.replace(/&callback=\?/, '').replace(/&my=1/, '&user_id=' + userId).replace(/&status\[\]=active/, '').replace(/&status\[\]=expired/, '') + '"></script>';
					$('#embed_code').attr('value', embedCode);
					$('#embed_code').click(function(){this.select();});
					if(!($.browser.msie && $.browser.version < 8)) {
			        	var clip = new ZeroClipboard.Client();
						ZeroClipboard.setMoviePath(siteUrl + '/flash/ZeroClipboard.swf');
						var copiedText = $('#embed_code').attr('value');
						clip.setText(copiedText);
						clip.glue('copy-code');
						clip.addEventListener( 'onComplete', function(){
							$('#embed_code').attr('value', 'Copied!');
							$('#embed_code').effect("highlight", {}, 1500);
							setTimeout(function(){ $('#embed_code').attr('value', copiedText); }, 1500);
						});
					}
				}
			
				
				// Map link and button functions
				$('#links li:not(.ui-state-disabled) a.listings-selector, #my-listings-container li:not(.ui-state-disabled) a.listings-selector')
					.hover(
						function(){
							if(!$(this).find('span').is('.ui-state-active')) { 
								$(this).addClass('ui-state-hover');
								$(this).find('span').addClass('ui-state-hover');
							}
						}, 
						function(){
							if(!$(this).find('span').is('.ui-state-active')) { 
								$(this).removeClass('ui-state-hover');
								$(this).find('span').removeClass('ui-state-hover');
							}
						})
					.click(function() { 
						if($(this).find('span').is('.ui-state-active')){ 
							$(this).removeClass('ui-state-hover');
							$(this).find('span').removeClass('ui-state-active');
						}
						else {
							$(this).addClass('ui-state-hover');
							$(this).find('span').addClass('ui-state-active');
						}
						$('#listings').fadeOut();
						$('#listings-results-spinner').addClass('links');
						$('#listings-results-spinner').addClass('results');
					});

				$('#links li.ui-state-disabled a.listings-selector, #my-listings-container li.ui-state-disabled a.listings-selector')
					.click(function() { 
						if($(this).find('span').is('.ui-state-active')){ 
							$(this).removeClass('ui-state-hover');
							$(this).find('span').removeClass('ui-state-active');
						}
						else {
							$(this).addClass('ui-state-hover');
							$(this).find('span').addClass('ui-state-active');
						}
						$('#listings').fadeOut();
						$('#listings-results-spinner').addClass('links');
						$('#listings-results-spinner').addClass('results');
					});

				$('#links a.baseapp-button:not(.ui-state-disabled), #my-listings-container a.baseapp-button:not(.ui-state-disabled)')
					.hover(
						function(){ 
							$(this).addClass('ui-state-hover');
						}, 
						function(){ 
							$(this).removeClass('ui-state-hover');
						})
					.click(function() {
						if($(this).is('.ui-state-active'))
							$(this).removeClass('ui-state-active');
						else
							$(this).addClass('ui-state-active');
						$('#listings').fadeOut();
						$('#listings-results-spinner').addClass('links');
						$('#listings-results-spinner').addClass('results');
					});

				$('#listings-reset a').click(function(){ 
					$('#listings').fadeOut();
					$('#listings-results-spinner').addClass('links');
					$('#listings-results-spinner').addClass('results'); 
				});
				$('#listings-results-spinner').removeClass('links');
			});
		}

		//Send AJAX Request For Results
		var listings_html = '';
		var pages_html = '';
		$.getJSON('/listings/ajax_results', query, function(data) {
			
			// Create Listings HTML
			listings_html += '<p>';
			$.each(data.listings, function(i,item){
				var bedrooms = '1 Bedroom';
				if(item.listing.bedrooms == 0)
					bedrooms = 'Studio/Efficiency';
				else if(item.listing.bedrooms > 1)
					bedrooms = parseInt(item.listing.bedrooms) + ' Bedrooms';
				var bathrooms = '1 Bathroom';
				if(item.listing.bathrooms > 1)
					bathrooms = parseInt(item.listing.bathrooms) + ' Bathrooms';
				var distance = '';
				if(item.listing.distance != null)
					distance = Math.round(item.listing.distance*100)/100 + ' mi.';
				listings_html += '<a href="/' + item.listing.tiny_url + '" class="listings-listing ui-widget  ui-widget-header ui-helper-reset ui-helper-clearfix ui-corner-all listing-status-' + item.listing.status + '">';
				listings_html += '<span class="listings-listing-image"><img src="' + item.listing.large_thumb + '"></span><br />';
				listings_html += '<span class="listings-listing-heading">$' + parseInt(item.listing.rent) + ' - ' + bedrooms + ', ' + bathrooms + '</span><br />';
				listings_html += '<span class="listings-listing-title">' + item.listing.title.replace(regexp,'') + '</span><br />';
				listings_html += '<span class="listings-listing-address">' + item.listing.street_address.replace(regexp,'') + ', ' + item.listing.city.replace(regexp,'') + ', ' + item.listing.state.replace(regexp,'') + '</span><br />';
				listings_html += '<span class="listings-listing-available">Available: ' + monthNames[item.listing.month_available] + '</span><br />';
				listings_html += '<span class="listings-listing-distance">' +  distance + '</span><br />';
				listings_html += '<span class="listings-listing-posted">Posted ' + item.listing.posted_on.replace(regexp,'') + ' by ' + item.listing.posted_by.replace(regexp,'') + '</span><br /></a>';
		  	});
			listings_html += '</p>';
			
			// Create Pager HTML
			if(data.single_page && data.page_count > 1) {
				pages_html += '<li style="margin-bottom: 3px; float: right;">Showing all results</li><li style="float: right; clear: right;">';
				$.each(data.all_pages, function(i,item) {
					pages_html += '<li><a href="#' + sort + params.replace(/&all=1/, '').replace(/&page=\d+/, '') + '&page=' + item + '">' + item + '</a></li>';
				});
				pages_html += '</li>';
				$('#top_pager').addClass('all');
			}
			else if(data.single_page) { 
				pages_html += '<li>Showing all results</li>';
				$('#top_pager').removeClass('all');
			}
			else {
				pages_html += '<li class="all"><a href="#' + sort + params.replace(/&page=\d+/, '') + '&all=1">Show All</a></li>';
				if(data.prev_arrow)
					pages_html += '<li><a href="#' + sort + params.replace(/&page=\d+/, '') + '&page=' + (data.page - 1) + '">&laquo; Prev</a></li>';
				$.each(data.pages, function(i,item) {
					if(data.page == item)
						pages_html += '<li>' + item + '</li>'
					else
						pages_html += '<li><a href="#' + sort + params.replace(/&all=1/, '').replace(/&page=\d+/, '') + '&page=' + item + '">' + item + '</a></li>';
				});
				if(data.next_arrow)
					pages_html += '<li><a href="#' + sort + params.replace(/&page=\d+/, '') + '&page=' + (data.page + 1) + '">Next &raquo;</a></li>';
				$('#top_pager').removeClass('all');
			}
			
			// Create Price Slider
			$('#rent_slider').slider({
				min: data.rent_start,
				max: data.rent_end,
				range: true,
				step: 10,
				values: [data.min_rent, data.max_rent],
				change: function(event, ui) {
					$('#rent_start').html($(this).slider('values', 0));
					$('#rent_end').html($(this).slider('values', 1));
					$('#rent_range_values').css('display', 'block');
				},
				slide: function(event, ui) { 
					$('#rent_start').html($(this).slider('values', 0));
					$('#rent_end').html($(this).slider('values', 1));
				},
				stop: function(event, ui) {
					var new_hash = '#' + sort + params.replace(/&page=\d+/, '').replace(/&min_rent=\d+/, '').replace(/&max_rent=\d+/, '')
					if($(this).slider('values', 0) != $(this).slider('option', 'min'))
						new_hash += '&min_rent=' + $(this).slider('values', 0);
					if($(this).slider('values', 1) != $(this).slider('option', 'max'))
						new_hash += '&max_rent=' + $(this).slider('values', 1);
					if(document.location.hash != new_hash){
						document.location.hash = new_hash;
						$('#listings').fadeOut();
						$('#listings-results-spinner').addClass('links');
						$('#listings-results-spinner').addClass('results');
					}
				}
			});
			$('#rent_start').html(data.min_rent);
			$('#rent_end').html(data.max_rent);
			$('#rent_range_values').css('display', 'block');
			$('#listings-pages-top').html(pages_html);
			$('#listings-pages-bottom').html(pages_html);
			$('#listings-sort-selector').html(getSortLinks(data.sort));
			$('#listings').html(listings_html);
			$('#listings-results-spinner').removeClass('results');

			if($.cookie('origin') != null) {
				var origin_html = '<span class="baseapp-small"><strong>Starting Address:</strong></span> <span class="baseapp-small">' + $.cookie('origin') + '</span> <span class="baseapp-small"><a id="listings-origin-reset" href="#">Reset</a></span><br />';
				$('#listings-origin').html(origin_html);
				$('#listings-origin').slideDown();
				$('.listings-pager').removeClass('ui-corner-all');
				$('.listings-pager').addClass('ui-corner-top');
				$('#listings-origin-reset').click(function(){
					$('#listings-origin').slideUp();
					$('#listings').fadeOut();
					$.cookie('origin', null);
					document.location.hash = '#' + query.replace(/sort=/, '').replace(/&callback=\?/, '').replace(/&origin=.*/, '');
					return false;
				});
			}
			else {
				$('.listings-pager').removeClass('ui-corner-top');
				$('.listings-pager').addClass('ui-corner-all');
			}
		
			if(sort == 'distance' && $.cookie('origin') == null) {
				var origin_html = '<span class="baseapp-small"><strong>Starting Address</strong></span> <span class="baseapp-smaller">(e.g. 1234 56th Ave S, Fargo, ND)</span><br />';
				origin_html += '<input class="ui-widget-content ui-corner-all" id="origin-input" name="origin" type="text" value="" /> ';
				origin_html += '<span class="baseapp-small"><a id="listings-origin-go" href="#" onClick="pageTracker._trackPageview(\'listings/sort/distance_from/go\');">Go</a></span>';
				$('#listings-origin').html(origin_html);
				$('#listings-origin').slideDown();
				// Change Input Fields Class on Focus
				$('input[type="text"], input[type="password"], textarea').focus(function() {
					$(this).addClass("ui-state-active");
				});
				$('input[type="text"], input[type="password"], textarea').blur(function() {
					$(this).removeClass("ui-state-active");
				});
				$('.listings-pager').removeClass('ui-corner-all');
				$('.listings-pager').addClass('ui-corner-top');
				$('#listings-origin-go').click(function(){
					$.getJSON("/listings/ajax_address", { address: $('#origin-input').attr('value') },
					  function(data){
							$('#listings-origin').slideUp();
							$('#listings').fadeOut();
							$('#listings-results-spinner').addClass('results');
							$.cookie('origin', data.origin);
							document.location.hash = '#' + query.replace(/sort=/, '').replace(/&callback=\?/, '') + '&origin=' + encodeURIComponent(data.origin);
					  });
					return false;
				});
				//capture the return key on text field
				$("#origin-input").bind("keydown", function(e) {
					if (e.keyCode == 13)
						$('#listings-origin-go').click();
				});
			}
			else if ($.cookie('origin') == null) {
				$('.listings-pager').removeClass('ui-corner-top');
				$('.listings-pager').addClass('ui-corner-all');
				$('#listings-origin').slideUp();
			}
		
			$('#listings-sort-selector').css('display', 'block');
			$('#listings-sort-selector a').click(function(){ 
				$('#listings').fadeOut();
				$('#listings-results-spinner').addClass('results'); });
			$('#listings-pages-top a, #listings-pages-bottom a').click(function(){ 
				$('#listings').fadeOut();
				$('#listings-results-spinner').addClass('results'); });
							
			$('#listings').fadeIn();
		});
	}
}

function gup(name){
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function getGroupLinks(group_name, group){
	var links_html = '';
	var disabled_text = '';
	$.each(group, function(i,item){
		if(item.count > 0)
			disabled = '';
		else
			disabled = ' class="ui-state-disabled"';
		count_html = ' <span class="link-count">(' + item.count + ')</span>';
		var item_name = String(item.text).toLowerCase().replace(' - ', '_').replace('/', '_').replace(' ', '_');
		if(item.css_class.substring(0,32) == 'ui-state-default ui-state-active')
			links_html += '<li' + disabled + '><a href="' + item.link + '" class="listings-selector ' + item.css_class + '" onClick="pageTracker._trackPageview(\'listings/' + group_name + '/' + item_name + '\');"><span class="' + item.css_class.substring(0,32) + ' ui-corner-all"></span>' + item.text + '</a>' + count_html + '</li>';
		else
			links_html += '<li' + disabled + '><a href="' + item.link + '" class="listings-selector ' + item.css_class + '" onClick="pageTracker._trackPageview(\'listings/' + group_name + '/' + item_name + '\');"><span class="ui-state-default ui-corner-all"></span>' + item.text + '</a>' + count_html + '</li>';
  });
	return links_html;
}

function getSortLinks(sort_data){
	var links_html = '';
	$.each(sort_data, function(i,item){
		var item_name = String(item.text).toLowerCase().replace(': ', '_').replace(' to ', '_').replace(' ', '_').replace('...', '');
		if(i == 0)
			links_html += '<a href="' + item.link + '" class="listings-sort-first" onClick="pageTracker._trackPageview(\'listings/sort/' + item_name + '\');"><span>' + item.text + '</span><span class="ui-icon ui-icon-triangle-1-s"></span></a>'
		else
			links_html += '<a href="' + item.link + '" class="' + item.css_class + '" onClick="pageTracker._trackPageview(\'listings/sort/' + item_name + '\');"><span>' + item.text + '</span></a>'
  });
	return links_html;	
}

function collapseAccordion(){
	if($.cookie('location') == 'collapsed')
		collapseHeader('#location_header');
	if($.cookie('rental_type') == 'collapsed')
		collapseHeader('#rental_type_header');
	if($.cookie('bedrooms') == 'collapsed')
		collapseHeader('#bedrooms_header');
	if($.cookie('pets_allowed') == 'collapsed')
		collapseHeader('#pets_allowed_header');
	if($.cookie('more_features') == 'collapsed')
		collapseHeader('#more_features_header');
	if($.cookie('month_available') == 'collapsed')
		collapseHeader('#month_available_header');
	if($.cookie('rent_range') == 'collapsed')
		collapseHeader('#rent_range_header');
}

function collapseHeader(header_name) {
	$(header_name).removeClass('ui-state-active ui-corner-top');
	$(header_name).addClass('ui-corner-all');
	$(header_name).find('.ui-icon').addClass('ui-icon-triangle-1-e');
	$(header_name).find('.ui-icon').removeClass('ui-icon-triangle-1-s');
	$(header_name).next().removeClass('ui-accordion-content-active');
}

function uncollapseHeader(header_name) {
	$(header_name).addClass('ui-state-active ui-corner-top');
	$(header_name).removeClass('ui-corner-all');
	$(header_name).find('.ui-icon').addClass('ui-icon-triangle-1-s');
	$(header_name).find('.ui-icon').removeClass('ui-icon-triangle-1-e');
	$(header_name).next().addClass('ui-accordion-content-active');
}

function replaceQueryValue(anchorString, key, newValue) {
	if(anchorString == '')
		anchorString = "#freshness";
	var splits = anchorString.split('&');
	var regex = new RegExp(key + '=.*');
	for(var i in splits) {
	    if(splits[i].match(regex)) splits.splice(i, 1);
	}
	splits.push(key + '=' + newValue);
	return splits.join('&');
}

function removeQueryValue(anchorString, keys) {
	if(anchorString != null) {
		if(anchorString == '')
			anchorString = "#freshness";
		var splits = anchorString.split('&');
		$.each(keys, function(index, key) {
			var regex = new RegExp(key + '=.*');
			for(var i in splits) {
	    		if(splits[i].match(regex)) 
					delete splits[i];
			}
		});
		return splits.join('&');
	}
	else
		return null;
}

function removeRandomAmps(anchorString) {
	if(anchorString != null) {
		if (anchorString == '&' || anchorString == '&&' || anchorString == '&&&' || anchorString == '&&&&' || anchorString == '&&&&' || anchorString == '&&&&&')
			return ''
		else
			return anchorString
	}
	else
		return null;
}