var MODECOOKIE = '_crimsonlist_ui_browse_or_search';
var BROWSECOOKIE = '_crimsonlist_ui_current-browse';
var current_user = null;

// 'cache' results to avoid multiple requests
var results = { ALL: null, BOOKS: null, GENERAL: null, FURNITURE: null }

function _browse(search) {
	$.cookie(BROWSECOOKIE, search);
	$.cookie(MODECOOKIE, 'browse');
	current_user = _inList();
	
	var display = $("#content-area");
	
	if (is_undef(search)) {
		display.empty().append('<img id="books4sale" src="'+assets('css/images/books4sale.jpg')+'" alt="logo" />');
		$.cookie(BROWSECOOKIE, null);
		return;
	}
	
	var path = search.split('/');
	
	display.empty().append($('<img src="'+assets('css/images/ajax-loader.gif')+'" alt="loading..." />').css({
		'margin':'auto','display':'block','position':'absolute','top':0,'bottom':0,'left':0,'right':0,'height':'30px','width':'200px'
		}));
	
	$.post(siteurl('home/browseitems'), { _nocsrf: nocsrf(), query: path },
		function (response) {
			if (response.length) {
				
				var html = "";
				for (var item in response) {
					html += item_template(response[item]);
				}
				
				html = $(html);
				display.empty().append(html);
				$(".browse").click(function() { _browse(this.getAttribute('search')); });
				$(".buy-item").click(function() { buyItem(this.getAttribute('item')); });
				$(".see-photos").click(function() { seePhotos(this.getAttribute('gallery')); });
				$(".flag-this").click(function() { flagPost(this.getAttribute('item')) });
			}
			else {
				display.empty().append('<div class="no-result">Your search produced no results. Try a broader search, or browsing a larger category.</div>');
			}
		}, 'json');
}

function _search(query) {
	$.cookie(MODECOOKIE, 'search');
	
	var display = $("#content-area");
	current_user = _inList();
	
	display.empty().append($('<img src="'+assets('css/images/ajax-loader.gif')+'" alt="loading..." />').css({
		'margin':'auto','display':'block','position':'absolute','top':0,'bottom':0,'left':0,'right':0,'height':'30px','width':'200px'
		}));
	
	$.post(siteurl('home/searchitems'), { _nocsrf: nocsrf(), query: query },
			function (response) {
				if (response.length) {
					var html = "";
					for (item in response) {
						html += item_template(response[item]);
					}
					html = $(html);
					display.empty().append(html);
					$(".browse").click(function() { _browse(this.getAttribute('search')); });
					$(".buy-item").click(function() { buyItem(this.getAttribute('item')); });
					$(".see-photos").click(function() { seePhotos(this.getAttribute('gallery')); });
					$(".flag-this").click(function() { flagPost(this.getAttribute('item')) });
				}
				else {
					display.empty().append('<div class="no-result">Your search produced no results. Try a broader search, or browsing a larger category.</div>');
				}
			}, 'json');
}

function browserView (view) {}

function item_template (item) {
	
	var hide = function(v,e) { return (!current_user) ? e : v; }
	var has = (is_empty(item.uploads)) ? 'No ' : 'Has ';
	var self = item.seller.uid == current_user ? 'self' : '';
	var obo = item.obo == 1 ? "OBO" : '';
	
	return '' +
	'<div class="listing '+self+'" item="'+item.item_hash+'">'+
		'<div class="listing-filter">'+
			'<span class="path">'+
				'<a class="browse" search="'+item.table+'">'+item.table+'</a> >>'+ 
				'<a class="browse" search="'+item.table+'/'+item.category+'">'+item.category+'</a> >>'+ 
				'<a class="browse" search="'+item.table+'/'+item.category+'/'+item.subcategory+'">'+item.subcategory+'</a>'+
			'</span>'+
		'</div>'+
		'<button item="'+item.item_hash+'" class="buy-item">buy</button>'+
		'<div class="item-meta">'+
			'<span class="title">'+item.title+'</span>'+
			'<span class="price">$ '+item.price+'</span>'+
			'<span class="obo">'+obo+'</span>'+
			'<span class="seller">'+hide(item.seller.username,"Crimsonlist user")+'</span><span class="karma">'+fracBox((item.seller.karma)/MAXKARMA, 75, 12, 0, 0, true)+'</span>'+
			'<span class="condition">'+item.condition+'</span>'+
			'<div class="notes">'+item.notes+'</div>'+
		'</div>'+
		'<div class="markers">'+
			'<img item="'+item.item_hash+'" class="flag-this" src="'+assets('css/images/flag-icon.png')+'" />'+
			'<button class="buy-count" title="Potential Buyers">'+item.buyers+'</button>'+
			'<img gallery="'+item.uploads+'" class="see-photos" src="'+assets('css/images/photos-icon.png')+'" title="'+has+'Images" />'+
		'</div>'+
	'</div>';
}

function buyItem(item_hash) {
	if (! (uid = _inList())) { Alert("Log In to contact this seller."); return; }
	
	Confirm('<div>Add a message. <label id="charcount"></label></div><textarea cols="35" id="buy-message"></textarea>', 
		function() {
		var msg = $("#buy-message").val();
		var mail = { uid_from: uid, item_hash: item_hash, content: msg };
		$.post(siteurl('home/buyitem'), {_nocsrf: nocsrf(), message: mail}, function(m) { 
			if (m=='sent') Alert("Your request for this item has been sent."); 
			else if (m=='sent already') Alert("You've already requested this item. Good luck!");
			else if (m=='same') Alert("You just tried to buy from yourself... We're gonna pretend we didn't see it happen.");
		}, 'json');
	});
	$("#buy-message").keyup(function() { limitChars(this, 100, '#charcount'); });
}

function seePhotos(gallery) {
	$.post(siteurl('home/checkgallery'), {_nocsrf: nocsrf(), gallery: gallery}, function (g) {
		if (g == 'empty') {
			
		}
		else {
			popup = new Popup();
			popup.content = '<div id="item-gallery-load" class="pics">';
			for (i in g) { popup.content += '<img src="'+appurl('uploads/'+gallery+g[i])+'" width="200" height="200" />'; }
			popup.content += '</div>';
			popup.style = { 'width': '330px', 'height':'330px', 'border-color':'#900'}
			popup.show();
			$("#item-gallery-load").cycle({ fx: 'shuffle', pause: 1, next: '#item-gallery-load'});
		}
	}, 'json');
}

function flagPost(item_hash) {
	if (! (uid = _inList())) { Alert("To protect our sellers, we only allow Crimsonlist users to flag posts. If you think this post is inappropriate, please Log In to flag it. Thanks!"); return; }
	
	var reason = 	'<b>Reason</b><br /><select id="flag-enums"><option value="MPICS">Misleading Pictures</option><option value="MINFO">Misleading Information</option><option value="XXX">Explicit Content</option>'+
					'<option value="DUPLICATE">Duplicate Post</option><option value="OFFENSIVE">Offensive Content</option></select><br /><b>Details</b> (required.) <label id="charcount"></label><textarea cols="33" id="flag-details"></textarea>';
	
	Confirm("Please tell us why you're flagging this post. <br /><br />"+reason, function() {
		var enumer = $("#flag-enums").val(), details = $("#flag-details").val();
		$.post(siteurl('home/flagpost'), {_nocsrf: nocsrf(), flag: { item_hash: item_hash, uid: uid, enum: enumer, reason: details }}, 
			function(m) {
				if (m) { Alert("Thank you for reporting this post. We'll be taking a close look at it very soon."); }
		}, 'json');
	});
	$("#flag-details").keyup(function() { limitChars(this, 100, '#charcount'); });
}


