
var _sellHTML = getSimpleJSON(siteurl('home/sellview'));;

var _height		= 600;
var _width		= 650;

var form = null;
var post = null;
var current_user = null;

var registrar = getRegistrar();

function sellPopup() {
	current_user = _inList();

	var itemhash = getItemHash();

	var popup = new Popup();
	popup.content = _sellHTML;
	popup.style = { 'width': _width+'px', 'overflow-y':'auto', 'overflow-x':'hidden' };
	popup.show();
	popup.content.css({'overflow-y':'visible'});
	
	form = $("#crimsonlist-sell");
	post = {
		item: $("#sell-item"), category: $("#sell-category"), subcategory: $("#sell-subcategory"), 
		title: $("#sell-title"), price: $("#sell-price"), 
		obo: $("#sell-obo"), condition: $("#sell-condition"), notes: $("#sell-notes"), 
		location: $("#sell-location"), title: $("#sell-title")
	};
	
	post.price.keyup(function() { limitChars(this,10); });
	post.title.keyup(function() { limitChars(this,25); });
	post.notes.keyup(function() { limitChars(this,350); });
	
	form.attr('action',siteurl('home/post/'));
	form.append('<input type="hidden" name="_nocsrf" value="'+nocsrf()+'" />');
	form.append('<input type="hidden" name="uid" value="'+current_user+'" />');
	form.append('<input type="hidden" name="item_hash" value="'+itemhash+'" />');

	$.each(_categories, function(key,data){
		post.item.append('<option value="'+key+'">'+key+'</option>');
	});

	post.category.change(function(e) {
		var itemType = post.item.val(), categoryType = $(this).children('option:selected').attr('index');
		post.subcategory.empty();
		$.each(_categories[itemType][categoryType], function(key,array) {
			$.each(array, function(index,data){
				post.subcategory.append('<option value="'+data+'">'+data+'</option>');
			});
		});
	});
	
	post.item.change(function() {
		var itemType = $(this).val();
		
		post.category.empty();
		$.each(_categories[itemType], function(index,array){
			$.each(array, function(key,data){
				post.category.append('<option index="'+index+'" value="'+key+'">'+key+'</option>');
			});
		});
		post.category.change();
		
		if (itemType == 'books') {
			var bookextra = '<label class="sell required bookextra">isbn</label><input class="input bookextra required" type="text" name="isbn" id="sell-isbn" />'+
							'<label class="sell bookextra">author</label><input class="input bookextra" type="text" name="author" id="sell-author" />'+
							'<label class="sell bookextra">department</label><select class="input bookextra" name="department" id="sell-department" ><option value=""></option></select>'+
							'<label class="sell bookextra">course</label><select class="input bookextra" name="course" id="sell-course" ></select>';
			post.subcategory.after(bookextra);
			post.isbn = $("#sell-isbn");
			post.author = $("#sell-author"); 
			post.department = $("#sell-department");
			post.course = $("#sell-course");
			
			$.each(registrar, function (i, array) {
				post.department.append(registrar[i].d);
			});
			
			post.department.change(function(){
				if (! is_empty(post.department.val())) post.course.empty().append(registrar[post.department.val()].c);
			});
			
			post.department.change();
			
			post.isbn.blur(function(){
				var isbn = $(this).val();
				container = ($("#suggested-info").length) ? $("#suggested-info") : $('<div id="suggested-info"></div>');
				container.css({'overflow-y':'visible','position':'absolute','top':'150px','right':'5px', 'width':'300px', 'height':'200px'});
				if(isbn.length && validateISBN(isbn)) {
					post.isbn.attr('readonly','readonly');
					container.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'
					}));
					$("#fieldset-item-details").append( container );
					var info = getSimpleJSON(siteurl('home/isbncheck/'+isbn));
					var infostr = '<div class="title">ISBN Found:</div>' +
						'<span class="note">We recommend that you use some of this info in the \'notes\' field</span>';
					$.each(info, function(key,value) {
						if ( is_string(value) ) value = value.substr(0,200);
						if (! is_empty(value)) infostr += '<div><label>'+key+'</label><span>'+value+'</span><div>';
					});
					container.empty().append( infostr );
					post.isbn.val(info['ISBN-10']);
					post.isbn.removeAttr('readonly');
					post.author.val(info['Authors']);	
					post.title.val(info['Title']);
				} else { container.empty(); }
			});
		} else { 
			if ($('.bookextra').length) $('.bookextra').detach(); 
			post.isbn = $("#sell-isbn");
			post.author = $("#sell-author"); 
			post.department = $("#sell-department");
			post.course = $("#sell-course");
		}
	});

	post.item.change();
	
	$('#fileupload').fileupload();
	$('#fileupload')
		.bind('fileuploadsend', function (e, data) {
			if (is_empty(post.title.val()) || post.title.val().length < 3) { 
				Alert("Oh no! You missed a required field. Sorry, we had to clear your uploads >_<."); 
				return false;
			}
		})
		.bind('fileuploaddone', function (e, data) {
			popup.hide();
			Confirm("Thanks for posting! <br />Would you like to post another?", function() {
				sellPopup();
			}, 'Yes', 'No');
			panel_refresh();
		});
	
	$("#no-pic-submit").click(function(){
		var check = checkInputs();
		if (! check.result) {
			var error = ($("#form-error-box").length) ? $("#form-error-box") : $('<div id="form-error-box"></div>');
			error.empty();
			for (e in check.error) {
				error.append($('<div class="form-error">'+check.error[e]+'</div>'));
			}
			error.css({'position':'absolute', 'top':'20px', 'right':'5px', 'width': '300px', 'height': '200px'});
			$("#fieldset-item-details").append( error );
		}
		else {
			if ($("#form-error-box").length) $("#form-error-box").empty();
			$.ajax({
				type: 'post',
				url: siteurl('home/post/'),
				data: { _nocsrf: nocsrf(), uid:current_user, item: post.item.val(), category: post.category.val(), 
					subcategory: post.subcategory.val(), title: post.title.val(), price: post.price.val(), 
					obo: post.obo.val(), condition: post.condition.val(), notes: post.notes.val(), 
					location: post.location.val(), title: post.title.val(), isbn: post.isbn.val(),
					author: post.author.val(), department: post.department.val(), 
					course: post.course.val(), item_hash: itemhash
				},
				dataType: 'json',
				success: function(msg) {
					popup.hide();
					Confirm("Thanks for posting! <br />Would you like to post another?", function() {
						sellPopup();
					}, 'Yes', 'No');
					panel_refresh();
				}
			});
		}
	});

}

function getItemHash() {
	return getSimpleJSON(siteurl('home/getitemhash'));
}

function checkInputs() {
	var good = true, errors = Array();
	for (key in post) {
		if (post[key].length && (post[key].hasClass('required') && !post[key].val().length )) {
			errors.push("You've forgotten a required field. (they're in <b>bold</b>).");
			good = false;
			break;
		}
	}
	if (! is_num(post.price.val())) {
		errors.push("You need to enter a valid price. (don't use a '$' sign).");
		good = false;
	}
	if (post.item.val() == 'books' && !validateISBN(post.isbn.val())) {
		errors.push("You're not using a valid ISBN. Try another.");
		good = false;
	}
	
	return {result: good, error: errors};
}

function getRegistrar() {
	reggy = Array(), i = 0;
	$.each(_registrar, function(key, array) {
		var department = '<option value="'+i+'" >'+key+'</option>';
		var courses = "";
		$.each(_registrar[key], function (index, value) {
			courses += '<option value="'+value+'" >'+value+'</option>';
		});
		reggy.push({d: department, c: courses});
		i++;
	});
	return reggy;
}

