﻿clist = new ListBrowser({
	hashSection: null,
	url: __root + 'Bars/Browse',
	holderSelector: "#search_results_place"
});
clist.masterFilter.view_num = 1;
clist.defaults.view_num = 1;
clist.defaults['Page.rpp'] = 50;
clist.defaults['Page.sort'] = 3;
clist.defaults.q = '';
clist.masterFilter.q = '';

clist.li = 0;
clist.ci = 0;

String.prototype.endsWith = function(s) {
	return this.length >= s.length && this.substr(this.length - s.length) == s;
};


clist.saveState = function() {

	StateHolder.prototype.saveState.call(clist);

	var ps = 'Page.num=' + clist.page + '&Page.sort=' + clist.sort + '&Page.rpp=' + clist.rpp;
	for (var i in clist.state) {
		if (ps.length > 0)
			ps += '&';
		ps += i + '=' + clist.state[i];
	}

	var h = window.location.hash.toLowerCase().replace('#', '');
	if (h)
		h = '?' + h;
	var s = window.location.toString().toLowerCase();
	var i = s.indexOf('#');
	if (i > -1)
		s = s.substring(0, i);
	if (!s.endsWith('bars/search') && !s.endsWith('bars/search' + h)) {
		window.location = __root + 'Bars/Search#' + ps;
		return false;
	}

};

clist.getOverlayContent = function() {
	var img = jQuery('<img alt="Loading.."/>');
	img.attr('src', __root + 'Content/images/ajax-loader.gif');
	img.css({
		'left': '300px',
		'top': '170px',
		position: 'relative'
	});
	return img;
};

clist.renew = function() {

	var th = clist;
	if (th.beforeRenew)
		th.beforeRenew();

	th.getState();
	var prm = { };
	for (var i in th.state) {
		prm[i] = th.state[i];
	}
	var s = jQuery.param(prm);
	if (s) prm['stateLink'] = s;
	th.showOverlay();

	prm.loggedin = th.li;
	prm.ci = th.ci;

	jQuery(th.holderSelector).load(th.url, prm, function(resp) {
		th.hideOverlay();
		if (th.onPageLoad)
			th.onPageLoad(resp);
		th.afterPageLoad(resp);
	});

};

clist.beforeRenew = function() {
	jQuery('.bars-sort-order').removeClass('active');
	jQuery('#sordr' + Math.abs(this.sort)).addClass('active');
	if (this.rpp > 100 && this.masterFilter.view_num == 1)
		this.rpp = 100;

	if (clist.masterFilter.view_num == 2) {
		jQuery('#search_list_view').removeClass('active');
		jQuery('#search_map_view').addClass('active');
	} else {
		jQuery('#search_map_view').removeClass('active');
		jQuery('#search_list_view').addClass('active');
	}

	var canvas = jQuery('#map_canvas');
	var necessary_css = clist.masterFilter.view_num == 2 ? 'block' : 'none';
	if (canvas.css('display') != necessary_css)
		jQuery('#map_canvas').css('display', necessary_css);

};


clist.beforeChangePage = function() {
	window.scrollTo(0, 0);
};

clist.removeBar = function(id) {
	var th = clist;
	if (confirm('Remove this bar from search results?')) {
		jQuery.get(__root + "Bars/Run/RemoveFromResults", { BarID: id }, function(resp) {
			th.doSrch();
		});
	}
};

clist.afterPageLoad = function() {
	if (clist.masterFilter.view_num == 2)
		MapViewInit();

	jQuery('.search_option_container').each(function() {
		var jopt = jQuery(this);
		if (jopt.find("a:contains('See all')").length > 0) {
			var ids = '';
			jopt.find("input[type='checkbox']").each(function() {
				if (this.checked)
					ids += ',' + this.value;
			});
			var id = jopt.attr('id').replace('srch_opt_cntnr', '');
			jQuery.get(__root + 'Bars/GetOption/' + id, { values: ids }, function(resp) {
				jopt.replaceWith(resp);
			});
		}
	});

};

clist.doSrch = function() {
	clist.applyFilter();
	clist.show();
};

clist.clear_q = function() {
	clist.masterFilter.q = '';
	clist.show();
};


clist.setView = function(num) {
	clist.masterFilter.view_num = num;
	clist.show();
};

clist.popups = {};
clist.showPopup = function(anchor, cnt, id) {
	if (!cnt || cnt < 1) return;
	var th = this;
	var hp = jQuery("#hpopup");
	var pos = jQuery(anchor).offset();
	var i = pos.top + (cnt > 4 ? 300 : 120) + 50 - utils.scrollOffsetY() - utils.screenHeight();
	if (i < 0) i = 0;
	var __top = pos.top + 30 - i;
	var __left = pos.left - 120;
	hp.css({ "left": __left + 'px' });
	hp.css('top', __top + 'px');
	var mleft = -80;
	if (th.masterFilter.view_num == 2)
		mleft += 10;
	hp.css('width', '367px');
	hp.css('position', 'absolute');
	jQuery(document.body).append(hp);
	if (th.popups[id])
		hp.html(th.popups[id])
	else {
		hp.html('<img src="' + __root + 'content/images/load_circle.gif" alt="loading..." style="margin:15% 0 0 47%;"/>');
		jQuery.get(__root + 'Bars/Load/Popup', { barID: id }, function(resp) {
			th.popups[id] = resp;
			hp.html(resp);
		});
	}
	hp.jqmShow();
	th.stopHPopupTimer();
	th.startHPopupTimer();
};

clist.startHPopupTimer = function() {
	var hp = jQuery('#hpopup');
	hp.oneTime('3s', 'close-timer', function() { hp.jqmHide() });
};

clist.stopHPopupTimer = function() {
	jQuery('#hpopup').stopTime('close-timer');
};

clist.showBar = function(num) {
	if (!mrkrs) return;
	var latLng = new google.maps.LatLng(mrkrs[num].lat, mrkrs[num].lng);
	map.setCenter(latLng);
	map.setZoom(17);
	showInfoWindow(num);
	window.scrollTo(0, 20);
};

clist.init = function() {
	jQuery('#sordr' + Math.abs(clist.sort)).addClass('active');
	var h = window.location.hash.replace('#', '');
	var s = window.location.toString();
	var i = s.indexOf('#');
	if (i > -1)
		s = s.substring(0, i);

	if (clist.li && !h && clist.searchDefaults && s.toLowerCase().endsWith('bars/search')) {
		window.location.hash = clist.searchDefaults;
	} else {
		i = s.indexOf('?');
		if (i > 0)
			s = s.substring(i + 1);
		else
			s = '';
		if (!clist.li && (h == s || !h)) {
			//MapViewInit();
			viewState.currentHash = '#' + (h ? h : s);
			window.location.hash = viewState.currentHash;
			viewState.updateInterval = setInterval(viewState.checkHash, 500);
			return;
		}
	}
	viewState.track(500);
};

clearMarkers = function() {
	if (typeof(mrkrs) == 'undefined' || !mrkrs)
		return;
	for (var i in mrkrs)
		if (mrkrs[i].marker)
			mrkrs[i].marker.setMap(null);
};

function onCloseSelPopup(opt_id, itms_class) {
	var ids = '';
	jQuery.each(jQuery(".p_" + itms_class), function () {
		if (this.checked)
			ids += ',' + this.id;
	});
	jQuery('#srch_opt_cntnr' + opt_id).load(__root + 'Bars/GetOption/' + opt_id, { values: ids }, function () {
		clist.applyFilter();
		clist.doSrch();
	});
}

function showInfoWindow(num) {
	if (!mrkrs[num].content) {
		infowin.setContent('<div style="width:200px;text-align:center;padding-top:20px;"><img src="' + __root + 'content/images/load_circle.gif" alt="loading..."/></div>');
		jQuery.get(__root + 'Bar/PopupInfo/' + mrkrs[num].id, null, function (data) {
			infowin.setContent(data);
			mrkrs[num].content = data;
		});
	} else {
		infowin.setContent(mrkrs[num].content);
	}
	infowin.open(map, mrkrs[num].marker);
}

function MapViewInit() {
	if (typeof(map) == 'undefined' || !map) {
		var latlng = new google.maps.LatLng(40.764676, -73.973366);
		var myOptions = {
			zoom: 8,
			center: latlng,
			navigationControlOptions: {
				style: google.maps.NavigationControlStyle.SMALL
			},
			scrollwheel: false,
			streetViewControl: true,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		infowin = new google.maps.InfoWindow({ content: '' });

		var step = 20;
		map.controls[google.maps.ControlPosition.TOP].push(NavControl(1, 'north', 75, 28, 0, -step, 0));
		map.controls[google.maps.ControlPosition.BOTTOM].push(NavControl(2, 'south', 75, 28, 0, step, 0));
		map.controls[google.maps.ControlPosition.LEFT].push(NavControl(3, 'west', 28, 75, -step, 0, 82));
		map.controls[google.maps.ControlPosition.RIGHT].push(NavControl(4, 'east', 28, 75, step, 0, 143));

	}

	if (mrkrs) {
		var bounds = new google.maps.LatLngBounds();
		var pointCount = 0;
		for (var i in mrkrs)
			if (mrkrs[i].lat != 0 && mrkrs[i].lng != 0) {
				var ll = new google.maps.LatLng(mrkrs[i].lat, mrkrs[i].lng);
				mrkrs[i].marker = new google.maps.Marker({
					position: ll,
					map: map,
					title: mrkrs[i].text,
					icon: __root + 'content/images/drink/' + i + '.png'
				});
				mrkrs[i].marker.mnum = i;
				google.maps.event.addListener(mrkrs[i].marker, 'click', function (t) {
					showInfoWindow(this.mnum);
				});
				pointCount++;
				bounds.extend(ll);
			}
			if (pointCount == 0) {
				bounds.extend(new google.maps.LatLng(40.7, -74));
				bounds.extend(new google.maps.LatLng(40.88, -73.8));
			}
		map.fitBounds(bounds);
	}

}

function NavControl(idx, dir, width, height, dx, dy, top_marg) {
	var div = document.createElement('div');
	div.id = dir;
	div.index = idx;
	jQuery(div).css('margin-top', top_marg + 'px');
	jQuery(div).addClass('direction');
	div.innerHTML = "<a href='javascript:void(0);'><img src='" + __root + "content/images/spacer.gif' width='" + width + "' height='" + height + "' alt='" + dir + "' /></a>";
	google.maps.event.addDomListener(div, 'click', function () {
		map.panBy(dx, dy);
	})
	return div;
}

